filename
stringlengths
3
9
code
stringlengths
4
1.87M
244958.c
#include "esteps.h" #include "sweeps.h" #include <math.h> /* this routine is to be used only for el,eh and ph */ void init_estep30_array(energy_step30 *nrg30,uint2 *dactable,sweep_cal *cal) { int e,i,d=0; double nrg,anrg0,anrg9; for(e=0;e<30;e++){ for(i=0;i<4;i++,d++){ nrg = dac_to_energy(dactable[d],cal); if(i==0) nrg30->upper[e] = nrg; if((e==0) && (i==1)) anrg0 = nrg; if(i==2) anrg9 = nrg; } nrg30->lower[e] = nrg; nrg30->wid[e] = nrg30->upper[e] - nrg30->lower[e]; nrg30->unc[e] = 1.0; /* TBD later */ if(e>0){ nrg = (nrg30->lower[e-1]+nrg30->upper[e])/2.; nrg30->lower[e-1] = nrg; nrg30->upper[e] = nrg; nrg30->mid[e-1] = (nrg30->lower[e-1]+nrg30->upper[e-1])/2.; nrg30->wid[e-1] = (nrg30->upper[e-1] - nrg30->lower[e-1]); } } nrg30->upper[0] = nrg30->upper[0]+(nrg30->upper[0]-anrg0)/2.; nrg30->mid[0] = (nrg30->upper[0] + nrg30->lower[0])/2.; nrg30->wid[0] = nrg30->upper[0] - nrg30->lower[0]; nrg30->lower[29] = nrg30->lower[29]-(anrg9-nrg30->lower[29])/2.; nrg30->mid[29] = (nrg30->upper[29] + nrg30->lower[29])/2.; nrg30->wid[29] = nrg30->upper[29] - nrg30->lower[29]; #if 1 /* special case for EESA LOW sweep problem */ if(nrg30->upper[0] < nrg30->upper[1]) nrg30->upper[0] = dac_to_energy(dactable[1],cal); #endif } void init_estep15_array(struct energy_step15_def *nrg15,struct energy_step30_def *nrg30) { int e; for(e=0;e<15;e++){ nrg15->upper[e] = nrg30->upper[2*e]; nrg15->lower[e] = nrg30->lower[2*e+1]; nrg15->mid[e] = (nrg15->upper[e] + nrg15->lower[e])/2.; nrg15->wid[e] = (nrg15->upper[e] - nrg15->lower[e]); nrg15->unc[e] = (nrg30->unc[2*e] + nrg30->unc[2*e+1]) / 2.; } } /* this routine is to be used only for pesal */ void init_esteppl_array2(energy_steppl *snrg,uint2 *dactable,sweep_cal *cal, uint2 bndry) { int e,i,j,a=0,d=0; double nrg,anrg[8]; for(e=0;e<bndry;e++){ d=e; if(bndry-e < 4) j=bndry-e; else j=4; for(i=0;i<j;i++,d++){ nrg = dac_to_energy(dactable[d],cal); if(i==0) snrg->upper[e] = nrg; if((e<4) && (i==1)) anrg[a++] = nrg; if((i==j-2) && (e>=bndry-4)) anrg[a++] = nrg; } snrg->lower[e] = nrg; snrg->wid[e] = snrg->upper[e] - snrg->lower[e]; snrg->unc[e] = 1.0; /* TBD later */ if(e>3){ nrg = (snrg->lower[e-4]+snrg->upper[e])/2.; snrg->lower[e-4] = nrg; snrg->upper[e] = nrg; snrg->mid[e-4] = (snrg->lower[e-4]+snrg->upper[e-4])/2.; snrg->wid[e-4] = (snrg->upper[e-4] - snrg->lower[e-4]); } } anrg[7]=anrg[6]; e--; for(a=0;a<4;a++){ snrg->upper[a] = snrg->upper[a]+(snrg->upper[a]-anrg[a])/2.; snrg->mid[a] = (snrg->upper[a] + snrg->lower[a])/2.; snrg->wid[a] = snrg->upper[a] - snrg->lower[a]; snrg->lower[e-a] = snrg->lower[e-a]-(anrg[7-a]-snrg->lower[e-a])/2.; snrg->mid[e-a] = (snrg->upper[e-a] + snrg->lower[e-a])/2.; snrg->wid[e-a] = snrg->upper[e-a] - snrg->lower[e-a]; } a=0; for(e=bndry;e<(DAC_TBL_SIZE_PL-3);e++){ d=e; for(i=0;i<4;i++,d++){ nrg = dac_to_energy(dactable[d],cal); if(i==0) snrg->upper[e] = nrg; if((e<bndry+4) && (i==1)) anrg[a++] = nrg; if((i==2) && (e>DAC_TBL_SIZE_PL-8)) anrg[a++] = nrg; } snrg->lower[e] = nrg; snrg->wid[e] = snrg->upper[e] - snrg->lower[e]; snrg->unc[e] = 1.0; /* TBD later */ if(e>bndry+3){ nrg = (snrg->lower[e-4]+snrg->upper[e])/2.; snrg->lower[e-4] = nrg; snrg->upper[e] = nrg; snrg->mid[e-4] = (snrg->lower[e-4]+snrg->upper[e-4])/2.; snrg->wid[e-4] = (snrg->upper[e-4] - snrg->lower[e-4]); } } e--; for(a=0;a<4;a++){ snrg->upper[bndry+a] = snrg->upper[bndry+a]+(snrg->upper[bndry+a]-anrg[a])/2.; snrg->mid[bndry+a] = (snrg->upper[bndry+a] + snrg->lower[bndry+a])/2.; snrg->wid[bndry+a] = snrg->upper[bndry+a] - snrg->lower[bndry+a]; snrg->lower[e-a] = snrg->lower[e-a]-(anrg[7-a]-snrg->lower[e-a])/2.; snrg->mid[e-a] = (snrg->upper[e-a] + snrg->lower[e-a])/2.; snrg->wid[e-a] = snrg->upper[e-a] - snrg->lower[e-a]; } } /* converts spectrum to proper units */ /* dt is the duration of one energy step */ /* dth is the number of sweeps times the angular range theta */ int convert_units(int ne,double *nrg,float *counts, double dt,double dth,double geom,int flux_units) { int e; double scale; double A; geom = geom * dth; A = 1.; /* ERROR must be fixed !!! */ switch(flux_units){ case NCOUNTS_UNITS: scale = dth/(22.5*2); for(e=0;e<ne;e++) counts[e] /= scale; break; case RATE_UNITS: scale = dt; for(e=0;e<ne;e++) counts[e] /= scale; break; case EFLUX_UNITS: scale = dt*geom; for(e=0;e<ne;e++) counts[e] /= scale; break; case FLUX_UNITS: scale = dt*geom; for(e=0;e<ne;e++) counts[e] /= scale*(nrg[e]/1000.); break; case DISTF_UNITS: scale = dt*geom*A; for(e=0;e<ne;e++) counts[e] /= scale*nrg[e]*nrg[e]; break; default: flux_units = COUNTS_UNITS; break; } return(flux_units); }
521942.c
/* * Copyright (C) 2015 Red Hat, Inc. * All Rights Reserved. * * 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 (including the * next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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 <drm/drm_debugfs.h> #include <drm/drm_file.h> #include "virtgpu_drv.h" static void virtio_add_bool(struct seq_file *m, const char *name, bool value) { seq_printf(m, "%-16s : %s\n", name, value ? "yes" : "no"); } static void virtio_add_int(struct seq_file *m, const char *name, int value) { seq_printf(m, "%-16s : %d\n", name, value); } static int virtio_gpu_features(struct seq_file *m, void *data) { struct drm_info_node *node = (struct drm_info_node *) m->private; struct virtio_gpu_device *vgdev = node->minor->dev->dev_private; virtio_add_bool(m, "virgl", vgdev->has_virgl_3d); virtio_add_bool(m, "edid", vgdev->has_edid); virtio_add_bool(m, "indirect", vgdev->has_indirect); virtio_add_bool(m, "resource uuid", vgdev->has_resource_assign_uuid); virtio_add_int(m, "cap sets", vgdev->num_capsets); virtio_add_int(m, "scanouts", vgdev->num_scanouts); return 0; } static int virtio_gpu_debugfs_irq_info(struct seq_file *m, void *data) { struct drm_info_node *node = (struct drm_info_node *) m->private; struct virtio_gpu_device *vgdev = node->minor->dev->dev_private; seq_printf(m, "fence %llu %lld\n", (u64)atomic64_read(&vgdev->fence_drv.last_seq), vgdev->fence_drv.sync_seq); return 0; } static struct drm_info_list virtio_gpu_debugfs_list[] = { { "virtio-gpu-features", virtio_gpu_features }, { "virtio-gpu-irq-fence", virtio_gpu_debugfs_irq_info, 0, NULL }, }; #define VIRTIO_GPU_DEBUGFS_ENTRIES ARRAY_SIZE(virtio_gpu_debugfs_list) void virtio_gpu_debugfs_init(struct drm_minor *minor) { drm_debugfs_create_files(virtio_gpu_debugfs_list, VIRTIO_GPU_DEBUGFS_ENTRIES, minor->debugfs_root, minor); }
56932.c
/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * 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. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strcmp.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/string/strcmp.c,v 1.6 2007/01/09 00:28:12 imp Exp $");
548088.c
/* * Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd * * 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/backlight.h> #include <linux/gpio/consumer.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/regulator/consumer.h> #include <drm/drmP.h> #include <drm/drm_crtc.h> #include <drm/drm_mipi_dsi.h> #include <drm/drm_panel.h> #include <video/mipi_display.h> struct panel_init_cmd { size_t len; const char *data; }; #define _INIT_CMD(...) { \ .len = sizeof((char[]){__VA_ARGS__}), \ .data = (char[]){__VA_ARGS__} } struct panel_desc { const struct drm_display_mode *mode; unsigned int bpc; struct { unsigned int width; unsigned int height; } size; unsigned long flags; enum mipi_dsi_pixel_format format; const struct panel_init_cmd *init_cmds; unsigned int lanes; const char * const *supply_names; unsigned int num_supplies; unsigned int sleep_mode_delay; unsigned int power_down_delay; }; struct innolux_panel { struct drm_panel base; struct mipi_dsi_device *link; const struct panel_desc *desc; struct backlight_device *backlight; struct regulator_bulk_data *supplies; unsigned int num_supplies; struct gpio_desc *enable_gpio; bool prepared; bool enabled; }; static inline struct innolux_panel *to_innolux_panel(struct drm_panel *panel) { return container_of(panel, struct innolux_panel, base); } static int innolux_panel_disable(struct drm_panel *panel) { struct innolux_panel *innolux = to_innolux_panel(panel); int err; if (!innolux->enabled) return 0; backlight_disable(innolux->backlight); err = mipi_dsi_dcs_set_display_off(innolux->link); if (err < 0) DRM_DEV_ERROR(panel->dev, "failed to set display off: %d\n", err); innolux->enabled = false; return 0; } static int innolux_panel_unprepare(struct drm_panel *panel) { struct innolux_panel *innolux = to_innolux_panel(panel); int err; if (!innolux->prepared) return 0; err = mipi_dsi_dcs_enter_sleep_mode(innolux->link); if (err < 0) { DRM_DEV_ERROR(panel->dev, "failed to enter sleep mode: %d\n", err); return err; } if (innolux->desc->sleep_mode_delay) msleep(innolux->desc->sleep_mode_delay); gpiod_set_value_cansleep(innolux->enable_gpio, 0); if (innolux->desc->power_down_delay) msleep(innolux->desc->power_down_delay); err = regulator_bulk_disable(innolux->desc->num_supplies, innolux->supplies); if (err < 0) return err; innolux->prepared = false; return 0; } static int innolux_panel_prepare(struct drm_panel *panel) { struct innolux_panel *innolux = to_innolux_panel(panel); int err; if (innolux->prepared) return 0; gpiod_set_value_cansleep(innolux->enable_gpio, 0); err = regulator_bulk_enable(innolux->desc->num_supplies, innolux->supplies); if (err < 0) return err; /* p079zca: t2 (20ms), p097pfg: t4 (15ms) */ usleep_range(20000, 21000); gpiod_set_value_cansleep(innolux->enable_gpio, 1); /* p079zca: t4, p097pfg: t5 */ usleep_range(20000, 21000); if (innolux->desc->init_cmds) { const struct panel_init_cmd *cmds = innolux->desc->init_cmds; unsigned int i; for (i = 0; cmds[i].len != 0; i++) { const struct panel_init_cmd *cmd = &cmds[i]; err = mipi_dsi_generic_write(innolux->link, cmd->data, cmd->len); if (err < 0) { dev_err(panel->dev, "failed to write command %u\n", i); goto poweroff; } /* * Included by random guessing, because without this * (or at least, some delay), the panel sometimes * didn't appear to pick up the command sequence. */ err = mipi_dsi_dcs_nop(innolux->link); if (err < 0) { dev_err(panel->dev, "failed to send DCS nop: %d\n", err); goto poweroff; } } } err = mipi_dsi_dcs_exit_sleep_mode(innolux->link); if (err < 0) { DRM_DEV_ERROR(panel->dev, "failed to exit sleep mode: %d\n", err); goto poweroff; } /* T6: 120ms - 1000ms*/ msleep(120); err = mipi_dsi_dcs_set_display_on(innolux->link); if (err < 0) { DRM_DEV_ERROR(panel->dev, "failed to set display on: %d\n", err); goto poweroff; } /* T7: 5ms */ usleep_range(5000, 6000); innolux->prepared = true; return 0; poweroff: gpiod_set_value_cansleep(innolux->enable_gpio, 0); regulator_bulk_disable(innolux->desc->num_supplies, innolux->supplies); return err; } static int innolux_panel_enable(struct drm_panel *panel) { struct innolux_panel *innolux = to_innolux_panel(panel); int ret; if (innolux->enabled) return 0; ret = backlight_enable(innolux->backlight); if (ret) { DRM_DEV_ERROR(panel->drm->dev, "Failed to enable backlight %d\n", ret); return ret; } innolux->enabled = true; return 0; } static const char * const innolux_p079zca_supply_names[] = { "power", }; static const struct drm_display_mode innolux_p079zca_mode = { .clock = 56900, .hdisplay = 768, .hsync_start = 768 + 40, .hsync_end = 768 + 40 + 40, .htotal = 768 + 40 + 40 + 40, .vdisplay = 1024, .vsync_start = 1024 + 20, .vsync_end = 1024 + 20 + 4, .vtotal = 1024 + 20 + 4 + 20, .vrefresh = 60, }; static const struct panel_desc innolux_p079zca_panel_desc = { .mode = &innolux_p079zca_mode, .bpc = 8, .size = { .width = 120, .height = 160, }, .flags = MIPI_DSI_MODE_VIDEO | MIPI_DSI_MODE_VIDEO_SYNC_PULSE | MIPI_DSI_MODE_LPM, .format = MIPI_DSI_FMT_RGB888, .lanes = 4, .supply_names = innolux_p079zca_supply_names, .num_supplies = ARRAY_SIZE(innolux_p079zca_supply_names), .power_down_delay = 80, /* T8: 80ms - 1000ms */ }; static const char * const innolux_p097pfg_supply_names[] = { "avdd", "avee", }; static const struct drm_display_mode innolux_p097pfg_mode = { .clock = 229000, .hdisplay = 1536, .hsync_start = 1536 + 100, .hsync_end = 1536 + 100 + 24, .htotal = 1536 + 100 + 24 + 100, .vdisplay = 2048, .vsync_start = 2048 + 100, .vsync_end = 2048 + 100 + 2, .vtotal = 2048 + 100 + 2 + 18, .vrefresh = 60, }; /* * Display manufacturer failed to provide init sequencing according to * https://chromium-review.googlesource.com/c/chromiumos/third_party/coreboot/+/892065/ * so the init sequence stems from a register dump of a working panel. */ static const struct panel_init_cmd innolux_p097pfg_init_cmds[] = { /* page 0 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x00), _INIT_CMD(0xB1, 0xE8, 0x11), _INIT_CMD(0xB2, 0x25, 0x02), _INIT_CMD(0xB5, 0x08, 0x00), _INIT_CMD(0xBC, 0x0F, 0x00), _INIT_CMD(0xB8, 0x03, 0x06, 0x00, 0x00), _INIT_CMD(0xBD, 0x01, 0x90, 0x14, 0x14), _INIT_CMD(0x6F, 0x01), _INIT_CMD(0xC0, 0x03), _INIT_CMD(0x6F, 0x02), _INIT_CMD(0xC1, 0x0D), _INIT_CMD(0xD9, 0x01, 0x09, 0x70), _INIT_CMD(0xC5, 0x12, 0x21, 0x00), _INIT_CMD(0xBB, 0x93, 0x93), /* page 1 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x01), _INIT_CMD(0xB3, 0x3C, 0x3C), _INIT_CMD(0xB4, 0x0F, 0x0F), _INIT_CMD(0xB9, 0x45, 0x45), _INIT_CMD(0xBA, 0x14, 0x14), _INIT_CMD(0xCA, 0x02), _INIT_CMD(0xCE, 0x04), _INIT_CMD(0xC3, 0x9B, 0x9B), _INIT_CMD(0xD8, 0xC0, 0x03), _INIT_CMD(0xBC, 0x82, 0x01), _INIT_CMD(0xBD, 0x9E, 0x01), /* page 2 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x02), _INIT_CMD(0xB0, 0x82), _INIT_CMD(0xD1, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x82, 0x00, 0xA5, 0x00, 0xC1, 0x00, 0xEA, 0x01, 0x0D, 0x01, 0x40), _INIT_CMD(0xD2, 0x01, 0x6A, 0x01, 0xA8, 0x01, 0xDC, 0x02, 0x29, 0x02, 0x67, 0x02, 0x68, 0x02, 0xA8, 0x02, 0xF0), _INIT_CMD(0xD3, 0x03, 0x19, 0x03, 0x49, 0x03, 0x67, 0x03, 0x8C, 0x03, 0xA6, 0x03, 0xC7, 0x03, 0xDE, 0x03, 0xEC), _INIT_CMD(0xD4, 0x03, 0xFF, 0x03, 0xFF), _INIT_CMD(0xE0, 0x00, 0x00, 0x00, 0x86, 0x00, 0xC5, 0x00, 0xE5, 0x00, 0xFF, 0x01, 0x26, 0x01, 0x45, 0x01, 0x75), _INIT_CMD(0xE1, 0x01, 0x9C, 0x01, 0xD5, 0x02, 0x05, 0x02, 0x4D, 0x02, 0x86, 0x02, 0x87, 0x02, 0xC3, 0x03, 0x03), _INIT_CMD(0xE2, 0x03, 0x2A, 0x03, 0x56, 0x03, 0x72, 0x03, 0x94, 0x03, 0xAC, 0x03, 0xCB, 0x03, 0xE0, 0x03, 0xED), _INIT_CMD(0xE3, 0x03, 0xFF, 0x03, 0xFF), /* page 3 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x03), _INIT_CMD(0xB0, 0x00, 0x00, 0x00, 0x00), _INIT_CMD(0xB1, 0x00, 0x00, 0x00, 0x00), _INIT_CMD(0xB2, 0x00, 0x00, 0x06, 0x04, 0x01, 0x40, 0x85), _INIT_CMD(0xB3, 0x10, 0x07, 0xFC, 0x04, 0x01, 0x40, 0x80), _INIT_CMD(0xB6, 0xF0, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x40, 0x80), _INIT_CMD(0xBA, 0xC5, 0x07, 0x00, 0x04, 0x11, 0x25, 0x8C), _INIT_CMD(0xBB, 0xC5, 0x07, 0x00, 0x03, 0x11, 0x25, 0x8C), _INIT_CMD(0xC0, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x80, 0x80), _INIT_CMD(0xC1, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x80, 0x80), _INIT_CMD(0xC4, 0x00, 0x00), _INIT_CMD(0xEF, 0x41), /* page 4 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x04), _INIT_CMD(0xEC, 0x4C), /* page 5 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x05), _INIT_CMD(0xB0, 0x13, 0x03, 0x03, 0x01), _INIT_CMD(0xB1, 0x30, 0x00), _INIT_CMD(0xB2, 0x02, 0x02, 0x00), _INIT_CMD(0xB3, 0x82, 0x23, 0x82, 0x9D), _INIT_CMD(0xB4, 0xC5, 0x75, 0x24, 0x57), _INIT_CMD(0xB5, 0x00, 0xD4, 0x72, 0x11, 0x11, 0xAB, 0x0A), _INIT_CMD(0xB6, 0x00, 0x00, 0xD5, 0x72, 0x24, 0x56), _INIT_CMD(0xB7, 0x5C, 0xDC, 0x5C, 0x5C), _INIT_CMD(0xB9, 0x0C, 0x00, 0x00, 0x01, 0x00), _INIT_CMD(0xC0, 0x75, 0x11, 0x11, 0x54, 0x05), _INIT_CMD(0xC6, 0x00, 0x00, 0x00, 0x00), _INIT_CMD(0xD0, 0x00, 0x48, 0x08, 0x00, 0x00), _INIT_CMD(0xD1, 0x00, 0x48, 0x09, 0x00, 0x00), /* page 6 */ _INIT_CMD(0xF0, 0x55, 0xAA, 0x52, 0x08, 0x06), _INIT_CMD(0xB0, 0x02, 0x32, 0x32, 0x08, 0x2F), _INIT_CMD(0xB1, 0x2E, 0x15, 0x14, 0x13, 0x12), _INIT_CMD(0xB2, 0x11, 0x10, 0x00, 0x3D, 0x3D), _INIT_CMD(0xB3, 0x3D, 0x3D, 0x3D, 0x3D, 0x3D), _INIT_CMD(0xB4, 0x3D, 0x32), _INIT_CMD(0xB5, 0x03, 0x32, 0x32, 0x09, 0x2F), _INIT_CMD(0xB6, 0x2E, 0x1B, 0x1A, 0x19, 0x18), _INIT_CMD(0xB7, 0x17, 0x16, 0x01, 0x3D, 0x3D), _INIT_CMD(0xB8, 0x3D, 0x3D, 0x3D, 0x3D, 0x3D), _INIT_CMD(0xB9, 0x3D, 0x32), _INIT_CMD(0xC0, 0x01, 0x32, 0x32, 0x09, 0x2F), _INIT_CMD(0xC1, 0x2E, 0x1A, 0x1B, 0x16, 0x17), _INIT_CMD(0xC2, 0x18, 0x19, 0x03, 0x3D, 0x3D), _INIT_CMD(0xC3, 0x3D, 0x3D, 0x3D, 0x3D, 0x3D), _INIT_CMD(0xC4, 0x3D, 0x32), _INIT_CMD(0xC5, 0x00, 0x32, 0x32, 0x08, 0x2F), _INIT_CMD(0xC6, 0x2E, 0x14, 0x15, 0x10, 0x11), _INIT_CMD(0xC7, 0x12, 0x13, 0x02, 0x3D, 0x3D), _INIT_CMD(0xC8, 0x3D, 0x3D, 0x3D, 0x3D, 0x3D), _INIT_CMD(0xC9, 0x3D, 0x32), {}, }; static const struct panel_desc innolux_p097pfg_panel_desc = { .mode = &innolux_p097pfg_mode, .bpc = 8, .size = { .width = 147, .height = 196, }, .flags = MIPI_DSI_MODE_VIDEO | MIPI_DSI_MODE_VIDEO_SYNC_PULSE | MIPI_DSI_MODE_LPM, .format = MIPI_DSI_FMT_RGB888, .init_cmds = innolux_p097pfg_init_cmds, .lanes = 4, .supply_names = innolux_p097pfg_supply_names, .num_supplies = ARRAY_SIZE(innolux_p097pfg_supply_names), .sleep_mode_delay = 100, /* T15 */ }; static int innolux_panel_get_modes(struct drm_panel *panel) { struct innolux_panel *innolux = to_innolux_panel(panel); const struct drm_display_mode *m = innolux->desc->mode; struct drm_display_mode *mode; mode = drm_mode_duplicate(panel->drm, m); if (!mode) { DRM_DEV_ERROR(panel->drm->dev, "failed to add mode %ux%ux@%u\n", m->hdisplay, m->vdisplay, m->vrefresh); return -ENOMEM; } drm_mode_set_name(mode); drm_mode_probed_add(panel->connector, mode); panel->connector->display_info.width_mm = innolux->desc->size.width; panel->connector->display_info.height_mm = innolux->desc->size.height; panel->connector->display_info.bpc = innolux->desc->bpc; return 1; } static const struct drm_panel_funcs innolux_panel_funcs = { .disable = innolux_panel_disable, .unprepare = innolux_panel_unprepare, .prepare = innolux_panel_prepare, .enable = innolux_panel_enable, .get_modes = innolux_panel_get_modes, }; static const struct of_device_id innolux_of_match[] = { { .compatible = "innolux,p079zca", .data = &innolux_p079zca_panel_desc }, { .compatible = "innolux,p097pfg", .data = &innolux_p097pfg_panel_desc }, { } }; MODULE_DEVICE_TABLE(of, innolux_of_match); static int innolux_panel_add(struct mipi_dsi_device *dsi, const struct panel_desc *desc) { struct innolux_panel *innolux; struct device *dev = &dsi->dev; int err, i; innolux = devm_kzalloc(dev, sizeof(*innolux), GFP_KERNEL); if (!innolux) return -ENOMEM; innolux->desc = desc; innolux->supplies = devm_kcalloc(dev, desc->num_supplies, sizeof(*innolux->supplies), GFP_KERNEL); if (!innolux->supplies) return -ENOMEM; for (i = 0; i < desc->num_supplies; i++) innolux->supplies[i].supply = desc->supply_names[i]; err = devm_regulator_bulk_get(dev, desc->num_supplies, innolux->supplies); if (err < 0) return err; innolux->enable_gpio = devm_gpiod_get_optional(dev, "enable", GPIOD_OUT_HIGH); if (IS_ERR(innolux->enable_gpio)) { err = PTR_ERR(innolux->enable_gpio); dev_dbg(dev, "failed to get enable gpio: %d\n", err); innolux->enable_gpio = NULL; } innolux->backlight = devm_of_find_backlight(dev); if (IS_ERR(innolux->backlight)) return PTR_ERR(innolux->backlight); drm_panel_init(&innolux->base); innolux->base.funcs = &innolux_panel_funcs; innolux->base.dev = dev; err = drm_panel_add(&innolux->base); if (err < 0) return err; mipi_dsi_set_drvdata(dsi, innolux); innolux->link = dsi; return 0; } static void innolux_panel_del(struct innolux_panel *innolux) { drm_panel_remove(&innolux->base); } static int innolux_panel_probe(struct mipi_dsi_device *dsi) { const struct panel_desc *desc; int err; desc = of_device_get_match_data(&dsi->dev); dsi->mode_flags = desc->flags; dsi->format = desc->format; dsi->lanes = desc->lanes; err = innolux_panel_add(dsi, desc); if (err < 0) return err; return mipi_dsi_attach(dsi); } static int innolux_panel_remove(struct mipi_dsi_device *dsi) { struct innolux_panel *innolux = mipi_dsi_get_drvdata(dsi); int err; err = innolux_panel_unprepare(&innolux->base); if (err < 0) DRM_DEV_ERROR(&dsi->dev, "failed to unprepare panel: %d\n", err); err = innolux_panel_disable(&innolux->base); if (err < 0) DRM_DEV_ERROR(&dsi->dev, "failed to disable panel: %d\n", err); err = mipi_dsi_detach(dsi); if (err < 0) DRM_DEV_ERROR(&dsi->dev, "failed to detach from DSI host: %d\n", err); innolux_panel_del(innolux); return 0; } static void innolux_panel_shutdown(struct mipi_dsi_device *dsi) { struct innolux_panel *innolux = mipi_dsi_get_drvdata(dsi); innolux_panel_unprepare(&innolux->base); innolux_panel_disable(&innolux->base); } static struct mipi_dsi_driver innolux_panel_driver = { .driver = { .name = "panel-innolux-p079zca", .of_match_table = innolux_of_match, }, .probe = innolux_panel_probe, .remove = innolux_panel_remove, .shutdown = innolux_panel_shutdown, }; module_mipi_dsi_driver(innolux_panel_driver); MODULE_AUTHOR("Chris Zhong <[email protected]>"); MODULE_AUTHOR("Lin Huang <[email protected]>"); MODULE_DESCRIPTION("Innolux P079ZCA panel driver"); MODULE_LICENSE("GPL v2");
247783.c
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE 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 ANY - 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. *====================================================================*/ /* * pixa2_reg.c * * Tests various replacement functions on pixa. */ #include "allheaders.h" int main(int argc, char **argv) { const char *name; l_int32 i, n; BOX *box; PIX *pix0, *pix1, *pixd; PIXA *pixa; SARRAY *sa1, *sa2, *sa3, *sa4; L_REGPARAMS *rp; if (regTestSetup(argc, argv, &rp)) return 1; /* ---------------- Find all the jpg and tif images --------------- */ sa1 = getSortedPathnamesInDirectory(".", ".jpg", 0, 0); sa2 = getSortedPathnamesInDirectory(".", ".tif", 0, 0); sa3 = sarraySelectByRange(sa1, 0, 9); sa4 = sarraySelectByRange(sa2, 0, 9); sarrayConcatenate(sa3, sa4); n =sarrayGetCount(sa3); sarrayDestroy(&sa1); sarrayDestroy(&sa2); sarrayDestroy(&sa4); /* ---------------- Use replace to fill up a pixa -------------------*/ pixa = pixaCreate(1); pixaExtendArrayToSize(pixa, n); if ((pix0 = pixRead("marge.jpg")) == NULL) rp->success = FALSE; pix1 = pixScaleToSize(pix0, 144, 108); /* scale 0.25 */ pixDestroy(&pix0); pixaInitFull(pixa, pix1, NULL); /* fill it up */ pixd = pixaDisplayTiledInRows(pixa, 32, 1000, 1.0, 0, 25, 2); pixDisplayWithTitle(pixd, 100, 100, NULL, rp->display); pixWrite("/tmp/pix1.jpg", pixd, IFF_JFIF_JPEG); pixDestroy(&pix1); pixDestroy(&pixd); /* ---------------- And again with jpgs and tifs -------------------*/ for (i = 0; i < n; i++) { name = sarrayGetString(sa3, i, L_NOCOPY); if ((pix0 = pixRead(name)) == NULL) rp->success = FALSE; pix1 = pixScaleToSize(pix0, 144, 108); pixaReplacePix(pixa, i, pix1, NULL); pixDestroy(&pix0); } pixd = pixaDisplayTiledInRows(pixa, 32, 1000, 1.0, 0, 25, 2); pixDisplayWithTitle(pixd, 400, 100, NULL, rp->display); pixWrite("/tmp/pix2.jpg", pixd, IFF_JFIF_JPEG); pixDestroy(&pixd); /* ---------------- And again, reversing the order ------------------*/ box = boxCreate(0, 0, 0, 0); pixaInitFull(pixa, NULL, box); boxDestroy(&box); for (i = 0; i < n; i++) { name = sarrayGetString(sa3, i, L_NOCOPY); if ((pix0 = pixRead(name)) == NULL) rp->success = FALSE; pix1 = pixScaleToSize(pix0, 144, 108); pixaReplacePix(pixa, n - 1 - i, pix1, NULL); pixDestroy(&pix0); } pixd = pixaDisplayTiledInRows(pixa, 32, 1000, 1.0, 0, 25, 2); pixDisplayWithTitle(pixd, 700, 100, NULL, rp->display); pixWrite("/tmp/pix3.jpg", pixd, IFF_JFIF_JPEG); pixDestroy(&pixd); sarrayDestroy(&sa3); pixaDestroy(&pixa); return regTestCleanup(rp); }
428937.c
/* * Converts filenames from decomposed unicode into precomposed unicode. * Used on MacOS X. */ #define PRECOMPOSE_UNICODE_C #include "cache.h" #include "utf8.h" #include "precompose_utf8.h" typedef char *iconv_ibp; static const char *repo_encoding = "UTF-8"; static const char *path_encoding = "UTF-8-MAC"; static size_t has_non_ascii(const char *s, size_t maxlen, size_t *strlen_c) { const uint8_t *ptr = (const uint8_t *)s; size_t strlen_chars = 0; size_t ret = 0; if (!ptr || !*ptr) return 0; while (*ptr && maxlen) { if (*ptr & 0x80) ret++; strlen_chars++; ptr++; maxlen--; } if (strlen_c) *strlen_c = strlen_chars; return ret; } void probe_utf8_pathname_composition(void) { struct strbuf path = STRBUF_INIT; static const char *auml_nfc = "\xc3\xa4"; static const char *auml_nfd = "\x61\xcc\x88"; int output_fd; if (precomposed_unicode != -1) return; /* We found it defined in the global config, respect it */ git_path_buf(&path, "%s", auml_nfc); output_fd = open(path.buf, O_CREAT|O_EXCL|O_RDWR, 0600); if (output_fd >= 0) { close(output_fd); git_path_buf(&path, "%s", auml_nfd); precomposed_unicode = access(path.buf, R_OK) ? 0 : 1; git_config_set("core.precomposeunicode", precomposed_unicode ? "true" : "false"); git_path_buf(&path, "%s", auml_nfc); if (unlink(path.buf)) die_errno(_("failed to unlink '%s'"), path.buf); } strbuf_release(&path); } void precompose_argv(int argc, const char **argv) { int i = 0; const char *oldarg; char *newarg; iconv_t ic_precompose; if (precomposed_unicode != 1) return; ic_precompose = iconv_open(repo_encoding, path_encoding); if (ic_precompose == (iconv_t) -1) return; while (i < argc) { size_t namelen; oldarg = argv[i]; if (has_non_ascii(oldarg, (size_t)-1, &namelen)) { newarg = reencode_string_iconv(oldarg, namelen, ic_precompose, NULL); if (newarg) argv[i] = newarg; } i++; } iconv_close(ic_precompose); } PREC_DIR *precompose_utf8_opendir(const char *dirname) { PREC_DIR *prec_dir = xmalloc(sizeof(PREC_DIR)); prec_dir->dirent_nfc = xmalloc(sizeof(dirent_prec_psx)); prec_dir->dirent_nfc->max_name_len = sizeof(prec_dir->dirent_nfc->d_name); prec_dir->dirp = opendir(dirname); if (!prec_dir->dirp) { free(prec_dir->dirent_nfc); free(prec_dir); return NULL; } else { int ret_errno = errno; prec_dir->ic_precompose = iconv_open(repo_encoding, path_encoding); /* if iconv_open() fails, die() in readdir() if needed */ errno = ret_errno; } return prec_dir; } struct dirent_prec_psx *precompose_utf8_readdir(PREC_DIR *prec_dir) { struct dirent *res; res = readdir(prec_dir->dirp); if (res) { size_t namelenz = strlen(res->d_name) + 1; /* \0 */ size_t new_maxlen = namelenz; int ret_errno = errno; if (new_maxlen > prec_dir->dirent_nfc->max_name_len) { size_t new_len = sizeof(dirent_prec_psx) + new_maxlen - sizeof(prec_dir->dirent_nfc->d_name); prec_dir->dirent_nfc = xrealloc(prec_dir->dirent_nfc, new_len); prec_dir->dirent_nfc->max_name_len = new_maxlen; } prec_dir->dirent_nfc->d_ino = res->d_ino; prec_dir->dirent_nfc->d_type = res->d_type; if ((precomposed_unicode == 1) && has_non_ascii(res->d_name, (size_t)-1, NULL)) { if (prec_dir->ic_precompose == (iconv_t)-1) { die("iconv_open(%s,%s) failed, but needed:\n" " precomposed unicode is not supported.\n" " If you want to use decomposed unicode, run\n" " \"git config core.precomposeunicode false\"\n", repo_encoding, path_encoding); } else { iconv_ibp cp = (iconv_ibp)res->d_name; size_t inleft = namelenz; char *outpos = &prec_dir->dirent_nfc->d_name[0]; size_t outsz = prec_dir->dirent_nfc->max_name_len; errno = 0; iconv(prec_dir->ic_precompose, &cp, &inleft, &outpos, &outsz); if (errno || inleft) { /* * iconv() failed and errno could be E2BIG, EILSEQ, EINVAL, EBADF * MacOS X avoids illegal byte sequemces. * If they occur on a mounted drive (e.g. NFS) it is not worth to * die() for that, but rather let the user see the original name */ namelenz = 0; /* trigger strlcpy */ } } } else namelenz = 0; if (!namelenz) strlcpy(prec_dir->dirent_nfc->d_name, res->d_name, prec_dir->dirent_nfc->max_name_len); errno = ret_errno; return prec_dir->dirent_nfc; } return NULL; } int precompose_utf8_closedir(PREC_DIR *prec_dir) { int ret_value; int ret_errno; ret_value = closedir(prec_dir->dirp); ret_errno = errno; if (prec_dir->ic_precompose != (iconv_t)-1) iconv_close(prec_dir->ic_precompose); free(prec_dir->dirent_nfc); free(prec_dir); errno = ret_errno; return ret_value; }
487175.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) 2009 by Nicholas Bishop * All rights reserved. */ /** \file * \ingroup bke */ #include <stdlib.h> #include <string.h> #include "MEM_guardedalloc.h" #include "DNA_object_types.h" #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "DNA_modifier_types.h" #include "DNA_scene_types.h" #include "DNA_brush_types.h" #include "DNA_space_types.h" #include "DNA_gpencil_types.h" #include "DNA_view3d_types.h" #include "DNA_workspace_types.h" #include "BLI_bitmap.h" #include "BLI_utildefines.h" #include "BLI_math_vector.h" #include "BLI_listbase.h" #include "BLT_translation.h" #include "BKE_animsys.h" #include "BKE_brush.h" #include "BKE_ccg.h" #include "BKE_colortools.h" #include "BKE_deform.h" #include "BKE_main.h" #include "BKE_context.h" #include "BKE_crazyspace.h" #include "BKE_gpencil.h" #include "BKE_image.h" #include "BKE_key.h" #include "BKE_lib_id.h" #include "BKE_mesh.h" #include "BKE_mesh_mapping.h" #include "BKE_mesh_runtime.h" #include "BKE_modifier.h" #include "BKE_multires.h" #include "BKE_object.h" #include "BKE_paint.h" #include "BKE_pbvh.h" #include "BKE_subdiv_ccg.h" #include "BKE_subsurf.h" #include "DEG_depsgraph.h" #include "DEG_depsgraph_query.h" #include "RNA_enum_types.h" #include "bmesh.h" const char PAINT_CURSOR_SCULPT[3] = {255, 100, 100}; const char PAINT_CURSOR_VERTEX_PAINT[3] = {255, 255, 255}; const char PAINT_CURSOR_WEIGHT_PAINT[3] = {200, 200, 255}; const char PAINT_CURSOR_TEXTURE_PAINT[3] = {255, 255, 255}; static ePaintOverlayControlFlags overlay_flags = 0; void BKE_paint_invalidate_overlay_tex(Scene *scene, ViewLayer *view_layer, const Tex *tex) { Paint *p = BKE_paint_get_active(scene, view_layer); if (!p) { return; } Brush *br = p->brush; if (!br) { return; } if (br->mtex.tex == tex) { overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY; } if (br->mask_mtex.tex == tex) { overlay_flags |= PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY; } } void BKE_paint_invalidate_cursor_overlay(Scene *scene, ViewLayer *view_layer, CurveMapping *curve) { Paint *p = BKE_paint_get_active(scene, view_layer); if (p == NULL) { return; } Brush *br = p->brush; if (br && br->curve == curve) { overlay_flags |= PAINT_OVERLAY_INVALID_CURVE; } } void BKE_paint_invalidate_overlay_all(void) { overlay_flags |= (PAINT_OVERLAY_INVALID_TEXTURE_SECONDARY | PAINT_OVERLAY_INVALID_TEXTURE_PRIMARY | PAINT_OVERLAY_INVALID_CURVE); } ePaintOverlayControlFlags BKE_paint_get_overlay_flags(void) { return overlay_flags; } void BKE_paint_set_overlay_override(eOverlayFlags flags) { if (flags & BRUSH_OVERLAY_OVERRIDE_MASK) { if (flags & BRUSH_OVERLAY_CURSOR_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_CURSOR; } if (flags & BRUSH_OVERLAY_PRIMARY_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_PRIMARY; } if (flags & BRUSH_OVERLAY_SECONDARY_OVERRIDE_ON_STROKE) { overlay_flags |= PAINT_OVERLAY_OVERRIDE_SECONDARY; } } else { overlay_flags &= ~(PAINT_OVERRIDE_MASK); } } void BKE_paint_reset_overlay_invalid(ePaintOverlayControlFlags flag) { overlay_flags &= ~(flag); } bool BKE_paint_ensure_from_paintmode(Scene *sce, ePaintMode mode) { ToolSettings *ts = sce->toolsettings; Paint **paint_ptr = NULL; /* Some paint modes don't store paint settings as pointer, for these this can be set and * referenced by paint_ptr. */ Paint *paint_tmp = NULL; switch (mode) { case PAINT_MODE_SCULPT: paint_ptr = (Paint **)&ts->sculpt; break; case PAINT_MODE_VERTEX: paint_ptr = (Paint **)&ts->vpaint; break; case PAINT_MODE_WEIGHT: paint_ptr = (Paint **)&ts->wpaint; break; case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: paint_tmp = (Paint *)&ts->imapaint; paint_ptr = &paint_tmp; break; case PAINT_MODE_SCULPT_UV: paint_ptr = (Paint **)&ts->uvsculpt; break; case PAINT_MODE_GPENCIL: paint_ptr = (Paint **)&ts->gp_paint; break; case PAINT_MODE_INVALID: break; } if (paint_ptr) { BKE_paint_ensure(ts, paint_ptr); return true; } return false; } Paint *BKE_paint_get_active_from_paintmode(Scene *sce, ePaintMode mode) { if (sce) { ToolSettings *ts = sce->toolsettings; switch (mode) { case PAINT_MODE_SCULPT: return &ts->sculpt->paint; case PAINT_MODE_VERTEX: return &ts->vpaint->paint; case PAINT_MODE_WEIGHT: return &ts->wpaint->paint; case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return &ts->imapaint.paint; case PAINT_MODE_SCULPT_UV: return &ts->uvsculpt->paint; case PAINT_MODE_GPENCIL: return &ts->gp_paint->paint; case PAINT_MODE_INVALID: return NULL; default: return &ts->imapaint.paint; } } return NULL; } const EnumPropertyItem *BKE_paint_get_tool_enum_from_paintmode(ePaintMode mode) { switch (mode) { case PAINT_MODE_SCULPT: return rna_enum_brush_sculpt_tool_items; case PAINT_MODE_VERTEX: return rna_enum_brush_vertex_tool_items; case PAINT_MODE_WEIGHT: return rna_enum_brush_weight_tool_items; case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return rna_enum_brush_image_tool_items; case PAINT_MODE_SCULPT_UV: return rna_enum_brush_uv_sculpt_tool_items; case PAINT_MODE_GPENCIL: return rna_enum_brush_gpencil_types_items; case PAINT_MODE_INVALID: break; } return NULL; } const char *BKE_paint_get_tool_prop_id_from_paintmode(ePaintMode mode) { switch (mode) { case PAINT_MODE_SCULPT: return "sculpt_tool"; case PAINT_MODE_VERTEX: return "vertex_tool"; case PAINT_MODE_WEIGHT: return "weight_tool"; case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return "image_tool"; case PAINT_MODE_SCULPT_UV: return "uv_sculpt_tool"; case PAINT_MODE_GPENCIL: return "gpencil_tool"; default: /* invalid paint mode */ return NULL; } } Paint *BKE_paint_get_active(Scene *sce, ViewLayer *view_layer) { if (sce && view_layer) { ToolSettings *ts = sce->toolsettings; if (view_layer->basact && view_layer->basact->object) { switch (view_layer->basact->object->mode) { case OB_MODE_SCULPT: return &ts->sculpt->paint; case OB_MODE_VERTEX_PAINT: return &ts->vpaint->paint; case OB_MODE_WEIGHT_PAINT: return &ts->wpaint->paint; case OB_MODE_TEXTURE_PAINT: return &ts->imapaint.paint; case OB_MODE_PAINT_GPENCIL: return &ts->gp_paint->paint; case OB_MODE_EDIT: return &ts->uvsculpt->paint; default: break; } } /* default to image paint */ return &ts->imapaint.paint; } return NULL; } Paint *BKE_paint_get_active_from_context(const bContext *C) { Scene *sce = CTX_data_scene(C); ViewLayer *view_layer = CTX_data_view_layer(C); SpaceImage *sima; if (sce && view_layer) { ToolSettings *ts = sce->toolsettings; Object *obact = NULL; if (view_layer->basact && view_layer->basact->object) { obact = view_layer->basact->object; } if ((sima = CTX_wm_space_image(C)) != NULL) { if (obact && obact->mode == OB_MODE_EDIT) { if (sima->mode == SI_MODE_PAINT) { return &ts->imapaint.paint; } else if (sima->mode == SI_MODE_UV) { return &ts->uvsculpt->paint; } } else { return &ts->imapaint.paint; } } else { return BKE_paint_get_active(sce, view_layer); } } return NULL; } ePaintMode BKE_paintmode_get_active_from_context(const bContext *C) { Scene *sce = CTX_data_scene(C); ViewLayer *view_layer = CTX_data_view_layer(C); SpaceImage *sima; if (sce && view_layer) { Object *obact = NULL; if (view_layer->basact && view_layer->basact->object) { obact = view_layer->basact->object; } if ((sima = CTX_wm_space_image(C)) != NULL) { if (obact && obact->mode == OB_MODE_EDIT) { if (sima->mode == SI_MODE_PAINT) { return PAINT_MODE_TEXTURE_2D; } else if (sima->mode == SI_MODE_UV) { return PAINT_MODE_SCULPT_UV; } } else { return PAINT_MODE_TEXTURE_2D; } } else if (obact) { switch (obact->mode) { case OB_MODE_SCULPT: return PAINT_MODE_SCULPT; case OB_MODE_VERTEX_PAINT: return PAINT_MODE_VERTEX; case OB_MODE_WEIGHT_PAINT: return PAINT_MODE_WEIGHT; case OB_MODE_TEXTURE_PAINT: return PAINT_MODE_TEXTURE_3D; case OB_MODE_EDIT: return PAINT_MODE_SCULPT_UV; default: return PAINT_MODE_TEXTURE_2D; } } else { /* default to image paint */ return PAINT_MODE_TEXTURE_2D; } } return PAINT_MODE_INVALID; } ePaintMode BKE_paintmode_get_from_tool(const struct bToolRef *tref) { if (tref->space_type == SPACE_VIEW3D) { switch (tref->mode) { case CTX_MODE_SCULPT: return PAINT_MODE_SCULPT; case CTX_MODE_PAINT_VERTEX: return PAINT_MODE_VERTEX; case CTX_MODE_PAINT_WEIGHT: return PAINT_MODE_WEIGHT; case CTX_MODE_PAINT_GPENCIL: return PAINT_MODE_GPENCIL; case CTX_MODE_PAINT_TEXTURE: return PAINT_MODE_TEXTURE_3D; } } else if (tref->space_type == SPACE_IMAGE) { switch (tref->mode) { case SI_MODE_PAINT: return PAINT_MODE_TEXTURE_2D; case SI_MODE_UV: return PAINT_MODE_SCULPT_UV; } } return PAINT_MODE_INVALID; } Brush *BKE_paint_brush(Paint *p) { return p ? p->brush : NULL; } void BKE_paint_brush_set(Paint *p, Brush *br) { if (p) { id_us_min((ID *)p->brush); id_us_plus((ID *)br); p->brush = br; BKE_paint_toolslots_brush_update(p); } } void BKE_paint_runtime_init(const ToolSettings *ts, Paint *paint) { if (paint == &ts->imapaint.paint) { paint->runtime.tool_offset = offsetof(Brush, imagepaint_tool); paint->runtime.ob_mode = OB_MODE_TEXTURE_PAINT; } else if (paint == &ts->sculpt->paint) { paint->runtime.tool_offset = offsetof(Brush, sculpt_tool); paint->runtime.ob_mode = OB_MODE_SCULPT; } else if (paint == &ts->vpaint->paint) { paint->runtime.tool_offset = offsetof(Brush, vertexpaint_tool); paint->runtime.ob_mode = OB_MODE_VERTEX_PAINT; } else if (paint == &ts->wpaint->paint) { paint->runtime.tool_offset = offsetof(Brush, weightpaint_tool); paint->runtime.ob_mode = OB_MODE_WEIGHT_PAINT; } else if (paint == &ts->uvsculpt->paint) { paint->runtime.tool_offset = offsetof(Brush, uv_sculpt_tool); paint->runtime.ob_mode = OB_MODE_EDIT; } else if (paint == &ts->gp_paint->paint) { paint->runtime.tool_offset = offsetof(Brush, gpencil_tool); paint->runtime.ob_mode = OB_MODE_PAINT_GPENCIL; } else { BLI_assert(0); } } uint BKE_paint_get_brush_tool_offset_from_paintmode(const ePaintMode mode) { switch (mode) { case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return offsetof(Brush, imagepaint_tool); case PAINT_MODE_SCULPT: return offsetof(Brush, sculpt_tool); case PAINT_MODE_VERTEX: return offsetof(Brush, vertexpaint_tool); case PAINT_MODE_WEIGHT: return offsetof(Brush, weightpaint_tool); case PAINT_MODE_SCULPT_UV: return offsetof(Brush, uv_sculpt_tool); case PAINT_MODE_GPENCIL: return offsetof(Brush, gpencil_tool); case PAINT_MODE_INVALID: break; /* We don't use these yet. */ } return 0; } /** Free (or release) any data used by this paint curve (does not free the pcurve itself). */ void BKE_paint_curve_free(PaintCurve *pc) { MEM_SAFE_FREE(pc->points); pc->tot_points = 0; } PaintCurve *BKE_paint_curve_add(Main *bmain, const char *name) { PaintCurve *pc; pc = BKE_libblock_alloc(bmain, ID_PC, name, 0); return pc; } /** * Only copy internal data of PaintCurve ID from source to * already allocated/initialized destination. * You probably never want to use that directly, * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * * \param flag: Copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more). */ void BKE_paint_curve_copy_data(Main *UNUSED(bmain), PaintCurve *pc_dst, const PaintCurve *pc_src, const int UNUSED(flag)) { if (pc_src->tot_points != 0) { pc_dst->points = MEM_dupallocN(pc_src->points); } } PaintCurve *BKE_paint_curve_copy(Main *bmain, const PaintCurve *pc) { PaintCurve *pc_copy; BKE_id_copy(bmain, &pc->id, (ID **)&pc_copy); return pc_copy; } void BKE_paint_curve_make_local(Main *bmain, PaintCurve *pc, const bool lib_local) { BKE_id_make_local_generic(bmain, &pc->id, true, lib_local); } Palette *BKE_paint_palette(Paint *p) { return p ? p->palette : NULL; } void BKE_paint_palette_set(Paint *p, Palette *palette) { if (p) { id_us_min((ID *)p->palette); p->palette = palette; id_us_plus((ID *)p->palette); } } void BKE_paint_curve_set(Brush *br, PaintCurve *pc) { if (br) { id_us_min((ID *)br->paint_curve); br->paint_curve = pc; id_us_plus((ID *)br->paint_curve); } } void BKE_paint_curve_clamp_endpoint_add_index(PaintCurve *pc, const int add_index) { pc->add_index = (add_index || pc->tot_points == 1) ? (add_index + 1) : 0; } /** Remove color from palette. Must be certain color is inside the palette! */ void BKE_palette_color_remove(Palette *palette, PaletteColor *color) { if (BLI_listbase_count_at_most(&palette->colors, palette->active_color) == palette->active_color) { palette->active_color--; } BLI_remlink(&palette->colors, color); if (palette->active_color < 0 && !BLI_listbase_is_empty(&palette->colors)) { palette->active_color = 0; } MEM_freeN(color); } void BKE_palette_clear(Palette *palette) { BLI_freelistN(&palette->colors); palette->active_color = 0; } Palette *BKE_palette_add(Main *bmain, const char *name) { Palette *palette = BKE_id_new(bmain, ID_PAL, name); return palette; } /** * Only copy internal data of Palette ID from source * to already allocated/initialized destination. * You probably never want to use that directly, * use #BKE_id_copy or #BKE_id_copy_ex for typical needs. * * WARNING! This function will not handle ID user count! * * \param flag: Copying options (see BKE_lib_id.h's LIB_ID_COPY_... flags for more). */ void BKE_palette_copy_data(Main *UNUSED(bmain), Palette *palette_dst, const Palette *palette_src, const int UNUSED(flag)) { BLI_duplicatelist(&palette_dst->colors, &palette_src->colors); } Palette *BKE_palette_copy(Main *bmain, const Palette *palette) { Palette *palette_copy; BKE_id_copy(bmain, &palette->id, (ID **)&palette_copy); return palette_copy; } void BKE_palette_make_local(Main *bmain, Palette *palette, const bool lib_local) { BKE_id_make_local_generic(bmain, &palette->id, true, lib_local); } void BKE_palette_init(Palette *palette) { /* Enable fake user by default. */ id_fake_user_set(&palette->id); } /** Free (or release) any data used by this palette (does not free the palette itself). */ void BKE_palette_free(Palette *palette) { BLI_freelistN(&palette->colors); } PaletteColor *BKE_palette_color_add(Palette *palette) { PaletteColor *color = MEM_callocN(sizeof(*color), "Palette Color"); BLI_addtail(&palette->colors, color); return color; } bool BKE_palette_is_empty(const struct Palette *palette) { return BLI_listbase_is_empty(&palette->colors); } /* are we in vertex paint or weight paint face select mode? */ bool BKE_paint_select_face_test(Object *ob) { return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) && (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_FACE_SEL) && (ob->mode & (OB_MODE_VERTEX_PAINT | OB_MODE_WEIGHT_PAINT | OB_MODE_TEXTURE_PAINT))); } /* are we in weight paint vertex select mode? */ bool BKE_paint_select_vert_test(Object *ob) { return ((ob != NULL) && (ob->type == OB_MESH) && (ob->data != NULL) && (((Mesh *)ob->data)->editflag & ME_EDIT_PAINT_VERT_SEL) && (ob->mode & OB_MODE_WEIGHT_PAINT || ob->mode & OB_MODE_VERTEX_PAINT)); } /** * used to check if selection is possible * (when we don't care if its face or vert) */ bool BKE_paint_select_elem_test(Object *ob) { return (BKE_paint_select_vert_test(ob) || BKE_paint_select_face_test(ob)); } void BKE_paint_cavity_curve_preset(Paint *p, int preset) { CurveMapping *cumap = NULL; CurveMap *cuma = NULL; if (!p->cavity_curve) { p->cavity_curve = BKE_curvemapping_add(1, 0, 0, 1, 1); } cumap = p->cavity_curve; cumap->flag &= ~CUMA_EXTEND_EXTRAPOLATE; cumap->preset = preset; cuma = cumap->cm; BKE_curvemap_reset(cuma, &cumap->clipr, cumap->preset, CURVEMAP_SLOPE_POSITIVE); BKE_curvemapping_changed(cumap, false); } eObjectMode BKE_paint_object_mode_from_paintmode(ePaintMode mode) { switch (mode) { case PAINT_MODE_SCULPT: return OB_MODE_SCULPT; case PAINT_MODE_VERTEX: return OB_MODE_VERTEX_PAINT; case PAINT_MODE_WEIGHT: return OB_MODE_WEIGHT_PAINT; case PAINT_MODE_TEXTURE_2D: case PAINT_MODE_TEXTURE_3D: return OB_MODE_TEXTURE_PAINT; case PAINT_MODE_SCULPT_UV: return OB_MODE_EDIT; case PAINT_MODE_INVALID: default: return 0; } } /** * Call when entering each respective paint mode. */ bool BKE_paint_ensure(ToolSettings *ts, struct Paint **r_paint) { Paint *paint = NULL; if (*r_paint) { /* Tool offset should never be 0 for initialized paint settings, so it's a reliable way to * check if already initialized. */ if ((*r_paint)->runtime.tool_offset == 0) { /* Currently only image painting is initialized this way, others have to be allocated. */ BLI_assert(ELEM(*r_paint, (Paint *)&ts->imapaint)); BKE_paint_runtime_init(ts, *r_paint); } else { BLI_assert(ELEM(*r_paint, /* Cast is annoying, but prevent NULL-pointer access. */ (Paint *)ts->gp_paint, (Paint *)ts->sculpt, (Paint *)ts->vpaint, (Paint *)ts->wpaint, (Paint *)ts->uvsculpt, (Paint *)&ts->imapaint)); #ifdef DEBUG struct Paint paint_test = **r_paint; BKE_paint_runtime_init(ts, *r_paint); /* Swap so debug doesn't hide errors when release fails. */ SWAP(Paint, **r_paint, paint_test); BLI_assert(paint_test.runtime.ob_mode == (*r_paint)->runtime.ob_mode); BLI_assert(paint_test.runtime.tool_offset == (*r_paint)->runtime.tool_offset); #endif } return true; } if (((VPaint **)r_paint == &ts->vpaint) || ((VPaint **)r_paint == &ts->wpaint)) { VPaint *data = MEM_callocN(sizeof(*data), __func__); paint = &data->paint; } else if ((Sculpt **)r_paint == &ts->sculpt) { Sculpt *data = MEM_callocN(sizeof(*data), __func__); paint = &data->paint; /* Turn on X plane mirror symmetry by default */ paint->symmetry_flags |= PAINT_SYMM_X; /* Make sure at least dyntopo subdivision is enabled */ data->flags |= SCULPT_DYNTOPO_SUBDIVIDE | SCULPT_DYNTOPO_COLLAPSE; } else if ((GpPaint **)r_paint == &ts->gp_paint) { GpPaint *data = MEM_callocN(sizeof(*data), __func__); paint = &data->paint; } else if ((UvSculpt **)r_paint == &ts->uvsculpt) { UvSculpt *data = MEM_callocN(sizeof(*data), __func__); paint = &data->paint; } else if (*r_paint == &ts->imapaint.paint) { paint = &ts->imapaint.paint; } paint->flags |= PAINT_SHOW_BRUSH; *r_paint = paint; BKE_paint_runtime_init(ts, paint); return false; } void BKE_paint_init(Main *bmain, Scene *sce, ePaintMode mode, const char col[3]) { UnifiedPaintSettings *ups = &sce->toolsettings->unified_paint_settings; Paint *paint = BKE_paint_get_active_from_paintmode(sce, mode); BKE_paint_ensure_from_paintmode(sce, mode); /* If there's no brush, create one */ if (PAINT_MODE_HAS_BRUSH(mode)) { Brush *brush = BKE_paint_brush(paint); if (brush == NULL) { eObjectMode ob_mode = BKE_paint_object_mode_from_paintmode(mode); brush = BKE_brush_first_search(bmain, ob_mode); if (!brush) { brush = BKE_brush_add(bmain, "Brush", ob_mode); id_us_min(&brush->id); /* fake user only */ } BKE_paint_brush_set(paint, brush); } } memcpy(paint->paint_cursor_col, col, 3); paint->paint_cursor_col[3] = 128; ups->last_stroke_valid = false; zero_v3(ups->average_stroke_accum); ups->average_stroke_counter = 0; if (!paint->cavity_curve) { BKE_paint_cavity_curve_preset(paint, CURVE_PRESET_LINE); } } void BKE_paint_free(Paint *paint) { BKE_curvemapping_free(paint->cavity_curve); MEM_SAFE_FREE(paint->tool_slots); } /* called when copying scene settings, so even if 'src' and 'tar' are the same * still do a id_us_plus(), rather then if we were copying between 2 existing * scenes where a matching value should decrease the existing user count as * with paint_brush_set() */ void BKE_paint_copy(Paint *src, Paint *tar, const int flag) { tar->brush = src->brush; tar->cavity_curve = BKE_curvemapping_copy(src->cavity_curve); tar->tool_slots = MEM_dupallocN(src->tool_slots); if ((flag & LIB_ID_CREATE_NO_USER_REFCOUNT) == 0) { id_us_plus((ID *)tar->brush); id_us_plus((ID *)tar->palette); if (src->tool_slots != NULL) { for (int i = 0; i < tar->tool_slots_len; i++) { id_us_plus((ID *)tar->tool_slots[i].brush); } } } } void BKE_paint_stroke_get_average(Scene *scene, Object *ob, float stroke[3]) { UnifiedPaintSettings *ups = &scene->toolsettings->unified_paint_settings; if (ups->last_stroke_valid && ups->average_stroke_counter > 0) { float fac = 1.0f / ups->average_stroke_counter; mul_v3_v3fl(stroke, ups->average_stroke_accum, fac); } else { copy_v3_v3(stroke, ob->obmat[3]); } } /* returns non-zero if any of the face's vertices * are hidden, zero otherwise */ bool paint_is_face_hidden(const MLoopTri *lt, const MVert *mvert, const MLoop *mloop) { return ((mvert[mloop[lt->tri[0]].v].flag & ME_HIDE) || (mvert[mloop[lt->tri[1]].v].flag & ME_HIDE) || (mvert[mloop[lt->tri[2]].v].flag & ME_HIDE)); } /* returns non-zero if any of the corners of the grid * face whose inner corner is at (x, y) are hidden, * zero otherwise */ bool paint_is_grid_face_hidden(const uint *grid_hidden, int gridsize, int x, int y) { /* skip face if any of its corners are hidden */ return (BLI_BITMAP_TEST(grid_hidden, y * gridsize + x) || BLI_BITMAP_TEST(grid_hidden, y * gridsize + x + 1) || BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x + 1) || BLI_BITMAP_TEST(grid_hidden, (y + 1) * gridsize + x)); } /* Return true if all vertices in the face are visible, false otherwise */ bool paint_is_bmesh_face_hidden(BMFace *f) { BMLoop *l_iter; BMLoop *l_first; l_iter = l_first = BM_FACE_FIRST_LOOP(f); do { if (BM_elem_flag_test(l_iter->v, BM_ELEM_HIDDEN)) { return true; } } while ((l_iter = l_iter->next) != l_first); return false; } float paint_grid_paint_mask(const GridPaintMask *gpm, uint level, uint x, uint y) { int factor = BKE_ccg_factor(level, gpm->level); int gridsize = BKE_ccg_gridsize(gpm->level); return gpm->data[(y * factor) * gridsize + (x * factor)]; } /* threshold to move before updating the brush rotation */ #define RAKE_THRESHHOLD 20 void paint_update_brush_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, float rotation) { if (brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) { ups->brush_rotation = rotation; } else { ups->brush_rotation = 0.0f; } if (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE) { ups->brush_rotation_sec = rotation; } else { ups->brush_rotation_sec = 0.0f; } } bool paint_calculate_rake_rotation(UnifiedPaintSettings *ups, Brush *brush, const float mouse_pos[2]) { bool ok = false; if ((brush->mtex.brush_angle_mode & MTEX_ANGLE_RAKE) || (brush->mask_mtex.brush_angle_mode & MTEX_ANGLE_RAKE)) { const float r = RAKE_THRESHHOLD; float rotation; float dpos[2]; sub_v2_v2v2(dpos, ups->last_rake, mouse_pos); if (len_squared_v2(dpos) >= r * r) { rotation = atan2f(dpos[0], dpos[1]); copy_v2_v2(ups->last_rake, mouse_pos); ups->last_rake_angle = rotation; paint_update_brush_rake_rotation(ups, brush, rotation); ok = true; } /* make sure we reset here to the last rotation to avoid accumulating * values in case a random rotation is also added */ else { paint_update_brush_rake_rotation(ups, brush, ups->last_rake_angle); ok = false; } } else { ups->brush_rotation = ups->brush_rotation_sec = 0.0f; ok = true; } return ok; } void BKE_sculptsession_free_deformMats(SculptSession *ss) { MEM_SAFE_FREE(ss->orig_cos); MEM_SAFE_FREE(ss->deform_cos); MEM_SAFE_FREE(ss->deform_imats); } void BKE_sculptsession_free_vwpaint_data(struct SculptSession *ss) { struct SculptVertexPaintGeomMap *gmap = NULL; if (ss->mode_type == OB_MODE_VERTEX_PAINT) { gmap = &ss->mode.vpaint.gmap; MEM_SAFE_FREE(ss->mode.vpaint.previous_color); } else if (ss->mode_type == OB_MODE_WEIGHT_PAINT) { gmap = &ss->mode.wpaint.gmap; MEM_SAFE_FREE(ss->mode.wpaint.alpha_weight); if (ss->mode.wpaint.dvert_prev) { BKE_defvert_array_free_elems(ss->mode.wpaint.dvert_prev, ss->totvert); MEM_freeN(ss->mode.wpaint.dvert_prev); ss->mode.wpaint.dvert_prev = NULL; } } else { return; } MEM_SAFE_FREE(gmap->vert_to_loop); MEM_SAFE_FREE(gmap->vert_map_mem); MEM_SAFE_FREE(gmap->vert_to_poly); MEM_SAFE_FREE(gmap->poly_map_mem); } /* Write out the sculpt dynamic-topology BMesh to the Mesh */ static void sculptsession_bm_to_me_update_data_only(Object *ob, bool reorder) { SculptSession *ss = ob->sculpt; if (ss->bm) { if (ob->data) { BMIter iter; BMFace *efa; BM_ITER_MESH (efa, &iter, ss->bm, BM_FACES_OF_MESH) { BM_elem_flag_set(efa, BM_ELEM_SMOOTH, ss->bm_smooth_shading); } if (reorder) { BM_log_mesh_elems_reorder(ss->bm, ss->bm_log); } BM_mesh_bm_to_me(NULL, ss->bm, ob->data, (&(struct BMeshToMeshParams){ .calc_object_remap = false, })); } } } void BKE_sculptsession_bm_to_me(Object *ob, bool reorder) { if (ob && ob->sculpt) { sculptsession_bm_to_me_update_data_only(ob, reorder); /* Ensure the objects evaluated mesh doesn't hold onto arrays * now realloc'd in the mesh T34473. */ DEG_id_tag_update(&ob->id, ID_RECALC_GEOMETRY); } } static void sculptsession_free_pbvh(Object *object) { SculptSession *ss = object->sculpt; if (!ss) { return; } if (ss->pbvh) { BKE_pbvh_free(ss->pbvh); ss->pbvh = NULL; } MEM_SAFE_FREE(ss->pmap); MEM_SAFE_FREE(ss->pmap_mem); MEM_SAFE_FREE(ss->preview_vert_index_list); ss->preview_vert_index_count = 0; } void BKE_sculptsession_bm_to_me_for_render(Object *object) { if (object && object->sculpt) { if (object->sculpt->bm) { /* Ensure no points to old arrays are stored in DM * * Apparently, we could not use DEG_id_tag_update * here because this will lead to the while object * surface to disappear, so we'll release DM in place. */ BKE_object_free_derived_caches(object); sculptsession_bm_to_me_update_data_only(object, false); /* In contrast with sculptsession_bm_to_me no need in * DAG tag update here - derived mesh was freed and * old pointers are nowhere stored. */ } } } void BKE_sculptsession_free(Object *ob) { if (ob && ob->sculpt) { SculptSession *ss = ob->sculpt; if (ss->bm) { BKE_sculptsession_bm_to_me(ob, true); BM_mesh_free(ss->bm); } sculptsession_free_pbvh(ob); MEM_SAFE_FREE(ss->pmap); MEM_SAFE_FREE(ss->pmap_mem); if (ss->bm_log) { BM_log_free(ss->bm_log); } if (ss->texcache) { MEM_freeN(ss->texcache); } if (ss->tex_pool) { BKE_image_pool_free(ss->tex_pool); } if (ss->layer_co) { MEM_freeN(ss->layer_co); } if (ss->orig_cos) { MEM_freeN(ss->orig_cos); } if (ss->deform_cos) { MEM_freeN(ss->deform_cos); } if (ss->deform_imats) { MEM_freeN(ss->deform_imats); } if (ss->preview_vert_index_list) { MEM_freeN(ss->preview_vert_index_list); } if (ss->pose_ik_chain_preview) { for (int i = 0; i < ss->pose_ik_chain_preview->tot_segments; i++) { MEM_SAFE_FREE(ss->pose_ik_chain_preview->segments[i].weights); } MEM_SAFE_FREE(ss->pose_ik_chain_preview->segments); MEM_SAFE_FREE(ss->pose_ik_chain_preview); } BKE_sculptsession_free_vwpaint_data(ob->sculpt); MEM_freeN(ss); ob->sculpt = NULL; } } /* Sculpt mode handles multires differently from regular meshes, but only if * it's the last modifier on the stack and it is not on the first level */ MultiresModifierData *BKE_sculpt_multires_active(Scene *scene, Object *ob) { Mesh *me = (Mesh *)ob->data; ModifierData *md; VirtualModifierData virtualModifierData; if (ob->sculpt && ob->sculpt->bm) { /* can't combine multires and dynamic topology */ return NULL; } if (!CustomData_get_layer(&me->ldata, CD_MDISPS)) { /* multires can't work without displacement layer */ return NULL; } /* Weight paint operates on original vertices, and needs to treat multires as regular modifier * to make it so that PBVH vertices are at the multires surface. */ if ((ob->mode & OB_MODE_SCULPT) == 0) { return NULL; } for (md = modifiers_getVirtualModifierList(ob, &virtualModifierData); md; md = md->next) { if (md->type == eModifierType_Multires) { MultiresModifierData *mmd = (MultiresModifierData *)md; if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; } if (BKE_multires_sculpt_level_get(mmd) > 0) { return mmd; } else { return NULL; } } } return NULL; } /* Checks if there are any supported deformation modifiers active */ static bool sculpt_modifiers_active(Scene *scene, Sculpt *sd, Object *ob) { ModifierData *md; Mesh *me = (Mesh *)ob->data; MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob); VirtualModifierData virtualModifierData; if (mmd || ob->sculpt->bm) { return false; } /* non-locked shape keys could be handled in the same way as deformed mesh */ if ((ob->shapeflag & OB_SHAPE_LOCK) == 0 && me->key && ob->shapenr) { return true; } md = modifiers_getVirtualModifierList(ob, &virtualModifierData); /* exception for shape keys because we can edit those */ for (; md; md = md->next) { const ModifierTypeInfo *mti = modifierType_getInfo(md->type); if (!modifier_isEnabled(scene, md, eModifierMode_Realtime)) { continue; } if (md->type == eModifierType_Multires && (ob->mode & OB_MODE_SCULPT)) { continue; } if (md->type == eModifierType_ShapeKey) { continue; } if (mti->type == eModifierTypeType_OnlyDeform) { return true; } else if ((sd->flags & SCULPT_ONLY_DEFORM) == 0) { return true; } } return false; } /** * \param need_mask: So that the evaluated mesh that is returned has mask data. */ static void sculpt_update_object( Depsgraph *depsgraph, Object *ob, Mesh *me_eval, bool need_pmap, bool need_mask) { Scene *scene = DEG_get_input_scene(depsgraph); Sculpt *sd = scene->toolsettings->sculpt; SculptSession *ss = ob->sculpt; Mesh *me = BKE_object_get_original_mesh(ob); MultiresModifierData *mmd = BKE_sculpt_multires_active(scene, ob); ss->deform_modifiers_active = sculpt_modifiers_active(scene, sd, ob); ss->show_mask = (sd->flags & SCULPT_HIDE_MASK) == 0; ss->building_vp_handle = false; if (need_mask) { if (mmd == NULL) { if (!CustomData_has_layer(&me->vdata, CD_PAINT_MASK)) { BKE_sculpt_mask_layers_ensure(ob, NULL); } } else { if (!CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) { BKE_sculpt_mask_layers_ensure(ob, mmd); } } } /* tessfaces aren't used and will become invalid */ BKE_mesh_tessface_clear(me); ss->shapekey_active = (mmd == NULL) ? BKE_keyblock_from_object(ob) : NULL; /* NOTE: Weight pPaint require mesh info for loop lookup, but it never uses multires code path, * so no extra checks is needed here. */ if (mmd) { ss->multires = mmd; ss->totvert = me_eval->totvert; ss->totpoly = me_eval->totpoly; ss->mvert = NULL; ss->mpoly = NULL; ss->mloop = NULL; } else { ss->totvert = me->totvert; ss->totpoly = me->totpoly; ss->mvert = me->mvert; ss->mpoly = me->mpoly; ss->mloop = me->mloop; ss->multires = NULL; ss->vmask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK); } ss->subdiv_ccg = me_eval->runtime.subdiv_ccg; PBVH *pbvh = BKE_sculpt_object_pbvh_ensure(depsgraph, ob); BLI_assert(pbvh == ss->pbvh); UNUSED_VARS_NDEBUG(pbvh); if (need_pmap && ob->type == OB_MESH && !ss->pmap) { BKE_mesh_vert_poly_map_create( &ss->pmap, &ss->pmap_mem, me->mpoly, me->mloop, me->totvert, me->totpoly, me->totloop); } pbvh_show_mask_set(ss->pbvh, ss->show_mask); if (ss->deform_modifiers_active) { if (!ss->orig_cos) { int a; BKE_sculptsession_free_deformMats(ss); ss->orig_cos = (ss->shapekey_active) ? BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active) : BKE_mesh_vert_coords_alloc(me, NULL); BKE_crazyspace_build_sculpt(depsgraph, scene, ob, &ss->deform_imats, &ss->deform_cos); BKE_pbvh_vert_coords_apply(ss->pbvh, ss->deform_cos, me->totvert); for (a = 0; a < me->totvert; a++) { invert_m3(ss->deform_imats[a]); } } } else { BKE_sculptsession_free_deformMats(ss); } if (ss->shapekey_active != NULL && ss->deform_cos == NULL) { ss->deform_cos = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active); } /* if pbvh is deformed, key block is already applied to it */ if (ss->shapekey_active) { bool pbvh_deformed = BKE_pbvh_is_deformed(ss->pbvh); if (!pbvh_deformed || ss->deform_cos == NULL) { float(*vertCos)[3] = BKE_keyblock_convert_to_vertcos(ob, ss->shapekey_active); if (vertCos) { if (!pbvh_deformed) { /* apply shape keys coordinates to PBVH */ BKE_pbvh_vert_coords_apply(ss->pbvh, vertCos, me->totvert); } if (ss->deform_cos == NULL) { ss->deform_cos = vertCos; } if (vertCos != ss->deform_cos) { MEM_freeN(vertCos); } } } } } void BKE_sculpt_update_object_before_eval(Object *ob) { /* Update before mesh evaluation in the dependency graph. */ SculptSession *ss = ob->sculpt; if (ss && ss->building_vp_handle == false) { if (!ss->cache && !ss->filter_cache) { /* We free pbvh on changes, except in the middle of drawing a stroke * since it can't deal with changing PVBH node organization, we hope * topology does not change in the meantime .. weak. */ sculptsession_free_pbvh(ob); BKE_sculptsession_free_deformMats(ob->sculpt); /* In vertex/weight paint, force maps to be rebuilt. */ BKE_sculptsession_free_vwpaint_data(ob->sculpt); } else { PBVHNode **nodes; int n, totnode; BKE_pbvh_search_gather(ss->pbvh, NULL, NULL, &nodes, &totnode); for (n = 0; n < totnode; n++) { BKE_pbvh_node_mark_update(nodes[n]); } MEM_freeN(nodes); } } } void BKE_sculpt_update_object_after_eval(Depsgraph *depsgraph, Object *ob_eval) { /* Update after mesh evaluation in the dependency graph, to rebuild PBVH or * other data when modifiers change the mesh. */ Object *ob_orig = DEG_get_original_object(ob_eval); Mesh *me_eval = ob_eval->runtime.mesh_eval; BLI_assert(me_eval != NULL); sculpt_update_object(depsgraph, ob_orig, me_eval, false, false); } void BKE_sculpt_update_object_for_edit(Depsgraph *depsgraph, Object *ob_orig, bool need_pmap, bool need_mask) { /* Update from sculpt operators and undo, to update sculpt session * and PBVH after edits. */ Scene *scene_eval = DEG_get_evaluated_scene(depsgraph); Object *ob_eval = DEG_get_evaluated_object(depsgraph, ob_orig); Mesh *me_eval = mesh_get_eval_final(depsgraph, scene_eval, ob_eval, &CD_MASK_BAREMESH); BLI_assert(ob_orig == DEG_get_original_object(ob_orig)); sculpt_update_object(depsgraph, ob_orig, me_eval, need_pmap, need_mask); } int BKE_sculpt_mask_layers_ensure(Object *ob, MultiresModifierData *mmd) { const float *paint_mask; Mesh *me = ob->data; int ret = 0; paint_mask = CustomData_get_layer(&me->vdata, CD_PAINT_MASK); /* if multires is active, create a grid paint mask layer if there * isn't one already */ if (mmd && !CustomData_has_layer(&me->ldata, CD_GRID_PAINT_MASK)) { GridPaintMask *gmask; int level = max_ii(1, BKE_multires_sculpt_level_get(mmd)); int gridsize = BKE_ccg_gridsize(level); int gridarea = gridsize * gridsize; int i, j; gmask = CustomData_add_layer(&me->ldata, CD_GRID_PAINT_MASK, CD_CALLOC, NULL, me->totloop); for (i = 0; i < me->totloop; i++) { GridPaintMask *gpm = &gmask[i]; gpm->level = level; gpm->data = MEM_callocN(sizeof(float) * gridarea, "GridPaintMask.data"); } /* if vertices already have mask, copy into multires data */ if (paint_mask) { for (i = 0; i < me->totpoly; i++) { const MPoly *p = &me->mpoly[i]; float avg = 0; /* mask center */ for (j = 0; j < p->totloop; j++) { const MLoop *l = &me->mloop[p->loopstart + j]; avg += paint_mask[l->v]; } avg /= (float)p->totloop; /* fill in multires mask corner */ for (j = 0; j < p->totloop; j++) { GridPaintMask *gpm = &gmask[p->loopstart + j]; const MLoop *l = &me->mloop[p->loopstart + j]; const MLoop *prev = ME_POLY_LOOP_PREV(me->mloop, p, j); const MLoop *next = ME_POLY_LOOP_NEXT(me->mloop, p, j); gpm->data[0] = avg; gpm->data[1] = (paint_mask[l->v] + paint_mask[next->v]) * 0.5f; gpm->data[2] = (paint_mask[l->v] + paint_mask[prev->v]) * 0.5f; gpm->data[3] = paint_mask[l->v]; } } } ret |= SCULPT_MASK_LAYER_CALC_LOOP; } /* create vertex paint mask layer if there isn't one already */ if (!paint_mask) { CustomData_add_layer(&me->vdata, CD_PAINT_MASK, CD_CALLOC, NULL, me->totvert); ret |= SCULPT_MASK_LAYER_CALC_VERT; } return ret; } void BKE_sculpt_toolsettings_data_ensure(struct Scene *scene) { BKE_paint_ensure(scene->toolsettings, (Paint **)&scene->toolsettings->sculpt); Sculpt *sd = scene->toolsettings->sculpt; if (!sd->detail_size) { sd->detail_size = 12; } if (!sd->detail_percent) { sd->detail_percent = 25; } if (sd->constant_detail == 0.0f) { sd->constant_detail = 3.0f; } /* Set sane default tiling offsets */ if (!sd->paint.tile_offset[0]) { sd->paint.tile_offset[0] = 1.0f; } if (!sd->paint.tile_offset[1]) { sd->paint.tile_offset[1] = 1.0f; } if (!sd->paint.tile_offset[2]) { sd->paint.tile_offset[2] = 1.0f; } } static bool check_sculpt_object_deformed(Object *object, const bool for_construction) { bool deformed = false; /* Active modifiers means extra deformation, which can't be handled correct * on birth of PBVH and sculpt "layer" levels, so use PBVH only for internal brush * stuff and show final evaluated mesh so user would see actual object shape. */ deformed |= object->sculpt->deform_modifiers_active; if (for_construction) { deformed |= object->sculpt->shapekey_active != NULL; } else { /* As in case with modifiers, we can't synchronize deformation made against * PBVH and non-locked keyblock, so also use PBVH only for brushes and * final DM to give final result to user. */ deformed |= object->sculpt->shapekey_active && (object->shapeflag & OB_SHAPE_LOCK) == 0; } return deformed; } static PBVH *build_pbvh_for_dynamic_topology(Object *ob) { PBVH *pbvh = BKE_pbvh_new(); BKE_pbvh_build_bmesh(pbvh, ob->sculpt->bm, ob->sculpt->bm_smooth_shading, ob->sculpt->bm_log, ob->sculpt->cd_vert_node_offset, ob->sculpt->cd_face_node_offset); pbvh_show_mask_set(pbvh, ob->sculpt->show_mask); return pbvh; } static PBVH *build_pbvh_from_regular_mesh(Object *ob, Mesh *me_eval_deform) { Mesh *me = BKE_object_get_original_mesh(ob); const int looptris_num = poly_to_tri_count(me->totpoly, me->totloop); PBVH *pbvh = BKE_pbvh_new(); MLoopTri *looptri = MEM_malloc_arrayN(looptris_num, sizeof(*looptri), __func__); BKE_mesh_recalc_looptri(me->mloop, me->mpoly, me->mvert, me->totloop, me->totpoly, looptri); BKE_pbvh_build_mesh(pbvh, me, me->mpoly, me->mloop, me->mvert, me->totvert, &me->vdata, &me->ldata, looptri, looptris_num); pbvh_show_mask_set(pbvh, ob->sculpt->show_mask); const bool is_deformed = check_sculpt_object_deformed(ob, true); if (is_deformed && me_eval_deform != NULL) { int totvert; float(*v_cos)[3] = BKE_mesh_vert_coords_alloc(me_eval_deform, &totvert); BKE_pbvh_vert_coords_apply(pbvh, v_cos, totvert); MEM_freeN(v_cos); } return pbvh; } static PBVH *build_pbvh_from_ccg(Object *ob, SubdivCCG *subdiv_ccg) { CCGKey key; BKE_subdiv_ccg_key_top_level(&key, subdiv_ccg); PBVH *pbvh = BKE_pbvh_new(); BKE_pbvh_build_grids(pbvh, subdiv_ccg->grids, subdiv_ccg->num_grids, &key, (void **)subdiv_ccg->grid_faces, subdiv_ccg->grid_flag_mats, subdiv_ccg->grid_hidden); pbvh_show_mask_set(pbvh, ob->sculpt->show_mask); return pbvh; } PBVH *BKE_sculpt_object_pbvh_ensure(Depsgraph *depsgraph, Object *ob) { if (ob == NULL || ob->sculpt == NULL) { return NULL; } PBVH *pbvh = ob->sculpt->pbvh; if (pbvh != NULL) { /* NOTE: It is possible that grids were re-allocated due to modifier * stack. Need to update those pointers. */ if (BKE_pbvh_type(pbvh) == PBVH_GRIDS) { Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); Mesh *mesh_eval = object_eval->data; SubdivCCG *subdiv_ccg = mesh_eval->runtime.subdiv_ccg; if (subdiv_ccg != NULL) { BKE_sculpt_bvh_update_from_ccg(pbvh, subdiv_ccg); } } return pbvh; } if (ob->sculpt->bm != NULL) { /* Sculpting on a BMesh (dynamic-topology) gets a special PBVH. */ pbvh = build_pbvh_for_dynamic_topology(ob); } else { Object *object_eval = DEG_get_evaluated_object(depsgraph, ob); Mesh *mesh_eval = object_eval->data; if (mesh_eval->runtime.subdiv_ccg != NULL) { pbvh = build_pbvh_from_ccg(ob, mesh_eval->runtime.subdiv_ccg); } else if (ob->type == OB_MESH) { Mesh *me_eval_deform = object_eval->runtime.mesh_deform_eval; pbvh = build_pbvh_from_regular_mesh(ob, me_eval_deform); } } ob->sculpt->pbvh = pbvh; return pbvh; } void BKE_sculpt_bvh_update_from_ccg(PBVH *pbvh, SubdivCCG *subdiv_ccg) { BKE_pbvh_grids_update(pbvh, subdiv_ccg->grids, (void **)subdiv_ccg->grid_faces, subdiv_ccg->grid_flag_mats, subdiv_ccg->grid_hidden); } /* Test if PBVH can be used directly for drawing, which is faster than * drawing the mesh and all updates that come with it. */ bool BKE_sculptsession_use_pbvh_draw(const Object *ob, const View3D *v3d) { SculptSession *ss = ob->sculpt; if (ss == NULL || ss->pbvh == NULL || ss->mode_type != OB_MODE_SCULPT) { return false; } if (BKE_pbvh_type(ss->pbvh) == PBVH_FACES) { /* Regular mesh only draws from PBVH without modifiers and shape keys. */ const bool full_shading = (v3d && (v3d->shading.type > OB_SOLID)); return !(ss->shapekey_active || ss->deform_modifiers_active || full_shading); } else { /* Multires and dyntopo always draw directly from the PBVH. */ return true; } }
760898.c
/* * Copyright 2012 Red Hat Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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. * * Authors: Ben Skeggs */ #include <engine/graph/nv40.h> #include "nv04.h" /****************************************************************************** * instmem subdev implementation *****************************************************************************/ static u32 nv40_instmem_rd32(struct nouveau_object *object, u64 addr) { struct nv04_instmem_priv *priv = (void *)object; return ioread32_native(priv->iomem + addr); } static void nv40_instmem_wr32(struct nouveau_object *object, u64 addr, u32 data) { struct nv04_instmem_priv *priv = (void *)object; iowrite32_native(data, priv->iomem + addr); } static int nv40_instmem_ctor(struct nouveau_object *parent, struct nouveau_object *engine, struct nouveau_oclass *oclass, void *data, u32 size, struct nouveau_object **pobject) { struct nouveau_device *device = nv_device(parent); struct pci_dev *pdev = device->pdev; struct nv04_instmem_priv *priv; int ret, bar, vs; ret = nouveau_instmem_create(parent, engine, oclass, &priv); *pobject = nv_object(priv); if (ret) return ret; /* map bar */ if (pci_resource_len(pdev, 2)) bar = 2; else bar = 3; priv->iomem = ioremap(pci_resource_start(pdev, bar), pci_resource_len(pdev, bar)); if (!priv->iomem) { nv_error(priv, "unable to map PRAMIN BAR\n"); return -EFAULT; } /* PRAMIN aperture maps over the end of vram, reserve enough space * to fit graphics contexts for every channel, the magics come * from engine/graph/nv40.c */ vs = hweight8((nv_rd32(priv, 0x001540) & 0x0000ff00) >> 8); if (device->chipset == 0x40) priv->base.reserved = 0x6aa0 * vs; else if (device->chipset < 0x43) priv->base.reserved = 0x4f00 * vs; else if (nv44_graph_class(priv)) priv->base.reserved = 0x4980 * vs; else priv->base.reserved = 0x4a40 * vs; priv->base.reserved += 16 * 1024; priv->base.reserved *= 32; /* per-channel */ priv->base.reserved += 512 * 1024; /* pci(e)gart table */ priv->base.reserved += 512 * 1024; /* object storage */ priv->base.reserved = round_up(priv->base.reserved, 4096); ret = nouveau_mm_init(&priv->heap, 0, priv->base.reserved, 1); if (ret) return ret; /* 0x00000-0x10000: reserve for probable vbios image */ ret = nouveau_gpuobj_new(nv_object(priv), NULL, 0x10000, 0, 0, &priv->vbios); if (ret) return ret; /* 0x10000-0x18000: reserve for RAMHT */ ret = nouveau_ramht_new(nv_object(priv), NULL, 0x08000, 0, &priv->ramht); if (ret) return ret; /* 0x18000-0x18200: reserve for RAMRO * 0x18200-0x20000: padding */ ret = nouveau_gpuobj_new(nv_object(priv), NULL, 0x08000, 0, 0, &priv->ramro); if (ret) return ret; /* 0x20000-0x21000: reserve for RAMFC * 0x21000-0x40000: padding and some unknown crap */ ret = nouveau_gpuobj_new(nv_object(priv), NULL, 0x20000, 0, NVOBJ_FLAG_ZERO_ALLOC, &priv->ramfc); if (ret) return ret; return 0; } struct nouveau_oclass * nv40_instmem_oclass = &(struct nouveau_instmem_impl) { .base.handle = NV_SUBDEV(INSTMEM, 0x40), .base.ofuncs = &(struct nouveau_ofuncs) { .ctor = nv40_instmem_ctor, .dtor = nv04_instmem_dtor, .init = _nouveau_instmem_init, .fini = _nouveau_instmem_fini, .rd32 = nv40_instmem_rd32, .wr32 = nv40_instmem_wr32, }, .instobj = &nv04_instobj_oclass.base, }.base;
19436.c
/* * This source file is part of the bstring string library. This code was * written by Paul Hsieh in 2002-2008, and is covered by the BSD open source * license and the GPL. Refer to the accompanying documentation for details * on usage and license. */ /* * bstrlib.c * * This file is the core module for implementing the bstring functions. */ #if defined (_MSC_VER) # define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <stddef.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "bstrlib.h" /* Optionally include a mechanism for debugging memory */ #if defined(MEMORY_DEBUG) || defined(BSTRLIB_MEMORY_DEBUG) #include "memdbg.h" #endif #ifndef bstr__alloc #define bstr__alloc(x) malloc (x) #endif #ifndef bstr__free #define bstr__free(p) free (p) #endif #ifndef bstr__realloc #define bstr__realloc(p,x) realloc ((p), (x)) #endif #ifndef bstr__memcpy #define bstr__memcpy(d,s,l) memcpy ((d), (s), (l)) #endif #ifndef bstr__memmove #define bstr__memmove(d,s,l) memmove ((d), (s), (l)) #endif #ifndef bstr__memset #define bstr__memset(d,c,l) memset ((d), (c), (l)) #endif #ifndef bstr__memcmp #define bstr__memcmp(d,c,l) memcmp ((d), (c), (l)) #endif #ifndef bstr__memchr #define bstr__memchr(s,c,l) memchr ((s), (c), (l)) #endif /* Just a length safe wrapper for memmove. */ #define bBlockCopy(D,S,L) { if ((L) > 0) bstr__memmove ((D),(S),(L)); } /* Compute the snapped size for a given requested size. By snapping to powers of 2 like this, repeated reallocations are avoided. */ static int snapUpSize (int i) { if (i < 8) { i = 8; } else { unsigned int j; j = (unsigned int) i; j |= (j >> 1); j |= (j >> 2); j |= (j >> 4); j |= (j >> 8); /* Ok, since int >= 16 bits */ #if (UINT_MAX != 0xffff) j |= (j >> 16); /* For 32 bit int systems */ #if (UINT_MAX > 0xffffffffUL) j |= (j >> 32); /* For 64 bit int systems */ #endif #endif /* Least power of two greater than i */ j++; if ((int) j >= i) i = (int) j; } return i; } /* int balloc (bstring b, int len) * * Increase the size of the memory backing the bstring b to at least len. */ int balloc (bstring b, int olen) { int len; if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen <= 0 || b->mlen < b->slen || olen <= 0) { return BSTR_ERR; } if (olen >= b->mlen) { unsigned char * x; if ((len = snapUpSize (olen)) <= b->mlen) return BSTR_OK; /* Assume probability of a non-moving realloc is 0.125 */ if (7 * b->mlen < 8 * b->slen) { /* If slen is close to mlen in size then use realloc to reduce the memory defragmentation */ reallocStrategy:; x = (unsigned char *) bstr__realloc (b->data, (size_t) len); if (x == NULL) { /* Since we failed, try allocating the tighest possible allocation */ if (NULL == (x = (unsigned char *) bstr__realloc (b->data, (size_t) (len = olen)))) { return BSTR_ERR; } } } else { /* If slen is not close to mlen then avoid the penalty of copying the extra bytes that are allocated, but not considered part of the string */ if (NULL == (x = (unsigned char *) bstr__alloc ((size_t) len))) { /* Perhaps there is no available memory for the two allocations to be in memory at once */ goto reallocStrategy; } else { if (b->slen) bstr__memcpy ((char *) x, (char *) b->data, (size_t) b->slen); bstr__free (b->data); } } b->data = x; b->mlen = len; b->data[b->slen] = (unsigned char) '\0'; } return BSTR_OK; } /* int ballocmin (bstring b, int len) * * Set the size of the memory backing the bstring b to len or b->slen+1, * whichever is larger. Note that repeated use of this function can degrade * performance. */ int ballocmin (bstring b, int len) { unsigned char * s; if (b == NULL || b->data == NULL || (b->slen+1) < 0 || b->mlen <= 0 || b->mlen < b->slen || len <= 0) { return BSTR_ERR; } if (len < b->slen + 1) len = b->slen + 1; if (len != b->mlen) { s = (unsigned char *) bstr__realloc (b->data, (size_t) len); if (NULL == s) return BSTR_ERR; s[b->slen] = (unsigned char) '\0'; b->data = s; b->mlen = len; } return BSTR_OK; } /* bstring bfromcstr (const char * str) * * Create a bstring which contains the contents of the '\0' terminated char * * buffer str. */ bstring bfromcstr (const char * str) { bstring b; int i; size_t j; if (str == NULL) return NULL; j = (strlen) (str); i = snapUpSize ((int) (j + (2 - (j != 0)))); if (i <= (int) j) return NULL; b = (bstring) bstr__alloc (sizeof (struct tagbstring)); if (NULL == b) return NULL; b->slen = (int) j; if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) { bstr__free (b); return NULL; } bstr__memcpy (b->data, str, j+1); return b; } /* bstring bfromcstralloc (int mlen, const char * str) * * Create a bstring which contains the contents of the '\0' terminated char * * buffer str. The memory buffer backing the string is at least len * characters in length. */ bstring bfromcstralloc (int mlen, const char * str) { bstring b; int i; size_t j; if (str == NULL) return NULL; j = (strlen) (str); i = snapUpSize ((int) (j + (2 - (j != 0)))); if (i <= (int) j) return NULL; b = (bstring) bstr__alloc (sizeof (struct tagbstring)); if (b == NULL) return NULL; b->slen = (int) j; if (i < mlen) i = mlen; if (NULL == (b->data = (unsigned char *) bstr__alloc (b->mlen = i))) { bstr__free (b); return NULL; } bstr__memcpy (b->data, str, j+1); return b; } /* bstring blk2bstr (const void * blk, int len) * * Create a bstring which contains the content of the block blk of length * len. */ bstring blk2bstr (const void * blk, int len) { bstring b; int i; if (blk == NULL || len < 0) return NULL; b = (bstring) bstr__alloc (sizeof (struct tagbstring)); if (b == NULL) return NULL; b->slen = len; i = len + (2 - (len != 0)); i = snapUpSize (i); b->mlen = i; b->data = (unsigned char *) bstr__alloc ((size_t) b->mlen); if (b->data == NULL) { bstr__free (b); return NULL; } if (len > 0) bstr__memcpy (b->data, blk, (size_t) len); b->data[len] = (unsigned char) '\0'; return b; } /* char * bstr2cstr (const_bstring s, char z) * * Create a '\0' terminated char * buffer which is equal to the contents of * the bstring s, except that any contained '\0' characters are converted * to the character in z. This returned value should be freed with a * bcstrfree () call, by the calling application. */ char * bstr2cstr (const_bstring b, char z) { int i, l; char * r; if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; l = b->slen; r = (char *) bstr__alloc ((size_t) (l + 1)); if (r == NULL) return r; for (i=0; i < l; i ++) { r[i] = (char) ((b->data[i] == '\0') ? z : (char) (b->data[i])); } r[l] = (unsigned char) '\0'; return r; } /* int bcstrfree (char * s) * * Frees a C-string generated by bstr2cstr (). This is normally unnecessary * since it just wraps a call to bstr__free (), however, if bstr__alloc () * and bstr__free () have been redefined as a macros within the bstrlib * module (via defining them in memdbg.h after defining * BSTRLIB_MEMORY_DEBUG) with some difference in behaviour from the std * library functions, then this allows a correct way of freeing the memory * that allows higher level code to be independent from these macro * redefinitions. */ int bcstrfree (char * s) { if (s) { bstr__free (s); return BSTR_OK; } return BSTR_ERR; } /* int bconcat (bstring b0, const_bstring b1) * * Concatenate the bstring b1 to the bstring b0. */ int bconcat (bstring b0, const_bstring b1) { int len, d; bstring aux = (bstring) b1; if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL) return BSTR_ERR; d = b0->slen; len = b1->slen; if ((d | (b0->mlen - d) | len | (d + len)) < 0) return BSTR_ERR; if (b0->mlen <= d + len + 1) { ptrdiff_t pd = b1->data - b0->data; if (0 <= pd && pd < b0->mlen) { if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR; } if (balloc (b0, d + len + 1) != BSTR_OK) { if (aux != b1) bdestroy (aux); return BSTR_ERR; } } bBlockCopy (&b0->data[d], &aux->data[0], (size_t) len); b0->data[d + len] = (unsigned char) '\0'; b0->slen = d + len; if (aux != b1) bdestroy (aux); return BSTR_OK; } /* int bconchar (bstring b, char c) * * Concatenate the single character c to the bstring b. */ int bconchar (bstring b, char c) { int d; if (b == NULL) return BSTR_ERR; d = b->slen; if ((d | (b->mlen - d)) < 0 || balloc (b, d + 2) != BSTR_OK) return BSTR_ERR; b->data[d] = (unsigned char) c; b->data[d + 1] = (unsigned char) '\0'; b->slen++; return BSTR_OK; } /* int bcatcstr (bstring b, const char * s) * * Concatenate a char * string to a bstring. */ int bcatcstr (bstring b, const char * s) { char * d; int i, l; if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || s == NULL) return BSTR_ERR; /* Optimistically concatenate directly */ l = b->mlen - b->slen; d = (char *) &b->data[b->slen]; for (i=0; i < l; i++) { if ((*d++ = *s++) == '\0') { b->slen += i; return BSTR_OK; } } b->slen += i; /* Need to explicitely resize and concatenate tail */ return bcatblk (b, (const void *) s, (int) strlen (s)); } /* int bcatblk (bstring b, const void * s, int len) * * Concatenate a fixed length buffer to a bstring. */ int bcatblk (bstring b, const void * s, int len) { int nl; if (b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || s == NULL || len < 0) return BSTR_ERR; if (0 > (nl = b->slen + len)) return BSTR_ERR; /* Overflow? */ if (b->mlen <= nl && 0 > balloc (b, nl + 1)) return BSTR_ERR; bBlockCopy (&b->data[b->slen], s, (size_t) len); b->slen = nl; b->data[nl] = (unsigned char) '\0'; return BSTR_OK; } /* bstring bstrcpy (const_bstring b) * * Create a copy of the bstring b. */ bstring bstrcpy (const_bstring b) { bstring b0; int i,j; /* Attempted to copy an invalid string? */ if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; b0 = (bstring) bstr__alloc (sizeof (struct tagbstring)); if (b0 == NULL) { /* Unable to allocate memory for string header */ return NULL; } i = b->slen; j = snapUpSize (i + 1); b0->data = (unsigned char *) bstr__alloc (j); if (b0->data == NULL) { j = i + 1; b0->data = (unsigned char *) bstr__alloc (j); if (b0->data == NULL) { /* Unable to allocate memory for string data */ bstr__free (b0); return NULL; } } b0->mlen = j; b0->slen = i; if (i) bstr__memcpy ((char *) b0->data, (char *) b->data, i); b0->data[b0->slen] = (unsigned char) '\0'; return b0; } /* int bassign (bstring a, const_bstring b) * * Overwrite the string a with the contents of string b. */ int bassign (bstring a, const_bstring b) { if (b == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR; if (b->slen != 0) { if (balloc (a, b->slen) != BSTR_OK) return BSTR_ERR; bstr__memmove (a->data, b->data, b->slen); } else { if (a == NULL || a->data == NULL || a->mlen < a->slen || a->slen < 0 || a->mlen == 0) return BSTR_ERR; } a->data[b->slen] = (unsigned char) '\0'; a->slen = b->slen; return BSTR_OK; } /* int bassignmidstr (bstring a, const_bstring b, int left, int len) * * Overwrite the string a with the middle of contents of string b * starting from position left and running for a length len. left and * len are clamped to the ends of b as with the function bmidstr. */ int bassignmidstr (bstring a, const_bstring b, int left, int len) { if (b == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR; if (left < 0) { len += left; left = 0; } if (len > b->slen - left) len = b->slen - left; if (a == NULL || a->data == NULL || a->mlen < a->slen || a->slen < 0 || a->mlen == 0) return BSTR_ERR; if (len > 0) { if (balloc (a, len) != BSTR_OK) return BSTR_ERR; bstr__memmove (a->data, b->data + left, len); a->slen = len; } else { a->slen = 0; } a->data[a->slen] = (unsigned char) '\0'; return BSTR_OK; } /* int bassigncstr (bstring a, const char * str) * * Overwrite the string a with the contents of char * string str. Note that * the bstring a must be a well defined and writable bstring. If an error * occurs BSTR_ERR is returned however a may be partially overwritten. */ int bassigncstr (bstring a, const char * str) { int i; size_t len; if (a == NULL || a->data == NULL || a->mlen < a->slen || a->slen < 0 || a->mlen == 0 || NULL == str) return BSTR_ERR; for (i=0; i < a->mlen; i++) { if ('\0' == (a->data[i] = str[i])) { a->slen = i; return BSTR_OK; } } a->slen = i; len = strlen (str + i); if (len > INT_MAX || i + len + 1 > INT_MAX || 0 > balloc (a, (int) (i + len + 1))) return BSTR_ERR; bBlockCopy (a->data + i, str + i, (size_t) len + 1); a->slen += (int) len; return BSTR_OK; } /* int bassignblk (bstring a, const void * s, int len) * * Overwrite the string a with the contents of the block (s, len). Note that * the bstring a must be a well defined and writable bstring. If an error * occurs BSTR_ERR is returned and a is not overwritten. */ int bassignblk (bstring a, const void * s, int len) { if (a == NULL || a->data == NULL || a->mlen < a->slen || a->slen < 0 || a->mlen == 0 || NULL == s || len + 1 < 1) return BSTR_ERR; if (len + 1 > a->mlen && 0 > balloc (a, len + 1)) return BSTR_ERR; bBlockCopy (a->data, s, (size_t) len); a->data[len] = (unsigned char) '\0'; a->slen = len; return BSTR_OK; } /* int btrunc (bstring b, int n) * * Truncate the bstring to at most n characters. */ int btrunc (bstring b, int n) { if (n < 0 || b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; if (b->slen > n) { b->slen = n; b->data[n] = (unsigned char) '\0'; } return BSTR_OK; } #define upcase(c) (toupper ((unsigned char) c)) #define downcase(c) (tolower ((unsigned char) c)) #define wspace(c) (isspace ((unsigned char) c)) /* int btoupper (bstring b) * * Convert contents of bstring to upper case. */ int btoupper (bstring b) { int i, len; if (b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; for (i=0, len = b->slen; i < len; i++) { b->data[i] = (unsigned char) upcase (b->data[i]); } return BSTR_OK; } /* int btolower (bstring b) * * Convert contents of bstring to lower case. */ int btolower (bstring b) { int i, len; if (b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; for (i=0, len = b->slen; i < len; i++) { b->data[i] = (unsigned char) downcase (b->data[i]); } return BSTR_OK; } /* int bstricmp (const_bstring b0, const_bstring b1) * * Compare two strings without differentiating between case. The return * value is the difference of the values of the characters where the two * strings first differ after lower case transformation, otherwise 0 is * returned indicating that the strings are equal. If the lengths are * different, then a difference from 0 is given, but if the first extra * character is '\0', then it is taken to be the value UCHAR_MAX+1. */ int bstricmp (const_bstring b0, const_bstring b1) { int i, v, n; if (bdata (b0) == NULL || b0->slen < 0 || bdata (b1) == NULL || b1->slen < 0) return SHRT_MIN; if ((n = b0->slen) > b1->slen) n = b1->slen; else if (b0->slen == b1->slen && b0->data == b1->data) return BSTR_OK; for (i = 0; i < n; i ++) { v = (char) downcase (b0->data[i]) - (char) downcase (b1->data[i]); if (0 != v) return v; } if (b0->slen > n) { v = (char) downcase (b0->data[n]); if (v) return v; return UCHAR_MAX + 1; } if (b1->slen > n) { v = - (char) downcase (b1->data[n]); if (v) return v; return - (int) (UCHAR_MAX + 1); } return BSTR_OK; } /* int bstrnicmp (const_bstring b0, const_bstring b1, int n) * * Compare two strings without differentiating between case for at most n * characters. If the position where the two strings first differ is * before the nth position, the return value is the difference of the values * of the characters, otherwise 0 is returned. If the lengths are different * and less than n characters, then a difference from 0 is given, but if the * first extra character is '\0', then it is taken to be the value * UCHAR_MAX+1. */ int bstrnicmp (const_bstring b0, const_bstring b1, int n) { int i, v, m; if (bdata (b0) == NULL || b0->slen < 0 || bdata (b1) == NULL || b1->slen < 0 || n < 0) return SHRT_MIN; m = n; if (m > b0->slen) m = b0->slen; if (m > b1->slen) m = b1->slen; if (b0->data != b1->data) { for (i = 0; i < m; i ++) { v = (char) downcase (b0->data[i]); v -= (char) downcase (b1->data[i]); if (v != 0) return b0->data[i] - b1->data[i]; } } if (n == m || b0->slen == b1->slen) return BSTR_OK; if (b0->slen > m) { v = (char) downcase (b0->data[m]); if (v) return v; return UCHAR_MAX + 1; } v = - (char) downcase (b1->data[m]); if (v) return v; return - (int) (UCHAR_MAX + 1); } /* int biseqcaseless (const_bstring b0, const_bstring b1) * * Compare two strings for equality without differentiating between case. * If the strings differ other than in case, 0 is returned, if the strings * are the same, 1 is returned, if there is an error, -1 is returned. If * the length of the strings are different, this function is O(1). '\0' * termination characters are not treated in any special way. */ int biseqcaseless (const_bstring b0, const_bstring b1) { int i, n; if (bdata (b0) == NULL || b0->slen < 0 || bdata (b1) == NULL || b1->slen < 0) return BSTR_ERR; if (b0->slen != b1->slen) return BSTR_OK; if (b0->data == b1->data || b0->slen == 0) return 1; for (i=0, n=b0->slen; i < n; i++) { if (b0->data[i] != b1->data[i]) { unsigned char c = (unsigned char) downcase (b0->data[i]); if (c != (unsigned char) downcase (b1->data[i])) return 0; } } return 1; } /* int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len) * * Compare beginning of string b0 with a block of memory of length len * without differentiating between case for equality. If the beginning of b0 * differs from the memory block other than in case (or if b0 is too short), * 0 is returned, if the strings are the same, 1 is returned, if there is an * error, -1 is returned. '\0' characters are not treated in any special * way. */ int bisstemeqcaselessblk (const_bstring b0, const void * blk, int len) { int i; if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0) return BSTR_ERR; if (b0->slen < len) return BSTR_OK; if (b0->data == (const unsigned char *) blk || len == 0) return 1; for (i = 0; i < len; i ++) { if (b0->data[i] != ((const unsigned char *) blk)[i]) { if (downcase (b0->data[i]) != downcase (((const unsigned char *) blk)[i])) return 0; } } return 1; } /* * int bltrimws (bstring b) * * Delete whitespace contiguous from the left end of the string. */ int bltrimws (bstring b) { int i, len; if (b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; for (len = b->slen, i = 0; i < len; i++) { if (!wspace (b->data[i])) { return bdelete (b, 0, i); } } b->data[0] = (unsigned char) '\0'; b->slen = 0; return BSTR_OK; } /* * int brtrimws (bstring b) * * Delete whitespace contiguous from the right end of the string. */ int brtrimws (bstring b) { int i; if (b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; for (i = b->slen - 1; i >= 0; i--) { if (!wspace (b->data[i])) { if (b->mlen > i) b->data[i+1] = (unsigned char) '\0'; b->slen = i + 1; return BSTR_OK; } } b->data[0] = (unsigned char) '\0'; b->slen = 0; return BSTR_OK; } /* * int btrimws (bstring b) * * Delete whitespace contiguous from both ends of the string. */ int btrimws (bstring b) { int i, j; if (b == NULL || b->data == NULL || b->mlen < b->slen || b->slen < 0 || b->mlen <= 0) return BSTR_ERR; for (i = b->slen - 1; i >= 0; i--) { if (!wspace (b->data[i])) { if (b->mlen > i) b->data[i+1] = (unsigned char) '\0'; b->slen = i + 1; for (j = 0; wspace (b->data[j]); j++) {} return bdelete (b, 0, j); } } b->data[0] = (unsigned char) '\0'; b->slen = 0; return BSTR_OK; } /* int biseq (const_bstring b0, const_bstring b1) * * Compare the string b0 and b1. If the strings differ, 0 is returned, if * the strings are the same, 1 is returned, if there is an error, -1 is * returned. If the length of the strings are different, this function is * O(1). '\0' termination characters are not treated in any special way. */ int biseq (const_bstring b0, const_bstring b1) { if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || b0->slen < 0 || b1->slen < 0) return BSTR_ERR; if (b0->slen != b1->slen) return BSTR_OK; if (b0->data == b1->data || b0->slen == 0) return 1; return !bstr__memcmp (b0->data, b1->data, b0->slen); } /* int bisstemeqblk (const_bstring b0, const void * blk, int len) * * Compare beginning of string b0 with a block of memory of length len for * equality. If the beginning of b0 differs from the memory block (or if b0 * is too short), 0 is returned, if the strings are the same, 1 is returned, * if there is an error, -1 is returned. '\0' characters are not treated in * any special way. */ int bisstemeqblk (const_bstring b0, const void * blk, int len) { int i; if (bdata (b0) == NULL || b0->slen < 0 || NULL == blk || len < 0) return BSTR_ERR; if (b0->slen < len) return BSTR_OK; if (b0->data == (const unsigned char *) blk || len == 0) return 1; for (i = 0; i < len; i ++) { if (b0->data[i] != ((const unsigned char *) blk)[i]) return BSTR_OK; } return 1; } /* int biseqcstr (const_bstring b, const char *s) * * Compare the bstring b and char * string s. The C string s must be '\0' * terminated at exactly the length of the bstring b, and the contents * between the two must be identical with the bstring b with no '\0' * characters for the two contents to be considered equal. This is * equivalent to the condition that their current contents will be always be * equal when comparing them in the same format after converting one or the * other. If the strings are equal 1 is returned, if they are unequal 0 is * returned and if there is a detectable error BSTR_ERR is returned. */ int biseqcstr (const_bstring b, const char * s) { int i; if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR; for (i=0; i < b->slen; i++) { if (s[i] == '\0' || b->data[i] != (unsigned char) s[i]) return BSTR_OK; } return s[i] == '\0'; } /* int biseqcstrcaseless (const_bstring b, const char *s) * * Compare the bstring b and char * string s. The C string s must be '\0' * terminated at exactly the length of the bstring b, and the contents * between the two must be identical except for case with the bstring b with * no '\0' characters for the two contents to be considered equal. This is * equivalent to the condition that their current contents will be always be * equal ignoring case when comparing them in the same format after * converting one or the other. If the strings are equal, except for case, * 1 is returned, if they are unequal regardless of case 0 is returned and * if there is a detectable error BSTR_ERR is returned. */ int biseqcstrcaseless (const_bstring b, const char * s) { int i; if (b == NULL || s == NULL || b->data == NULL || b->slen < 0) return BSTR_ERR; for (i=0; i < b->slen; i++) { if (s[i] == '\0' || (b->data[i] != (unsigned char) s[i] && downcase (b->data[i]) != (unsigned char) downcase (s[i]))) return BSTR_OK; } return s[i] == '\0'; } /* int bstrcmp (const_bstring b0, const_bstring b1) * * Compare the string b0 and b1. If there is an error, SHRT_MIN is returned, * otherwise a value less than or greater than zero, indicating that the * string pointed to by b0 is lexicographically less than or greater than * the string pointed to by b1 is returned. If the the string lengths are * unequal but the characters up until the length of the shorter are equal * then a value less than, or greater than zero, indicating that the string * pointed to by b0 is shorter or longer than the string pointed to by b1 is * returned. 0 is returned if and only if the two strings are the same. If * the length of the strings are different, this function is O(n). Like its * standard C library counter part strcmp, the comparison does not proceed * past any '\0' termination characters encountered. */ int bstrcmp (const_bstring b0, const_bstring b1) { int i, v, n; if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || b0->slen < 0 || b1->slen < 0) return SHRT_MIN; n = b0->slen; if (n > b1->slen) n = b1->slen; if (b0->slen == b1->slen && (b0->data == b1->data || b0->slen == 0)) return BSTR_OK; for (i = 0; i < n; i ++) { v = ((char) b0->data[i]) - ((char) b1->data[i]); if (v != 0) return v; if (b0->data[i] == (unsigned char) '\0') return BSTR_OK; } if (b0->slen > n) return 1; if (b1->slen > n) return -1; return BSTR_OK; } /* int bstrncmp (const_bstring b0, const_bstring b1, int n) * * Compare the string b0 and b1 for at most n characters. If there is an * error, SHRT_MIN is returned, otherwise a value is returned as if b0 and * b1 were first truncated to at most n characters then bstrcmp was called * with these new strings are paremeters. If the length of the strings are * different, this function is O(n). Like its standard C library counter * part strcmp, the comparison does not proceed past any '\0' termination * characters encountered. */ int bstrncmp (const_bstring b0, const_bstring b1, int n) { int i, v, m; if (b0 == NULL || b1 == NULL || b0->data == NULL || b1->data == NULL || b0->slen < 0 || b1->slen < 0) return SHRT_MIN; m = n; if (m > b0->slen) m = b0->slen; if (m > b1->slen) m = b1->slen; if (b0->data != b1->data) { for (i = 0; i < m; i ++) { v = ((char) b0->data[i]) - ((char) b1->data[i]); if (v != 0) return v; if (b0->data[i] == (unsigned char) '\0') return BSTR_OK; } } if (n == m || b0->slen == b1->slen) return BSTR_OK; if (b0->slen > m) return 1; return -1; } /* bstring bmidstr (const_bstring b, int left, int len) * * Create a bstring which is the substring of b starting from position left * and running for a length len (clamped by the end of the bstring b.) If * b is detectably invalid, then NULL is returned. The section described * by (left, len) is clamped to the boundaries of b. */ bstring bmidstr (const_bstring b, int left, int len) { if (b == NULL || b->slen < 0 || b->data == NULL) return NULL; if (left < 0) { len += left; left = 0; } if (len > b->slen - left) len = b->slen - left; if (len <= 0) return bfromcstr (""); return blk2bstr (b->data + left, len); } /* int bdelete (bstring b, int pos, int len) * * Removes characters from pos to pos+len-1 inclusive and shifts the tail of * the bstring starting from pos+len to pos. len must be positive for this * call to have any effect. The section of the string described by (pos, * len) is clamped to boundaries of the bstring b. */ int bdelete (bstring b, int pos, int len) { /* Clamp to left side of bstring */ if (pos < 0) { len += pos; pos = 0; } if (len < 0 || b == NULL || b->data == NULL || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0) return BSTR_ERR; if (len > 0 && pos < b->slen) { if (pos + len >= b->slen) { b->slen = pos; } else { bBlockCopy ((char *) (b->data + pos), (char *) (b->data + pos + len), b->slen - (pos+len)); b->slen -= len; } b->data[b->slen] = (unsigned char) '\0'; } return BSTR_OK; } /* int bdestroy (bstring b) * * Free up the bstring. Note that if b is detectably invalid or not writable * then no action is performed and BSTR_ERR is returned. Like a freed memory * allocation, dereferences, writes or any other action on b after it has * been bdestroyed is undefined. */ int bdestroy (bstring b) { if (b == NULL || b->slen < 0 || b->mlen <= 0 || b->mlen < b->slen || b->data == NULL) return BSTR_ERR; bstr__free (b->data); /* In case there is any stale usage, there is one more chance to notice this error. */ b->slen = -1; b->mlen = -__LINE__; b->data = NULL; bstr__free (b); return BSTR_OK; } /* int binstr (const_bstring b1, int pos, const_bstring b2) * * Search for the bstring b2 in b1 starting from position pos, and searching * forward. If it is found then return with the first position where it is * found, otherwise return BSTR_ERR. Note that this is just a brute force * string searcher that does not attempt clever things like the Boyer-Moore * search algorithm. Because of this there are many degenerate cases where * this can take much longer than it needs to. */ int binstr (const_bstring b1, int pos, const_bstring b2) { int j, ii, ll, lf; unsigned char * d0; unsigned char c0; register unsigned char * d1; register unsigned char c1; register int i; if (b1 == NULL || b1->data == NULL || b1->slen < 0 || b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR; if (b1->slen < pos || pos < 0) return BSTR_ERR; if (b2->slen == 0) return pos; /* No space to find such a string? */ if ((lf = b1->slen - b2->slen + 1) <= pos) return BSTR_ERR; /* An obvious alias case */ if (b1->data == b2->data && pos == 0) return 0; i = pos; d0 = b2->data; d1 = b1->data; ll = b2->slen; /* Peel off the b2->slen == 1 case */ c0 = d0[0]; if (1 == ll) { for (;i < lf; i++) if (c0 == d1[i]) return i; return BSTR_ERR; } c1 = c0; j = 0; lf = b1->slen - 1; ii = -1; if (i < lf) do { /* Unrolled current character test */ if (c1 != d1[i]) { if (c1 != d1[1+i]) { i += 2; continue; } i++; } /* Take note if this is the start of a potential match */ if (0 == j) ii = i; /* Shift the test character down by one */ j++; i++; /* If this isn't past the last character continue */ if (j < ll) { c1 = d0[j]; continue; } N0:; /* If no characters mismatched, then we matched */ if (i == ii+j) return ii; /* Shift back to the beginning */ i -= j; j = 0; c1 = c0; } while (i < lf); /* Deal with last case if unrolling caused a misalignment */ if (i == lf && ll == j+1 && c1 == d1[i]) goto N0; return BSTR_ERR; } /* int binstrr (const_bstring b1, int pos, const_bstring b2) * * Search for the bstring b2 in b1 starting from position pos, and searching * backward. If it is found then return with the first position where it is * found, otherwise return BSTR_ERR. Note that this is just a brute force * string searcher that does not attempt clever things like the Boyer-Moore * search algorithm. Because of this there are many degenerate cases where * this can take much longer than it needs to. */ int binstrr (const_bstring b1, int pos, const_bstring b2) { int j, i, l; unsigned char * d0, * d1; if (b1 == NULL || b1->data == NULL || b1->slen < 0 || b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; if (b1->slen == pos && b2->slen == 0) return pos; if (b1->slen < pos || pos < 0) return BSTR_ERR; if (b2->slen == 0) return pos; /* Obvious alias case */ if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) return 0; i = pos; if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR; /* If no space to find such a string then snap back */ if (l + 1 <= i) i = l; j = 0; d0 = b2->data; d1 = b1->data; l = b2->slen; for (;;) { if (d0[j] == d1[i + j]) { j ++; if (j >= l) return i; } else { i --; if (i < 0) break; j=0; } } return BSTR_ERR; } /* int binstrcaseless (const_bstring b1, int pos, const_bstring b2) * * Search for the bstring b2 in b1 starting from position pos, and searching * forward but without regard to case. If it is found then return with the * first position where it is found, otherwise return BSTR_ERR. Note that * this is just a brute force string searcher that does not attempt clever * things like the Boyer-Moore search algorithm. Because of this there are * many degenerate cases where this can take much longer than it needs to. */ int binstrcaseless (const_bstring b1, int pos, const_bstring b2) { int j, i, l, ll; unsigned char * d0, * d1; if (b1 == NULL || b1->data == NULL || b1->slen < 0 || b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; if (b1->slen == pos) return (b2->slen == 0)?pos:BSTR_ERR; if (b1->slen < pos || pos < 0) return BSTR_ERR; if (b2->slen == 0) return pos; l = b1->slen - b2->slen + 1; /* No space to find such a string? */ if (l <= pos) return BSTR_ERR; /* An obvious alias case */ if (b1->data == b2->data && pos == 0) return BSTR_OK; i = pos; j = 0; d0 = b2->data; d1 = b1->data; ll = b2->slen; for (;;) { if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) { j ++; if (j >= ll) return i; } else { i ++; if (i >= l) break; j=0; } } return BSTR_ERR; } /* int binstrrcaseless (const_bstring b1, int pos, const_bstring b2) * * Search for the bstring b2 in b1 starting from position pos, and searching * backward but without regard to case. If it is found then return with the * first position where it is found, otherwise return BSTR_ERR. Note that * this is just a brute force string searcher that does not attempt clever * things like the Boyer-Moore search algorithm. Because of this there are * many degenerate cases where this can take much longer than it needs to. */ int binstrrcaseless (const_bstring b1, int pos, const_bstring b2) { int j, i, l; unsigned char * d0, * d1; if (b1 == NULL || b1->data == NULL || b1->slen < 0 || b2 == NULL || b2->data == NULL || b2->slen < 0) return BSTR_ERR; if (b1->slen == pos && b2->slen == 0) return pos; if (b1->slen < pos || pos < 0) return BSTR_ERR; if (b2->slen == 0) return pos; /* Obvious alias case */ if (b1->data == b2->data && pos == 0 && b2->slen <= b1->slen) return BSTR_OK; i = pos; if ((l = b1->slen - b2->slen) < 0) return BSTR_ERR; /* If no space to find such a string then snap back */ if (l + 1 <= i) i = l; j = 0; d0 = b2->data; d1 = b1->data; l = b2->slen; for (;;) { if (d0[j] == d1[i + j] || downcase (d0[j]) == downcase (d1[i + j])) { j ++; if (j >= l) return i; } else { i --; if (i < 0) break; j=0; } } return BSTR_ERR; } /* int bstrchrp (const_bstring b, int c, int pos) * * Search for the character c in b forwards from the position pos * (inclusive). */ int bstrchrp (const_bstring b, int c, int pos) { unsigned char * p; if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) return BSTR_ERR; p = (unsigned char *) bstr__memchr ((b->data + pos), (unsigned char) c, (b->slen - pos)); if (p) return (int) (p - b->data); return BSTR_ERR; } /* int bstrrchrp (const_bstring b, int c, int pos) * * Search for the character c in b backwards from the position pos in string * (inclusive). */ int bstrrchrp (const_bstring b, int c, int pos) { int i; if (b == NULL || b->data == NULL || b->slen <= pos || pos < 0) return BSTR_ERR; for (i=pos; i >= 0; i--) { if (b->data[i] == (unsigned char) c) return i; } return BSTR_ERR; } #if !defined (BSTRLIB_AGGRESSIVE_MEMORY_FOR_SPEED_TRADEOFF) #define LONG_LOG_BITS_QTY (3) #define LONG_BITS_QTY (1 << LONG_LOG_BITS_QTY) #define LONG_TYPE unsigned char #define CFCLEN ((1 << CHAR_BIT) / LONG_BITS_QTY) struct charField { LONG_TYPE content[CFCLEN]; }; #define testInCharField(cf,c) ((cf)->content[(c) >> LONG_LOG_BITS_QTY] & (((long)1) << ((c) & (LONG_BITS_QTY-1)))) #define setInCharField(cf,idx) { \ unsigned int c = (unsigned int) (idx); \ (cf)->content[c >> LONG_LOG_BITS_QTY] |= (LONG_TYPE) (1ul << (c & (LONG_BITS_QTY-1))); \ } #else #define CFCLEN (1 << CHAR_BIT) struct charField { unsigned char content[CFCLEN]; }; #define testInCharField(cf,c) ((cf)->content[(unsigned char) (c)]) #define setInCharField(cf,idx) (cf)->content[(unsigned int) (idx)] = ~0 #endif /* Convert a bstring to charField */ static int buildCharField (struct charField * cf, const_bstring b) { int i; if (b == NULL || b->data == NULL || b->slen <= 0) return BSTR_ERR; memset ((void *) cf->content, 0, sizeof (struct charField)); for (i=0; i < b->slen; i++) { setInCharField (cf, b->data[i]); } return BSTR_OK; } static void invertCharField (struct charField * cf) { int i; for (i=0; i < CFCLEN; i++) cf->content[i] = ~cf->content[i]; } /* Inner engine for binchr */ static int binchrCF (const unsigned char * data, int len, int pos, const struct charField * cf) { int i; for (i=pos; i < len; i++) { unsigned char c = (unsigned char) data[i]; if (testInCharField (cf, c)) return i; } return BSTR_ERR; } /* int binchr (const_bstring b0, int pos, const_bstring b1); * * Search for the first position in b0 starting from pos or after, in which * one of the characters in b1 is found and return it. If such a position * does not exist in b0, then BSTR_ERR is returned. */ int binchr (const_bstring b0, int pos, const_bstring b1) { struct charField chrs; if (pos < 0 || b0 == NULL || b0->data == NULL || b0->slen <= pos) return BSTR_ERR; if (1 == b1->slen) return bstrchrp (b0, b1->data[0], pos); if (0 > buildCharField (&chrs, b1)) return BSTR_ERR; return binchrCF (b0->data, b0->slen, pos, &chrs); } /* Inner engine for binchrr */ static int binchrrCF (const unsigned char * data, int pos, const struct charField * cf) { int i; for (i=pos; i >= 0; i--) { unsigned int c = (unsigned int) data[i]; if (testInCharField (cf, c)) return i; } return BSTR_ERR; } /* int binchrr (const_bstring b0, int pos, const_bstring b1); * * Search for the last position in b0 no greater than pos, in which one of * the characters in b1 is found and return it. If such a position does not * exist in b0, then BSTR_ERR is returned. */ int binchrr (const_bstring b0, int pos, const_bstring b1) { struct charField chrs; if (pos < 0 || b0 == NULL || b0->data == NULL || b1 == NULL || b0->slen < pos) return BSTR_ERR; if (pos == b0->slen) pos--; if (1 == b1->slen) return bstrrchrp (b0, b1->data[0], pos); if (0 > buildCharField (&chrs, b1)) return BSTR_ERR; return binchrrCF (b0->data, pos, &chrs); } /* int bninchr (const_bstring b0, int pos, const_bstring b1); * * Search for the first position in b0 starting from pos or after, in which * none of the characters in b1 is found and return it. If such a position * does not exist in b0, then BSTR_ERR is returned. */ int bninchr (const_bstring b0, int pos, const_bstring b1) { struct charField chrs; if (pos < 0 || b0 == NULL || b0->data == NULL || b0->slen <= pos) return BSTR_ERR; if (buildCharField (&chrs, b1) < 0) return BSTR_ERR; invertCharField (&chrs); return binchrCF (b0->data, b0->slen, pos, &chrs); } /* int bninchrr (const_bstring b0, int pos, const_bstring b1); * * Search for the last position in b0 no greater than pos, in which none of * the characters in b1 is found and return it. If such a position does not * exist in b0, then BSTR_ERR is returned. */ int bninchrr (const_bstring b0, int pos, const_bstring b1) { struct charField chrs; if (pos < 0 || b0 == NULL || b0->data == NULL || b0->slen < pos) return BSTR_ERR; if (pos == b0->slen) pos--; if (buildCharField (&chrs, b1) < 0) return BSTR_ERR; invertCharField (&chrs); return binchrrCF (b0->data, pos, &chrs); } /* int bsetstr (bstring b0, int pos, bstring b1, unsigned char fill) * * Overwrite the string b0 starting at position pos with the string b1. If * the position pos is past the end of b0, then the character "fill" is * appended as necessary to make up the gap between the end of b0 and pos. * If b1 is NULL, it behaves as if it were a 0-length string. */ int bsetstr (bstring b0, int pos, const_bstring b1, unsigned char fill) { int d, newlen; ptrdiff_t pd; bstring aux = (bstring) b1; if (pos < 0 || b0 == NULL || b0->slen < 0 || NULL == b0->data || b0->mlen < b0->slen || b0->mlen <= 0) return BSTR_ERR; if (b1 != NULL && (b1->slen < 0 || b1->data == NULL)) return BSTR_ERR; d = pos; /* Aliasing case */ if (NULL != aux) { if ((pd = (ptrdiff_t) (b1->data - b0->data)) >= 0 && pd < (ptrdiff_t) b0->mlen) { if (NULL == (aux = bstrcpy (b1))) return BSTR_ERR; } d += aux->slen; } /* Increase memory size if necessary */ if (balloc (b0, d + 1) != BSTR_OK) { if (aux != b1) bdestroy (aux); return BSTR_ERR; } newlen = b0->slen; /* Fill in "fill" character as necessary */ if (pos > newlen) { bstr__memset (b0->data + b0->slen, (int) fill, (size_t) (pos - b0->slen)); newlen = pos; } /* Copy b1 to position pos in b0. */ if (aux != NULL) { bBlockCopy ((char *) (b0->data + pos), (char *) aux->data, aux->slen); if (aux != b1) bdestroy (aux); } /* Indicate the potentially increased size of b0 */ if (d > newlen) newlen = d; b0->slen = newlen; b0->data[newlen] = (unsigned char) '\0'; return BSTR_OK; } /* int binsert (bstring b1, int pos, bstring b2, unsigned char fill) * * Inserts the string b2 into b1 at position pos. If the position pos is * past the end of b1, then the character "fill" is appended as necessary to * make up the gap between the end of b1 and pos. Unlike bsetstr, binsert * does not allow b2 to be NULL. */ int binsert (bstring b1, int pos, const_bstring b2, unsigned char fill) { int d, l; ptrdiff_t pd; bstring aux = (bstring) b2; if (pos < 0 || b1 == NULL || b2 == NULL || b1->slen < 0 || b2->slen < 0 || b1->mlen < b1->slen || b1->mlen <= 0) return BSTR_ERR; /* Aliasing case */ if ((pd = (ptrdiff_t) (b2->data - b1->data)) >= 0 && pd < (ptrdiff_t) b1->mlen) { if (NULL == (aux = bstrcpy (b2))) return BSTR_ERR; } /* Compute the two possible end pointers */ d = b1->slen + aux->slen; l = pos + aux->slen; if ((d|l) < 0) return BSTR_ERR; if (l > d) { /* Inserting past the end of the string */ if (balloc (b1, l + 1) != BSTR_OK) { if (aux != b2) bdestroy (aux); return BSTR_ERR; } bstr__memset (b1->data + b1->slen, (int) fill, (size_t) (pos - b1->slen)); b1->slen = l; } else { /* Inserting in the middle of the string */ if (balloc (b1, d + 1) != BSTR_OK) { if (aux != b2) bdestroy (aux); return BSTR_ERR; } bBlockCopy (b1->data + l, b1->data + pos, d - l); b1->slen = d; } bBlockCopy (b1->data + pos, aux->data, aux->slen); b1->data[b1->slen] = (unsigned char) '\0'; if (aux != b2) bdestroy (aux); return BSTR_OK; } /* int breplace (bstring b1, int pos, int len, bstring b2, * unsigned char fill) * * Replace a section of a string from pos for a length len with the string b2. * fill is used is pos > b1->slen. */ int breplace (bstring b1, int pos, int len, const_bstring b2, unsigned char fill) { int pl, ret; ptrdiff_t pd; bstring aux = (bstring) b2; if (pos < 0 || len < 0 || (pl = pos + len) < 0 || b1 == NULL || b2 == NULL || b1->data == NULL || b2->data == NULL || b1->slen < 0 || b2->slen < 0 || b1->mlen < b1->slen || b1->mlen <= 0) return BSTR_ERR; /* Straddles the end? */ if (pl >= b1->slen) { if ((ret = bsetstr (b1, pos, b2, fill)) < 0) return ret; if (pos + b2->slen < b1->slen) { b1->slen = pos + b2->slen; b1->data[b1->slen] = (unsigned char) '\0'; } return ret; } /* Aliasing case */ if ((pd = (ptrdiff_t) (b2->data - b1->data)) >= 0 && pd < (ptrdiff_t) b1->slen) { if (NULL == (aux = bstrcpy (b2))) return BSTR_ERR; } if (aux->slen > len) { if (balloc (b1, b1->slen + aux->slen - len) != BSTR_OK) { if (aux != b2) bdestroy (aux); return BSTR_ERR; } } if (aux->slen != len) bstr__memmove (b1->data + pos + aux->slen, b1->data + pos + len, b1->slen - (pos + len)); bstr__memcpy (b1->data + pos, aux->data, aux->slen); b1->slen += aux->slen - len; b1->data[b1->slen] = (unsigned char) '\0'; if (aux != b2) bdestroy (aux); return BSTR_OK; } /* * findreplaceengine is used to implement bfindreplace and * bfindreplacecaseless. It works by breaking the three cases of * expansion, reduction and replacement, and solving each of these * in the most efficient way possible. */ typedef int (*instr_fnptr) (const_bstring s1, int pos, const_bstring s2); #define INITIAL_STATIC_FIND_INDEX_COUNT 32 static int findreplaceengine (bstring b, const_bstring find, const_bstring repl, int pos, instr_fnptr instr) { int i, ret, slen, mlen, delta, acc; int * d; int static_d[INITIAL_STATIC_FIND_INDEX_COUNT+1]; /* This +1 is unnecessary, but it shuts up LINT. */ ptrdiff_t pd; bstring auxf = (bstring) find; bstring auxr = (bstring) repl; if (b == NULL || b->data == NULL || find == NULL || find->data == NULL || repl == NULL || repl->data == NULL || pos < 0 || find->slen <= 0 || b->mlen < 0 || b->slen > b->mlen || b->mlen <= 0 || b->slen < 0 || repl->slen < 0) return BSTR_ERR; if (pos > b->slen - find->slen) return BSTR_OK; /* Alias with find string */ pd = (ptrdiff_t) (find->data - b->data); if ((ptrdiff_t) (pos - find->slen) < pd && pd < (ptrdiff_t) b->slen) { if (NULL == (auxf = bstrcpy (find))) return BSTR_ERR; } /* Alias with repl string */ pd = (ptrdiff_t) (repl->data - b->data); if ((ptrdiff_t) (pos - repl->slen) < pd && pd < (ptrdiff_t) b->slen) { if (NULL == (auxr = bstrcpy (repl))) { if (auxf != find) bdestroy (auxf); return BSTR_ERR; } } delta = auxf->slen - auxr->slen; /* in-place replacement since find and replace strings are of equal length */ if (delta == 0) { while ((pos = instr (b, pos, auxf)) >= 0) { bstr__memcpy (b->data + pos, auxr->data, auxr->slen); pos += auxf->slen; } if (auxf != find) bdestroy (auxf); if (auxr != repl) bdestroy (auxr); return BSTR_OK; } /* shrinking replacement since auxf->slen > auxr->slen */ if (delta > 0) { acc = 0; while ((i = instr (b, pos, auxf)) >= 0) { if (acc && i > pos) bstr__memmove (b->data + pos - acc, b->data + pos, i - pos); if (auxr->slen) bstr__memcpy (b->data + i - acc, auxr->data, auxr->slen); acc += delta; pos = i + auxf->slen; } if (acc) { i = b->slen; if (i > pos) bstr__memmove (b->data + pos - acc, b->data + pos, i - pos); b->slen -= acc; b->data[b->slen] = (unsigned char) '\0'; } if (auxf != find) bdestroy (auxf); if (auxr != repl) bdestroy (auxr); return BSTR_OK; } /* expanding replacement since find->slen < repl->slen. Its a lot more complicated. This works by first finding all the matches and storing them to a growable array, then doing at most one resize of the destination bstring and then performing the direct memory transfers of the string segment pieces to form the final result. The growable array of matches uses a deferred doubling reallocing strategy. What this means is that it starts as a reasonably fixed sized auto array in the hopes that many if not most cases will never need to grow this array. But it switches as soon as the bounds of the array will be exceeded. An extra find result is always appended to this array that corresponds to the end of the destination string, so slen is checked against mlen - 1 rather than mlen before resizing. */ mlen = INITIAL_STATIC_FIND_INDEX_COUNT; d = (int *) static_d; /* Avoid malloc for trivial/initial cases */ acc = slen = 0; while ((pos = instr (b, pos, auxf)) >= 0) { if (slen >= mlen - 1) { int sl, *t; mlen += mlen; sl = sizeof (int *) * mlen; if (static_d == d) d = NULL; /* static_d cannot be realloced */ if (mlen <= 0 || sl < mlen || NULL == (t = (int *) bstr__realloc (d, sl))) { ret = BSTR_ERR; goto done; } if (NULL == d) bstr__memcpy (t, static_d, sizeof (static_d)); d = t; } d[slen] = pos; slen++; acc -= delta; pos += auxf->slen; if (pos < 0 || acc < 0) { ret = BSTR_ERR; goto done; } } /* slen <= INITIAL_STATIC_INDEX_COUNT-1 or mlen-1 here. */ d[slen] = b->slen; if (BSTR_OK == (ret = balloc (b, b->slen + acc + 1))) { b->slen += acc; for (i = slen-1; i >= 0; i--) { int s, l; s = d[i] + auxf->slen; l = d[i+1] - s; /* d[slen] may be accessed here. */ if (l) { bstr__memmove (b->data + s + acc, b->data + s, l); } if (auxr->slen) { bstr__memmove (b->data + s + acc - auxr->slen, auxr->data, auxr->slen); } acc += delta; } b->data[b->slen] = (unsigned char) '\0'; } done:; if (static_d == d) d = NULL; bstr__free (d); if (auxf != find) bdestroy (auxf); if (auxr != repl) bdestroy (auxr); return ret; } /* int bfindreplace (bstring b, const_bstring find, const_bstring repl, * int pos) * * Replace all occurrences of a find string with a replace string after a * given point in a bstring. */ int bfindreplace (bstring b, const_bstring find, const_bstring repl, int pos) { return findreplaceengine (b, find, repl, pos, binstr); } /* int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, * int pos) * * Replace all occurrences of a find string, ignoring case, with a replace * string after a given point in a bstring. */ int bfindreplacecaseless (bstring b, const_bstring find, const_bstring repl, int pos) { return findreplaceengine (b, find, repl, pos, binstrcaseless); } /* int binsertch (bstring b, int pos, int len, unsigned char fill) * * Inserts the character fill repeatedly into b at position pos for a * length len. If the position pos is past the end of b, then the * character "fill" is appended as necessary to make up the gap between the * end of b and the position pos + len. */ int binsertch (bstring b, int pos, int len, unsigned char fill) { int d, l, i; if (pos < 0 || b == NULL || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || len < 0) return BSTR_ERR; /* Compute the two possible end pointers */ d = b->slen + len; l = pos + len; if ((d|l) < 0) return BSTR_ERR; if (l > d) { /* Inserting past the end of the string */ if (balloc (b, l + 1) != BSTR_OK) return BSTR_ERR; pos = b->slen; b->slen = l; } else { /* Inserting in the middle of the string */ if (balloc (b, d + 1) != BSTR_OK) return BSTR_ERR; for (i = d - 1; i >= l; i--) { b->data[i] = b->data[i - len]; } b->slen = d; } for (i=pos; i < l; i++) b->data[i] = fill; b->data[b->slen] = (unsigned char) '\0'; return BSTR_OK; } /* int bpattern (bstring b, int len) * * Replicate the bstring, b in place, end to end repeatedly until it * surpasses len characters, then chop the result to exactly len characters. * This function operates in-place. The function will return with BSTR_ERR * if b is NULL or of length 0, otherwise BSTR_OK is returned. */ int bpattern (bstring b, int len) { int i, d; d = blength (b); if (d <= 0 || len < 0 || balloc (b, len + 1) != BSTR_OK) return BSTR_ERR; if (len > 0) { if (d == 1) return bsetstr (b, len, NULL, b->data[0]); for (i = d; i < len; i++) b->data[i] = b->data[i - d]; } b->data[len] = (unsigned char) '\0'; b->slen = len; return BSTR_OK; } #define BS_BUFF_SZ (1024) /* int breada (bstring b, bNread readPtr, void * parm) * * Use a finite buffer fread-like function readPtr to concatenate to the * bstring b the entire contents of file-like source data in a roughly * efficient way. */ int breada (bstring b, bNread readPtr, void * parm) { int i, l, n; if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || readPtr == NULL) return BSTR_ERR; i = b->slen; for (n=i+16; ; n += ((n < BS_BUFF_SZ) ? n : BS_BUFF_SZ)) { if (BSTR_OK != balloc (b, n + 1)) return BSTR_ERR; l = (int) readPtr ((void *) (b->data + i), 1, n - i, parm); i += l; b->slen = i; if (i < n) break; } b->data[i] = (unsigned char) '\0'; return BSTR_OK; } /* bstring bread (bNread readPtr, void * parm) * * Use a finite buffer fread-like function readPtr to create a bstring * filled with the entire contents of file-like source data in a roughly * efficient way. */ bstring bread (bNread readPtr, void * parm) { bstring buff; if (0 > breada (buff = bfromcstr (""), readPtr, parm)) { bdestroy (buff); return NULL; } return buff; } /* int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator) * * Use an fgetc-like single character stream reading function (getcPtr) to * obtain a sequence of characters which are concatenated to the end of the * bstring b. The stream read is terminated by the passed in terminator * parameter. * * If getcPtr returns with a negative number, or the terminator character * (which is appended) is read, then the stream reading is halted and the * function returns with a partial result in b. If there is an empty partial * result, 1 is returned. If no characters are read, or there is some other * detectable error, BSTR_ERR is returned. */ int bassigngets (bstring b, bNgetc getcPtr, void * parm, char terminator) { int c, d, e; if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || getcPtr == NULL) return BSTR_ERR; d = 0; e = b->mlen - 2; while ((c = getcPtr (parm)) >= 0) { if (d > e) { b->slen = d; if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR; e = b->mlen - 2; } b->data[d] = (unsigned char) c; d++; if (c == terminator) break; } b->data[d] = (unsigned char) '\0'; b->slen = d; return d == 0 && c < 0; } /* int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator) * * Use an fgetc-like single character stream reading function (getcPtr) to * obtain a sequence of characters which are concatenated to the end of the * bstring b. The stream read is terminated by the passed in terminator * parameter. * * If getcPtr returns with a negative number, or the terminator character * (which is appended) is read, then the stream reading is halted and the * function returns with a partial result concatentated to b. If there is * an empty partial result, 1 is returned. If no characters are read, or * there is some other detectable error, BSTR_ERR is returned. */ int bgetsa (bstring b, bNgetc getcPtr, void * parm, char terminator) { int c, d, e; if (b == NULL || b->mlen <= 0 || b->slen < 0 || b->mlen < b->slen || b->mlen <= 0 || getcPtr == NULL) return BSTR_ERR; d = b->slen; e = b->mlen - 2; while ((c = getcPtr (parm)) >= 0) { if (d > e) { b->slen = d; if (balloc (b, d + 2) != BSTR_OK) return BSTR_ERR; e = b->mlen - 2; } b->data[d] = (unsigned char) c; d++; if (c == terminator) break; } b->data[d] = (unsigned char) '\0'; b->slen = d; return d == 0 && c < 0; } /* bstring bgets (bNgetc getcPtr, void * parm, char terminator) * * Use an fgetc-like single character stream reading function (getcPtr) to * obtain a sequence of characters which are concatenated into a bstring. * The stream read is terminated by the passed in terminator function. * * If getcPtr returns with a negative number, or the terminator character * (which is appended) is read, then the stream reading is halted and the * result obtained thus far is returned. If no characters are read, or * there is some other detectable error, NULL is returned. */ bstring bgets (bNgetc getcPtr, void * parm, char terminator) { bstring buff; if (0 > bgetsa (buff = bfromcstr (""), getcPtr, parm, terminator) || 0 >= buff->slen) { bdestroy (buff); buff = NULL; } return buff; } struct bStream { bstring buff; /* Buffer for over-reads */ void * parm; /* The stream handle for core stream */ bNread readFnPtr; /* fread compatible fnptr for core stream */ int isEOF; /* track file's EOF state */ int maxBuffSz; }; /* struct bStream * bsopen (bNread readPtr, void * parm) * * Wrap a given open stream (described by a fread compatible function * pointer and stream handle) into an open bStream suitable for the bstring * library streaming functions. */ struct bStream * bsopen (bNread readPtr, void * parm) { struct bStream * s; if (readPtr == NULL) return NULL; s = (struct bStream *) bstr__alloc (sizeof (struct bStream)); if (s == NULL) return NULL; s->parm = parm; s->buff = bfromcstr (""); s->readFnPtr = readPtr; s->maxBuffSz = BS_BUFF_SZ; s->isEOF = 0; return s; } /* int bsbufflength (struct bStream * s, int sz) * * Set the length of the buffer used by the bStream. If sz is zero, the * length is not set. This function returns with the previous length. */ int bsbufflength (struct bStream * s, int sz) { int oldSz; if (s == NULL || sz < 0) return BSTR_ERR; oldSz = s->maxBuffSz; if (sz > 0) s->maxBuffSz = sz; return oldSz; } int bseof (const struct bStream * s) { if (s == NULL || s->readFnPtr == NULL) return BSTR_ERR; return s->isEOF && (s->buff->slen == 0); } /* void * bsclose (struct bStream * s) * * Close the bStream, and return the handle to the stream that was originally * used to open the given stream. */ void * bsclose (struct bStream * s) { void * parm; if (s == NULL) return NULL; s->readFnPtr = NULL; if (s->buff) bdestroy (s->buff); s->buff = NULL; parm = s->parm; s->parm = NULL; s->isEOF = 1; bstr__free (s); return parm; } /* int bsreadlna (bstring r, struct bStream * s, char terminator) * * Read a bstring terminated by the terminator character or the end of the * stream from the bStream (s) and return it into the parameter r. This * function may read additional characters from the core stream that are not * returned, but will be retained for subsequent read operations. */ int bsreadlna (bstring r, struct bStream * s, char terminator) { int i, l, ret, rlo; char * b; struct tagbstring x; if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 || r->slen < 0 || r->mlen < r->slen) return BSTR_ERR; l = s->buff->slen; if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; b = (char *) s->buff->data; x.data = (unsigned char *) b; /* First check if the current buffer holds the terminator */ b[l] = terminator; /* Set sentinel */ for (i=0; b[i] != terminator; i++) ; if (i < l) { x.slen = i + 1; ret = bconcat (r, &x); s->buff->slen = l; if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1); return BSTR_OK; } rlo = r->slen; /* If not then just concatenate the entire buffer to the output */ x.slen = l; if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR; /* Perform direct in-place reads into the destination to allow for the minimum of data-copies */ for (;;) { if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) return BSTR_ERR; b = (char *) (r->data + r->slen); l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm); if (l <= 0) { r->data[r->slen] = (unsigned char) '\0'; s->buff->slen = 0; s->isEOF = 1; /* If nothing was read return with an error message */ return BSTR_ERR & -(r->slen == rlo); } b[l] = terminator; /* Set sentinel */ for (i=0; b[i] != terminator; i++) ; if (i < l) break; r->slen += l; } /* Terminator found, push over-read back to buffer */ i++; r->slen += i; s->buff->slen = l - i; bstr__memcpy (s->buff->data, b + i, l - i); r->data[r->slen] = (unsigned char) '\0'; return BSTR_OK; } /* int bsreadlnsa (bstring r, struct bStream * s, bstring term) * * Read a bstring terminated by any character in the term string or the end * of the stream from the bStream (s) and return it into the parameter r. * This function may read additional characters from the core stream that * are not returned, but will be retained for subsequent read operations. */ int bsreadlnsa (bstring r, struct bStream * s, const_bstring term) { int i, l, ret, rlo; unsigned char * b; struct tagbstring x; struct charField cf; if (s == NULL || s->buff == NULL || r == NULL || term == NULL || term->data == NULL || r->mlen <= 0 || r->slen < 0 || r->mlen < r->slen) return BSTR_ERR; if (term->slen == 1) return bsreadlna (r, s, term->data[0]); if (term->slen < 1 || buildCharField (&cf, term)) return BSTR_ERR; l = s->buff->slen; if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; b = (unsigned char *) s->buff->data; x.data = b; /* First check if the current buffer holds the terminator */ b[l] = term->data[0]; /* Set sentinel */ for (i=0; !testInCharField (&cf, b[i]); i++) ; if (i < l) { x.slen = i + 1; ret = bconcat (r, &x); s->buff->slen = l; if (BSTR_OK == ret) bdelete (s->buff, 0, i + 1); return BSTR_OK; } rlo = r->slen; /* If not then just concatenate the entire buffer to the output */ x.slen = l; if (BSTR_OK != bconcat (r, &x)) return BSTR_ERR; /* Perform direct in-place reads into the destination to allow for the minimum of data-copies */ for (;;) { if (BSTR_OK != balloc (r, r->slen + s->maxBuffSz + 1)) return BSTR_ERR; b = (unsigned char *) (r->data + r->slen); l = (int) s->readFnPtr (b, 1, s->maxBuffSz, s->parm); if (l <= 0) { r->data[r->slen] = (unsigned char) '\0'; s->buff->slen = 0; s->isEOF = 1; /* If nothing was read return with an error message */ return BSTR_ERR & -(r->slen == rlo); } b[l] = term->data[0]; /* Set sentinel */ for (i=0; !testInCharField (&cf, b[i]); i++) ; if (i < l) break; r->slen += l; } /* Terminator found, push over-read back to buffer */ i++; r->slen += i; s->buff->slen = l - i; bstr__memcpy (s->buff->data, b + i, l - i); r->data[r->slen] = (unsigned char) '\0'; return BSTR_OK; } /* int bsreada (bstring r, struct bStream * s, int n) * * Read a bstring of length n (or, if it is fewer, as many bytes as is * remaining) from the bStream. This function may read additional * characters from the core stream that are not returned, but will be * retained for subsequent read operations. This function will not read * additional characters from the core stream beyond virtual stream pointer. */ int bsreada (bstring r, struct bStream * s, int n) { int l, ret, orslen; char * b; struct tagbstring x; if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 || r->slen < 0 || r->mlen < r->slen || n <= 0) return BSTR_ERR; n += r->slen; if (n <= 0) return BSTR_ERR; l = s->buff->slen; orslen = r->slen; if (0 == l) { if (s->isEOF) return BSTR_ERR; if (r->mlen > n) { l = (int) s->readFnPtr (r->data + r->slen, 1, n - r->slen, s->parm); if (0 >= l || l > n - r->slen) { s->isEOF = 1; return BSTR_ERR; } r->slen += l; r->data[r->slen] = (unsigned char) '\0'; return 0; } } if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; b = (char *) s->buff->data; x.data = (unsigned char *) b; do { if (l + r->slen >= n) { x.slen = n - r->slen; ret = bconcat (r, &x); s->buff->slen = l; if (BSTR_OK == ret) bdelete (s->buff, 0, x.slen); return BSTR_ERR & -(r->slen == orslen); } x.slen = l; if (BSTR_OK != bconcat (r, &x)) break; l = n - r->slen; if (l > s->maxBuffSz) l = s->maxBuffSz; l = (int) s->readFnPtr (b, 1, l, s->parm); } while (l > 0); if (l < 0) l = 0; if (l == 0) s->isEOF = 1; s->buff->slen = l; return BSTR_ERR & -(r->slen == orslen); } /* int bsreadln (bstring r, struct bStream * s, char terminator) * * Read a bstring terminated by the terminator character or the end of the * stream from the bStream (s) and return it into the parameter r. This * function may read additional characters from the core stream that are not * returned, but will be retained for subsequent read operations. */ int bsreadln (bstring r, struct bStream * s, char terminator) { if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0) return BSTR_ERR; if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; r->slen = 0; return bsreadlna (r, s, terminator); } /* int bsreadlns (bstring r, struct bStream * s, bstring term) * * Read a bstring terminated by any character in the term string or the end * of the stream from the bStream (s) and return it into the parameter r. * This function may read additional characters from the core stream that * are not returned, but will be retained for subsequent read operations. */ int bsreadlns (bstring r, struct bStream * s, const_bstring term) { if (s == NULL || s->buff == NULL || r == NULL || term == NULL || term->data == NULL || r->mlen <= 0) return BSTR_ERR; if (term->slen == 1) return bsreadln (r, s, term->data[0]); if (term->slen < 1) return BSTR_ERR; if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; r->slen = 0; return bsreadlnsa (r, s, term); } /* int bsread (bstring r, struct bStream * s, int n) * * Read a bstring of length n (or, if it is fewer, as many bytes as is * remaining) from the bStream. This function may read additional * characters from the core stream that are not returned, but will be * retained for subsequent read operations. This function will not read * additional characters from the core stream beyond virtual stream pointer. */ int bsread (bstring r, struct bStream * s, int n) { if (s == NULL || s->buff == NULL || r == NULL || r->mlen <= 0 || n <= 0) return BSTR_ERR; if (BSTR_OK != balloc (s->buff, s->maxBuffSz + 1)) return BSTR_ERR; r->slen = 0; return bsreada (r, s, n); } /* int bsunread (struct bStream * s, const_bstring b) * * Insert a bstring into the bStream at the current position. These * characters will be read prior to those that actually come from the core * stream. */ int bsunread (struct bStream * s, const_bstring b) { if (s == NULL || s->buff == NULL) return BSTR_ERR; return binsert (s->buff, 0, b, (unsigned char) '?'); } /* int bspeek (bstring r, const struct bStream * s) * * Return the currently buffered characters from the bStream that will be * read prior to reads from the core stream. */ int bspeek (bstring r, const struct bStream * s) { if (s == NULL || s->buff == NULL) return BSTR_ERR; return bassign (r, s->buff); } /* bstring bjoin (const struct bstrList * bl, const_bstring sep); * * Join the entries of a bstrList into one bstring by sequentially * concatenating them with the sep string in between. If there is an error * NULL is returned, otherwise a bstring with the correct result is returned. */ bstring bjoin (const struct bstrList * bl, const_bstring sep) { bstring b; int i, c, v; if (bl == NULL || bl->qty < 0) return NULL; if (sep != NULL && (sep->slen < 0 || sep->data == NULL)) return NULL; for (i = 0, c = 1; i < bl->qty; i++) { v = bl->entry[i]->slen; if (v < 0) return NULL; /* Invalid input */ c += v; if (c < 0) return NULL; /* Wrap around ?? */ } if (sep != NULL) c += (bl->qty - 1) * sep->slen; b = (bstring) bstr__alloc (sizeof (struct tagbstring)); if (NULL == b) return NULL; /* Out of memory */ b->data = (unsigned char *) bstr__alloc (c); if (b->data == NULL) { bstr__free (b); return NULL; } b->mlen = c; b->slen = c-1; for (i = 0, c = 0; i < bl->qty; i++) { if (i > 0 && sep != NULL) { bstr__memcpy (b->data + c, sep->data, sep->slen); c += sep->slen; } v = bl->entry[i]->slen; bstr__memcpy (b->data + c, bl->entry[i]->data, v); c += v; } b->data[c] = (unsigned char) '\0'; return b; } #define BSSSC_BUFF_LEN (256) /* int bssplitscb (struct bStream * s, const_bstring splitStr, * int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) * * Iterate the set of disjoint sequential substrings read from a stream * divided by any of the characters in splitStr. An empty splitStr causes * the whole stream to be iterated once. * * Note: At the point of calling the cb function, the bStream pointer is * pointed exactly at the position right after having read the split * character. The cb function can act on the stream by causing the bStream * pointer to move, and bssplitscb will continue by starting the next split * at the position of the pointer after the return from cb. * * However, if the cb causes the bStream s to be destroyed then the cb must * return with a negative value, otherwise bssplitscb will continue in an * undefined manner. */ int bssplitscb (struct bStream * s, const_bstring splitStr, int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) { struct charField chrs; bstring buff; int i, p, ret; if (cb == NULL || s == NULL || s->readFnPtr == NULL || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; if (NULL == (buff = bfromcstr (""))) return BSTR_ERR; if (splitStr->slen == 0) { while (bsreada (buff, s, BSSSC_BUFF_LEN) >= 0) ; if ((ret = cb (parm, 0, buff)) > 0) ret = 0; } else { buildCharField (&chrs, splitStr); ret = p = i = 0; for (;;) { if (i >= buff->slen) { bsreada (buff, s, BSSSC_BUFF_LEN); if (i >= buff->slen) { if (0 < (ret = cb (parm, p, buff))) ret = 0; break; } } if (testInCharField (&chrs, buff->data[i])) { struct tagbstring t; unsigned char c; blk2tbstr (t, buff->data + i + 1, buff->slen - (i + 1)); if ((ret = bsunread (s, &t)) < 0) break; buff->slen = i; c = buff->data[i]; buff->data[i] = (unsigned char) '\0'; if ((ret = cb (parm, p, buff)) < 0) break; buff->data[i] = c; buff->slen = 0; p += i + 1; i = -1; } i++; } } bdestroy (buff); return ret; } /* int bssplitstrcb (struct bStream * s, const_bstring splitStr, * int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) * * Iterate the set of disjoint sequential substrings read from a stream * divided by the entire substring splitStr. An empty splitStr causes * each character of the stream to be iterated. * * Note: At the point of calling the cb function, the bStream pointer is * pointed exactly at the position right after having read the split * character. The cb function can act on the stream by causing the bStream * pointer to move, and bssplitscb will continue by starting the next split * at the position of the pointer after the return from cb. * * However, if the cb causes the bStream s to be destroyed then the cb must * return with a negative value, otherwise bssplitscb will continue in an * undefined manner. */ int bssplitstrcb (struct bStream * s, const_bstring splitStr, int (* cb) (void * parm, int ofs, const_bstring entry), void * parm) { bstring buff; int i, p, ret; if (cb == NULL || s == NULL || s->readFnPtr == NULL || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; if (splitStr->slen == 1) return bssplitscb (s, splitStr, cb, parm); if (NULL == (buff = bfromcstr (""))) return BSTR_ERR; if (splitStr->slen == 0) { for (i=0; bsreada (buff, s, BSSSC_BUFF_LEN) >= 0; i++) { if ((ret = cb (parm, 0, buff)) < 0) { bdestroy (buff); return ret; } buff->slen = 0; } return BSTR_OK; } else { ret = p = i = 0; for (i=p=0;;) { if ((ret = binstr (buff, 0, splitStr)) >= 0) { struct tagbstring t; blk2tbstr (t, buff->data, ret); i = ret + splitStr->slen; if ((ret = cb (parm, p, &t)) < 0) break; p += i; bdelete (buff, 0, i); } else { bsreada (buff, s, BSSSC_BUFF_LEN); if (bseof (s)) { if ((ret = cb (parm, p, buff)) > 0) ret = 0; break; } } } } bdestroy (buff); return ret; } /* int bstrListCreate (void) * * Create a bstrList. */ struct bstrList * bstrListCreate (void) { struct bstrList * sl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); if (sl) { sl->entry = (bstring *) bstr__alloc (1*sizeof (bstring)); if (!sl->entry) { bstr__free (sl); sl = NULL; } else { sl->qty = 0; sl->mlen = 1; } } return sl; } /* int bstrListDestroy (struct bstrList * sl) * * Destroy a bstrList that has been created by bsplit, bsplits or bstrListCreate. */ int bstrListDestroy (struct bstrList * sl) { int i; if (sl == NULL || sl->qty < 0) return BSTR_ERR; for (i=0; i < sl->qty; i++) { if (sl->entry[i]) { bdestroy (sl->entry[i]); sl->entry[i] = NULL; } } sl->qty = -1; sl->mlen = -1; bstr__free (sl->entry); sl->entry = NULL; bstr__free (sl); return BSTR_OK; } /* int bstrListAlloc (struct bstrList * sl, int msz) * * Ensure that there is memory for at least msz number of entries for the * list. */ int bstrListAlloc (struct bstrList * sl, int msz) { bstring * l; int smsz; size_t nsz; if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || sl->qty > sl->mlen) return BSTR_ERR; if (sl->mlen >= msz) return BSTR_OK; smsz = snapUpSize (msz); nsz = ((size_t) smsz) * sizeof (bstring); if (nsz < (size_t) smsz) return BSTR_ERR; l = (bstring *) bstr__realloc (sl->entry, nsz); if (!l) { smsz = msz; nsz = ((size_t) smsz) * sizeof (bstring); l = (bstring *) bstr__realloc (sl->entry, nsz); if (!l) return BSTR_ERR; } sl->mlen = smsz; sl->entry = l; return BSTR_OK; } /* int bstrListAllocMin (struct bstrList * sl, int msz) * * Try to allocate the minimum amount of memory for the list to include at * least msz entries or sl->qty whichever is greater. */ int bstrListAllocMin (struct bstrList * sl, int msz) { bstring * l; size_t nsz; if (!sl || msz <= 0 || !sl->entry || sl->qty < 0 || sl->mlen <= 0 || sl->qty > sl->mlen) return BSTR_ERR; if (msz < sl->qty) msz = sl->qty; if (sl->mlen == msz) return BSTR_OK; nsz = ((size_t) msz) * sizeof (bstring); if (nsz < (size_t) msz) return BSTR_ERR; l = (bstring *) bstr__realloc (sl->entry, nsz); if (!l) return BSTR_ERR; sl->mlen = msz; sl->entry = l; return BSTR_OK; } /* int bsplitcb (const_bstring str, unsigned char splitChar, int pos, * int (* cb) (void * parm, int ofs, int len), void * parm) * * Iterate the set of disjoint sequential substrings over str divided by the * character in splitChar. * * Note: Non-destructive modification of str from within the cb function * while performing this split is not undefined. bsplitcb behaves in * sequential lock step with calls to cb. I.e., after returning from a cb * that return a non-negative integer, bsplitcb continues from the position * 1 character after the last detected split character and it will halt * immediately if the length of str falls below this point. However, if the * cb function destroys str, then it *must* return with a negative value, * otherwise bsplitcb will continue in an undefined manner. */ int bsplitcb (const_bstring str, unsigned char splitChar, int pos, int (* cb) (void * parm, int ofs, int len), void * parm) { int i, p, ret; if (cb == NULL || str == NULL || pos < 0 || pos > str->slen) return BSTR_ERR; p = pos; do { for (i=p; i < str->slen; i++) { if (str->data[i] == splitChar) break; } if ((ret = cb (parm, p, i - p)) < 0) return ret; p = i + 1; } while (p <= str->slen); return BSTR_OK; } /* int bsplitscb (const_bstring str, const_bstring splitStr, int pos, * int (* cb) (void * parm, int ofs, int len), void * parm) * * Iterate the set of disjoint sequential substrings over str divided by any * of the characters in splitStr. An empty splitStr causes the whole str to * be iterated once. * * Note: Non-destructive modification of str from within the cb function * while performing this split is not undefined. bsplitscb behaves in * sequential lock step with calls to cb. I.e., after returning from a cb * that return a non-negative integer, bsplitscb continues from the position * 1 character after the last detected split character and it will halt * immediately if the length of str falls below this point. However, if the * cb function destroys str, then it *must* return with a negative value, * otherwise bsplitscb will continue in an undefined manner. */ int bsplitscb (const_bstring str, const_bstring splitStr, int pos, int (* cb) (void * parm, int ofs, int len), void * parm) { struct charField chrs; int i, p, ret; if (cb == NULL || str == NULL || pos < 0 || pos > str->slen || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; if (splitStr->slen == 0) { if ((ret = cb (parm, 0, str->slen)) > 0) ret = 0; return ret; } if (splitStr->slen == 1) return bsplitcb (str, splitStr->data[0], pos, cb, parm); buildCharField (&chrs, splitStr); p = pos; do { for (i=p; i < str->slen; i++) { if (testInCharField (&chrs, str->data[i])) break; } if ((ret = cb (parm, p, i - p)) < 0) return ret; p = i + 1; } while (p <= str->slen); return BSTR_OK; } /* int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos, * int (* cb) (void * parm, int ofs, int len), void * parm) * * Iterate the set of disjoint sequential substrings over str divided by the * substring splitStr. An empty splitStr causes the whole str to be * iterated once. * * Note: Non-destructive modification of str from within the cb function * while performing this split is not undefined. bsplitstrcb behaves in * sequential lock step with calls to cb. I.e., after returning from a cb * that return a non-negative integer, bsplitscb continues from the position * 1 character after the last detected split character and it will halt * immediately if the length of str falls below this point. However, if the * cb function destroys str, then it *must* return with a negative value, * otherwise bsplitscb will continue in an undefined manner. */ int bsplitstrcb (const_bstring str, const_bstring splitStr, int pos, int (* cb) (void * parm, int ofs, int len), void * parm) { int i, p, ret; if (cb == NULL || str == NULL || pos < 0 || pos > str->slen || splitStr == NULL || splitStr->slen < 0) return BSTR_ERR; if (0 == splitStr->slen) { for (i=pos; i < str->slen; i++) { if ((ret = cb (parm, i, 1)) < 0) return ret; } return BSTR_OK; } if (splitStr->slen == 1) return bsplitcb (str, splitStr->data[0], pos, cb, parm); for (i=p=pos; i <= str->slen - splitStr->slen; i++) { if (0 == bstr__memcmp (splitStr->data, str->data + i, splitStr->slen)) { if ((ret = cb (parm, p, i - p)) < 0) return ret; i += splitStr->slen; p = i; } } if ((ret = cb (parm, p, str->slen - p)) < 0) return ret; return BSTR_OK; } struct genBstrList { bstring b; struct bstrList * bl; }; static int bscb (void * parm, int ofs, int len) { struct genBstrList * g = (struct genBstrList *) parm; if (g->bl->qty >= g->bl->mlen) { int mlen = g->bl->mlen * 2; bstring * tbl; while (g->bl->qty >= mlen) { if (mlen < g->bl->mlen) return BSTR_ERR; mlen += mlen; } tbl = (bstring *) bstr__realloc (g->bl->entry, sizeof (bstring) * mlen); if (tbl == NULL) return BSTR_ERR; g->bl->entry = tbl; g->bl->mlen = mlen; } g->bl->entry[g->bl->qty] = bmidstr (g->b, ofs, len); g->bl->qty++; return BSTR_OK; } /* struct bstrList * bsplit (const_bstring str, unsigned char splitChar) * * Create an array of sequential substrings from str divided by the character * splitChar. */ struct bstrList * bsplit (const_bstring str, unsigned char splitChar) { struct genBstrList g; if (str == NULL || str->data == NULL || str->slen < 0) return NULL; g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); if (g.bl == NULL) return NULL; g.bl->mlen = 4; g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); if (NULL == g.bl->entry) { bstr__free (g.bl); return NULL; } g.b = (bstring) str; g.bl->qty = 0; if (bsplitcb (str, splitChar, 0, bscb, &g) < 0) { bstrListDestroy (g.bl); return NULL; } return g.bl; } /* struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr) * * Create an array of sequential substrings from str divided by the entire * substring splitStr. */ struct bstrList * bsplitstr (const_bstring str, const_bstring splitStr) { struct genBstrList g; if (str == NULL || str->data == NULL || str->slen < 0) return NULL; g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); if (g.bl == NULL) return NULL; g.bl->mlen = 4; g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); if (NULL == g.bl->entry) { bstr__free (g.bl); return NULL; } g.b = (bstring) str; g.bl->qty = 0; if (bsplitstrcb (str, splitStr, 0, bscb, &g) < 0) { bstrListDestroy (g.bl); return NULL; } return g.bl; } /* struct bstrList * bsplits (const_bstring str, bstring splitStr) * * Create an array of sequential substrings from str divided by any of the * characters in splitStr. An empty splitStr causes a single entry bstrList * containing a copy of str to be returned. */ struct bstrList * bsplits (const_bstring str, const_bstring splitStr) { struct genBstrList g; if ( str == NULL || str->slen < 0 || str->data == NULL || splitStr == NULL || splitStr->slen < 0 || splitStr->data == NULL) return NULL; g.bl = (struct bstrList *) bstr__alloc (sizeof (struct bstrList)); if (g.bl == NULL) return NULL; g.bl->mlen = 4; g.bl->entry = (bstring *) bstr__alloc (g.bl->mlen * sizeof (bstring)); if (NULL == g.bl->entry) { bstr__free (g.bl); return NULL; } g.b = (bstring) str; g.bl->qty = 0; if (bsplitscb (str, splitStr, 0, bscb, &g) < 0) { bstrListDestroy (g.bl); return NULL; } return g.bl; } #if defined (__TURBOC__) && !defined (__BORLANDC__) # ifndef BSTRLIB_NOVSNP # define BSTRLIB_NOVSNP # endif #endif /* Give WATCOM C/C++, MSVC some latitude for their non-support of vsnprintf */ #if defined(__WATCOMC__) || defined(_MSC_VER) #define exvsnprintf(r,b,n,f,a) {r = _vsnprintf (b,n,f,a);} #else #ifdef BSTRLIB_NOVSNP /* This is just a hack. If you are using a system without a vsnprintf, it is not recommended that bformat be used at all. */ #define exvsnprintf(r,b,n,f,a) {vsprintf (b,f,a); r = -1;} #define START_VSNBUFF (256) #else #if defined(__GNUC__) && !defined(__APPLE__) /* Something is making gcc complain about this prototype not being here, so I've just gone ahead and put it in. */ extern int vsnprintf (char *buf, size_t count, const char *format, va_list arg); #endif #define exvsnprintf(r,b,n,f,a) {r = vsnprintf (b,n,f,a);} #endif #endif #if !defined (BSTRLIB_NOVSNP) #ifndef START_VSNBUFF #define START_VSNBUFF (16) #endif /* On IRIX vsnprintf returns n-1 when the operation would overflow the target buffer, WATCOM and MSVC both return -1, while C99 requires that the returned value be exactly what the length would be if the buffer would be large enough. This leads to the idea that if the return value is larger than n, then changing n to the return value will reduce the number of iterations required. */ /* int bformata (bstring b, const char * fmt, ...) * * After the first parameter, it takes the same parameters as printf (), but * rather than outputting results to stdio, it appends the results to * a bstring which contains what would have been output. Note that if there * is an early generation of a '\0' character, the bstring will be truncated * to this end point. */ int bformata (bstring b, const char * fmt, ...) { va_list arglist; bstring buff; int n, r; if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; /* Since the length is not determinable beforehand, a search is performed using the truncating "vsnprintf" call (to avoid buffer overflows) on increasing potential sizes for the output result. */ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; if (NULL == (buff = bfromcstralloc (n + 2, ""))) { n = 1; if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR; } for (;;) { va_start (arglist, fmt); exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); va_end (arglist); buff->data[n] = (unsigned char) '\0'; buff->slen = (int) (strlen) ((char *) buff->data); if (buff->slen < n) break; if (r > n) n = r; else n += n; if (BSTR_OK != balloc (buff, n + 2)) { bdestroy (buff); return BSTR_ERR; } } r = bconcat (b, buff); bdestroy (buff); return r; } /* int bassignformat (bstring b, const char * fmt, ...) * * After the first parameter, it takes the same parameters as printf (), but * rather than outputting results to stdio, it outputs the results to * the bstring parameter b. Note that if there is an early generation of a * '\0' character, the bstring will be truncated to this end point. */ int bassignformat (bstring b, const char * fmt, ...) { va_list arglist; bstring buff; int n, r; if (b == NULL || fmt == NULL || b->data == NULL || b->mlen <= 0 || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; /* Since the length is not determinable beforehand, a search is performed using the truncating "vsnprintf" call (to avoid buffer overflows) on increasing potential sizes for the output result. */ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; if (NULL == (buff = bfromcstralloc (n + 2, ""))) { n = 1; if (NULL == (buff = bfromcstralloc (n + 2, ""))) return BSTR_ERR; } for (;;) { va_start (arglist, fmt); exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); va_end (arglist); buff->data[n] = (unsigned char) '\0'; buff->slen = (int) (strlen) ((char *) buff->data); if (buff->slen < n) break; if (r > n) n = r; else n += n; if (BSTR_OK != balloc (buff, n + 2)) { bdestroy (buff); return BSTR_ERR; } } r = bassign (b, buff); bdestroy (buff); return r; } /* bstring bformat (const char * fmt, ...) * * Takes the same parameters as printf (), but rather than outputting results * to stdio, it forms a bstring which contains what would have been output. * Note that if there is an early generation of a '\0' character, the * bstring will be truncated to this end point. */ bstring bformat (const char * fmt, ...) { va_list arglist; bstring buff; int n, r; if (fmt == NULL) return NULL; /* Since the length is not determinable beforehand, a search is performed using the truncating "vsnprintf" call (to avoid buffer overflows) on increasing potential sizes for the output result. */ if ((n = (int) (2*strlen (fmt))) < START_VSNBUFF) n = START_VSNBUFF; if (NULL == (buff = bfromcstralloc (n + 2, ""))) { n = 1; if (NULL == (buff = bfromcstralloc (n + 2, ""))) return NULL; } for (;;) { va_start (arglist, fmt); exvsnprintf (r, (char *) buff->data, n + 1, fmt, arglist); va_end (arglist); buff->data[n] = (unsigned char) '\0'; buff->slen = (int) (strlen) ((char *) buff->data); if (buff->slen < n) break; if (r > n) n = r; else n += n; if (BSTR_OK != balloc (buff, n + 2)) { bdestroy (buff); return NULL; } } return buff; } /* int bvcformata (bstring b, int count, const char * fmt, va_list arglist) * * The bvcformata function formats data under control of the format control * string fmt and attempts to append the result to b. The fmt parameter is * the same as that of the printf function. The variable argument list is * replaced with arglist, which has been initialized by the va_start macro. * The size of the output is upper bounded by count. If the required output * exceeds count, the string b is not augmented with any contents and a value * below BSTR_ERR is returned. If a value below -count is returned then it * is recommended that the negative of this value be used as an update to the * count in a subsequent pass. On other errors, such as running out of * memory, parameter errors or numeric wrap around BSTR_ERR is returned. * BSTR_OK is returned when the output is successfully generated and * appended to b. * * Note: There is no sanity checking of arglist, and this function is * destructive of the contents of b from the b->slen point onward. If there * is an early generation of a '\0' character, the bstring will be truncated * to this end point. */ int bvcformata (bstring b, int count, const char * fmt, va_list arg) { int n, r, l; if (b == NULL || fmt == NULL || count <= 0 || b->data == NULL || b->mlen <= 0 || b->slen < 0 || b->slen > b->mlen) return BSTR_ERR; if (count > (n = b->slen + count) + 2) return BSTR_ERR; if (BSTR_OK != balloc (b, n + 2)) return BSTR_ERR; exvsnprintf (r, (char *) b->data + b->slen, count + 2, fmt, arg); /* Did the operation complete successfully within bounds? */ if (n >= (l = b->slen + (int) (strlen) ((const char *) b->data + b->slen))) { b->slen = l; return BSTR_OK; } /* Abort, since the buffer was not large enough. The return value tries to help set what the retry length should be. */ b->data[b->slen] = '\0'; if (r > count+1) l = r; else { l = count+count; if (count > l) l = INT_MAX; } n = -l; if (n > BSTR_ERR-1) n = BSTR_ERR-1; return n; } #endif
549300.c
/* crypto/lhash/lhash.c */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* Code for dynamic hash table routines * Author - Eric Young v 2.0 * * 2.2 eay - added #include "crypto.h" so the memory leak checking code is * present. eay 18-Jun-98 * * 2.1 eay - Added an 'error in last operation' flag. eay 6-May-98 * * 2.0 eay - Fixed a bug that occurred when using lh_delete * from inside lh_doall(). As entries were deleted, * the 'table' was 'contract()ed', making some entries * jump from the end of the table to the start, there by * skipping the lh_doall() processing. eay - 4/12/95 * * 1.9 eay - Fixed a memory leak in lh_free, the LHASH_NODEs * were not being free()ed. 21/11/95 * * 1.8 eay - Put the stats routines into a separate file, lh_stats.c * 19/09/95 * * 1.7 eay - Removed the fputs() for realloc failures - the code * should silently tolerate them. I have also fixed things * lint complained about 04/05/95 * * 1.6 eay - Fixed an invalid pointers in contract/expand 27/07/92 * * 1.5 eay - Fixed a misuse of realloc in expand 02/03/1992 * * 1.4 eay - Fixed lh_doall so the function can call lh_delete 28/05/91 * * 1.3 eay - Fixed a few lint problems 19/3/1991 * * 1.2 eay - Fixed lh_doall problem 13/3/1991 * * 1.1 eay - Added lh_doall * * 1.0 eay - First version */ #include <stdio.h> #include <string.h> #include <stdlib.h> #if 0 /* STANDALONE */ #include <openssl/crypto.h> #include <openssl/lhash.h> #else #include "lhash.h" #endif /* STANDALONE */ #if 0 /* STANDALONE */ const char lh_version[]="lhash" OPENSSL_VERSION_PTEXT; #else #define OPENSSL_malloc(i) malloc(i) #define OPENSSL_free(i) free(i) #define OPENSSL_realloc(i, j) realloc(i, j) #endif #undef MIN_NODES #define MIN_NODES 16 #define UP_LOAD (2*LH_LOAD_MULT) /* load times 256 (default 2) */ #define DOWN_LOAD (LH_LOAD_MULT) /* load times 256 (default 1) */ static void expand(_LHASH *lh); static void contract(_LHASH *lh); static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash); _LHASH *lh_new(LHASH_HASH_FN_TYPE h, LHASH_COMP_FN_TYPE c) { _LHASH *ret; int i; if ((ret=OPENSSL_malloc(sizeof(_LHASH))) == NULL) goto err0; if ((ret->b=OPENSSL_malloc(sizeof(LHASH_NODE *)*MIN_NODES)) == NULL) goto err1; for (i=0; i<MIN_NODES; i++) ret->b[i]=NULL; ret->comp=((c == NULL)?(LHASH_COMP_FN_TYPE)strcmp:c); ret->hash=((h == NULL)?(LHASH_HASH_FN_TYPE)lh_strhash:h); ret->num_nodes=MIN_NODES/2; ret->num_alloc_nodes=MIN_NODES; ret->p=0; ret->pmax=MIN_NODES/2; ret->up_load=UP_LOAD; ret->down_load=DOWN_LOAD; ret->num_items=0; ret->num_expands=0; ret->num_expand_reallocs=0; ret->num_contracts=0; ret->num_contract_reallocs=0; ret->num_hash_calls=0; ret->num_comp_calls=0; ret->num_insert=0; ret->num_replace=0; ret->num_delete=0; ret->num_no_delete=0; ret->num_retrieve=0; ret->num_retrieve_miss=0; ret->num_hash_comps=0; ret->error=0; return(ret); err1: OPENSSL_free(ret); err0: return(NULL); } void lh_free(_LHASH *lh) { unsigned int i; LHASH_NODE *n,*nn; if (lh == NULL) return; for (i=0; i<lh->num_nodes; i++) { n=lh->b[i]; while (n != NULL) { nn=n->next; OPENSSL_free(n); n=nn; } } OPENSSL_free(lh->b); OPENSSL_free(lh); } void *lh_insert(_LHASH *lh, void *data) { unsigned long hash; LHASH_NODE *nn,**rn; void *ret; lh->error=0; if (lh->up_load <= (lh->num_items*LH_LOAD_MULT/lh->num_nodes)) expand(lh); rn=getrn(lh,data,&hash); if (*rn == NULL) { if ((nn=(LHASH_NODE *)OPENSSL_malloc(sizeof(LHASH_NODE))) == NULL) { lh->error++; return(NULL); } nn->data=data; nn->next=NULL; #ifndef OPENSSL_NO_HASH_COMP nn->hash=hash; #endif *rn=nn; ret=NULL; lh->num_insert++; lh->num_items++; } else /* replace same key */ { ret= (*rn)->data; (*rn)->data=data; lh->num_replace++; } return(ret); } #if 0 void *lh_delete(_LHASH *lh, const void *data) { unsigned long hash; LHASH_NODE *nn,**rn; void *ret; lh->error=0; rn=getrn(lh,data,&hash); if (*rn == NULL) { lh->num_no_delete++; return(NULL); } else { nn= *rn; *rn=nn->next; ret=nn->data; OPENSSL_free(nn); lh->num_delete++; } lh->num_items--; if ((lh->num_nodes > MIN_NODES) && (lh->down_load >= (lh->num_items*LH_LOAD_MULT/lh->num_nodes))) contract(lh); return(ret); } #endif void *lh_retrieve(_LHASH *lh, const void *data) { unsigned long hash; LHASH_NODE **rn; void *ret; lh->error=0; rn=getrn(lh,data,&hash); if (*rn == NULL) { lh->num_retrieve_miss++; return(NULL); } else { ret= (*rn)->data; lh->num_retrieve++; } return(ret); } static void doall_util_fn(_LHASH *lh, int use_arg, LHASH_DOALL_FN_TYPE func, LHASH_DOALL_ARG_FN_TYPE func_arg, void *arg) { int i; LHASH_NODE *a,*n; if (lh == NULL) return; /* reverse the order so we search from 'top to bottom' * We were having memory leaks otherwise */ for (i=lh->num_nodes-1; i>=0; i--) { a=lh->b[i]; while (a != NULL) { /* 28/05/91 - eay - n added so items can be deleted * via lh_doall */ /* 22/05/08 - ben - eh? since a is not passed, * this should not be needed */ n=a->next; if(use_arg) func_arg(a->data,arg); else func(a->data); a=n; } } } void lh_doall(_LHASH *lh, LHASH_DOALL_FN_TYPE func) { doall_util_fn(lh, 0, func, (LHASH_DOALL_ARG_FN_TYPE)0, NULL); } #if 0 /* STANDALONE */ void lh_doall_arg(_LHASH *lh, LHASH_DOALL_ARG_FN_TYPE func, void *arg) { doall_util_fn(lh, 1, (LHASH_DOALL_FN_TYPE)0, func, arg); } #endif /* STANDALONE */ static void expand(_LHASH *lh) { LHASH_NODE **n,**n1,**n2,*np; unsigned int p,i,j; unsigned long hash,nni; lh->num_nodes++; lh->num_expands++; p=(int)lh->p++; n1= &(lh->b[p]); n2= &(lh->b[p+(int)lh->pmax]); *n2=NULL; /* 27/07/92 - eay - undefined pointer bug */ nni=lh->num_alloc_nodes; for (np= *n1; np != NULL; ) { #ifndef OPENSSL_NO_HASH_COMP hash=np->hash; #else hash=lh->hash(np->data); lh->num_hash_calls++; #endif if ((hash%nni) != p) { /* move it */ *n1= (*n1)->next; np->next= *n2; *n2=np; } else n1= &((*n1)->next); np= *n1; } if ((lh->p) >= lh->pmax) { j=(int)lh->num_alloc_nodes*2; n=(LHASH_NODE **)OPENSSL_realloc(lh->b, (int)(sizeof(LHASH_NODE *)*j)); if (n == NULL) { /* fputs("realloc error in lhash",stderr); */ lh->error++; lh->p=0; return; } /* else */ for (i=(int)lh->num_alloc_nodes; i<j; i++)/* 26/02/92 eay */ n[i]=NULL; /* 02/03/92 eay */ lh->pmax=lh->num_alloc_nodes; lh->num_alloc_nodes=j; lh->num_expand_reallocs++; lh->p=0; lh->b=n; } } #if 0 /* STANDALONE */ static void contract(_LHASH *lh) { LHASH_NODE **n,*n1,*np; np=lh->b[lh->p+lh->pmax-1]; lh->b[lh->p+lh->pmax-1]=NULL; /* 24/07-92 - eay - weird but :-( */ if (lh->p == 0) { n=(LHASH_NODE **)OPENSSL_realloc(lh->b, (unsigned int)(sizeof(LHASH_NODE *)*lh->pmax)); if (n == NULL) { /* fputs("realloc error in lhash",stderr); */ lh->error++; return; } lh->num_contract_reallocs++; lh->num_alloc_nodes/=2; lh->pmax/=2; lh->p=lh->pmax-1; lh->b=n; } else lh->p--; lh->num_nodes--; lh->num_contracts++; n1=lh->b[(int)lh->p]; if (n1 == NULL) lh->b[(int)lh->p]=np; else { while (n1->next != NULL) n1=n1->next; n1->next=np; } } #endif /* STANDALONE */ static LHASH_NODE **getrn(_LHASH *lh, const void *data, unsigned long *rhash) { LHASH_NODE **ret,*n1; unsigned long hash,nn; LHASH_COMP_FN_TYPE cf; hash=(*(lh->hash))(data); lh->num_hash_calls++; *rhash=hash; nn=hash%lh->pmax; if (nn < lh->p) nn=hash%lh->num_alloc_nodes; cf=lh->comp; ret= &(lh->b[(int)nn]); for (n1= *ret; n1 != NULL; n1=n1->next) { #ifndef OPENSSL_NO_HASH_COMP lh->num_hash_comps++; if (n1->hash != hash) { ret= &(n1->next); continue; } #endif lh->num_comp_calls++; if(cf(n1->data,data) == 0) break; ret= &(n1->next); } return(ret); } /* The following hash seems to work very well on normal text strings * no collisions on /usr/dict/words and it distributes on %2^n quite * well, not as good as MD5, but still good. */ unsigned long lh_strhash(const char *c) { unsigned long ret=0; long n; unsigned long v; int r; if ((c == NULL) || (*c == '\0')) return(ret); /* unsigned char b[16]; MD5(c,strlen(c),b); return(b[0]|(b[1]<<8)|(b[2]<<16)|(b[3]<<24)); */ n=0x100; while (*c) { v=n|(*c); n+=0x100; r= (int)((v>>2)^v)&0x0f; ret=(ret<<r)|(ret>>(32-r)); ret&=0xFFFFFFFFL; ret^=v*v; c++; } return((ret>>16)^ret); } #if 0 /* STANDALONE */ unsigned long lh_num_items(const _LHASH *lh) { return lh ? lh->num_items : 0; } #endif /* STANDALONE */
709152.c
#include "ipc_user.h" int addUser(char *name, int fd, char *IP, unsigned short port, Usernode *top) { Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); int i; for (i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if (strcmp((&top[i])->name, name) == 0) { if (strcmp((&top[i])->IP, IP) != 0 || (&top[i])->is_online) return ERR_USER; else { (&top[i])->fd = fd; (&top[i])->port = port; (&top[i])->is_online = true; return OLD_USER; } } } if (i == MAX_USERS) return ERR_USER; Usernode *node = (Usernode *)calloc(1, sizeof(Usernode)); strncpy(node->name, name, BUF_SIZ); node->fd = fd; strncpy(node->IP, IP, INET6_ADDRSTRLEN); node->port = port; node->is_online = true; memcpy((&top[i]), node, sizeof(Usernode)); free(node); return NEW_USER; } void broadcast(int fd, Usernode *top) { char *from_name, *from_IP; unsigned short from_port; bool from_is_online; Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ((&top[i])->fd == fd) { from_name = (char *)calloc(1, strlen((&top[i])->name)+1); strcpy(from_name, (&top[i])->name); from_IP = (char *)calloc(1, strlen((&top[i])->IP)+1); strcpy(from_IP, (&top[i])->IP); from_port = (&top[i])->port; from_is_online = (&top[i])->is_online; break; } } char buf[BUF_SIZ] = ""; if (from_is_online) sprintf(buf, "<User %s is on-line, IP address: [%s]:%hu.>\n", from_name, from_IP, from_port); else sprintf(buf, "<User %s is off-line.>\n", from_name); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ( (&top[i])->fd != fd && (&top[i])->is_online ) strncpy((&top[i])->nowMsg, buf, BUF_SIZ);// sendall((&top[i])->fd, buf); } } void unicast(int fd, char *to_name, char *msg, Usernode *top) { Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); char *from_name; for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ((&top[i])->fd == fd) { from_name = (char *)calloc(1, strlen((&top[i])->name)+1); strcpy(from_name, (&top[i])->name); break; } } char buf[BUF_SIZ] = ""; for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if (strcmp((&top[i])->name, to_name) == 0) { if ((&top[i])->is_online) { sprintf(buf, "%s: \"%s\"\n", from_name, msg); // sendall((&top[i])->fd, buf); strncpy((&top[i])->nowMsg, buf, BUF_SIZ); } else { time_t rawtime; struct tm * timeinfo; char buffer[80] = ""; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer, 80, "%I:%M%p %Y/%m/%d", timeinfo); sprintf(buf, "<User %s has sent you a message \"%s\" at %s.>\n", from_name, msg, buffer); strncat((&top[i])->stMsg, buf, BUF_SIZ); memset(buf, 0, BUF_SIZ); sprintf(buf, "User %s is off-line. The message will be passed when he/she comes back.\n", to_name); sendall(fd, buf); } return; } } sprintf(buf, "<User %s does not exist.>\n", to_name); sendall(fd, buf); } void unicast_Offline(int fd, Usernode *top) { Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ((&top[i])->fd == fd) { if (strcmp((&top[i])->stMsg, "") != 0) { sendall(fd, (&top[i])->stMsg); memset((&top[i])->stMsg, 0, BUF_SIZ); } break; } } } void *unicast_Online(void *info) { Msgnode node = *(Msgnode *)info; int fd = (&node)->fd; Usernode *top = (&node)->top; int semid = (&node)->semid; struct sembuf grab = (&node)->grab; struct sembuf release = (&node)->release; Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); while(1) { if (semop(semid, &grab, 1) == -1) DIE("server.unicast_Online semop grab\n"); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ((&top[i])->fd == fd) { if (strcmp((&top[i])->nowMsg, "") != 0) { sendall(fd, (&top[i])->nowMsg); memset((&top[i])->nowMsg, 0, BUF_SIZ); } break; } } if (semop(semid, &release, 1) == -1) DIE("server.unicast_Online semop release\n"); } return NULL; } void logoutUser(int fd, Usernode *top) { Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; if ((&top[i])->fd == fd) { (&top[i])->is_online = false; break; } } } void showUser(Usernode *top) { Usernode tmp; memset(&tmp, 0, sizeof(Usernode)); for (int i=0; i<MAX_USERS; ++i) { if (memcmp(&tmp, (&top[i]), sizeof(Usernode)) == 0) break; printf("User: %s, [%s]:%hu, online: %d, fd: %d\n", (&top[i])->name, (&top[i])->IP, (&top[i])->port, (&top[i])->is_online, (&top[i])->fd); } printf("---------------------------\n"); }
280583.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putchar_fd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vpopovyc <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/26 22:22:37 by vpopovyc #+# #+# */ /* Updated: 2016/11/26 22:23:16 by vpopovyc ### ########.fr */ /* */ /* ************************************************************************** */ #include "includes/libft.h" void ft_putchar_fd(char c, int fd) { write(fd, &c, 1); }
600127.c
#include "Window.h" #include "String.h" #include "Platform.h" #include "Input.h" #include "Event.h" #include "Logger.h" #include "Funcs.h" #include "ExtMath.h" #include "Bitmap.h" #include "Options.h" #include "Errors.h" struct _DisplayData DisplayInfo; struct _WinData WindowInfo; int Display_ScaleX(int x) { return (int)(x * DisplayInfo.ScaleX); } int Display_ScaleY(int y) { return (int)(y * DisplayInfo.ScaleY); } #if defined CC_BUILD_IOS /* iOS implements these functions in external interop_ios.m file */ #define CC_MAYBE_OBJC1 extern #define CC_MAYBE_OBJC2 extern #define CC_OBJC_VISIBLE #elif defined CC_BUILD_COCOA /* Cocoa implements some functions in external interop_cocoa.m file */ #define CC_MAYBE_OBJC1 extern #define CC_MAYBE_OBJC2 static #define CC_OBJC_VISIBLE #else /* All other platforms implement internally in this file */ #define CC_MAYBE_OBJC1 static #define CC_MAYBE_OBJC2 static #define CC_OBJC_VISIBLE static #endif static int cursorPrevX, cursorPrevY; static cc_bool cursorVisible = true; /* Gets the position of the cursor in screen or window coordinates. */ CC_MAYBE_OBJC1 void Cursor_GetRawPos(int* x, int* y); CC_MAYBE_OBJC2 void Cursor_DoSetVisible(cc_bool visible); void Cursor_SetVisible(cc_bool visible) { if (cursorVisible == visible) return; cursorVisible = visible; Cursor_DoSetVisible(visible); } static void CentreMousePosition(void) { Cursor_SetPosition(WindowInfo.Width / 2, WindowInfo.Height / 2); /* Fixes issues with large DPI displays on Windows >= 8.0. */ Cursor_GetRawPos(&cursorPrevX, &cursorPrevY); } static void RegrabMouse(void) { if (!WindowInfo.Focused || !WindowInfo.Exists) return; CentreMousePosition(); } static void DefaultEnableRawMouse(void) { Input_RawMode = true; RegrabMouse(); Cursor_SetVisible(false); } static void DefaultUpdateRawMouse(void) { int x, y; Cursor_GetRawPos(&x, &y); Event_RaiseRawMove(&PointerEvents.RawMoved, x - cursorPrevX, y - cursorPrevY); CentreMousePosition(); } static void DefaultDisableRawMouse(void) { Input_RawMode = false; RegrabMouse(); Cursor_SetVisible(true); } /* The actual windowing system specific method to display a message box */ CC_MAYBE_OBJC1 void ShowDialogCore(const char* title, const char* msg); void Window_ShowDialog(const char* title, const char* msg) { /* Ensure cursor is visible while showing message box */ cc_bool visible = cursorVisible; if (!visible) Cursor_SetVisible(true); ShowDialogCore(title, msg); if (!visible) Cursor_SetVisible(false); } void OpenKeyboardArgs_Init(struct OpenKeyboardArgs* args, STRING_REF const cc_string* text, int type) { args->text = text; args->type = type; args->placeholder = ""; } struct GraphicsMode { int R, G, B, A, IsIndexed; }; /* Creates a GraphicsMode compatible with the default display device */ static void InitGraphicsMode(struct GraphicsMode* m) { int bpp = DisplayInfo.Depth; m->IsIndexed = bpp < 15; m->A = 0; switch (bpp) { case 32: m->R = 8; m->G = 8; m->B = 8; m->A = 8; break; case 24: m->R = 8; m->G = 8; m->B = 8; break; case 16: m->R = 5; m->G = 6; m->B = 5; break; case 15: m->R = 5; m->G = 5; m->B = 5; break; case 8: m->R = 3; m->G = 3; m->B = 2; break; case 4: m->R = 2; m->G = 2; m->B = 1; break; default: /* mode->R = 0; mode->G = 0; mode->B = 0; */ Logger_Abort2(bpp, "Unsupported bits per pixel"); break; } } /*########################################################################################################################* *-------------------------------------------------------SDL window--------------------------------------------------------* *#########################################################################################################################*/ #if defined CC_BUILD_SDL #include <SDL2/SDL.h> #include "Graphics.h" static SDL_Window* win_handle; static void RefreshWindowBounds(void) { SDL_GetWindowSize(win_handle, &WindowInfo.Width, &WindowInfo.Height); } static void Window_SDLFail(const char* place) { char strBuffer[256]; cc_string str; String_InitArray_NT(str, strBuffer); String_Format2(&str, "Error when %c: %c", place, SDL_GetError()); str.buffer[str.length] = '\0'; Logger_Abort(str.buffer); } void Window_Init(void) { printf("SDL2 Window_Init()\n"); SDL_DisplayMode mode = { 0 }; printf("SDL_DisplayMode mode\n"); SDL_Init(SDL_INIT_VIDEO); printf("SDL_Init()\n"); SDL_GetDesktopDisplayMode(0, &mode); printf("SDL_GetDesktopDisplayMode()\n"); DisplayInfo.Width = mode.w; DisplayInfo.Height = mode.h; DisplayInfo.Depth = SDL_BITSPERPIXEL(mode.format); DisplayInfo.ScaleX = 1; DisplayInfo.ScaleY = 1; } void Window_Create(int width, int height) { int x = Display_CentreX(width); int y = Display_CentreY(height); /* TODO: Don't set this flag for launcher window */ win_handle = SDL_CreateWindow(NULL, x, y, width, height, SDL_WINDOW_OPENGL); if (!win_handle) Window_SDLFail("creating window"); RefreshWindowBounds(); WindowInfo.Exists = true; WindowInfo.Handle = win_handle; } void Window_SetTitle(const cc_string* title) { char str[NATIVE_STR_LEN]; Platform_EncodeUtf8(str, title); SDL_SetWindowTitle(win_handle, str); } void Clipboard_GetText(cc_string* value) { char* ptr = SDL_GetClipboardText(); if (!ptr) return; int len = String_Length(ptr); String_AppendUtf8(value, ptr, len); SDL_free(ptr); } void Clipboard_SetText(const cc_string* value) { char str[NATIVE_STR_LEN]; Platform_EncodeUtf8(str, value); SDL_SetClipboardText(str); } void Window_Show(void) { SDL_ShowWindow(win_handle); } int Window_GetWindowState(void) { Uint32 flags = SDL_GetWindowFlags(win_handle); if (flags & SDL_WINDOW_MINIMIZED) return WINDOW_STATE_MINIMISED; if (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) return WINDOW_STATE_FULLSCREEN; return WINDOW_STATE_NORMAL; } cc_result Window_EnterFullscreen(void) { return SDL_SetWindowFullscreen(win_handle, SDL_WINDOW_FULLSCREEN_DESKTOP); } cc_result Window_ExitFullscreen(void) { SDL_RestoreWindow(win_handle); return 0; } void Window_SetSize(int width, int height) { SDL_SetWindowSize(win_handle, width, height); } void Window_Close(void) { SDL_Event e; e.type = SDL_QUIT; SDL_PushEvent(&e); } static int MapNativeKey(SDL_Keycode k) { if (k >= SDLK_0 && k <= SDLK_9) { return '0' + (k - SDLK_0); } if (k >= SDLK_a && k <= SDLK_z) { return 'A' + (k - SDLK_a); } if (k >= SDLK_F1 && k <= SDLK_F12) { return KEY_F1 + (k - SDLK_F1); } if (k >= SDLK_F13 && k <= SDLK_F24) { return KEY_F13 + (k - SDLK_F13); } /* SDLK_KP_0 isn't before SDLK_KP_1 */ if (k >= SDLK_KP_1 && k <= SDLK_KP_9) { return KEY_KP1 + (k - SDLK_KP_1); } switch (k) { case SDLK_RETURN: return KEY_ENTER; case SDLK_ESCAPE: return KEY_ESCAPE; case SDLK_BACKSPACE: return KEY_BACKSPACE; case SDLK_TAB: return KEY_TAB; case SDLK_SPACE: return KEY_SPACE; case SDLK_QUOTE: return KEY_QUOTE; case SDLK_EQUALS: return KEY_EQUALS; case SDLK_COMMA: return KEY_COMMA; case SDLK_MINUS: return KEY_MINUS; case SDLK_PERIOD: return KEY_PERIOD; case SDLK_SLASH: return KEY_SLASH; case SDLK_SEMICOLON: return KEY_SEMICOLON; case SDLK_LEFTBRACKET: return KEY_LBRACKET; case SDLK_BACKSLASH: return KEY_BACKSLASH; case SDLK_RIGHTBRACKET: return KEY_RBRACKET; case SDLK_BACKQUOTE: return KEY_TILDE; case SDLK_CAPSLOCK: return KEY_CAPSLOCK; case SDLK_PRINTSCREEN: return KEY_PRINTSCREEN; case SDLK_SCROLLLOCK: return KEY_SCROLLLOCK; case SDLK_PAUSE: return KEY_PAUSE; case SDLK_INSERT: return KEY_INSERT; case SDLK_HOME: return KEY_HOME; case SDLK_PAGEUP: return KEY_PAGEUP; case SDLK_DELETE: return KEY_DELETE; case SDLK_END: return KEY_END; case SDLK_PAGEDOWN: return KEY_PAGEDOWN; case SDLK_RIGHT: return KEY_RIGHT; case SDLK_LEFT: return KEY_LEFT; case SDLK_DOWN: return KEY_DOWN; case SDLK_UP: return KEY_UP; case SDLK_NUMLOCKCLEAR: return KEY_NUMLOCK; case SDLK_KP_DIVIDE: return KEY_KP_DIVIDE; case SDLK_KP_MULTIPLY: return KEY_KP_MULTIPLY; case SDLK_KP_MINUS: return KEY_KP_MINUS; case SDLK_KP_PLUS: return KEY_KP_PLUS; case SDLK_KP_ENTER: return KEY_KP_ENTER; case SDLK_KP_0: return KEY_KP0; case SDLK_KP_PERIOD: return KEY_KP_DECIMAL; case SDLK_LCTRL: return KEY_LCTRL; case SDLK_LSHIFT: return KEY_LSHIFT; case SDLK_LALT: return KEY_LALT; case SDLK_LGUI: return KEY_LWIN; case SDLK_RCTRL: return KEY_RCTRL; case SDLK_RSHIFT: return KEY_RSHIFT; case SDLK_RALT: return KEY_RALT; case SDLK_RGUI: return KEY_RWIN; } return KEY_NONE; } static void OnKeyEvent(const SDL_Event* e) { cc_bool pressed = e->key.state == SDL_PRESSED; int key = MapNativeKey(e->key.keysym.sym); if (key) Input_Set(key, pressed); } static void OnMouseEvent(const SDL_Event* e) { cc_bool pressed = e->button.state == SDL_PRESSED; int btn; switch (e->button.button) { case SDL_BUTTON_LEFT: btn = KEY_LMOUSE; break; case SDL_BUTTON_MIDDLE: btn = KEY_MMOUSE; break; case SDL_BUTTON_RIGHT: btn = KEY_RMOUSE; break; case SDL_BUTTON_X1: btn = KEY_XBUTTON1; break; case SDL_BUTTON_X2: btn = KEY_XBUTTON2; break; default: return; } Input_Set(btn, pressed); } static void OnTextEvent(const SDL_Event* e) { char buffer[SDL_TEXTINPUTEVENT_TEXT_SIZE]; cc_string str; int i, len; String_InitArray(str, buffer); len = String_CalcLen(e->text.text, SDL_TEXTINPUTEVENT_TEXT_SIZE); String_AppendUtf8(&str, e->text.text, len); for (i = 0; i < str.length; i++) { Event_RaiseInt(&InputEvents.Press, str.buffer[i]); } } static void OnWindowEvent(const SDL_Event* e) { switch (e->window.event) { case SDL_WINDOWEVENT_EXPOSED: Event_RaiseVoid(&WindowEvents.Redraw); break; case SDL_WINDOWEVENT_SIZE_CHANGED: RefreshWindowBounds(); Event_RaiseVoid(&WindowEvents.Resized); break; case SDL_WINDOWEVENT_MINIMIZED: case SDL_WINDOWEVENT_MAXIMIZED: case SDL_WINDOWEVENT_RESTORED: Event_RaiseVoid(&WindowEvents.StateChanged); break; case SDL_WINDOWEVENT_FOCUS_GAINED: WindowInfo.Focused = true; Event_RaiseVoid(&WindowEvents.FocusChanged); break; case SDL_WINDOWEVENT_FOCUS_LOST: WindowInfo.Focused = false; Event_RaiseVoid(&WindowEvents.FocusChanged); break; case SDL_WINDOWEVENT_CLOSE: Window_Close(); break; } } void Window_ProcessEvents(void) { SDL_Event e; while (SDL_PollEvent(&e)) { switch (e.type) { case SDL_KEYDOWN: case SDL_KEYUP: OnKeyEvent(&e); break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: OnMouseEvent(&e); break; case SDL_MOUSEWHEEL: Mouse_ScrollWheel(e.wheel.y); break; case SDL_MOUSEMOTION: Pointer_SetPosition(0, e.motion.x, e.motion.y); if (Input_RawMode) Event_RaiseRawMove(&PointerEvents.RawMoved, e.motion.xrel, e.motion.yrel); break; case SDL_TEXTINPUT: OnTextEvent(&e); break; case SDL_WINDOWEVENT: OnWindowEvent(&e); break; case SDL_QUIT: WindowInfo.Exists = false; Event_RaiseVoid(&WindowEvents.Closing); SDL_DestroyWindow(win_handle); break; case SDL_RENDER_DEVICE_RESET: Gfx_LoseContext("SDL device reset event"); Gfx_RecreateContext(); break; } } } static void Cursor_GetRawPos(int* x, int* y) { SDL_GetMouseState(x, y); } void Cursor_SetPosition(int x, int y) { SDL_WarpMouseInWindow(win_handle, x, y); } static void Cursor_DoSetVisible(cc_bool visible) { SDL_ShowCursor(visible ? SDL_ENABLE : SDL_DISABLE); } static void ShowDialogCore(const char* title, const char* msg) { SDL_ShowSimpleMessageBox(0, title, msg, win_handle); } static SDL_Surface* surface; void Window_AllocFramebuffer(struct Bitmap* bmp) { surface = SDL_GetWindowSurface(win_handle); if (!surface) Window_SDLFail("getting window surface"); if (SDL_MUSTLOCK(surface)) { int ret = SDL_LockSurface(surface); if (ret < 0) Window_SDLFail("locking window surface"); } bmp->scan0 = surface->pixels; } void Window_DrawFramebuffer(Rect2D r) { SDL_Rect rect; rect.x = r.X; rect.w = r.Width; rect.y = r.Y; rect.h = r.Height; SDL_UpdateWindowSurfaceRects(win_handle, &rect, 1); } void Window_FreeFramebuffer(struct Bitmap* bmp) { /* SDL docs explicitly say to NOT free the surface */ /* https://wiki.libsdl.org/SDL_GetWindowSurface */ /* TODO: Do we still need to unlock it though? */ } void Window_OpenKeyboard(const struct OpenKeyboardArgs* args) { SDL_StartTextInput(); } void Window_SetKeyboardText(const cc_string* text) { } void Window_CloseKeyboard(void) { SDL_StopTextInput(); } void Window_EnableRawMouse(void) { RegrabMouse(); SDL_SetRelativeMouseMode(true); Input_RawMode = true; } void Window_UpdateRawMouse(void) { CentreMousePosition(); } void Window_DisableRawMouse(void) { RegrabMouse(); SDL_SetRelativeMouseMode(false); Input_RawMode = false; } /*########################################################################################################################* *------------------------------------------------------Win32 window-------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_WINGUI #define WIN32_LEAN_AND_MEAN #define NOSERVICE #define NOMCX #define NOIME #ifndef UNICODE #define UNICODE #define _UNICODE #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 /* Windows XP */ /* NOTE: Functions that are not present on Windows 2000 are dynamically loaded. */ /* Hence the actual minimum supported OS is Windows 2000. This just avoids redeclaring structs. */ #endif #include <windows.h> #define CC_WIN_STYLE WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN #define CC_WIN_CLASSNAME TEXT("ClassiCube_Window") #define Rect_Width(rect) (rect.right - rect.left) #define Rect_Height(rect) (rect.bottom - rect.top) #ifndef WM_XBUTTONDOWN /* Missing if _WIN32_WINNT isn't defined */ #define WM_XBUTTONDOWN 0x020B #define WM_XBUTTONUP 0x020C #endif typedef BOOL (WINAPI *FUNC_RegisterRawInput)(PCRAWINPUTDEVICE devices, UINT numDevices, UINT size); static FUNC_RegisterRawInput _registerRawInput; typedef UINT (WINAPI *FUNC_GetRawInputData)(HRAWINPUT hRawInput, UINT cmd, void* data, UINT* size, UINT headerSize); static FUNC_GetRawInputData _getRawInputData; static HINSTANCE win_instance; static HWND win_handle; static HDC win_DC; static cc_bool suppress_resize; static int win_totalWidth, win_totalHeight; /* Size of window including titlebar and borders */ static int windowX, windowY; static cc_bool is_ansiWindow; static const cc_uint8 key_map[14 * 16] = { 0, 0, 0, 0, 0, 0, 0, 0, KEY_BACKSPACE, KEY_TAB, 0, 0, 0, KEY_ENTER, 0, 0, 0, 0, 0, KEY_PAUSE, KEY_CAPSLOCK, 0, 0, 0, 0, 0, 0, KEY_ESCAPE, 0, 0, 0, 0, KEY_SPACE, KEY_PAGEUP, KEY_PAGEDOWN, KEY_END, KEY_HOME, KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, 0, KEY_PRINTSCREEN, 0, KEY_PRINTSCREEN, KEY_INSERT, KEY_DELETE, 0, '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 0, 0, 0, 0, 0, 0, 0, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', KEY_LWIN, KEY_RWIN, KEY_MENU, 0, 0, KEY_KP0, KEY_KP1, KEY_KP2, KEY_KP3, KEY_KP4, KEY_KP5, KEY_KP6, KEY_KP7, KEY_KP8, KEY_KP9, KEY_KP_MULTIPLY, KEY_KP_PLUS, 0, KEY_KP_MINUS, KEY_KP_DECIMAL, KEY_KP_DIVIDE, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, KEY_F13, KEY_F14, KEY_F15, KEY_F16, KEY_F17, KEY_F18, KEY_F19, KEY_F20, KEY_F21, KEY_F22, KEY_F23, KEY_F24, 0, 0, 0, 0, 0, 0, 0, 0, KEY_NUMLOCK, KEY_SCROLLLOCK, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_LSHIFT, KEY_RSHIFT, KEY_LCTRL, KEY_RCTRL, KEY_LALT, KEY_RALT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_SEMICOLON, KEY_EQUALS, KEY_COMMA, KEY_MINUS, KEY_PERIOD, KEY_SLASH, KEY_TILDE, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_LBRACKET, KEY_BACKSLASH, KEY_RBRACKET, KEY_QUOTE, 0, }; static int MapNativeKey(WPARAM key, LPARAM meta) { LPARAM ext = meta & (1UL << 24); switch (key) { case VK_CONTROL: return ext ? KEY_RCTRL : KEY_LCTRL; case VK_MENU: return ext ? KEY_RALT : KEY_LALT; case VK_RETURN: return ext ? KEY_KP_ENTER : KEY_ENTER; default: return key < Array_Elems(key_map) ? key_map[key] : 0; } } static void RefreshWindowBounds(void) { RECT rect; POINT topLeft = { 0, 0 }; GetWindowRect(win_handle, &rect); win_totalWidth = Rect_Width(rect); win_totalHeight = Rect_Height(rect); GetClientRect(win_handle, &rect); WindowInfo.Width = Rect_Width(rect); WindowInfo.Height = Rect_Height(rect); /* GetClientRect always returns 0,0 for left,top (see MSDN) */ ClientToScreen(win_handle, &topLeft); windowX = topLeft.x; windowY = topLeft.y; } static LRESULT CALLBACK Window_Procedure(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) { char keyChar; float wheelDelta; switch (message) { case WM_ACTIVATE: WindowInfo.Focused = LOWORD(wParam) != 0; Event_RaiseVoid(&WindowEvents.FocusChanged); break; case WM_ERASEBKGND: return 1; /* Avoid flickering */ case WM_PAINT: ValidateRect(win_handle, NULL); Event_RaiseVoid(&WindowEvents.Redraw); return 0; case WM_WINDOWPOSCHANGED: { WINDOWPOS* pos = (WINDOWPOS*)lParam; if (pos->hwnd != win_handle) break; cc_bool sized = pos->cx != win_totalWidth || pos->cy != win_totalHeight; RefreshWindowBounds(); if (sized && !suppress_resize) Event_RaiseVoid(&WindowEvents.Resized); } break; case WM_SIZE: Event_RaiseVoid(&WindowEvents.StateChanged); break; case WM_CHAR: /* TODO: Use WM_UNICHAR instead, as WM_CHAR is just utf16 */ if (Convert_TryCodepointToCP437((cc_unichar)wParam, &keyChar)) { Event_RaiseInt(&InputEvents.Press, keyChar); } break; case WM_MOUSEMOVE: /* Set before position change, in case mouse buttons changed when outside window */ Input_SetNonRepeatable(KEY_LMOUSE, wParam & 0x01); Input_SetNonRepeatable(KEY_RMOUSE, wParam & 0x02); Input_SetNonRepeatable(KEY_MMOUSE, wParam & 0x10); /* TODO: do we need to set XBUTTON1/XBUTTON2 here */ Pointer_SetPosition(0, LOWORD(lParam), HIWORD(lParam)); break; case WM_MOUSEWHEEL: wheelDelta = ((short)HIWORD(wParam)) / (float)WHEEL_DELTA; Mouse_ScrollWheel(wheelDelta); return 0; case WM_LBUTTONDOWN: Input_SetPressed(KEY_LMOUSE); break; case WM_MBUTTONDOWN: Input_SetPressed(KEY_MMOUSE); break; case WM_RBUTTONDOWN: Input_SetPressed(KEY_RMOUSE); break; case WM_XBUTTONDOWN: Input_SetPressed(HIWORD(wParam) == 1 ? KEY_XBUTTON1 : KEY_XBUTTON2); break; case WM_LBUTTONUP: Input_SetReleased(KEY_LMOUSE); break; case WM_MBUTTONUP: Input_SetReleased(KEY_MMOUSE); break; case WM_RBUTTONUP: Input_SetReleased(KEY_RMOUSE); break; case WM_XBUTTONUP: Input_SetReleased(HIWORD(wParam) == 1 ? KEY_XBUTTON1 : KEY_XBUTTON2); break; case WM_INPUT: { RAWINPUT raw; UINT ret, rawSize = sizeof(RAWINPUT); int dx, dy; ret = _getRawInputData((HRAWINPUT)lParam, RID_INPUT, &raw, &rawSize, sizeof(RAWINPUTHEADER)); if (ret == -1 || raw.header.dwType != RIM_TYPEMOUSE) break; if (raw.data.mouse.usFlags == MOUSE_MOVE_RELATIVE) { dx = raw.data.mouse.lLastX; dy = raw.data.mouse.lLastY; } else if (raw.data.mouse.usFlags == MOUSE_MOVE_ABSOLUTE) { static int prevPosX, prevPosY; dx = raw.data.mouse.lLastX - prevPosX; dy = raw.data.mouse.lLastY - prevPosY; prevPosX = raw.data.mouse.lLastX; prevPosY = raw.data.mouse.lLastY; } else { break; } if (Input_RawMode) Event_RaiseRawMove(&PointerEvents.RawMoved, (float)dx, (float)dy); } break; case WM_KEYDOWN: case WM_KEYUP: case WM_SYSKEYDOWN: case WM_SYSKEYUP: { cc_bool pressed = message == WM_KEYDOWN || message == WM_SYSKEYDOWN; /* Shift/Control/Alt behave strangely when e.g. ShiftRight is held down and ShiftLeft is pressed and released. It looks like neither key is released in this case, or that the wrong key is released in the case of Control and Alt. To combat this, we are going to release both keys when either is released. Hacky, but should work. Win95 does not distinguish left/right key constants (GetAsyncKeyState returns 0). In this case, both keys will be reported as pressed. */ cc_bool lShiftDown, rShiftDown; int key; if (wParam == VK_SHIFT) { /* The behavior of this key is very strange. Unlike Control and Alt, there is no extended bit to distinguish between left and right keys. Moreover, pressing both keys and releasing one may result in both keys being held down (but not always).*/ lShiftDown = ((USHORT)GetKeyState(VK_LSHIFT)) >> 15; rShiftDown = ((USHORT)GetKeyState(VK_RSHIFT)) >> 15; if (!pressed || lShiftDown != rShiftDown) { Input_Set(KEY_LSHIFT, lShiftDown); Input_Set(KEY_RSHIFT, rShiftDown); } } else { key = MapNativeKey(wParam, lParam); if (key) Input_Set(key, pressed); else Platform_Log1("Unknown key: %x", &wParam); } return 0; } break; case WM_SYSCHAR: return 0; case WM_KILLFOCUS: /* TODO: Keep track of keyboard when focus is lost */ Input_Clear(); break; case WM_CLOSE: Event_RaiseVoid(&WindowEvents.Closing); if (WindowInfo.Exists) DestroyWindow(win_handle); WindowInfo.Exists = false; break; case WM_DESTROY: WindowInfo.Exists = false; UnregisterClassW(CC_WIN_CLASSNAME, win_instance); if (win_DC) ReleaseDC(win_handle, win_DC); break; } return is_ansiWindow ? DefWindowProcA(handle, message, wParam, lParam) : DefWindowProcW(handle, message, wParam, lParam); } /*########################################################################################################################* *--------------------------------------------------Public implementation--------------------------------------------------* *#########################################################################################################################*/ void Window_Init(void) { HDC hdc = GetDC(NULL); DisplayInfo.Width = GetSystemMetrics(SM_CXSCREEN); DisplayInfo.Height = GetSystemMetrics(SM_CYSCREEN); DisplayInfo.Depth = GetDeviceCaps(hdc, BITSPIXEL); DisplayInfo.ScaleX = GetDeviceCaps(hdc, LOGPIXELSX) / 96.0f; DisplayInfo.ScaleY = GetDeviceCaps(hdc, LOGPIXELSY) / 96.0f; ReleaseDC(NULL, hdc); } static ATOM DoRegisterClass(void) { ATOM atom; WNDCLASSEXW wc = { 0 }; wc.cbSize = sizeof(WNDCLASSEXW); wc.style = CS_OWNDC; wc.hInstance = win_instance; wc.lpfnWndProc = Window_Procedure; wc.lpszClassName = CC_WIN_CLASSNAME; wc.hIcon = (HICON)LoadImageA(win_instance, MAKEINTRESOURCEA(1), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0); wc.hIconSm = (HICON)LoadImageA(win_instance, MAKEINTRESOURCEA(1), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0); wc.hCursor = LoadCursorA(NULL, IDC_ARROW); if ((atom = RegisterClassExW(&wc))) return atom; /* Windows 9x does not support W API functions */ return RegisterClassExA((const WNDCLASSEXA*)&wc); } static void DoCreateWindow(ATOM atom, int width, int height) { cc_result res; RECT r; /* Calculate final window rectangle after window decorations are added (titlebar, borders etc) */ r.left = Display_CentreX(width); r.right = r.left + width; r.top = Display_CentreY(height); r.bottom = r.top + height; AdjustWindowRect(&r, CC_WIN_STYLE, false); if ((win_handle = CreateWindowExW(0, MAKEINTATOM(atom), NULL, CC_WIN_STYLE, r.left, r.top, Rect_Width(r), Rect_Height(r), NULL, NULL, win_instance, NULL))) return; res = GetLastError(); /* Windows 9x does not support W API functions */ if (res == ERROR_CALL_NOT_IMPLEMENTED) { is_ansiWindow = true; if ((win_handle = CreateWindowExA(0, MAKEINTATOM(atom), NULL, CC_WIN_STYLE, r.left, r.top, Rect_Width(r), Rect_Height(r), NULL, NULL, win_instance, NULL))) return; res = GetLastError(); } Logger_Abort2(res, "Failed to create window"); } void Window_Create(int width, int height) { ATOM atom; win_instance = GetModuleHandleA(NULL); /* TODO: UngroupFromTaskbar(); */ width = Display_ScaleX(width); height = Display_ScaleY(height); atom = DoRegisterClass(); DoCreateWindow(atom, width, height); RefreshWindowBounds(); win_DC = GetDC(win_handle); if (!win_DC) Logger_Abort2(GetLastError(), "Failed to get device context"); WindowInfo.Exists = true; WindowInfo.Handle = win_handle; } void Window_SetTitle(const cc_string* title) { WCHAR str[NATIVE_STR_LEN]; Platform_EncodeUtf16(str, title); if (SetWindowTextW(win_handle, str)) return; /* Windows 9x does not support W API functions */ Platform_Utf16ToAnsi(str); SetWindowTextA(win_handle, (const char*)str); } void Clipboard_GetText(cc_string* value) { cc_bool unicode; HANDLE hGlobal; LPVOID src; SIZE_T size; int i; /* retry up to 50 times */ for (i = 0; i < 50; i++) { if (!OpenClipboard(win_handle)) { Thread_Sleep(10); continue; } unicode = true; hGlobal = GetClipboardData(CF_UNICODETEXT); if (!hGlobal) { hGlobal = GetClipboardData(CF_TEXT); unicode = false; } if (!hGlobal) { CloseClipboard(); return; } src = GlobalLock(hGlobal); size = GlobalSize(hGlobal); /* ignore trailing NULL at end */ /* TODO: Verify it's always there */ if (unicode) { String_AppendUtf16(value, src, size - 2); } else { String_DecodeCP1252(value, src, size - 1); } GlobalUnlock(hGlobal); CloseClipboard(); return; } } void Clipboard_SetText(const cc_string* value) { cc_unichar* text; HANDLE hGlobal; int i; /* retry up to 10 times */ for (i = 0; i < 10; i++) { if (!OpenClipboard(win_handle)) { Thread_Sleep(100); continue; } hGlobal = GlobalAlloc(GMEM_MOVEABLE, (value->length + 1) * 2); if (!hGlobal) { CloseClipboard(); return; } text = (cc_unichar*)GlobalLock(hGlobal); for (i = 0; i < value->length; i++, text++) { *text = Convert_CP437ToUnicode(value->buffer[i]); } *text = '\0'; GlobalUnlock(hGlobal); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, hGlobal); CloseClipboard(); return; } } void Window_Show(void) { ShowWindow(win_handle, SW_SHOW); BringWindowToTop(win_handle); SetForegroundWindow(win_handle); } int Window_GetWindowState(void) { DWORD s = GetWindowLongW(win_handle, GWL_STYLE); if ((s & WS_MINIMIZE)) return WINDOW_STATE_MINIMISED; if ((s & WS_MAXIMIZE) && (s & WS_POPUP)) return WINDOW_STATE_FULLSCREEN; return WINDOW_STATE_NORMAL; } static void ToggleFullscreen(cc_bool fullscreen, UINT finalShow) { DWORD style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS; style |= (fullscreen ? WS_POPUP : WS_OVERLAPPEDWINDOW); suppress_resize = true; { ShowWindow(win_handle, SW_RESTORE); /* reset maximised state */ SetWindowLongW(win_handle, GWL_STYLE, style); SetWindowPos(win_handle, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); ShowWindow(win_handle, finalShow); Window_ProcessEvents(); } suppress_resize = false; /* call Resized event only once */ RefreshWindowBounds(); Event_RaiseVoid(&WindowEvents.Resized); } static UINT win_show; cc_result Window_EnterFullscreen(void) { WINDOWPLACEMENT w = { 0 }; w.length = sizeof(WINDOWPLACEMENT); GetWindowPlacement(win_handle, &w); win_show = w.showCmd; ToggleFullscreen(true, SW_MAXIMIZE); return 0; } cc_result Window_ExitFullscreen(void) { ToggleFullscreen(false, win_show); return 0; } void Window_SetSize(int width, int height) { DWORD style = GetWindowLongW(win_handle, GWL_STYLE); RECT rect = { 0, 0, width, height }; AdjustWindowRect(&rect, style, false); SetWindowPos(win_handle, NULL, 0, 0, Rect_Width(rect), Rect_Height(rect), SWP_NOMOVE); } void Window_Close(void) { PostMessageW(win_handle, WM_CLOSE, 0, 0); } void Window_ProcessEvents(void) { HWND foreground; MSG msg; if (is_ansiWindow) { while (PeekMessageA(&msg, NULL, 0, 0, 1)) { TranslateMessage(&msg); DispatchMessageA(&msg); } } else { while (PeekMessageW(&msg, NULL, 0, 0, 1)) { TranslateMessage(&msg); DispatchMessageW(&msg); } } foreground = GetForegroundWindow(); if (foreground) { WindowInfo.Focused = foreground == win_handle; } } static void Cursor_GetRawPos(int* x, int* y) { POINT point; GetCursorPos(&point); *x = point.x; *y = point.y; } void Cursor_SetPosition(int x, int y) { SetCursorPos(x + windowX, y + windowY); } static void Cursor_DoSetVisible(cc_bool visible) { int i; /* ShowCursor actually is a counter (returns > 0 if visible, <= 0 if not) */ /* Try multiple times in case cursor count was changed by something else */ if (visible) { for (i = 0; i < 10 && ShowCursor(true) < 0; i++) { } } else { for (i = 0; i < 10 && ShowCursor(false) >= 0; i++) {} } } static void ShowDialogCore(const char* title, const char* msg) { MessageBoxA(win_handle, msg, title, 0); } static HDC draw_DC; static HBITMAP draw_DIB; void Window_AllocFramebuffer(struct Bitmap* bmp) { BITMAPINFO hdr = { 0 }; if (!draw_DC) draw_DC = CreateCompatibleDC(win_DC); /* sizeof(BITMAPINFO) does not work on Windows 9x */ hdr.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); hdr.bmiHeader.biWidth = bmp->width; hdr.bmiHeader.biHeight = -bmp->height; hdr.bmiHeader.biBitCount = 32; hdr.bmiHeader.biPlanes = 1; draw_DIB = CreateDIBSection(draw_DC, &hdr, DIB_RGB_COLORS, (void**)&bmp->scan0, NULL, 0); if (!draw_DIB) Logger_Abort2(GetLastError(), "Failed to create DIB"); } void Window_DrawFramebuffer(Rect2D r) { HGDIOBJ oldSrc = SelectObject(draw_DC, draw_DIB); BitBlt(win_DC, r.X, r.Y, r.Width, r.Height, draw_DC, r.X, r.Y, SRCCOPY); SelectObject(draw_DC, oldSrc); } void Window_FreeFramebuffer(struct Bitmap* bmp) { DeleteObject(draw_DIB); } static cc_bool rawMouseInited, rawMouseSupported; static void InitRawMouse(void) { static const cc_string user32 = String_FromConst("USER32.DLL"); void* lib; RAWINPUTDEVICE rid; if ((lib = DynamicLib_Load2(&user32))) { _registerRawInput = (FUNC_RegisterRawInput)DynamicLib_Get2(lib, "RegisterRawInputDevices"); _getRawInputData = (FUNC_GetRawInputData) DynamicLib_Get2(lib, "GetRawInputData"); rawMouseSupported = _registerRawInput && _getRawInputData; } rawMouseSupported &= Options_GetBool(OPT_RAW_INPUT, true); if (!rawMouseSupported) { Platform_LogConst("## Raw input unsupported!"); return; } rid.usUsagePage = 1; /* HID_USAGE_PAGE_GENERIC; */ rid.usUsage = 2; /* HID_USAGE_GENERIC_MOUSE; */ rid.dwFlags = RIDEV_INPUTSINK; rid.hwndTarget = win_handle; if (_registerRawInput(&rid, 1, sizeof(rid))) return; Logger_SysWarn(GetLastError(), "initing raw mouse"); rawMouseSupported = false; } void Window_OpenKeyboard(const struct OpenKeyboardArgs* args) { } void Window_SetKeyboardText(const cc_string* text) { } void Window_CloseKeyboard(void) { } void Window_EnableRawMouse(void) { DefaultEnableRawMouse(); if (!rawMouseInited) InitRawMouse(); rawMouseInited = true; } void Window_UpdateRawMouse(void) { if (rawMouseSupported) { /* handled in WM_INPUT messages */ CentreMousePosition(); } else { DefaultUpdateRawMouse(); } } void Window_DisableRawMouse(void) { DefaultDisableRawMouse(); } /*########################################################################################################################* *-------------------------------------------------------X11 window--------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_X11 #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/XKBlib.h> #include <X11/extensions/XInput2.h> #ifdef X_HAVE_UTF8_STRING #define CC_BUILD_XIM /* XIM support based off details described in */ /* https://tedyin.com/posts/a-brief-intro-to-linux-input-method-framework/ */ #endif #define _NET_WM_STATE_REMOVE 0 #define _NET_WM_STATE_ADD 1 #define _NET_WM_STATE_TOGGLE 2 static Display* win_display; static Window win_rootWin, win_handle; static XVisualInfo win_visual; #ifdef CC_BUILD_XIM static XIM win_xim; static XIC win_xic; #endif static Atom wm_destroy, net_wm_state, net_wm_ping; static Atom net_wm_state_minimized; static Atom net_wm_state_fullscreen; static Atom xa_clipboard, xa_targets, xa_utf8_string, xa_data_sel; static Atom xa_atom = 4; static cc_bool grabCursor; static long win_eventMask = StructureNotifyMask | /* SubstructureNotifyMask | */ ExposureMask | KeyReleaseMask | KeyPressMask | KeymapStateMask | PointerMotionMask | FocusChangeMask | ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PropertyChangeMask; static int MapNativeKey(KeySym key, unsigned int state) { if (key >= XK_0 && key <= XK_9) { return '0' + (key - XK_0); } if (key >= XK_A && key <= XK_Z) { return 'A' + (key - XK_A); } if (key >= XK_a && key <= XK_z) { return 'A' + (key - XK_a); } if (key >= XK_F1 && key <= XK_F24) { return KEY_F1 + (key - XK_F1); } if (key >= XK_KP_0 && key <= XK_KP_9) { return KEY_KP0 + (key - XK_KP_0); } /* Same Num Lock behaviour as Windows and text editors */ if (key >= XK_KP_Home && key <= XK_KP_Delete && !(state & Mod2Mask)) { if (key == XK_KP_Home) return KEY_HOME; if (key == XK_KP_Up) return KEY_UP; if (key == XK_KP_Page_Up) return KEY_PAGEUP; if (key == XK_KP_Left) return KEY_LEFT; if (key == XK_KP_Insert) return KEY_INSERT; if (key == XK_KP_Right) return KEY_RIGHT; if (key == XK_KP_End) return KEY_END; if (key == XK_KP_Down) return KEY_DOWN; if (key == XK_KP_Page_Down) return KEY_PAGEDOWN; } /* A chromebook user reported issues with pressing some keys: */ /* tilde - "Unknown key press: (8000060, 800007E) */ /* quote - "Unknown key press: (8000027, 8000022) */ /* Note if 8000 is stripped, you get '0060' (XK_grave) and 0027 (XK_apostrophe) */ /* ChromeOS seems to also mask to 0xFFFF, so I also do so here */ /* https://chromium.googlesource.com/chromium/src/+/lkgr/ui/events/keycodes/keyboard_code_conversion_x.cc */ key &= 0xFFFF; switch (key) { case XK_Escape: return KEY_ESCAPE; case XK_Return: return KEY_ENTER; case XK_space: return KEY_SPACE; case XK_BackSpace: return KEY_BACKSPACE; case XK_Shift_L: return KEY_LSHIFT; case XK_Shift_R: return KEY_RSHIFT; case XK_Alt_L: return KEY_LALT; case XK_Alt_R: return KEY_RALT; case XK_Control_L: return KEY_LCTRL; case XK_Control_R: return KEY_RCTRL; case XK_Super_L: return KEY_LWIN; case XK_Super_R: return KEY_RWIN; case XK_Meta_L: return KEY_LWIN; case XK_Meta_R: return KEY_RWIN; case XK_Menu: return KEY_MENU; case XK_Tab: return KEY_TAB; case XK_minus: return KEY_MINUS; case XK_plus: return KEY_EQUALS; case XK_equal: return KEY_EQUALS; case XK_Caps_Lock: return KEY_CAPSLOCK; case XK_Num_Lock: return KEY_NUMLOCK; case XK_Pause: return KEY_PAUSE; case XK_Break: return KEY_PAUSE; case XK_Scroll_Lock: return KEY_SCROLLLOCK; case XK_Insert: return KEY_INSERT; case XK_Print: return KEY_PRINTSCREEN; case XK_Sys_Req: return KEY_PRINTSCREEN; case XK_backslash: return KEY_BACKSLASH; case XK_bar: return KEY_BACKSLASH; case XK_braceleft: return KEY_LBRACKET; case XK_bracketleft: return KEY_LBRACKET; case XK_braceright: return KEY_RBRACKET; case XK_bracketright: return KEY_RBRACKET; case XK_colon: return KEY_SEMICOLON; case XK_semicolon: return KEY_SEMICOLON; case XK_quoteright: return KEY_QUOTE; case XK_quotedbl: return KEY_QUOTE; case XK_quoteleft: return KEY_TILDE; case XK_asciitilde: return KEY_TILDE; case XK_comma: return KEY_COMMA; case XK_less: return KEY_COMMA; case XK_period: return KEY_PERIOD; case XK_greater: return KEY_PERIOD; case XK_slash: return KEY_SLASH; case XK_question: return KEY_SLASH; case XK_Left: return KEY_LEFT; case XK_Down: return KEY_DOWN; case XK_Right: return KEY_RIGHT; case XK_Up: return KEY_UP; case XK_Delete: return KEY_DELETE; case XK_Home: return KEY_HOME; case XK_End: return KEY_END; case XK_Page_Up: return KEY_PAGEUP; case XK_Page_Down: return KEY_PAGEDOWN; case XK_KP_Add: return KEY_KP_PLUS; case XK_KP_Subtract: return KEY_KP_MINUS; case XK_KP_Multiply: return KEY_KP_MULTIPLY; case XK_KP_Divide: return KEY_KP_DIVIDE; case XK_KP_Decimal: return KEY_KP_DECIMAL; case XK_KP_Insert: return KEY_KP0; case XK_KP_End: return KEY_KP1; case XK_KP_Down: return KEY_KP2; case XK_KP_Page_Down: return KEY_KP3; case XK_KP_Left: return KEY_KP4; case XK_KP_Begin: return KEY_KP5; case XK_KP_Right: return KEY_KP6; case XK_KP_Home: return KEY_KP7; case XK_KP_Up: return KEY_KP8; case XK_KP_Page_Up: return KEY_KP9; case XK_KP_Delete: return KEY_KP_DECIMAL; case XK_KP_Enter: return KEY_KP_ENTER; } return KEY_NONE; } /* NOTE: This may not be entirely accurate, because user can configure keycode mappings */ static const cc_uint8 keycodeMap[136] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_ESCAPE, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', KEY_MINUS, KEY_EQUALS, KEY_BACKSPACE, KEY_TAB, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', KEY_LBRACKET, KEY_RBRACKET, KEY_ENTER, KEY_LCTRL, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', KEY_SEMICOLON, KEY_QUOTE, KEY_TILDE, KEY_LSHIFT, KEY_BACKSLASH, 'Z', 'X', 'C', 'V', 'B', 'N', 'M', KEY_PERIOD, KEY_COMMA, KEY_SLASH, KEY_RSHIFT, KEY_KP_MULTIPLY, KEY_LALT, KEY_SPACE, KEY_CAPSLOCK, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_NUMLOCK, KEY_SCROLLLOCK, KEY_KP7, KEY_KP8, KEY_KP9, KEY_KP_MINUS, KEY_KP4, KEY_KP5, KEY_KP6, KEY_KP_PLUS, KEY_KP1, KEY_KP2, KEY_KP3, KEY_KP0, KEY_KP_DECIMAL, 0, 0, 0, KEY_F11, KEY_F12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_RALT, KEY_RCTRL, KEY_HOME, KEY_UP, KEY_PAGEUP, KEY_LEFT, KEY_RIGHT, KEY_END, KEY_DOWN, KEY_PAGEDOWN, KEY_INSERT, KEY_DELETE, 0, 0, 0, 0, 0, 0, 0, KEY_PAUSE, 0, 0, 0, 0, 0, KEY_LWIN, 0, KEY_RWIN }; static int MapNativeKeycode(unsigned int keycode) { return keycode < Array_Elems(keycodeMap) ? keycodeMap[keycode] : 0; } static void RegisterAtoms(void) { Display* display = win_display; wm_destroy = XInternAtom(display, "WM_DELETE_WINDOW", true); net_wm_state = XInternAtom(display, "_NET_WM_STATE", false); net_wm_ping = XInternAtom(display, "_NET_WM_PING", false); net_wm_state_minimized = XInternAtom(display, "_NET_WM_STATE_MINIMIZED", false); net_wm_state_fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", false); xa_clipboard = XInternAtom(display, "CLIPBOARD", false); xa_targets = XInternAtom(display, "TARGETS", false); xa_utf8_string = XInternAtom(display, "UTF8_STRING", false); xa_data_sel = XInternAtom(display, "CC_SEL_DATA", false); } static void RefreshWindowBounds(int width, int height) { if (width != WindowInfo.Width || height != WindowInfo.Height) { WindowInfo.Width = width; WindowInfo.Height = height; Event_RaiseVoid(&WindowEvents.Resized); } } typedef int (*X11_ErrorHandler)(Display* dpy, XErrorEvent* ev); typedef int (*X11_IOErrorHandler)(Display* dpy); static X11_ErrorHandler realXErrorHandler; static X11_IOErrorHandler realXIOErrorHandler; static void LogXErrorCore(const char* msg) { char traceBuffer[2048]; cc_string trace; Platform_LogConst(msg); String_InitArray(trace, traceBuffer); Logger_Backtrace(&trace, NULL); Platform_Log(traceBuffer, trace.length); } static int LogXError(Display* dpy, XErrorEvent* ev) { LogXErrorCore("== unhandled X11 error =="); return realXErrorHandler(dpy, ev); } static int LogXIOError(Display* dpy) { LogXErrorCore("== unhandled XIO error =="); return realXIOErrorHandler(dpy); } static void HookXErrors(void) { realXErrorHandler = XSetErrorHandler(LogXError); realXIOErrorHandler = XSetIOErrorHandler(LogXIOError); } /*########################################################################################################################* *--------------------------------------------------Public implementation--------------------------------------------------* *#########################################################################################################################*/ static XVisualInfo GLContext_SelectVisual(void); void Window_Init(void) { Display* display = XOpenDisplay(NULL); int screen; if (!display) Logger_Abort("Failed to open display"); screen = DefaultScreen(display); HookXErrors(); win_display = display; win_rootWin = RootWindow(display, screen); /* TODO: Use Xinerama and XRandR for querying these */ DisplayInfo.Width = DisplayWidth(display, screen); DisplayInfo.Height = DisplayHeight(display, screen); DisplayInfo.Depth = DefaultDepth(display, screen); DisplayInfo.ScaleX = 1; DisplayInfo.ScaleY = 1; } #ifdef CC_BUILD_ICON extern const long CCIcon_Data[]; extern const int CCIcon_Size; static void ApplyIcon(void) { Atom net_wm_icon = XInternAtom(win_display, "_NET_WM_ICON", false); Atom xa_cardinal = XInternAtom(win_display, "CARDINAL", false); XChangeProperty(win_display, win_handle, net_wm_icon, xa_cardinal, 32, PropModeReplace, CCIcon_Data, CCIcon_Size); } #else static void ApplyIcon(void) { } #endif void Window_Create(int width, int height) { XSetWindowAttributes attributes = { 0 }; XSizeHints hints = { 0 }; Atom protocols[2]; int supported, x, y; x = Display_CentreX(width); y = Display_CentreY(height); RegisterAtoms(); win_visual = GLContext_SelectVisual(); Platform_LogConst("Opening render window... "); attributes.colormap = XCreateColormap(win_display, win_rootWin, win_visual.visual, AllocNone); attributes.event_mask = win_eventMask; win_handle = XCreateWindow(win_display, win_rootWin, x, y, width, height, 0, win_visual.depth /* CopyFromParent*/, InputOutput, win_visual.visual, CWColormap | CWEventMask | CWBackPixel | CWBorderPixel, &attributes); if (!win_handle) Logger_Abort("XCreateWindow failed"); #ifdef CC_BUILD_XIM win_xim = XOpenIM(win_display, NULL, NULL, NULL); win_xic = XCreateIC(win_xim, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, win_handle, NULL); #endif /* Set hints to try to force WM to create window at requested x,y */ /* Without this, some WMs will instead place the window whereever */ hints.base_width = width; hints.base_height = height; hints.flags = PSize | PPosition; XSetWMNormalHints(win_display, win_handle, &hints); /* Register for window destroy notification */ protocols[0] = wm_destroy; protocols[1] = net_wm_ping; XSetWMProtocols(win_display, win_handle, protocols, 2); /* Request that auto-repeat is only set on devices that support it physically. This typically means that it's turned off for keyboards (which is what we want). We prefer this method over XAutoRepeatOff/On, because the latter needs to be reset before the program exits. */ XkbSetDetectableAutoRepeat(win_display, true, &supported); RefreshWindowBounds(width, height); WindowInfo.Exists = true; WindowInfo.Handle = (void*)win_handle; grabCursor = Options_GetBool(OPT_GRAB_CURSOR, false); /* So right name appears in e.g. Ubuntu Unity launchbar */ XClassHint hint = { 0 }; hint.res_name = GAME_APP_TITLE; hint.res_class = GAME_APP_TITLE; XSetClassHint(win_display, win_handle, &hint); ApplyIcon(); } void Window_SetTitle(const cc_string* title) { char str[NATIVE_STR_LEN]; Platform_EncodeUtf8(str, title); XStoreName(win_display, win_handle, str); } static char clipboard_copy_buffer[256]; static char clipboard_paste_buffer[256]; static cc_string clipboard_copy_text = String_FromArray(clipboard_copy_buffer); static cc_string clipboard_paste_text = String_FromArray(clipboard_paste_buffer); void Clipboard_GetText(cc_string* value) { Window owner = XGetSelectionOwner(win_display, xa_clipboard); int i; if (!owner) return; /* no window owner */ XConvertSelection(win_display, xa_clipboard, xa_utf8_string, xa_data_sel, win_handle, 0); clipboard_paste_text.length = 0; /* wait up to 1 second for SelectionNotify event to arrive */ for (i = 0; i < 100; i++) { Window_ProcessEvents(); if (clipboard_paste_text.length) { String_AppendString(value, &clipboard_paste_text); return; } else { Thread_Sleep(10); } } } void Clipboard_SetText(const cc_string* value) { String_Copy(&clipboard_copy_text, value); XSetSelectionOwner(win_display, xa_clipboard, win_handle, 0); } void Window_Show(void) { XMapWindow(win_display, win_handle); } int Window_GetWindowState(void) { cc_bool fullscreen = false, minimised = false; Atom prop_type; unsigned long items, after; int i, prop_format; Atom* data = NULL; XGetWindowProperty(win_display, win_handle, net_wm_state, 0, 256, false, xa_atom, &prop_type, &prop_format, &items, &after, &data); if (data) { for (i = 0; i < items; i++) { Atom atom = data[i]; if (atom == net_wm_state_minimized) { minimised = true; } else if (atom == net_wm_state_fullscreen) { fullscreen = true; } } XFree(data); } if (fullscreen) return WINDOW_STATE_FULLSCREEN; if (minimised) return WINDOW_STATE_MINIMISED; return WINDOW_STATE_NORMAL; } static void ToggleFullscreen(long op) { XEvent ev = { 0 }; ev.xclient.type = ClientMessage; ev.xclient.window = win_handle; ev.xclient.message_type = net_wm_state; ev.xclient.format = 32; ev.xclient.data.l[0] = op; ev.xclient.data.l[1] = net_wm_state_fullscreen; XSendEvent(win_display, win_rootWin, false, SubstructureRedirectMask | SubstructureNotifyMask, &ev); XSync(win_display, false); XRaiseWindow(win_display, win_handle); Window_ProcessEvents(); } cc_result Window_EnterFullscreen(void) { ToggleFullscreen(_NET_WM_STATE_ADD); return 0; } cc_result Window_ExitFullscreen(void) { ToggleFullscreen(_NET_WM_STATE_REMOVE); return 0; } void Window_SetSize(int width, int height) { XResizeWindow(win_display, win_handle, width, height); Window_ProcessEvents(); } void Window_Close(void) { XEvent ev = { 0 }; ev.type = ClientMessage; ev.xclient.format = 32; ev.xclient.display = win_display; ev.xclient.window = win_handle; ev.xclient.data.l[0] = wm_destroy; XSendEvent(win_display, win_handle, false, 0, &ev); XFlush(win_display); } static int MapNativeMouse(int button) { if (button == 1) return KEY_LMOUSE; if (button == 2) return KEY_MMOUSE; if (button == 3) return KEY_RMOUSE; if (button == 8) return KEY_XBUTTON1; if (button == 9) return KEY_XBUTTON2; return 0; } static int TryGetKey(XKeyEvent* ev) { KeySym keysym1 = XLookupKeysym(ev, 0); KeySym keysym2 = XLookupKeysym(ev, 1); int key = MapNativeKey(keysym1, ev->state); if (!key) key = MapNativeKey(keysym2, ev->state); if (key) return key; Platform_Log3("Unknown key %i (%x, %x)", &ev->keycode, &keysym1, &keysym2); /* The user may be using a keyboard layout such as cryllic - */ /* fallback to trying to conver the raw scancodes instead */ return MapNativeKeycode(ev->keycode); } static Atom Window_GetSelectionProperty(XEvent* e) { Atom prop = e->xselectionrequest.property; if (prop) return prop; /* For obsolete clients. See ICCCM spec, selections chapter for reasoning. */ return e->xselectionrequest.target; } static Bool FilterEvent(Display* d, XEvent* e, XPointer w) { return e->xany.window == (Window)w || !e->xany.window || /* KeymapNotify events don't have a window */ e->type == GenericEvent; /* For XInput events */ } static void HandleWMDestroy(void) { Platform_LogConst("Exit message received."); Event_RaiseVoid(&WindowEvents.Closing); /* sync and discard all events queued */ XSync(win_display, true); XDestroyWindow(win_display, win_handle); WindowInfo.Exists = false; } static void HandleWMPing(XEvent* e) { e->xany.window = win_rootWin; XSendEvent(win_display, win_rootWin, false, SubstructureRedirectMask | SubstructureNotifyMask, e); } static void HandleGenericEvent(XEvent* e); void Window_ProcessEvents(void) { XEvent e; Window focus; int focusRevert; int i, btn, key, status; while (WindowInfo.Exists) { if (!XCheckIfEvent(win_display, &e, FilterEvent, (XPointer)win_handle)) break; if (XFilterEvent(&e, None) == True) continue; switch (e.type) { case GenericEvent: HandleGenericEvent(&e); break; case ClientMessage: if (e.xclient.data.l[0] == wm_destroy) { HandleWMDestroy(); } else if (e.xclient.data.l[0] == net_wm_ping) { HandleWMPing(&e); } break; case DestroyNotify: Platform_LogConst("Window destroyed"); WindowInfo.Exists = false; break; case ConfigureNotify: RefreshWindowBounds(e.xconfigure.width, e.xconfigure.height); break; case Expose: if (e.xexpose.count == 0) Event_RaiseVoid(&WindowEvents.Redraw); break; case LeaveNotify: XGetInputFocus(win_display, &focus, &focusRevert); if (focus == PointerRoot) { WindowInfo.Focused = false; Event_RaiseVoid(&WindowEvents.FocusChanged); } break; case EnterNotify: XGetInputFocus(win_display, &focus, &focusRevert); if (focus == PointerRoot) { WindowInfo.Focused = true; Event_RaiseVoid(&WindowEvents.FocusChanged); } break; case KeyPress: { char data[64], c; key = TryGetKey(&e.xkey); if (key) Input_SetPressed(key); #ifdef CC_BUILD_XIM cc_codepoint cp; char* chars = data; status = Xutf8LookupString(win_xic, &e.xkey, data, Array_Elems(data), NULL, NULL); for (; status > 0; status -= i) { i = Convert_Utf8ToCodepoint(&cp, chars, status); if (!i) break; if (Convert_TryCodepointToCP437(cp, &c)) Event_RaiseInt(&InputEvents.Press, c); chars += i; } #else /* This only really works for latin keys (e.g. so some finnish keys still work) */ status = XLookupString(&e.xkey, data, Array_Elems(data), NULL, NULL); for (i = 0; i < status; i++) { if (!Convert_TryCodepointToCP437((cc_uint8)data[i], &c)) continue; Event_RaiseInt(&InputEvents.Press, c); } #endif } break; case KeyRelease: key = TryGetKey(&e.xkey); if (key) Input_SetReleased(key); break; case ButtonPress: btn = MapNativeMouse(e.xbutton.button); if (btn) Input_SetPressed(btn); else if (e.xbutton.button == 4) Mouse_ScrollWheel(+1); else if (e.xbutton.button == 5) Mouse_ScrollWheel(-1); break; case ButtonRelease: btn = MapNativeMouse(e.xbutton.button); if (btn) Input_SetReleased(btn); break; case MotionNotify: Pointer_SetPosition(0, e.xmotion.x, e.xmotion.y); break; case FocusIn: case FocusOut: /* Don't lose focus when another app grabs key or mouse */ if (e.xfocus.mode == NotifyGrab || e.xfocus.mode == NotifyUngrab) break; WindowInfo.Focused = e.type == FocusIn; Event_RaiseVoid(&WindowEvents.FocusChanged); /* TODO: Keep track of keyboard when focus is lost */ if (!WindowInfo.Focused) Input_Clear(); break; case MappingNotify: if (e.xmapping.request == MappingModifier || e.xmapping.request == MappingKeyboard) { Platform_LogConst("keybard mapping refreshed"); XRefreshKeyboardMapping(&e.xmapping); } break; case PropertyNotify: if (e.xproperty.atom == net_wm_state) { Event_RaiseVoid(&WindowEvents.StateChanged); } break; case SelectionNotify: clipboard_paste_text.length = 0; if (e.xselection.selection == xa_clipboard && e.xselection.target == xa_utf8_string && e.xselection.property == xa_data_sel) { Atom prop_type; int prop_format; unsigned long items, after; cc_uint8* data = NULL; XGetWindowProperty(win_display, win_handle, xa_data_sel, 0, 1024, false, 0, &prop_type, &prop_format, &items, &after, &data); XDeleteProperty(win_display, win_handle, xa_data_sel); if (data && items && prop_type == xa_utf8_string) { clipboard_paste_text.length = 0; String_AppendUtf8(&clipboard_paste_text, data, items); } if (data) XFree(data); } break; case SelectionRequest: { XEvent reply = { 0 }; reply.xselection.type = SelectionNotify; reply.xselection.send_event = true; reply.xselection.display = win_display; reply.xselection.requestor = e.xselectionrequest.requestor; reply.xselection.selection = e.xselectionrequest.selection; reply.xselection.target = e.xselectionrequest.target; reply.xselection.property = 0; reply.xselection.time = e.xselectionrequest.time; if (e.xselectionrequest.selection == xa_clipboard && e.xselectionrequest.target == xa_utf8_string && clipboard_copy_text.length) { reply.xselection.property = Window_GetSelectionProperty(&e); char str[800]; int len = Platform_EncodeUtf8(str, &clipboard_copy_text); XChangeProperty(win_display, reply.xselection.requestor, reply.xselection.property, xa_utf8_string, 8, PropModeReplace, (unsigned char*)str, len); } else if (e.xselectionrequest.selection == xa_clipboard && e.xselectionrequest.target == xa_targets) { reply.xselection.property = Window_GetSelectionProperty(&e); Atom data[2] = { xa_utf8_string, xa_targets }; XChangeProperty(win_display, reply.xselection.requestor, reply.xselection.property, xa_atom, 32, PropModeReplace, (unsigned char*)data, 2); } XSendEvent(win_display, e.xselectionrequest.requestor, true, 0, &reply); } break; } } } static void Cursor_GetRawPos(int* x, int* y) { Window rootW, childW; int childX, childY; unsigned int mask; XQueryPointer(win_display, win_rootWin, &rootW, &childW, x, y, &childX, &childY, &mask); } void Cursor_SetPosition(int x, int y) { XWarpPointer(win_display, None, win_handle, 0, 0, 0, 0, x, y); XFlush(win_display); /* TODO: not sure if XFlush call is necessary */ } static Cursor blankCursor; static void Cursor_DoSetVisible(cc_bool visible) { if (visible) { XUndefineCursor(win_display, win_handle); } else { if (!blankCursor) { char data = 0; XColor col = { 0 }; Pixmap pixmap = XCreateBitmapFromData(win_display, win_handle, &data, 1, 1); blankCursor = XCreatePixmapCursor(win_display, pixmap, pixmap, &col, &col, 0, 0); XFreePixmap(win_display, pixmap); } XDefineCursor(win_display, win_handle, blankCursor); } } /*########################################################################################################################* *-----------------------------------------------------X11 message box-----------------------------------------------------* *#########################################################################################################################*/ struct X11MessageBox { Window win; Display* dpy; GC gc; unsigned long white, black, background; unsigned long btnBorder, highlight, shadow; }; static unsigned long X11_Col(struct X11MessageBox* m, cc_uint8 r, cc_uint8 g, cc_uint8 b) { Colormap cmap = XDefaultColormap(m->dpy, DefaultScreen(m->dpy)); XColor col = { 0 }; col.red = r << 8; col.green = g << 8; col.blue = b << 8; col.flags = DoRed | DoGreen | DoBlue; XAllocColor(m->dpy, cmap, &col); return col.pixel; } static void X11MessageBox_Init(struct X11MessageBox* m) { m->black = BlackPixel(m->dpy, DefaultScreen(m->dpy)); m->white = WhitePixel(m->dpy, DefaultScreen(m->dpy)); m->background = X11_Col(m, 206, 206, 206); m->btnBorder = X11_Col(m, 60, 60, 60); m->highlight = X11_Col(m, 144, 144, 144); m->shadow = X11_Col(m, 49, 49, 49); m->win = XCreateSimpleWindow(m->dpy, DefaultRootWindow(m->dpy), 0, 0, 100, 100, 0, m->black, m->background); XSelectInput(m->dpy, m->win, ExposureMask | StructureNotifyMask | KeyReleaseMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask ); m->gc = XCreateGC(m->dpy, m->win, 0, NULL); XSetForeground(m->dpy, m->gc, m->black); XSetBackground(m->dpy, m->gc, m->background); } static void X11MessageBox_Free(struct X11MessageBox* m) { XFreeGC(m->dpy, m->gc); XDestroyWindow(m->dpy, m->win); } struct X11Textbox { int x, y, width, height; int lineHeight, descent; const char* text; }; static void X11Textbox_Measure(struct X11Textbox* t, XFontStruct* font) { cc_string str = String_FromReadonly(t->text), line; XCharStruct overall; int direction, ascent, descent, lines = 0; for (; str.length; lines++) { String_UNSAFE_SplitBy(&str, '\n', &line); XTextExtents(font, line.buffer, line.length, &direction, &ascent, &descent, &overall); t->width = max(overall.width, t->width); } t->lineHeight = ascent + descent; t->descent = descent; t->height = t->lineHeight * lines; } static void X11Textbox_Draw(struct X11Textbox* t, struct X11MessageBox* m) { cc_string str = String_FromReadonly(t->text), line; int y = t->y + t->lineHeight - t->descent; /* TODO: is -descent even right? */ for (; str.length; y += t->lineHeight) { String_UNSAFE_SplitBy(&str, '\n', &line); XDrawString(m->dpy, m->win, m->gc, t->x, y, line.buffer, line.length); } } struct X11Button { int x, y, width, height; cc_bool clicked; struct X11Textbox text; }; static void X11Button_Draw(struct X11Button* b, struct X11MessageBox* m) { struct X11Textbox* t; int begX, endX, begY, endY; XSetForeground(m->dpy, m->gc, m->btnBorder); XDrawRectangle(m->dpy, m->win, m->gc, b->x, b->y, b->width, b->height); t = &b->text; begX = b->x + 1; endX = b->x + b->width - 1; begY = b->y + 1; endY = b->y + b->height - 1; if (b->clicked) { XSetForeground(m->dpy, m->gc, m->highlight); XDrawRectangle(m->dpy, m->win, m->gc, begX, begY, endX - begX, endY - begY); } else { XSetForeground(m->dpy, m->gc, m->white); XDrawLine(m->dpy, m->win, m->gc, begX, begY, endX - 1, begY); XDrawLine(m->dpy, m->win, m->gc, begX, begY, begX, endY - 1); XSetForeground(m->dpy, m->gc, m->highlight); XDrawLine(m->dpy, m->win, m->gc, begX + 1, endY - 1, endX - 1, endY - 1); XDrawLine(m->dpy, m->win, m->gc, endX - 1, begY + 1, endX - 1, endY - 1); XSetForeground(m->dpy, m->gc, m->shadow); XDrawLine(m->dpy, m->win, m->gc, begX, endY, endX, endY); XDrawLine(m->dpy, m->win, m->gc, endX, begY, endX, endY); } XSetForeground(m->dpy, m->gc, m->black); t->x = b->x + b->clicked + (b->width - t->width) / 2; t->y = b->y + b->clicked + (b->height - t->height) / 2; X11Textbox_Draw(t, m); } static int X11Button_Contains(struct X11Button* b, int x, int y) { return x >= b->x && x < (b->x + b->width) && y >= b->y && y < (b->y + b->height); } static Bool X11_FilterEvent(Display* d, XEvent* e, XPointer w) { return e->xany.window == (Window)w; } static void X11_MessageBox(const char* title, const char* text, struct X11MessageBox* m) { struct X11Button ok = { 0 }; struct X11Textbox body = { 0 }; Atom protocols[2]; XFontStruct* font; int x, y, width, height; XSizeHints hints = { 0 }; int mouseX = -1, mouseY = -1, over; XEvent e; X11MessageBox_Init(m); XMapWindow(m->dpy, m->win); XStoreName(m->dpy, m->win, title); protocols[0] = XInternAtom(m->dpy, "WM_DELETE_WINDOW", false); protocols[1] = XInternAtom(m->dpy, "_NET_WM_PING", false); XSetWMProtocols(m->dpy, m->win, protocols, 2); font = XQueryFont(m->dpy, XGContextFromGC(m->gc)); if (!font) return; /* Compute size of widgets */ body.text = text; X11Textbox_Measure(&body, font); ok.text.text = "OK"; X11Textbox_Measure(&ok.text, font); ok.width = ok.text.width + 70; ok.height = ok.text.height + 10; /* Compute size and position of window */ width = body.width + 20; height = body.height + 20 + ok.height + 20; x = DisplayWidth (m->dpy, DefaultScreen(m->dpy))/2 - width/2; y = DisplayHeight(m->dpy, DefaultScreen(m->dpy))/2 - height/2; XMoveResizeWindow(m->dpy, m->win, x, y, width, height); /* Adjust bounds of widgets */ body.x = 10; body.y = 10; ok.x = width/2 - ok.width/2; ok.y = height - ok.height - 10; /* This marks the window as popup window of the main window */ /* http://tronche.com/gui/x/icccm/sec-4.html#WM_TRANSIENT_FOR */ /* Depending on WM, removes minimise and doesn't show in taskbar */ if (win_handle) XSetTransientForHint(m->dpy, m->win, win_handle); XFreeFontInfo(NULL, font, 1); XUnmapWindow(m->dpy, m->win); /* Make window non resizeable */ hints.flags = PSize | PMinSize | PMaxSize; hints.min_width = hints.max_width = hints.base_width = width; hints.min_height = hints.max_height = hints.base_height = height; XSetWMNormalHints(m->dpy, m->win, &hints); XMapRaised(m->dpy, m->win); XFlush(m->dpy); for (;;) { /* The naive solution is to use XNextEvent(m->dpy, &e) here. */ /* However this causes issues as that removes events that */ /* should have been delivered to the main game window. */ /* (e.g. breaks initial window resize with i3 WM) */ XIfEvent(m->dpy, &e, X11_FilterEvent, (XPointer)m->win); switch (e.type) { case ButtonPress: case ButtonRelease: if (e.xbutton.button != Button1) break; over = X11Button_Contains(&ok, mouseX, mouseY); if (ok.clicked && e.type == ButtonRelease) { if (over) return; } ok.clicked = e.type == ButtonPress && over; /* fallthrough to redraw window */ case Expose: case MapNotify: XClearWindow(m->dpy, m->win); X11Textbox_Draw(&body, m); X11Button_Draw(&ok, m); XFlush(m->dpy); break; case KeyRelease: if (XLookupKeysym(&e.xkey, 0) == XK_Escape) return; break; case ClientMessage: /* { WM_DELETE_WINDOW, _NET_WM_PING } */ if (e.xclient.data.l[0] == protocols[0]) return; if (e.xclient.data.l[0] == protocols[1]) HandleWMPing(&e); break; case MotionNotify: mouseX = e.xmotion.x; mouseY = e.xmotion.y; break; } } } static void ShowDialogCore(const char* title, const char* msg) { struct X11MessageBox m = { 0 }; m.dpy = win_display; /* Failing to create a display means can't display a message box. */ /* However the user might have launched the game through terminal, */ /* so fallback to console instead of just dying from a segfault */ if (!m.dpy) { Platform_LogConst("### MESSAGE ###"); Platform_LogConst(title); Platform_LogConst(msg); return; } X11_MessageBox(title, msg, &m); X11MessageBox_Free(&m); XFlush(m.dpy); /* flush so window disappears immediately */ } static GC fb_gc; static XImage* fb_image; void Window_AllocFramebuffer(struct Bitmap* bmp) { if (!fb_gc) fb_gc = XCreateGC(win_display, win_handle, 0, NULL); bmp->scan0 = (BitmapCol*)Mem_Alloc(bmp->width * bmp->height, 4, "window pixels"); fb_image = XCreateImage(win_display, win_visual.visual, win_visual.depth, ZPixmap, 0, (char*)bmp->scan0, bmp->width, bmp->height, 32, 0); } void Window_DrawFramebuffer(Rect2D r) { XPutImage(win_display, win_handle, fb_gc, fb_image, r.X, r.Y, r.X, r.Y, r.Width, r.Height); } void Window_FreeFramebuffer(struct Bitmap* bmp) { XFree(fb_image); Mem_Free(bmp->scan0); } void Window_OpenKeyboard(const struct OpenKeyboardArgs* args) { } void Window_SetKeyboardText(const cc_string* text) { } void Window_CloseKeyboard(void) { } static cc_bool rawMouseInited, rawMouseSupported; static int xiOpcode; static void CheckMovementDelta(double dx, double dy) { /* Despite the assumption that XI_RawMotion is relative, */ /* unfortunately there's a few buggy corner cases out there */ /* where absolute coordinates are provided instead. */ /* The ugly code belows tries to detect these corner cases, */ /* and disables XInput2 when that happens */ static int valid, fails; if (valid) return; /* The default window resolution is 854 x 480, so if there's */ /* a delta less than half of that, then it's almost certain */ /* that the provided coordinates are relative.*/ if (dx < 300 || dy < 200) { valid = true; return; } if (fails++ < 20) return; /* Checked over 20 times now, but no relative coordinates, */ /* so give up trying to use XInput2 anymore. */ Platform_LogConst("Buggy XInput2 detected, disabling it.."); rawMouseSupported = false; } static void HandleGenericEvent(XEvent* e) { const double* values; XIRawEvent* ev; double dx, dy; if (!rawMouseSupported || e->xcookie.extension != xiOpcode) return; if (!XGetEventData(win_display, &e->xcookie)) return; if (e->xcookie.evtype == XI_RawMotion && Input_RawMode) { ev = (XIRawEvent*)e->xcookie.data; values = ev->raw_values; /* Raw motion events may not always have values for both axes */ dx = XIMaskIsSet(ev->valuators.mask, 0) ? *values++ : 0; dy = XIMaskIsSet(ev->valuators.mask, 1) ? *values++ : 0; CheckMovementDelta(dx, dy); /* Using 0.5f here makes the sensitivity about same as normal cursor movement */ Event_RaiseRawMove(&PointerEvents.RawMoved, dx * 0.5f, dy * 0.5f); } XFreeEventData(win_display, &e->xcookie); } static void InitRawMouse(void) { XIEventMask evmask; unsigned char masks[XIMaskLen(XI_LASTEVENT)] = { 0 }; int ev, err, major, minor; if (!XQueryExtension(win_display, "XInputExtension", &xiOpcode, &ev, &err)) { Platform_LogConst("XInput unsupported"); return; } /* Only XInput 2.0 is actually required. However, 2.0 has the annoying */ /* behaviour where raw input is NOT delivered while pointer is grabbed. */ /* (i.e. if you press mouse button, no more raw mouse movement events) */ /* http://wine.1045685.n8.nabble.com/PATCH-0-9-Implement-DInput8-mouse-using-RawInput-and-XInput2-RawEvents-only-td6016923.html */ /* Thankfully XInput >= 2.1 corrects this behaviour */ /* http://who-t.blogspot.com/2011/09/whats-new-in-xi-21-raw-events.html */ major = 2; minor = 2; if (XIQueryVersion(win_display, &major, &minor) != Success) { Platform_Log2("Only XInput %i.%i supported", &major, &minor); return; } /* Sometimes XIQueryVersion will report Success, even though the */ /* supported version is only 2.0! So make sure to handle that. */ if (major < 2 || minor < 2) { Platform_Log2("Only XInput %i.%i supported", &major, &minor); return; } XISetMask(masks, XI_RawMotion); evmask.deviceid = XIAllMasterDevices; evmask.mask_len = sizeof(masks); evmask.mask = masks; XISelectEvents(win_display, win_rootWin, &evmask, 1); rawMouseSupported = true; } void Window_EnableRawMouse(void) { DefaultEnableRawMouse(); if (!rawMouseInited) InitRawMouse(); rawMouseInited = true; if (!grabCursor) return; XGrabPointer(win_display, win_handle, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, win_handle, blankCursor, CurrentTime); } void Window_UpdateRawMouse(void) { if (rawMouseSupported) { /* Handled by XI_RawMotion generic event */ CentreMousePosition(); } else { DefaultUpdateRawMouse(); } } void Window_DisableRawMouse(void) { DefaultDisableRawMouse(); if (!grabCursor) return; XUngrabPointer(win_display, CurrentTime); } /*########################################################################################################################* *---------------------------------------------------Carbon/Cocoa window---------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_CARBON || defined CC_BUILD_COCOA #include <ApplicationServices/ApplicationServices.h> CC_OBJC_VISIBLE int windowX, windowY; CC_OBJC_VISIBLE void Window_CommonInit(void) { CGDirectDisplayID display = CGMainDisplayID(); CGRect bounds = CGDisplayBounds(display); DisplayInfo.X = (int)bounds.origin.x; DisplayInfo.Y = (int)bounds.origin.y; DisplayInfo.Width = (int)bounds.size.width; DisplayInfo.Height = (int)bounds.size.height; DisplayInfo.Depth = CGDisplayBitsPerPixel(display); DisplayInfo.ScaleX = 1; DisplayInfo.ScaleY = 1; } static pascal OSErr HandleQuitMessage(const AppleEvent* ev, AppleEvent* reply, long handlerRefcon) { Window_Close(); return 0; } CC_OBJC_VISIBLE void Window_CommonCreate(void) { WindowInfo.Exists = true; /* for quit buttons in dock and menubar */ AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(HandleQuitMessage), 0, false); } /* Sourced from https://www.meandmark.com/keycodes.html */ static const cc_uint8 key_map[8 * 16] = { 'A', 'S', 'D', 'F', 'H', 'G', 'Z', 'X', 'C', 'V', 0, 'B', 'Q', 'W', 'E', 'R', 'Y', 'T', '1', '2', '3', '4', '6', '5', KEY_EQUALS, '9', '7', KEY_MINUS, '8', '0', KEY_RBRACKET, 'O', 'U', KEY_LBRACKET, 'I', 'P', KEY_ENTER, 'L', 'J', KEY_QUOTE, 'K', KEY_SEMICOLON, KEY_BACKSLASH, KEY_COMMA, KEY_SLASH, 'N', 'M', KEY_PERIOD, KEY_TAB, KEY_SPACE, KEY_TILDE, KEY_BACKSPACE, 0, KEY_ESCAPE, 0, 0, 0, KEY_CAPSLOCK, 0, 0, 0, 0, 0, 0, 0, KEY_KP_DECIMAL, 0, KEY_KP_MULTIPLY, 0, KEY_KP_PLUS, 0, KEY_NUMLOCK, 0, 0, 0, KEY_KP_DIVIDE, KEY_KP_ENTER, 0, KEY_KP_MINUS, 0, 0, KEY_KP_ENTER, KEY_KP0, KEY_KP1, KEY_KP2, KEY_KP3, KEY_KP4, KEY_KP5, KEY_KP6, KEY_KP7, 0, KEY_KP8, KEY_KP9, 'N', 'M', KEY_PERIOD, KEY_F5, KEY_F6, KEY_F7, KEY_F3, KEY_F8, KEY_F9, 0, KEY_F11, 0, KEY_F13, 0, KEY_F14, 0, KEY_F10, 0, KEY_F12, 'U', KEY_F15, KEY_INSERT, KEY_HOME, KEY_PAGEUP, KEY_DELETE, KEY_F4, KEY_END, KEY_F2, KEY_PAGEDOWN, KEY_F1, KEY_LEFT, KEY_RIGHT, KEY_DOWN, KEY_UP, 0, }; CC_OBJC_VISIBLE int MapNativeKey(UInt32 key) { return key < Array_Elems(key_map) ? key_map[key] : 0; } /* TODO: Check these.. */ /* case 0x37: return KEY_LWIN; */ /* case 0x38: return KEY_LSHIFT; */ /* case 0x3A: return KEY_LALT; */ /* case 0x3B: return Key_ControlLeft; */ /* TODO: Verify these differences from OpenTK */ /*Backspace = 51, (0x33, KEY_DELETE according to that link)*/ /*Return = 52, (0x34, ??? according to that link)*/ /*Menu = 110, (0x6E, ??? according to that link)*/ /* NOTE: All Pasteboard functions are OSX 10.3 or later */ static PasteboardRef Window_GetPasteboard(void) { PasteboardRef pbRef; OSStatus err = PasteboardCreate(kPasteboardClipboard, &pbRef); if (err) Logger_Abort2(err, "Creating Pasteboard reference"); PasteboardSynchronize(pbRef); return pbRef; } #define FMT_UTF8 CFSTR("public.utf8-plain-text") #define FMT_UTF16 CFSTR("public.utf16-plain-text") void Clipboard_GetText(cc_string* value) { PasteboardRef pbRef; ItemCount itemCount; PasteboardItemID itemID; CFDataRef outData; const UInt8* ptr; CFIndex len; OSStatus err; pbRef = Window_GetPasteboard(); err = PasteboardGetItemCount(pbRef, &itemCount); if (err) Logger_Abort2(err, "Getting item count from Pasteboard"); if (itemCount < 1) return; err = PasteboardGetItemIdentifier(pbRef, 1, &itemID); if (err) Logger_Abort2(err, "Getting item identifier from Pasteboard"); if (!(err = PasteboardCopyItemFlavorData(pbRef, itemID, FMT_UTF16, &outData))) { ptr = CFDataGetBytePtr(outData); len = CFDataGetLength(outData); if (ptr) String_AppendUtf16(value, ptr, len); } else if (!(err = PasteboardCopyItemFlavorData(pbRef, itemID, FMT_UTF8, &outData))) { ptr = CFDataGetBytePtr(outData); len = CFDataGetLength(outData); if (ptr) String_AppendUtf8(value, ptr, len); } } void Clipboard_SetText(const cc_string* value) { PasteboardRef pbRef; CFDataRef cfData; UInt8 str[800]; int len; OSStatus err; pbRef = Window_GetPasteboard(); err = PasteboardClear(pbRef); if (err) Logger_Abort2(err, "Clearing Pasteboard"); PasteboardSynchronize(pbRef); len = Platform_EncodeUtf8(str, value); cfData = CFDataCreate(NULL, str, len); if (!cfData) Logger_Abort("CFDataCreate() returned null pointer"); PasteboardPutItemFlavor(pbRef, 1, FMT_UTF8, cfData, 0); } void Cursor_SetPosition(int x, int y) { CGPoint point; point.x = x + windowX; point.y = y + windowY; CGDisplayMoveCursorToPoint(CGMainDisplayID(), point); } static void Cursor_DoSetVisible(cc_bool visible) { if (visible) { CGDisplayShowCursor(CGMainDisplayID()); } else { CGDisplayHideCursor(CGMainDisplayID()); } } void Window_OpenKeyboard(const struct OpenKeyboardArgs* args) { } void Window_SetKeyboardText(const cc_string* text) { } void Window_CloseKeyboard(void) { } void Window_EnableRawMouse(void) { DefaultEnableRawMouse(); CGAssociateMouseAndMouseCursorPosition(0); } void Window_UpdateRawMouse(void) { CentreMousePosition(); } void Window_DisableRawMouse(void) { CGAssociateMouseAndMouseCursorPosition(1); DefaultDisableRawMouse(); } /*########################################################################################################################* *------------------------------------------------------Carbon window------------------------------------------------------* *#########################################################################################################################*/ #if defined CC_BUILD_CARBON #include <Carbon/Carbon.h> static WindowRef win_handle; static cc_bool win_fullscreen, showingDialog; /* fullscreen is tied to OpenGL context unfortunately */ static cc_result GLContext_UnsetFullscreen(void); static cc_result GLContext_SetFullscreen(void); static void RefreshWindowBounds(void) { Rect r; if (win_fullscreen) return; /* TODO: kWindowContentRgn ??? */ GetWindowBounds(win_handle, kWindowGlobalPortRgn, &r); windowX = r.left; WindowInfo.Width = r.right - r.left; windowY = r.top; WindowInfo.Height = r.bottom - r.top; } static OSStatus Window_ProcessKeyboardEvent(EventRef inEvent) { UInt32 kind, code; int key; OSStatus res; kind = GetEventKind(inEvent); switch (kind) { case kEventRawKeyDown: case kEventRawKeyRepeat: case kEventRawKeyUp: res = GetEventParameter(inEvent, kEventParamKeyCode, typeUInt32, NULL, sizeof(UInt32), NULL, &code); if (res) Logger_Abort2(res, "Getting key button"); key = MapNativeKey(code); if (key) { Input_Set(key, kind != kEventRawKeyUp); } else { Platform_Log1("Ignoring unknown key %i", &code); } return eventNotHandledErr; case kEventRawKeyModifiersChanged: res = GetEventParameter(inEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(UInt32), NULL, &code); if (res) Logger_Abort2(res, "Getting key modifiers"); Input_Set(KEY_LCTRL, code & 0x1000); Input_Set(KEY_LALT, code & 0x0800); Input_Set(KEY_LSHIFT, code & 0x0200); Input_Set(KEY_LWIN, code & 0x0100); Input_Set(KEY_CAPSLOCK, code & 0x0400); return eventNotHandledErr; } return eventNotHandledErr; } static OSStatus Window_ProcessWindowEvent(EventRef inEvent) { int oldWidth, oldHeight; switch (GetEventKind(inEvent)) { case kEventWindowClose: WindowInfo.Exists = false; Event_RaiseVoid(&WindowEvents.Closing); return eventNotHandledErr; case kEventWindowClosed: WindowInfo.Exists = false; return 0; case kEventWindowBoundsChanged: oldWidth = WindowInfo.Width; oldHeight = WindowInfo.Height; RefreshWindowBounds(); if (oldWidth != WindowInfo.Width || oldHeight != WindowInfo.Height) { Event_RaiseVoid(&WindowEvents.Resized); } return eventNotHandledErr; case kEventWindowActivated: WindowInfo.Focused = true; Event_RaiseVoid(&WindowEvents.FocusChanged); return eventNotHandledErr; case kEventWindowDeactivated: WindowInfo.Focused = false; Event_RaiseVoid(&WindowEvents.FocusChanged); return eventNotHandledErr; case kEventWindowDrawContent: Event_RaiseVoid(&WindowEvents.Redraw); return eventNotHandledErr; } return eventNotHandledErr; } static OSStatus Window_ProcessMouseEvent(EventRef inEvent) { int mouseX, mouseY; HIPoint pt, raw; UInt32 kind; cc_bool down; EventMouseButton button; SInt32 delta; OSStatus res; res = GetEventParameter(inEvent, kEventParamMouseLocation, typeHIPoint, NULL, sizeof(HIPoint), NULL, &pt); /* this error comes up from the application event handler */ if (res && res != eventParameterNotFoundErr) { Logger_Abort2(res, "Getting mouse position"); } if (Input_RawMode) { raw.x = 0; raw.y = 0; GetEventParameter(inEvent, kEventParamMouseDelta, typeHIPoint, NULL, sizeof(HIPoint), NULL, &raw); Event_RaiseRawMove(&PointerEvents.RawMoved, raw.x, raw.y); } if (showingDialog) return eventNotHandledErr; mouseX = (int)pt.x; mouseY = (int)pt.y; /* kEventParamMouseLocation is in screen coordinates */ /* So need to make sure mouse click lies inside window */ /* Otherwise this breaks close/minimise/maximise in titlebar and dock */ if (!win_fullscreen) { mouseX -= windowX; mouseY -= windowY; if (mouseX < 0 || mouseX >= WindowInfo.Width) return eventNotHandledErr; if (mouseY < 0 || mouseY >= WindowInfo.Height) return eventNotHandledErr; } kind = GetEventKind(inEvent); switch (kind) { case kEventMouseDown: case kEventMouseUp: down = kind == kEventMouseDown; res = GetEventParameter(inEvent, kEventParamMouseButton, typeMouseButton, NULL, sizeof(EventMouseButton), NULL, &button); if (res) Logger_Abort2(res, "Getting mouse button"); switch (button) { case kEventMouseButtonPrimary: Input_Set(KEY_LMOUSE, down); break; case kEventMouseButtonSecondary: Input_Set(KEY_RMOUSE, down); break; case kEventMouseButtonTertiary: Input_Set(KEY_MMOUSE, down); break; } return eventNotHandledErr; case kEventMouseWheelMoved: res = GetEventParameter(inEvent, kEventParamMouseWheelDelta, typeSInt32, NULL, sizeof(SInt32), NULL, &delta); if (res) Logger_Abort2(res, "Getting mouse wheel delta"); Mouse_ScrollWheel(delta); return 0; case kEventMouseMoved: case kEventMouseDragged: Pointer_SetPosition(0, mouseX, mouseY); return eventNotHandledErr; } return eventNotHandledErr; } static OSStatus Window_ProcessTextEvent(EventRef inEvent) { UInt32 kind; EventRef keyEvent = NULL; UniChar chars[17] = { 0 }; char keyChar; int i; OSStatus res; kind = GetEventKind(inEvent); if (kind != kEventTextInputUnicodeForKeyEvent) return eventNotHandledErr; /* When command key is pressed, text input should be ignored */ res = GetEventParameter(inEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, NULL, sizeof(keyEvent), NULL, &keyEvent); if (!res && keyEvent) { UInt32 modifiers = 0; GetEventParameter(keyEvent, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(modifiers), NULL, &modifiers); if (modifiers & 0x0100) return eventNotHandledErr; } /* TODO: is the assumption we only get 1-4 characters always valid */ res = GetEventParameter(inEvent, kEventParamTextInputSendText, typeUnicodeText, NULL, 16 * sizeof(UniChar), NULL, chars); if (res) Logger_Abort2(res, "Getting text chars"); for (i = 0; i < 16 && chars[i]; i++) { /* TODO: UTF16 to codepoint conversion */ if (Convert_TryCodepointToCP437(chars[i], &keyChar)) { Event_RaiseInt(&InputEvents.Press, keyChar); } } return eventNotHandledErr; } static OSStatus Window_EventHandler(EventHandlerCallRef inCaller, EventRef inEvent, void* userData) { EventRecord record; switch (GetEventClass(inEvent)) { case kEventClassAppleEvent: /* Only event here is the apple event. */ Platform_LogConst("Processing apple event."); ConvertEventRefToEventRecord(inEvent, &record); AEProcessAppleEvent(&record); break; case kEventClassKeyboard: return Window_ProcessKeyboardEvent(inEvent); case kEventClassMouse: return Window_ProcessMouseEvent(inEvent); case kEventClassWindow: return Window_ProcessWindowEvent(inEvent); case kEventClassTextInput: return Window_ProcessTextEvent(inEvent); } return eventNotHandledErr; } typedef EventTargetRef (*GetMenuBarEventTarget_Func)(void); static void HookEvents(void) { static const EventTypeSpec winEventTypes[] = { { kEventClassKeyboard, kEventRawKeyDown }, { kEventClassKeyboard, kEventRawKeyRepeat }, { kEventClassKeyboard, kEventRawKeyUp }, { kEventClassKeyboard, kEventRawKeyModifiersChanged }, { kEventClassWindow, kEventWindowClose }, { kEventClassWindow, kEventWindowClosed }, { kEventClassWindow, kEventWindowBoundsChanged }, { kEventClassWindow, kEventWindowActivated }, { kEventClassWindow, kEventWindowDeactivated }, { kEventClassWindow, kEventWindowDrawContent }, { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }, { kEventClassAppleEvent, kEventAppleEvent } }; static const EventTypeSpec appEventTypes[] = { { kEventClassMouse, kEventMouseDown }, { kEventClassMouse, kEventMouseUp }, { kEventClassMouse, kEventMouseMoved }, { kEventClassMouse, kEventMouseDragged }, { kEventClassMouse, kEventMouseWheelMoved } }; GetMenuBarEventTarget_Func getMenuBarEventTarget; EventTargetRef target; target = GetWindowEventTarget(win_handle); InstallEventHandler(target, NewEventHandlerUPP(Window_EventHandler), Array_Elems(winEventTypes), winEventTypes, NULL, NULL); target = GetApplicationEventTarget(); InstallEventHandler(target, NewEventHandlerUPP(Window_EventHandler), Array_Elems(appEventTypes), appEventTypes, NULL, NULL); /* The code below is to get the menubar working. */ /* The documentation for 'RunApplicationEventLoop' states that it installs */ /* the standard application event handler which lets the menubar work. */ /* However, we cannot use that since the event loop is managed by us instead. */ /* Unfortunately, there is no proper API to duplicate that behaviour, so rely */ /* on the undocumented GetMenuBarEventTarget to achieve similar behaviour. */ /* TODO: This is wrong for PowerPC. But at least it doesn't crash or anything. */ #define _RTLD_DEFAULT ((void*)-2) getMenuBarEventTarget = DynamicLib_Get2(_RTLD_DEFAULT, "GetMenuBarEventTarget"); InstallStandardEventHandler(GetApplicationEventTarget()); /* TODO: Why does this not work properly until user activates another window */ /* Followup: Seems to be a bug in OSX http://www.sheepsystems.com/developers_blog/transformprocesstype--bette.html */ if (getMenuBarEventTarget) { InstallStandardEventHandler(getMenuBarEventTarget()); } else { Platform_LogConst("MenuBar won't work!"); } /* MenuRef menu = AcquireRootMenu(); */ /* InstallStandardEventHandler(GetMenuEventTarget(menu)); */ } /*########################################################################################################################* *--------------------------------------------------Public implementation--------------------------------------------------* *#########################################################################################################################*/ void Window_Init(void) { Window_CommonInit(); } /* Private CGS/CGL stuff */ typedef int CGSConnectionID; typedef int CGSWindowID; extern CGSConnectionID _CGSDefaultConnection(void); extern CGSWindowID GetNativeWindowFromWindowRef(WindowRef window); extern CGContextRef CGWindowContextCreate(CGSConnectionID conn, CGSWindowID win, void* opts); static CGSConnectionID conn; static CGSWindowID winId; #ifndef kCGBitmapByteOrder32Host /* Undefined in < 10.4 SDK. No issue since < 10.4 is only Big Endian PowerPC anyways */ #define kCGBitmapByteOrder32Host 0 #endif #ifdef CC_BUILD_ICON extern const int CCIcon_Data[]; extern const int CCIcon_Width, CCIcon_Height; static void ApplyIcon(void) { CGColorSpaceRef colSpace; CGDataProviderRef provider; CGImageRef image; colSpace = CGColorSpaceCreateDeviceRGB(); provider = CGDataProviderCreateWithData(NULL, CCIcon_Data, Bitmap_DataSize(CCIcon_Width, CCIcon_Height), NULL); image = CGImageCreate(CCIcon_Width, CCIcon_Height, 8, 32, CCIcon_Width * 4, colSpace, kCGBitmapByteOrder32Host | kCGImageAlphaLast, provider, NULL, 0, 0); SetApplicationDockTileImage(image); CGImageRelease(image); CGDataProviderRelease(provider); CGColorSpaceRelease(colSpace); } #else static void ApplyIcon(void) { } #endif void Window_Create(int width, int height) { Rect r; OSStatus res; ProcessSerialNumber psn; r.left = Display_CentreX(width); r.right = r.left + width; r.top = Display_CentreY(height); r.bottom = r.top + height; res = CreateNewWindow(kDocumentWindowClass, kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute | kWindowInWindowMenuAttribute | kWindowLiveResizeAttribute, &r, &win_handle); if (res) Logger_Abort2(res, "Creating window failed"); RefreshWindowBounds(); AcquireRootMenu(); GetCurrentProcess(&psn); SetFrontProcess(&psn); /* TODO: Use BringWindowToFront instead.. (look in the file which has RepositionWindow in it) !!!! */ HookEvents(); Window_CommonCreate(); WindowInfo.Handle = win_handle; conn = _CGSDefaultConnection(); winId = GetNativeWindowFromWindowRef(win_handle); ApplyIcon(); } void Window_SetTitle(const cc_string* title) { UInt8 str[NATIVE_STR_LEN]; CFStringRef titleCF; int len; /* TODO: This leaks memory, old title isn't released */ len = Platform_EncodeUtf8(str, title); titleCF = CFStringCreateWithBytes(kCFAllocatorDefault, str, len, kCFStringEncodingUTF8, false); SetWindowTitleWithCFString(win_handle, titleCF); } void Window_Show(void) { ShowWindow(win_handle); /* TODO: Do we actually need to reposition */ RepositionWindow(win_handle, NULL, kWindowCenterOnMainScreen); SelectWindow(win_handle); } int Window_GetWindowState(void) { if (win_fullscreen) return WINDOW_STATE_FULLSCREEN; if (IsWindowCollapsed(win_handle)) return WINDOW_STATE_MINIMISED; return WINDOW_STATE_NORMAL; } static void UpdateWindowState(void) { Event_RaiseVoid(&WindowEvents.StateChanged); RefreshWindowBounds(); Event_RaiseVoid(&WindowEvents.Resized); } cc_result Window_EnterFullscreen(void) { cc_result res = GLContext_SetFullscreen(); UpdateWindowState(); return res; } cc_result Window_ExitFullscreen(void) { cc_result res = GLContext_UnsetFullscreen(); UpdateWindowState(); return res; } void Window_SetSize(int width, int height) { SizeWindow(win_handle, width, height, true); } void Window_Close(void) { /* DisposeWindow only sends a kEventWindowClosed */ Event_RaiseVoid(&WindowEvents.Closing); if (WindowInfo.Exists) DisposeWindow(win_handle); WindowInfo.Exists = false; } void Window_ProcessEvents(void) { EventRef theEvent; EventTargetRef target = GetEventDispatcherTarget(); OSStatus res; for (;;) { res = ReceiveNextEvent(0, NULL, 0.0, true, &theEvent); if (res == eventLoopTimedOutErr) break; if (res) { Platform_Log1("Message Loop status: %i", &res); break; } if (!theEvent) break; SendEventToEventTarget(theEvent, target); ReleaseEvent(theEvent); } } static void Cursor_GetRawPos(int* x, int* y) { Point point; GetGlobalMouse(&point); *x = (int)point.h; *y = (int)point.v; } static void ShowDialogCore(const char* title, const char* msg) { CFStringRef titleCF = CFStringCreateWithCString(NULL, title, kCFStringEncodingASCII); CFStringRef msgCF = CFStringCreateWithCString(NULL, msg, kCFStringEncodingASCII); DialogRef dialog; DialogItemIndex itemHit; showingDialog = true; CreateStandardAlert(kAlertPlainAlert, titleCF, msgCF, NULL, &dialog); CFRelease(titleCF); CFRelease(msgCF); RunStandardAlert(dialog, NULL, &itemHit); showingDialog = false; } static CGrafPtr fb_port; static struct Bitmap fb_bmp; static CGColorSpaceRef colorSpace; void Window_AllocFramebuffer(struct Bitmap* bmp) { if (!fb_port) fb_port = GetWindowPort(win_handle); bmp->scan0 = Mem_Alloc(bmp->width * bmp->height, 4, "window pixels"); colorSpace = CGColorSpaceCreateDeviceRGB(); fb_bmp = *bmp; } void Window_DrawFramebuffer(Rect2D r) { CGContextRef context = NULL; CGDataProviderRef provider; CGImageRef image; CGRect rect; OSStatus err; /* Unfortunately CGImageRef is immutable, so changing the */ /* underlying data doesn't change what shows when drawing. */ /* TODO: Use QuickDraw alternative instead */ /* TODO: Only update changed bit.. */ rect.origin.x = 0; rect.origin.y = 0; rect.size.width = WindowInfo.Width; rect.size.height = WindowInfo.Height; err = QDBeginCGContext(fb_port, &context); if (err) Logger_Abort2(err, "Begin draw"); /* TODO: REPLACE THIS AWFUL HACK */ provider = CGDataProviderCreateWithData(NULL, fb_bmp.scan0, Bitmap_DataSize(fb_bmp.width, fb_bmp.height), NULL); image = CGImageCreate(fb_bmp.width, fb_bmp.height, 8, 32, fb_bmp.width * 4, colorSpace, kCGBitmapByteOrder32Host | kCGImageAlphaNoneSkipFirst, provider, NULL, 0, 0); CGContextDrawImage(context, rect, image); CGContextSynchronize(context); err = QDEndCGContext(fb_port, &context); if (err) Logger_Abort2(err, "End draw"); CGImageRelease(image); CGDataProviderRelease(provider); } void Window_FreeFramebuffer(struct Bitmap* bmp) { Mem_Free(bmp->scan0); CGColorSpaceRelease(colorSpace); } /*########################################################################################################################* *-------------------------------------------------------Cocoa window------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_COCOA /* NOTE: Mostly implemented in interop_cocoa.m */ #endif /*########################################################################################################################* *------------------------------------------------Emscripten canvas window-------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_WEB #include <emscripten/emscripten.h> #include <emscripten/html5.h> #include <emscripten/key_codes.h> #include "Game.h" extern int interop_CanvasWidth(void); extern int interop_CanvasHeight(void); extern int interop_ScreenWidth(void); extern int interop_ScreenHeight(void); static cc_bool keyboardOpen, needResize; static int RawDpiScale(int x) { return (int)(x * emscripten_get_device_pixel_ratio()); } static int GetScreenWidth(void) { return RawDpiScale(interop_ScreenWidth()); } static int GetScreenHeight(void) { return RawDpiScale(interop_ScreenHeight()); } static void UpdateWindowBounds(void) { int width = interop_CanvasWidth(); int height = interop_CanvasHeight(); if (width == WindowInfo.Width && height == WindowInfo.Height) return; WindowInfo.Width = width; WindowInfo.Height = height; Event_RaiseVoid(&WindowEvents.Resized); } static void SetFullscreenBounds(void) { int width = GetScreenWidth(); int height = GetScreenHeight(); emscripten_set_canvas_element_size("#canvas", width, height); } /* Browser only allows pointer lock requests in response to user input */ static void DeferredEnableRawMouse(void) { EmscriptenPointerlockChangeEvent status; if (!Input_RawMode) return; status.isActive = false; emscripten_get_pointerlock_status(&status); if (!status.isActive) emscripten_request_pointerlock("#canvas", false); } static EM_BOOL OnMouseWheel(int type, const EmscriptenWheelEvent* ev, void* data) { /* TODO: The scale factor isn't standardised.. is there a better way though? */ Mouse_ScrollWheel(-Math_Sign(ev->deltaY)); DeferredEnableRawMouse(); return true; } static EM_BOOL OnMouseButton(int type, const EmscriptenMouseEvent* ev, void* data) { cc_bool down = type == EMSCRIPTEN_EVENT_MOUSEDOWN; /* https://stackoverflow.com/questions/60895686/how-to-get-mouse-buttons-4-5-browser-back-browser-forward-working-in-firef */ switch (ev->button) { case 0: Input_Set(KEY_LMOUSE, down); break; case 1: Input_Set(KEY_MMOUSE, down); break; case 2: Input_Set(KEY_RMOUSE, down); break; case 3: Input_Set(KEY_XBUTTON1, down); break; case 4: Input_Set(KEY_XBUTTON2, down); break; } DeferredEnableRawMouse(); return true; } /* input coordinates are CSS pixels, remap to internal pixels */ static void RescaleXY(int* x, int* y) { double css_width, css_height; emscripten_get_element_css_size("#canvas", &css_width, &css_height); if (css_width && css_height) { *x = (int)(*x * WindowInfo.Width / css_width ); *y = (int)(*y * WindowInfo.Height / css_height); } else { /* If css width or height is 0, something is bogus */ /* Better to avoid divsision by 0 in that case though */ } } static EM_BOOL OnMouseMove(int type, const EmscriptenMouseEvent* ev, void* data) { int x, y, buttons = ev->buttons; /* Set before position change, in case mouse buttons changed when outside window */ Input_SetNonRepeatable(KEY_LMOUSE, buttons & 0x01); Input_SetNonRepeatable(KEY_RMOUSE, buttons & 0x02); Input_SetNonRepeatable(KEY_MMOUSE, buttons & 0x04); x = ev->targetX; y = ev->targetY; RescaleXY(&x, &y); Pointer_SetPosition(0, x, y); if (Input_RawMode) Event_RaiseRawMove(&PointerEvents.RawMoved, ev->movementX, ev->movementY); return true; } /* TODO: Also query mouse coordinates globally (in OnMouseMove) and reuse interop_AdjustXY here */ extern void interop_AdjustXY(int* x, int* y); static EM_BOOL OnTouchStart(int type, const EmscriptenTouchEvent* ev, void* data) { const EmscriptenTouchPoint* t; int i, x, y; for (i = 0; i < ev->numTouches; ++i) { t = &ev->touches[i]; if (!t->isChanged) continue; x = t->targetX; y = t->targetY; interop_AdjustXY(&x, &y); RescaleXY(&x, &y); Input_AddTouch(t->identifier, x, y); } /* Don't intercept touchstart events while keyboard is open, that way */ /* user can still touch to move the caret position in input textbox. */ return !keyboardOpen; } static EM_BOOL OnTouchMove(int type, const EmscriptenTouchEvent* ev, void* data) { const EmscriptenTouchPoint* t; int i, x, y; for (i = 0; i < ev->numTouches; ++i) { t = &ev->touches[i]; if (!t->isChanged) continue; x = t->targetX; y = t->targetY; interop_AdjustXY(&x, &y); RescaleXY(&x, &y); Input_UpdateTouch(t->identifier, x, y); } /* Don't intercept touchmove events while keyboard is open, that way */ /* user can still touch to move the caret position in input textbox. */ return !keyboardOpen; } static EM_BOOL OnTouchEnd(int type, const EmscriptenTouchEvent* ev, void* data) { const EmscriptenTouchPoint* t; int i, x, y; for (i = 0; i < ev->numTouches; ++i) { t = &ev->touches[i]; if (!t->isChanged) continue; x = t->targetX; y = t->targetY; interop_AdjustXY(&x, &y); RescaleXY(&x, &y); Input_RemoveTouch(t->identifier, x, y); } /* Don't intercept touchend events while keyboard is open, that way */ /* user can still touch to move the caret position in input textbox. */ return !keyboardOpen; } static EM_BOOL OnFocus(int type, const EmscriptenFocusEvent* ev, void* data) { WindowInfo.Focused = type == EMSCRIPTEN_EVENT_FOCUS; Event_RaiseVoid(&WindowEvents.FocusChanged); return true; } static EM_BOOL OnResize(int type, const EmscriptenUiEvent* ev, void *data) { UpdateWindowBounds(); needResize = true; return true; } /* This is only raised when going into fullscreen */ static EM_BOOL OnCanvasResize(int type, const void* reserved, void *data) { UpdateWindowBounds(); needResize = true; return false; } static EM_BOOL OnFullscreenChange(int type, const EmscriptenFullscreenChangeEvent* ev, void *data) { UpdateWindowBounds(); needResize = true; return false; } static const char* OnBeforeUnload(int type, const void* ev, void *data) { if (!Game_ShouldClose()) { /* Exit pointer lock, otherwise when you press Ctrl+W, the */ /* cursor remains invisible in the confirmation dialog */ emscripten_exit_pointerlock(); return "You have unsaved changes. Are you sure you want to quit?"; } Window_Close(); return NULL; } static int MapNativeKey(int k, int l) { if (k >= '0' && k <= '9') return k; if (k >= 'A' && k <= 'Z') return k; if (k >= DOM_VK_F1 && k <= DOM_VK_F24) { return KEY_F1 + (k - DOM_VK_F1); } if (k >= DOM_VK_NUMPAD0 && k <= DOM_VK_NUMPAD9) { return KEY_KP0 + (k - DOM_VK_NUMPAD0); } switch (k) { case DOM_VK_BACK_SPACE: return KEY_BACKSPACE; case DOM_VK_TAB: return KEY_TAB; case DOM_VK_RETURN: return l == DOM_KEY_LOCATION_NUMPAD ? KEY_KP_ENTER : KEY_ENTER; case DOM_VK_SHIFT: return l == DOM_KEY_LOCATION_RIGHT ? KEY_RSHIFT : KEY_LSHIFT; case DOM_VK_CONTROL: return l == DOM_KEY_LOCATION_RIGHT ? KEY_RCTRL : KEY_LCTRL; case DOM_VK_ALT: return l == DOM_KEY_LOCATION_RIGHT ? KEY_RALT : KEY_LALT; case DOM_VK_PAUSE: return KEY_PAUSE; case DOM_VK_CAPS_LOCK: return KEY_CAPSLOCK; case DOM_VK_ESCAPE: return KEY_ESCAPE; case DOM_VK_SPACE: return KEY_SPACE; case DOM_VK_PAGE_UP: return KEY_PAGEUP; case DOM_VK_PAGE_DOWN: return KEY_PAGEDOWN; case DOM_VK_END: return KEY_END; case DOM_VK_HOME: return KEY_HOME; case DOM_VK_LEFT: return KEY_LEFT; case DOM_VK_UP: return KEY_UP; case DOM_VK_RIGHT: return KEY_RIGHT; case DOM_VK_DOWN: return KEY_DOWN; case DOM_VK_PRINTSCREEN: return KEY_PRINTSCREEN; case DOM_VK_INSERT: return KEY_INSERT; case DOM_VK_DELETE: return KEY_DELETE; case DOM_VK_SEMICOLON: return KEY_SEMICOLON; case DOM_VK_EQUALS: return KEY_EQUALS; case DOM_VK_WIN: return l == DOM_KEY_LOCATION_RIGHT ? KEY_RWIN : KEY_LWIN; case DOM_VK_MULTIPLY: return KEY_KP_MULTIPLY; case DOM_VK_ADD: return KEY_KP_PLUS; case DOM_VK_SUBTRACT: return KEY_KP_MINUS; case DOM_VK_DECIMAL: return KEY_KP_DECIMAL; case DOM_VK_DIVIDE: return KEY_KP_DIVIDE; case DOM_VK_NUM_LOCK: return KEY_NUMLOCK; case DOM_VK_SCROLL_LOCK: return KEY_SCROLLLOCK; case DOM_VK_HYPHEN_MINUS: return KEY_MINUS; case DOM_VK_COMMA: return KEY_COMMA; case DOM_VK_PERIOD: return KEY_PERIOD; case DOM_VK_SLASH: return KEY_SLASH; case DOM_VK_BACK_QUOTE: return KEY_TILDE; case DOM_VK_OPEN_BRACKET: return KEY_LBRACKET; case DOM_VK_BACK_SLASH: return KEY_BACKSLASH; case DOM_VK_CLOSE_BRACKET: return KEY_RBRACKET; case DOM_VK_QUOTE: return KEY_QUOTE; /* chrome */ case 186: return KEY_SEMICOLON; case 187: return KEY_EQUALS; case 189: return KEY_MINUS; } return KEY_NONE; } static EM_BOOL OnKeyDown(int type, const EmscriptenKeyboardEvent* ev, void* data) { int key = MapNativeKey(ev->keyCode, ev->location); /* iOS safari still sends backspace key events, don't intercept those */ if (key == KEY_BACKSPACE && Input_TouchMode && keyboardOpen) return false; if (key) Input_SetPressed(key); DeferredEnableRawMouse(); if (!key) return false; /* If holding down Ctrl or Alt, keys aren't going to generate a KeyPress event anyways. */ /* This intercepts Ctrl+S etc. Ctrl+C and Ctrl+V are not intercepted for clipboard. */ /* NOTE: macOS uses Win (Command) key instead of Ctrl, have to account for that too */ if (Key_IsAltPressed()) return true; if (Key_IsWinPressed()) return key != 'C' && key != 'V'; if (Key_IsCtrlPressed()) return key != 'C' && key != 'V'; /* Space needs special handling, as intercepting this prevents the ' ' key press event */ /* But on Safari, space scrolls the page - so need to intercept when keyboard is NOT open */ if (key == KEY_SPACE) return !keyboardOpen; /* Must not intercept KeyDown for regular keys, otherwise KeyPress doesn't get raised. */ /* However, do want to prevent browser's behaviour on F11, F5, home etc. */ /* e.g. not preventing F11 means browser makes page fullscreen instead of just canvas */ return (key >= KEY_F1 && key <= KEY_F24) || (key >= KEY_UP && key <= KEY_RIGHT) || (key >= KEY_INSERT && key <= KEY_MENU) || (key >= KEY_ENTER && key <= KEY_NUMLOCK); } static EM_BOOL OnKeyUp(int type, const EmscriptenKeyboardEvent* ev, void* data) { int key = MapNativeKey(ev->keyCode, ev->location); if (key) Input_SetReleased(key); DeferredEnableRawMouse(); return key != KEY_NONE; } static EM_BOOL OnKeyPress(int type, const EmscriptenKeyboardEvent* ev, void* data) { char keyChar; DeferredEnableRawMouse(); /* When on-screen keyboard is open, we don't want to intercept any key presses, */ /* because they should be sent to the HTML text input instead. */ /* (Chrome for android sends keypresses sometimes for '0' to '9' keys) */ /* - If any keys are intercepted, this causes the HTML text input to become */ /* desynchronised from the chat/menu input widget the user sees in game. */ /* - This causes problems such as attempting to backspace all text later to */ /* not actually backspace everything. (because the HTML text input does not */ /* have these intercepted key presses in its text buffer) */ if (Input_TouchMode && keyboardOpen) return false; /* Safari on macOS still sends a keypress event, which must not be cancelled */ /* (otherwise copy/paste doesn't work, as it uses Win+C / Win+V) */ if (ev->metaKey) return false; if (Convert_TryCodepointToCP437(ev->charCode, &keyChar)) { Event_RaiseInt(&InputEvents.Press, keyChar); } return true; } /* Really old emscripten versions (e.g. 1.38.21) don't have this defined */ /* Can't just use "#window", newer versions switched to const int instead */ #ifndef EMSCRIPTEN_EVENT_TARGET_WINDOW #define EMSCRIPTEN_EVENT_TARGET_WINDOW "#window" #endif static void HookEvents(void) { emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnMouseWheel); emscripten_set_mousedown_callback("#canvas", NULL, 0, OnMouseButton); emscripten_set_mouseup_callback("#canvas", NULL, 0, OnMouseButton); emscripten_set_mousemove_callback("#canvas", NULL, 0, OnMouseMove); emscripten_set_fullscreenchange_callback("#canvas", NULL, 0, OnFullscreenChange); emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnFocus); emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnFocus); emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnResize); emscripten_set_beforeunload_callback( NULL, OnBeforeUnload); emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnKeyDown); emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnKeyUp); emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnKeyPress); emscripten_set_touchstart_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnTouchStart); emscripten_set_touchmove_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnTouchMove); emscripten_set_touchend_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnTouchEnd); emscripten_set_touchcancel_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, OnTouchEnd); } static void UnhookEvents(void) { emscripten_set_wheel_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_mousedown_callback("#canvas", NULL, 0, NULL); emscripten_set_mouseup_callback("#canvas", NULL, 0, NULL); emscripten_set_mousemove_callback("#canvas", NULL, 0, NULL); emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_beforeunload_callback( NULL, NULL); emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_touchstart_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_touchmove_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_touchend_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); emscripten_set_touchcancel_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, NULL, 0, NULL); } extern int interop_IsAndroid(void); extern int interop_IsIOS(void); extern void interop_AddClipboardListeners(void); extern void interop_ForceTouchPageLayout(void); void Window_Init(void) { int is_ios, droid; DisplayInfo.Width = GetScreenWidth(); DisplayInfo.Height = GetScreenHeight(); DisplayInfo.Depth = 24; DisplayInfo.ScaleX = emscripten_get_device_pixel_ratio(); DisplayInfo.ScaleY = DisplayInfo.ScaleX; interop_AddClipboardListeners(); droid = interop_IsAndroid(); is_ios = interop_IsIOS(); Input_SetTouchMode(is_ios || droid); /* iOS shifts the whole webpage up when opening chat, which causes problems */ /* as the chat/send butons are positioned at the top of the canvas - they */ /* get pushed offscreen and can't be used at all anymore. So handle this */ /* case specially by positioning them at the bottom instead for iOS. */ WindowInfo.SoftKeyboard = is_ios ? SOFT_KEYBOARD_SHIFT : SOFT_KEYBOARD_RESIZE; /* Let the webpage know it needs to force a mobile layout */ if (!Input_TouchMode) return; interop_ForceTouchPageLayout(); } extern void interop_InitContainer(void); void Window_Create(int width, int height) { WindowInfo.Exists = true; WindowInfo.Focused = true; HookEvents(); /* Let the webpage decide on initial bounds */ WindowInfo.Width = interop_CanvasWidth(); WindowInfo.Height = interop_CanvasHeight(); interop_InitContainer(); } extern void interop_SetPageTitle(const char* title); void Window_SetTitle(const cc_string* title) { char str[NATIVE_STR_LEN]; Platform_EncodeUtf8(str, title); interop_SetPageTitle(str); } static char pasteBuffer[512]; static cc_string pasteStr; EMSCRIPTEN_KEEPALIVE void Window_RequestClipboardText(void) { Event_RaiseInput(&InputEvents.Down, INPUT_CLIPBOARD_COPY, 0); } EMSCRIPTEN_KEEPALIVE void Window_StoreClipboardText(char* src) { String_InitArray(pasteStr, pasteBuffer); String_AppendUtf8(&pasteStr, src, String_CalcLen(src, 2048)); } EMSCRIPTEN_KEEPALIVE void Window_GotClipboardText(char* src) { Window_StoreClipboardText(src); Event_RaiseInput(&InputEvents.Down, INPUT_CLIPBOARD_PASTE, 0); } extern void interop_TryGetClipboardText(void); void Clipboard_GetText(cc_string* value) { /* Window_StoreClipboardText may or may not be called by this */ interop_TryGetClipboardText(); String_Copy(value, &pasteStr); pasteStr.length = 0; } extern void interop_TrySetClipboardText(const char* text); void Clipboard_SetText(const cc_string* value) { char str[NATIVE_STR_LEN]; Platform_EncodeUtf8(str, value); interop_TrySetClipboardText(str); } void Window_Show(void) { } int Window_GetWindowState(void) { EmscriptenFullscreenChangeEvent status = { 0 }; emscripten_get_fullscreen_status(&status); return status.isFullscreen ? WINDOW_STATE_FULLSCREEN : WINDOW_STATE_NORMAL; } extern int interop_GetContainerID(void); extern void interop_EnterFullscreen(void); cc_result Window_EnterFullscreen(void) { EmscriptenFullscreenStrategy strategy; const char* target; int res; strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH; strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_HIDEF; strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT; strategy.canvasResizedCallback = OnCanvasResize; strategy.canvasResizedCallbackUserData = NULL; /* TODO: Return container element ID instead of hardcoding here */ res = interop_GetContainerID(); target = res ? "canvas_wrapper" : "#canvas"; res = emscripten_request_fullscreen_strategy(target, 1, &strategy); if (res == EMSCRIPTEN_RESULT_NOT_SUPPORTED) res = ERR_NOT_SUPPORTED; if (res) return res; interop_EnterFullscreen(); return 0; } cc_result Window_ExitFullscreen(void) { emscripten_exit_fullscreen(); UpdateWindowBounds(); return 0; } void Window_SetSize(int width, int height) { emscripten_set_canvas_element_size("#canvas", width, height); /* CSS size is in CSS units not pixel units */ emscripten_set_element_css_size("#canvas", width / DisplayInfo.ScaleX, height / DisplayInfo.ScaleY); UpdateWindowBounds(); } void Window_Close(void) { WindowInfo.Exists = false; Event_RaiseVoid(&WindowEvents.Closing); /* If the game is closed while in fullscreen, the last rendered frame stays */ /* shown in fullscreen, but the game can't be interacted with anymore */ Window_ExitFullscreen(); /* Don't want cursor stuck on the dead 0,0 canvas */ Window_DisableRawMouse(); Window_SetSize(0, 0); UnhookEvents(); } extern void interop_RequestCanvasResize(void); void Window_ProcessEvents(void) { if (!needResize) return; needResize = false; if (!WindowInfo.Exists) return; if (Window_GetWindowState() == WINDOW_STATE_FULLSCREEN) { SetFullscreenBounds(); } else { /* Webpage can adjust canvas size if it wants to */ interop_RequestCanvasResize(); } UpdateWindowBounds(); } /* Not needed because browser provides relative mouse and touch events */ static void Cursor_GetRawPos(int* x, int* y) { *x = 0; *y = 0; } /* Not allowed to move cursor from javascript */ void Cursor_SetPosition(int x, int y) { } extern void interop_SetCursorVisible(int visible); static void Cursor_DoSetVisible(cc_bool visible) { interop_SetCursorVisible(visible); } extern void interop_ShowDialog(const char* title, const char* msg); static void ShowDialogCore(const char* title, const char* msg) { interop_ShowDialog(title, msg); } static OpenFileDialogCallback uploadCallback; EMSCRIPTEN_KEEPALIVE void Window_OnFileUploaded(const char* src) { cc_string file; char buffer[FILENAME_SIZE]; String_InitArray(file, buffer); String_AppendUtf8(&file, src, String_Length(src)); uploadCallback(&file); uploadCallback = NULL; } extern void interop_OpenFileDialog(const char* filter); cc_result Window_OpenFileDialog(const char* filter, OpenFileDialogCallback callback) { uploadCallback = callback; /* Calls Window_OnFileUploaded on success */ interop_OpenFileDialog(filter); return ERR_NOT_SUPPORTED; } void Window_AllocFramebuffer(struct Bitmap* bmp) { } void Window_DrawFramebuffer(Rect2D r) { } void Window_FreeFramebuffer(struct Bitmap* bmp) { } extern void interop_OpenKeyboard(const char* text, int type, const char* placeholder); extern void interop_SetKeyboardText(const char* text); extern void interop_CloseKeyboard(void); EMSCRIPTEN_KEEPALIVE void Window_OnTextChanged(const char* src) { cc_string str; char buffer[800]; String_InitArray(str, buffer); String_AppendUtf8(&str, src, String_CalcLen(src, 3200)); Event_RaiseString(&InputEvents.TextChanged, &str); } void Window_OpenKeyboard(const struct OpenKeyboardArgs* args) { char str[NATIVE_STR_LEN]; keyboardOpen = true; if (!Input_TouchMode) return; Platform_EncodeUtf8(str, args->text); Platform_LogConst("OPEN SESAME"); interop_OpenKeyboard(str, args->type, args->placeholder); } void Window_SetKeyboardText(const cc_string* text) { char str[NATIVE_STR_LEN]; if (!Input_TouchMode) return; Platform_EncodeUtf8(str, text); interop_SetKeyboardText(str); } void Window_CloseKeyboard(void) { keyboardOpen = false; if (!Input_TouchMode) return; interop_CloseKeyboard(); } void Window_EnableRawMouse(void) { RegrabMouse(); /* defer pointerlock request until next user input */ Input_RawMode = true; } void Window_UpdateRawMouse(void) { } void Window_DisableRawMouse(void) { RegrabMouse(); emscripten_exit_pointerlock(); Input_RawMode = false; } /*########################################################################################################################* *------------------------------------------------Android activity window-------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_ANDROID #include <android/native_window.h> #include <android/native_window_jni.h> #include <android/keycodes.h> static ANativeWindow* win_handle; static void RefreshWindowBounds(void) { WindowInfo.Width = ANativeWindow_getWidth(win_handle); WindowInfo.Height = ANativeWindow_getHeight(win_handle); Platform_Log2("SCREEN BOUNDS: %i,%i", &WindowInfo.Width, &WindowInfo.Height); Event_RaiseVoid(&WindowEvents.Resized); } static int MapNativeKey(int code) { if (code >= AKEYCODE_0 && code <= AKEYCODE_9) return (code - AKEYCODE_0) + '0'; if (code >= AKEYCODE_A && code <= AKEYCODE_Z) return (code - AKEYCODE_A) + 'A'; if (code >= AKEYCODE_F1 && code <= AKEYCODE_F12) return (code - AKEYCODE_F1) + KEY_F1; if (code >= AKEYCODE_NUMPAD_0 && code <= AKEYCODE_NUMPAD_9) return (code - AKEYCODE_NUMPAD_0) + KEY_KP0; switch (code) { /* TODO: AKEYCODE_STAR */ /* TODO: AKEYCODE_POUND */ case AKEYCODE_BACK: return KEY_ESCAPE; case AKEYCODE_COMMA: return KEY_COMMA; case AKEYCODE_PERIOD: return KEY_PERIOD; case AKEYCODE_ALT_LEFT: return KEY_LALT; case AKEYCODE_ALT_RIGHT: return KEY_RALT; case AKEYCODE_SHIFT_LEFT: return KEY_LSHIFT; case AKEYCODE_SHIFT_RIGHT: return KEY_RSHIFT; case AKEYCODE_TAB: return KEY_TAB; case AKEYCODE_SPACE: return KEY_SPACE; case AKEYCODE_ENTER: return KEY_ENTER; case AKEYCODE_DEL: return KEY_BACKSPACE; case AKEYCODE_GRAVE: return KEY_TILDE; case AKEYCODE_MINUS: return KEY_MINUS; case AKEYCODE_EQUALS: return KEY_EQUALS; case AKEYCODE_LEFT_BRACKET: return KEY_LBRACKET; case AKEYCODE_RIGHT_BRACKET: return KEY_RBRACKET; case AKEYCODE_BACKSLASH: return KEY_BACKSLASH; case AKEYCODE_SEMICOLON: return KEY_SEMICOLON; case AKEYCODE_APOSTROPHE: return KEY_QUOTE; case AKEYCODE_SLASH: return KEY_SLASH; /* TODO: AKEYCODE_AT */ /* TODO: AKEYCODE_PLUS */ /* TODO: AKEYCODE_MENU */ case AKEYCODE_PAGE_UP: return KEY_PAGEUP; case AKEYCODE_PAGE_DOWN: return KEY_PAGEDOWN; case AKEYCODE_ESCAPE: return KEY_ESCAPE; case AKEYCODE_FORWARD_DEL: return KEY_DELETE; case AKEYCODE_CTRL_LEFT: return KEY_LCTRL; case AKEYCODE_CTRL_RIGHT: return KEY_RCTRL; case AKEYCODE_CAPS_LOCK: return KEY_CAPSLOCK; case AKEYCODE_SCROLL_LOCK: return KEY_SCROLLLOCK; case AKEYCODE_META_LEFT: return KEY_LWIN; case AKEYCODE_META_RIGHT: return KEY_RWIN; case AKEYCODE_SYSRQ: return KEY_PRINTSCREEN; case AKEYCODE_BREAK: return KEY_PAUSE; case AKEYCODE_INSERT: return KEY_INSERT; case AKEYCODE_NUM_LOCK: return KEY_NUMLOCK; case AKEYCODE_NUMPAD_DIVIDE: return KEY_KP_DIVIDE; case AKEYCODE_NUMPAD_MULTIPLY: return KEY_KP_MULTIPLY; case AKEYCODE_NUMPAD_SUBTRACT: return KEY_KP_MINUS; case AKEYCODE_NUMPAD_ADD: return KEY_KP_PLUS; case AKEYCODE_NUMPAD_DOT: return KEY_KP_DECIMAL; case AKEYCODE_NUMPAD_ENTER: return KEY_KP_ENTER; } return KEY_NONE; } static void JNICALL java_processKeyDown(JNIEnv* env, jobject o, jint code) { int key = MapNativeKey(code); Platform_Log2("KEY - DOWN %i,%i", &code, &key); if (key) Input_SetPressed(key); } static void JNICALL java_processKeyUp(JNIEnv* env, jobject o, jint code) { int key = MapNativeKey(code); Platform_Log2("KEY - UP %i,%i", &code, &key); if (key) Input_SetReleased(key); } static void JNICALL java_processKeyChar(JNIEnv* env, jobject o, jint code) { char keyChar; int key = MapNativeKey(code); Platform_Log2("KEY - PRESS %i,%i", &code, &key); if (Convert_TryCodepointToCP437(code, &keyChar)) { Event_RaiseInt(&InputEvents.Press, keyChar); } } static void JNICALL java_processKeyText(JNIEnv* env, jobject o, jstring str) { char buffer[NATIVE_STR_LEN]; cc_string text = JavaGetString(env, str, buffer); Platform_Log1("KEY - TEXT %s", &text); Event_RaiseString(&InputEvents.TextChanged, &text); } static void JNICALL java_processPointerDown(JNIEnv* env, jobject o, jint id, jint x, jint y, jint isMouse) { Platform_Log4("POINTER %i (%i) - DOWN %i,%i", &id, &isMouse, &x, &y); Input_AddTouch(id, x, y); } static void JNICALL java_processPointerUp(JNIEnv* env, jobject o, jint id, jint x, jint y, jint isMouse) { Platform_Log4("POINTER %i (%i) - UP %i,%i", &id, &isMouse, &x, &y); Input_RemoveTouch(id, x, y); } static void JNICALL java_processPointerMove(JNIEnv* env, jobject o, jint id, jint x, jint y, jint isMouse) { Platform_Log4("POINTER %i (%i) - MOVE %i,%i", &id, &isMouse, &x, &y); Input_UpdateTouch(id, x, y); } static void JNICALL java_processSurfaceCreated(JNIEnv* env, jobject o, jobject surface) { Platform_LogConst("WIN - CREATED"); win_handle = ANativeWindow_fromSurface(env, surface); WindowInfo.Handle = win_handle; RefreshWindowBounds(); /* TODO: Restore context */ Event_RaiseVoid(&WindowEvents.Created); } #include "Graphics.h" static void JNICALL java_processSurfaceDestroyed(JNIEnv* env, jobject o) { Platform_LogConst("WIN - DESTROYED"); if (win_handle) ANativeWindow_release(win_handle); win_handle = NULL; WindowInfo.Handle = NULL; /* eglSwapBuffers might return EGL_BAD_SURFACE, EGL_BAD_ALLOC, or some other error */ /* Instead the context is lost here in a consistent manner */ if (Gfx.Created) Gfx_LoseContext("surface lost"); JavaCallVoid(env, "processedSurfaceDestroyed", "()V", NULL); } static void JNICALL java_processSurfaceResized(JNIEnv* env, jobject o, jobject surface) { Platform_LogConst("WIN - RESIZED"); RefreshWindowBounds(); } static void JNICALL java_processSurfaceRedrawNeeded(JNIEnv* env, jobject o) { Platform_LogConst("WIN - REDRAW"); Event_RaiseVoid(&WindowEvents.Redraw); } static void JNICALL java_onStart(JNIEnv* env, jobject o) { Platform_LogConst("APP - ON START"); } static void JNICALL java_onStop(JNIEnv* env, jobject o) { Platform_LogConst("APP - ON STOP"); } static void JNICALL java_onResume(JNIEnv* env, jobject o) { Platform_LogConst("APP - ON RESUME"); /* TODO: Resume rendering */ } static void JNICALL java_onPause(JNIEnv* env, jobject o) { Platform_LogConst("APP - ON PAUSE"); /* TODO: Disable rendering */ } static void JNICALL java_onDestroy(JNIEnv* env, jobject o) { Platform_LogConst("APP - ON DESTROY"); if (WindowInfo.Exists) Window_Close(); /* TODO: signal to java code we're done */ JavaCallVoid(env, "processedDestroyed", "()V", NULL); } static void JNICALL java_onGotFocus(JNIEnv* env, jobject o) { Platform_LogConst("APP - GOT FOCUS"); WindowInfo.Focused = true; Event_RaiseVoid(&WindowEvents.FocusChanged); } static void JNICALL java_onLostFocus(JNIEnv* env, jobject o) { Platform_LogConst("APP - LOST FOCUS"); WindowInfo.Focused = false; Event_RaiseVoid(&WindowEvents.FocusChanged); /* TODO: Disable rendering? */ } static void JNICALL java_onLowMemory(JNIEnv* env, jobject o) { Platform_LogConst("APP - LOW MEM"); /* TODO: Low memory */ } static const JNINativeMethod methods[19] = { { "processKeyDown", "(I)V", java_processKeyDown }, { "processKeyUp", "(I)V", java_processKeyUp }, { "processKeyChar", "(I)V", java_processKeyChar }, { "processKeyText", "(Ljava/lang/String;)V", java_processKeyText }, { "processPointerDown", "(IIII)V", java_processPointerDown }, { "processPointerUp", "(IIII)V", java_processPointerUp }, { "processPointerMove", "(IIII)V", java_processPointerMove }, { "processSurfaceCreated", "(Landroid/view/Surface;)V", java_processSurfaceCreated }, { "processSurfaceDestroyed", "()V", java_processSurfaceDestroyed }, { "processSurfaceResized", "(Landroid/view/Surface;)V", java_processSurfaceResized }, { "processSurfaceRedrawNeeded", "()V", java_processSurfaceRedrawNeeded }, { "processOnStart", "()V", java_onStart }, { "processOnStop", "()V", java_onStop }, { "processOnResume", "()V", java_onResume }, { "processOnPause", "()V", java_onPause }, { "processOnDestroy", "()V", java_onDestroy }, { "processOnGotFocus", "()V", java_onGotFocus }, { "processOnLostFocus", "()V", java_onLostFocus }, { "processOnLowMemory", "()V", java_onLowMemory } }; void Window_Init(void) { JNIEnv* env; /* TODO: ANativeActivity_setWindowFlags(app->activity, AWINDOW_FLAG_FULLSCREEN, 0); */ JavaGetCurrentEnv(env); JavaRegisterNatives(env, methods); WindowInfo.SoftKeyboard = SOFT_KEYBOARD_RESIZE; Input_SetTouchMode(true); DisplayInfo.Depth = 32; DisplayInfo.ScaleX = JavaCallFloat(env, "getDpiX", "()F", NULL); DisplayInfo.ScaleY = JavaCallFloat(env, "getDpiY", "()F", NULL); } void Window_Create(int width, int height) { WindowInfo.Exists = true; /* actual window creation is done when processSurfaceCreated is received */ } static cc_bool winCreated; static void OnWindowCreated(void* obj) { winCreated = true; } cc_bool Window_RemakeSurface(void) { JNIEnv* env; JavaGetCurrentEnv(env); winCreated = false; /* Force window to be destroyed and re-created */ /* (see comments in setupForGame for why this has to be done) */ JavaCallVoid(env, "setupForGame", "()V", NULL); Event_Register_(&WindowEvents.Created, NULL, OnWindowCreated); Platform_LogConst("Entering wait for window exist loop.."); /* Loop until window gets created async */ while (WindowInfo.Exists && !winCreated) { Window_ProcessEvents(); Thread_Sleep(10); } Platform_LogConst("OK window created.."); Event_Unregister_(&WindowEvents.Created, NULL, OnWindowCreated); return winCreated; } void Window_SetTitle(const cc_string* title) { /* TODO: Implement this somehow */ /* Maybe https://stackoverflow.com/questions/2198410/how-to-change-title-of-activity-in-android */ } void Clipboard_GetText(cc_string* value) { JavaCall_Void_String("getClipboardText", value); } void Clipboard_SetText(const cc_string* value) { JavaCall_String_Void("setClipboardText", value); } void Window_Show(void) { } /* Window already visible */ int Window_GetWindowState(void) { JNIEnv* env; JavaGetCurrentEnv(env); return JavaCallInt(env, "getWindowState", "()I", NULL); } cc_result Window_EnterFullscreen(void) { JNIEnv* env; JavaGetCurrentEnv(env); JavaCallVoid(env, "enterFullscreen", "()V", NULL); return 0; } cc_result Window_ExitFullscreen(void) { JNIEnv* env; JavaGetCurrentEnv(env); JavaCallVoid(env, "exitFullscreen", "()V", NULL); return 0; } void Window_SetSize(int width, int height) { } void Window_Close(void) { WindowInfo.Exists = false; Event_RaiseVoid(&WindowEvents.Closing); /* TODO: Do we need to call finish here */ /* ANativeActivity_finish(app->activity); */ } void Window_ProcessEvents(void) { JNIEnv* env; JavaGetCurrentEnv(env); /* TODO: Cache the java env and cache the method ID!!!!! */ JavaCallVoid(env, "processEvents", "()V", NULL); } /* No actual mouse cursor */ static void Cursor_GetRawPos(int* x, int* y) { *x = 0; *y = 0; } void Cursor_SetPosition(int x, int y) { } static void Cursor_DoSetVisible(cc_bool visible) { } static void ShowDialogCore(const char* title, const char* msg) { JNIEnv* env; jvalue args[2]; JavaGetCurrentEnv(env); Platform_LogConst(title); Platform_LogConst(msg); /* in case surface destroyed message has arrived */ Window_ProcessEvents(); args[0].l = JavaMakeConst(env, title); args[1].l = JavaMakeConst(env, msg); JavaCallVoid(env, "showAlert", "(Ljava/lang/String;Ljava/lang/String;)V", args); (*env)->DeleteLocalRef(env, args[0].l); (*env)->DeleteLocalRef(env, args[1].l); } static struct Bitmap fb_bmp; void Window_AllocFramebuffer(struct Bitmap* bmp) { bmp->scan0 = (BitmapCol*)Mem_Alloc(bmp->width * bmp->height, 4, "window pixels"); fb_bmp = *bmp; } void Window_DrawFramebuffer(Rect2D r) { ANativeWindow_Buffer buffer; cc_uint32* src; cc_uint32* dst; ARect b; int y, res, size; /* window not created yet */ if (!win_handle) return; b.left = r.X; b.right = r.X + r.Width; b.top = r.Y; b.bottom = r.Y + r.Height; /* Platform_Log4("DIRTY: %i,%i - %i,%i", &b.left, &b.top, &b.right, &b.bottom); */ res = ANativeWindow_lock(win_handle, &buffer, &b); if (res) Logger_Abort2(res, "Locking window pixels"); /* Platform_Log4("ADJUS: %i,%i - %i,%i", &b.left, &b.top, &b.right, &b.bottom); */ /* In some rare cases, the returned locked region will be entire area of the surface */ /* This can cause a crash if the surface has been resized (i.e. device rotated), */ /* but the framebuffer has not been resized yet. So always constrain bounds. */ b.left = min(b.left, fb_bmp.width); b.right = min(b.right, fb_bmp.width); b.top = min(b.top, fb_bmp.height); b.bottom = min(b.bottom, fb_bmp.height); src = (cc_uint32*)fb_bmp.scan0 + b.left; dst = (cc_uint32*)buffer.bits + b.left; size = (b.right - b.left) * 4; for (y = b.top; y < b.bottom; y++) { Mem_Copy(dst + y * buffer.stride, src + y * fb_bmp.width, size); } res = ANativeWindow_unlockAndPost(win_handle); if (res) Logger_Abort2(res, "Unlocking window pixels"); } void Window_FreeFramebuffer(struct Bitmap* bmp) { Mem_Free(bmp->scan0); } void Window_OpenKeyboard(const struct OpenKeyboardArgs* kArgs) { JNIEnv* env; jvalue args[2]; JavaGetCurrentEnv(env); args[0].l = JavaMakeString(env, kArgs->text); args[1].i = kArgs->type; JavaCallVoid(env, "openKeyboard", "(Ljava/lang/String;I)V", args); (*env)->DeleteLocalRef(env, args[0].l); } void Window_SetKeyboardText(const cc_string* text) { JNIEnv* env; jvalue args[1]; JavaGetCurrentEnv(env); args[0].l = JavaMakeString(env, text); JavaCallVoid(env, "setKeyboardText", "(Ljava/lang/String;)V", args); (*env)->DeleteLocalRef(env, args[0].l); } void Window_CloseKeyboard(void) { JNIEnv* env; JavaGetCurrentEnv(env); JavaCallVoid(env, "closeKeyboard", "()V", NULL); } void Window_EnableRawMouse(void) { DefaultEnableRawMouse(); } void Window_UpdateRawMouse(void) { } void Window_DisableRawMouse(void) { DefaultDisableRawMouse(); } #endif #ifdef CC_BUILD_GL /* OpenGL contexts are heavily tied to the window, so for simplicitly are also included here */ /* SDL and EGL are platform agnostic, other OpenGL context backends are tied to one windowing system. */ #define GLContext_IsInvalidAddress(ptr) (ptr == (void*)0 || ptr == (void*)1 || ptr == (void*)-1 || ptr == (void*)2) void GLContext_GetAll(const struct DynamicLibSym* syms, int count) { int i; for (i = 0; i < count; i++) { *syms[i].symAddr = GLContext_GetAddress(syms[i].name); } } /*########################################################################################################################* *-------------------------------------------------------SDL OpenGL--------------------------------------------------------* *#########################################################################################################################*/ #if defined CC_BUILD_SDL static SDL_GLContext win_ctx; void GLContext_Create(void) { struct GraphicsMode mode; InitGraphicsMode(&mode); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, mode.R); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, mode.G); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, mode.B); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, mode.A); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, GLCONTEXT_DEFAULT_DEPTH); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 0); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, true); win_ctx = SDL_GL_CreateContext(win_handle); if (!win_ctx) Window_SDLFail("creating OpenGL context"); } void GLContext_Update(void) { } cc_bool GLContext_TryRestore(void) { return true; } void GLContext_Free(void) { SDL_GL_DeleteContext(win_ctx); win_ctx = NULL; } void* GLContext_GetAddress(const char* function) { return SDL_GL_GetProcAddress(function); } cc_bool GLContext_SwapBuffers(void) { SDL_GL_SwapWindow(win_handle); return true; } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { SDL_GL_SetSwapInterval(vsync); } void GLContext_GetApiInfo(cc_string* info) { } /*########################################################################################################################* *-------------------------------------------------------EGL OpenGL--------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_EGL #include <EGL/egl.h> static EGLDisplay ctx_display; static EGLContext ctx_context; static EGLSurface ctx_surface; static EGLConfig ctx_config; static EGLint ctx_numConfig; #ifdef CC_BUILD_X11 static XVisualInfo GLContext_SelectVisual(void) { XVisualInfo info; cc_result res; int screen = DefaultScreen(win_display); res = XMatchVisualInfo(win_display, screen, 24, TrueColor, &info) || XMatchVisualInfo(win_display, screen, 32, TrueColor, &info); if (!res) Logger_Abort("Selecting visual"); return info; } #endif static void GLContext_InitSurface(void) { if (!win_handle) return; /* window not created or lost */ ctx_surface = eglCreateWindowSurface(ctx_display, ctx_config, win_handle, NULL); if (!ctx_surface) return; eglMakeCurrent(ctx_display, ctx_surface, ctx_surface, ctx_context); } static void GLContext_FreeSurface(void) { if (!ctx_surface) return; eglMakeCurrent(ctx_display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroySurface(ctx_display, ctx_surface); ctx_surface = NULL; } void GLContext_Create(void) { static EGLint contextAttribs[3] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; static EGLint attribs[19] = { EGL_RED_SIZE, 0, EGL_GREEN_SIZE, 0, EGL_BLUE_SIZE, 0, EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, GLCONTEXT_DEFAULT_DEPTH, EGL_STENCIL_SIZE, 0, EGL_COLOR_BUFFER_TYPE, EGL_RGB_BUFFER, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; struct GraphicsMode mode; InitGraphicsMode(&mode); attribs[1] = mode.R; attribs[3] = mode.G; attribs[5] = mode.B; attribs[7] = mode.A; ctx_display = eglGetDisplay(EGL_DEFAULT_DISPLAY); eglInitialize(ctx_display, NULL, NULL); eglBindAPI(EGL_OPENGL_ES_API); eglChooseConfig(ctx_display, attribs, &ctx_config, 1, &ctx_numConfig); ctx_context = eglCreateContext(ctx_display, ctx_config, EGL_NO_CONTEXT, contextAttribs); GLContext_InitSurface(); } void GLContext_Update(void) { GLContext_FreeSurface(); GLContext_InitSurface(); } cc_bool GLContext_TryRestore(void) { GLContext_FreeSurface(); GLContext_InitSurface(); return ctx_surface != NULL; } void GLContext_Free(void) { GLContext_FreeSurface(); eglDestroyContext(ctx_display, ctx_context); eglTerminate(ctx_display); } void* GLContext_GetAddress(const char* function) { return eglGetProcAddress(function); } cc_bool GLContext_SwapBuffers(void) { EGLint err; if (!ctx_surface) return false; if (eglSwapBuffers(ctx_display, ctx_surface)) return true; err = eglGetError(); /* TODO: figure out what errors need to be handled here */ Logger_Abort2(err, "Failed to swap buffers"); return false; } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { eglSwapInterval(ctx_display, vsync); } void GLContext_GetApiInfo(cc_string* info) { } /*########################################################################################################################* *-------------------------------------------------------WGL OpenGL--------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_WINGUI static HGLRC ctx_handle; static HDC ctx_DC; typedef BOOL (WINAPI *FP_SWAPINTERVAL)(int interval); static FP_SWAPINTERVAL wglSwapIntervalEXT; static void GLContext_SelectGraphicsMode(struct GraphicsMode* mode) { PIXELFORMATDESCRIPTOR pfd = { 0 }; pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; /* TODO: PFD_SUPPORT_COMPOSITION FLAG? CHECK IF IT WORKS ON XP */ pfd.cColorBits = mode->R + mode->G + mode->B; pfd.cDepthBits = GLCONTEXT_DEFAULT_DEPTH; pfd.iPixelType = mode->IsIndexed ? PFD_TYPE_COLORINDEX : PFD_TYPE_RGBA; pfd.cRedBits = mode->R; pfd.cGreenBits = mode->G; pfd.cBlueBits = mode->B; pfd.cAlphaBits = mode->A; int modeIndex = ChoosePixelFormat(win_DC, &pfd); if (modeIndex == 0) { Logger_Abort("Requested graphics mode not available"); } Mem_Set(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; DescribePixelFormat(win_DC, modeIndex, pfd.nSize, &pfd); if (!SetPixelFormat(win_DC, modeIndex, &pfd)) { Logger_Abort2(GetLastError(), "SetPixelFormat failed"); } } void GLContext_Create(void) { struct GraphicsMode mode; InitGraphicsMode(&mode); GLContext_SelectGraphicsMode(&mode); ctx_handle = wglCreateContext(win_DC); if (!ctx_handle) ctx_handle = wglCreateContext(win_DC); if (!ctx_handle) { Logger_Abort2(GetLastError(), "Failed to create OpenGL context"); } if (!wglMakeCurrent(win_DC, ctx_handle)) { Logger_Abort2(GetLastError(), "Failed to make OpenGL context current"); } ctx_DC = wglGetCurrentDC(); wglSwapIntervalEXT = (FP_SWAPINTERVAL)GLContext_GetAddress("wglSwapIntervalEXT"); } void GLContext_Update(void) { } cc_bool GLContext_TryRestore(void) { return true; } void GLContext_Free(void) { if (!ctx_handle) return; wglDeleteContext(ctx_handle); ctx_handle = NULL; } void* GLContext_GetAddress(const char* function) { void* addr = (void*)wglGetProcAddress(function); return GLContext_IsInvalidAddress(addr) ? NULL : addr; } cc_bool GLContext_SwapBuffers(void) { if (!SwapBuffers(ctx_DC)) Logger_Abort2(GetLastError(), "Failed to swap buffers"); return true; } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { if (!wglSwapIntervalEXT) return; wglSwapIntervalEXT(vsync); } void GLContext_GetApiInfo(cc_string* info) { } /*########################################################################################################################* *-------------------------------------------------------glX OpenGL--------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_X11 #include <GL/glx.h> static GLXContext ctx_handle; typedef int (*FP_SWAPINTERVAL)(int interval); typedef Bool (*FP_QUERYRENDERER)(int attribute, unsigned int* value); static FP_SWAPINTERVAL swapIntervalMESA, swapIntervalSGI; static FP_QUERYRENDERER queryRendererMESA; void GLContext_Create(void) { static const cc_string vsync_mesa = String_FromConst("GLX_MESA_swap_control"); static const cc_string vsync_sgi = String_FromConst("GLX_SGI_swap_control"); static const cc_string info_mesa = String_FromConst("GLX_MESA_query_renderer"); const char* raw_exts; cc_string exts; ctx_handle = glXCreateContext(win_display, &win_visual, NULL, true); if (!ctx_handle) { Platform_LogConst("Context create failed. Trying indirect..."); ctx_handle = glXCreateContext(win_display, &win_visual, NULL, false); } if (!ctx_handle) Logger_Abort("Failed to create OpenGL context"); if (!glXIsDirect(win_display, ctx_handle)) { Platform_LogConst("== WARNING: Context is not direct =="); } if (!glXMakeCurrent(win_display, win_handle, ctx_handle)) { Logger_Abort("Failed to make OpenGL context current."); } /* GLX may return non-null function pointers that don't actually work */ /* So we need to manually check the extensions string for support */ raw_exts = glXQueryExtensionsString(win_display, DefaultScreen(win_display)); exts = String_FromReadonly(raw_exts); if (String_CaselessContains(&exts, &vsync_mesa)) { swapIntervalMESA = (FP_SWAPINTERVAL)GLContext_GetAddress("glXSwapIntervalMESA"); } if (String_CaselessContains(&exts, &vsync_sgi)) { swapIntervalSGI = (FP_SWAPINTERVAL)GLContext_GetAddress("glXSwapIntervalSGI"); } if (String_CaselessContains(&exts, &info_mesa)) { queryRendererMESA = (FP_QUERYRENDERER)GLContext_GetAddress("glXQueryCurrentRendererIntegerMESA"); } } void GLContext_Update(void) { } cc_bool GLContext_TryRestore(void) { return true; } void GLContext_Free(void) { if (!ctx_handle) return; glXMakeCurrent(win_display, None, NULL); glXDestroyContext(win_display, ctx_handle); ctx_handle = NULL; } void* GLContext_GetAddress(const char* function) { void* addr = (void*)glXGetProcAddress((const GLubyte*)function); return GLContext_IsInvalidAddress(addr) ? NULL : addr; } cc_bool GLContext_SwapBuffers(void) { glXSwapBuffers(win_display, win_handle); return true; } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { int res = 0; if (swapIntervalMESA) { res = swapIntervalMESA(vsync); } else if (swapIntervalSGI) { res = swapIntervalSGI(vsync); } if (res) Platform_Log1("Set VSync failed, error: %i", &res); } void GLContext_GetApiInfo(cc_string* info) { unsigned int vram, acc; if (!queryRendererMESA) return; queryRendererMESA(0x8186, &acc); queryRendererMESA(0x8187, &vram); String_Format2(info, "VRAM: %i MB, %c", &vram, acc ? "HW accelerated" : "no HW acceleration"); } static void GetAttribs(struct GraphicsMode* mode, int* attribs, int depth) { int i = 0; /* See http://www-01.ibm.com/support/knowledgecenter/ssw_aix_61/com.ibm.aix.opengl/doc/openglrf/glXChooseFBConfig.htm%23glxchoosefbconfig */ /* See http://www-01.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.opengl/doc/openglrf/glXChooseVisual.htm%23b5c84be452rree */ /* for the attribute declarations. Note that the attributes are different than those used in glxChooseVisual */ if (!mode->IsIndexed) { attribs[i++] = GLX_RGBA; } attribs[i++] = GLX_RED_SIZE; attribs[i++] = mode->R; attribs[i++] = GLX_GREEN_SIZE; attribs[i++] = mode->G; attribs[i++] = GLX_BLUE_SIZE; attribs[i++] = mode->B; attribs[i++] = GLX_ALPHA_SIZE; attribs[i++] = mode->A; attribs[i++] = GLX_DEPTH_SIZE; attribs[i++] = depth; attribs[i++] = GLX_DOUBLEBUFFER; attribs[i++] = 0; } static XVisualInfo GLContext_SelectVisual(void) { int attribs[20]; int major, minor; XVisualInfo* visual = NULL; int fbcount, screen; GLXFBConfig* fbconfigs; XVisualInfo info; struct GraphicsMode mode; InitGraphicsMode(&mode); GetAttribs(&mode, attribs, GLCONTEXT_DEFAULT_DEPTH); screen = DefaultScreen(win_display); if (!glXQueryVersion(win_display, &major, &minor)) { Platform_LogConst("glXQueryVersion failed"); } else if (major >= 1 && minor >= 3) { /* ChooseFBConfig returns an array of GLXFBConfig opaque structures */ fbconfigs = glXChooseFBConfig(win_display, screen, attribs, &fbcount); if (fbconfigs && fbcount) { /* Use the first GLXFBConfig from the fbconfigs array (best match) */ visual = glXGetVisualFromFBConfig(win_display, *fbconfigs); XFree(fbconfigs); } } if (!visual) { Platform_LogConst("Falling back to glXChooseVisual."); visual = glXChooseVisual(win_display, screen, attribs); } /* Some really old devices will only supply 16 bit depths */ if (!visual) { GetAttribs(&mode, attribs, 16); visual = glXChooseVisual(win_display, screen, attribs); } if (!visual) Logger_Abort("Requested GraphicsMode not available."); info = *visual; XFree(visual); return info; } /*########################################################################################################################* *-------------------------------------------------------AGL OpenGL--------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_CARBON #include <AGL/agl.h> static AGLContext ctx_handle; static cc_bool ctx_firstFullscreen; static int ctx_windowWidth, ctx_windowHeight; static void GLContext_Check(int code, const char* place) { cc_result res; if (code) return; res = aglGetError(); if (res) Logger_Abort2(res, place); } static void GLContext_MakeCurrent(void) { int code = aglSetCurrentContext(ctx_handle); GLContext_Check(code, "Setting GL context"); } static void GLContext_SetDrawable(void) { CGrafPtr windowPort = GetWindowPort(win_handle); int code = aglSetDrawable(ctx_handle, windowPort); GLContext_Check(code, "Attaching GL context"); } static void GLContext_GetAttribs(struct GraphicsMode* mode, GLint* attribs, cc_bool fullscreen) { int i = 0; if (!mode->IsIndexed) { attribs[i++] = AGL_RGBA; } attribs[i++] = AGL_RED_SIZE; attribs[i++] = mode->R; attribs[i++] = AGL_GREEN_SIZE; attribs[i++] = mode->G; attribs[i++] = AGL_BLUE_SIZE; attribs[i++] = mode->B; attribs[i++] = AGL_ALPHA_SIZE; attribs[i++] = mode->A; attribs[i++] = AGL_DEPTH_SIZE; attribs[i++] = GLCONTEXT_DEFAULT_DEPTH; attribs[i++] = AGL_DOUBLEBUFFER; if (fullscreen) { attribs[i++] = AGL_FULLSCREEN; } attribs[i++] = 0; } static cc_result GLContext_UnsetFullscreen(void) { int code; Platform_LogConst("Unsetting fullscreen."); code = aglSetDrawable(ctx_handle, NULL); if (!code) return aglGetError(); /* TODO: I don't think this is necessary */ code = aglUpdateContext(ctx_handle); if (!code) return aglGetError(); CGDisplayRelease(CGMainDisplayID()); GLContext_SetDrawable(); win_fullscreen = false; /* TODO: Eliminate this if possible */ Window_SetSize(ctx_windowWidth, ctx_windowHeight); return 0; } static cc_result GLContext_SetFullscreen(void) { int width = DisplayInfo.Width; int height = DisplayInfo.Height; int code; Platform_LogConst("Switching to fullscreen"); /* TODO: Does aglSetFullScreen capture the screen anyways? */ CGDisplayCapture(CGMainDisplayID()); if (!aglSetFullScreen(ctx_handle, width, height, 0, 0)) { code = aglGetError(); GLContext_UnsetFullscreen(); return code; } /* TODO: Do we really need to call this? */ GLContext_MakeCurrent(); /* This is a weird hack to workaround a bug where the first time a context */ /* is made fullscreen, we just end up with a blank screen. So we undo it as fullscreen */ /* and redo it as fullscreen. */ /* TODO: We really should'd need to do this. Need to debug on real hardware. */ if (!ctx_firstFullscreen) { ctx_firstFullscreen = true; GLContext_UnsetFullscreen(); return GLContext_SetFullscreen(); } win_fullscreen = true; ctx_windowWidth = WindowInfo.Width; ctx_windowHeight = WindowInfo.Height; windowX = DisplayInfo.X; WindowInfo.Width = DisplayInfo.Width; windowY = DisplayInfo.Y; WindowInfo.Height = DisplayInfo.Height; return 0; } void GLContext_Create(void) { GLint attribs[20]; AGLPixelFormat fmt; GDHandle gdevice; OSStatus res; struct GraphicsMode mode; InitGraphicsMode(&mode); /* Initially try creating fullscreen compatible context */ res = DMGetGDeviceByDisplayID(CGMainDisplayID(), &gdevice, false); if (res) Logger_Abort2(res, "Getting display device failed"); GLContext_GetAttribs(&mode, attribs, true); fmt = aglChoosePixelFormat(&gdevice, 1, attribs); res = aglGetError(); /* Try again with non-compatible context if that fails */ if (!fmt || res == AGL_BAD_PIXELFMT) { Platform_LogConst("Failed to create full screen pixel format."); Platform_LogConst("Trying again to create a non-fullscreen pixel format."); GLContext_GetAttribs(&mode, attribs, false); fmt = aglChoosePixelFormat(NULL, 0, attribs); res = aglGetError(); } if (res) Logger_Abort2(res, "Choosing pixel format"); ctx_handle = aglCreateContext(fmt, NULL); GLContext_Check(0, "Creating GL context"); aglDestroyPixelFormat(fmt); GLContext_Check(0, "Destroying pixel format"); GLContext_SetDrawable(); GLContext_Update(); GLContext_MakeCurrent(); } void GLContext_Update(void) { if (win_fullscreen) return; GLContext_SetDrawable(); aglUpdateContext(ctx_handle); } cc_bool GLContext_TryRestore(void) { return true; } void GLContext_Free(void) { if (!ctx_handle) return; aglSetCurrentContext(NULL); aglDestroyContext(ctx_handle); ctx_handle = NULL; } void* GLContext_GetAddress(const char* function) { static const cc_string glPath = String_FromConst("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL"); static void* lib; void* addr; if (!lib) lib = DynamicLib_Load2(&glPath); addr = DynamicLib_Get2(lib, function); return GLContext_IsInvalidAddress(addr) ? NULL : addr; } cc_bool GLContext_SwapBuffers(void) { aglSwapBuffers(ctx_handle); GLContext_Check(0, "Swapping buffers"); return true; } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { int value = vsync ? 1 : 0; aglSetInteger(ctx_handle, AGL_SWAP_INTERVAL, &value); } void GLContext_GetApiInfo(cc_string* info) { } /*########################################################################################################################* *--------------------------------------------------------NSOpenGL---------------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_COCOA /* NOTE: Mostly implemented in interop_cocoa.m */ cc_bool GLContext_TryRestore(void) { return true; } void* GLContext_GetAddress(const char* function) { static const cc_string glPath = String_FromConst("/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL"); static void* lib; void* addr; if (!lib) lib = DynamicLib_Load2(&glPath); addr = DynamicLib_Get2(lib, function); return GLContext_IsInvalidAddress(addr) ? NULL : addr; } void GLContext_GetApiInfo(cc_string* info) { } /*########################################################################################################################* *------------------------------------------------Emscripten WebGL context-------------------------------------------------* *#########################################################################################################################*/ #elif defined CC_BUILD_WEB #include "Graphics.h" static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx_handle; static EM_BOOL GLContext_OnLost(int eventType, const void *reserved, void *userData) { Gfx_LoseContext("WebGL context lost"); return 1; } void GLContext_Create(void) { EmscriptenWebGLContextAttributes attribs; emscripten_webgl_init_context_attributes(&attribs); attribs.alpha = false; attribs.depth = true; attribs.stencil = false; attribs.antialias = false; ctx_handle = emscripten_webgl_create_context("#canvas", &attribs); if (!ctx_handle) Window_ShowDialog("WebGL unsupported", "WebGL is required to run ClassiCube"); emscripten_webgl_make_context_current(ctx_handle); emscripten_set_webglcontextlost_callback("#canvas", NULL, 0, GLContext_OnLost); } void GLContext_Update(void) { /* TODO: do we need to do something here.... ? */ } cc_bool GLContext_TryRestore(void) { return !emscripten_is_webgl_context_lost(0); } void GLContext_Free(void) { emscripten_webgl_destroy_context(ctx_handle); emscripten_set_webglcontextlost_callback("#canvas", NULL, 0, NULL); } void* GLContext_GetAddress(const char* function) { return NULL; } cc_bool GLContext_SwapBuffers(void) { return true; /* Browser implicitly does this */ } void GLContext_SetFpsLimit(cc_bool vsync, float minFrameMs) { if (vsync) { emscripten_set_main_loop_timing(EM_TIMING_RAF, 1); } else { emscripten_set_main_loop_timing(EM_TIMING_SETTIMEOUT, (int)minFrameMs); } } extern void interop_GetGpuRenderer(char* buffer, int len); void GLContext_GetApiInfo(cc_string* info) { char buffer[NATIVE_STR_LEN]; int len; interop_GetGpuRenderer(buffer, NATIVE_STR_LEN); len = String_CalcLen(buffer, NATIVE_STR_LEN); if (!len) return; String_AppendConst(info, "GPU: "); String_AppendUtf8(info, buffer, len); } #endif #endif
627661.c
/* crypto/bio/b_dump.c */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* * Stolen from tjh's ssl/ssl_trc.c stuff. */ #include <stdio.h> #include "cryptlib.h" #include "bio_lcl.h" #define TRUNCATE #define DUMP_WIDTH 16 #define DUMP_WIDTH_LESS_INDENT(i) (DUMP_WIDTH-((i-(i>6?6:i)+3)/4)) int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const char *s, int len) { return BIO_dump_indent_cb(cb, u, s, len, 0); } int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u), void *u, const char *s, int len, int indent) { int ret = 0; char buf[288 + 1], tmp[20], str[128 + 1]; int i, j, rows, trc; unsigned char ch; int dump_width; trc = 0; #ifdef TRUNCATE for (; (len > 0) && ((s[len - 1] == ' ') || (s[len - 1] == '\0')); len--) trc++; #endif if (indent < 0) indent = 0; if (indent) { if (indent > 128) indent = 128; memset(str, ' ', indent); } str[indent] = '\0'; dump_width = DUMP_WIDTH_LESS_INDENT(indent); rows = (len / dump_width); if ((rows * dump_width) < len) rows++; for (i = 0; i < rows; i++) { BUF_strlcpy(buf, str, sizeof(buf)); BIO_snprintf(tmp, sizeof(tmp), "%04x - ", i * dump_width); BUF_strlcat(buf, tmp, sizeof(buf)); for (j = 0; j < dump_width; j++) { if (((i * dump_width) + j) >= len) { BUF_strlcat(buf, " ", sizeof(buf)); } else { ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; BIO_snprintf(tmp, sizeof(tmp), "%02x%c", ch, j == 7 ? '-' : ' '); BUF_strlcat(buf, tmp, sizeof(buf)); } } BUF_strlcat(buf, " ", sizeof(buf)); for (j = 0; j < dump_width; j++) { if (((i * dump_width) + j) >= len) break; ch = ((unsigned char)*(s + i * dump_width + j)) & 0xff; #ifndef CHARSET_EBCDIC BIO_snprintf(tmp, sizeof(tmp), "%c", ((ch >= ' ') && (ch <= '~')) ? ch : '.'); #else BIO_snprintf(tmp, sizeof(tmp), "%c", ((ch >= os_toascii[' ']) && (ch <= os_toascii['~'])) ? os_toebcdic[ch] : '.'); #endif BUF_strlcat(buf, tmp, sizeof(buf)); } BUF_strlcat(buf, "\n", sizeof(buf)); /* * if this is the last call then update the ddt_dump thing so that we * will move the selection point in the debug window */ ret += cb((void *)buf, strlen(buf), u); } #ifdef TRUNCATE if (trc > 0) { BIO_snprintf(buf, sizeof buf, "%s%04x - <SPACES/NULS>\n", str, len + trc); ret += cb((void *)buf, strlen(buf), u); } #endif return (ret); } #ifndef OPENSSL_NO_FP_API static int write_fp(const void *data, size_t len, void *fp) { return UP_fwrite(data, len, 1, fp); } int BIO_dump_fp(FILE *fp, const char *s, int len) { return BIO_dump_cb(write_fp, fp, s, len); } int BIO_dump_indent_fp(FILE *fp, const char *s, int len, int indent) { return BIO_dump_indent_cb(write_fp, fp, s, len, indent); } #endif static int write_bio(const void *data, size_t len, void *bp) { return BIO_write((BIO *)bp, (const char *)data, len); } int BIO_dump(BIO *bp, const char *s, int len) { return BIO_dump_cb(write_bio, bp, s, len); } int BIO_dump_indent(BIO *bp, const char *s, int len, int indent) { return BIO_dump_indent_cb(write_bio, bp, s, len, indent); } int BIO_hex_string(BIO *out, int indent, int width, unsigned char *data, int datalen) { int i, j = 0; if (datalen < 1) return 1; for (i = 0; i < datalen - 1; i++) { if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X:", data[i]); j = (j + 1) % width; if (!j) BIO_printf(out, "\n"); } if (i && !j) BIO_printf(out, "%*s", indent, ""); BIO_printf(out, "%02X", data[datalen - 1]); return 1; }
187928.c
/*====================================================================* - Copyright (C) 2001 Leptonica. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE 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 ANY - 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. *====================================================================*/ /* * scale_it.c * * scale_it filein scalex scaley fileout lossless [sharpen antialias togray] * * where * scalex: floating pt input * scaley: ditto * lossless: (for bpp >= 8) 1 to output jpeg; 0 to output png * sharpen : (for bpp > 1; scale factor in [0.2 ... 1.4]): * 1 to sharpen; 0 not to sharpen * antialias: (for bpp > 1): 1 to use area-mapping or linear * interpolation; 0 for sampling. * togray: (for bpp == 1, reduction): 1 for scale-to-gray; * 0 for sampling * * The choice of writing lossless (png) or lossy (jpeg) only applies * for bpp >= 8. Otherwise: * bpp == 1 --> tiffg4 * bpp == 2 --> png * bpp == 4 --> png * * Sharpening: no sharpening is done for scale factors < 0.2 or > 1.4. * Sharpening increases the saliency of edges, making the scaled image * look less fuzzy. It is much slower than scaling without sharpening. * The default is to sharpen. * * Antialias: area-mapping and linear interpolation give higher * quality results with bpp > 1. Sampling is faster, but shows * artifacts, such as pixel-sized steps in lines. The default is * to use antialiasing. * * ScaleToGray: for bpp == 1, downscaling to gray gives a better appearance * than subsampling. The default is to scale-to-gray. * * The defaults are all intended to improve the quality of the result. * The quality can be degraded, with faster processing, by setting * some of the three optional inputs to 0. * * Note that the short form: * scale_it filein scalex scaley fileout lossless * is equivalent to * scale_it filein scalex scaley fileout lossless 1 1 1 */ #include "allheaders.h" int main(int argc, char **argv) { char *filein, *fileout; l_int32 sharpen, antialias, togray, format, lossless, d; l_float32 scalex, scaley; PIX *pixs, *pixd; static char mainName[] = "scale_it"; if (argc != 6 && argc != 9) return ERROR_INT( "\n Syntax: scale_it filein scalex scaley fileout lossless " "[sharpen antialias togray]", mainName, 1); filein = argv[1]; scalex = atof(argv[2]); scaley = atof(argv[3]); fileout = argv[4]; lossless = atoi(argv[5]); sharpen = antialias = togray = 1; if (argc == 9) { sharpen = atoi(argv[6]); antialias = atoi(argv[7]); togray = atoi(argv[8]); } if (scalex <= 0 || scaley <= 0) return ERROR_INT("invalid scale factor; must be > 0.0", mainName, 1); setLeptDebugOK(1); if ((pixs = pixRead(filein)) == NULL) return ERROR_INT("pixs not made", mainName, 1); d = pixGetDepth(pixs); if (d == 1) { if (togray && scalex < 1.0) pixd = pixScaleToGray(pixs, scalex); else /* this will just scale by sampling */ pixd = pixScaleBinary(pixs, scalex, scaley); } else { if (antialias == 0) { pixd = pixScaleBySampling(pixs, scalex, scaley); } else if (sharpen == 0) { pixd = pixScaleGeneral(pixs, scalex, scaley, 0.0, 0); } else { /* antialias == 1, sharpen == 1 */ pixd = pixScale(pixs, scalex, scaley); } } if (!pixd) return ERROR_INT("pixd not made", mainName, 1); d = pixGetDepth(pixd); if (d == 1) pixWrite(fileout, pixd, IFF_TIFF_G4); else if (d == 2 || d == 4) pixWrite(fileout, pixd, IFF_PNG); else { /* d >= 8 */ if (lossless) pixWrite(fileout, pixd, IFF_PNG); else pixWrite(fileout, pixd, IFF_JFIF_JPEG); } pixDestroy(&pixs); pixDestroy(&pixd); return 0; }
913685.c
/* * Copyright 2015 Hippo Seven * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include "image.h" #include "image_png.h" #include "image_utils.h" #include "image_decoder.h" #include "image_convert.h" #include "animated_image.h" #include "../log.h" #define IMAGE_PNG_PREPARE_NONE 0x00 #define IMAGE_PNG_PREPARE_BACKGROUND 0x01 #define IMAGE_PNG_PREPARE_USE_BACKUP 0x02 typedef struct { uint32_t width; uint32_t height; uint32_t offset_x; uint32_t offset_y; uint16_t delay_num; uint16_t delay_den; uint32_t delay; // ms uint8_t dop; uint8_t bop; uint8_t pop; uint8_t* buffer; } PngFrame; typedef struct { PngFrame* frames; uint32_t frame_count; png_structp png_ptr; png_infop info_ptr; Stream* stream; } PngData; LIBRARY_EXPORT bool png_init(ImageLibrary* library) { library->loaded = true; library->is_magic = png_is_magic; library->decode = png_decode; library->decode_info = png_decode_info; library->decode_buffer = png_decode_buffer; library->create = NULL; library->get_description = png_get_description; return true; } bool png_is_magic(Stream* stream) { uint8_t magic[2]; size_t read = stream->peek(stream, magic, sizeof(magic)); if (read != sizeof(magic)) { LOGE(MSG("Could not read %zu bytes from stream, only read %zu"), sizeof(magic), read); return false; } return magic[0] == IMAGE_PNG_MAGIC_NUMBER_0 && magic[1] == IMAGE_PNG_MAGIC_NUMBER_1; } const char* png_get_description() { return IMAGE_PNG_DECODER_DESCRIPTION; } /** * Skip some rows */ static void png_skip_rows(png_structrp png_ptr, png_uint_32 num_rows) { for (png_uint_32 i = 0; i < num_rows; ++i) { png_read_row(png_ptr, NULL, NULL); } } /** * Skip the whole image */ static void png_skip_image(png_structrp png_ptr, png_infop info_ptr) { png_uint_32 image_height; int pass, i, j; image_height = png_get_image_height(png_ptr, info_ptr); pass = png_set_interlace_handling(png_ptr); for (j = 0; j < pass; j++) { for (i = 0; i < image_height; i++) { png_read_row(png_ptr, NULL, NULL); } } } static void user_read_fn(png_structp png_ptr, png_bytep data, png_size_t length) { Stream* stream = png_get_io_ptr(png_ptr); stream->read(stream, data, length); } static void user_error_fn(__unused png_structp png_ptr, png_const_charp error_msg) { LOGE(MSG("%s"), error_msg); } static void user_warn_fn(__unused png_structp png_ptr, png_const_charp error_msg) { LOGW(MSG("%s"), error_msg); } static void free_frames(PngFrame** frames, size_t count) { PngFrame* frame_info; size_t i; if (frames == NULL || *frames == NULL) { return; } for (i = 0; i < count; i++) { frame_info = *frames + i; free(frame_info->buffer); frame_info->buffer = NULL; } free(*frames); *frames = NULL; } static inline void blend_over(uint8_t* dp, const uint8_t* sp, size_t len) { uint32_t i; uint32_t u, v, al; for (i = 0; i < len; i += 4, sp += 4, dp += 4) { if (sp[3] == 255) { memcpy(dp, sp, 4); } else if (sp[3] != 0) { if (dp[3] != 0) { u = sp[3] * 255u; v = (255u - sp[3]) * dp[3]; al = u + v; dp[0] = (uint8_t) ((sp[0] * u + dp[0] * v) / al); dp[1] = (uint8_t) ((sp[1] * u + dp[1] * v) / al); dp[2] = (uint8_t) ((sp[2] * u + dp[2] * v) / al); dp[3] = (uint8_t) (al / 255u); } else { memcpy(dp, sp, 4); } } } } static void blend(uint8_t* dst, uint32_t dst_width, uint32_t dst_height, uint8_t* src, uint32_t src_width, uint32_t src_height, uint32_t offset_x, uint32_t offset_y, bool blend_op_over) { uint32_t i; uint8_t* src_ptr; uint8_t* dst_ptr; size_t len; uint32_t copy_width = MIN(dst_width - offset_x, src_width); uint32_t copy_height = MIN(dst_height - offset_y, src_height); for (i = 0; i < copy_height; i++) { src_ptr = src + (i * src_width * 4); dst_ptr = dst + (((offset_y + i) * dst_width + offset_x) * 4); len = (size_t) (copy_width * 4); if (blend_op_over) { blend_over(dst_ptr, src_ptr, len); } else { memcpy(dst_ptr, src_ptr, len); } } } // Read pixels static void read_image(png_structp png_ptr, uint8_t* buffer, uint32_t width, uint32_t height) { uint32_t i; uint8_t** image = (png_bytepp) malloc(height * sizeof(png_bytep)); if (image == NULL) { png_error(png_ptr, OUT_OF_MEMORY); } for (i = 0; i < height; i++) { *(image + i) = buffer + (width * i * 4); } png_read_image(png_ptr, image); free(image); } // Read frame info and frame image pixel. // Pixels buffer will be malloc. static void read_frame(png_structp png_ptr, png_infop info_ptr, PngFrame* frame, PngFrame* pre_frame) { int pre_dop; png_read_frame_head(png_ptr, info_ptr); png_get_next_frame_fcTL(png_ptr, info_ptr, &frame->width, &frame->height, &frame->offset_x, &frame->offset_y, &frame->delay_num, &frame->delay_den, &frame->dop, &frame->bop); // If hide first frame and only one frame, // no fcTL chunk, so width and height will be zero. if (frame->width == 0 || frame->height == 0) { frame->width = png_get_image_width(png_ptr, info_ptr); frame->height = png_get_image_height(png_ptr, info_ptr); frame->offset_x = 0; frame->offset_y = 0; frame->delay_num = 0; frame->delay_den = 1000; frame->dop = PNG_DISPOSE_OP_NONE; frame->bop = PNG_BLEND_OP_SOURCE; } // Set delay if (frame->delay_den != 0) { frame->delay = 1000u * frame->delay_num / frame->delay_den; } else { frame->delay = 0; } // Set pop pre_dop = pre_frame != NULL ? pre_frame->dop : PNG_DISPOSE_OP_BACKGROUND; switch (pre_dop) { case PNG_DISPOSE_OP_NONE: frame->pop = IMAGE_PNG_PREPARE_NONE; break; default: case PNG_DISPOSE_OP_BACKGROUND: frame->pop = IMAGE_PNG_PREPARE_BACKGROUND; break; case PNG_DISPOSE_OP_PREVIOUS: frame->pop = IMAGE_PNG_PREPARE_USE_BACKUP; break; } // Malloc frame->buffer = (png_bytep) malloc(4 * frame->width * frame->height * sizeof(png_byte)); if (frame->buffer == NULL) { png_error(png_ptr, OUT_OF_MEMORY); } // Read pixels read_image(png_ptr, frame->buffer, frame->width, frame->height); } static Stream* get_stream(AnimatedImage* image) { return ((PngData*) image->data)->stream; } static void complete(AnimatedImage* image) { PngData* data = image->data; PngFrame* frame; uint32_t i = 1; uint32_t j; if (image->completed || data->png_ptr == NULL || data->info_ptr == NULL || data->stream == NULL) { return; } // Set new jmp if (setjmp(png_jmpbuf(data->png_ptr))) { // i is decoded frame count now. for (j = i; j < data->frame_count; j++) { frame = data->frames + j; if (frame->buffer == NULL) { break; } else { free(frame->buffer); frame->buffer = NULL; } } data->frame_count = i; png_destroy_read_struct(&data->png_ptr, &data->info_ptr, NULL); return; } for (i = 1; i < data->frame_count; i++) { read_frame(data->png_ptr, data->info_ptr, data->frames + i, data->frames + i - 1); } // End read png_read_end(data->png_ptr, data->info_ptr); png_destroy_read_struct(&data->png_ptr, &data->info_ptr, NULL); // Close stream data->stream->close(&data->stream); // Clean up data->png_ptr = NULL; data->info_ptr = NULL; data->stream = NULL; // Completed image->completed = true; } static uint32_t get_frame_count(AnimatedImage* image) { return ((PngData*)image->data)->frame_count; } static uint32_t get_delay(AnimatedImage* image, uint32_t frame) { PngData* data = image->data; if (frame >= data->frame_count) { LOGE(MSG("Frame count is %ud, can't get delay of index %ud"), data->frame_count, frame); return 0; } return (data->frames + frame)->delay; } static uint32_t get_byte_count(AnimatedImage* image) { uint32_t size = 0; uint32_t i; PngFrame* frame; PngData* data = image->data; if (image->completed) { for (i = 0; i < data->frame_count; i++) { frame = data->frames + i; size += frame->width * frame->height * 4; } return size; } else { LOGE(MSG("Can't call get_byte_count on Uncompleted AnimatedImage")); return 0; } } static void advance(AnimatedImage* image, DelegateImage* dImage) { PngData* data = image->data; int32_t target_index = dImage->index + 1; uint32_t width = image->width; uint32_t height = image->height; PngFrame* frame; if (target_index < 0 || target_index >= data->frame_count) { target_index = 0; } if (target_index == dImage->index) { return; } frame = data->frames + target_index; if (frame->dop == PNG_DISPOSE_OP_PREVIOUS && frame->pop == IMAGE_PNG_PREPARE_USE_BACKUP) { delegate_image_switch_data_backup(dImage); } else { // Backup if (frame->dop == PNG_DISPOSE_OP_PREVIOUS) { delegate_image_backup(dImage); } // Prepare switch (frame->pop) { case IMAGE_PNG_PREPARE_NONE: // Do nothing break; default: case IMAGE_PNG_PREPARE_BACKGROUND: // Set transparent memset(dImage->buffer, '\0', width * height * 4); break; case IMAGE_PNG_PREPARE_USE_BACKUP: delegate_image_restore(dImage); break; } } blend(dImage->buffer, dImage->width, dImage->height, frame->buffer, frame->width, frame->height, frame->offset_x, frame->offset_y, frame->bop == PNG_BLEND_OP_OVER); delegate_image_apply(dImage); dImage->index = target_index; } static void recycle(AnimatedImage** image) { PngData* data; if (image == NULL || *image == NULL) { return; } data = (PngData*) (*image)->data; free_frames(&data->frames, data->frame_count); if (data->png_ptr != NULL || data->info_ptr != NULL) { png_destroy_read_struct(&data->png_ptr, &data->info_ptr, NULL); } data->png_ptr = NULL; data->info_ptr = NULL; if (data->stream != NULL) { data->stream->close(&data->stream); data->stream = NULL; } free(data); (*image)->data = NULL; free(*image); *image = NULL; } void* png_decode(Stream* stream, bool partially, bool* animated) { StaticImage* static_image = NULL; AnimatedImage* animated_image = NULL; PngData* png_data = NULL; PngFrame* frames = NULL; png_structp png_ptr = NULL; png_infop info_ptr = NULL; bool apng; uint32_t width; uint32_t height; uint8_t color_type; uint8_t bit_depth; uint32_t frame_count = 1; bool hide_first_frame = false; bool opaque; int i; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, &user_error_fn, &user_warn_fn); if (png_ptr == NULL) { WTF_OOM; return NULL; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { WTF_OOM; png_destroy_read_struct(&png_ptr, NULL, NULL); return NULL; } if (setjmp(png_jmpbuf(png_ptr))) { static_image_delete(&static_image); free(animated_image); free(png_data); free_frames(&frames, frame_count); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return NULL; } // Init png_set_read_fn(png_ptr, stream, &user_read_fn); png_read_info(png_ptr, info_ptr); // Get info apng = (bool) png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL); width = png_get_image_width(png_ptr, info_ptr); height = png_get_image_height(png_ptr, info_ptr); color_type = png_get_color_type(png_ptr, info_ptr); bit_depth = png_get_bit_depth(png_ptr, info_ptr); if (apng) { frame_count = png_get_num_frames(png_ptr, info_ptr); // Don't hide first frame for only-one-frame png if (frame_count > 1) { hide_first_frame = png_get_first_frame_is_hidden(png_ptr, info_ptr); if (hide_first_frame) { frame_count -= 1; } } } // If only one frame, decode all if (frame_count == 1) { partially = false; } // Check info invalid if (width == 0 || height == 0 || frame_count == 0) { png_error(png_ptr, "Invalid png info"); return NULL; } // Configure to ARGB png_set_expand(png_ptr); if (bit_depth == 16) { png_set_scale_16(png_ptr); } if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); } if (color_type & PNG_COLOR_MASK_ALPHA) { opaque = false; } else { opaque = true; png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); } if (apng) { // Skip first frame if necessary if (hide_first_frame && frame_count > 0) { png_skip_image(png_ptr, info_ptr); } // Malloc frames frames = (PngFrame*) malloc(frame_count * sizeof(PngFrame)); if (frames == NULL) { png_error(png_ptr, OUT_OF_MEMORY); return NULL; } // Set frame buffer NULL for safety for (i = 0; i < frame_count; i++) { (frames + i)->buffer = NULL; } // Read first frame read_frame(png_ptr, info_ptr, frames, NULL); // Fix first frame dop if (frames->dop == PNG_DISPOSE_OP_PREVIOUS) { frames->dop = PNG_DISPOSE_OP_BACKGROUND; } // Read next frame if (!partially) { for (i = 1; i < frame_count; i++) { read_frame(png_ptr, info_ptr, frames + i, frames + i - 1); } // End read png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); } if (frame_count == 1) { // For one-frame apng, use StaticImage static_image = static_image_new(width, height); if (static_image == NULL) { png_error(png_ptr, OUT_OF_MEMORY); return NULL; } memset(static_image->buffer, '\0', width * height * 4); blend(static_image->buffer, width, height, frames->buffer, frames->width, frames->height, frames->offset_x, frames->offset_y, false); // Free frames, don't need it anymore free_frames(&frames, 1); // Set final result static_image->format = IMAGE_FORMAT_PNG; static_image->opaque = opaque; *animated = false; return static_image; } else { // For multi-frame apng, use AnimatedImage animated_image = (AnimatedImage*) malloc(sizeof(AnimatedImage)); png_data = (PngData*) malloc(sizeof(PngData)); if (animated_image == NULL || png_data == NULL) { png_error(png_ptr, OUT_OF_MEMORY); return NULL; } animated_image->width = width; animated_image->height = height; animated_image->format = IMAGE_FORMAT_PNG; animated_image->opaque = opaque; animated_image->completed = !partially; animated_image->data = png_data; animated_image->get_stream = &get_stream; animated_image->complete = &complete; animated_image->get_frame_count = &get_frame_count; animated_image->get_delay = &get_delay; animated_image->get_byte_count = &get_byte_count; animated_image->advance = &advance; animated_image->recycle = &recycle; png_data->frames = frames; png_data->frame_count = frame_count; if (partially) { png_data->png_ptr = png_ptr; png_data->info_ptr = info_ptr; png_data->stream = stream; } else { png_data->png_ptr = NULL; png_data->info_ptr = NULL; png_data->stream = NULL; } return animated_image; } } else { // For png, use StaticImage static_image = static_image_new(width, height); if (static_image == NULL) { png_error(png_ptr, OUT_OF_MEMORY); return NULL; } // Read pixel read_image(png_ptr, static_image->buffer, width, height); // End read png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); // Set final result static_image->format = IMAGE_FORMAT_PNG; static_image->opaque = opaque; *animated = false; return static_image; } } bool png_decode_info(Stream* stream, ImageInfo* info) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, &user_error_fn, &user_warn_fn); if (png_ptr == NULL) { WTF_OOM; return false; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { WTF_OOM; png_destroy_read_struct(&png_ptr, NULL, NULL); return false; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return false; } // Init png_set_read_fn(png_ptr, stream, &user_read_fn); png_read_info(png_ptr, info_ptr); // Assign info->width = png_get_image_width(png_ptr, info_ptr); info->height = png_get_image_height(png_ptr, info_ptr); info->format = IMAGE_FORMAT_PNG; info->opaque = !(png_get_color_type(png_ptr, info_ptr) & PNG_COLOR_MASK_ALPHA); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) { // APNG info->frame_count = png_get_num_frames(png_ptr, info_ptr); if (info->frame_count > 1 && png_get_first_frame_is_hidden(png_ptr, info_ptr)) { --info->frame_count; } } else { info->frame_count = 1; } // End read png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return true; } bool png_decode_buffer(Stream* stream, bool clip, uint32_t x, uint32_t y, uint32_t width, uint32_t height, int32_t config, uint32_t ratio, BufferContainer* container) { png_structp png_ptr = NULL; png_infop info_ptr = NULL; uint32_t i; bool result = false; uint32_t i_width; uint32_t i_height; uint8_t i_color_type; uint8_t i_bit_depth; bool i_opaque; const uint32_t i_components = 4; // Always rgba8888 uint32_t d_width; uint32_t d_height; uint32_t d_stride; bool d_too_small; uint32_t d_components; int32_t pass; uint32_t r_stride; uint32_t r_start_stride; uint8_t* r_buffer = NULL; // Don't free it uint8_t* r_line = NULL; uint8_t* r_line_1 = NULL; uint8_t* r_line_2 = NULL; uint8_t* d_buffer = NULL; uint8_t* d_line = NULL; RowFunc row_func = NULL; // Prepare png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, &user_error_fn, &user_warn_fn); if (png_ptr == NULL) { WTF_OOM; goto end; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { goto end; } if (setjmp(png_jmpbuf(png_ptr))) { goto end; } // Init png_set_read_fn(png_ptr, stream, &user_read_fn); png_read_info(png_ptr, info_ptr); // Get png info i_width = png_get_image_width(png_ptr, info_ptr); i_height = png_get_image_height(png_ptr, info_ptr); i_color_type = png_get_color_type(png_ptr, info_ptr); i_bit_depth = png_get_bit_depth(png_ptr, info_ptr); // Set clip info if (!clip) { // Decode full image x = 0; y = 0; width = i_width; height = i_height; } // Configure output png_set_expand(png_ptr); if (i_bit_depth == 16) { png_set_scale_16(png_ptr); } if (i_color_type == PNG_COLOR_TYPE_GRAY || i_color_type == PNG_COLOR_TYPE_GRAY_ALPHA) { png_set_gray_to_rgb(png_ptr); } if (!(i_color_type & PNG_COLOR_MASK_ALPHA)) { i_opaque = true; png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); } else { i_opaque = false; } pass = png_set_interlace_handling(png_ptr); // Resolve config if (config == IMAGE_CONFIG_AUTO) { config = (int32_t) (i_opaque ? IMAGE_CONFIG_RGB_565 : IMAGE_CONFIG_RGBA_8888); } else if (!is_explicit_config(config)) { LOGE("Invalid config: %d", config); goto end; } // Fix width and height width = floor_uint32_t(width, ratio); height = floor_uint32_t(height, ratio); d_width = width / ratio; d_height = height / ratio; d_too_small = d_width == 0 || d_height == 0; // Create buffer d_buffer = container->create_buffer(container, MAX(d_width, 1), MAX(d_height, 1), config); if (d_buffer == NULL) { goto end; } // Check image ratio too large if (d_too_small) { // Ratio is too large, no need to decode. // Still treat it as success. LOGE("Ratio is too large!"); result = true; goto end; } d_components = get_depth_for_config(config); d_stride = d_width * d_components; r_start_stride = x * i_components; r_stride = i_width * i_components; // Row function row_func = config == IMAGE_CONFIG_RGBA_8888 ? &RGBA8888_to_RGBA8888_row : &RGBA8888_to_RGB565_row; // Read data if (pass > 1) { // Interlaced PNG, read all rows to r_buffer, // then transfer them to d_buffer uint32_t remain_y = i_height - y - height; if (ratio == 1) { r_buffer = malloc(r_stride * height); if (r_buffer == NULL) { WTF_OOM; goto end; } // Read all rows to r_buffer while (--pass >= 0) { // Skip start lines png_skip_rows(png_ptr, y); // Read rows r_line = r_buffer; for (i = 0; i < height; ++i) { png_read_row(png_ptr, r_line, NULL); r_line += r_stride; } // Skip end lines png_skip_rows(png_ptr, remain_y); } // r_buffer to d_buffer d_line = d_buffer; r_line = r_buffer; for (i = 0; i < height; ++i) { row_func(d_line, r_line + r_start_stride, NULL, d_width, 1); d_line += d_stride; r_line += r_stride; } } else { r_buffer = malloc(r_stride * d_height * 2); if (r_buffer == NULL) { WTF_OOM; goto end; } uint32_t temp = ratio - 2; uint32_t skip_start = temp / 2; uint32_t skip_end = temp - skip_start; // Read all rows to r_buffer while (--pass >= 0) { // Skip start lines png_skip_rows(png_ptr, y); // Read rows r_line = r_buffer; for (i = 0; i < d_height; ++i) { png_skip_rows(png_ptr, skip_start); png_read_row(png_ptr, r_line, NULL); r_line += r_stride; png_read_row(png_ptr, r_line, NULL); r_line += r_stride; png_skip_rows(png_ptr, skip_end); } // Skip end lines png_skip_rows(png_ptr, remain_y); } // r_buffer to d_buffer d_line = d_buffer; r_line = r_buffer; for (i = 0; i < d_height; ++i) { row_func(d_line, r_line + r_start_stride, r_line + r_stride + r_start_stride, d_width, ratio); d_line += d_stride; r_line += r_stride * 2; } } } else if (ratio == 1) { r_line_1 = malloc(r_stride); if (r_line_1 == NULL) { WTF_OOM; goto end; } // Skip start lines png_skip_rows(png_ptr, y); // Read lines d_line = d_buffer; for (i = 0; i < d_height; ++i) { png_read_row(png_ptr, r_line_1, NULL); row_func(d_line, r_line_1 + r_start_stride, NULL, d_width, 1); d_line += d_stride; } } else { r_line_1 = malloc(r_stride); r_line_2 = malloc(r_stride); if (r_line_1 == NULL || r_line_2 == NULL) { WTF_OOM; goto end; } // Skip start lines png_skip_rows(png_ptr, y); // Read lines uint32_t temp = ratio - 2; uint32_t skip_start = temp / 2; uint32_t skip_end = temp - skip_start; d_line = d_buffer; for (i = 0; i < d_height; ++i) { png_skip_rows(png_ptr, skip_start); png_read_row(png_ptr, r_line_1, NULL); png_read_row(png_ptr, r_line_2, NULL); row_func(d_line, r_line_1 + r_start_stride, r_line_2 + r_start_stride, d_width, ratio); png_skip_rows(png_ptr, skip_end); d_line += d_stride; } } // It's not necessary to call png_read_end(). // Also the png might not be totally decoded. // Skip it will increase decode speed. // Done result = true; end: free(r_line_1); free(r_line_2); free(r_buffer); if (d_buffer != NULL) { container->release_buffer(container, d_buffer); } png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return result; }
368338.c
#include "Common.h" void addNode(list_node* head,void* o){ list_node* node = newNode(o); _addNode(head,node); } void _addNode(list_node* head,list_node* node){ list_node* p = head; if (p->arg==NULL){ p->arg = node->arg; free(node); return; } while (p->next!=NULL){ p = p->next; } p->next = node; } list_node* newNode(void* a){ list_node* node = (list_node*)malloc(sizeof(list_node)); node->next = NULL; node->arg = a; return node; } void delList(list_node* head,void (*func)(void* arg)){ list_node* t; while (head!=NULL){ t = head->next; if (func!=NULL) func(head->arg); else free(head->arg); free(head); head = t; } } list_node* at(list_node* head,int pos){ list_node* p = head; int i = 0; for (i=1;i<pos;++i){ if (p==NULL) return NULL; p = p->next; } return p; } list_node* pickNode(list_node* head,int pos){ if (pos==0) return head; list_node* n = at(head,pos-1); if (n==NULL || n->next==NULL) return NULL; list_node* ne = n->next; n->next = ne->next; return ne; } pair* newPair(void* a,void* b){ pair* p = (pair*)malloc(sizeof(pair)); p->a = a; p->b = b; return p; } void delPair(pair* p){ free(p); } void linkNode(list_node* head,list_node* _head){ list_node* tmp = head; while (tmp->next!=NULL) tmp = tmp->next; tmp->next = _head; } task_e* funcZeroArg(void(*func)()){ task_e* e = (task_e*)MEMALLOC(sizeof(task_e)); e->num = 0; e->f.Zero.func = func; return e; } task_e* funcOneArg(void(*func)(void*),void* arg){ task_e* e = (task_e*)MEMALLOC(sizeof(task_e)); e->num = 1; e->f.One.func = func; e->f.One.arg1 = arg; return e; } task_e* funcTwoArg(void(*func)(void*,void*),void* arg1,void* arg2){ task_e* e = (task_e*)MEMALLOC(sizeof(task_e)); e->num = 2; e->f.Two.func = func; e->f.Two.arg1 = arg1; e->f.Two.arg2 = arg2; return e; } task_e* funcThreeArg(void(*func)(void*,void*,void*),void* arg1,void* arg2,void* arg3){ task_e* e = (task_e*)MEMALLOC(sizeof(task_e)); e->num = 3; e->f.Three.func = func; e->f.Three.arg1 = arg1; e->f.Three.arg2 = arg2; e->f.Three.arg3 = arg3; return e; } task_e* funcFourArg(void(*func)(void*,void*,void*,void*),void* arg1,void* arg2,void* arg3,void* arg4){ task_e* e = (task_e*)MEMALLOC(sizeof(task_e)); e->num = 4; e->f.Four.func = func; e->f.Four.arg1 = arg1; e->f.Four.arg2 = arg2; e->f.Four.arg3 = arg3; e->f.Four.arg4 = arg4; return e; } void invokeArgs_e(task_e* t){ switch (t->num){ case 0: t->f.Zero.func(); break; case 1: t->f.One.func(t->f.One.arg1); break; case 2: t->f.Two.func(t->f.Two.arg1,t->f.Two.arg2); break; case 3: t->f.Three.func(t->f.Three.arg1,t->f.Three.arg2,t->f.Three.arg3); break; case 4: t->f.Four.func(t->f.Four.arg1,t->f.Four.arg2,t->f.Four.arg3,t->f.Four.arg4); break; } } void inline free_taske(task_e* t){ DEMEMALLOC((void*)t); } pthread_cond_t _cond; pthread_mutex_t _mtx; void _wake(int sig){ pthread_cond_broadcast(&_cond); } void sync(){ struct sigaction act; act.sa_handler = _wake; act.sa_flags = 0; sigemptyset(&act.sa_mask); sigaction(SIGINT,&act,NULL); pthread_cond_init(&_cond,NULL); pthread_mutex_init(&_mtx,NULL); pthread_mutex_lock(&_mtx); pthread_cond_wait(&_cond,&_mtx); pthread_mutex_unlock(&_mtx); }
467433.c
static const struct Animation anim_5C[] = { 1, 189, 0, 0, 0x14, ANIMINDEX_NUMPARTS(anim_5C_indices), anim_5C_values, anim_5C_indices, 0, }; static const u16 anim_5C_indices[] = { 0x0015, 0x0001, 0x0015, 0x0016, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x002B, 0x0001, 0x0000, 0x0015, 0x0236, 0x0015, 0x024B, 0x0015, 0x0260, 0x0015, 0x01F7, 0x0015, 0x020C, 0x0015, 0x0221, 0x0015, 0x01B8, 0x0015, 0x01CD, 0x0015, 0x01E2, 0x0001, 0x01B4, 0x0001, 0x01B5, 0x0001, 0x01B6, 0x0015, 0x0030, 0x0015, 0x0045, 0x0015, 0x005A, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x002F, 0x0001, 0x002C, 0x0001, 0x002D, 0x0001, 0x002E, 0x0001, 0x01B0, 0x0001, 0x01B1, 0x0001, 0x01B2, 0x0015, 0x0087, 0x0015, 0x009C, 0x0015, 0x00B1, 0x0001, 0x0000, 0x0001, 0x0000, 0x0015, 0x0072, 0x0001, 0x006F, 0x0001, 0x0070, 0x0001, 0x0071, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x01B3, 0x0015, 0x0171, 0x0015, 0x0186, 0x0015, 0x019B, 0x0001, 0x0000, 0x0001, 0x0000, 0x0015, 0x015C, 0x0015, 0x011D, 0x0015, 0x0132, 0x0015, 0x0147, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x01B7, 0x0015, 0x00DE, 0x0015, 0x00F3, 0x0015, 0x0108, 0x0001, 0x0000, 0x0001, 0x0000, 0x0015, 0x00C9, 0x0001, 0x00C6, 0x0001, 0x00C7, 0x0001, 0x00C8, }; static const s16 anim_5C_values[] = { 0x0000, 0xFFC3, 0xFFD2, 0xFFE4, 0xFFF8, 0x000A, 0x001A, 0x0028, 0x0036, 0x0042, 0x004C, 0x0050, 0x0050, 0x004D, 0x0047, 0x003F, 0x0038, 0x0031, 0x002B, 0x0024, 0x001E, 0x001B, 0x00BD, 0x00BF, 0x00C2, 0x00C5, 0x00C9, 0x00CC, 0x00CE, 0x00D2, 0x00D5, 0x00D7, 0x00D7, 0x00D6, 0x00D3, 0x00D0, 0x00CC, 0x00C8, 0x00C5, 0x00C2, 0x00BF, 0x00BD, 0x00BD, 0x3FFF, 0xFF8A, 0xF980, 0xF06F, 0xF085, 0x4A46, 0x476A, 0x4375, 0x3EFC, 0x3A96, 0x36D7, 0x3456, 0x34E1, 0x37DA, 0x3A32, 0x38D8, 0x33AA, 0x2CE1, 0x2500, 0x1C86, 0x13F5, 0x0BCC, 0x048E, 0xFEBB, 0xFAD2, 0xF955, 0xD9C9, 0xDBDD, 0xDE87, 0xE17D, 0xE472, 0xE71A, 0xE929, 0xEABB, 0xEBD4, 0xEC05, 0xEADF, 0xE883, 0xE580, 0xE20A, 0xDE51, 0xDA89, 0xD6E4, 0xD394, 0xD0CC, 0xCEBE, 0xCD9D, 0x3EAD, 0x42BB, 0x48DC, 0x5004, 0x5725, 0x5D35, 0x6127, 0x5FD4, 0x5A77, 0x5691, 0x59A2, 0x63D4, 0x7101, 0x803F, 0x909D, 0xA12E, 0xB106, 0xBF38, 0xCAD6, 0xD2F3, 0xD6A1, 0x0F57, 0x0217, 0xF7EF, 0xF8B2, 0xF819, 0xF756, 0xF676, 0xF588, 0xF499, 0xF3B6, 0xF2EE, 0xF24E, 0xF1E4, 0xF1BE, 0xF1F3, 0xF281, 0xF354, 0xF453, 0xF569, 0xF67F, 0xF77E, 0xF850, 0xF8DF, 0xF913, 0x1B7F, 0x1685, 0x0FD5, 0x07F0, 0xFF5A, 0xF692, 0xEE1B, 0xE677, 0xE027, 0xDBAE, 0xD98D, 0xDA5D, 0xDDF0, 0xE39B, 0xEAB1, 0xF28A, 0xFA78, 0x01D2, 0x07ED, 0x0C1D, 0x0DB8, 0x21A3, 0x2195, 0x21FD, 0x22BC, 0x23B6, 0x24CB, 0x25E0, 0x26D5, 0x278D, 0x27EA, 0x27D0, 0x2728, 0x2605, 0x2486, 0x22CC, 0x20F5, 0x1F20, 0x1D6D, 0x1BFB, 0x1AE9, 0x1A58, 0xD591, 0xCF1C, 0xC63C, 0xBB88, 0xAF92, 0xA2F2, 0x963B, 0x8A02, 0x7ED9, 0x755B, 0x6E1A, 0x68F3, 0x6537, 0x62A6, 0x60FF, 0x6001, 0x5F6E, 0x5F04, 0x5E83, 0x5DAC, 0x5C3E, 0x001B, 0x025B, 0xCB25, 0x403A, 0x3D08, 0x3978, 0x36DA, 0x3680, 0x38F7, 0x3D4D, 0x4299, 0x47F4, 0x4C73, 0x4F2E, 0x507B, 0x5158, 0x51D3, 0x51F9, 0x51DB, 0x5185, 0x5107, 0x5070, 0x4FCD, 0x4F2E, 0x0F1A, 0x0E84, 0x0DE3, 0x0D3F, 0x0C9C, 0x0C02, 0x0B75, 0x0AFB, 0x0A9C, 0x0A5C, 0x0A41, 0x0A54, 0x0A94, 0x0AF9, 0x0B7A, 0x0C11, 0x0CB4, 0x0D5D, 0x0E03, 0x0E9E, 0x0F26, 0x0A48, 0x0B27, 0x0C59, 0x0DC1, 0x0F44, 0x10C6, 0x122A, 0x1355, 0x142B, 0x148F, 0x1467, 0x1378, 0x11BD, 0x0F6C, 0x0CB9, 0x09D8, 0x06FF, 0x0461, 0x0234, 0x00AB, 0xFFFD, 0xB64D, 0xB534, 0xB3F2, 0xB297, 0xB131, 0xAFD0, 0xAE84, 0xAD5C, 0xAC68, 0xABB7, 0xAB59, 0xAB5A, 0xABB1, 0xAC4F, 0xAD25, 0xAE22, 0xAF37, 0xB055, 0xB16A, 0xB268, 0xB340, 0x0016, 0x0012, 0x000F, 0x000F, 0x0011, 0x0014, 0x0018, 0x001D, 0x0029, 0x003C, 0x0051, 0x0062, 0x0069, 0x0066, 0x005F, 0x0054, 0x0047, 0x003A, 0x002E, 0x0024, 0x001D, 0xFEDE, 0xFEDD, 0xFEDD, 0xFEDD, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE1, 0xFEE4, 0xFEE8, 0xFEED, 0xFEF1, 0xFEF3, 0xFEF2, 0xFEF1, 0xFEEE, 0xFEEB, 0xFEE8, 0xFEE5, 0xFEE2, 0xFEE1, 0xDF45, 0xDFF4, 0xE04B, 0xE053, 0xE016, 0xDFA0, 0xDEFB, 0xDE31, 0xDC81, 0xD9B5, 0xD6A7, 0xD432, 0xD330, 0xD398, 0xD4AD, 0xD63D, 0xD814, 0xD9FE, 0xDBC9, 0xDD40, 0xDE31, 0x123E, 0x1235, 0x12A6, 0x1395, 0x1506, 0x16FB, 0x197A, 0x1C85, 0x223D, 0x2B08, 0x344D, 0x3B77, 0x3DED, 0x3BAE, 0x36F6, 0x308E, 0x2941, 0x21D6, 0x1B16, 0x15CB, 0x12BD, 0xEADD, 0xEB2B, 0xEC3A, 0xEDD2, 0xEFBE, 0xF1C6, 0xF3B5, 0xF554, 0xF6FC, 0xF8F4, 0xFAED, 0xFC97, 0xFDA0, 0xFE18, 0xFE4C, 0xFE4E, 0xFE2A, 0xFDF1, 0xFDB2, 0xFD7B, 0xFD5C, 0xFC33, 0xF968, 0xF5B5, 0xF18D, 0xED64, 0xE9AD, 0xE6DE, 0xE568, 0xE67E, 0xEA11, 0xEEB2, 0xF2F4, 0xF56A, 0xF647, 0xF6BA, 0xF6CF, 0xF694, 0xF616, 0xF560, 0xF481, 0xF385, 0xCD7C, 0xCD27, 0xCC46, 0xCB0C, 0xC9B1, 0xC868, 0xC768, 0xC6E5, 0xC713, 0xC7D0, 0xC8D2, 0xC9D0, 0xCA7E, 0xCAE3, 0xCB38, 0xCB7F, 0xCBBC, 0xCBF0, 0xCC20, 0xCC4E, 0xCC7D, 0x8001, 0x8001, 0x4171, 0xBF5F, 0x8001, 0x8001, 0x4171, 0xBF5F, 0x070A, 0x028B, 0xFDC3, 0xF8DC, 0xF403, 0xEF64, 0xEB2B, 0xE785, 0xE49D, 0xE2A0, 0xE1B9, 0xE238, 0xE41E, 0xE726, 0xEB09, 0xEF7F, 0xF442, 0xF90A, 0xFD92, 0x0191, 0x04C2, 0x02D7, 0x044A, 0x05CE, 0x0756, 0x08D4, 0x0A39, 0x0B79, 0x0C84, 0x0D4E, 0x0DC9, 0x0DE6, 0x0D98, 0x0CE6, 0x0BDD, 0x0A8A, 0x08FD, 0x0743, 0x056A, 0x0380, 0x0193, 0xFFB2, 0x1949, 0x180A, 0x15DC, 0x1300, 0x0FB2, 0x0C33, 0x08C0, 0x0597, 0x02F7, 0x011F, 0x004C, 0x00BB, 0x024B, 0x04B2, 0x07A5, 0x0ADA, 0x0E06, 0x10DF, 0x131A, 0x146E, 0x148E, 0xF22E, 0xF54C, 0xF90C, 0xFD39, 0x019C, 0x0602, 0x0A35, 0x0DFF, 0x112B, 0x1384, 0x14D5, 0x14FA, 0x1416, 0x125C, 0x0FFD, 0x0D2B, 0x0A19, 0x06F8, 0x03FB, 0x0154, 0xFF37, 0x1105, 0x0FDF, 0x0E74, 0x0CD4, 0x0B0D, 0x092F, 0x0749, 0x056A, 0x03A1, 0x01FE, 0x008F, 0xFF28, 0xFD9D, 0xFC04, 0xFA74, 0xF8FF, 0xF7BD, 0xF6C2, 0xF623, 0xF5F6, 0xF64F, 0xF985, 0xF88F, 0xF76C, 0xF62E, 0xF4EB, 0xF3B6, 0xF2A2, 0xF1C4, 0xF130, 0xF0F8, 0xF132, 0xF210, 0xF39A, 0xF5A5, 0xF808, 0xFA97, 0xFD28, 0xFF90, 0x01A4, 0x033C, 0x042B, 0xFCA8, 0x0154, 0x0660, 0x0B9C, 0x10D6, 0x15E1, 0x1A8A, 0x1EA4, 0x21FE, 0x2468, 0x25B3, 0x25B5, 0x2486, 0x2255, 0x1F53, 0x1BAF, 0x1799, 0x1341, 0x0ED7, 0x0A8B, 0x068D, 0x00FA, 0x037B, 0x0616, 0x08B1, 0x0B34, 0x0D85, 0x0F8A, 0x112A, 0x124D, 0x12D9, 0x12B4, 0x119C, 0x0F83, 0x0C9F, 0x0924, 0x054A, 0x0145, 0xFD4D, 0xF995, 0xF653, 0xF3BE, 0x2FA6, 0x2FDF, 0x305C, 0x3109, 0x31D4, 0x32A9, 0x3374, 0x3424, 0x34A3, 0x34DF, 0x34C5, 0x3430, 0x3320, 0x31B7, 0x3018, 0x2E66, 0x2CC3, 0x2B53, 0x2A38, 0x2995, 0x298D, };
440375.c
#include <noclass.h> void Java_noclass_find_1it (JNIEnv *env, jclass k) { /* We cause an exception by asking for a class we know does not exist. */ k = (*env)->FindClass (env, "java/lang/Sarcophagus"); }
804434.c
/* * Copyright (c) 2021 Telink Semiconductor * * SPDX-License-Identifier: Apache-2.0 */ #define DT_DRV_COMPAT telink_b91_pwm #include "pwm.h" #include "clock.h" #include <drivers/pwm.h> #include <drivers/pinctrl.h> #define PWM_PCLK_SPEED DT_INST_PROP(0, clock_frequency) #define NUM_OF_CHANNELS DT_INST_PROP(0, channels) PINCTRL_DT_INST_DEFINE(0); static const struct pinctrl_dev_config *pcfg = PINCTRL_DT_INST_DEV_CONFIG_GET(0); /* API implementation: init */ static int pwm_b91_init(const struct device *dev) { ARG_UNUSED(dev); uint32_t status = 0; uint8_t clk_32k_en = 0; uint32_t pwm_clk_div = 0; /* Calculate and check PWM clock divider */ pwm_clk_div = sys_clk.pclk * 1000 * 1000 / PWM_PCLK_SPEED - 1; if (pwm_clk_div > 255) { return -EINVAL; } /* Set PWM Peripheral clock */ pwm_set_clk((unsigned char) (pwm_clk_div & 0xFF)); /* Set PWM 32k Channel clock if enabled */ clk_32k_en |= DT_INST_PROP(0, clk32k_ch0_enable) ? PWM_CLOCK_32K_CHN_PWM0 : 0; clk_32k_en |= DT_INST_PROP(0, clk32k_ch1_enable) ? PWM_CLOCK_32K_CHN_PWM1 : 0; clk_32k_en |= DT_INST_PROP(0, clk32k_ch2_enable) ? PWM_CLOCK_32K_CHN_PWM2 : 0; clk_32k_en |= DT_INST_PROP(0, clk32k_ch3_enable) ? PWM_CLOCK_32K_CHN_PWM3 : 0; clk_32k_en |= DT_INST_PROP(0, clk32k_ch4_enable) ? PWM_CLOCK_32K_CHN_PWM4 : 0; clk_32k_en |= DT_INST_PROP(0, clk32k_ch5_enable) ? PWM_CLOCK_32K_CHN_PWM5 : 0; pwm_32k_chn_en(clk_32k_en); /* Config PWM pins */ status = pinctrl_apply_state(pcfg, PINCTRL_STATE_DEFAULT); if (status < 0) { return status; } return 0; } /* API implementation: set_cycles */ static int pwm_b91_set_cycles(const struct device *dev, uint32_t channel, uint32_t period_cycles, uint32_t pulse_cycles, pwm_flags_t flags) { ARG_UNUSED(dev); /* check pwm channel */ if (channel >= NUM_OF_CHANNELS) { return -EINVAL; } /* check size of pulse and period (2 bytes) */ if ((period_cycles > 0xFFFFu) || (pulse_cycles > 0xFFFFu)) { return -EINVAL; } /* set polarity */ if (flags & PWM_POLARITY_INVERTED) { pwm_invert_en(channel); } else { pwm_invert_dis(channel); } /* set pulse and period */ pwm_set_tcmp(channel, pulse_cycles); pwm_set_tmax(channel, period_cycles); /* start pwm */ pwm_start(channel); return 0; } /* API implementation: get_cycles_per_sec */ static int pwm_b91_get_cycles_per_sec(const struct device *dev, uint32_t channel, uint64_t *cycles) { ARG_UNUSED(dev); /* check pwm channel */ if (channel >= NUM_OF_CHANNELS) { return -EINVAL; } if ( ((channel == 0u) && DT_INST_PROP(0, clk32k_ch0_enable)) || ((channel == 1u) && DT_INST_PROP(0, clk32k_ch1_enable)) || ((channel == 2u) && DT_INST_PROP(0, clk32k_ch2_enable)) || ((channel == 3u) && DT_INST_PROP(0, clk32k_ch3_enable)) || ((channel == 4u) && DT_INST_PROP(0, clk32k_ch4_enable)) || ((channel == 5u) && DT_INST_PROP(0, clk32k_ch5_enable)) ) { *cycles = 32000u; } else { *cycles = sys_clk.pclk * 1000 * 1000 / (reg_pwm_clkdiv + 1); } return 0; } /* PWM driver APIs structure */ static const struct pwm_driver_api pwm_b91_driver_api = { .set_cycles = pwm_b91_set_cycles, .get_cycles_per_sec = pwm_b91_get_cycles_per_sec, }; BUILD_ASSERT(DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) <= 1, "unsupported PWM instance"); /* PWM driver registration */ #define PWM_B91_INIT(n) \ \ DEVICE_DT_INST_DEFINE(n, pwm_b91_init, \ NULL, NULL, NULL, \ POST_KERNEL, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, \ &pwm_b91_driver_api); DT_INST_FOREACH_STATUS_OKAY(PWM_B91_INIT)
717396.c
/* * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/x509.h> #include <stdio.h> #include "internal/cryptlib.h" int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI* x, EVP_PKEY* pkey) { if ((x == NULL) || (x->spkac == NULL)) return 0; return X509_PUBKEY_set(&(x->spkac->pubkey), pkey); } EVP_PKEY* NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI* x) { if ((x == NULL) || (x->spkac == NULL)) return NULL; return X509_PUBKEY_get(x->spkac->pubkey); } /* Load a Netscape SPKI from a base64 encoded string */ NETSCAPE_SPKI* NETSCAPE_SPKI_b64_decode(const char* str, int len) { unsigned char* spki_der; const unsigned char* p; int spki_len; NETSCAPE_SPKI* spki; if (len <= 0) len = strlen(str); if ((spki_der = OPENSSL_malloc(len + 1)) == NULL) { X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, ERR_R_MALLOC_FAILURE); return NULL; } spki_len = EVP_DecodeBlock(spki_der, (const unsigned char*)str, len); if (spki_len < 0) { X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, X509_R_BASE64_DECODE_ERROR); OPENSSL_free(spki_der); return NULL; } p = spki_der; spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len); OPENSSL_free(spki_der); return spki; } /* Generate a base64 encoded string from an SPKI */ char* NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI* spki) { unsigned char *der_spki, *p; char* b64_str; int der_len; der_len = i2d_NETSCAPE_SPKI(spki, NULL); der_spki = OPENSSL_malloc(der_len); b64_str = OPENSSL_malloc(der_len * 2); if (der_spki == NULL || b64_str == NULL) { X509err(X509_F_NETSCAPE_SPKI_B64_ENCODE, ERR_R_MALLOC_FAILURE); OPENSSL_free(der_spki); OPENSSL_free(b64_str); return NULL; } p = der_spki; i2d_NETSCAPE_SPKI(spki, &p); EVP_EncodeBlock((unsigned char*)b64_str, der_spki, der_len); OPENSSL_free(der_spki); return b64_str; }
216843.c
/* * Samsung Exynos5 SoC series Sensor driver * * * Copyright (c) 2016 Samsung Electronics Co., Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/i2c.h> #include <linux/slab.h> #include <linux/irq.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/version.h> #include <linux/gpio.h> #include <linux/clk.h> #include <linux/regulator/consumer.h> #include <linux/videodev2.h> #include <linux/videodev2_exynos_camera.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/of_gpio.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #include <exynos-fimc-is-sensor.h> #include "fimc-is-hw.h" #include "fimc-is-core.h" #include "fimc-is-device-sensor.h" #include "fimc-is-device-sensor-peri.h" #include "fimc-is-resourcemgr.h" #include "fimc-is-dt.h" #include "fimc-is-device-module-base.h" #define MAX_2P6_SETPIN_CNT 2 enum sensor_module_2p6_actuator { SENSOR_MODULE_2P6_WITHOUT_ACTUATOR = 0, SENSOR_MODULE_2P6_WITH_ACTUATOR = 1, }; enum sensor_module_2p6_position { SENSOR_MODULE_2P6_REAR = 0, SENSOR_MODULE_2P6_FRONT = 1, }; static struct fimc_is_sensor_cfg config_module_2p6[] = { /* 4608x3456@30fps */ FIMC_IS_SENSOR_CFG_EXT(4608, 3456, 30, 36, 0, CSI_DATA_LANES_4, 1443), /* 4608x2624@30fps */ FIMC_IS_SENSOR_CFG_EXT(4608, 2624, 30, 36, 1, CSI_DATA_LANES_4, 1443), /* 4608x2240@30fps */ FIMC_IS_SENSOR_CFG_EXT(4608, 2240, 30, 36, 2, CSI_DATA_LANES_4, 1443), /* 2304x1728@30fps */ FIMC_IS_SENSOR_CFG_EXT(2304, 1728, 30, 34, 3, CSI_DATA_LANES_4, 1352), /* 2304x1728@15fps */ FIMC_IS_SENSOR_CFG_EXT(2304, 1728, 15, 34, 4, CSI_DATA_LANES_4, 1352), /* 2304x1312@30fps */ FIMC_IS_SENSOR_CFG_EXT(2304, 1312, 30, 34, 5, CSI_DATA_LANES_4, 1352), /* 2304x1120@30fps */ FIMC_IS_SENSOR_CFG_EXT(2304, 1120, 30, 34, 6, CSI_DATA_LANES_4, 1352), /* 1152x864@120fps */ FIMC_IS_SENSOR_CFG_EXT(1152, 864, 120, 34, 7, CSI_DATA_LANES_4, 1352), /* 1152x656@120fps */ FIMC_IS_SENSOR_CFG_EXT(1152, 656, 120, 34, 8, CSI_DATA_LANES_4, 1352), }; static struct fimc_is_vci vci_module_2p6[] = { { .pixelformat = V4L2_PIX_FMT_SBGGR10, .config = {{0, HW_FORMAT_RAW10}, {1, HW_FORMAT_USER}, {2, 0}, {3, 0} } }, { .pixelformat = V4L2_PIX_FMT_SBGGR12, .config = {{0, HW_FORMAT_RAW10}, {1, HW_FORMAT_USER}, {2, 0}, {3, 0} } }, { .pixelformat = V4L2_PIX_FMT_SBGGR16, .config = {{0, HW_FORMAT_RAW10}, {1, HW_FORMAT_USER}, {2, 0}, {3, 0} } } }; static const struct v4l2_subdev_core_ops core_ops = { .init = sensor_module_init, .g_ctrl = sensor_module_g_ctrl, .s_ctrl = sensor_module_s_ctrl, .g_ext_ctrls = sensor_module_g_ext_ctrls, .s_ext_ctrls = sensor_module_s_ext_ctrls, .ioctl = sensor_module_ioctl, .log_status = sensor_module_log_status, }; static const struct v4l2_subdev_video_ops video_ops = { .s_stream = sensor_module_s_stream, .s_mbus_fmt = sensor_module_s_format, }; static const struct v4l2_subdev_ops subdev_ops = { .core = &core_ops, .video = &video_ops, }; static int sensor_module_2p6_power_setpin_with_af(struct platform_device *pdev, struct exynos_platform_fimc_is_module *pdata) { struct device *dev; struct device_node *dnode; int gpio_reset = 0; int gpio_none = 0; int gpio_cam_2p8_en = 0; int gpio_cam_core_en = 0; int gpio_camaf_2p8_en = 0; int gpio_camio_1p8_en = 0; BUG_ON(!pdev); dev = &pdev->dev; dnode = dev->of_node; dev_info(dev, "%s E v4\n", __func__); gpio_reset = of_get_named_gpio(dnode, "gpio_reset", 0); if (!gpio_is_valid(gpio_reset)) { dev_err(dev, "failed to get PIN_RESET\n"); return -EINVAL; } else { gpio_request_one(gpio_reset, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_reset); } gpio_cam_2p8_en = of_get_named_gpio(dnode, "gpio_cam_2p8_en", 0); if (!gpio_is_valid(gpio_cam_2p8_en)) { dev_err(dev, "failed to get gpio_cam_2p8_en\n"); } else { gpio_request_one(gpio_cam_2p8_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_cam_2p8_en); } gpio_cam_core_en = of_get_named_gpio(dnode, "gpio_cam_core_en", 0); if (!gpio_is_valid(gpio_cam_core_en)) { dev_err(dev, "failed to get gpio_cam_core_en\n"); } else { gpio_request_one(gpio_cam_core_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_cam_core_en); } gpio_camaf_2p8_en = of_get_named_gpio(dnode, "gpio_camaf_2p8_en", 0); if (!gpio_is_valid(gpio_camaf_2p8_en)) { err("%s failed to get gpio_camaf_2p8_en\n", __func__); } else { gpio_request_one(gpio_camaf_2p8_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_camaf_2p8_en); } gpio_camio_1p8_en = of_get_named_gpio(dnode, "gpio_camio_1p8_en", 0); if (!gpio_is_valid(gpio_camio_1p8_en)) { err("%s failed to get gpio_camio_1p8_en\n", __func__); } else { gpio_request_one(gpio_camio_1p8_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_camio_1p8_en); } SET_PIN_INIT(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON); SET_PIN_INIT(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF); SET_PIN_INIT(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON); SET_PIN_INIT(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF); /* BACK CAMERA - POWER ON */ SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_reset, "sen_rst low", PIN_OUTPUT, 0, 0); if (gpio_is_valid(gpio_cam_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_cam_2p8_en, "gpio_cam_2p8_en", PIN_OUTPUT, 1, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDD_CAM_SENSOR_A2P8", PIN_REGULATOR, 1, 0); } if (gpio_is_valid(gpio_cam_core_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_cam_core_en, "gpio_cam_core_en", PIN_OUTPUT, 1, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDDD_1.2V_CAM", PIN_REGULATOR, 1, 0); } if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 1, 3000); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 1, 3000); } if (gpio_is_valid(gpio_camaf_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_camaf_2p8_en, "gpio_camaf_2p8_en", PIN_OUTPUT, 1, 5000); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDD_CAM_AF_2P8", PIN_REGULATOR, 1, 5000); } SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_reset, "sen_rst high", PIN_OUTPUT, 1, 1000); SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "pin", PIN_FUNCTION, 1, 3000); /* BACK CAEMRA - POWER OFF */ SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "pin", PIN_FUNCTION, 0, 1000); if (gpio_is_valid(gpio_camaf_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_camaf_2p8_en, "gpio_camaf_2p8_en", PIN_OUTPUT, 0, 2000); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDD_CAM_AF_2P8", PIN_REGULATOR, 0, 2000); } SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_reset, "sen_rst", PIN_OUTPUT, 0, 0); if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 0, 0); } if (gpio_is_valid(gpio_cam_core_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_cam_core_en, "gpio_cam_core_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDDD_1.2V_CAM", PIN_REGULATOR, 0, 0); } if (gpio_is_valid(gpio_cam_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_cam_2p8_en, "gpio_cam_2p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDD_CAM_SENSOR_A2P8", PIN_REGULATOR, 0, 0); } /* READ_ROM - POWER ON */ if (gpio_is_valid(gpio_camaf_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_camaf_2p8_en, "gpio_camaf_2p8_en", PIN_OUTPUT, 1, 2000); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_none, "VDD_CAM_AF_2P8", PIN_REGULATOR, 1, 2000); } if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 1, 2000); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 1, 2000); } /* READ_ROM - POWER OFF */ if (gpio_is_valid(gpio_camaf_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_camaf_2p8_en, "gpio_camaf_2p8_en", PIN_OUTPUT, 0, 10); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_none, "VDD_CAM_AF_2P8", PIN_REGULATOR, 0, 10); } if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_camio_1p8_en, "camio_1p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 0, 0); } dev_info(dev, "%s X v4\n", __func__); return 0; } static int sensor_module_2p6_power_setpin(struct platform_device *pdev, struct exynos_platform_fimc_is_module *pdata) { struct device *dev; struct device_node *dnode; int gpio_reset = 0; int gpio_none = 0; int gpio_cam_2p8_en = 0; int gpio_cam_core_en = 0; int gpio_camio_1p8_en = 0; BUG_ON(!pdev); dev = &pdev->dev; dnode = dev->of_node; dev_info(dev, "%s E v4\n", __func__); gpio_reset = of_get_named_gpio(dnode, "gpio_reset", 0); if (!gpio_is_valid(gpio_reset)) { dev_err(dev, "failed to get PIN_RESET\n"); return -EINVAL; } else { gpio_request_one(gpio_reset, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_reset); } gpio_cam_2p8_en = of_get_named_gpio(dnode, "gpio_cam_2p8_en", 0); if (!gpio_is_valid(gpio_cam_2p8_en)) { dev_err(dev, "failed to get gpio_cam_2p8_en\n"); } else { gpio_request_one(gpio_cam_2p8_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_cam_2p8_en); } gpio_cam_core_en = of_get_named_gpio(dnode, "gpio_cam_core_en", 0); if (!gpio_is_valid(gpio_cam_core_en)) { dev_err(dev, "failed to get gpio_cam_core_en\n"); } else { gpio_request_one(gpio_cam_core_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_cam_core_en); } gpio_camio_1p8_en = of_get_named_gpio(dnode, "gpio_camio_1p8_en", 0); if (!gpio_is_valid(gpio_camio_1p8_en)) { err("%s failed to get gpio_camio_1p8_en\n", __func__); } else { gpio_request_one(gpio_camio_1p8_en, GPIOF_OUT_INIT_LOW, "CAM_GPIO_OUTPUT_LOW"); gpio_free(gpio_camio_1p8_en); } SET_PIN_INIT(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON); SET_PIN_INIT(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF); SET_PIN_INIT(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON); SET_PIN_INIT(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF); /* BACK CAMERA - POWER ON */ SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_reset, "sen_rst low", PIN_OUTPUT, 0, 0); if (gpio_is_valid(gpio_cam_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_cam_2p8_en, "gpio_cam_2p8_en", PIN_OUTPUT, 1, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDD_CAM_SENSOR_A2P8", PIN_REGULATOR, 1, 0); } if (gpio_is_valid(gpio_cam_core_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_cam_core_en, "gpio_cam_core_en", PIN_OUTPUT, 1, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDDD_1.2V_CAM", PIN_REGULATOR, 1, 0); } if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 1, 2000); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 1, 2000); } SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_reset, "sen_rst high", PIN_OUTPUT, 1, 1000); SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_ON, gpio_none, "pin", PIN_FUNCTION, 1, 3000); /* BACK CAEMRA - POWER OFF */ SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "pin", PIN_FUNCTION, 0, 0); SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_reset, "sen_rst", PIN_OUTPUT, 0, 0); if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 0, 0); } if (gpio_is_valid(gpio_cam_core_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_cam_core_en, "gpio_cam_core_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDDD_1.2V_CAM", PIN_REGULATOR, 0, 0); } if (gpio_is_valid(gpio_cam_2p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_cam_2p8_en, "gpio_cam_2p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_NORMAL, GPIO_SCENARIO_OFF, gpio_none, "VDD_CAM_SENSOR_A2P8", PIN_REGULATOR, 0, 0); } /* READ_ROM - POWER ON */ if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_camio_1p8_en, "gpio_camio_1p8_en", PIN_OUTPUT, 1, 2000); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_ON, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 1, 2000); } /* READ_ROM - POWER OFF */ if (gpio_is_valid(gpio_camio_1p8_en)) { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_camio_1p8_en, "camio_1p8_en", PIN_OUTPUT, 0, 0); } else { SET_PIN(pdata, SENSOR_SCENARIO_READ_ROM, GPIO_SCENARIO_OFF, gpio_none, "VDDIO_1.8V_CAM", PIN_REGULATOR, 0, 0); } dev_info(dev, "%s X v4\n", __func__); return 0; } static int (*module_2p6_power_setpin[MAX_2P6_SETPIN_CNT])(struct platform_device *pdev, struct exynos_platform_fimc_is_module *pdata) = { sensor_module_2p6_power_setpin, sensor_module_2p6_power_setpin_with_af, }; int sensor_module_2p6_probe(struct platform_device *pdev) { int ret = 0; u8 exist_actuator = 0; struct device_node *af_np; struct fimc_is_core *core; struct v4l2_subdev *subdev_module; struct fimc_is_module_enum *module; struct fimc_is_device_sensor *device; struct sensor_open_extended *ext; struct exynos_platform_fimc_is_module *pdata; struct device *dev; BUG_ON(!fimc_is_dev); core = (struct fimc_is_core *)dev_get_drvdata(fimc_is_dev); if (!core) { probe_info("core device is not yet probed"); return -EPROBE_DEFER; } dev = &pdev->dev; af_np = of_find_node_by_name(dev->of_node, "af"); if (!af_np) { exist_actuator = SENSOR_MODULE_2P6_WITHOUT_ACTUATOR; dev_info(dev, "[DHL] Front CAM..!!\n"); } else{ exist_actuator = SENSOR_MODULE_2P6_WITH_ACTUATOR; dev_info(dev, "[DHL] Rear CAM..!!\n"); } probe_info("%s exist_actuator(%d)\n", __func__, exist_actuator); fimc_is_sensor_module_parse_dt(pdev, module_2p6_power_setpin[exist_actuator]); pdata = dev_get_platdata(dev); device = &core->sensor[pdata->id]; subdev_module = kzalloc(sizeof(struct v4l2_subdev), GFP_KERNEL); if (!subdev_module) { probe_err("subdev_module is NULL"); ret = -ENOMEM; goto p_err; } probe_info("%s pdta->id(%d), module_enum id = %d \n", __func__, pdata->id, atomic_read(&core->resourcemgr.rsccount_module)); module = &device->module_enum[atomic_read(&core->resourcemgr.rsccount_module)]; atomic_inc(&core->resourcemgr.rsccount_module); clear_bit(FIMC_IS_MODULE_GPIO_ON, &module->state); module->pdata = pdata; module->dev = dev; module->sensor_id = SENSOR_NAME_S5K2P6; module->subdev = subdev_module; module->device = pdata->id; module->client = NULL; module->active_width = 4608 + 0; module->active_height = 3456 + 0; module->margin_left = 0; module->margin_right = 0; module->margin_top = 0; module->margin_bottom = 0; module->pixel_width = module->active_width; module->pixel_height = module->active_height; module->max_framerate = 120; module->position = pdata->position; module->mode = CSI_MODE_VC_DT; module->lanes = CSI_DATA_LANES_4; module->bitwidth = 10; module->vcis = ARRAY_SIZE(vci_module_2p6); module->vci = vci_module_2p6; module->sensor_maker = "SLSI"; module->sensor_name = "S5K2P6"; /* default */ if (pdata->position == SENSOR_MODULE_2P6_REAR) { module->setfile_name = "setfile_2p6.bin"; } else if (pdata->position == SENSOR_MODULE_2P6_FRONT) { module->setfile_name = "setfile_2p6_front.bin"; } module->cfgs = ARRAY_SIZE(config_module_2p6); module->cfg = config_module_2p6; module->ops = NULL; /* Sensor peri */ module->private_data = kzalloc(sizeof(struct fimc_is_device_sensor_peri), GFP_KERNEL); if (!module->private_data) { probe_err("fimc_is_device_sensor_peri is NULL"); ret = -ENOMEM; goto p_err; } fimc_is_sensor_peri_probe((struct fimc_is_device_sensor_peri *)module->private_data); PERI_SET_MODULE(module); ext = &module->ext; ext->mipi_lane_num = module->lanes; ext->sensor_con.product_name = module->sensor_id; ext->sensor_con.peri_type = SE_I2C; ext->sensor_con.peri_setting.i2c.channel = pdata->sensor_i2c_ch; ext->sensor_con.peri_setting.i2c.slave_address = pdata->sensor_i2c_addr; ext->sensor_con.peri_setting.i2c.speed = 400000; if (pdata->af_product_name != ACTUATOR_NAME_NOTHING) { ext->actuator_con.product_name = pdata->af_product_name; ext->actuator_con.peri_type = SE_I2C; ext->actuator_con.peri_setting.i2c.channel = pdata->af_i2c_ch; ext->actuator_con.peri_setting.i2c.slave_address = pdata->af_i2c_addr; ext->actuator_con.peri_setting.i2c.speed = 400000; } if (pdata->flash_product_name != FLADRV_NAME_NOTHING) { ext->flash_con.product_name = pdata->flash_product_name; ext->flash_con.peri_type = SE_GPIO; ext->flash_con.peri_setting.gpio.first_gpio_port_no = pdata->flash_first_gpio; ext->flash_con.peri_setting.gpio.second_gpio_port_no = pdata->flash_second_gpio; } ext->from_con.product_name = FROMDRV_NAME_NOTHING; if (pdata->preprocessor_product_name != PREPROCESSOR_NAME_NOTHING) { ext->preprocessor_con.product_name = pdata->preprocessor_product_name; ext->preprocessor_con.peri_info0.valid = true; ext->preprocessor_con.peri_info0.peri_type = SE_SPI; ext->preprocessor_con.peri_info0.peri_setting.spi.channel = pdata->preprocessor_spi_channel; ext->preprocessor_con.peri_info1.valid = true; ext->preprocessor_con.peri_info1.peri_type = SE_I2C; ext->preprocessor_con.peri_info1.peri_setting.i2c.channel = pdata->preprocessor_i2c_ch; ext->preprocessor_con.peri_info1.peri_setting.i2c.slave_address = pdata->preprocessor_i2c_addr; ext->preprocessor_con.peri_info1.peri_setting.i2c.speed = 400000; ext->preprocessor_con.peri_info2.valid = true; ext->preprocessor_con.peri_info2.peri_type = SE_DMA; ext->preprocessor_con.peri_info2.peri_setting.dma.channel = FLITE_ID_D; } else { ext->preprocessor_con.product_name = pdata->preprocessor_product_name; } if (pdata->ois_product_name != OIS_NAME_NOTHING) { ext->ois_con.product_name = pdata->ois_product_name; ext->ois_con.peri_type = SE_I2C; ext->ois_con.peri_setting.i2c.channel = pdata->ois_i2c_ch; ext->ois_con.peri_setting.i2c.slave_address = pdata->ois_i2c_addr; ext->ois_con.peri_setting.i2c.speed = 400000; } else { ext->ois_con.product_name = pdata->ois_product_name; ext->ois_con.peri_type = SE_NULL; } v4l2_subdev_init(subdev_module, &subdev_ops); v4l2_set_subdevdata(subdev_module, module); v4l2_set_subdev_hostdata(subdev_module, device); snprintf(subdev_module->name, V4L2_SUBDEV_NAME_SIZE, "sensor-subdev.%d", module->sensor_id); probe_info("%s done\n", __func__); p_err: return ret; } static int sensor_module_2p6_remove(struct platform_device *pdev) { int ret = 0; info("%s\n", __func__); return ret; } static const struct of_device_id exynos_fimc_is_sensor_module_2p6_match[] = { { .compatible = "samsung,sensor-module-2p6", }, {}, }; MODULE_DEVICE_TABLE(of, exynos_fimc_is_sensor_module_2p6_match); static struct platform_driver sensor_module_2p6_driver = { .probe = sensor_module_2p6_probe, .remove = sensor_module_2p6_remove, .driver = { .name = "FIMC-IS-SENSOR-MODULE-2P6", .owner = THIS_MODULE, .of_match_table = exynos_fimc_is_sensor_module_2p6_match, } }; module_platform_driver(sensor_module_2p6_driver);
823372.c
#include "../lib/api.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include "thpool.h" //线程池模块,仅做为测试用,不包含在sdk模块中。 struct part_data{ struct ufile_mutipart_state *state; char *buf; size_t buf_len; int pos; }; void upload_task(void *param){ struct part_data *part = (struct part_data*)param; struct ufile_error error; error = ufile_multiple_upload_part(part->state, part->buf, part->buf_len, part->pos); if(UFILE_HAS_ERROR(error.code)){ printf("调用 upload 失败,错误信息为:%s\n", error.message); ufile_multiple_upload_abort(part->state); exit(1); //失败了就直接退出程序。 } free(part->buf); free(part); } int main(int argc, char *argv[]){ if(argc < 2){ printf("请输入一个文件路径!!!!"); exit(1); } struct ufile_config cfg; cfg.public_key = getenv("UFILE_PUBLIC_KEY"); cfg.private_key = getenv("UFILE_PRIVATE_KEY"); cfg.bucket_host = "api.ucloud.cn"; cfg.file_host = "cn-bj.ufileos.com"; printf("正在初始化 SDK ......\n"); struct ufile_error error; error = ufile_sdk_initialize(cfg, 1); if(UFILE_HAS_ERROR(error.code)){ ufile_sdk_cleanup(); printf("初始化 sdk 失败,错误信息为:%s\n", error.message); return 1; } printf("调用 (mput)分片 上传文件.....\n"); struct ufile_mutipart_state state; error = ufile_multiple_upload_init(&state, "echotest2", "multiple_upload", ""); if(UFILE_HAS_ERROR(error.code)){ ufile_sdk_cleanup(); printf("调用 ufile_multiple_upload_init 失败,错误信息为:%d, %s\n", error.code, error.message); return 1; } threadpool thpool = thpool_init(4); //初始化 4 线程的线程池。 FILE *fp = fopen(argv[1], "rb"); int i; for(i=0; ; i++){ struct part_data *part = malloc(sizeof(struct part_data)); part->state = &state; part->buf = malloc(state.part_size); part->buf_len = fread(part->buf, 1, state.part_size, fp); part->pos = i; if(part->buf_len == 0){ free(part->buf); free(part); break; } thpool_add_work(thpool, &upload_task, part); } thpool_wait(thpool); thpool_destroy(thpool); error = ufile_multiple_upload_finish(&state); if(UFILE_HAS_ERROR(error.code)){ printf("调用 ufile_multiple_upload_part 失败,错误信息为:%s\n", error.message); }else{ printf("调用 (mput) 分片上传成功\n"); } ufile_sdk_cleanup(); return 0; }
570682.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kandeol <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/02/01 17:41:43 by kandeol #+# #+# */ /* Updated: 2018/03/16 15:40:34 by kandeol ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" t_point ft_type_map(t_point tmp, t_map *map) { t_point new; if (map->type == 1) new = ft_iso_map(tmp, map); else if (map->type == 2) new = ft_para_map(tmp, map); else if (map->type == 3) new = ft_pers_map(tmp, map); return (new); } static void ft_map_tmp(t_map *map) { t_var v; v.size_w = map->content_w; v.size_h = map->content_h; v.i = 0; v.j = 0; while (v.size_h--) { while (v.size_w--) { map->tmp[v.i][v.j] = ft_type_map(map->tab[v.i][v.j], map); v.j++; } v.size_w = map->content_w; v.i++; v.j = 0; } } static void ft_init_bres(t_bres *bres, t_point p1, t_point p2) { bres->dx = ft_abs((int)p2.x - (int)p1.x); bres->dy = ft_abs((int)p2.y - (int)p1.y); bres->sx = (int)p1.x < (int)p2.x ? 1 : -1; bres->sy = (int)p1.y < (int)p2.y ? 1 : -1; bres->err = (bres->dx > bres->dy ? bres->dx : -bres->dy) / 2; } static void ft_draw_seg(t_point p1, t_point p2, t_mlx *mlx) { t_bres bres; ft_init_bres(&bres, p1, p2); while (1) { if (((int)p1.y < WIN_HEIGHT) && ((int)p1.y > 0) && ((int)p1.x < WIN_WIDTH) && ((int)p1.x > 0)) mlx->img.data[((int)p1.y * (WIN_WIDTH) + (int)p1.x)] = 0xADADAD; if ((int)p1.x == (int)p2.x && (int)p1.y == (int)p2.y) break ; bres.e2 = bres.err; if (bres.e2 > -bres.dx) { bres.err = bres.err - bres.dy; p1.x = (int)p1.x + bres.sx; } if (bres.e2 < bres.dy) { bres.err = bres.err + bres.dx; p1.y = (int)p1.y + bres.sy; } } } int ft_draw_map(t_mlx mlx) { t_var v; int i; int j; i = 0; j = 0; ft_map_tmp(&mlx.map); v.size_h = mlx.map.content_h; v.size_w = (mlx.map.content_w) - 1; while (v.size_h--) { while (v.size_w--) { ft_draw_seg(mlx.map.tmp[i][j], mlx.map.tmp[i][j + 1], &mlx); if (v.size_h > 0) ft_draw_seg(mlx.map.tmp[i][j], mlx.map.tmp[i + 1][j], &mlx); j++; } v.size_w = (mlx.map.content_w) - 1; if (v.size_h > 0) ft_draw_seg(mlx.map.tmp[i][j], mlx.map.tmp[i + 1][j], &mlx); i++; j = 0; } return (0); }
397732.c
/* * %CopyrightBegin% * * Copyright Ericsson AB 1996-2013. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ /* * This is a C version of the erl.exec Bourne shell script, including * additions required for Windows NT. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "sys.h" #include "erl_driver.h" #include <stdlib.h> #include <stdarg.h> #include "erl_misc_utils.h" #ifdef __WIN32__ # include "erl_version.h" # include "init_file.h" #endif #define NO 0 #define YES 1 #define DEFAULT_PROGNAME "erl" #ifdef __WIN32__ #define INI_FILENAME L"erl.ini" #define INI_SECTION "erlang" #define DIRSEP "\\" #define PATHSEP ";" #define NULL_DEVICE "nul" #define BINARY_EXT "" #define DLL_EXT ".dll" #define EMULATOR_EXECUTABLE "beam.dll" #else #define PATHSEP ":" #define DIRSEP "/" #define NULL_DEVICE "/dev/null" #define BINARY_EXT "" #define EMULATOR_EXECUTABLE "beam" #endif #define QUOTE(s) s /* +M alloc_util allocators */ static const char plusM_au_allocs[]= { 'u', /* all alloc_util allocators */ 'B', /* binary_alloc */ 'D', /* std_alloc */ 'E', /* ets_alloc */ 'F', /* fix_alloc */ 'H', /* eheap_alloc */ 'L', /* ll_alloc */ 'R', /* driver_alloc */ 'S', /* sl_alloc */ 'T', /* temp_alloc */ 'Z', /* test_alloc */ '\0' }; /* +M alloc_util allocator specific arguments */ static char *plusM_au_alloc_switches[] = { "as", "asbcst", "acul", "e", "t", "lmbcs", "mbcgs", "mbsd", "mmbcs", "mmmbc", "mmsbc", "msbclt", "ramv", "rmbcmt", "rsbcmt", "rsbcst", "sbct", "smbcs", NULL }; /* +M other arguments */ static char *plusM_other_switches[] = { "ea", "ummc", "uycs", "usac", "im", "is", "it", "lpm", "Mamcbf", "Mrmcbf", "Mmcs", "Mscs", "Mscrfsd", "Msco", "Mscrpm", "Ye", "Ym", "Ytp", "Ytt", NULL }; /* +s arguments with values */ static char *pluss_val_switches[] = { "bt", "bwt", "cl", "ct", "ecio", "fwi", "tbt", "wct", "wt", "ws", "ss", "pp", "ub", NULL }; /* +h arguments with values */ static char *plush_val_switches[] = { "ms", "mbs", "pds", "", NULL }; /* +r arguments with values */ static char *plusr_val_switches[] = { "g", NULL }; /* +x arguments with values */ static char *plusx_val_switches[] = { "mqd", NULL }; /* +z arguments with values */ static char *plusz_val_switches[] = { "dbbl", "dntgc", "ebwt", NULL }; /* * Define sleep(seconds) in terms of Sleep() on Windows. */ #ifdef __WIN32__ #define sleep(seconds) Sleep(seconds*1000) #endif #define SMP_SUFFIX ".smp" #define DEBUG_SUFFIX ".debug" #define EMU_TYPE_SUFFIX_LENGTH strlen(DEBUG_SUFFIX) /* * Define flags for different memory architectures. */ #define EMU_TYPE_SMP 0x0001 #ifdef __WIN32__ #define EMU_TYPE_DEBUG 0x0004 #endif void usage(const char *switchname); void start_epmd(char *epmd); void error(char* format, ...); /* * Local functions. */ #if !defined(ERTS_HAVE_SMP_EMU) static void usage_notsup(const char *switchname); #endif static char **build_args_from_env(char *env_var); static char **build_args_from_string(char *env_var); static void initial_argv_massage(int *argc, char ***argv); static void get_parameters(int argc, char** argv); static void add_arg(char *new_arg); static void add_args(char *first_arg, ...); static void ensure_EargsSz(int sz); static void add_Eargs(char *new_arg); static void *emalloc(size_t size); static void *erealloc(void *p, size_t size); static void efree(void *p); static char* strsave(char* string); static int is_one_of_strings(char *str, char *strs[]); static char *write_str(char *to, char *from); static void get_home(void); static void add_epmd_port(void); #ifdef __WIN32__ static void get_start_erl_data(char *); static char* get_value(HKEY key, char* value_name, BOOL mustExit); static char* possibly_quote(char* arg); /* * Functions from win_erlexec.c */ int start_win_emulator(char* emu, char *startprog,char** argv, int start_detached); int start_emulator(char* emu, char*start_prog, char** argv, int start_detached); #endif /* * Variables. */ int nohup = 0; int keep_window = 0; static char **Eargsp = NULL; /* Emulator arguments (to appear first). */ static int EargsSz = 0; /* Size of Eargsp */ static int EargsCnt = 0; /* Number of emulator arguments. */ static char **argsp = NULL; /* Common arguments. */ static int argsCnt = 0; /* Number of common arguments */ static int argsSz = 0; /* Size of argsp */ static char tmpStr[10240]; /* Temporary string buffer. */ static int verbose = 0; /* If non-zero, print some extra information. */ static int start_detached = 0; /* If non-zero, the emulator should be * started detached (in the background). */ static int emu_type = 0; /* If non-zero, start beam.ARCH or beam.ARCH.exe * instead of beam or beam.exe, where ARCH is defined by flags. */ static int emu_type_passed = 0; /* Types explicitly set */ #ifdef __WIN32__ static char *start_emulator_program = NULL; /* For detachec mode - erl.exe/werl.exe */ static char* key_val_name = ERLANG_VERSION; /* Used by the registry * access functions. */ static char* boot_script = NULL; /* used by option -start_erl and -boot */ static char* config_script = NULL; /* used by option -start_erl and -config */ static HANDLE this_module_handle; static int run_werl; static WCHAR *utf8_to_utf16(unsigned char *bytes); static char *utf16_to_utf8(WCHAR *wstr); static WCHAR *latin1_to_utf16(char *str); #endif /* * Needed parameters to be fetched from the environment (Unix) * or the ini file (Win32). */ static char* bindir; /* Location of executables. */ static char* rootdir; /* Root location of Erlang installation. */ static char* emu; /* Emulator to run. */ static char* progname; /* Name of this program. */ static char* home; /* Path of user's home directory. */ static void set_env(char *key, char *value) { #ifdef __WIN32__ WCHAR *wkey = latin1_to_utf16(key); WCHAR *wvalue = utf8_to_utf16(value); if (!SetEnvironmentVariableW(wkey, wvalue)) error("SetEnvironmentVariable(\"%s\", \"%s\") failed!", key, value); efree(wkey); efree(wvalue); #else size_t size = strlen(key) + 1 + strlen(value) + 1; char *str = emalloc(size); sprintf(str, "%s=%s", key, value); if (putenv(str) != 0) error("putenv(\"%s\") failed!", str); #ifdef HAVE_COPYING_PUTENV efree(str); #endif #endif } static char * get_env(char *key) { #ifdef __WIN32__ DWORD size = 32; WCHAR *value = NULL; WCHAR *wkey = latin1_to_utf16(key); char *res; while (1) { DWORD nsz; if (value) efree(value); value = emalloc(size*sizeof(WCHAR)); SetLastError(0); nsz = GetEnvironmentVariableW(wkey, value, size); if (nsz == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) { efree(value); efree(wkey); return NULL; } if (nsz <= size) { efree(wkey); res = utf16_to_utf8(value); efree(value); return res; } size = nsz; } #else return getenv(key); #endif } static void free_env_val(char *value) { #ifdef __WIN32__ if (value) free(value); #endif } /* * Add the architecture suffix to the program name if needed, * except on Windows, where we insert it just before ".DLL". */ static char* add_extra_suffixes(char *prog, int type) { char *res; char *p; int len; #ifdef __WIN32__ char *dll_p; int dll = 0; #endif if (!type) { return prog; } len = strlen(prog); /* Worst-case allocation */ p = emalloc(len + EMU_TYPE_SUFFIX_LENGTH + + 1); res = p; p = write_str(p, prog); #ifdef __WIN32__ dll_p = res + len - 4; if (dll_p >= res) { if (dll_p[0] == '.' && (dll_p[1] == 'd' || dll_p[1] == 'D') && (dll_p[2] == 'l' || dll_p[2] == 'L') && (dll_p[3] == 'l' || dll_p[3] == 'L')) { p = dll_p; dll = 1; } } #endif #ifdef __WIN32__ if (type & EMU_TYPE_DEBUG) { p = write_str(p, DEBUG_SUFFIX); type &= ~(EMU_TYPE_DEBUG); } #endif if (type == EMU_TYPE_SMP) { p = write_str(p, SMP_SUFFIX); } #ifdef __WIN32__ if (dll) { p = write_str(p, DLL_EXT); } #endif return res; } #ifdef __WIN32__ __declspec(dllexport) int win_erlexec(int argc, char **argv, HANDLE module, int windowed) #else int main(int argc, char **argv) #endif { int haltAfterwards = 0; /* If true, put 's erlang halt' at the end * of the arguments. */ int isdistributed = 0; int no_epmd = 0; int i; char* s; char *epmd_prog = NULL; char *malloc_lib; int process_args = 1; int print_args_exit = 0; int print_qouted_cmd_exit = 0; erts_cpu_info_t *cpuinfo = NULL; char* emu_name; #ifdef __WIN32__ this_module_handle = module; run_werl = windowed; /* if we started this erl just to get a detached emulator, * the arguments are already prepared for beam, so we skip * directly to start_emulator */ s = get_env("ERL_CONSOLE_MODE"); if (s != NULL && strcmp(s, "detached")==0) { free_env_val(s); s = get_env("ERL_EMULATOR_DLL"); if (s != NULL) { argv[0] = strsave(s); } else { argv[0] = strsave(EMULATOR_EXECUTABLE); } ensure_EargsSz(argc + 1); memcpy((void *) Eargsp, (void *) argv, argc * sizeof(char *)); Eargsp[argc] = NULL; emu = argv[0]; start_emulator_program = strsave(argv[0]); goto skip_arg_massage; } free_env_val(s); #else int reset_cerl_detached = 0; s = get_env("CERL_DETACHED_PROG"); if (s && strcmp(s, "") != 0) { emu = s; start_detached = 1; reset_cerl_detached = 1; ensure_EargsSz(argc + 1); memcpy((void *) Eargsp, (void *) argv, argc * sizeof(char *)); Eargsp[argc] = emu; Eargsp[argc] = NULL; goto skip_arg_massage; } free_env_val(s); #endif initial_argv_massage(&argc, &argv); /* Merge with env; expand -args_file */ i = 1; #ifdef __WIN32__ /* Not used? /rickard */ if ((argc > 2) && (strcmp(argv[i], "-regkey") == 0)) { key_val_name = strsave(argv[i+1]); i = 3; } #endif get_parameters(argc, argv); /* * Construct the path of the executable. */ cpuinfo = erts_cpu_info_create(); /* '-smp auto' is default */ #ifdef ERTS_HAVE_SMP_EMU if (erts_get_cpu_configured(cpuinfo) > 1) emu_type |= EMU_TYPE_SMP; #endif #if defined(__WIN32__) && defined(WIN32_ALWAYS_DEBUG) emu_type_passed |= EMU_TYPE_DEBUG; emu_type |= EMU_TYPE_DEBUG; #endif /* We need to do this before the ordinary processing. */ malloc_lib = get_env("ERL_MALLOC_LIB"); while (i < argc) { if (argv[i][0] == '+') { if (argv[i][1] == 'M' && argv[i][2] == 'Y' && argv[i][3] == 'm') { if (argv[i][4] == '\0') { if (++i < argc) malloc_lib = argv[i]; else usage("+MYm"); } else malloc_lib = &argv[i][4]; } } else if (argv[i][0] == '-') { if (strcmp(argv[i], "-smp") == 0) { if (i + 1 >= argc) goto smp; if (strcmp(argv[i+1], "auto") == 0) { i++; smp_auto: emu_type_passed |= EMU_TYPE_SMP; #ifdef ERTS_HAVE_SMP_EMU if (erts_get_cpu_configured(cpuinfo) > 1) emu_type |= EMU_TYPE_SMP; else #endif emu_type &= ~EMU_TYPE_SMP; } else if (strcmp(argv[i+1], "enable") == 0) { i++; smp_enable: emu_type_passed |= EMU_TYPE_SMP; #ifdef ERTS_HAVE_SMP_EMU emu_type |= EMU_TYPE_SMP; #else usage_notsup("-smp enable"); #endif } else if (strcmp(argv[i+1], "disable") == 0) { i++; smp_disable: emu_type_passed |= EMU_TYPE_SMP; emu_type &= ~EMU_TYPE_SMP; } else { smp: emu_type_passed |= EMU_TYPE_SMP; #ifdef ERTS_HAVE_SMP_EMU emu_type |= EMU_TYPE_SMP; #else usage_notsup("-smp"); #endif } } else if (strcmp(argv[i], "-smpenable") == 0) { goto smp_enable; } else if (strcmp(argv[i], "-smpauto") == 0) { goto smp_auto; } else if (strcmp(argv[i], "-smpdisable") == 0) { goto smp_disable; #ifdef __WIN32__ } else if (strcmp(argv[i], "-debug") == 0) { emu_type_passed |= EMU_TYPE_DEBUG; emu_type |= EMU_TYPE_DEBUG; #endif } else if (strcmp(argv[i], "-extra") == 0) { break; } } i++; } erts_cpu_info_destroy(cpuinfo); cpuinfo = NULL; if (malloc_lib) { if (strcmp(malloc_lib, "libc") != 0) usage("+MYm"); } emu = add_extra_suffixes(emu, emu_type); emu_name = strsave(emu); erts_snprintf(tmpStr, sizeof(tmpStr), "%s" DIRSEP "%s" BINARY_EXT, bindir, emu); emu = strsave(tmpStr); add_Eargs(emu); /* Will be argv[0] -- necessary! */ /* * Add the bindir to the path (unless it is there already). */ s = get_env("PATH"); if (!s) { erts_snprintf(tmpStr, sizeof(tmpStr), "%s" PATHSEP "%s" DIRSEP "bin", bindir, rootdir); } else if (strstr(s, bindir) == NULL) { erts_snprintf(tmpStr, sizeof(tmpStr), "%s" PATHSEP "%s" DIRSEP "bin" PATHSEP "%s", bindir, rootdir, s); } else { erts_snprintf(tmpStr, sizeof(tmpStr), "%s", s); } free_env_val(s); set_env("PATH", tmpStr); i = 1; #ifdef __WIN32__ #define ADD_BOOT_CONFIG \ if (boot_script) \ add_args("-boot", boot_script, NULL); \ if (config_script) \ add_args("-config", config_script, NULL); #else #define ADD_BOOT_CONFIG #endif get_home(); add_args("-home", home, NULL); add_epmd_port(); add_arg("--"); while (i < argc) { if (!process_args) { /* Copy arguments after '-extra' */ add_arg(argv[i]); i++; } else { switch (argv[i][0]) { case '-': switch (argv[i][1]) { #ifdef __WIN32__ case 'b': if (strcmp(argv[i], "-boot") == 0) { if (boot_script) error("Conflicting -start_erl and -boot options"); if (i+1 >= argc) usage("-boot"); boot_script = strsave(argv[i+1]); i++; } else { add_arg(argv[i]); } break; #endif case 'c': if (strcmp(argv[i], "-compile") == 0) { /* * Note that the shell script erl.exec does an recursive call * on itself here. We'll avoid doing that. */ add_args("-noshell", "-noinput", "-s", "c", "lc_batch", NULL); add_Eargs("-B"); haltAfterwards = 0; } #ifdef __WIN32__ else if (strcmp(argv[i], "-config") == 0){ if (config_script) error("Conflicting -start_erl and -config options"); if (i+1 >= argc) usage("-config"); config_script = strsave(argv[i+1]); i++; } #endif else { add_arg(argv[i]); } break; case 'd': if (strcmp(argv[i], "-detached") != 0) { add_arg(argv[i]); } else { start_detached = 1; add_args("-noshell", "-noinput", NULL); } break; case 'i': if (strcmp(argv[i], "-instr") == 0) { add_Eargs("-Mim"); add_Eargs("true"); } else add_arg(argv[i]); break; case 'e': if (strcmp(argv[i], "-extra") == 0) { process_args = 0; ADD_BOOT_CONFIG; add_arg(argv[i]); } else if (strcmp(argv[i], "-emu_args") == 0) { /* -emu_args */ verbose = 1; } else if (strcmp(argv[i], "-emu_args_exit") == 0) { print_args_exit = 1; } else if (strcmp(argv[i], "-emu_name_exit") == 0) { printf("%s\n", emu_name); exit(0); } else if (strcmp(argv[i], "-emu_qouted_cmd_exit") == 0) { print_qouted_cmd_exit = 1; } else if (strcmp(argv[i], "-env") == 0) { /* -env VARNAME VARVALUE */ if (i+2 >= argc) usage("-env"); set_env(argv[i+1], argv[i+2]); i += 2; } else if (strcmp(argv[i], "-epmd") == 0) { if (i+1 >= argc) usage("-epmd"); epmd_prog = argv[i+1]; ++i; } else { add_arg(argv[i]); } break; case 'k': if (strcmp(argv[i], "-keep_window") == 0) { keep_window = 1; } else add_arg(argv[i]); break; case 'm': /* * Note that the shell script erl.exec does an recursive call * on itself here. We'll avoid doing that. */ if (strcmp(argv[i], "-make") == 0) { add_args("-noshell", "-noinput", "-s", "make", "all_or_nothing", NULL); add_Eargs("-B"); haltAfterwards = 1; i = argc; /* Skip rest of command line */ } else if (strcmp(argv[i], "-man") == 0) { #if defined(__WIN32__) error("-man not supported on Windows"); #else argv[i] = "man"; erts_snprintf(tmpStr, sizeof(tmpStr), "%s/man", rootdir); set_env("MANPATH", tmpStr); execvp("man", argv+i); error("Could not execute the 'man' command."); #endif } else add_arg(argv[i]); break; case 'n': if (strcmp(argv[i], "-name") == 0) { /* -name NAME */ if (i+1 >= argc) usage("-name"); /* * Note: Cannot use add_args() here, due to non-defined * evaluation order. */ add_arg(argv[i]); add_arg(argv[i+1]); isdistributed = 1; i++; } else if (strcmp(argv[i], "-noinput") == 0) { add_args("-noshell", "-noinput", NULL); } else if (strcmp(argv[i], "-nohup") == 0) { add_arg("-nohup"); nohup = 1; } else if (strcmp(argv[i], "-no_epmd") == 0) { add_arg("-no_epmd"); no_epmd = 1; } else { add_arg(argv[i]); } break; case 's': /* -sname NAME */ if (strcmp(argv[i], "-sname") == 0) { if (i+1 >= argc) usage("-sname"); add_arg(argv[i]); add_arg(argv[i+1]); isdistributed = 1; i++; } #ifdef __WIN32__ else if (strcmp(argv[i], "-service_event") == 0) { add_arg(argv[i]); add_arg(argv[i+1]); i++; } else if (strcmp(argv[i], "-start_erl") == 0) { if (i+1 < argc && argv[i+1][0] != '-') { get_start_erl_data(argv[i+1]); i++; } else get_start_erl_data((char *) NULL); } #endif else add_arg(argv[i]); break; case 'v': /* -version */ if (strcmp(argv[i], "-version") == 0) { add_Eargs("-V"); } else { add_arg(argv[i]); } break; default: add_arg(argv[i]); break; } /* switch(argv[i][1] */ break; case '+': switch (argv[i][1]) { case '#': case 'a': case 'A': case 'b': case 'C': case 'e': case 'i': case 'n': case 'P': case 'Q': case 't': case 'T': case 'R': case 'W': case 'K': if (argv[i][2] != '\0') goto the_default; if (i+1 >= argc) usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; break; case 'S': if (argv[i][2] == 'P') { if (argv[i][3] != '\0') goto the_default; } #ifdef ERTS_DIRTY_SCHEDULERS else if (argv[i][2] == 'D') { char* type = argv[i]+3; if (strncmp(type, "cpu", 3) != 0 && strncmp(type, "Pcpu", 4) != 0 && strncmp(type, "io", 2) != 0) usage(argv[i]); if ((argv[i][3] == 'c' && argv[i][6] != '\0') || (argv[i][3] == 'P' && argv[i][7] != '\0') || (argv[i][3] == 'i' && argv[i][5] != '\0')) goto the_default; } #endif else if (argv[i][2] != '\0') goto the_default; if (i+1 >= argc) usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; break; case 'B': argv[i][0] = '-'; if (argv[i][2] != '\0') { if ((argv[i][2] != 'i') && (argv[i][2] != 'c') && (argv[i][2] != 'd')) { usage(argv[i]); } else { add_Eargs(argv[i]); break; } } if (i+1 < argc) { if ((argv[i+1][0] != '-') && (argv[i+1][0] != '+')) { if (argv[i+1][0] == 'i') { add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; break; } else { usage(argv[i]); } } } add_Eargs(argv[i]); break; case 'c': argv[i][0] = '-'; if (argv[i][2] == '\0' && i+1 < argc) { if (sys_strcmp(argv[i+1], "true") == 0 || sys_strcmp(argv[i+1], "false") == 0) { add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; break; } } add_Eargs(argv[i]); break; case 'M': { int x; for (x = 0; plusM_au_allocs[x]; x++) if (plusM_au_allocs[x] == argv[i][2]) break; if ((plusM_au_allocs[x] && is_one_of_strings(&argv[i][3], plusM_au_alloc_switches)) || is_one_of_strings(&argv[i][2], plusM_other_switches)) { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } else goto the_default; break; } case 'h': if (!is_one_of_strings(&argv[i][2], plush_val_switches)) { goto the_default; } else { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } break; case 'r': if (!is_one_of_strings(&argv[i][2], plusr_val_switches)) goto the_default; else { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } break; case 's': if (!is_one_of_strings(&argv[i][2], pluss_val_switches)) goto the_default; else { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } break; case 'p': if (argv[i][2] != 'c' || argv[i][3] != '\0') goto the_default; if (i+1 >= argc) usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; break; case 'x': if (!is_one_of_strings(&argv[i][2], plusx_val_switches)) { goto the_default; } else { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } break; case 'z': if (!is_one_of_strings(&argv[i][2], plusz_val_switches)) { goto the_default; } else { if (i+1 >= argc || argv[i+1][0] == '-' || argv[i+1][0] == '+') usage(argv[i]); argv[i][0] = '-'; add_Eargs(argv[i]); add_Eargs(argv[i+1]); i++; } break; default: the_default: argv[i][0] = '-'; /* Change +option to -option. */ add_Eargs(argv[i]); } break; default: add_arg(argv[i]); } /* switch(argv[i][0] */ i++; } } if (process_args) { ADD_BOOT_CONFIG; } #undef ADD_BOOT_CONFIG /* Doesn't conflict with -extra, since -make skips all the rest of the arguments. */ if (haltAfterwards) { add_args("-s", "erlang", "halt", NULL); } if (isdistributed && !no_epmd) start_epmd(epmd_prog); #if (! defined(__WIN32__)) && defined(DEBUG) if (start_detached) { /* Start the emulator within an xterm. * Move up all arguments and insert * "xterm -e " first. * The path must be searched for this * to work, i.e execvp() must be used. */ ensure_EargsSz(EargsCnt+2); for (i = EargsCnt; i > 0; i--) Eargsp[i+1] = Eargsp[i-1]; /* Two args to insert */ EargsCnt += 2; /* Two args to insert */ Eargsp[0] = emu = "xterm"; Eargsp[1] = "-e"; } #endif add_Eargs("--"); add_Eargs("-root"); add_Eargs(rootdir); add_Eargs("-progname"); add_Eargs(progname); add_Eargs("--"); ensure_EargsSz(EargsCnt + argsCnt + 1); for (i = 0; i < argsCnt; i++) Eargsp[EargsCnt++] = argsp[i]; Eargsp[EargsCnt] = NULL; if (print_qouted_cmd_exit) { printf("\"%s\" ", emu); for (i = 1; i < EargsCnt; i++) printf("\"%s\" ", Eargsp[i]); printf("\n"); exit(0); } if (print_args_exit) { for (i = 1; i < EargsCnt; i++) printf("%s\n", Eargsp[i]); exit(0); } if (verbose) { printf("Executing: %s", emu); for (i = 0; i < EargsCnt; i++) printf(" %s", Eargsp[i]); printf("\n\n"); } #ifdef __WIN32__ if (EargsSz != EargsCnt + 1) Eargsp = (char **) erealloc((void *) Eargsp, (EargsCnt + 1) * sizeof(char *)); efree((void *) argsp); skip_arg_massage: /*DebugBreak();*/ if (run_werl) { if (start_detached) { char *p; /* transform werl to erl */ p = start_emulator_program+strlen(start_emulator_program); while (--p >= start_emulator_program && *p != '/' && *p != '\\' && *p != 'W' && *p != 'w') ; if (p >= start_emulator_program && (*p == 'W' || *p == 'w') && (p[1] == 'E' || p[1] == 'e') && (p[2] == 'R' || p[2] == 'r') && (p[3] == 'L' || p[3] == 'l')) { memmove(p,p+1,strlen(p)); } } return start_win_emulator(emu, start_emulator_program, Eargsp, start_detached); } else { return start_emulator(emu, start_emulator_program, Eargsp, start_detached); } #else skip_arg_massage: if (start_detached) { int status = fork(); if (status != 0) /* Parent */ return 0; if (reset_cerl_detached) putenv("CERL_DETACHED_PROG="); /* Detach from controlling terminal */ #ifdef HAVE_SETSID setsid(); #elif defined(TIOCNOTTY) { int fd = open("/dev/tty", O_RDWR); if (fd >= 0) { ioctl(fd, TIOCNOTTY, NULL); close(fd); } } #endif status = fork(); if (status != 0) /* Parent */ return 0; /* * Grandchild. */ close(0); open("/dev/null", O_RDONLY); close(1); open("/dev/null", O_WRONLY); close(2); open("/dev/null", O_WRONLY); #ifdef DEBUG execvp(emu, Eargsp); /* "xterm ..." needs to search the path */ #endif } #ifdef DEBUG else #endif { execv(emu, Eargsp); } error("Error %d executing \'%s\'.", errno, emu); return 1; #endif } static void usage_aux(void) { fprintf(stderr, "Usage: erl [-version] [-sname NAME | -name NAME] " "[-noshell] [-noinput] [-env VAR VALUE] [-compile file ...] " #ifdef __WIN32__ "[-start_erl [datafile]] " #endif "[-smp " #ifdef ERTS_HAVE_SMP_EMU "[enable|" #endif "auto|disable" #ifdef ERTS_HAVE_SMP_EMU "]" #endif "] " "[-make] [-man [manopts] MANPAGE] [-x] [-emu_args] " "[-args_file FILENAME] [+A THREADS] [+a SIZE] [+B[c|d|i]] [+c [BOOLEAN]] " "[+C MODE] [+h HEAP_SIZE_OPTION] [+K BOOLEAN] " "[+l] [+M<SUBSWITCH> <ARGUMENT>] [+P MAX_PROCS] [+Q MAX_PORTS] " "[+R COMPAT_REL] " "[+r] [+rg READER_GROUPS_LIMIT] [+s SCHEDULER_OPTION] " "[+S NO_SCHEDULERS:NO_SCHEDULERS_ONLINE] " "[+SP PERCENTAGE_SCHEDULERS:PERCENTAGE_SCHEDULERS_ONLINE] " "[+T LEVEL] [+V] [+v] " "[+W<i|w|e>] [+x DEFAULT_PROC_FLAGS] [+z MISC_OPTION] [args ...]\n"); exit(1); } void usage(const char *switchname) { fprintf(stderr, "Missing argument(s) for \'%s\'.\n", switchname); usage_aux(); } #if !defined(ERTS_HAVE_SMP_EMU) static void usage_notsup(const char *switchname) { fprintf(stderr, "Argument \'%s\' not supported.\n", switchname); usage_aux(); } #endif static void usage_format(char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); usage_aux(); } void start_epmd(char *epmd) { char epmd_cmd[MAXPATHLEN+100]; #ifdef __WIN32__ char* arg1 = NULL; #endif int result; if (!epmd) { epmd = epmd_cmd; #ifdef __WIN32__ erts_snprintf(epmd_cmd, sizeof(epmd_cmd), "%s" DIRSEP "epmd", bindir); arg1 = "-daemon"; #else erts_snprintf(epmd_cmd, sizeof(epmd_cmd), "\"%s" DIRSEP "epmd\" -daemon", bindir); #endif } #ifdef __WIN32__ if (arg1 != NULL) { strcat(epmd, " "); strcat(epmd, arg1); } { wchar_t wcepmd[MAXPATHLEN+100]; STARTUPINFOW start; PROCESS_INFORMATION pi; memset(&start, 0, sizeof (start)); start.cb = sizeof (start); MultiByteToWideChar(CP_UTF8, 0, epmd, -1, wcepmd, MAXPATHLEN+100); if (!CreateProcessW(NULL, wcepmd, NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS, NULL, NULL, &start, &pi)) result = -1; else result = 0; } #else result = system(epmd); #endif if (result == -1) { fprintf(stderr, "Error spawning %s (error %d)\n", epmd_cmd,errno); exit(1); } } static void add_arg(char *new_arg) { if (argsCnt >= argsSz) argsp = (char **) erealloc((void *) argsp, sizeof(char *) * (argsSz += 20)); argsp[argsCnt++] = QUOTE(new_arg); } static void add_args(char *first_arg, ...) { va_list ap; char* arg; add_arg(first_arg); va_start(ap, first_arg); while ((arg = va_arg(ap, char *)) != NULL) { add_arg(arg); } va_end(ap); } static void ensure_EargsSz(int sz) { if (EargsSz < sz) Eargsp = (char **) erealloc((void *) Eargsp, sizeof(char *) * (EargsSz = sz)); } static void add_Eargs(char *new_arg) { if (EargsCnt >= EargsSz) Eargsp = (char **) erealloc((void *) Eargsp, sizeof(char *) * (EargsSz += 20)); Eargsp[EargsCnt++] = QUOTE(new_arg); } #if !defined(__WIN32__) void error(char* format, ...) { char sbuf[1024]; va_list ap; va_start(ap, format); erts_vsnprintf(sbuf, sizeof(sbuf), format, ap); va_end(ap); fprintf(stderr, "erlexec: %s\n", sbuf); exit(1); } #endif static void * emalloc(size_t size) { void *p = malloc(size); if (p == NULL) error("Insufficient memory"); return p; } static void * erealloc(void *p, size_t size) { void *res = realloc(p, size); if (res == NULL) error("Insufficient memory"); return res; } static void efree(void *p) { free(p); } static int is_one_of_strings(char *str, char *strs[]) { int i, j; for (i = 0; strs[i]; i++) { for (j = 0; str[j] && strs[i][j] && str[j] == strs[i][j]; j++); if (!str[j] && !strs[i][j]) return 1; } return 0; } static char *write_str(char *to, char *from) { while (*from) *(to++) = *(from++); *to = '\0'; return to; } char* strsave(char* string) { char* p = emalloc(strlen(string)+1); strcpy(p, string); return p; } #if defined(__WIN32__) static void get_start_erl_data(char *file) { int fp; char tmpbuffer[512]; char start_erl_data[512]; int bytesread; char* env; char* reldir; char* otpstring; char* tprogname; if (boot_script) error("Conflicting -start_erl and -boot options"); if (config_script) error("Conflicting -start_erl and -config options"); env = get_env("RELDIR"); if (env) reldir = strsave(env); else { erts_snprintf(tmpbuffer, sizeof(tmpbuffer), "%s/releases", rootdir); reldir = strsave(tmpbuffer); } free_env_val(env); if (file == NULL) erts_snprintf(start_erl_data, sizeof(start_erl_data), "%s/start_erl.data", reldir); else erts_snprintf(start_erl_data, sizeof(start_erl_data), "%s", file); fp = _open(start_erl_data, _O_RDONLY ); if( fp == -1 ) error( "open failed on %s",start_erl_data ); else { if( ( bytesread = _read( fp, tmpbuffer, 512 ) ) <= 0 ) error( "Problem reading file %s", start_erl_data ); else { tmpbuffer[bytesread]='\0'; if ((otpstring = strchr(tmpbuffer,' ')) != NULL) { *otpstring = '\0'; otpstring++; /* * otpstring is the otpversion * tmpbuffer is the emuversion */ } } } tprogname = otpstring; while (*tprogname) { if (*tprogname <= ' ') { *tprogname='\0'; break; } tprogname++; } bindir = emalloc(512); erts_snprintf(bindir,512,"%s/erts-%s/bin",rootdir,tmpbuffer); /* BINDIR=$ROOTDIR/erts-$ERTS_VSN/bin */ tprogname = progname; progname = emalloc(strlen(tprogname) + 20); erts_snprintf(progname,strlen(tprogname) + 20,"%s -start_erl",tprogname); boot_script = emalloc(512); config_script = emalloc(512); erts_snprintf(boot_script, 512, "%s/%s/start", reldir, otpstring); erts_snprintf(config_script, 512, "%s/%s/sys", reldir, otpstring); } static wchar_t *replace_filename(wchar_t *path, wchar_t *new_base) { int plen = wcslen(path); wchar_t *res = (wchar_t *) emalloc((plen+wcslen(new_base)+1)*sizeof(wchar_t)); wchar_t *p; wcscpy(res,path); for (p = res+plen-1 ;p >= res && *p != L'\\'; --p) ; *(p+1) =L'\0'; wcscat(res,new_base); return res; } static char *path_massage(wchar_t *long_path) { char *p; int len; len = WideCharToMultiByte(CP_UTF8, 0, long_path, -1, NULL, 0, NULL, NULL); p = emalloc(len*sizeof(char)); WideCharToMultiByte(CP_UTF8, 0, long_path, -1, p, len, NULL, NULL); return p; } static char *do_lookup_in_section(InitSection *inis, char *name, char *section, wchar_t *filename, int is_path) { char *p = lookup_init_entry(inis, name); if (p == NULL) { error("Could not find key %s in section %s of file %S", name,section,filename); } return strsave(p); } // Setup bindir, rootdir and progname as utf8 buffers static void get_parameters(int argc, char** argv) { wchar_t *p; wchar_t buffer[MAX_PATH]; wchar_t *ini_filename; HANDLE module = GetModuleHandle(NULL); /* This might look strange, but we want the erl.ini that resides in the same dir as erl.exe, not an erl.ini in our directory */ InitFile *inif; InitSection *inis; if (module == NULL) { error("Cannot GetModuleHandle()"); } if (GetModuleFileNameW(module,buffer,MAX_PATH) == 0) { error("Could not GetModuleFileName"); } ini_filename = replace_filename(buffer,INI_FILENAME); if ((inif = load_init_file(ini_filename)) == NULL) { wchar_t wbindir[MAX_PATH]; wchar_t wrootdir[MAX_PATH]; /* Assume that the path is absolute and that it does not contain any symbolic link */ /* Determine bindir */ if (GetEnvironmentVariableW(L"ERLEXEC_DIR", buffer, MAX_PATH) == 0) { wcscpy(buffer, ini_filename); for (p = buffer+wcslen(buffer)-1; p >= buffer && *p != L'\\'; --p) ; *p = L'\0'; } bindir = path_massage(buffer); /* Determine rootdir */ for (p = buffer+wcslen(buffer)-1; p >= buffer && *p != L'\\'; --p) ; p--; for (;p >= buffer && *p != L'\\'; --p) ; *p =L'\0'; rootdir = path_massage(buffer); /* Hardcoded progname */ progname = strsave(DEFAULT_PROGNAME); } else { if ((inis = lookup_init_section(inif,INI_SECTION)) == NULL) { error("Could not find section %s in init file %s", INI_SECTION, ini_filename); } bindir = do_lookup_in_section(inis, "Bindir", INI_SECTION, ini_filename,1); rootdir = do_lookup_in_section(inis, "Rootdir", INI_SECTION, ini_filename,1); progname = do_lookup_in_section(inis, "Progname", INI_SECTION, ini_filename,0); free_init_file(inif); } emu = EMULATOR_EXECUTABLE; start_emulator_program = strsave(argv[0]); free(ini_filename); } static void get_home(void) { int len; char tmpstr[MAX_PATH+1]; char* homedrive; char* homepath; homedrive = get_env("HOMEDRIVE"); homepath = get_env("HOMEPATH"); if (!homedrive || !homepath) { if (len = GetWindowsDirectory(tmpstr,MAX_PATH)) { home = emalloc(len+1); strcpy(home,tmpstr); } else error("HOMEDRIVE or HOMEPATH is not set and GetWindowsDir failed"); } else { home = emalloc(strlen(homedrive)+strlen(homepath)+1); strcpy(home, homedrive); strcat(home, homepath); } free_env_val(homedrive); free_env_val(homepath); } #else static void get_parameters(int argc, char** argv) { progname = get_env("PROGNAME"); if (!progname) { progname = strsave(DEFAULT_PROGNAME); } emu = get_env("EMU"); if (!emu) { emu = strsave(EMULATOR_EXECUTABLE); } bindir = get_env("BINDIR"); if (!bindir) { /* Determine bindir from absolute path to executable */ char *p; char buffer[PATH_MAX]; strncpy(buffer, argv[0], sizeof(buffer)); buffer[sizeof(buffer)-1] = '\0'; for (p = buffer+strlen(buffer)-1 ; p >= buffer && *p != '/'; --p) ; *p ='\0'; bindir = strsave(buffer); } rootdir = get_env("ROOTDIR"); if (!rootdir) { /* Determine rootdir from absolute path to bindir */ char *p; char buffer[PATH_MAX]; strncpy(buffer, bindir, sizeof(buffer)); buffer[sizeof(buffer)-1] = '\0'; for (p = buffer+strlen(buffer)-1; p >= buffer && *p != '/'; --p) ; p--; for (; p >= buffer && *p != '/'; --p) ; *p ='\0'; rootdir = strsave(buffer); } if (!progname || !emu || !rootdir || !bindir) { error("PROGNAME, EMU, ROOTDIR and BINDIR must be set"); } } static void get_home(void) { home = get_env("HOME"); if (home == NULL) error("HOME must be set"); } #endif static void add_epmd_port(void) { char* port = get_env("ERL_EPMD_PORT"); if (port != NULL) { add_args("-epmd_port", port, NULL); } } static char **build_args_from_env(char *env_var) { char *value = get_env(env_var); char **res = build_args_from_string(value); free_env_val(value); return res; } static char **build_args_from_string(char *string) { int argc = 0; char **argv = NULL; int alloced = 0; char **cur_s = NULL; /* Initialized to avoid warning. */ int s_alloced = 0; int s_pos = 0; char *p = string; enum {Start, Build, Build0, BuildSQuoted, BuildDQuoted, AcceptNext} state; #define ENSURE() \ if (s_pos >= s_alloced) { \ if (!*cur_s) { \ *cur_s = emalloc(s_alloced = 20); \ } else { \ *cur_s = erealloc(*cur_s, s_alloced += 20); \ } \ } if (!p) return NULL; argv = emalloc(sizeof(char *) * (alloced = 10)); state = Start; for(;;) { switch (state) { case Start: if (!*p) goto done; if (argc >= alloced - 1) { /* Make room for extra NULL */ argv = erealloc(argv, (alloced += 10) * sizeof(char *)); } cur_s = argc + argv; *cur_s = NULL; s_pos = 0; s_alloced = 0; state = Build0; break; case Build0: switch (*p) { case ' ': ++p; break; case '\0': state = Start; break; default: state = Build; break; } break; case Build: switch (*p) { case ' ': case '\0': ENSURE(); (*cur_s)[s_pos] = '\0'; ++argc; state = Start; break; case '"': ++p; state = BuildDQuoted; break; case '\'': ++p; state = BuildSQuoted; break; case '\\': ++p; state = AcceptNext; break; default: ENSURE(); (*cur_s)[s_pos++] = *p++; break; } break; case BuildDQuoted: switch (*p) { case '"': ++p; /* fall through */ case '\0': state = Build; break; default: ENSURE(); (*cur_s)[s_pos++] = *p++; break; } break; case BuildSQuoted: switch (*p) { case '\'': ++p; /* fall through */ case '\0': state = Build; break; default: ENSURE(); (*cur_s)[s_pos++] = *p++; break; } break; case AcceptNext: if (!*p) { state = Build; } else { ENSURE(); (*cur_s)[s_pos++] = *p++; } state = Build; break; } } done: argv[argc] = NULL; /* Sure to be large enough */ if (!argc) { efree(argv); return NULL; } return argv; #undef ENSURE } static char * errno_string(void) { char *str = strerror(errno); if (!str) return "unknown error"; return str; } static char ** read_args_file(char *filename) { int c, aix = 0, quote = 0, cmnt = 0, asize = 0; char **res, *astr = NULL; FILE *file; #undef EAF_CMNT #undef EAF_QUOTE #undef SAVE_CHAR #define EAF_CMNT (1 << 8) #define EAF_QUOTE (1 << 9) #define SAVE_CHAR(C) \ do { \ if (!astr) \ astr = emalloc(sizeof(char)*(asize = 20)); \ if (aix == asize) \ astr = erealloc(astr, sizeof(char)*(asize += 20)); \ if (' ' != (char) (C)) \ astr[aix++] = (char) (C); \ else if (aix > 0 && astr[aix-1] != ' ') \ astr[aix++] = ' '; \ } while (0) do { errno = 0; file = fopen(filename, "r"); } while (!file && errno == EINTR); if (!file) { usage_format("Failed to open arguments file \"%s\": %s\n", filename, errno_string()); } while (1) { c = getc(file); if (c == EOF) { if (ferror(file)) { if (errno == EINTR) { clearerr(file); continue; } usage_format("Failed to read arguments file \"%s\": %s\n", filename, errno_string()); } break; } switch (quote | cmnt | c) { case '\\': quote = EAF_QUOTE; break; case '#': cmnt = EAF_CMNT; break; case EAF_CMNT|'\n': cmnt = 0; /* Fall through... */ case '\n': case '\f': case '\r': case '\t': case '\v': if (!quote) c = ' '; /* Fall through... */ default: if (!cmnt) SAVE_CHAR(c); quote = 0; break; } } SAVE_CHAR('\0'); fclose(file); if (astr[0] == '\0') res = NULL; else res = build_args_from_string(astr); efree(astr); return res; #undef EAF_CMNT #undef EAF_QUOTE #undef SAVE_CHAR } typedef struct { char **argv; int argc; int size; } argv_buf; static void trim_argv_buf(argv_buf *abp) { abp->argv = erealloc(abp->argv, sizeof(char *)*(abp->size = abp->argc)); } static void save_arg(argv_buf *abp, char *arg) { if (abp->size <= abp->argc) { if (!abp->argv) abp->argv = emalloc(sizeof(char *)*(abp->size = 100)); else abp->argv = erealloc(abp->argv, sizeof(char *)*(abp->size += 100)); } abp->argv[abp->argc++] = arg; } #define DEF_ARGV_STACK_SIZE 10 #define ARGV_STACK_SIZE_INCR 50 typedef struct { char **argv; int ix; } argv_stack_element; typedef struct { int top_ix; int size; argv_stack_element *base; argv_stack_element def_buf[DEF_ARGV_STACK_SIZE]; } argv_stack; #define ARGV_STACK_INIT(S) \ do { \ (S)->top_ix = 0; \ (S)->size = DEF_ARGV_STACK_SIZE; \ (S)->base = &(S)->def_buf[0]; \ } while (0) static void push_argv(argv_stack *stck, char **argv, int ix) { if (stck->top_ix == stck->size) { if (stck->base != &stck->def_buf[0]) { stck->size += ARGV_STACK_SIZE_INCR; stck->base = erealloc(stck->base, sizeof(argv_stack_element)*stck->size); } else { argv_stack_element *base; base = emalloc(sizeof(argv_stack_element) *(stck->size + ARGV_STACK_SIZE_INCR)); memcpy((void *) base, (void *) stck->base, sizeof(argv_stack_element)*stck->size); stck->base = base; stck->size += ARGV_STACK_SIZE_INCR; } } stck->base[stck->top_ix].argv = argv; stck->base[stck->top_ix++].ix = ix; } static void pop_argv(argv_stack *stck, char ***argvp, int *ixp) { if (stck->top_ix == 0) { *argvp = NULL; *ixp = 0; } else { *argvp = stck->base[--stck->top_ix].argv; *ixp = stck->base[stck->top_ix].ix; if (stck->top_ix == 0 && stck->base != &stck->def_buf[0]) { efree(stck->base); stck->base = &stck->def_buf[0]; stck->size = DEF_ARGV_STACK_SIZE; } } } static void get_file_args(char *filename, argv_buf *abp, argv_buf *xabp) { argv_stack stck; int i; char **argv; ARGV_STACK_INIT(&stck); i = 0; argv = read_args_file(filename); while (argv) { while (argv[i]) { if (strcmp(argv[i], "-args_file") == 0) { char **new_argv; char *fname; if (!argv[++i]) usage("-args_file"); fname = argv[i++]; new_argv = read_args_file(fname); if (new_argv) { if (argv[i]) push_argv(&stck, argv, i); else efree(argv); i = 0; argv = new_argv; } } else { if (strcmp(argv[i], "-extra") == 0) { i++; while (argv[i]) save_arg(xabp, argv[i++]); break; } save_arg(abp, argv[i++]); } } efree(argv); pop_argv(&stck, &argv, &i); } } static void initial_argv_massage(int *argc, char ***argv) { argv_buf ab = {0}, xab = {0}; int ix, vix, ac; char **av; struct { int argc; char **argv; } avv[] = {{INT_MAX, NULL}, {INT_MAX, NULL}, {INT_MAX, NULL}, {INT_MAX, NULL}, {INT_MAX, NULL}, {INT_MAX, NULL}}; /* * The environment flag containing OTP release is intentionally * undocumented and intended for OTP internal use only. */ vix = 0; av = build_args_from_env("ERL_OTP" OTP_SYSTEM_VERSION "_FLAGS"); if (av) avv[vix++].argv = av; av = build_args_from_env("ERL_AFLAGS"); if (av) avv[vix++].argv = av; /* command line */ if (*argc > 1) { avv[vix].argc = *argc - 1; avv[vix++].argv = &(*argv)[1]; } av = build_args_from_env("ERL_FLAGS"); if (av) avv[vix++].argv = av; av = build_args_from_env("ERL_ZFLAGS"); if (av) avv[vix++].argv = av; if (vix == (*argc > 1 ? 1 : 0)) { /* Only command line argv; check if we can use argv as it is... */ ac = *argc; av = *argv; for (ix = 1; ix < ac; ix++) { if (strcmp(av[ix], "-args_file") == 0) { /* ... no; we need to expand arguments from file into argument list */ goto build_new_argv; } if (strcmp(av[ix], "-extra") == 0) { break; } } /* ... yes; we can use argv as it is. */ return; } build_new_argv: save_arg(&ab, (*argv)[0]); vix = 0; while (avv[vix].argv) { ac = avv[vix].argc; av = avv[vix].argv; ix = 0; while (ix < ac && av[ix]) { if (strcmp(av[ix], "-args_file") == 0) { if (++ix == ac) usage("-args_file"); get_file_args(av[ix++], &ab, &xab); } else { if (strcmp(av[ix], "-extra") == 0) { ix++; while (ix < ac && av[ix]) save_arg(&xab, av[ix++]); break; } save_arg(&ab, av[ix++]); } } vix++; } vix = 0; while (avv[vix].argv) { if (avv[vix].argc == INT_MAX) /* not command line */ efree(avv[vix].argv); vix++; } if (xab.argc) { save_arg(&ab, "-extra"); for (ix = 0; ix < xab.argc; ix++) save_arg(&ab, xab.argv[ix]); efree(xab.argv); } save_arg(&ab, NULL); trim_argv_buf(&ab); *argv = ab.argv; *argc = ab.argc - 1; } #ifdef __WIN32__ static char* possibly_quote(char* arg) { int mustQuote = NO; int n = 0; char* s; char* narg; /* * Scan the string to find out if it needs quoting and return * the original argument if not. */ for (s = arg; *s; s++, n++) { if (*s == ' ' || *s == '"') { mustQuote = YES; n++; } } if (!mustQuote) { return arg; } /* * Insert the quotes and put a backslash in front of every quote * inside the string. */ s = narg = emalloc(n+2+1); for (*s++ = '"'; *arg; arg++, s++) { if (*s == '"') { *s++ = '\\'; } *s = *arg; } *s++ = '"'; *s = '\0'; return narg; } /* * Unicode helpers to handle environment and command line parameters on * Windows. We internally handle all environment variables in UTF8, * but put and get the environment using the WCHAR (limited UTF16) interface * * These are simplified to only handle Unicode characters that can fit in * Windows simplified UTF16, i.e. characters that fit in 16 bits. */ static int utf8_len(unsigned char first) { if ((first & ((unsigned char) 0x80)) == 0) { return 1; } else if ((first & ((unsigned char) 0xE0)) == 0xC0) { return 2; } else if ((first & ((unsigned char) 0xF0)) == 0xE0) { return 3; } else if ((first & ((unsigned char) 0xF8)) == 0xF0) { return 4; } return 1; /* will be a '?' */ } static WCHAR *utf8_to_utf16(unsigned char *bytes) { unsigned int unipoint; unsigned char *tmp = bytes; WCHAR *target, *res; int num = 0; while (*tmp) { num++; tmp += utf8_len(*tmp); } res = target = emalloc((num + 1) * sizeof(WCHAR)); while (*bytes) { if (((*bytes) & ((unsigned char) 0x80)) == 0) { unipoint = (Uint) *bytes; ++bytes; } else if (((*bytes) & ((unsigned char) 0xE0)) == 0xC0) { unipoint = (((Uint) ((*bytes) & ((unsigned char) 0x1F))) << 6) | ((Uint) (bytes[1] & ((unsigned char) 0x3F))); bytes += 2; } else if (((*bytes) & ((unsigned char) 0xF0)) == 0xE0) { unipoint = (((Uint) ((*bytes) & ((unsigned char) 0xF))) << 12) | (((Uint) (bytes[1] & ((unsigned char) 0x3F))) << 6) | ((Uint) (bytes[2] & ((unsigned char) 0x3F))); if (unipoint > 0xFFFF) { unipoint = (unsigned int) '?'; } bytes +=3; } else if (((*bytes) & ((unsigned char) 0xF8)) == 0xF0) { unipoint = (unsigned int) '?'; /* Cannot put in a wchar */ bytes += 4; } else { unipoint = (unsigned int) '?'; } *target++ = (WCHAR) unipoint; } *target = L'\0'; return res; } static int put_utf8(WCHAR ch, unsigned char *target, int sz, int *pos) { Uint x = (Uint) ch; if (x < 0x80) { if (*pos >= sz) { return -1; } target[(*pos)++] = (unsigned char) x; } else if (x < 0x800) { if (((*pos) + 1) >= sz) { return -1; } target[(*pos)++] = (((unsigned char) (x >> 6)) | ((unsigned char) 0xC0)); target[(*pos)++] = (((unsigned char) (x & 0x3F)) | ((unsigned char) 0x80)); } else { if ((x >= 0xD800 && x <= 0xDFFF) || (x == 0xFFFE) || (x == 0xFFFF)) { /* Invalid unicode range */ return -1; } if (((*pos) + 2) >= sz) { return -1; } target[(*pos)++] = (((unsigned char) (x >> 12)) | ((unsigned char) 0xE0)); target[(*pos)++] = ((((unsigned char) (x >> 6)) & 0x3F) | ((unsigned char) 0x80)); target[(*pos)++] = (((unsigned char) (x & 0x3F)) | ((unsigned char) 0x80)); } return 0; } static int need_bytes_for_utf8(WCHAR x) { if (x < 0x80) return 1; else if (x < 0x800) return 2; else return 3; } static WCHAR *latin1_to_utf16(char *str) { int len = strlen(str); int i; WCHAR *wstr = emalloc((len+1) * sizeof(WCHAR)); for(i=0;i<len;++i) wstr[i] = (WCHAR) str[i]; wstr[len] = L'\0'; return wstr; } static char *utf16_to_utf8(WCHAR *wstr) { int len = wcslen(wstr); char *result; int i,pos; int reslen = 0; for(i=0;i<len;++i) { reslen += need_bytes_for_utf8(wstr[i]); } result = emalloc(reslen+1); pos = 0; for(i=0;i<len;++i) { if (put_utf8((int) wstr[i], result, reslen, &pos) < 0) { break; } } result[pos] = '\0'; return result; } #endif
498039.c
/* ** $Id: lstrlib.c,v 1.1.1.1 2002/04/05 08:42:51 strive Exp $ ** Standard library for string operations and pattern-matching ** See Copyright Notice in lua.h */ #include <ctype.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" static int str_len (lua_State *L) { size_t l; luaL_check_lstr(L, 1, &l); lua_pushnumber(L, l); return 1; } static long posrelat (long pos, size_t len) { /* relative string position: negative means back from end */ return (pos>=0) ? pos : (long)len+pos+1; } static int str_sub (lua_State *L) { size_t l; const char *s = luaL_check_lstr(L, 1, &l); long start = posrelat(luaL_check_long(L, 2), l); long end = posrelat(luaL_opt_long(L, 3, -1), l); if (start < 1) start = 1; if (end > (long)l) end = l; if (start <= end) lua_pushlstring(L, s+start-1, end-start+1); else lua_pushstring(L, ""); return 1; } static int str_lower (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_check_lstr(L, 1, &l); luaL_buffinit(L, &b); for (i=0; i<l; i++) luaL_putchar(&b, tolower((unsigned char)(s[i]))); luaL_pushresult(&b); return 1; } static int str_upper (lua_State *L) { size_t l; size_t i; luaL_Buffer b; const char *s = luaL_check_lstr(L, 1, &l); luaL_buffinit(L, &b); for (i=0; i<l; i++) luaL_putchar(&b, toupper((unsigned char)(s[i]))); luaL_pushresult(&b); return 1; } static int str_rep (lua_State *L) { size_t l; luaL_Buffer b; const char *s = luaL_check_lstr(L, 1, &l); int n = luaL_check_int(L, 2); luaL_buffinit(L, &b); while (n-- > 0) luaL_addlstring(&b, s, l); luaL_pushresult(&b); return 1; } static int str_byte (lua_State *L) { size_t l; const char *s = luaL_check_lstr(L, 1, &l); long pos = posrelat(luaL_opt_long(L, 2, 1), l); luaL_arg_check(L, 0<pos && (size_t)pos<=l, 2, "out of range"); lua_pushnumber(L, (unsigned char)s[pos-1]); return 1; } static int str_char (lua_State *L) { int n = lua_gettop(L); /* number of arguments */ int i; luaL_Buffer b; luaL_buffinit(L, &b); for (i=1; i<=n; i++) { int c = luaL_check_int(L, i); luaL_arg_check(L, (unsigned char)c == c, i, "invalid value"); luaL_putchar(&b, (unsigned char)c); } luaL_pushresult(&b); return 1; } /* ** {====================================================== ** PATTERN MATCHING ** ======================================================= */ #ifndef MAX_CAPTURES #define MAX_CAPTURES 32 /* arbitrary limit */ #endif struct Capture { const char *src_end; /* end ('\0') of source string */ int level; /* total number of captures (finished or unfinished) */ struct { const char *init; long len; /* -1 signals unfinished capture */ } capture[MAX_CAPTURES]; }; #define ESC '%' #define SPECIALS "^$*+?.([%-" static int check_capture (lua_State *L, int l, struct Capture *cap) { l -= '1'; if (!(0 <= l && l < cap->level && cap->capture[l].len != -1)) lua_error(L, "invalid capture index"); return l; } static int capture_to_close (lua_State *L, struct Capture *cap) { int level = cap->level; for (level--; level>=0; level--) if (cap->capture[level].len == -1) return level; lua_error(L, "invalid pattern capture"); return 0; /* to avoid warnings */ } const char *luaI_classend (lua_State *L, const char *p) { switch (*p++) { case ESC: if (*p == '\0') lua_error(L, "malformed pattern (ends with `%')"); return p+1; case '[': if (*p == '^') p++; do { /* look for a ']' */ if (*p == '\0') lua_error(L, "malformed pattern (missing `]')"); if (*(p++) == ESC && *p != '\0') p++; /* skip escapes (e.g. '%]') */ } while (*p != ']'); return p+1; default: return p; } } static int match_class (int c, int cl) { int res; switch (tolower(cl)) { case 'a' : res = isalpha(c); break; case 'c' : res = iscntrl(c); break; case 'd' : res = isdigit(c); break; case 'l' : res = islower(c); break; case 'p' : res = ispunct(c); break; case 's' : res = isspace(c); break; case 'u' : res = isupper(c); break; case 'w' : res = isalnum(c); break; case 'x' : res = isxdigit(c); break; case 'z' : res = (c == '\0'); break; default: return (cl == c); } return (islower(cl) ? res : !res); } static int matchbracketclass (int c, const char *p, const char *endclass) { int sig = 1; if (*(p+1) == '^') { sig = 0; p++; /* skip the '^' */ } while (++p < endclass) { if (*p == ESC) { p++; if (match_class(c, (unsigned char)*p)) return sig; } else if ((*(p+1) == '-') && (p+2 < endclass)) { p+=2; if ((int)(unsigned char)*(p-2) <= c && c <= (int)(unsigned char)*p) return sig; } else if ((int)(unsigned char)*p == c) return sig; } return !sig; } int luaI_singlematch (int c, const char *p, const char *ep) { switch (*p) { case '.': /* matches any char */ return 1; case ESC: return match_class(c, (unsigned char)*(p+1)); case '[': return matchbracketclass(c, p, ep-1); default: return ((unsigned char)*p == c); } } static const char *match (lua_State *L, const char *s, const char *p, struct Capture *cap); static const char *matchbalance (lua_State *L, const char *s, const char *p, struct Capture *cap) { if (*p == 0 || *(p+1) == 0) lua_error(L, "unbalanced pattern"); if (*s != *p) return NULL; else { int b = *p; int e = *(p+1); int cont = 1; while (++s < cap->src_end) { if (*s == e) { if (--cont == 0) return s+1; } else if (*s == b) cont++; } } return NULL; /* string ends out of balance */ } static const char *max_expand (lua_State *L, const char *s, const char *p, const char *ep, struct Capture *cap) { long i = 0; /* counts maximum expand for item */ while ((s+i)<cap->src_end && luaI_singlematch((unsigned char)*(s+i), p, ep)) i++; /* keeps trying to match with the maximum repetitions */ while (i>=0) { const char *res = match(L, (s+i), ep+1, cap); if (res) return res; i--; /* else didn't match; reduce 1 repetition to try again */ } return NULL; } static const char *min_expand (lua_State *L, const char *s, const char *p, const char *ep, struct Capture *cap) { for (;;) { const char *res = match(L, s, ep+1, cap); if (res != NULL) return res; else if (s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep)) s++; /* try with one more repetition */ else return NULL; } } static const char *start_capture (lua_State *L, const char *s, const char *p, struct Capture *cap) { const char *res; int level = cap->level; if (level >= MAX_CAPTURES) lua_error(L, "too many captures"); cap->capture[level].init = s; cap->capture[level].len = -1; cap->level = level+1; if ((res=match(L, s, p+1, cap)) == NULL) /* match failed? */ cap->level--; /* undo capture */ return res; } static const char *end_capture (lua_State *L, const char *s, const char *p, struct Capture *cap) { int l = capture_to_close(L, cap); const char *res; cap->capture[l].len = s - cap->capture[l].init; /* close capture */ if ((res = match(L, s, p+1, cap)) == NULL) /* match failed? */ cap->capture[l].len = -1; /* undo capture */ return res; } static const char *match_capture (lua_State *L, const char *s, int level, struct Capture *cap) { int l = check_capture(L, level, cap); size_t len = cap->capture[l].len; if ((size_t)(cap->src_end-s) >= len && memcmp(cap->capture[l].init, s, len) == 0) return s+len; else return NULL; } static const char *match (lua_State *L, const char *s, const char *p, struct Capture *cap) { init: /* using goto's to optimize tail recursion */ switch (*p) { case '(': /* start capture */ return start_capture(L, s, p, cap); case ')': /* end capture */ return end_capture(L, s, p, cap); case ESC: /* may be %[0-9] or %b */ if (isdigit((unsigned char)(*(p+1)))) { /* capture? */ s = match_capture(L, s, *(p+1), cap); if (s == NULL) return NULL; p+=2; goto init; /* else return match(L, s, p+2, cap) */ } else if (*(p+1) == 'b') { /* balanced string? */ s = matchbalance(L, s, p+2, cap); if (s == NULL) return NULL; p+=4; goto init; /* else return match(L, s, p+4, cap); */ } else goto dflt; /* case default */ case '\0': /* end of pattern */ return s; /* match succeeded */ case '$': if (*(p+1) == '\0') /* is the '$' the last char in pattern? */ return (s == cap->src_end) ? s : NULL; /* check end of string */ else goto dflt; default: dflt: { /* it is a pattern item */ const char *ep = luaI_classend(L, p); /* points to what is next */ int m = s<cap->src_end && luaI_singlematch((unsigned char)*s, p, ep); switch (*ep) { case '?': { /* optional */ const char *res; if (m && ((res=match(L, s+1, ep+1, cap)) != NULL)) return res; p=ep+1; goto init; /* else return match(L, s, ep+1, cap); */ } case '*': /* 0 or more repetitions */ return max_expand(L, s, p, ep, cap); case '+': /* 1 or more repetitions */ return (m ? max_expand(L, s+1, p, ep, cap) : NULL); case '-': /* 0 or more repetitions (minimum) */ return min_expand(L, s, p, ep, cap); default: if (!m) return NULL; s++; p=ep; goto init; /* else return match(L, s+1, ep, cap); */ } } } } static const char *lmemfind (const char *s1, size_t l1, const char *s2, size_t l2) { if (l2 == 0) return s1; /* empty strings are everywhere */ else if (l2 > l1) return NULL; /* avoids a negative `l1' */ else { const char *init; /* to search for a `*s2' inside `s1' */ l2--; /* 1st char will be checked by `memchr' */ l1 = l1-l2; /* `s2' cannot be found after that */ while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) { init++; /* 1st char is already checked */ if (memcmp(init, s2+1, l2) == 0) return init-1; else { /* correct `l1' and `s1' to try again */ l1 -= init-s1; s1 = init; } } return NULL; /* not found */ } } static int push_captures (lua_State *L, struct Capture *cap) { int i; luaL_checkstack(L, cap->level, "too many captures"); for (i=0; i<cap->level; i++) { int l = cap->capture[i].len; if (l == -1) lua_error(L, "unfinished capture"); lua_pushlstring(L, cap->capture[i].init, l); } return cap->level; /* number of strings pushed */ } static int str_find (lua_State *L) { size_t l1, l2; const char *s = luaL_check_lstr(L, 1, &l1); const char *p = luaL_check_lstr(L, 2, &l2); long init = posrelat(luaL_opt_long(L, 3, 1), l1) - 1; struct Capture cap; luaL_arg_check(L, 0 <= init && (size_t)init <= l1, 3, "out of range"); if (lua_gettop(L) > 3 || /* extra argument? */ strpbrk(p, SPECIALS) == NULL) { /* or no special characters? */ const char *s2 = lmemfind(s+init, l1-init, p, l2); if (s2) { lua_pushnumber(L, s2-s+1); lua_pushnumber(L, s2-s+l2); return 2; } } else { int anchor = (*p == '^') ? (p++, 1) : 0; const char *s1=s+init; cap.src_end = s+l1; do { const char *res; cap.level = 0; if ((res=match(L, s1, p, &cap)) != NULL) { lua_pushnumber(L, s1-s+1); /* start */ lua_pushnumber(L, res-s); /* end */ return push_captures(L, &cap) + 2; } } while (s1++<cap.src_end && !anchor); } lua_pushnil(L); /* not found */ return 1; } static void add_s (lua_State *L, luaL_Buffer *b, struct Capture *cap) { if (lua_isstring(L, 3)) { const char *news = lua_tostring(L, 3); size_t l = lua_strlen(L, 3); size_t i; for (i=0; i<l; i++) { if (news[i] != ESC) luaL_putchar(b, news[i]); else { i++; /* skip ESC */ if (!isdigit((unsigned char)news[i])) luaL_putchar(b, news[i]); else { int level = check_capture(L, news[i], cap); luaL_addlstring(b, cap->capture[level].init, cap->capture[level].len); } } } } else { /* is a function */ int n; lua_pushvalue(L, 3); n = push_captures(L, cap); lua_rawcall(L, n, 1); if (lua_isstring(L, -1)) luaL_addvalue(b); /* add return to accumulated result */ else lua_pop(L, 1); /* function result is not a string: pop it */ } } static int str_gsub (lua_State *L) { size_t srcl; const char *src = luaL_check_lstr(L, 1, &srcl); const char *p = luaL_check_string(L, 2); int max_s = luaL_opt_int(L, 4, srcl+1); int anchor = (*p == '^') ? (p++, 1) : 0; int n = 0; struct Capture cap; luaL_Buffer b; luaL_arg_check(L, lua_gettop(L) >= 3 && (lua_isstring(L, 3) || lua_isfunction(L, 3)), 3, "string or function expected"); luaL_buffinit(L, &b); cap.src_end = src+srcl; while (n < max_s) { const char *e; cap.level = 0; e = match(L, src, p, &cap); if (e) { n++; add_s(L, &b, &cap); } if (e && e>src) /* non empty match? */ src = e; /* skip it */ else if (src < cap.src_end) luaL_putchar(&b, *src++); else break; if (anchor) break; } luaL_addlstring(&b, src, cap.src_end-src); luaL_pushresult(&b); lua_pushnumber(L, n); /* number of substitutions */ return 2; } /* }====================================================== */ static void luaI_addquoted (lua_State *L, luaL_Buffer *b, int arg) { size_t l; const char *s = luaL_check_lstr(L, arg, &l); luaL_putchar(b, '"'); while (l--) { switch (*s) { case '"': case '\\': case '\n': luaL_putchar(b, '\\'); luaL_putchar(b, *s); break; case '\0': luaL_addlstring(b, "\\000", 4); break; default: luaL_putchar(b, *s); } s++; } luaL_putchar(b, '"'); } /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */ #define MAX_ITEM 512 /* maximum size of each format specification (such as '%-099.99d') */ #define MAX_FORMAT 20 static int str_format (lua_State *L) { int arg = 1; const char *strfrmt = luaL_check_string(L, arg); luaL_Buffer b; luaL_buffinit(L, &b); while (*strfrmt) { if (*strfrmt != '%') luaL_putchar(&b, *strfrmt++); else if (*++strfrmt == '%') luaL_putchar(&b, *strfrmt++); /* %% */ else { /* format item */ struct Capture cap; char form[MAX_FORMAT]; /* to store the format ('%...') */ char buff[MAX_ITEM]; /* to store the formatted item */ const char *initf = strfrmt; form[0] = '%'; if (isdigit((unsigned char)*initf) && *(initf+1) == '$') { arg = *initf - '0'; initf += 2; /* skip the 'n$' */ } arg++; cap.src_end = strfrmt+strlen(strfrmt)+1; cap.level = 0; strfrmt = match(L, initf, "[-+ #0]*(%d*)%.?(%d*)", &cap); if (cap.capture[0].len > 2 || cap.capture[1].len > 2 || /* < 100? */ strfrmt-initf > MAX_FORMAT-2) lua_error(L, "invalid format (width or precision too long)"); strncpy(form+1, initf, strfrmt-initf+1); /* +1 to include conversion */ form[strfrmt-initf+2] = 0; switch (*strfrmt++) { case 'c': case 'd': case 'i': sprintf(buff, form, luaL_check_int(L, arg)); break; case 'o': case 'u': case 'x': case 'X': sprintf(buff, form, (unsigned int)luaL_check_number(L, arg)); break; case 'e': case 'E': case 'f': case 'g': case 'G': sprintf(buff, form, luaL_check_number(L, arg)); break; case 'q': luaI_addquoted(L, &b, arg); continue; /* skip the "addsize" at the end */ case 's': { size_t l; const char *s = luaL_check_lstr(L, arg, &l); if (cap.capture[1].len == 0 && l >= 100) { /* no precision and string is too long to be formatted; keep original string */ lua_pushvalue(L, arg); luaL_addvalue(&b); continue; /* skip the "addsize" at the end */ } else { sprintf(buff, form, s); break; } } default: /* also treat cases 'pnLlh' */ lua_error(L, "invalid option in `format'"); } luaL_addlstring(&b, buff, strlen(buff)); } } luaL_pushresult(&b); return 1; } static const struct luaL_reg strlib[] = { {"strlen", str_len}, {"strsub", str_sub}, {"strlower", str_lower}, {"strupper", str_upper}, {"strchar", str_char}, {"strrep", str_rep}, {"ascii", str_byte}, /* for compatibility with 3.0 and earlier */ {"strbyte", str_byte}, {"format", str_format}, {"strfind", str_find}, {"gsub", str_gsub} }; /* ** Open string library */ LUALIB_API void lua_strlibopen (lua_State *L) { luaL_openl(L, strlib); }
259547.c
/* +--------------------------------------------------------------------+ | libmemcached-awesome - C/C++ Client Library for memcached | +--------------------------------------------------------------------+ | Redistribution and use in source and binary forms, with or without | | modification, are permitted under the terms of the BSD license. | | You should have received a copy of the license in a bundled file | | named LICENSE; in case you did not receive a copy you can review | | the terms online at: https://opensource.org/licenses/BSD-3-Clause | +--------------------------------------------------------------------+ | Copyright (c) 2006-2014 Brian Aker https://datadifferential.com/ | | Copyright (c) 2020 Michael Wallner <[email protected]> | +--------------------------------------------------------------------+ */ #include "mem_config.h" #if defined(HAVE_SYS_TIME_H) # include <sys/time.h> #endif #include <time.h> #include <inttypes.h> #include "ms_thread.h" #include "ms_setting.h" #include "ms_atomic.h" /* command distribution adjustment cycle */ #define CMD_DISTR_ADJUST_CYCLE 1000 #define DISADJUST_FACTOR \ 0.03 /** \ * In one adjustment cycle, if undo set or get \ * operations proportion is more than 3% , means \ * there are too many new item or need more new \ * item in the window. This factor shows it. \ */ /* get item from task window */ static ms_task_item_t *ms_get_cur_opt_item(ms_conn_t *c); static ms_task_item_t *ms_get_next_get_item(ms_conn_t *c); static ms_task_item_t *ms_get_next_set_item(ms_conn_t *c); static ms_task_item_t *ms_get_random_overwrite_item(ms_conn_t *c); /* select next operation to do */ static void ms_select_opt(ms_conn_t *c, ms_task_t *task); /* set and get speed estimate for controlling and adjustment */ static bool ms_is_set_too_fast(ms_task_t *task); static bool ms_is_get_too_fast(ms_task_t *task); static void ms_kick_out_item(ms_task_item_t *item); /* miss rate adjustment */ static bool ms_need_overwrite_item(ms_task_t *task); static bool ms_adjust_opt(ms_conn_t *c, ms_task_t *task); /* deal with data verification initialization */ static void ms_task_data_verify_init(ms_task_t *task); static void ms_task_expire_verify_init(ms_task_t *task); /* select a new task to do */ static ms_task_t *ms_get_task(ms_conn_t *c, bool warmup); /* run the selected task */ static void ms_update_set_result(ms_conn_t *c, ms_task_item_t *item); static void ms_update_stat_result(ms_conn_t *c); static void ms_update_multi_get_result(ms_conn_t *c); static void ms_update_single_get_result(ms_conn_t *c, ms_task_item_t *item); static void ms_update_task_result(ms_conn_t *c); static void ms_single_getset_task_sch(ms_conn_t *c); static void ms_multi_getset_task_sch(ms_conn_t *c); static void ms_send_signal(ms_sync_lock_t *sync_lock); static void ms_warmup_server(ms_conn_t *c); static int ms_run_getset_task(ms_conn_t *c); /** * used to get the current operation item(object) * * @param c, pointer of the concurrency * * @return ms_task_item_t*, current operating item */ static ms_task_item_t *ms_get_cur_opt_item(ms_conn_t *c) { return c->curr_task.item; } /** * used to get the next item to do get operation * * @param c, pointer of the concurrency * * @return ms_task_item_t*, the pointer of the next item to do * get operation */ static ms_task_item_t *ms_get_next_get_item(ms_conn_t *c) { ms_task_item_t *item = NULL; if (c->set_cursor <= 0) { /* the first item in the window */ item = &c->item_win[0]; } else if (c->set_cursor > 0 && c->set_cursor < (uint32_t) c->win_size) { /* random get one item set before */ item = &c->item_win[random() % (int64_t) c->set_cursor]; } else { /* random get one item from the window */ item = &c->item_win[random() % c->win_size]; } return item; } /* ms_get_next_get_item */ /** * used to get the next item to do set operation * * @param c, pointer of the concurrency * * @return ms_task_item_t*, the pointer of the next item to do * set operation */ static ms_task_item_t *ms_get_next_set_item(ms_conn_t *c) { /** * when a set command successes, the cursor will plus 1. If set * fails, the cursor doesn't change. it isn't necessary to * increase the cursor here. */ return &c->item_win[(int64_t) c->set_cursor % c->win_size]; } /** * If we need do overwrite, we could select a item set before. * This function is used to get a item set before to do * overwrite. * * @param c, pointer of the concurrency * * @return ms_task_item_t*, the pointer of the previous item of * set operation */ static ms_task_item_t *ms_get_random_overwrite_item(ms_conn_t *c) { return ms_get_next_get_item(c); } /* ms_get_random_overwrite_item */ /** * According to the proportion of operations(get or set), select * an operation to do. * * @param c, pointer of the concurrency * @param task, pointer of current task in the concurrency */ static void ms_select_opt(ms_conn_t *c, ms_task_t *task) { double get_prop = ms_setting.cmd_distr[CMD_GET].cmd_prop; double set_prop = ms_setting.cmd_distr[CMD_SET].cmd_prop; /* update cycle operation number if necessary */ if ((task->cycle_undo_get == 0) || (task->cycle_undo_set == 0)) { task->cycle_undo_get += (int) (CMD_DISTR_ADJUST_CYCLE * get_prop); task->cycle_undo_set += (int) (CMD_DISTR_ADJUST_CYCLE * set_prop); } /** * According to operation distribution to choose doing which * operation. If it can't set new object to sever, just change * to do get operation. */ if ((set_prop > PROP_ERROR) && ((double) task->get_opt * set_prop >= (double) task->set_opt * get_prop)) { task->cmd = CMD_SET; task->item = ms_get_next_set_item(c); } else { task->cmd = CMD_GET; task->item = ms_get_next_get_item(c); } } /* ms_select_opt */ /** * used to judge whether the number of get operations done is * more than expected number of get operations to do right now. * * @param task, pointer of current task in the concurrency * * @return bool, if get too fast, return true, else return false */ static bool ms_is_get_too_fast(ms_task_t *task) { double get_prop = ms_setting.cmd_distr[CMD_GET].cmd_prop; double set_prop = ms_setting.cmd_distr[CMD_SET].cmd_prop; /* no get operation */ if (get_prop < PROP_ERROR) { return false; } int max_undo_set = (int) (set_prop / get_prop * (1.0 + DISADJUST_FACTOR)) * task->cycle_undo_get; if (((double) task->get_opt * set_prop > (double) task->set_opt * get_prop) && (task->cycle_undo_set > max_undo_set)) { return true; } return false; } /* ms_is_get_too_fast */ /** * used to judge whether the number of set operations done is * more than expected number of set operations to do right now. * * @param task, pointer of current task in the concurrency * * @return bool, if set too fast, return true, else return false */ static bool ms_is_set_too_fast(ms_task_t *task) { double get_prop = ms_setting.cmd_distr[CMD_GET].cmd_prop; double set_prop = ms_setting.cmd_distr[CMD_SET].cmd_prop; /* no set operation */ if (set_prop < PROP_ERROR) { return false; } /* If it does set operation too fast, skip some */ int max_undo_get = (int) ((get_prop / set_prop * (1.0 + DISADJUST_FACTOR)) * (double) task->cycle_undo_set); if (((double) task->get_opt * set_prop < (double) task->set_opt * get_prop) && (task->cycle_undo_get > max_undo_get)) { return true; } return false; } /* ms_is_set_too_fast */ /** * kick out the old item in the window, and add a new item to * overwrite the old item. When we don't want to do overwrite * object, and the current item to do set operation is an old * item, we could kick out the old item and add a new item. Then * we can ensure we set new object every time. * * @param item, pointer of task item which includes the object * information */ static void ms_kick_out_item(ms_task_item_t *item) { /* allocate a new item */ item->key_prefix = ms_get_key_prefix(); item->key_suffix_offset++; item->value_offset = INVALID_OFFSET; /* new item use invalid value offset */ item->client_time = 0; } /* ms_kick_out_item */ /** * used to judge whether we need overwrite object based on the * options user specified * * @param task, pointer of current task in the concurrency * * @return bool, if need overwrite, return true, else return * false */ static bool ms_need_overwrite_item(ms_task_t *task) { ms_task_item_t *item = task->item; assert(item); assert(task->cmd == CMD_SET); /** * according to data overwrite percent to determine if do data * overwrite. */ if (task->overwrite_set < (double) task->set_opt * ms_setting.overwrite_percent) { return true; } return false; } /* ms_need_overwirte_item */ /** * used to adjust operation. the function must be called after * select operation. the function change get operation to set * operation, or set operation to get operation based on the * current case. * * @param c, pointer of the concurrency * @param task, pointer of current task in the concurrency * * @return bool, if success, return true, else return false */ static bool ms_adjust_opt(ms_conn_t *c, ms_task_t *task) { ms_task_item_t *item = task->item; assert(item); if (task->cmd == CMD_SET) { /* If did set operation too fast, skip some */ if (ms_is_set_too_fast(task)) { /* get the item instead */ if (item->value_offset != INVALID_OFFSET) { task->cmd = CMD_GET; return true; } } /* If the current item is not a new item, kick it out */ if (item->value_offset != INVALID_OFFSET) { if (ms_need_overwrite_item(task)) { /* overwrite */ task->overwrite_set++; } else { /* kick out the current item to do set operation */ ms_kick_out_item(item); } } else /* it's a new item */ { /* need overwrite */ if (ms_need_overwrite_item(task)) { /** * overwrite not use the item with current set cursor, revert * set cursor. */ c->set_cursor--; item = ms_get_random_overwrite_item(c); if (item->value_offset != INVALID_OFFSET) { task->item = item; task->overwrite_set++; } else /* item is a new item */ { /* select the item to run, and cancel overwrite */ task->item = item; } } } task->cmd = CMD_SET; return true; } else { if (item->value_offset == INVALID_OFFSET) { task->cmd = CMD_SET; return true; } /** * If It does get operation too fast, it will change the * operation to set. */ if (ms_is_get_too_fast(task)) { /* don't kick out the first item in the window */ if (!ms_is_set_too_fast(task)) { ms_kick_out_item(item); task->cmd = CMD_SET; return true; } else { return false; } } assert(item->value_offset != INVALID_OFFSET); task->cmd = CMD_GET; return true; } } /* ms_adjust_opt */ /** * used to initialize the task which need verify data. * * @param task, pointer of current task in the concurrency */ static void ms_task_data_verify_init(ms_task_t *task) { ms_task_item_t *item = task->item; assert(item); assert(task->cmd == CMD_GET); /** * according to data verification percent to determine if do * data verification. */ if (task->verified_get < (double) task->get_opt * ms_setting.verify_percent) { /** * currently it doesn't do verify, just increase the counter, * and do verification next proper get command */ if ((task->item->value_offset != INVALID_OFFSET) && (item->exp_time == 0)) { task->verify = true; task->finish_verify = false; task->verified_get++; } } } /* ms_task_data_verify_init */ /** * used to initialize the task which need verify expire time. * * @param task, pointer of current task in the concurrency */ static void ms_task_expire_verify_init(ms_task_t *task) { ms_task_item_t *item = task->item; assert(item); assert(task->cmd == CMD_GET); assert(item->exp_time > 0); task->verify = true; task->finish_verify = false; } /* ms_task_expire_verify_init */ /** * used to get one task, the function initializes the task * structure. * * @param c, pointer of the concurrency * @param warmup, whether it need warmup * * @return ms_task_t*, pointer of current task in the * concurrency */ static ms_task_t *ms_get_task(ms_conn_t *c, bool warmup) { ms_task_t *task = &c->curr_task; while (1) { task->verify = false; task->finish_verify = true; task->get_miss = true; if (warmup) { task->cmd = CMD_SET; task->item = ms_get_next_set_item(c); return task; } /* according to operation distribution to choose doing which operation */ ms_select_opt(c, task); if (!ms_adjust_opt(c, task)) { continue; } if ((ms_setting.verify_percent > 0) && (task->cmd == CMD_GET)) { ms_task_data_verify_init(task); } if ((ms_setting.exp_ver_per > 0) && (task->cmd == CMD_GET) && (task->item->exp_time > 0)) { ms_task_expire_verify_init(task); } break; } /** * Only update get and delete counter, set counter will be * updated after set operation successes. */ if (task->cmd == CMD_GET) { task->get_opt++; task->cycle_undo_get--; } return task; } /* ms_get_task */ /** * send a signal to the main monitor thread * * @param sync_lock, pointer of the lock */ static void ms_send_signal(ms_sync_lock_t *sync_lock) { pthread_mutex_lock(&sync_lock->lock); sync_lock->count++; pthread_cond_signal(&sync_lock->cond); pthread_mutex_unlock(&sync_lock->lock); } /* ms_send_signal */ /** * If user only want to do get operation, but there is no object * in server , so we use this function to warmup the server, and * set some objects to server. It runs at the beginning of task. * * @param c, pointer of the concurrency */ static void ms_warmup_server(ms_conn_t *c) { ms_task_t *task; ms_task_item_t *item; /** * Extra one loop to get the last command returned state. * Normally it gets the previous command returned state. */ if ((c->remain_warmup_num >= 0) && (c->remain_warmup_num != c->warmup_num)) { item = ms_get_cur_opt_item(c); /* only update the set command result state for data verification */ if ((c->precmd.cmd == CMD_SET) && (c->precmd.retstat == MCD_STORED)) { item->value_offset = item->key_suffix_offset; /* set success, update counter */ c->set_cursor++; } else if (c->precmd.cmd == CMD_SET && c->precmd.retstat != MCD_STORED) { printf("key: %" PRIx64 " didn't set success\n", item->key_prefix); } } /* the last time don't run a task */ if (c->remain_warmup_num-- > 0) { /* operate next task item */ task = ms_get_task(c, true); item = task->item; ms_mcd_set(c, item); } /** * finish warming up server, wait all connects initialize * complete. Then all connects can start do task at the same * time. */ if (c->remain_warmup_num == -1) { ms_send_signal(&ms_global.warmup_lock); c->remain_warmup_num--; /* never run the if branch */ } } /* ms_warmup_server */ /** * dispatch single get and set task * * @param c, pointer of the concurrency */ static void ms_single_getset_task_sch(ms_conn_t *c) { ms_task_t *task; ms_task_item_t *item; /* the last time don't run a task */ if (c->remain_exec_num-- > 0) { task = ms_get_task(c, false); item = task->item; if (task->cmd == CMD_SET) { ms_mcd_set(c, item); } else if (task->cmd == CMD_GET) { assert(task->cmd == CMD_GET); ms_mcd_get(c, item); } } } /* ms_single_getset_task_sch */ /** * dispatch multi-get and set task * * @param c, pointer of the concurrency */ static void ms_multi_getset_task_sch(ms_conn_t *c) { ms_task_t *task; ms_mlget_task_item_t *mlget_item; while (1) { if (c->remain_exec_num-- > 0) { task = ms_get_task(c, false); if (task->cmd == CMD_SET) /* just do it */ { ms_mcd_set(c, task->item); break; } else { assert(task->cmd == CMD_GET); mlget_item = &c->mlget_task.mlget_item[c->mlget_task.mlget_num]; mlget_item->item = task->item; mlget_item->verify = task->verify; mlget_item->finish_verify = task->finish_verify; mlget_item->get_miss = task->get_miss; c->mlget_task.mlget_num++; /* enough multi-get task items can be done */ if ((c->mlget_task.mlget_num >= ms_setting.mult_key_num) || ((c->remain_exec_num == 0) && (c->mlget_task.mlget_num > 0))) { ms_mcd_mlget(c); break; } } } else { if ((c->remain_exec_num <= 0) && (c->mlget_task.mlget_num > 0)) { ms_mcd_mlget(c); } break; } } } /* ms_multi_getset_task_sch */ /** * calculate the difference value of two time points * * @param start_time, the start time * @param end_time, the end time * * @return uint64_t, the difference value between start_time and end_time in us */ int64_t ms_time_diff(struct timeval *start_time, struct timeval *end_time) { int64_t endtime = end_time->tv_sec * 1000000 + end_time->tv_usec; int64_t starttime = start_time->tv_sec * 1000000 + start_time->tv_usec; assert(endtime >= starttime); return endtime - starttime; } /* ms_time_diff */ /** * after get the response from server for multi-get, the * function update the state of the task and do data verify if * necessary. * * @param c, pointer of the concurrency */ static void ms_update_multi_get_result(ms_conn_t *c) { ms_mlget_task_item_t *mlget_item; ms_task_item_t *item; char *orignval = NULL; char *orignkey = NULL; if (c == NULL) { return; } assert(c); for (int i = 0; i < c->mlget_task.mlget_num; i++) { mlget_item = &c->mlget_task.mlget_item[i]; item = mlget_item->item; orignval = &ms_setting.char_block[item->value_offset]; orignkey = &ms_setting.char_block[item->key_suffix_offset]; /* update get miss counter */ if (mlget_item->get_miss) { atomic_add_size(&ms_stats.get_misses, 1); } /* get nothing from server for this task item */ if (mlget_item->verify && !mlget_item->finish_verify) { /* verify expire time if necessary */ if (item->exp_time > 0) { struct timeval curr_time; gettimeofday(&curr_time, NULL); /* object doesn't expire but can't get it now */ if (curr_time.tv_sec - item->client_time < item->exp_time - EXPIRE_TIME_ERROR) { atomic_add_size(&ms_stats.unexp_unget, 1); if (ms_setting.verbose) { char set_time[64]; char cur_time[64]; strftime(set_time, 64, "%Y-%m-%d %H:%M:%S", localtime(&item->client_time)); strftime(cur_time, 64, "%Y-%m-%d %H:%M:%S", localtime(&curr_time.tv_sec)); fprintf(stderr, "\n\t<%d expire time verification failed, object " "doesn't expire but can't get it now\n" "\tkey len: %d\n" "\tkey: %" PRIx64 " %.*s\n" "\tset time: %s current time: %s " "diff time: %d expire time: %d\n" "\texpected data len: %d\n" "\texpected data: %.*s\n" "\treceived data: \n", c->sfd, item->key_size, item->key_prefix, item->key_size - (int) KEY_PREFIX_SIZE, orignkey, set_time, cur_time, (int) (curr_time.tv_sec - item->client_time), item->exp_time, item->value_size, item->value_size, orignval); fflush(stderr); } } } else { atomic_add_size(&ms_stats.vef_miss, 1); if (ms_setting.verbose) { fprintf(stderr, "\n<%d data verification failed\n" "\tkey len: %d\n" "\tkey: %" PRIx64 " %.*s\n" "\texpected data len: %d\n" "\texpected data: %.*s\n" "\treceived data: \n", c->sfd, item->key_size, item->key_prefix, item->key_size - (int) KEY_PREFIX_SIZE, orignkey, item->value_size, item->value_size, orignval); fflush(stderr); } } } } c->mlget_task.mlget_num = 0; c->mlget_task.value_index = INVALID_OFFSET; } /* ms_update_multi_get_result */ /** * after get the response from server for single get, the * function update the state of the task and do data verify if * necessary. * * @param c, pointer of the concurrency * @param item, pointer of task item which includes the object * information */ static void ms_update_single_get_result(ms_conn_t *c, ms_task_item_t *item) { char *orignval = NULL; char *orignkey = NULL; if ((c == NULL) || (item == NULL)) { return; } assert(c); assert(item); orignval = &ms_setting.char_block[item->value_offset]; orignkey = &ms_setting.char_block[item->key_suffix_offset]; /* update get miss counter */ if ((c->precmd.cmd == CMD_GET) && c->curr_task.get_miss) { atomic_add_size(&ms_stats.get_misses, 1); } /* get nothing from server for this task item */ if ((c->precmd.cmd == CMD_GET) && c->curr_task.verify && !c->curr_task.finish_verify) { /* verify expire time if necessary */ if (item->exp_time > 0) { struct timeval curr_time; gettimeofday(&curr_time, NULL); /* object doesn't expire but can't get it now */ if (curr_time.tv_sec - item->client_time < item->exp_time - EXPIRE_TIME_ERROR) { atomic_add_size(&ms_stats.unexp_unget, 1); if (ms_setting.verbose) { char set_time[64]; char cur_time[64]; strftime(set_time, 64, "%Y-%m-%d %H:%M:%S", localtime(&item->client_time)); strftime(cur_time, 64, "%Y-%m-%d %H:%M:%S", localtime(&curr_time.tv_sec)); fprintf(stderr, "\n\t<%d expire time verification failed, object " "doesn't expire but can't get it now\n" "\tkey len: %d\n" "\tkey: %" PRIx64 " %.*s\n" "\tset time: %s current time: %s " "diff time: %d expire time: %d\n" "\texpected data len: %d\n" "\texpected data: %.*s\n" "\treceived data: \n", c->sfd, item->key_size, item->key_prefix, item->key_size - (int) KEY_PREFIX_SIZE, orignkey, set_time, cur_time, (int) (curr_time.tv_sec - item->client_time), item->exp_time, item->value_size, item->value_size, orignval); fflush(stderr); } } } else { atomic_add_size(&ms_stats.vef_miss, 1); if (ms_setting.verbose) { fprintf(stderr, "\n<%d data verification failed\n" "\tkey len: %d\n" "\tkey: %" PRIx64 " %.*s\n" "\texpected data len: %d\n" "\texpected data: %.*s\n" "\treceived data: \n", c->sfd, item->key_size, item->key_prefix, item->key_size - (int) KEY_PREFIX_SIZE, orignkey, item->value_size, item->value_size, orignval); fflush(stderr); } } } } /* ms_update_single_get_result */ /** * after get the response from server for set the function * update the state of the task and do data verify if necessary. * * @param c, pointer of the concurrency * @param item, pointer of task item which includes the object * information */ static void ms_update_set_result(ms_conn_t *c, ms_task_item_t *item) { if ((c == NULL) || (item == NULL)) { return; } assert(c); assert(item); if (c->precmd.cmd == CMD_SET) { switch (c->precmd.retstat) { case MCD_STORED: if (item->value_offset == INVALID_OFFSET) { /* first set with the same offset of key suffix */ item->value_offset = item->key_suffix_offset; } else { /* not first set, just increase the value offset */ item->value_offset += 1; } /* set successes, update counter */ c->set_cursor++; c->curr_task.set_opt++; c->curr_task.cycle_undo_set--; break; case MCD_SERVER_ERROR: default: break; } /* switch */ } } /* ms_update_set_result */ /** * update the response time result * * @param c, pointer of the concurrency */ static void ms_update_stat_result(ms_conn_t *c) { bool get_miss = false; if (c == NULL) { return; } assert(c); gettimeofday(&c->end_time, NULL); uint64_t time_diff = (uint64_t) ms_time_diff(&c->start_time, &c->end_time); pthread_mutex_lock(&ms_statistic.stat_mutex); switch (c->precmd.cmd) { case CMD_SET: ms_record_event(&ms_statistic.set_stat, time_diff, false); break; case CMD_GET: if (c->curr_task.get_miss) { get_miss = true; } ms_record_event(&ms_statistic.get_stat, time_diff, get_miss); break; default: break; } /* switch */ ms_record_event(&ms_statistic.total_stat, time_diff, get_miss); pthread_mutex_unlock(&ms_statistic.stat_mutex); } /* ms_update_stat_result */ /** * after get response from server for the current operation, and * before doing the next operation, update the state of the * current operation. * * @param c, pointer of the concurrency */ static void ms_update_task_result(ms_conn_t *c) { ms_task_item_t *item; if (c == NULL) { return; } assert(c); item = ms_get_cur_opt_item(c); if (item == NULL) { return; } assert(item); ms_update_set_result(c, item); if ((ms_setting.stat_freq > 0) && ((c->precmd.cmd == CMD_SET) || (c->precmd.cmd == CMD_GET))) { ms_update_stat_result(c); } /* update multi-get task item */ if (((ms_setting.mult_key_num > 1) && (c->mlget_task.mlget_num >= ms_setting.mult_key_num)) || ((c->remain_exec_num == 0) && (c->mlget_task.mlget_num > 0))) { ms_update_multi_get_result(c); } else { ms_update_single_get_result(c, item); } } /* ms_update_task_result */ /** * run get and set operation * * @param c, pointer of the concurrency * * @return int, if success, return EXIT_SUCCESS, else return -1 */ static int ms_run_getset_task(ms_conn_t *c) { /** * extra one loop to get the last command return state. get the * last command return state. */ if ((c->remain_exec_num >= 0) && (c->remain_exec_num != c->exec_num)) { ms_update_task_result(c); } /* multi-get */ if (ms_setting.mult_key_num > 1) { /* operate next task item */ ms_multi_getset_task_sch(c); } else { /* operate next task item */ ms_single_getset_task_sch(c); } /* no task to do, exit */ if ((c->remain_exec_num == -1) || ms_global.time_out) { return -1; } return EXIT_SUCCESS; } /* ms_run_getset_task */ /** * the state machine call the function to execute task. * * @param c, pointer of the concurrency * * @return int, if success, return EXIT_SUCCESS, else return -1 */ int ms_exec_task(struct conn *c) { if (!ms_global.finish_warmup) { ms_warmup_server(c); } else { if (ms_run_getset_task(c)) { return -1; } } return EXIT_SUCCESS; } /* ms_exec_task */
731758.c
/**************************************************************************** * sched/signal/sig_suspend.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <signal.h> #include <assert.h> #include <debug.h> #include <sched.h> #include <nuttx/irq.h> #include <nuttx/arch.h> #include <nuttx/cancelpt.h> #include "sched/sched.h" #include "signal/signal.h" /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: sigsuspend * * Description: * * The sigsuspend() function replaces the signal mask of the task with the * set of signals pointed to by the argument 'set' and then suspends the * process until delivery of a signal to the task. * * If the effect of the set argument is to unblock a pending signal, then * no wait is performed. * * The original signal mask is restored when this function returns. * * Waiting for an empty signal set stops a task without freeing any * resources. * * Input Parameters: * set - signal mask to use while suspended. * * Returned Value: * -1 (ERROR) always * * Assumptions: * * POSIX Compatibility: * int sigsuspend(const sigset_t *set); * * POSIX states that sigsuspend() "suspends the process until delivery of * a signal whose action is either to execute a signal-catching function * or to terminate the process." Only the deliver of a signal is required * in the present implementation (even if the signal is ignored). * ****************************************************************************/ int sigsuspend(FAR const sigset_t *set) { FAR struct tcb_s *rtcb = this_task(); sigset_t saved_sigprocmask; irqstate_t flags; /* sigsuspend() is a cancellation point */ enter_cancellation_point(); /* Several operations must be performed below: We must determine if any * signal is pending and, if not, wait for the signal. Since signals can * be posted from the interrupt level, there is a race condition that * can only be eliminated by disabling interrupts! */ sched_lock(); /* Not necessary */ flags = enter_critical_section(); /* Save a copy of the old sigprocmask and install * the new (temporary) sigprocmask */ saved_sigprocmask = rtcb->sigprocmask; rtcb->sigprocmask = *set; rtcb->sigwaitmask = NULL_SIGNAL_SET; /* Check if there is a pending signal corresponding to one of the * signals that will be unblocked by the new sigprocmask. */ if (nxsig_unmask_pendingsignal()) { /* Dispatching one or more of the signals is sufficient to cause * us to not wait. Restore the original sigprocmask. */ rtcb->sigprocmask = saved_sigprocmask; leave_critical_section(flags); } else { /* Its time to wait until one of the unblocked signals is posted, * but first, ensure this is not the idle task, descheduling that * isn't going to end well. */ DEBUGASSERT(NULL != rtcb->flink); up_block_task(rtcb, TSTATE_WAIT_SIG); /* We are running again, restore the original sigprocmask */ rtcb->sigprocmask = saved_sigprocmask; leave_critical_section(flags); /* Now, handle the (rare?) case where (a) a blocked signal was received * while the task was suspended but (b) restoring the original * sigprocmask will unblock the signal. */ nxsig_unmask_pendingsignal(); } sched_unlock(); leave_cancellation_point(); set_errno(EINTR); return ERROR; }
110760.c
#include <stdio.h> #include <stdlib.h> #include <string.h> void print(char *str) { printf("%s", str); } void println(char *str) { printf("%s\n", str); } void printInt(int n) { printf("%d", n); } void printlnInt(int n) { printf("%d\n", n); } char* getString() { char* s = (char *) malloc(128); scanf("%s", s); return s; } int getInt() { int res; scanf("%d", &res); return res; } char* toString(int n) { // int len = 0; // len += n == 0 ? 1 : 0; // int t = n; // while (t != 0) { // t /= 10; // len++; // } // // len += n < 0 ? 1 : 0; // // char *s = (char *) malloc(len + 1); // s[len] = '\0'; // // int beg = 0; // if (n < 0) { // n = -n; // s[beg++] = '-'; // } // // int i; // for (i = len - 1; i >= beg; i--) { // s[i] = n % 10 + '0'; // n /= 10; // } // return s; char *ret = (char *) malloc(12); sprintf(ret, "%d", n); return ret; } int string__length(char *this) { return strlen(this); } char* string__substring(char *this, int left, int right) { char *substring = (char *) malloc(right - left + 1); // for (int i = left; i < right; ++i) { // substring[i - left] = this[i]; // } // substring[right - left] = '\0'; memcpy(substring, this + left, right - left); return substring; } int string__parseInt(char *this) { // int sgn = 1, i = 0, res = 0; // if (this[0] == '-') { // sgn = -1; // i = 1; // } // for (; this[i] >= '0' && this[i] <= '9'; ++i) { // res = res * 10 + this[i] - '0'; // } // return sgn * res; int ret; sscanf(this, "%d", &ret); return ret; } int string__ord(char *this, int pos) { return this[pos]; } char* _string_concatenate(char *s1, char *s2) { int l1 = strlen(s1); int l2 = strlen(s2); char *res = (char*) malloc(l1 + l2 + 1); // for (int i = 0; i < l1; i++) { // res[i] = s1[i]; // } // for (int i = 0; i < l2; i++) { // res[l1 + i] = s2[i]; // } memcpy(res, s1, l1); strcat(res, s2); // res[l1 + l2] = '\0'; return res; } char _string_eq(char *a, char *b) { return strcmp(a, b) == 0; } char _string_ne(char *a, char *b) { return strcmp(a, b) != 0; } char _string_slt(char *a, char *b) { return strcmp(a, b) < 0; } char _string_sle(char *a, char *b) { return strcmp(a, b) <= 0; } char _string_sgt(char *a, char *b) { return strcmp(a, b) > 0; } char _string_sge(char *a, char *b) { return strcmp(a, b) >= 0; }
137026.c
// NOTE: try running me with the option -chora-no-linspec int cost = 0; int lg_n_helper(int n) { int r = 0; for(int i = 1; i < n; i *= 2) { r ++; } return r; } void recursive(int n) { //__VERIFIER_assume(n >= 0); if (n == 2 || n == 3) { cost += 4; return; } int m = n/2; recursive(m); cost += 1; return; } void main(int n) { recursive(n); int height = lg_n_helper(n); __VERIFIER_assert(cost < 4 + height); }
198864.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <sys/time.h> #include <pthread.h> double ** arr_a; double ** arr_b; double ** arr_c; int row_a, col_a, row_b, col_b; char * out_file_name_1; char * out_file_name_2; char * out_file_name_3; struct index { int i; /* row */ int j; /* column */ }; double** read_file(char* path,int *r, int *c); void print_file_array(double** arr,char * path);; void first_method(); void *calculate_cell (void * param); void secod_method(); void * calculate_row(void * param); void third_method(); int main(int argc, char *argv[]) { if (argc > 1){ arr_a = read_file(argv[1],&row_a,&col_a); arr_b = read_file(argv[2],&row_b,&col_b); out_file_name_1 = malloc((strlen(argv[3]) + 7) * sizeof(char)); out_file_name_2 = malloc((strlen(argv[3]) + 7) * sizeof(char)); out_file_name_3 = malloc((strlen(argv[3]) + 7) * sizeof(char)); strcpy(out_file_name_1,argv[3]); strcpy(out_file_name_2,argv[3]); strcpy(out_file_name_3,argv[3]); } else { arr_a = read_file("a_10000.txt",&row_a,&col_a); arr_b = read_file("a_10000.txt",&row_b,&col_b); out_file_name_1 = malloc(10 * sizeof(char)); out_file_name_2 = malloc(10 * sizeof(char)); out_file_name_3 = malloc(10 * sizeof(char)); strcpy(out_file_name_1,"out"); strcpy(out_file_name_2,"out"); strcpy(out_file_name_3,"out"); } if (col_a != row_b){ printf("the number of rows in the first array is not equal the number of columns in the second array!"); return 0; } strcat(out_file_name_1,"_1.txt"); strcat(out_file_name_2,"_2.txt"); strcat(out_file_name_3,"_3.txt"); struct timeval stop,start; int i; arr_c = malloc(row_a * sizeof (double)); for (i = 0; i < row_a; i++){ arr_c[i] = malloc(col_b * sizeof(double)); } // first method gettimeofday(&start, NULL); //start checking time first_method(); gettimeofday(&stop, NULL); //end checking time printf("First method (%d threads): taken %lu Microseconds.\n", row_a * col_b, stop.tv_usec - start.tv_usec); printf("hhhhhhhhhhhhhhhhh\n"); // second method gettimeofday(&start, NULL); //start checking time secod_method(); gettimeofday(&stop, NULL); //end checking time printf("Second method (%d threads): taken %lu Microseconds.\n",row_a, stop.tv_usec - start.tv_usec); // third method gettimeofday(&start, NULL); //start checking time third_method(); gettimeofday(&stop, NULL); //end checking time printf("First method (%d threads): taken %lu Microseconds.\n", 1, stop.tv_usec - start.tv_usec); // main terminate pthread_exit(NULL); return 0; } // read input array from the file double** read_file(char* path,int *r, int *c) { int row, column; int i,j; FILE* input = fopen(path, "r"); if (input == NULL){ printf("the file [%s] is not found!\n",path); return NULL; } fscanf(input,"row=%d col=%d",&row,&column); *r = row; *c = column; double **arr = malloc(row * sizeof(double)); for (i = 0; i < row; i++) arr[i] = malloc(column * sizeof(double)); for (i = 0; i < row; i++) { for (j = 0; j < column; j++){ fscanf(input,"%lf",&arr[i][j]); } } fclose(input); return arr; } //write output array in the file void print_file_array(double** arr,char * path) { int i,j; FILE* output = fopen(path, "a"); for (i = 0; i < row_a; i++){ for (j = 0; j < col_b; j++){ fprintf(output, "%lf\t",arr[i][j]); } fprintf(output, "\n"); } fclose(output); } // frist method using #elements (#rows * # cols) threads void first_method() { int i,j; int thread_cnt = row_a * col_b; int cnt =0; pthread_t threads[thread_cnt]; /* declare an array of type pthread_t*/ for (i = 0; i < row_a; i++){ for (j = 0; j < col_b; j++){ struct index *data = (struct index *) malloc(sizeof(struct index)); data->i = i; data->j = j; // create pthreads pthread_create(&threads[i + j], NULL, calculate_cell, (void *)data); //ake sure the parent waits for all thread to complete pthread_join(threads[i + j], NULL); } } print_file_array(arr_c,out_file_name_1); } void *calculate_cell (void * param) { struct index *data = (struct index *)param; int x, sum = 0; for (x = 0; x < col_a; x++){ sum += arr_a[data->i][x] * arr_b[x][data->j]; } arr_c[data->i][data->j] = sum; } // second method using # rows threads void secod_method() { int i; pthread_t threads[row_a]; // creat row_a threads for (i = 0; i < row_a; i++){ pthread_create(&threads[i], NULL, calculate_row,(void *)i); } // join pthreads for (i = 0; i < row_a; i++){ pthread_join(threads[i], NULL); } print_file_array(arr_c,out_file_name_2); } void * calculate_row(void * param) { int i = (int *) param; int j ,k ,sum = 0; for (j = 0; j < col_b ;j ++){ for (k = 0; k < col_a; k++){ sum += arr_a[i][k] * arr_b[k][j]; } arr_c[i][j] = sum; sum = 0; } } // third method is the simple way void third_method() { int i; struct index *data = (struct index *) malloc(sizeof(struct index)); for (int i = 0; i < row_a; i++){ for (int j = 0; j < col_b; j++){ data->i = i; data->j = j; calculate_cell(data); } } print_file_array(arr_c,out_file_name_3); }
942945.c
/* $OpenBSD: radix_mpath.c,v 1.18 2010/05/07 13:33:16 claudio Exp $ */ /* $KAME: radix_mpath.c,v 1.13 2002/10/28 21:05:59 itojun Exp $ */ /* * Copyright (C) 2001 WIDE Project. * 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. Neither the name of the project 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 PROJECT 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 PROJECT 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. * THE AUTHORS DO NOT GUARANTEE THAT THIS SOFTWARE DOES NOT INFRINGE * ANY OTHERS' INTELLECTUAL PROPERTIES. IN NO EVENT SHALL THE AUTHORS * BE LIABLE FOR ANY INFRINGEMENT OF ANY OTHERS' INTELLECTUAL * PROPERTIES. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/malloc.h> #include <sys/socket.h> #define M_DONTWAIT M_NOWAIT #include <sys/domain.h> #include <sys/syslog.h> #include <net/radix.h> #include <net/radix_mpath.h> #include <net/route.h> #include <dev/rndvar.h> #include <netinet/in.h> extern int ipmultipath; extern int ip6_multipath; u_int32_t rn_mpath_hash(struct route *, u_int32_t *); /* * give some jitter to hash, to avoid synchronization between routers */ static u_int32_t hashjitter; #ifdef RN_DEBUG extern struct radix_node *rn_clist; #endif int rn_mpath_capable(struct radix_node_head *rnh) { return rnh->rnh_multipath; } struct radix_node * rn_mpath_next(struct radix_node *rn, int all) { struct radix_node *next; struct rtentry *rt = (struct rtentry *)rn; if (!rn->rn_dupedkey) return NULL; next = rn->rn_dupedkey; if (rn->rn_mask == next->rn_mask && (all || rt->rt_priority == ((struct rtentry *)next)->rt_priority)) return next; else return NULL; } struct radix_node * rn_mpath_prio(struct radix_node *rn, u_int8_t prio) { struct radix_node *prev = rn; struct rtentry *rt; if (prio == RTP_ANY) return (rn); while (rn) { /* different netmask -> different route */ if (rn->rn_mask != prev->rn_mask) return (prev); rt = (struct rtentry *)rn; if (rt->rt_priority == prio) return (rn); if (rt->rt_priority > prio) /* list is sorted return last more prefered entry */ return (prev); prev = rn; rn = rn->rn_dupedkey; } return (prev); } void rn_mpath_reprio(struct radix_node *rn, int newprio) { struct radix_node *prev = rn->rn_p; struct radix_node *next = rn->rn_dupedkey; struct radix_node *t, *tt, *saved_tt, *head; struct rtentry *rt = (struct rtentry *)rn; int mid, oldprio, prioinv = 0; oldprio = rt->rt_priority; rt->rt_priority = newprio; /* same prio, no change needed */ if (oldprio == newprio) return; if (rn_mpath_next(rn, 1) == NULL) { /* no need to move node, route is alone */ if (prev->rn_mask != rn->rn_mask) return; /* ... or route is last and prio gets bigger */ if (oldprio < newprio) return; } /* remove node from dupedkey list and reinsert at correct place */ if (prev->rn_dupedkey == rn) { prev->rn_dupedkey = next; if (next) next->rn_p = prev; else next = prev; } else { if (next == NULL) panic("next == NULL"); next->rn_p = prev; if (prev->rn_l == rn) prev->rn_l = next; else prev->rn_r = next; } /* re-insert rn at the right spot, so first rewind to the head */ for (tt = next; tt->rn_p->rn_dupedkey == tt; tt = tt->rn_p) ; saved_tt = tt; /* * Stolen from radix.c rn_addroute(). * This is nasty code with a certain amount of magic and dragons. * t is the element where the re-priorized rn is inserted -- before * or after depending on prioinv. saved_tt points to the head of the * dupedkey chain and tt is a bit of a helper * * First we skip with tt to the start of the mpath group then we * search the right spot to enter our node. */ for (; tt; tt = tt->rn_dupedkey) if (rn->rn_mask == tt->rn_mask) break; head = tt; /* store current head entry for rn_mklist check */ tt = rn_mpath_prio(tt, newprio); if (((struct rtentry *)tt)->rt_priority != newprio) { if (((struct rtentry *)tt)->rt_priority > newprio) prioinv = 1; t = tt; } else { mid = rn_mpath_count(tt) / 2; do { t = tt; tt = rn_mpath_next(tt, 0); } while (tt && --mid > 0); } /* insert rn before or after t depending on prioinv, tt and saved_tt */ if (tt == saved_tt && prioinv) { /* link in at head of list */ rn->rn_dupedkey = tt; rn->rn_p = tt->rn_p; tt->rn_p = rn; if (rn->rn_p->rn_l == tt) rn->rn_p->rn_l = rn; else rn->rn_p->rn_r = rn; } else if (prioinv == 1) { rn->rn_dupedkey = t; t->rn_p->rn_dupedkey = rn; rn->rn_p = t->rn_p; t->rn_p = rn; } else { rn->rn_dupedkey = t->rn_dupedkey; t->rn_dupedkey = rn; rn->rn_p = t; if (rn->rn_dupedkey) rn->rn_dupedkey->rn_p = rn; } #ifdef RN_DEBUG /* readd at head of creation list */ for (t = rn_clist; t && t->rn_ybro != rn; t = t->rn_ybro) ; if (t) t->rn_ybro = rn->rn_ybro; rn->rn_ybro = rn_clist; rn_clist = rn; #endif if (rn->rn_mklist && rn->rn_flags & RNF_NORMAL) { /* the rn_mklist needs to be fixed if the best route changed */ if (rn->rn_mklist->rm_leaf != rn) { if (rn->rn_mklist->rm_leaf->rn_p == rn) /* changed route is now best */ rn->rn_mklist->rm_leaf = rn; } else { if (rn->rn_dupedkey != head) /* rn moved behind head, so head is new head */ rn->rn_mklist->rm_leaf = head; } } } int rn_mpath_count(struct radix_node *rn) { int i; i = 1; while ((rn = rn_mpath_next(rn, 0)) != NULL) i++; return i; } struct rtentry * rt_mpath_matchgate(struct rtentry *rt, struct sockaddr *gate, u_int8_t prio) { struct radix_node *rn = (struct radix_node *)rt; do { rt = (struct rtentry *)rn; /* first find routes with correct priority */ if (prio != RTP_ANY && (rt->rt_priority & RTP_MASK) != (prio & RTP_MASK)) continue; /* * if gate is set it must be compared, if not set the route * must be a non-multipath one. */ if (!gate && !rn_mpath_next(rn, 0)) return rt; if (!gate) return NULL; if (!rt->rt_gateway) continue; if (rt->rt_gateway->sa_len == gate->sa_len && !memcmp(rt->rt_gateway, gate, gate->sa_len)) break; } while ((rn = rn_mpath_next(rn, 1)) != NULL); return (struct rtentry *)rn; } /* * check if we have the same key/mask/gateway on the table already. */ int rt_mpath_conflict(struct radix_node_head *rnh, struct rtentry *rt, struct sockaddr *netmask, int mpathok) { struct radix_node *rn, *rn1; struct rtentry *rt1; char *p, *q, *eq; int same, l, skip; rn = (struct radix_node *)rt; rn1 = rnh->rnh_lookup(rt_key(rt), netmask, rnh); if (!rn1 || rn1->rn_flags & RNF_ROOT) return 0; /* * unlike other functions we have in this file, we have to check * all key/mask/gateway as rnh_lookup can match less specific entry. */ rt1 = (struct rtentry *)rn1; /* compare key. */ if (rt_key(rt1)->sa_len != rt_key(rt)->sa_len || bcmp(rt_key(rt1), rt_key(rt), rt_key(rt1)->sa_len)) goto different; /* key was the same. compare netmask. hairy... */ if (rt_mask(rt1) && netmask) { skip = rnh->rnh_treetop->rn_off; if (rt_mask(rt1)->sa_len > netmask->sa_len) { /* * as rt_mask(rt1) is made optimal by radix.c, * there must be some 1-bits on rt_mask(rt1) * after netmask->sa_len. therefore, in * this case, the entries are different. */ if (rt_mask(rt1)->sa_len > skip) goto different; else { /* no bits to compare, i.e. same*/ goto maskmatched; } } l = rt_mask(rt1)->sa_len; if (skip > l) { /* no bits to compare, i.e. same */ goto maskmatched; } p = (char *)rt_mask(rt1); q = (char *)netmask; if (bcmp(p + skip, q + skip, l - skip)) goto different; /* * need to go through all the bit, as netmask is not * optimal and can contain trailing 0s */ eq = (char *)netmask + netmask->sa_len; q += l; same = 1; while (eq > q) if (*q++) { same = 0; break; } if (!same) goto different; } else if (!rt_mask(rt1) && !netmask) ; /* no mask to compare, i.e. same */ else { /* one has mask and the other does not, different */ goto different; } maskmatched: if (!mpathok && rt1->rt_priority == rt->rt_priority) return EEXIST; rn1 = rn_mpath_prio((struct radix_node *)rt1, rt->rt_priority); /* key/mask were the same. compare gateway for all multipaths */ do { rt1 = (struct rtentry *)rn1; /* sanity: no use in comparing the same thing */ if (rn1 == rn) continue; if (rt1->rt_gateway->sa_len != rt->rt_gateway->sa_len || bcmp(rt1->rt_gateway, rt->rt_gateway, rt1->rt_gateway->sa_len)) continue; /* check the route priority */ if (rt1->rt_priority != rt->rt_priority) continue; /* all key/mask/gateway are the same. conflicting entry. */ return EEXIST; } while ((rn1 = rn_mpath_next(rn1, 0)) != NULL); different: return 0; } /* * allocate a route, potentially using multipath to select the peer. */ void rtalloc_mpath(struct route *ro, u_int32_t *srcaddrp) { #if defined(INET) || defined(INET6) struct radix_node *rn; int hash, npaths, threshold; #endif /* * return a cached entry if it is still valid, otherwise we increase * the risk of disrupting local flows. */ if (ro->ro_rt && ro->ro_rt->rt_ifp && (ro->ro_rt->rt_flags & RTF_UP)) return; ro->ro_rt = rtalloc1(&ro->ro_dst, RT_REPORT, ro->ro_tableid); /* if the route does not exist or it is not multipath, don't care */ if (!ro->ro_rt || !(ro->ro_rt->rt_flags & RTF_MPATH)) return; /* check if multipath routing is enabled for the specified protocol */ if (!(0 #ifdef INET || (ipmultipath && ro->ro_dst.sa_family == AF_INET) #endif #ifdef INET6 || (ip6_multipath && ro->ro_dst.sa_family == AF_INET6) #endif )) return; #if defined(INET) || defined(INET6) /* gw selection by Hash-Threshold (RFC 2992) */ rn = (struct radix_node *)ro->ro_rt; npaths = rn_mpath_count(rn); hash = rn_mpath_hash(ro, srcaddrp) & 0xffff; threshold = 1 + (0xffff / npaths); while (hash > threshold && rn) { /* stay within the multipath routes */ if (rn_mpath_next(rn, 0) == NULL) break; rn = rn->rn_dupedkey; hash -= threshold; } /* XXX try filling rt_gwroute and avoid unreachable gw */ /* if gw selection fails, use the first match (default) */ if (!rn) return; rtfree(ro->ro_rt); ro->ro_rt = (struct rtentry *)rn; ro->ro_rt->rt_refcnt++; #endif } int rn_mpath_inithead(void **head, int off) { struct radix_node_head *rnh; while (hashjitter == 0) hashjitter = arc4random(); if (rn_inithead(head, off) == 1) { rnh = (struct radix_node_head *)*head; rnh->rnh_multipath = 1; return 1; } else return 0; } /* * hash function based on pf_hash in pf.c */ #define mix(a,b,c) \ do { \ a -= b; a -= c; a ^= (c >> 13); \ b -= c; b -= a; b ^= (a << 8); \ c -= a; c -= b; c ^= (b >> 13); \ a -= b; a -= c; a ^= (c >> 12); \ b -= c; b -= a; b ^= (a << 16); \ c -= a; c -= b; c ^= (b >> 5); \ a -= b; a -= c; a ^= (c >> 3); \ b -= c; b -= a; b ^= (a << 10); \ c -= a; c -= b; c ^= (b >> 15); \ } while (0) u_int32_t rn_mpath_hash(struct route *ro, u_int32_t *srcaddrp) { u_int32_t a, b, c; a = b = 0x9e3779b9; c = hashjitter; switch (ro->ro_dst.sa_family) { #ifdef INET case AF_INET: { struct sockaddr_in *sin_dst; sin_dst = (struct sockaddr_in *)&ro->ro_dst; a += sin_dst->sin_addr.s_addr; b += srcaddrp ? srcaddrp[0] : 0; mix(a, b, c); break; } #endif /* INET */ #ifdef INET6 case AF_INET6: { struct sockaddr_in6 *sin6_dst; sin6_dst = (struct sockaddr_in6 *)&ro->ro_dst; a += sin6_dst->sin6_addr.s6_addr32[0]; b += sin6_dst->sin6_addr.s6_addr32[2]; c += srcaddrp ? srcaddrp[0] : 0; mix(a, b, c); a += sin6_dst->sin6_addr.s6_addr32[1]; b += sin6_dst->sin6_addr.s6_addr32[3]; c += srcaddrp ? srcaddrp[1] : 0; mix(a, b, c); a += sin6_dst->sin6_addr.s6_addr32[2]; b += sin6_dst->sin6_addr.s6_addr32[1]; c += srcaddrp ? srcaddrp[2] : 0; mix(a, b, c); a += sin6_dst->sin6_addr.s6_addr32[3]; b += sin6_dst->sin6_addr.s6_addr32[0]; c += srcaddrp ? srcaddrp[3] : 0; mix(a, b, c); break; } #endif /* INET6 */ } return c; }
377274.c
/* * NEC NL8048HL11 Panel driver * * Copyright (C) 2010 Texas Instruments Inc. * Author: Erik Gilling <[email protected]> * Converted to new DSS device model: Tomi Valkeinen <[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/delay.h> #include <linux/spi/spi.h> #include <linux/fb.h> #include <linux/gpio.h> #include <video/omapdss.h> #include <video/omap-panel-data.h> struct panel_drv_data { struct omap_dss_device dssdev; struct omap_dss_device *in; struct omap_video_timings videomode; int data_lines; int res_gpio; int qvga_gpio; struct spi_device *spi; }; #define LCD_XRES 800 #define LCD_YRES 480 /* * NEC PIX Clock Ratings * MIN:21.8MHz TYP:23.8MHz MAX:25.7MHz */ #define LCD_PIXEL_CLOCK 23800 static const struct { unsigned char addr; unsigned char dat; } nec_8048_init_seq[] = { { 3, 0x01 }, { 0, 0x00 }, { 1, 0x01 }, { 4, 0x00 }, { 5, 0x14 }, { 6, 0x24 }, { 16, 0xD7 }, { 17, 0x00 }, { 18, 0x00 }, { 19, 0x55 }, { 20, 0x01 }, { 21, 0x70 }, { 22, 0x1E }, { 23, 0x25 }, { 24, 0x25 }, { 25, 0x02 }, { 26, 0x02 }, { 27, 0xA0 }, { 32, 0x2F }, { 33, 0x0F }, { 34, 0x0F }, { 35, 0x0F }, { 36, 0x0F }, { 37, 0x0F }, { 38, 0x0F }, { 39, 0x00 }, { 40, 0x02 }, { 41, 0x02 }, { 42, 0x02 }, { 43, 0x0F }, { 44, 0x0F }, { 45, 0x0F }, { 46, 0x0F }, { 47, 0x0F }, { 48, 0x0F }, { 49, 0x0F }, { 50, 0x00 }, { 51, 0x02 }, { 52, 0x02 }, { 53, 0x02 }, { 80, 0x0C }, { 83, 0x42 }, { 84, 0x42 }, { 85, 0x41 }, { 86, 0x14 }, { 89, 0x88 }, { 90, 0x01 }, { 91, 0x00 }, { 92, 0x02 }, { 93, 0x0C }, { 94, 0x1C }, { 95, 0x27 }, { 98, 0x49 }, { 99, 0x27 }, { 102, 0x76 }, { 103, 0x27 }, { 112, 0x01 }, { 113, 0x0E }, { 114, 0x02 }, { 115, 0x0C }, { 118, 0x0C }, { 121, 0x30 }, { 130, 0x00 }, { 131, 0x00 }, { 132, 0xFC }, { 134, 0x00 }, { 136, 0x00 }, { 138, 0x00 }, { 139, 0x00 }, { 140, 0x00 }, { 141, 0xFC }, { 143, 0x00 }, { 145, 0x00 }, { 147, 0x00 }, { 148, 0x00 }, { 149, 0x00 }, { 150, 0xFC }, { 152, 0x00 }, { 154, 0x00 }, { 156, 0x00 }, { 157, 0x00 }, { 2, 0x00 }, }; static const struct omap_video_timings nec_8048_panel_timings = { .x_res = LCD_XRES, .y_res = LCD_YRES, .pixel_clock = LCD_PIXEL_CLOCK, .hfp = 6, .hsw = 1, .hbp = 4, .vfp = 3, .vsw = 1, .vbp = 4, .vsync_level = OMAPDSS_SIG_ACTIVE_LOW, .hsync_level = OMAPDSS_SIG_ACTIVE_LOW, .data_pclk_edge = OMAPDSS_DRIVE_SIG_RISING_EDGE, .de_level = OMAPDSS_SIG_ACTIVE_HIGH, .sync_pclk_edge = OMAPDSS_DRIVE_SIG_RISING_EDGE, }; #define to_panel_data(p) container_of(p, struct panel_drv_data, dssdev) static int nec_8048_spi_send(struct spi_device *spi, unsigned char reg_addr, unsigned char reg_data) { int ret = 0; unsigned int cmd = 0, data = 0; cmd = 0x0000 | reg_addr; /* register address write */ data = 0x0100 | reg_data; /* register data write */ data = (cmd << 16) | data; ret = spi_write(spi, (unsigned char *)&data, 4); if (ret) pr_err("error in spi_write %x\n", data); return ret; } static int init_nec_8048_wvga_lcd(struct spi_device *spi) { unsigned int i; /* Initialization Sequence */ /* nec_8048_spi_send(spi, REG, VAL) */ for (i = 0; i < (ARRAY_SIZE(nec_8048_init_seq) - 1); i++) nec_8048_spi_send(spi, nec_8048_init_seq[i].addr, nec_8048_init_seq[i].dat); udelay(20); nec_8048_spi_send(spi, nec_8048_init_seq[i].addr, nec_8048_init_seq[i].dat); return 0; } static int nec_8048_connect(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; if (omapdss_device_is_connected(dssdev)) return 0; r = in->ops.dpi->connect(in, dssdev); if (r) return r; return 0; } static void nec_8048_disconnect(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; if (!omapdss_device_is_connected(dssdev)) return; in->ops.dpi->disconnect(in, dssdev); } static int nec_8048_enable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; int r; if (!omapdss_device_is_connected(dssdev)) return -ENODEV; if (omapdss_device_is_enabled(dssdev)) return 0; in->ops.dpi->set_data_lines(in, ddata->data_lines); in->ops.dpi->set_timings(in, &ddata->videomode); r = in->ops.dpi->enable(in); if (r) return r; if (gpio_is_valid(ddata->res_gpio)) gpio_set_value_cansleep(ddata->res_gpio, 1); dssdev->state = OMAP_DSS_DISPLAY_ACTIVE; return 0; } static void nec_8048_disable(struct omap_dss_device *dssdev) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; if (!omapdss_device_is_enabled(dssdev)) return; if (gpio_is_valid(ddata->res_gpio)) gpio_set_value_cansleep(ddata->res_gpio, 0); in->ops.dpi->disable(in); dssdev->state = OMAP_DSS_DISPLAY_DISABLED; } static void nec_8048_set_timings(struct omap_dss_device *dssdev, struct omap_video_timings *timings) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; ddata->videomode = *timings; dssdev->panel.timings = *timings; in->ops.dpi->set_timings(in, timings); } static void nec_8048_get_timings(struct omap_dss_device *dssdev, struct omap_video_timings *timings) { struct panel_drv_data *ddata = to_panel_data(dssdev); *timings = ddata->videomode; } static int nec_8048_check_timings(struct omap_dss_device *dssdev, struct omap_video_timings *timings) { struct panel_drv_data *ddata = to_panel_data(dssdev); struct omap_dss_device *in = ddata->in; return in->ops.dpi->check_timings(in, timings); } static struct omap_dss_driver nec_8048_ops = { .connect = nec_8048_connect, .disconnect = nec_8048_disconnect, .enable = nec_8048_enable, .disable = nec_8048_disable, .set_timings = nec_8048_set_timings, .get_timings = nec_8048_get_timings, .check_timings = nec_8048_check_timings, .get_resolution = omapdss_default_get_resolution, }; static int nec_8048_probe_pdata(struct spi_device *spi) { const struct panel_nec_nl8048hl11_platform_data *pdata; struct panel_drv_data *ddata = dev_get_drvdata(&spi->dev); struct omap_dss_device *dssdev, *in; pdata = dev_get_platdata(&spi->dev); ddata->qvga_gpio = pdata->qvga_gpio; ddata->res_gpio = pdata->res_gpio; in = omap_dss_find_output(pdata->source); if (in == NULL) { dev_err(&spi->dev, "failed to find video source '%s'\n", pdata->source); return -EPROBE_DEFER; } ddata->in = in; ddata->data_lines = pdata->data_lines; dssdev = &ddata->dssdev; dssdev->name = pdata->name; return 0; } static int nec_8048_probe(struct spi_device *spi) { struct panel_drv_data *ddata; struct omap_dss_device *dssdev; int r; dev_dbg(&spi->dev, "%s\n", __func__); spi->mode = SPI_MODE_0; spi->bits_per_word = 32; r = spi_setup(spi); if (r < 0) { dev_err(&spi->dev, "spi_setup failed: %d\n", r); return r; } init_nec_8048_wvga_lcd(spi); ddata = devm_kzalloc(&spi->dev, sizeof(*ddata), GFP_KERNEL); if (ddata == NULL) return -ENOMEM; dev_set_drvdata(&spi->dev, ddata); ddata->spi = spi; if (dev_get_platdata(&spi->dev)) { r = nec_8048_probe_pdata(spi); if (r) return r; } else { return -ENODEV; } if (gpio_is_valid(ddata->qvga_gpio)) { r = devm_gpio_request_one(&spi->dev, ddata->qvga_gpio, GPIOF_OUT_INIT_HIGH, "lcd QVGA"); if (r) goto err_gpio; } if (gpio_is_valid(ddata->res_gpio)) { r = devm_gpio_request_one(&spi->dev, ddata->res_gpio, GPIOF_OUT_INIT_LOW, "lcd RES"); if (r) goto err_gpio; } ddata->videomode = nec_8048_panel_timings; dssdev = &ddata->dssdev; dssdev->dev = &spi->dev; dssdev->driver = &nec_8048_ops; dssdev->type = OMAP_DISPLAY_TYPE_DPI; dssdev->owner = THIS_MODULE; dssdev->panel.timings = ddata->videomode; r = omapdss_register_display(dssdev); if (r) { dev_err(&spi->dev, "Failed to register panel\n"); goto err_reg; } return 0; err_reg: err_gpio: omap_dss_put_device(ddata->in); return r; } static int nec_8048_remove(struct spi_device *spi) { struct panel_drv_data *ddata = dev_get_drvdata(&spi->dev); struct omap_dss_device *dssdev = &ddata->dssdev; struct omap_dss_device *in = ddata->in; dev_dbg(&ddata->spi->dev, "%s\n", __func__); omapdss_unregister_display(dssdev); nec_8048_disable(dssdev); nec_8048_disconnect(dssdev); omap_dss_put_device(in); return 0; } #ifdef CONFIG_PM_SLEEP static int nec_8048_suspend(struct device *dev) { struct spi_device *spi = to_spi_device(dev); nec_8048_spi_send(spi, 2, 0x01); mdelay(40); return 0; } static int nec_8048_resume(struct device *dev) { struct spi_device *spi = to_spi_device(dev); /* reinitialize the panel */ spi_setup(spi); nec_8048_spi_send(spi, 2, 0x00); init_nec_8048_wvga_lcd(spi); return 0; } static SIMPLE_DEV_PM_OPS(nec_8048_pm_ops, nec_8048_suspend, nec_8048_resume); #define NEC_8048_PM_OPS (&nec_8048_pm_ops) #else #define NEC_8048_PM_OPS NULL #endif static struct spi_driver nec_8048_driver = { .driver = { .name = "panel-nec-nl8048hl11", .owner = THIS_MODULE, .pm = NEC_8048_PM_OPS, }, .probe = nec_8048_probe, .remove = nec_8048_remove, }; module_spi_driver(nec_8048_driver); MODULE_AUTHOR("Erik Gilling <[email protected]>"); MODULE_DESCRIPTION("NEC-NL8048HL11 Driver"); MODULE_LICENSE("GPL");
350532.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* replace.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lfilloux <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/01/20 19:04:49 by rblondia #+# #+# */ /* Updated: 2022/03/17 14:13:25 by lfilloux ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../../includes/minishell.h" static int ft_strstr(char *str, char *to_find) { int i; int j; i = -1; while (str[++i]) { j = 0; while (to_find[j] == str[i + j]) { if (to_find[j + 1] == '\0') return (i); j++; } } return (ft_strlen(str)); } char *replace_first(char *str, char *find, char *replace) { int start; char *after; char *tmp; start = ft_strstr(str, find); if (start >= (int) ft_strlen(str)) return (str); tmp = ft_strjoin_properly(ft_substr(str, 0, start), ft_strdup(replace)); if (start + ft_strlen(find) == ft_strlen(str)) return (tmp); after = ft_substr(str, start + ft_strlen(find), ft_strlen(str)); return (ft_strjoin_properly(tmp, after)); } char *replace_str(char *str, char *find, char *replace) { char *tmp; tmp = ft_strdup(str); while (ft_strstr(tmp, find) < (int) ft_strlen(tmp)) reset_str(&tmp, replace_first(tmp, find, replace)); return (tmp); }
185975.c
#include <pthread.h> #include <stdio.h> pthread_t incrementingThread; pthread_t decrementingThread; int i = 0; // Note the return type: void* void* incrementingThreadFunction(){ // TODO: increment i 1_000_000 times for ( int x = 1; x <= 1000000 ; x++ ) { i++; } } void* decrementingThreadFunction(){ // TODO: decrement testi 1_000_000 for ( int x = 1; x <= 1000000 ; x++ ) { i--; } } int main(){ // TODO: declare incrementingThread and decrementingThread (hint: google pthread_create) pthread_create(&incrementingThread, NULL, incrementingThreadFunction, NULL); pthread_create(&decrementingThread, NULL, decrementingThreadFunction, NULL); pthread_join(incrementingThread, NULL); pthread_join(decrementingThread, NULL); printf("The magic number is: %d\n", i); return 0; }
442328.c
/* * Server-side console management * * Copyright (C) 1998 Alexandre Julliard * 2001 Eric Pouech * Copyright 2020 Jacek 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 <assert.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <signal.h> #include <sys/ioctl.h> #include <termios.h> #include "ntstatus.h" #define WIN32_NO_STATUS #include "handle.h" #include "process.h" #include "request.h" #include "file.h" #include "unicode.h" #include "wincon.h" #include "winternl.h" #include "wine/condrv.h" struct screen_buffer; struct history_line { data_size_t len; WCHAR text[1]; }; struct console { struct object obj; /* object header */ int signaled; /* is console signaled */ struct thread *renderer; /* console renderer thread */ struct screen_buffer *active; /* active screen buffer */ struct console_server *server; /* console server object */ unsigned int last_id; /* id of last created console buffer */ struct fd *fd; /* for bare console, attached input fd */ struct async_queue ioctl_q; /* ioctl queue */ struct async_queue read_q; /* read queue */ }; static void console_dump( struct object *obj, int verbose ); static void console_destroy( struct object *obj ); static int console_signaled( struct object *obj, struct wait_queue_entry *entry ); static struct fd *console_get_fd( struct object *obj ); static struct object *console_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ); static struct object *console_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static int console_add_queue( struct object *obj, struct wait_queue_entry *entry ); static const struct object_ops console_ops = { sizeof(struct console), /* size */ &file_type, /* type */ console_dump, /* dump */ console_add_queue, /* add_queue */ remove_queue, /* remove_queue */ console_signaled, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ console_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ console_lookup_name, /* lookup_name */ no_link_name, /* link_name */ NULL, /* unlink_name */ console_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ console_destroy /* destroy */ }; static enum server_fd_type console_get_fd_type( struct fd *fd ); static void console_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class ); static void console_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class ); static void console_read( struct fd *fd, struct async *async, file_pos_t pos ); static void console_flush( struct fd *fd, struct async *async ); static void console_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops console_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ console_read, /* read */ no_fd_write, /* write */ console_flush, /* flush */ console_get_file_info, /* get_file_info */ console_get_volume_info, /* get_volume_info */ console_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; struct console_host_ioctl { unsigned int code; /* ioctl code */ int output; /* output id for screen buffer ioctls */ struct async *async; /* ioctl async */ struct list entry; /* list entry */ }; struct console_server { struct object obj; /* object header */ struct fd *fd; /* pseudo-fd for ioctls */ struct console *console; /* attached console */ struct list queue; /* ioctl queue */ struct list read_queue; /* blocking read queue */ unsigned int busy : 1; /* flag if server processing an ioctl */ unsigned int once_input : 1; /* flag if input thread has already been requested */ int term_fd; /* UNIX terminal fd */ struct termios termios; /* original termios */ }; static void console_server_dump( struct object *obj, int verbose ); static void console_server_destroy( struct object *obj ); static int console_server_signaled( struct object *obj, struct wait_queue_entry *entry ); static struct fd *console_server_get_fd( struct object *obj ); static struct object *console_server_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ); static struct object *console_server_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static const struct object_ops console_server_ops = { sizeof(struct console_server), /* size */ &file_type, /* type */ console_server_dump, /* dump */ add_queue, /* add_queue */ remove_queue, /* remove_queue */ console_server_signaled, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ console_server_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ console_server_lookup_name, /* lookup_name */ no_link_name, /* link_name */ NULL, /* unlink_name */ console_server_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ console_server_destroy /* destroy */ }; static void console_server_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops console_server_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ no_fd_read, /* read */ no_fd_write, /* write */ no_fd_flush, /* flush */ no_fd_get_file_info, /* get_file_info */ no_fd_get_volume_info, /* get_volume_info */ console_server_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; struct font_info { short int width; short int height; short int weight; short int pitch_family; WCHAR *face_name; data_size_t face_len; }; struct screen_buffer { struct object obj; /* object header */ struct list entry; /* entry in list of all screen buffers */ struct console *input; /* associated console input */ unsigned int id; /* buffer id */ struct fd *fd; /* for bare console, attached output fd */ struct async_queue ioctl_q; /* ioctl queue */ }; static void screen_buffer_dump( struct object *obj, int verbose ); static void screen_buffer_destroy( struct object *obj ); static int screen_buffer_add_queue( struct object *obj, struct wait_queue_entry *entry ); static struct fd *screen_buffer_get_fd( struct object *obj ); static struct object *screen_buffer_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static const struct object_ops screen_buffer_ops = { sizeof(struct screen_buffer), /* size */ &file_type, /* type */ screen_buffer_dump, /* dump */ screen_buffer_add_queue, /* add_queue */ NULL, /* remove_queue */ NULL, /* signaled */ NULL, /* satisfied */ no_signal, /* signal */ screen_buffer_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ no_lookup_name, /* lookup_name */ no_link_name, /* link_name */ NULL, /* unlink_name */ screen_buffer_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ screen_buffer_destroy /* destroy */ }; static void screen_buffer_write( struct fd *fd, struct async *async, file_pos_t pos ); static void screen_buffer_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops screen_buffer_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ no_fd_read, /* read */ screen_buffer_write, /* write */ no_fd_flush, /* flush */ console_get_file_info, /* get_file_info */ console_get_volume_info, /* get_volume_info */ screen_buffer_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; static void console_device_dump( struct object *obj, int verbose ); static struct object *console_device_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ); static struct object *console_device_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static const struct object_ops console_device_ops = { sizeof(struct object), /* size */ &device_type, /* type */ console_device_dump, /* dump */ no_add_queue, /* add_queue */ NULL, /* remove_queue */ NULL, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ no_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ default_get_full_name, /* get_full_name */ console_device_lookup_name, /* lookup_name */ directory_link_name, /* link_name */ default_unlink_name, /* unlink_name */ console_device_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ no_destroy /* destroy */ }; struct console_input { struct object obj; /* object header */ struct fd *fd; /* pseudo-fd */ }; static void console_input_dump( struct object *obj, int verbose ); static struct object *console_input_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static int console_input_add_queue( struct object *obj, struct wait_queue_entry *entry ); static struct fd *console_input_get_fd( struct object *obj ); static void console_input_destroy( struct object *obj ); static const struct object_ops console_input_ops = { sizeof(struct console_input), /* size */ &device_type, /* type */ console_input_dump, /* dump */ console_input_add_queue, /* add_queue */ NULL, /* remove_queue */ NULL, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ console_input_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ no_lookup_name, /* lookup_name */ directory_link_name, /* link_name */ default_unlink_name, /* unlink_name */ console_input_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ console_input_destroy /* destroy */ }; static void console_input_read( struct fd *fd, struct async *async, file_pos_t pos ); static void console_input_flush( struct fd *fd, struct async *async ); static void console_input_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops console_input_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ console_input_read, /* read */ no_fd_write, /* write */ console_input_flush, /* flush */ console_get_file_info, /* get_file_info */ console_get_volume_info, /* get_volume_info */ console_input_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; struct console_output { struct object obj; /* object header */ struct fd *fd; /* pseudo-fd */ }; static void console_output_dump( struct object *obj, int verbose ); static int console_output_add_queue( struct object *obj, struct wait_queue_entry *entry ); static struct fd *console_output_get_fd( struct object *obj ); static struct object *console_output_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static void console_output_destroy( struct object *obj ); static const struct object_ops console_output_ops = { sizeof(struct console_output), /* size */ &device_type, /* type */ console_output_dump, /* dump */ console_output_add_queue, /* add_queue */ NULL, /* remove_queue */ NULL, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ console_output_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ no_lookup_name, /* lookup_name */ directory_link_name, /* link_name */ default_unlink_name, /* unlink_name */ console_output_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ no_close_handle, /* close_handle */ console_output_destroy /* destroy */ }; static void console_output_write( struct fd *fd, struct async *async, file_pos_t pos ); static void console_output_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops console_output_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ no_fd_read, /* read */ console_output_write, /* write */ no_fd_flush, /* flush */ console_get_file_info, /* get_file_info */ console_get_volume_info, /* get_volume_info */ console_output_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; struct console_connection { struct object obj; /* object header */ struct fd *fd; /* pseudo-fd for ioctls */ }; static void console_connection_dump( struct object *obj, int verbose ); static struct fd *console_connection_get_fd( struct object *obj ); static struct object *console_connection_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ); static struct object *console_connection_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ); static int console_connection_close_handle( struct object *obj, struct process *process, obj_handle_t handle ); static void console_connection_destroy( struct object *obj ); static const struct object_ops console_connection_ops = { sizeof(struct console_connection),/* size */ &device_type, /* type */ console_connection_dump, /* dump */ no_add_queue, /* add_queue */ NULL, /* remove_queue */ NULL, /* signaled */ no_satisfied, /* satisfied */ no_signal, /* signal */ console_connection_get_fd, /* get_fd */ default_map_access, /* map_access */ default_get_sd, /* get_sd */ default_set_sd, /* set_sd */ no_get_full_name, /* get_full_name */ console_connection_lookup_name, /* lookup_name */ directory_link_name, /* link_name */ default_unlink_name, /* unlink_name */ console_connection_open_file, /* open_file */ no_kernel_obj_list, /* get_kernel_obj_list */ console_connection_close_handle, /* close_handle */ console_connection_destroy /* destroy */ }; static void console_connection_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ); static const struct fd_ops console_connection_fd_ops = { default_fd_get_poll_events, /* get_poll_events */ default_poll_event, /* poll_event */ console_get_fd_type, /* get_fd_type */ no_fd_read, /* read */ no_fd_write, /* write */ no_fd_flush, /* flush */ no_fd_get_file_info, /* get_file_info */ no_fd_get_volume_info, /* get_volume_info */ console_connection_ioctl, /* ioctl */ default_fd_cancel_async, /* cancel_async */ default_fd_queue_async, /* queue_async */ default_fd_reselect_async /* reselect_async */ }; static struct list screen_buffer_list = LIST_INIT(screen_buffer_list); static int queue_host_ioctl( struct console_server *server, unsigned int code, unsigned int output, struct async *async, struct async_queue *queue ); static int console_add_queue( struct object *obj, struct wait_queue_entry *entry ) { struct console *console = (struct console*)obj; assert( obj->ops == &console_ops ); /* before waiting, ensure conhost's input thread has been started */ if (console->server && !console->server->once_input) { console->server->once_input = 1; if (console->server->term_fd == -1) queue_host_ioctl( console->server, IOCTL_CONDRV_PEEK, 0, NULL, NULL ); } return add_queue( &console->obj, entry ); } static int console_signaled( struct object *obj, struct wait_queue_entry *entry ) { struct console *console = (struct console*)obj; return console->signaled; } static struct fd *console_get_fd( struct object *obj ) { struct console *console = (struct console *)obj; assert( obj->ops == &console_ops ); return (struct fd *)grab_object( console->fd ); } static enum server_fd_type console_get_fd_type( struct fd *fd ) { return FD_TYPE_CHAR; } static void console_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class ) { set_error( STATUS_INVALID_DEVICE_REQUEST ); } static void console_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class ) { switch (info_class) { case FileFsDeviceInformation: { static const FILE_FS_DEVICE_INFORMATION device_info = { FILE_DEVICE_CONSOLE, FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL }; if (get_reply_max_size() >= sizeof(device_info)) set_reply_data( &device_info, sizeof(device_info) ); else set_error( STATUS_BUFFER_TOO_SMALL ); break; } default: set_error( STATUS_NOT_IMPLEMENTED ); } } static struct object *create_console(void) { struct console *console; if (!(console = alloc_object( &console_ops ))) return NULL; console->renderer = NULL; console->signaled = 0; console->active = NULL; console->server = NULL; console->fd = NULL; console->last_id = 0; init_async_queue( &console->ioctl_q ); init_async_queue( &console->read_q ); console->fd = alloc_pseudo_fd( &console_fd_ops, &console->obj, FILE_SYNCHRONOUS_IO_NONALERT ); if (!console->fd) { release_object( console ); return NULL; } allow_fd_caching( console->fd ); return &console->obj; } static void console_host_ioctl_terminate( struct console_host_ioctl *call, unsigned int status ) { if (call->async) { async_terminate( call->async, status ); release_object( call->async ); } free( call ); } static int queue_host_ioctl( struct console_server *server, unsigned int code, unsigned int output, struct async *async, struct async_queue *queue ) { struct console_host_ioctl *ioctl; if (!(ioctl = mem_alloc( sizeof(*ioctl) ))) return 0; ioctl->code = code; ioctl->output = output; ioctl->async = NULL; if (async) { ioctl->async = (struct async *)grab_object( async ); queue_async( queue, async ); } list_add_tail( &server->queue, &ioctl->entry ); wake_up( &server->obj, 0 ); if (async) set_error( STATUS_PENDING ); return 1; } static void disconnect_console_server( struct console_server *server ) { while (!list_empty( &server->queue )) { struct console_host_ioctl *call = LIST_ENTRY( list_head( &server->queue ), struct console_host_ioctl, entry ); list_remove( &call->entry ); console_host_ioctl_terminate( call, STATUS_CANCELLED ); } while (!list_empty( &server->read_queue )) { struct console_host_ioctl *call = LIST_ENTRY( list_head( &server->read_queue ), struct console_host_ioctl, entry ); list_remove( &call->entry ); console_host_ioctl_terminate( call, STATUS_CANCELLED ); } if (server->term_fd != -1) { tcsetattr( server->term_fd, TCSANOW, &server->termios ); close( server->term_fd ); server->term_fd = -1; } if (server->console) { assert( server->console->server == server ); server->console->server = NULL; server->console = NULL; wake_up( &server->obj, 0 ); } } static void set_active_screen_buffer( struct console *console, struct screen_buffer *screen_buffer ) { if (console->active == screen_buffer) return; if (console->active) release_object( console->active ); console->active = (struct screen_buffer *)grab_object( screen_buffer ); if (console->server) queue_host_ioctl( console->server, IOCTL_CONDRV_ACTIVATE, screen_buffer->id, NULL, NULL ); } static struct object *create_screen_buffer( struct console *console ) { struct screen_buffer *screen_buffer; if (console->last_id == ~0) { set_error( STATUS_NO_MEMORY ); return NULL; } if (!(screen_buffer = alloc_object( &screen_buffer_ops ))) return NULL; screen_buffer->id = ++console->last_id; screen_buffer->input = console; init_async_queue( &screen_buffer->ioctl_q ); list_add_head( &screen_buffer_list, &screen_buffer->entry ); screen_buffer->fd = alloc_pseudo_fd( &screen_buffer_fd_ops, &screen_buffer->obj, FILE_SYNCHRONOUS_IO_NONALERT ); if (!screen_buffer->fd) { release_object( screen_buffer ); return NULL; } allow_fd_caching(screen_buffer->fd); if (console->server) queue_host_ioctl( console->server, IOCTL_CONDRV_INIT_OUTPUT, screen_buffer->id, NULL, NULL ); if (!console->active) set_active_screen_buffer( console, screen_buffer ); return &screen_buffer->obj; } struct thread *console_get_renderer( struct console *console ) { return console->renderer; } struct console_signal_info { struct console *console; process_id_t group; int signal; }; static int propagate_console_signal_cb(struct process *process, void *user) { struct console_signal_info* csi = (struct console_signal_info*)user; if (process->console == csi->console && (!csi->group || process->group_id == csi->group)) { /* find a suitable thread to signal */ struct thread *thread; LIST_FOR_EACH_ENTRY( thread, &process->thread_list, struct thread, proc_entry ) { if (send_thread_signal( thread, csi->signal )) break; } } return FALSE; } static void propagate_console_signal( struct console *console, int sig, process_id_t group_id ) { struct console_signal_info csi; if (!console) { set_error( STATUS_INVALID_PARAMETER ); return; } /* FIXME: should support the other events (like CTRL_BREAK) */ if (sig != CTRL_C_EVENT) { set_error( STATUS_NOT_IMPLEMENTED ); return; } csi.console = console; csi.signal = SIGINT; csi.group = group_id; enum_processes(propagate_console_signal_cb, &csi); } struct console_process_list { unsigned int size; unsigned int count; process_id_t *processes; struct console *console; }; static int console_process_list_cb(struct process *process, void *user) { struct console_process_list *cpl = user; if (process->console == cpl->console) { if (cpl->count < cpl->size) cpl->processes[cpl->count] = process->id; cpl->count++; } return 0; } /* dumb dump */ static void console_dump( struct object *obj, int verbose ) { struct console *console = (struct console *)obj; assert( obj->ops == &console_ops ); fprintf( stderr, "Console input active=%p server=%p\n", console->active, console->server ); } static void console_destroy( struct object *obj ) { struct console *console = (struct console *)obj; struct screen_buffer *curr; assert( obj->ops == &console_ops ); if (console->server) { assert( console->server->console == console ); disconnect_console_server( console->server ); } if (console->active) release_object( console->active ); console->active = NULL; LIST_FOR_EACH_ENTRY( curr, &screen_buffer_list, struct screen_buffer, entry ) { if (curr->input == console) curr->input = NULL; } free_async_queue( &console->ioctl_q ); free_async_queue( &console->read_q ); if (console->fd) release_object( console->fd ); } static struct object *create_console_connection( struct console *console ) { struct console_connection *connection; if (current->process->console) { set_error( STATUS_ACCESS_DENIED ); return NULL; } if (!(connection = alloc_object( &console_connection_ops ))) return NULL; if (!(connection->fd = alloc_pseudo_fd( &console_connection_fd_ops, &connection->obj, 0 ))) { release_object( connection ); return NULL; } if (console) current->process->console = (struct console *)grab_object( console ); return &connection->obj; } static struct object *console_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ) { struct console *console = (struct console *)obj; static const WCHAR connectionW[] = {'C','o','n','n','e','c','t','i','o','n'}; assert( obj->ops == &console_ops ); if (name->len == sizeof(connectionW) && !memcmp( name->str, connectionW, name->len )) { name->len = 0; return create_console_connection( console ); } return NULL; } static struct object *console_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static void screen_buffer_dump( struct object *obj, int verbose ) { struct screen_buffer *screen_buffer = (struct screen_buffer *)obj; assert( obj->ops == &screen_buffer_ops ); fprintf(stderr, "Console screen buffer input=%p\n", screen_buffer->input ); } static void screen_buffer_destroy( struct object *obj ) { struct screen_buffer *screen_buffer = (struct screen_buffer *)obj; assert( obj->ops == &screen_buffer_ops ); list_remove( &screen_buffer->entry ); if (screen_buffer->input && screen_buffer->input->server) queue_host_ioctl( screen_buffer->input->server, IOCTL_CONDRV_CLOSE_OUTPUT, screen_buffer->id, NULL, NULL ); if (screen_buffer->fd) release_object( screen_buffer->fd ); free_async_queue( &screen_buffer->ioctl_q ); } static struct object *screen_buffer_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static int screen_buffer_add_queue( struct object *obj, struct wait_queue_entry *entry ) { struct screen_buffer *screen_buffer = (struct screen_buffer*)obj; if (!screen_buffer->input) { set_error( STATUS_ACCESS_DENIED ); return 0; } return console_add_queue( &screen_buffer->input->obj, entry ); } static struct fd *screen_buffer_get_fd( struct object *obj ) { struct screen_buffer *screen_buffer = (struct screen_buffer*)obj; assert( obj->ops == &screen_buffer_ops ); if (screen_buffer->fd) return (struct fd*)grab_object( screen_buffer->fd ); set_error( STATUS_OBJECT_TYPE_MISMATCH ); return NULL; } static void console_server_dump( struct object *obj, int verbose ) { assert( obj->ops == &console_server_ops ); fprintf( stderr, "Console server\n" ); } static void console_server_destroy( struct object *obj ) { struct console_server *server = (struct console_server *)obj; assert( obj->ops == &console_server_ops ); disconnect_console_server( server ); if (server->fd) release_object( server->fd ); } static struct object *console_server_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ) { struct console_server *server = (struct console_server*)obj; static const WCHAR referenceW[] = {'R','e','f','e','r','e','n','c','e'}; assert( obj->ops == &console_server_ops ); if (name->len == sizeof(referenceW) && !memcmp( name->str, referenceW, name->len )) { struct screen_buffer *screen_buffer; name->len = 0; if (server->console) { set_error( STATUS_INVALID_HANDLE ); return 0; } if (!(server->console = (struct console *)create_console())) return NULL; if (!(screen_buffer = (struct screen_buffer *)create_screen_buffer( server->console ))) { release_object( server->console ); server->console = NULL; return NULL; } release_object( screen_buffer ); server->console->server = server; return &server->console->obj; } return NULL; } static int console_server_signaled( struct object *obj, struct wait_queue_entry *entry ) { struct console_server *server = (struct console_server*)obj; assert( obj->ops == &console_server_ops ); return !server->console || !list_empty( &server->queue ); } static struct fd *console_server_get_fd( struct object* obj ) { struct console_server *server = (struct console_server*)obj; assert( obj->ops == &console_server_ops ); return (struct fd *)grab_object( server->fd ); } static struct object *console_server_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static struct object *create_console_server( void ) { struct console_server *server; if (!(server = alloc_object( &console_server_ops ))) return NULL; server->console = NULL; server->busy = 0; server->once_input = 0; server->term_fd = -1; list_init( &server->queue ); list_init( &server->read_queue ); server->fd = alloc_pseudo_fd( &console_server_fd_ops, &server->obj, FILE_SYNCHRONOUS_IO_NONALERT ); if (!server->fd) { release_object( server ); return NULL; } allow_fd_caching(server->fd); return &server->obj; } static int is_blocking_read_ioctl( unsigned int code ) { switch (code) { case IOCTL_CONDRV_READ_INPUT: case IOCTL_CONDRV_READ_CONSOLE: case IOCTL_CONDRV_READ_CONSOLE_CONTROL: case IOCTL_CONDRV_READ_FILE: return 1; default: return 0; } } static void console_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct console *console = get_fd_user( fd ); switch (code) { case IOCTL_CONDRV_CTRL_EVENT: { const struct condrv_ctrl_event *event = get_req_data(); process_id_t group; if (get_req_data_size() != sizeof(*event)) { set_error( STATUS_INVALID_PARAMETER ); return; } group = event->group_id ? event->group_id : current->process->group_id; if (!group) { set_error( STATUS_INVALID_PARAMETER ); return; } propagate_console_signal( console, event->event, group ); return; } case IOCTL_CONDRV_GET_PROCESS_LIST: { struct console_process_list cpl; if (get_reply_max_size() < sizeof(unsigned int)) { set_error( STATUS_INVALID_PARAMETER ); return; } cpl.count = 0; cpl.size = 0; cpl.console = console; enum_processes( console_process_list_cb, &cpl ); if (cpl.count * sizeof(process_id_t) > get_reply_max_size()) { set_reply_data( &cpl.count, sizeof(cpl.count) ); set_error( STATUS_BUFFER_TOO_SMALL ); return; } cpl.size = cpl.count; cpl.count = 0; if ((cpl.processes = set_reply_data_size( cpl.size * sizeof(process_id_t) ))) enum_processes( console_process_list_cb, &cpl ); return; } default: if (!console->server || code >> 16 != FILE_DEVICE_CONSOLE) { set_error( STATUS_INVALID_HANDLE ); return; } queue_host_ioctl( console->server, code, 0, async, &console->ioctl_q ); } } static void console_read( struct fd *fd, struct async *async, file_pos_t pos ) { struct console *console = get_fd_user( fd ); if (!console->server) { set_error( STATUS_INVALID_HANDLE ); return; } queue_host_ioctl( console->server, IOCTL_CONDRV_READ_FILE, 0, async, &console->ioctl_q ); } static void console_flush( struct fd *fd, struct async *async ) { struct console *console = get_fd_user( fd ); if (!console->server) { set_error( STATUS_INVALID_HANDLE ); return; } queue_host_ioctl( console->server, IOCTL_CONDRV_FLUSH, 0, NULL, NULL ); } static void screen_buffer_write( struct fd *fd, struct async *async, file_pos_t pos ) { struct screen_buffer *screen_buffer = get_fd_user( fd ); if (!screen_buffer->input || !screen_buffer->input->server) { set_error( STATUS_INVALID_HANDLE ); return; } queue_host_ioctl( screen_buffer->input->server, IOCTL_CONDRV_WRITE_FILE, screen_buffer->id, async, &screen_buffer->ioctl_q ); } static void screen_buffer_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct screen_buffer *screen_buffer = get_fd_user( fd ); switch (code) { case IOCTL_CONDRV_ACTIVATE: if (!screen_buffer->input) { set_error( STATUS_INVALID_HANDLE ); return; } set_active_screen_buffer( screen_buffer->input, screen_buffer ); return; default: if (!screen_buffer->input || !screen_buffer->input->server || code >> 16 != FILE_DEVICE_CONSOLE || is_blocking_read_ioctl( code )) { set_error( STATUS_INVALID_HANDLE ); return; } queue_host_ioctl( screen_buffer->input->server, code, screen_buffer->id, async, &screen_buffer->ioctl_q ); } } static void console_connection_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct console_connection *console_connection = get_fd_user( fd ); switch (code) { case IOCTL_CONDRV_BIND_PID: { struct process *process; unsigned int pid; if (get_req_data_size() != sizeof(unsigned int)) { set_error( STATUS_INVALID_PARAMETER ); return; } if (current->process->console) { set_error( STATUS_INVALID_HANDLE ); return; } pid = *(unsigned int *)get_req_data(); if (pid == ATTACH_PARENT_PROCESS) pid = current->process->parent_id; if (!(process = get_process_from_id( pid ))) return; if (process->console) current->process->console = (struct console *)grab_object( process->console ); else set_error( STATUS_ACCESS_DENIED ); release_object( process ); return; } default: default_fd_ioctl( console_connection->fd, code, async ); } } static void console_server_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct console_server *server = get_fd_user( fd ); switch (code) { case IOCTL_CONDRV_CTRL_EVENT: { const struct condrv_ctrl_event *event = get_req_data(); if (get_req_data_size() != sizeof(*event)) { set_error( STATUS_INVALID_PARAMETER ); return; } if (!server->console) { set_error( STATUS_INVALID_HANDLE ); return; } propagate_console_signal( server->console, event->event, event->group_id ); return; } case IOCTL_CONDRV_SETUP_INPUT: { struct termios term; obj_handle_t handle; struct file *file; int unix_fd; if (get_req_data_size() != sizeof(unsigned int) || get_reply_max_size()) { set_error( STATUS_INVALID_PARAMETER ); return; } if (server->term_fd != -1) { tcsetattr( server->term_fd, TCSANOW, &server->termios ); close( server->term_fd ); server->term_fd = -1; } handle = *(unsigned int *)get_req_data(); if (!handle) return; if (!(file = get_file_obj( current->process, handle, FILE_READ_DATA ))) { return; } unix_fd = get_file_unix_fd( file ); release_object( file ); if (tcgetattr( unix_fd, &server->termios )) { file_set_error(); return; } term = server->termios; term.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN); term.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); term.c_cflag &= ~(CSIZE | PARENB); term.c_cflag |= CS8; term.c_cc[VMIN] = 1; term.c_cc[VTIME] = 0; if (tcsetattr( unix_fd, TCSANOW, &term ) || (server->term_fd = dup( unix_fd )) == -1) file_set_error(); return; } default: set_error( STATUS_INVALID_HANDLE ); return; } } static void console_connection_dump( struct object *obj, int verbose ) { fputs( "console connection\n", stderr ); } static struct fd *console_connection_get_fd( struct object *obj ) { struct console_connection *connection = (struct console_connection *)obj; return (struct fd *)grab_object( connection->fd ); } static struct object *console_connection_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ) { static const WCHAR referenceW[] = {'R','e','f','e','r','e','n','c','e'}; if (name->len == sizeof(referenceW) && !memcmp( name->str, referenceW, name->len )) { if (!current->process->console) { set_error( STATUS_INVALID_HANDLE ); return NULL; } name->len = 0; return grab_object( current->process->console ); } return NULL; } static struct object *console_connection_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static int console_connection_close_handle( struct object *obj, struct process *process, obj_handle_t handle ) { struct console *console = process->console; if (console) { process->console = NULL; release_object( console ); } return 1; } static void console_connection_destroy( struct object *obj ) { struct console_connection *connection = (struct console_connection *)obj; if (connection->fd) release_object( connection->fd ); } static void console_device_dump( struct object *obj, int verbose ) { fputs( "Console device\n", stderr ); } static struct object *console_device_lookup_name( struct object *obj, struct unicode_str *name, unsigned int attr, struct object *root ) { static const WCHAR connectionW[] = {'C','o','n','n','e','c','t','i','o','n'}; static const WCHAR consoleW[] = {'C','o','n','s','o','l','e'}; static const WCHAR current_inW[] = {'C','u','r','r','e','n','t','I','n'}; static const WCHAR current_outW[] = {'C','u','r','r','e','n','t','O','u','t'}; static const WCHAR inputW[] = {'I','n','p','u','t'}; static const WCHAR outputW[] = {'O','u','t','p','u','t'}; static const WCHAR screen_bufferW[] = {'S','c','r','e','e','n','B','u','f','f','e','r'}; static const WCHAR serverW[] = {'S','e','r','v','e','r'}; if (name->len == sizeof(current_inW) && !memcmp( name->str, current_inW, name->len )) { if (!current->process->console) { set_error( STATUS_INVALID_HANDLE ); return NULL; } name->len = 0; return grab_object( current->process->console ); } if (name->len == sizeof(current_outW) && !memcmp( name->str, current_outW, name->len )) { if (!current->process->console || !current->process->console->active) { set_error( STATUS_INVALID_HANDLE ); return NULL; } name->len = 0; return grab_object( current->process->console->active ); } if (name->len == sizeof(consoleW) && !memcmp( name->str, consoleW, name->len )) { name->len = 0; return grab_object( obj ); } if (name->len == sizeof(inputW) && !memcmp( name->str, inputW, name->len )) { struct console_input *console_input; name->len = 0; if (!(console_input = alloc_object( &console_input_ops ))) return NULL; console_input->fd = alloc_pseudo_fd( &console_input_fd_ops, &console_input->obj, FILE_SYNCHRONOUS_IO_NONALERT ); if (!console_input->fd) { release_object( console_input ); return NULL; } return &console_input->obj; } if (name->len == sizeof(outputW) && !memcmp( name->str, outputW, name->len )) { struct console_output *console_output; name->len = 0; if (!(console_output = alloc_object( &console_output_ops ))) return NULL; console_output->fd = alloc_pseudo_fd( &console_output_fd_ops, &console_output->obj, FILE_SYNCHRONOUS_IO_NONALERT ); if (!console_output->fd) { release_object( console_output ); return NULL; } return &console_output->obj; } if (name->len == sizeof(screen_bufferW) && !memcmp( name->str, screen_bufferW, name->len )) { if (!current->process->console) { set_error( STATUS_INVALID_HANDLE ); return NULL; } name->len = 0; return create_screen_buffer( current->process->console ); } if (name->len == sizeof(serverW) && !memcmp( name->str, serverW, name->len )) { name->len = 0; return create_console_server(); } if (name->len == sizeof(connectionW) && !memcmp( name->str, connectionW, name->len )) { name->len = 0; return create_console_connection( NULL ); } return NULL; } static struct object *console_device_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { int is_output; access = default_map_access( obj, access ); is_output = access & FILE_WRITE_DATA; if (!current->process->console || (is_output && !current->process->console)) { set_error( STATUS_INVALID_HANDLE ); return NULL; } if (is_output && (access & FILE_READ_DATA)) { set_error( STATUS_INVALID_PARAMETER ); return NULL; } return is_output ? grab_object( current->process->console->active ) : grab_object( current->process->console ); } static void console_input_dump( struct object *obj, int verbose ) { fputs( "console Input device\n", stderr ); } static int console_input_add_queue( struct object *obj, struct wait_queue_entry *entry ) { if (!current->process->console) { set_error( STATUS_ACCESS_DENIED ); return 0; } return console_add_queue( &current->process->console->obj, entry ); } static struct fd *console_input_get_fd( struct object *obj ) { struct console_input *console_input = (struct console_input *)obj; assert( obj->ops == &console_input_ops ); return (struct fd *)grab_object( console_input->fd ); } static struct object *console_input_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static void console_input_destroy( struct object *obj ) { struct console_input *console_input = (struct console_input *)obj; assert( obj->ops == &console_input_ops ); if (console_input->fd) release_object( console_input->fd ); } static void console_input_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct console *console = current->process->console; if (!console) { set_error( STATUS_INVALID_HANDLE ); return; } console_ioctl( console->fd, code, async ); } static void console_input_read( struct fd *fd, struct async *async, file_pos_t pos ) { struct console *console = current->process->console; if (!console) { set_error( STATUS_INVALID_HANDLE ); return; } console_read( console->fd, async, pos ); } static void console_input_flush( struct fd *fd, struct async *async ) { struct console *console = current->process->console; if (!console) { set_error( STATUS_INVALID_HANDLE ); return; } console_flush( console->fd, async ); } static void console_output_dump( struct object *obj, int verbose ) { fputs( "console Output device\n", stderr ); } static int console_output_add_queue( struct object *obj, struct wait_queue_entry *entry ) { if (!current->process->console || !current->process->console->active) { set_error( STATUS_ACCESS_DENIED ); return 0; } return console_add_queue( &current->process->console->obj, entry ); } static struct fd *console_output_get_fd( struct object *obj ) { struct console_output *console_output = (struct console_output *)obj; assert( obj->ops == &console_output_ops ); return (struct fd *)grab_object( console_output->fd ); } static struct object *console_output_open_file( struct object *obj, unsigned int access, unsigned int sharing, unsigned int options ) { return grab_object( obj ); } static void console_output_destroy( struct object *obj ) { struct console_output *console_output = (struct console_output *)obj; assert( obj->ops == &console_output_ops ); if (console_output->fd) release_object( console_output->fd ); } static void console_output_ioctl( struct fd *fd, ioctl_code_t code, struct async *async ) { struct console *console = current->process->console; if (!console || !console->active) { set_error( STATUS_INVALID_HANDLE ); return; } screen_buffer_ioctl( console->active->fd, code, async ); } static void console_output_write( struct fd *fd, struct async *async, file_pos_t pos ) { struct console *console = current->process->console; if (!console || !console->active) { set_error( STATUS_INVALID_HANDLE ); return; } screen_buffer_write( console->active->fd, async, pos ); } struct object *create_console_device( struct object *root, const struct unicode_str *name, unsigned int attr, const struct security_descriptor *sd ) { return create_named_object( root, &console_device_ops, name, attr, sd ); } /* retrieve the next pending console ioctl request */ DECL_HANDLER(get_next_console_request) { struct console_host_ioctl *ioctl = NULL, *next; struct console_server *server; struct iosb *iosb = NULL; server = (struct console_server *)get_handle_obj( current->process, req->handle, 0, &console_server_ops ); if (!server) return; if (!server->console) { set_error( STATUS_INVALID_HANDLE ); release_object( server ); return; } if (!server->console->renderer) server->console->renderer = current; if (!req->signal) server->console->signaled = 0; else if (!server->console->signaled) { server->console->signaled = 1; wake_up( &server->console->obj, 0 ); } if (req->read) { /* set result of current pending ioctl */ if (list_empty( &server->read_queue )) { set_error( STATUS_INVALID_HANDLE ); release_object( server ); return; } ioctl = LIST_ENTRY( list_head( &server->read_queue ), struct console_host_ioctl, entry ); list_remove( &ioctl->entry ); list_move_tail( &server->queue, &server->read_queue ); } else if (server->busy) { /* set result of previous ioctl */ ioctl = LIST_ENTRY( list_head( &server->queue ), struct console_host_ioctl, entry ); list_remove( &ioctl->entry ); } if (ioctl) { struct async *async = ioctl->async; unsigned int status = req->status; if (status == STATUS_PENDING) status = STATUS_INVALID_PARAMETER; if (async) { iosb = async_get_iosb( async ); if (iosb->status == STATUS_PENDING) { data_size_t out_size = min( iosb->out_size, get_req_data_size() ); data_size_t result = ioctl->code == IOCTL_CONDRV_WRITE_FILE ? iosb->in_size : out_size; async_request_complete_alloc( async, status, result, out_size, get_req_data() ); } release_object( async ); } free( ioctl ); if (iosb) release_object( iosb ); if (req->read) { release_object( server ); return; } server->busy = 0; } /* if we have a blocking read ioctl in queue head and previous blocking read is still waiting, * move it to read queue for execution after current read is complete. move all blocking * ioctl at the same time to preserve their order. */ if (!list_empty( &server->queue ) && !list_empty( &server->read_queue )) { ioctl = LIST_ENTRY( list_head( &server->queue ), struct console_host_ioctl, entry ); if (is_blocking_read_ioctl( ioctl->code )) { LIST_FOR_EACH_ENTRY_SAFE( ioctl, next, &server->queue, struct console_host_ioctl, entry ) { if (!is_blocking_read_ioctl( ioctl->code )) continue; list_remove( &ioctl->entry ); list_add_tail( &server->read_queue, &ioctl->entry ); } } } /* return the next ioctl */ if (!list_empty( &server->queue )) { ioctl = LIST_ENTRY( list_head( &server->queue ), struct console_host_ioctl, entry ); iosb = ioctl->async ? async_get_iosb( ioctl->async ) : NULL; if (!iosb || get_reply_max_size() >= iosb->in_size) { reply->code = ioctl->code; reply->output = ioctl->output; if (iosb) { reply->out_size = iosb->out_size; set_reply_data_ptr( iosb->in_data, iosb->in_size ); iosb->in_data = NULL; } if (is_blocking_read_ioctl( ioctl->code )) { list_remove( &ioctl->entry ); assert( list_empty( &server->read_queue )); list_add_tail( &server->read_queue, &ioctl->entry ); } else server->busy = 1; } else { reply->out_size = iosb->in_size; set_error( STATUS_BUFFER_OVERFLOW ); } if (iosb) release_object( iosb ); } else { set_error( STATUS_PENDING ); } release_object( server ); }
263310.c
/* $Id$ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <[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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* * sock_select.c * * This is the implementation of IOQueue using pj_sock_select(). * It runs anywhere where pj_sock_select() is available (currently * Win32, Linux, Linux kernel, etc.). */ #include <pj/ioqueue.h> #include <pj/os.h> #include <pj/lock.h> #include <pj/log.h> #include <pj/list.h> #include <pj/pool.h> #include <pj/string.h> #include <pj/assert.h> #include <pj/sock.h> #include <pj/compat/socket.h> #include <pj/sock_select.h> #include <pj/sock_qos.h> #include <pj/errno.h> #include <pj/rand.h> /* Now that we have access to OS'es <sys/select>, lets check again that * PJ_IOQUEUE_MAX_HANDLES is not greater than FD_SETSIZE */ #if PJ_IOQUEUE_MAX_HANDLES > FD_SETSIZE # error "PJ_IOQUEUE_MAX_HANDLES cannot be greater than FD_SETSIZE" #endif /* * Include declaration from common abstraction. */ #include "ioqueue_common_abs.h" /* * ISSUES with ioqueue_select() * * EAGAIN/EWOULDBLOCK error in recv(): * - when multiple threads are working with the ioqueue, application * may receive EAGAIN or EWOULDBLOCK in the receive callback. * This error happens because more than one thread is watching for * the same descriptor set, so when all of them call recv() or recvfrom() * simultaneously, only one will succeed and the rest will get the error. * */ #define THIS_FILE "ioq_select" /* * The select ioqueue relies on socket functions (pj_sock_xxx()) to return * the correct error code. */ #if PJ_RETURN_OS_ERROR(100) != PJ_STATUS_FROM_OS(100) # error "Error reporting must be enabled for this function to work!" #endif /* * During debugging build, VALIDATE_FD_SET is set. * This will check the validity of the fd_sets. */ /* #if defined(PJ_DEBUG) && PJ_DEBUG != 0 # define VALIDATE_FD_SET 1 #else # define VALIDATE_FD_SET 0 #endif */ #define VALIDATE_FD_SET 0 #if 0 # define TRACE__(args) PJ_LOG(3,args) #else # define TRACE__(args) #endif /* * This describes each key. */ struct pj_ioqueue_key_t { DECLARE_COMMON_KEY }; /* * This describes the I/O queue itself. */ struct pj_ioqueue_t { DECLARE_COMMON_IOQUEUE unsigned max, count; /* Max and current key count */ int nfds; /* The largest fd value (for select)*/ pj_ioqueue_key_t active_list; /* List of active keys. */ pj_fd_set_t rfdset; pj_fd_set_t wfdset; #if PJ_HAS_TCP pj_fd_set_t xfdset; #endif #if PJ_IOQUEUE_HAS_SAFE_UNREG pj_mutex_t *ref_cnt_mutex; pj_ioqueue_key_t closing_list; pj_ioqueue_key_t free_list; #endif }; /* Proto */ #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h); #endif /* Include implementation for common abstraction after we declare * pj_ioqueue_key_t and pj_ioqueue_t. */ #include "ioqueue_common_abs.c" #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Scan closing keys to be put to free list again */ static void scan_closing_keys(pj_ioqueue_t *ioqueue); #endif /* * pj_ioqueue_name() */ PJ_DEF(const char*) pj_ioqueue_name(void) { return "select"; } /* * Scan the socket descriptor sets for the largest descriptor. * This value is needed by select(). */ #if defined(PJ_SELECT_NEEDS_NFDS) && PJ_SELECT_NEEDS_NFDS!=0 static void rescan_fdset(pj_ioqueue_t *ioqueue) { pj_ioqueue_key_t *key = ioqueue->active_list.next; int max = 0; while (key != &ioqueue->active_list) { if (key->fd > max) max = key->fd; key = key->next; } ioqueue->nfds = max; } #else static void rescan_fdset(pj_ioqueue_t *ioqueue) { ioqueue->nfds = FD_SETSIZE-1; } #endif /* * pj_ioqueue_create() * * Create select ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_create( pj_pool_t *pool, pj_size_t max_fd, pj_ioqueue_t **p_ioqueue) { pj_ioqueue_t *ioqueue; pj_lock_t *lock; unsigned i; pj_status_t rc; /* Check that arguments are valid. */ PJ_ASSERT_RETURN(pool != NULL && p_ioqueue != NULL && max_fd > 0 && max_fd <= PJ_IOQUEUE_MAX_HANDLES, PJ_EINVAL); /* Check that size of pj_ioqueue_op_key_t is sufficient */ PJ_ASSERT_RETURN(sizeof(pj_ioqueue_op_key_t)-sizeof(void*) >= sizeof(union operation_key), PJ_EBUG); /* Create and init common ioqueue stuffs */ ioqueue = PJ_POOL_ALLOC_T(pool, pj_ioqueue_t); ioqueue_init(ioqueue); ioqueue->max = (unsigned)max_fd; ioqueue->count = 0; PJ_FD_ZERO(&ioqueue->rfdset); PJ_FD_ZERO(&ioqueue->wfdset); #if PJ_HAS_TCP PJ_FD_ZERO(&ioqueue->xfdset); #endif pj_list_init(&ioqueue->active_list); rescan_fdset(ioqueue); #if PJ_IOQUEUE_HAS_SAFE_UNREG /* When safe unregistration is used (the default), we pre-create * all keys and put them in the free list. */ /* Mutex to protect key's reference counter * We don't want to use key's mutex or ioqueue's mutex because * that would create deadlock situation in some cases. */ rc = pj_mutex_create_simple(pool, NULL, &ioqueue->ref_cnt_mutex); if (rc != PJ_SUCCESS) return rc; /* Init key list */ pj_list_init(&ioqueue->free_list); pj_list_init(&ioqueue->closing_list); /* Pre-create all keys according to max_fd */ for (i=0; i<max_fd; ++i) { pj_ioqueue_key_t *key; key = PJ_POOL_ALLOC_T(pool, pj_ioqueue_key_t); key->ref_count = 0; rc = pj_lock_create_recursive_mutex(pool, NULL, &key->lock); if (rc != PJ_SUCCESS) { key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { pj_lock_destroy(key->lock); key = key->next; } pj_mutex_destroy(ioqueue->ref_cnt_mutex); return rc; } pj_list_push_back(&ioqueue->free_list, key); } #endif /* Create and init ioqueue mutex */ rc = pj_lock_create_simple_mutex(pool, "ioq%p", &lock); if (rc != PJ_SUCCESS) return rc; rc = pj_ioqueue_set_lock(ioqueue, lock, PJ_TRUE); if (rc != PJ_SUCCESS) return rc; PJ_LOG(4, ("pjlib", "select() I/O Queue created (%p)", ioqueue)); *p_ioqueue = ioqueue; return PJ_SUCCESS; } /* * pj_ioqueue_destroy() * * Destroy ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_destroy(pj_ioqueue_t *ioqueue) { pj_ioqueue_key_t *key; PJ_ASSERT_RETURN(ioqueue, PJ_EINVAL); pj_lock_acquire(ioqueue->lock); #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Destroy reference counters */ key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { pj_lock_destroy(key->lock); key = key->next; } key = ioqueue->closing_list.next; while (key != &ioqueue->closing_list) { pj_lock_destroy(key->lock); key = key->next; } key = ioqueue->free_list.next; while (key != &ioqueue->free_list) { pj_lock_destroy(key->lock); key = key->next; } pj_mutex_destroy(ioqueue->ref_cnt_mutex); #endif return ioqueue_destroy(ioqueue); } /* * pj_ioqueue_register_sock() * * Register socket handle to ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_register_sock2(pj_pool_t *pool, pj_ioqueue_t *ioqueue, pj_sock_t sock, pj_grp_lock_t *grp_lock, void *user_data, const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { pj_ioqueue_key_t *key = NULL; #if defined(PJ_WIN32) && PJ_WIN32!=0 || \ defined(PJ_WIN64) && PJ_WIN64 != 0 || \ defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 u_long value; #else pj_uint32_t value; #endif pj_status_t rc = PJ_SUCCESS; PJ_ASSERT_RETURN(pool && ioqueue && sock != PJ_INVALID_SOCKET && cb && p_key, PJ_EINVAL); /* On platforms with fd_set containing fd bitmap such as *nix family, * avoid potential memory corruption caused by select() when given * an fd that is higher than FD_SETSIZE. */ if (sizeof(fd_set) < FD_SETSIZE && sock >= FD_SETSIZE) { PJ_LOG(4, ("pjlib", "Failed to register socket to ioqueue because " "socket fd is too big (fd=%d/FD_SETSIZE=%d)", sock, FD_SETSIZE)); return PJ_ETOOBIG; } pj_lock_acquire(ioqueue->lock); if (ioqueue->count >= ioqueue->max) { rc = PJ_ETOOMANY; goto on_return; } /* If safe unregistration (PJ_IOQUEUE_HAS_SAFE_UNREG) is used, get * the key from the free list. Otherwise allocate a new one. */ #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Scan closing_keys first to let them come back to free_list */ scan_closing_keys(ioqueue); pj_assert(!pj_list_empty(&ioqueue->free_list)); if (pj_list_empty(&ioqueue->free_list)) { rc = PJ_ETOOMANY; goto on_return; } key = ioqueue->free_list.next; pj_list_erase(key); #else key = (pj_ioqueue_key_t*)pj_pool_zalloc(pool, sizeof(pj_ioqueue_key_t)); #endif rc = ioqueue_init_key(pool, ioqueue, key, sock, grp_lock, user_data, cb); if (rc != PJ_SUCCESS) { key = NULL; goto on_return; } /* Set socket to nonblocking. */ value = 1; #if defined(PJ_WIN32) && PJ_WIN32!=0 || \ defined(PJ_WIN64) && PJ_WIN64 != 0 || \ defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 if (ioctlsocket(sock, FIONBIO, &value)) { #else if (ioctl(sock, FIONBIO, &value)) { #endif rc = pj_get_netos_error(); goto on_return; } /* Put in active list. */ pj_list_insert_before(&ioqueue->active_list, key); ++ioqueue->count; /* Rescan fdset to get max descriptor */ rescan_fdset(ioqueue); on_return: /* On error, socket may be left in non-blocking mode. */ if (rc != PJ_SUCCESS) { if (key && key->grp_lock) pj_grp_lock_dec_ref_dbg(key->grp_lock, "ioqueue", 0); } *p_key = key; pj_lock_release(ioqueue->lock); return rc; } PJ_DEF(pj_status_t) pj_ioqueue_register_sock( pj_pool_t *pool, pj_ioqueue_t *ioqueue, pj_sock_t sock, void *user_data, const pj_ioqueue_callback *cb, pj_ioqueue_key_t **p_key) { return pj_ioqueue_register_sock2(pool, ioqueue, sock, NULL, user_data, cb, p_key); } #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Increment key's reference counter */ static void increment_counter(pj_ioqueue_key_t *key) { pj_mutex_lock(key->ioqueue->ref_cnt_mutex); ++key->ref_count; pj_mutex_unlock(key->ioqueue->ref_cnt_mutex); } /* Decrement the key's reference counter, and when the counter reach zero, * destroy the key. * * Note: MUST NOT CALL THIS FUNCTION WHILE HOLDING ioqueue's LOCK. */ static void decrement_counter(pj_ioqueue_key_t *key) { pj_lock_acquire(key->ioqueue->lock); pj_mutex_lock(key->ioqueue->ref_cnt_mutex); --key->ref_count; if (key->ref_count == 0) { pj_assert(key->closing == 1); pj_gettickcount(&key->free_time); key->free_time.msec += PJ_IOQUEUE_KEY_FREE_DELAY; pj_time_val_normalize(&key->free_time); pj_list_erase(key); pj_list_push_back(&key->ioqueue->closing_list, key); /* Rescan fdset to get max descriptor */ rescan_fdset(key->ioqueue); } pj_mutex_unlock(key->ioqueue->ref_cnt_mutex); pj_lock_release(key->ioqueue->lock); } #endif /* * pj_ioqueue_unregister() * * Unregister handle from ioqueue. */ PJ_DEF(pj_status_t) pj_ioqueue_unregister( pj_ioqueue_key_t *key) { pj_ioqueue_t *ioqueue; PJ_ASSERT_RETURN(key, PJ_EINVAL); ioqueue = key->ioqueue; /* Lock the key to make sure no callback is simultaneously modifying * the key. We need to lock the key before ioqueue here to prevent * deadlock. */ pj_ioqueue_lock_key(key); /* Best effort to avoid double key-unregistration */ if (IS_CLOSING(key)) { pj_ioqueue_unlock_key(key); return PJ_SUCCESS; } /* Also lock ioqueue */ pj_lock_acquire(ioqueue->lock); /* Avoid "negative" ioqueue count */ if (ioqueue->count > 0) { --ioqueue->count; } else { /* If this happens, very likely there is double unregistration * of a key. */ pj_assert(!"Bad ioqueue count in key unregistration!"); PJ_LOG(1,(THIS_FILE, "Bad ioqueue count in key unregistration!")); } #if !PJ_IOQUEUE_HAS_SAFE_UNREG /* Ticket #520, key will be erased more than once */ pj_list_erase(key); #endif PJ_FD_CLR(key->fd, &ioqueue->rfdset); PJ_FD_CLR(key->fd, &ioqueue->wfdset); #if PJ_HAS_TCP PJ_FD_CLR(key->fd, &ioqueue->xfdset); #endif /* Close socket. */ if (key->fd != PJ_INVALID_SOCKET) { pj_sock_close(key->fd); key->fd = PJ_INVALID_SOCKET; } /* Clear callback */ key->cb.on_accept_complete = NULL; key->cb.on_connect_complete = NULL; key->cb.on_read_complete = NULL; key->cb.on_write_complete = NULL; /* Must release ioqueue lock first before decrementing counter, to * prevent deadlock. */ pj_lock_release(ioqueue->lock); #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Mark key is closing. */ key->closing = 1; /* Decrement counter. */ decrement_counter(key); /* Done. */ if (key->grp_lock) { /* just dec_ref and unlock. we will set grp_lock to NULL * elsewhere */ pj_grp_lock_t *grp_lock = key->grp_lock; // Don't set grp_lock to NULL otherwise the other thread // will crash. Just leave it as dangling pointer, but this // should be safe //key->grp_lock = NULL; pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); pj_grp_lock_release(grp_lock); } else { pj_ioqueue_unlock_key(key); } #else if (key->grp_lock) { /* set grp_lock to NULL and unlock */ pj_grp_lock_t *grp_lock = key->grp_lock; // Don't set grp_lock to NULL otherwise the other thread // will crash. Just leave it as dangling pointer, but this // should be safe //key->grp_lock = NULL; pj_grp_lock_dec_ref_dbg(grp_lock, "ioqueue", 0); pj_grp_lock_release(grp_lock); } else { pj_ioqueue_unlock_key(key); } pj_lock_destroy(key->lock); #endif return PJ_SUCCESS; } /* This supposed to check whether the fd_set values are consistent * with the operation currently set in each key. */ #if VALIDATE_FD_SET static void validate_sets(const pj_ioqueue_t *ioqueue, const pj_fd_set_t *rfdset, const pj_fd_set_t *wfdset, const pj_fd_set_t *xfdset) { pj_ioqueue_key_t *key; /* * This basicly would not work anymore. * We need to lock key before performing the check, but we can't do * so because we're holding ioqueue mutex. If we acquire key's mutex * now, the will cause deadlock. */ pj_assert(0); key = ioqueue->active_list.next; while (key != &ioqueue->active_list) { if (!pj_list_empty(&key->read_list) #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 || !pj_list_empty(&key->accept_list) #endif ) { pj_assert(PJ_FD_ISSET(key->fd, rfdset)); } else { pj_assert(PJ_FD_ISSET(key->fd, rfdset) == 0); } if (!pj_list_empty(&key->write_list) #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 || key->connecting #endif ) { pj_assert(PJ_FD_ISSET(key->fd, wfdset)); } else { pj_assert(PJ_FD_ISSET(key->fd, wfdset) == 0); } #if defined(PJ_HAS_TCP) && PJ_HAS_TCP != 0 if (key->connecting) { pj_assert(PJ_FD_ISSET(key->fd, xfdset)); } else { pj_assert(PJ_FD_ISSET(key->fd, xfdset) == 0); } #endif /* PJ_HAS_TCP */ key = key->next; } } #endif /* VALIDATE_FD_SET */ /* ioqueue_remove_from_set() * This function is called from ioqueue_dispatch_event() to instruct * the ioqueue to remove the specified descriptor from ioqueue's descriptor * set for the specified event. */ static void ioqueue_remove_from_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, enum ioqueue_event_type event_type) { pj_lock_acquire(ioqueue->lock); if (event_type == READABLE_EVENT) PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->rfdset); else if (event_type == WRITEABLE_EVENT) PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->wfdset); #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 else if (event_type == EXCEPTION_EVENT) PJ_FD_CLR((pj_sock_t)key->fd, &ioqueue->xfdset); #endif else pj_assert(0); pj_lock_release(ioqueue->lock); } /* * ioqueue_add_to_set() * This function is called from pj_ioqueue_recv(), pj_ioqueue_send() etc * to instruct the ioqueue to add the specified handle to ioqueue's descriptor * set for the specified event. */ static void ioqueue_add_to_set( pj_ioqueue_t *ioqueue, pj_ioqueue_key_t *key, enum ioqueue_event_type event_type ) { pj_lock_acquire(ioqueue->lock); if (event_type == READABLE_EVENT) PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->rfdset); else if (event_type == WRITEABLE_EVENT) PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->wfdset); #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 else if (event_type == EXCEPTION_EVENT) PJ_FD_SET((pj_sock_t)key->fd, &ioqueue->xfdset); #endif else pj_assert(0); pj_lock_release(ioqueue->lock); } #if PJ_IOQUEUE_HAS_SAFE_UNREG /* Scan closing keys to be put to free list again */ static void scan_closing_keys(pj_ioqueue_t *ioqueue) { pj_time_val now; pj_ioqueue_key_t *h; pj_gettickcount(&now); h = ioqueue->closing_list.next; while (h != &ioqueue->closing_list) { pj_ioqueue_key_t *next = h->next; pj_assert(h->closing != 0); if (PJ_TIME_VAL_GTE(now, h->free_time)) { pj_list_erase(h); // Don't set grp_lock to NULL otherwise the other thread // will crash. Just leave it as dangling pointer, but this // should be safe //h->grp_lock = NULL; pj_list_push_back(&ioqueue->free_list, h); } h = next; } } #endif #if defined(PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT) && \ PJ_IPHONE_OS_HAS_MULTITASKING_SUPPORT!=0 static pj_status_t replace_udp_sock(pj_ioqueue_key_t *h) { enum flags { HAS_PEER_ADDR = 1, HAS_QOS = 2 }; pj_sock_t old_sock, new_sock = PJ_INVALID_SOCKET; pj_sockaddr local_addr, rem_addr; int val, addr_len; pj_fd_set_t *fds[3]; unsigned i, fds_cnt, flags=0; pj_qos_params qos_params; unsigned msec; pj_status_t status; pj_lock_acquire(h->ioqueue->lock); old_sock = h->fd; fds_cnt = 0; fds[fds_cnt++] = &h->ioqueue->rfdset; fds[fds_cnt++] = &h->ioqueue->wfdset; #if PJ_HAS_TCP fds[fds_cnt++] = &h->ioqueue->xfdset; #endif /* Can only replace UDP socket */ pj_assert(h->fd_type == pj_SOCK_DGRAM()); PJ_LOG(4,(THIS_FILE, "Attempting to replace UDP socket %d", old_sock)); for (msec=20; (msec<1000 && status != PJ_SUCCESS) ; msec<1000? msec=msec*2 : 1000) { if (msec > 20) { PJ_LOG(4,(THIS_FILE, "Retry to replace UDP socket %d", old_sock)); pj_thread_sleep(msec); } if (old_sock != PJ_INVALID_SOCKET) { /* Investigate the old socket */ addr_len = sizeof(local_addr); status = pj_sock_getsockname(old_sock, &local_addr, &addr_len); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error get socket name")); continue; } addr_len = sizeof(rem_addr); status = pj_sock_getpeername(old_sock, &rem_addr, &addr_len); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error get peer name")); } else { flags |= HAS_PEER_ADDR; } status = pj_sock_get_qos_params(old_sock, &qos_params); if (status == PJ_STATUS_FROM_OS(EBADF) || status == PJ_STATUS_FROM_OS(EINVAL)) { PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); continue; } if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error get qos param")); } else { flags |= HAS_QOS; } /* We're done with the old socket, close it otherwise we'll get * error in bind() */ status = pj_sock_close(old_sock); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error closing socket")); } old_sock = PJ_INVALID_SOCKET; } /* Prepare the new socket */ status = pj_sock_socket(local_addr.addr.sa_family, PJ_SOCK_DGRAM, 0, &new_sock); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error create socket")); continue; } /* Even after the socket is closed, we'll still get "Address in use" * errors, so force it with SO_REUSEADDR */ val = 1; status = pj_sock_setsockopt(new_sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); if (status == PJ_STATUS_FROM_OS(EBADF) || status == PJ_STATUS_FROM_OS(EINVAL)) { PJ_PERROR(5,(THIS_FILE, status, "Error set socket option")); continue; } /* The loop is silly, but what else can we do? */ addr_len = pj_sockaddr_get_len(&local_addr); for (msec=20; msec<1000 ; msec<1000? msec=msec*2 : 1000) { status = pj_sock_bind(new_sock, &local_addr, addr_len); if (status != PJ_STATUS_FROM_OS(EADDRINUSE)) break; PJ_LOG(4,(THIS_FILE, "Address is still in use, retrying..")); pj_thread_sleep(msec); } if (status != PJ_SUCCESS) continue; if (flags & HAS_QOS) { status = pj_sock_set_qos_params(new_sock, &qos_params); if (status == PJ_STATUS_FROM_OS(EINVAL)) { PJ_PERROR(5,(THIS_FILE, status, "Error set qos param")); continue; } } if (flags & HAS_PEER_ADDR) { status = pj_sock_connect(new_sock, &rem_addr, addr_len); if (status != PJ_SUCCESS) { PJ_PERROR(5,(THIS_FILE, status, "Error connect socket")); continue; } } } if (status != PJ_SUCCESS) goto on_error; /* Set socket to nonblocking. */ val = 1; #if defined(PJ_WIN32) && PJ_WIN32!=0 || \ defined(PJ_WIN64) && PJ_WIN64 != 0 || \ defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE!=0 if (ioctlsocket(new_sock, FIONBIO, &val)) { #else if (ioctl(new_sock, FIONBIO, &val)) { #endif status = pj_get_netos_error(); goto on_error; } /* Replace the occurrence of old socket with new socket in the * fd sets. */ for (i=0; i<fds_cnt; ++i) { if (PJ_FD_ISSET(h->fd, fds[i])) { PJ_FD_CLR(h->fd, fds[i]); PJ_FD_SET(new_sock, fds[i]); } } /* And finally replace the fd in the key */ h->fd = new_sock; PJ_LOG(4,(THIS_FILE, "UDP has been replaced successfully!")); pj_lock_release(h->ioqueue->lock); return PJ_SUCCESS; on_error: if (new_sock != PJ_INVALID_SOCKET) pj_sock_close(new_sock); if (old_sock != PJ_INVALID_SOCKET) pj_sock_close(old_sock); /* Clear the occurrence of old socket in the fd sets. */ for (i=0; i<fds_cnt; ++i) { if (PJ_FD_ISSET(h->fd, fds[i])) { PJ_FD_CLR(h->fd, fds[i]); } } h->fd = PJ_INVALID_SOCKET; PJ_PERROR(1,(THIS_FILE, status, "Error replacing socket %d", old_sock)); pj_lock_release(h->ioqueue->lock); return PJ_ESOCKETSTOP; } #endif /* * pj_ioqueue_poll() * * Few things worth written: * * - we used to do only one callback called per poll, but it didn't go * very well. The reason is because on some situation, the write * callback gets called all the time, thus doesn't give the read * callback to get called. This happens, for example, when user * submit write operation inside the write callback. * As the result, we changed the behaviour so that now multiple * callbacks are called in a single poll. It should be fast too, * just that we need to be carefull with the ioqueue data structs. * * - to guarantee preemptiveness etc, the poll function must strictly * work on fd_set copy of the ioqueue (not the original one). */ PJ_DEF(int) pj_ioqueue_poll( pj_ioqueue_t *ioqueue, const pj_time_val *timeout) { pj_fd_set_t rfdset, wfdset, xfdset; int nfds; int i, count, event_cnt, processed_cnt; pj_ioqueue_key_t *h; enum { MAX_EVENTS = PJ_IOQUEUE_MAX_CAND_EVENTS }; struct event { pj_ioqueue_key_t *key; enum ioqueue_event_type event_type; } event[MAX_EVENTS]; PJ_ASSERT_RETURN(ioqueue, -PJ_EINVAL); /* Lock ioqueue before making fd_set copies */ pj_lock_acquire(ioqueue->lock); /* We will only do select() when there are sockets to be polled. * Otherwise select() will return error. */ if (PJ_FD_COUNT(&ioqueue->rfdset)==0 && PJ_FD_COUNT(&ioqueue->wfdset)==0 #if defined(PJ_HAS_TCP) && PJ_HAS_TCP!=0 && PJ_FD_COUNT(&ioqueue->xfdset)==0 #endif ) { #if PJ_IOQUEUE_HAS_SAFE_UNREG scan_closing_keys(ioqueue); #endif pj_lock_release(ioqueue->lock); TRACE__((THIS_FILE, " poll: no fd is set")); if (timeout) pj_thread_sleep(PJ_TIME_VAL_MSEC(*timeout)); return 0; } /* Copy ioqueue's pj_fd_set_t to local variables. */ pj_memcpy(&rfdset, &ioqueue->rfdset, sizeof(pj_fd_set_t)); pj_memcpy(&wfdset, &ioqueue->wfdset, sizeof(pj_fd_set_t)); #if PJ_HAS_TCP pj_memcpy(&xfdset, &ioqueue->xfdset, sizeof(pj_fd_set_t)); #else PJ_FD_ZERO(&xfdset); #endif #if VALIDATE_FD_SET validate_sets(ioqueue, &rfdset, &wfdset, &xfdset); #endif nfds = ioqueue->nfds; /* Unlock ioqueue before select(). */ pj_lock_release(ioqueue->lock); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 count = 0; __try { #endif count = pj_sock_select(nfds+1, &rfdset, &wfdset, &xfdset, timeout); #if defined(PJ_WIN32_WINPHONE8) && PJ_WIN32_WINPHONE8 /* Ignore Invalid Handle Exception raised by select().*/ } __except (GetExceptionCode() == STATUS_INVALID_HANDLE ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_CONTINUE_SEARCH) { } #endif if (count == 0) return 0; else if (count < 0) return -pj_get_netos_error(); /* Scan descriptor sets for event and add the events in the event * array to be processed later in this function. We do this so that * events can be processed in parallel without holding ioqueue lock. */ pj_lock_acquire(ioqueue->lock); event_cnt = 0; /* Scan for writable sockets first to handle piggy-back data * coming with accept(). */ for (h = ioqueue->active_list.next; h != &ioqueue->active_list && event_cnt < MAX_EVENTS; h = h->next) { if (h->fd == PJ_INVALID_SOCKET) continue; if ( (key_has_pending_write(h) || key_has_pending_connect(h)) && PJ_FD_ISSET(h->fd, &wfdset) && !IS_CLOSING(h)) { #if PJ_IOQUEUE_HAS_SAFE_UNREG increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = WRITEABLE_EVENT; ++event_cnt; } /* Scan for readable socket. */ if ((key_has_pending_read(h) || key_has_pending_accept(h)) && PJ_FD_ISSET(h->fd, &rfdset) && !IS_CLOSING(h) && event_cnt < MAX_EVENTS) { #if PJ_IOQUEUE_HAS_SAFE_UNREG increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = READABLE_EVENT; ++event_cnt; } #if PJ_HAS_TCP if (key_has_pending_connect(h) && PJ_FD_ISSET(h->fd, &xfdset) && !IS_CLOSING(h) && event_cnt < MAX_EVENTS) { #if PJ_IOQUEUE_HAS_SAFE_UNREG increment_counter(h); #endif event[event_cnt].key = h; event[event_cnt].event_type = EXCEPTION_EVENT; ++event_cnt; } #endif } for (i=0; i<event_cnt; ++i) { if (event[i].key->grp_lock) pj_grp_lock_add_ref_dbg(event[i].key->grp_lock, "ioqueue", 0); } PJ_RACE_ME(5); pj_lock_release(ioqueue->lock); PJ_RACE_ME(5); processed_cnt = 0; /* Now process all events. The dispatch functions will take care * of locking in each of the key */ for (i=0; i<event_cnt; ++i) { /* Just do not exceed PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL */ if (processed_cnt < PJ_IOQUEUE_MAX_EVENTS_IN_SINGLE_POLL) { switch (event[i].event_type) { case READABLE_EVENT: if (ioqueue_dispatch_read_event(ioqueue, event[i].key)) ++processed_cnt; break; case WRITEABLE_EVENT: if (ioqueue_dispatch_write_event(ioqueue, event[i].key)) ++processed_cnt; break; case EXCEPTION_EVENT: if (ioqueue_dispatch_exception_event(ioqueue, event[i].key)) ++processed_cnt; break; case NO_EVENT: pj_assert(!"Invalid event!"); break; } } #if PJ_IOQUEUE_HAS_SAFE_UNREG decrement_counter(event[i].key); #endif if (event[i].key->grp_lock) pj_grp_lock_dec_ref_dbg(event[i].key->grp_lock, "ioqueue", 0); } TRACE__((THIS_FILE, " poll: count=%d events=%d processed=%d", count, event_cnt, processed_cnt)); return processed_cnt; }
856821.c
/*! \file Copyright (c) 2003, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from U.S. Dept. of Energy) All rights reserved. The source code is distributed under BSD license, see the file License.txt at the top-level directory. */ /*! @file dsp_blas3.c * \brief Sparse BLAS3, using some dense BLAS3 operations * * <pre> * -- SuperLU routine (version 2.0) -- * Univ. of California Berkeley, Xerox Palo Alto Research Center, * and Lawrence Berkeley National Lab. * November 15, 1997 * </pre> */ /* * File name: sp_blas3.c * Purpose: Sparse BLAS3, using some dense BLAS3 operations. */ #include "slu_ddefs.h" /*! \brief * * <pre> * Purpose * ======= * * sp_d performs one of the matrix-matrix operations * * C := alpha*op( A )*op( B ) + beta*C, * * where op( X ) is one of * * op( X ) = X or op( X ) = X' or op( X ) = conjg( X' ), * * alpha and beta are scalars, and A, B and C are matrices, with op( A ) * an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. * * * Parameters * ========== * * TRANSA - (input) char* * On entry, TRANSA specifies the form of op( A ) to be used in * the matrix multiplication as follows: * TRANSA = 'N' or 'n', op( A ) = A. * TRANSA = 'T' or 't', op( A ) = A'. * TRANSA = 'C' or 'c', op( A ) = conjg( A' ). * Unchanged on exit. * * TRANSB - (input) char* * On entry, TRANSB specifies the form of op( B ) to be used in * the matrix multiplication as follows: * TRANSB = 'N' or 'n', op( B ) = B. * TRANSB = 'T' or 't', op( B ) = B'. * TRANSB = 'C' or 'c', op( B ) = conjg( B' ). * Unchanged on exit. * * M - (input) int * On entry, M specifies the number of rows of the matrix * op( A ) and of the matrix C. M must be at least zero. * Unchanged on exit. * * N - (input) int * On entry, N specifies the number of columns of the matrix * op( B ) and the number of columns of the matrix C. N must be * at least zero. * Unchanged on exit. * * K - (input) int * On entry, K specifies the number of columns of the matrix * op( A ) and the number of rows of the matrix op( B ). K must * be at least zero. * Unchanged on exit. * * ALPHA - (input) double * On entry, ALPHA specifies the scalar alpha. * * A - (input) SuperMatrix* * Matrix A with a sparse format, of dimension (A->nrow, A->ncol). * Currently, the type of A can be: * Stype = NC or NCP; Dtype = SLU_D; Mtype = GE. * In the future, more general A can be handled. * * B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is * n when TRANSB = 'N' or 'n', and is k otherwise. * Before entry with TRANSB = 'N' or 'n', the leading k by n * part of the array B must contain the matrix B, otherwise * the leading n by k part of the array B must contain the * matrix B. * Unchanged on exit. * * LDB - (input) int * On entry, LDB specifies the first dimension of B as declared * in the calling (sub) program. LDB must be at least max( 1, n ). * Unchanged on exit. * * BETA - (input) double * On entry, BETA specifies the scalar beta. When BETA is * supplied as zero then C need not be set on input. * * C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). * Before entry, the leading m by n part of the array C must * contain the matrix C, except when beta is zero, in which * case C need not be set on entry. * On exit, the array C is overwritten by the m by n matrix * ( alpha*op( A )*B + beta*C ). * * LDC - (input) int * On entry, LDC specifies the first dimension of C as declared * in the calling (sub)program. LDC must be at least max(1,m). * Unchanged on exit. * * ==== Sparse Level 3 Blas routine. * </pre> */ int sp_dgemm(char *transa, char *transb, int m, int n, int k, double alpha, SuperMatrix *A, double *b, int ldb, double beta, double *c, int ldc) { int incx = 1, incy = 1; int j; for (j = 0; j < n; ++j) { sp_dgemv(transa, alpha, A, &b[ldb*j], incx, beta, &c[ldc*j], incy); } return 0; }
244456.c
/** ****************************************************************************** * @file usb_endp.c * @author MCD Application Team * @version V1.1.0 * @date 20-September-2012 * @brief Endpoint routines ****************************************************************************** * @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_lib.h" #include "usb_istr.h" /** @addtogroup STM32F3-Discovery_Demo * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ extern __IO uint8_t PrevXferComplete; /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief EP1 OUT Callback Routine. * @param None * @retval None */ void EP1_IN_Callback(void) { /* Set the transfer complete token to inform upper layer that the current transfer has been complete */ PrevXferComplete = 1; } /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
485128.c
#include <stdlib.h> // ORACLE FLOAT foo(VOID) float foo(void) { int a; float b; int i; a = rand() % 65536; b = 1.0 / a; for (i = 0; i < a; i++) b += ((float) a) / ((float) i); return b; } int main(void) { int i; float a = 0, b = 0; for (i = 0; i < 100; i++) { a += foo(); b += foo(); } return 0; }
910550.c
// SPDX-License-Identifier: GPL-2.0 /* Copyright (c) 2010, Code Aurora Forum. All rights reserved. */ #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/usb/chipidea.h> #include <linux/clk.h> #include <linux/reset.h> #include <linux/mfd/syscon.h> #include <linux/regmap.h> #include <linux/io.h> #include <linux/reset-controller.h> #include <linux/extcon.h> #include <linux/of.h> #include "ci.h" #define HS_PHY_AHB_MODE 0x0098 #define HS_PHY_GENCONFIG 0x009c #define HS_PHY_TXFIFO_IDLE_FORCE_DIS BIT(4) #define HS_PHY_GENCONFIG_2 0x00a0 #define HS_PHY_SESS_VLD_CTRL_EN BIT(7) #define HS_PHY_ULPI_TX_PKT_EN_CLR_FIX BIT(19) #define HSPHY_SESS_VLD_CTRL BIT(25) /* Vendor base starts at 0x200 beyond CI base */ #define HS_PHY_CTRL 0x0040 #define HS_PHY_SEC_CTRL 0x0078 #define HS_PHY_DIG_CLAMP_N BIT(16) #define HS_PHY_POR_ASSERT BIT(0) struct ci_hdrc_msm { struct platform_device *ci; struct clk *core_clk; struct clk *iface_clk; struct clk *fs_clk; struct ci_hdrc_platform_data pdata; struct reset_controller_dev rcdev; bool secondary_phy; bool hsic; void __iomem *base; }; static int ci_hdrc_msm_por_reset(struct reset_controller_dev *r, unsigned long id) { struct ci_hdrc_msm *ci_msm = container_of(r, struct ci_hdrc_msm, rcdev); void __iomem *addr = ci_msm->base; u32 val; if (id) addr += HS_PHY_SEC_CTRL; else addr += HS_PHY_CTRL; val = readl_relaxed(addr); val |= HS_PHY_POR_ASSERT; writel(val, addr); /* * wait for minimum 10 microseconds as suggested by manual. * Use a slightly larger value since the exact value didn't * work 100% of the time. */ udelay(12); val &= ~HS_PHY_POR_ASSERT; writel(val, addr); return 0; } static const struct reset_control_ops ci_hdrc_msm_reset_ops = { .reset = ci_hdrc_msm_por_reset, }; static int ci_hdrc_msm_notify_event(struct ci_hdrc *ci, unsigned event) { struct device *dev = ci->dev->parent; struct ci_hdrc_msm *msm_ci = dev_get_drvdata(dev); int ret; switch (event) { case CI_HDRC_CONTROLLER_RESET_EVENT: dev_dbg(dev, "CI_HDRC_CONTROLLER_RESET_EVENT received\n"); hw_phymode_configure(ci); if (msm_ci->secondary_phy) { u32 val = readl_relaxed(msm_ci->base + HS_PHY_SEC_CTRL); val |= HS_PHY_DIG_CLAMP_N; writel_relaxed(val, msm_ci->base + HS_PHY_SEC_CTRL); } ret = phy_init(ci->phy); if (ret) return ret; ret = phy_power_on(ci->phy); if (ret) { phy_exit(ci->phy); return ret; } /* use AHB transactor, allow posted data writes */ hw_write_id_reg(ci, HS_PHY_AHB_MODE, 0xffffffff, 0x8); /* workaround for rx buffer collision issue */ hw_write_id_reg(ci, HS_PHY_GENCONFIG, HS_PHY_TXFIFO_IDLE_FORCE_DIS, 0); if (!msm_ci->hsic) hw_write_id_reg(ci, HS_PHY_GENCONFIG_2, HS_PHY_ULPI_TX_PKT_EN_CLR_FIX, 0); if (!IS_ERR(ci->platdata->vbus_extcon.edev) || ci->role_switch) { hw_write_id_reg(ci, HS_PHY_GENCONFIG_2, HS_PHY_SESS_VLD_CTRL_EN, HS_PHY_SESS_VLD_CTRL_EN); hw_write(ci, OP_USBCMD, HSPHY_SESS_VLD_CTRL, HSPHY_SESS_VLD_CTRL); } break; case CI_HDRC_CONTROLLER_STOPPED_EVENT: dev_dbg(dev, "CI_HDRC_CONTROLLER_STOPPED_EVENT received\n"); phy_power_off(ci->phy); phy_exit(ci->phy); break; default: dev_dbg(dev, "unknown ci_hdrc event\n"); break; } return 0; } static int ci_hdrc_msm_mux_phy(struct ci_hdrc_msm *ci, struct platform_device *pdev) { struct regmap *regmap; struct device *dev = &pdev->dev; struct of_phandle_args args; u32 val; int ret; ret = of_parse_phandle_with_fixed_args(dev->of_node, "phy-select", 2, 0, &args); if (ret) return 0; regmap = syscon_node_to_regmap(args.np); of_node_put(args.np); if (IS_ERR(regmap)) return PTR_ERR(regmap); ret = regmap_write(regmap, args.args[0], args.args[1]); if (ret) return ret; ci->secondary_phy = !!args.args[1]; if (ci->secondary_phy) { val = readl_relaxed(ci->base + HS_PHY_SEC_CTRL); val |= HS_PHY_DIG_CLAMP_N; writel_relaxed(val, ci->base + HS_PHY_SEC_CTRL); } return 0; } static int ci_hdrc_msm_probe(struct platform_device *pdev) { struct ci_hdrc_msm *ci; struct platform_device *plat_ci; struct clk *clk; struct reset_control *reset; int ret; struct device_node *ulpi_node, *phy_node; dev_dbg(&pdev->dev, "ci_hdrc_msm_probe\n"); ci = devm_kzalloc(&pdev->dev, sizeof(*ci), GFP_KERNEL); if (!ci) return -ENOMEM; platform_set_drvdata(pdev, ci); ci->pdata.name = "ci_hdrc_msm"; ci->pdata.capoffset = DEF_CAPOFFSET; ci->pdata.flags = CI_HDRC_REGS_SHARED | CI_HDRC_DISABLE_STREAMING | CI_HDRC_OVERRIDE_AHB_BURST | CI_HDRC_OVERRIDE_PHY_CONTROL; ci->pdata.notify_event = ci_hdrc_msm_notify_event; reset = devm_reset_control_get(&pdev->dev, "core"); if (IS_ERR(reset)) return PTR_ERR(reset); ci->core_clk = clk = devm_clk_get(&pdev->dev, "core"); if (IS_ERR(clk)) return PTR_ERR(clk); ci->iface_clk = clk = devm_clk_get(&pdev->dev, "iface"); if (IS_ERR(clk)) return PTR_ERR(clk); ci->fs_clk = clk = devm_clk_get_optional(&pdev->dev, "fs"); if (IS_ERR(clk)) return PTR_ERR(clk); ci->base = devm_platform_ioremap_resource(pdev, 1); if (IS_ERR(ci->base)) return PTR_ERR(ci->base); ci->rcdev.owner = THIS_MODULE; ci->rcdev.ops = &ci_hdrc_msm_reset_ops; ci->rcdev.of_node = pdev->dev.of_node; ci->rcdev.nr_resets = 2; ret = devm_reset_controller_register(&pdev->dev, &ci->rcdev); if (ret) return ret; ret = clk_prepare_enable(ci->fs_clk); if (ret) return ret; reset_control_assert(reset); usleep_range(10000, 12000); reset_control_deassert(reset); clk_disable_unprepare(ci->fs_clk); ret = clk_prepare_enable(ci->core_clk); if (ret) return ret; ret = clk_prepare_enable(ci->iface_clk); if (ret) goto err_iface; ret = ci_hdrc_msm_mux_phy(ci, pdev); if (ret) goto err_mux; ulpi_node = of_get_child_by_name(pdev->dev.of_node, "ulpi"); if (ulpi_node) { phy_node = of_get_next_available_child(ulpi_node, NULL); ci->hsic = of_device_is_compatible(phy_node, "qcom,usb-hsic-phy"); of_node_put(phy_node); } of_node_put(ulpi_node); plat_ci = ci_hdrc_add_device(&pdev->dev, pdev->resource, pdev->num_resources, &ci->pdata); if (IS_ERR(plat_ci)) { ret = PTR_ERR(plat_ci); if (ret != -EPROBE_DEFER) dev_err(&pdev->dev, "ci_hdrc_add_device failed!\n"); goto err_mux; } ci->ci = plat_ci; pm_runtime_set_active(&pdev->dev); pm_runtime_no_callbacks(&pdev->dev); pm_runtime_enable(&pdev->dev); return 0; err_mux: clk_disable_unprepare(ci->iface_clk); err_iface: clk_disable_unprepare(ci->core_clk); return ret; } static int ci_hdrc_msm_remove(struct platform_device *pdev) { struct ci_hdrc_msm *ci = platform_get_drvdata(pdev); pm_runtime_disable(&pdev->dev); ci_hdrc_remove_device(ci->ci); clk_disable_unprepare(ci->iface_clk); clk_disable_unprepare(ci->core_clk); return 0; } static const struct of_device_id msm_ci_dt_match[] = { { .compatible = "qcom,ci-hdrc", }, { } }; MODULE_DEVICE_TABLE(of, msm_ci_dt_match); static struct platform_driver ci_hdrc_msm_driver = { .probe = ci_hdrc_msm_probe, .remove = ci_hdrc_msm_remove, .driver = { .name = "msm_hsusb", .of_match_table = msm_ci_dt_match, }, }; module_platform_driver(ci_hdrc_msm_driver); MODULE_ALIAS("platform:msm_hsusb"); MODULE_ALIAS("platform:ci13xxx_msm"); MODULE_LICENSE("GPL v2");
937216.c
typedef struct { struct { int a }; } b; b *c; d() { return c->a; }
302927.c
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "sw/device/lib/testing/test_framework/ottf.h" #include <assert.h> #include <stddef.h> #include "sw/device/lib/arch/device.h" #include "sw/device/lib/dif/dif_uart.h" #include "sw/device/lib/runtime/log.h" #include "sw/device/lib/runtime/print.h" #include "sw/device/lib/testing/check.h" #include "sw/device/lib/testing/test_framework/FreeRTOSConfig.h" #include "sw/device/lib/testing/test_framework/test_coverage.h" #include "sw/device/lib/testing/test_framework/test_status.h" #include "sw/vendor/freertos_freertos_kernel/include/FreeRTOS.h" #include "sw/vendor/freertos_freertos_kernel/include/queue.h" #include "sw/vendor/freertos_freertos_kernel/include/task.h" // TODO: make this toplevel agnostic. #include "hw/top_earlgrey/sw/autogen/top_earlgrey.h" // Check layout of test configuration struct since OTTF ISR asm code requires a // specific layout. OT_ASSERT_MEMBER_OFFSET(test_config_t, enable_concurrency, 0); OT_ASSERT_MEMBER_SIZE(test_config_t, enable_concurrency, 1); // UART for communication with host. static dif_uart_t uart0; static void init_uart(void) { CHECK_DIF_OK(dif_uart_init( mmio_region_from_addr(TOP_EARLGREY_UART0_BASE_ADDR), &uart0)); CHECK_DIF_OK( dif_uart_configure(&uart0, (dif_uart_config_t){ .baudrate = kUartBaudrate, .clk_freq_hz = kClockFreqPeripheralHz, .parity_enable = kDifToggleDisabled, .parity = kDifUartParityEven, })); base_uart_stdout(&uart0); } static void report_test_status(bool result) { // Reinitialize UART before print any debug output if the test clobbered it. if (kDeviceType != kDeviceSimDV && kTestConfig.can_clobber_uart) { init_uart(); test_coverage_send_buffer(); } test_status_set(result ? kTestStatusPassed : kTestStatusFailed); } // A wrapper function is required to enable `test_main()` and test teardown // logic to be invoked as a FreeRTOS task. This wrapper can be used by tests // that are run on bare-metal. static void test_wrapper(void *task_parameters) { bool result = test_main(); report_test_status(result); } int main(int argc, char **argv) { test_status_set(kTestStatusInTest); // Initialize the UART to enable logging for non-DV simulation platforms. if (kDeviceType != kDeviceSimDV) { init_uart(); } // Run the test. if (kTestConfig.enable_concurrency) { // Run `test_main()` in a FreeRTOS task, allowing other FreeRTOS tasks to be // spawned, if requested in the main test task. xTaskCreate(test_wrapper, "TestTask", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL); vTaskStartScheduler(); } else { // Otherwise, launch `test_main()` on bare-metal. test_wrapper(NULL); } // Unreachable code. return 1; }
283656.c
/* * AppleKeyMapUtils.c * * Created by Jief on 25 May 2018. * */ #include <Library/BaseLib.h> #include <Library/UefiLib.h> #include <Library/UefiBootServicesTableLib.h> #include <Library/UefiRuntimeServicesTableLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/DebugLib.h> #include <Library/PrintLib.h> #include <Library/MemLogLib.h> #include <IndustryStandard/AppleHid.h> #include <Protocol/AppleKeyMapDatabase.h> // DBG_TO: 0=no debug, 1=serial, 2=console 3=log // serial requires // [PcdsFixedAtBuild] // gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x07 // gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0xFFFFFFFF // in package DSC file #ifdef JIEF_DEBUG #define DBG_APPLEKEYFEEDER 2 #endif #if DBG_APPLEKEYFEEDER == 3 #define DBG(...) MemLog(FALSE, 0, __VA_ARGS__) #elif DBG_APPLEKEYFEEDER == 2 #define DBG(...) AsciiPrint(__VA_ARGS__) #elif DBG_APPLEKEYFEEDER == 1 #define DBG(...) DebugPrint(1, __VA_ARGS__) #else #define DBG(...) #endif EFI_GUID gAppleKeyMapDatabaseProtocolGuid = {0x584B9EBE, 0x80C1, 0x4BD6, {0x98, 0xB0, 0xA7, 0x78, 0x6E, 0xC2, 0xF2, 0xE2}}; APPLE_KEY_MAP_DATABASE_PROTOCOL *AppleKeyMapDb = NULL; UINTN AppleKeyMapDbIndex = 0; static EFI_STATUS getAppleKeyMapDb() { EFI_STATUS Status = EFI_SUCCESS; Status = gBS->LocateProtocol ( &gAppleKeyMapDatabaseProtocolGuid, NULL, (VOID **)&AppleKeyMapDb ); if (!EFI_ERROR(Status)) { Status = AppleKeyMapDb->CreateKeyStrokesBuffer ( AppleKeyMapDb, 6, &AppleKeyMapDbIndex ); if (EFI_ERROR(Status)) { DBG("AppleKeyFeederEntrypoint: CreateKeyStrokesBuffer failed, Status=%x\n", Status); } }else{ DBG("AppleKeyFeederEntrypoint: LocateProtocol failed, Status=%x\n", Status); } return Status; } static EFI_EVENT eventKeyRelease; static VOID EFIAPI SendKeyRelease ( IN EFI_EVENT Event, IN VOID *Context ) { EFI_STATUS Status; //DBG("SendKeyRelease\n"); APPLE_KEY_CODE appleKey; // APPLE_KEY_CODE is UINT16 Status = AppleKeyMapDb->SetKeyStrokeBufferKeys ( AppleKeyMapDb, AppleKeyMapDbIndex, (APPLE_MODIFIER_MAP)0, 0, &appleKey ); if (EFI_ERROR(Status)) { DBG("SendKeyRelease: SetKeyStrokeBufferKeys failed, Status=%x\n", Status); } Status = gBS->SetTimer ( eventKeyRelease, TimerCancel, 10*1000 ); if (EFI_ERROR(Status)) { DBG("SendKeyRelease: SetTimer failed, Status=%x\n", Status); } } static int MapKeyData2AppleKey(EFI_KEY_DATA* KeyData, APPLE_KEY_CODE* pKey, UINT8* pCurModifierMap) { if ( KeyData->Key.UnicodeChar == 0 ) { *pCurModifierMap = 0; switch (KeyData->Key.ScanCode) { case 0x01: // up arrow *pKey = 0x7052; return 1; case 0x02: // down arrow *pKey = 0x7051; return 1; case 0x03: // left arrow *pKey = 0x704F; return 1; case 0x04: // right arrow *pKey = 0x7050; return 1; } return 0; } if ( KeyData->Key.UnicodeChar >= 'a' && KeyData->Key.UnicodeChar <= 'z' ) { *pKey = 0x7004 + ( KeyData->Key.UnicodeChar - 'a'); *pCurModifierMap = 0; return 1; } if ( KeyData->Key.UnicodeChar >= 'A' && KeyData->Key.UnicodeChar <= 'Z' ) { *pKey = 0x7004 + ( KeyData->Key.UnicodeChar - 'A'); *pCurModifierMap = 2; return 1; } if ( KeyData->Key.UnicodeChar == '0' ) { // Could have put that in the switch, but wanted to make very clear that the 0 wasn't forgotten and that this : "KeyData->Key.UnicodeChar >= '1'" (instead of '0') is not a mistake !!! *pKey = 0x7027; return 1; } if ( KeyData->Key.UnicodeChar >= '1' && KeyData->Key.UnicodeChar <= '9' ) { *pKey = 0x701E + ( KeyData->Key.UnicodeChar - '1'); return 1; } *pCurModifierMap = 0; switch (KeyData->Key.UnicodeChar) { case 0x01: // up arrow *pKey = 0x7052; return 1; case 0x02: // down arrow *pKey = 0x7051; return 1; case 0x03: // left arrow *pKey = 0x7050; return 1; case 0x04: // right arrow *pKey = 0x704F; return 1; case 0x08: // backspace *pKey = 0x702A; return 1; case 0x0D: // return *pKey = 0x7028; return 1; case ' ': // return *pKey = 0x702C; return 1; case '!': // return *pKey = 0x701E; *pCurModifierMap = 2; return 1; case '"': // return *pKey = 0x7034; *pCurModifierMap = 2; return 1; case '#': // return *pKey = 0x7020; *pCurModifierMap = 2; return 1; case '$': // return *pKey = 0x7021; *pCurModifierMap = 2; return 1; case '%': // return *pKey = 0x7022; *pCurModifierMap = 2; return 1; case '&': // return *pKey = 0x7024; *pCurModifierMap = 2; return 1; case '\'': // return *pKey = 0x7034; return 1; case '(': // return *pKey = 0x7026; *pCurModifierMap = 2; return 1; case ')': // return *pKey = 0x7027; *pCurModifierMap = 2; return 1; case '*': // return *pKey = 0x7025; *pCurModifierMap = 2; return 1; case '+': // return *pKey = 0x702E; *pCurModifierMap = 2; return 1; case ',': // return *pKey = 0x7036; return 1; case '-': // return *pKey = 0x702D; return 1; case '.': // return *pKey = 0x7037; return 1; case '/': // return *pKey = 0x7038; return 1; case ':': // return *pKey = 0x7033; *pCurModifierMap = 2; return 1; case ';': // return *pKey = 0x7033; return 1; case '<': // return *pKey = 0x7036; *pCurModifierMap = 2; return 1; case '=': // return *pKey = 0x702E; return 1; case '>': // return *pKey = 0x7037; *pCurModifierMap = 2; return 1; case '?': // return *pKey = 0x7038; *pCurModifierMap = 2; return 1; case '@': // return *pKey = 0x701F; *pCurModifierMap = 2; return 1; case '[': // return *pKey = 0x702F; return 1; case '\\': // return *pKey = 0x7031; return 1; case ']': // return *pKey = 0x7030; return 1; case '^': // return *pKey = 0x7023; *pCurModifierMap = 2; return 1; case '_': // return *pKey = 0x702D; *pCurModifierMap = 2; return 1; case '`': // return *pKey = 0x7035; return 1; case '{': // return *pKey = 0x702F; *pCurModifierMap = 2; return 1; case '|': // return *pKey = 0x7031; *pCurModifierMap = 2; return 1; case '}': // return *pKey = 0x7030; *pCurModifierMap = 2; return 1; case '~': // return *pKey = 0x7035; *pCurModifierMap = 2; return 1; } return 0; } EFI_STATUS EFIAPI SendDataToAppleMap(IN EFI_KEY_DATA *KeyData) { //DBG("SendDataToAppleMap ScanCode=%x, Uchar=%x, ShiftState=%x, ToogleState=%x\n", KeyData->Key.ScanCode, KeyData->Key.UnicodeChar, KeyData->KeyState.KeyShiftState, KeyData->KeyState.KeyToggleState); EFI_STATUS Status; UINT8 CurModifierMap = 0; UINTN NumberOfKeys = 1; APPLE_KEY_CODE appleKey; // APPLE_KEY_CODE is UINT16 if ( !AppleKeyMapDb ) { Status = getAppleKeyMapDb(); if (EFI_ERROR(Status)) { DBG("SendDataToAppleMap: getAppleKeyMapDb() failed, Status=%x\n", Status); } } if ( !AppleKeyMapDb ) { DBG("SendDataToAppleMap: AppleKeyMapDb==NULL, Status=%x\n", EFI_NOT_FOUND); return EFI_NOT_FOUND; } if ( MapKeyData2AppleKey(KeyData, &appleKey, &CurModifierMap) ) { Status = AppleKeyMapDb->SetKeyStrokeBufferKeys ( AppleKeyMapDb, AppleKeyMapDbIndex, (APPLE_MODIFIER_MAP)CurModifierMap, NumberOfKeys, &appleKey ); if (EFI_ERROR(Status)) { DBG("SendDataToAppleMap: SetKeyStrokeBufferKeys failed, Status=%x\n", Status); return Status; } Status = gBS->SetTimer ( eventKeyRelease, TimerPeriodic, 10*1000*15 // 15 ms ); if (EFI_ERROR(Status)) { // if this fail, we end up having the key repeated. DBG("SendDataToAppleMap: SetTimer failed, Status=%x\n", Status); return Status; } return Status; } DBG("SendDataToAppleMap: key not mapped, sorry\n"); return EFI_NOT_FOUND; } /**************************************************************** * Entry point ***************************************************************/ EFI_STATUS EFIAPI AppleKeyMapUtilsInit ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { DBG("AppleKeyMapUtilsInit\n"); EFI_STATUS Status = EFI_SUCCESS; // // Setup a periodic timer, used for send a key release to apple key map // Status = gBS->CreateEvent ( EVT_TIMER | EVT_NOTIFY_SIGNAL, TPL_NOTIFY, SendKeyRelease, NULL, &eventKeyRelease ); if ( EFI_ERROR(Status) ) { DBG("AppleKeyMapUtilsInit: CreateEvent failed, Status=%x\n", Status); } DBG("AppleKeyMapUtilsInit returns %x\n", Status); return Status; }
819525.c
#include "abt.h" static void free_node(abt_node_t *node); static void memswp(void *a, void *b, size_t size); struct abt { abt_node_t *root; uint32_t a; uint32_t b; size_t k_s; size_t v_s; }; struct abt_node { uint32_t degree; uint32_t height; void *key; void *next; }; abt_t *abt_constructor(size_t k_s, size_t v_s, uint32_t a, uint32_t b) { if (!k_s) return NULL; abt_t *tree = malloc(sizeof(*tree)); if (!tree) return NULL; tree->root = malloc(sizeof(*tree->root)); if (!tree->root) return NULL; tree->root->key = malloc(k_s * b); if (!tree->root->key) return NULL; tree->root->next = malloc(v_s * b); if (!tree->root->next) return NULL; tree->root->degree = 0; tree->root->height = 0; tree->a = a; tree->b = b; tree->k_s = k_s; tree->v_s = v_s; return tree; } void abt_destructor(abt_t *tree) { if (!tree) return; if (tree->root) { free_node(tree->root); } free(tree); tree = NULL; } void *abt_find(abt_t *tree, void *key) { // abt_node_t *cursor = malloc(sizeof(abt_node_t)); // *cursor = *tree->root; abt_node_t *cursor = tree->root; void *t = malloc(sizeof(void *)); while (cursor->height >= 0) { uint32_t right = cursor->degree; uint32_t left = 0; int keys_difference; uint32_t mid; while (right > left + 1) { mid = (right + left) / 2; keys_difference = memcmp(key, (unsigned char *) cursor->key + tree->k_s * mid, tree->k_s); if (keys_difference < 0) right = mid; else left = mid; } if (cursor->height > 0) // memcpy(cursor, (unsigned char *) cursor->next + sizeof(abt_node_t) * left, sizeof(abt_node_t)); cursor = ((void *) ((unsigned char *) cursor->next + sizeof(abt_node_t) * left)); else { if (memcmp(key, (unsigned char *) cursor->key + tree->k_s * left, tree->k_s) == 0) { memcpy(t, (unsigned char *) cursor->next + tree->v_s * left, tree->v_s); } else { t = NULL; } return t; } } // free_node(cursor); } void abt_insert(abt_t *tree, void *key, void *val) { if (!tree) return; abt_node_t *cursor = tree->root; if (tree->root->height == 0 && tree->root->degree == 0) { memcpy(tree->root->key, key, tree->k_s); memcpy(tree->root->next, val, tree->v_s); tree->root->degree = 1; return; } stack_t *path = stack_constructor(NULL); while (cursor->height > 0) { stack_push(path, cursor); uint32_t right = cursor->degree; uint32_t left = 0; int keys_difference; uint32_t mid; while (right > left + 1) { mid = (right + left) / 2; keys_difference = memcmp(key, (unsigned char *) cursor->key + tree->k_s * mid, tree->k_s); if (keys_difference < 0) right = mid; else left = mid; } cursor = ((void *) ((unsigned char *) cursor->next + sizeof(abt_node_t) * left)); } unsigned char finished = 0; void *insert_pt = val; void *insert_key = malloc(tree->k_s); memcpy(insert_key, key, tree->k_s); while (!finished) { int i, start; start = cursor->height > 0; if (cursor->degree < tree->b) { i = cursor->degree; while (i > start && memcmp(insert_key, (unsigned char *) cursor->key + tree->k_s * (i - 1), tree->k_s ) < 0) { memswp((unsigned char *) cursor->key + i * tree->k_s, (unsigned char *) cursor->key + (i - 1) * tree->k_s, tree->k_s); memswp((unsigned char *) cursor->next + i * tree->v_s, (unsigned char *) cursor->next + (i - 1) * tree->v_s, tree->v_s); i--; } memcpy((unsigned char *) cursor->key + i * tree->k_s, insert_key, tree->k_s); memcpy((unsigned char *) cursor->next + i * (cursor->height ? sizeof(abt_node_t) : tree->v_s), insert_pt, cursor->height ? sizeof(abt_node_t) : tree->v_s); // if (cursor->height) // memcpy((unsigned char *) cursor->next + i * sizeof(abt_node_t), insert_pt, sizeof(abt_node_t)); // else // memcpy((unsigned char *) cursor->next + i * tree->v_s, insert_pt, tree->v_s); cursor->degree++; finished = 1; } else { abt_node_t *new_node = malloc(sizeof(*new_node)); if (!new_node) exit(EXIT_FAILURE); new_node->key = malloc(tree->k_s * tree->b); if (!new_node->key) exit(EXIT_FAILURE); new_node->next = malloc(tree->v_s * tree->b); if (!new_node->next) exit(EXIT_FAILURE); int j; unsigned char done = 0; i = tree->b - 1; j = (tree->b - 1) / 2; while (j >= 0) { if (done || memcmp(insert_key, (unsigned char *) cursor->key + tree->k_s * i, tree->k_s) < 0) { memcpy((unsigned char *) new_node->next + tree->v_s * j, (unsigned char *) cursor->next + tree->v_s * i, tree->v_s); memcpy((unsigned char *) new_node->key + tree->k_s * j--, (unsigned char *) cursor->key + tree->k_s * i--, tree->k_s); } else { memcpy((unsigned char *) new_node->next + tree->v_s * j, insert_pt, tree->v_s); memcpy((unsigned char *) new_node->key + tree->k_s * j--, insert_key, tree->k_s); done = 1; } } while (!done) { if (memcmp(insert_key, (unsigned char *) cursor->key + tree->k_s * i, tree->k_s) < 0 && i >= start) { memcpy((unsigned char *) cursor->next + tree->v_s * (i + 1), (unsigned char *) cursor->next + tree->v_s * i, tree->v_s); memcpy((unsigned char *) cursor->key + tree->k_s * (i + 1), (unsigned char *) cursor->key + tree->k_s * i, tree->k_s); i--; } else { memcpy((unsigned char *) cursor->next + tree->v_s * (i + 1), insert_pt, tree->v_s); memcpy((unsigned char *) cursor->key + tree->k_s * (i + 1), insert_key, tree->k_s); done = 1; } } cursor->degree = tree->b + 1 - ((tree->b + 1) / 2); new_node->degree = (tree->b + 1) / 2; new_node->height = cursor->height; insert_pt = new_node; memcpy(insert_key, new_node->key, tree->k_s); if (!stack_is_empty(path)) { cursor = stack_pop(path); continue; } abt_node_t *_new_node = malloc(sizeof(*_new_node)); if (!_new_node) exit(EXIT_FAILURE); _new_node->key = malloc(tree->k_s * tree->b); if (!_new_node->key) exit(EXIT_FAILURE); _new_node->next = malloc(tree->v_s * tree->b); if (!_new_node->next) exit(EXIT_FAILURE); for (i = 0; i < cursor->degree; i++) { memcpy((unsigned char *) _new_node->next + tree->v_s * i, (unsigned char *) cursor->next + tree->v_s * i, tree->v_s); memcpy((unsigned char *) _new_node->key + tree->k_s * i, (unsigned char *) cursor->key + tree->k_s * i, tree->k_s); } _new_node->height = cursor->height; _new_node->degree = cursor->degree; cursor->height++; cursor->degree = 2; free(cursor->next); cursor->next = malloc(sizeof(abt_node_t) * tree->b); if (!cursor->next) exit(EXIT_FAILURE); memcpy(cursor->next, _new_node, sizeof(abt_node_t)); memcpy((unsigned char *) cursor->next + sizeof(abt_node_t), insert_pt, sizeof(abt_node_t)); memcpy((unsigned char *) cursor->key + tree->k_s, insert_key, tree->k_s); finished = 1; } } free(insert_key); insert_key = NULL; stack_destructor(path); } void abt_delete(abt_t *tree, void *key) { if (!tree) return; abt_node_t *cursor = tree->root; stack_t *bsi = stack_constructor((void *) free); stack_t *path = stack_constructor(NULL); while (cursor->height) { uint32_t right = cursor->degree; uint32_t left = 0; int keys_difference; uint32_t mid; while (right > left + 1) { mid = (right + left) / 2; keys_difference = memcmp(key, (unsigned char *) cursor->key + tree->k_s * mid, tree->k_s); if (keys_difference < 0) right = mid; else left = mid; } uint32_t *idx = malloc(sizeof(uint32_t)); *idx = left; stack_push(bsi, idx); stack_push(path, cursor); cursor = ((void *) ((unsigned char *) cursor->next + sizeof(abt_node_t) * left)); } uint32_t i = 0; for (i = 0; i < cursor->degree; i++) { if (memcmp(key, (unsigned char *) cursor->key + tree->k_s * i, tree->k_s) == 0) break; } if (i == cursor->degree) return; for (cursor->degree--; i < cursor->degree; i++) { memswp((unsigned char *) cursor->next + i * (cursor->height ? sizeof(abt_node_t) : tree->v_s), (unsigned char *) cursor->next + (i + 1) * (cursor->height ? sizeof(abt_node_t) : tree->v_s), tree->v_s); memswp((unsigned char *) cursor->key + i * tree->k_s, (unsigned char *) cursor->key + (i + 1) * tree->k_s, tree->k_s); } unsigned char finished = 0; abt_node_t *temp_node_pt; while (!finished) { if (cursor->degree >= tree->a) { finished = 1; break; } if (stack_is_empty(path)) { if (cursor->degree >= 2 || cursor->height == 0) finished = 1; else { // a temp_node_pt = cursor->next; for (i = 0; i < temp_node_pt->degree; i++) { memcpy((unsigned char *) cursor->next + (temp_node_pt->height ? sizeof(abt_node_t) : tree->v_s) * i, (unsigned char *) temp_node_pt->next + (temp_node_pt->height ? sizeof(abt_node_t) : tree->v_s) * i, tree->v_s); memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) temp_node_pt->key + tree->k_s * i, tree->k_s); } cursor->degree = temp_node_pt->degree; cursor->height = temp_node_pt->height; free_node(temp_node_pt); finished = 1; } } else { abt_node_t *parent, *sibling; uint32_t *index = malloc(sizeof(uint32_t)); uint32_t j; parent = stack_pop(path); index = stack_pop(bsi); unsigned char cursor_is_leaf = 0; if (*index < parent->degree - 1) { sibling = ((void *) ((unsigned char *) parent->next + sizeof(abt_node_t) * ((*index) + 1))); if (sibling->degree > tree->a) { i = cursor->degree; if (cursor->height) { memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) parent->key + tree->k_s * ((*index) + 1), tree->k_s); } else { memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) sibling->key, tree->k_s); memcpy((unsigned char *) sibling->key, (unsigned char *) sibling->key + tree->k_s, tree->k_s); cursor_is_leaf = !cursor_is_leaf; } memcpy((unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * i, (unsigned char *) sibling->next, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); memcpy((unsigned char *) parent->key + tree->k_s * ((*index) + 1), (unsigned char *) sibling->key + tree->k_s, tree->k_s); memcpy((unsigned char *) sibling->next, (unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)), (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); for (j = 2; j < sibling->degree; j++) { memcpy((unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * (j - 1), (unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * j, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); memcpy((unsigned char *) sibling->key + tree->k_s * (j - 1), (unsigned char *) sibling->key + tree->k_s * j, tree->k_s); } sibling->degree--; cursor->degree++; finished = 1; } else { i = cursor->degree; if (cursor->height) { memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) parent->key + tree->k_s * ((*index) + 1), tree->k_s); } else { memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) sibling->key, tree->k_s); cursor_is_leaf = 1; } memcpy((unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * i, sibling->next, cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)); for (j = 1; j < sibling->degree; j++) { memcpy((unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * ++i, (unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * j, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); memcpy((unsigned char *) cursor->key + tree->k_s * i, (unsigned char *) sibling->key + tree->k_s * j, tree->k_s); } cursor->degree = i + 1; free_node(sibling); parent->degree--; for (i = (*index) + 1; i < parent->degree; i++) { memswp((unsigned char *) parent->next + sizeof(abt_node_t) * i, (unsigned char *) parent->next + sizeof(abt_node_t) * (i + 1), sizeof(abt_node_t)); memswp((unsigned char *) parent->key + tree->k_s * i, (unsigned char *) parent->key + tree->k_s * (i + 1), tree->k_s); i++; } cursor = parent; } } else { sibling = ((void *) ((unsigned char *) parent->next + sizeof(abt_node_t) * ((*index) - 1))); cursor_is_leaf = !cursor->height; if (sibling->degree > tree->a) { for (j = cursor->degree; j > 1; j--) { memcpy((unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * j, (unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * (j - 1), (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); memcpy((unsigned char *) cursor->key + tree->k_s * j, (unsigned char *) cursor->key + tree->k_s * (j - 1), tree->k_s); } memcpy((unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)), (unsigned char *) cursor->next, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); i = sibling->degree; memcpy((unsigned char *) cursor->next, (unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * (i - 1), (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); if (cursor->height) { memcpy((unsigned char *) cursor->key + tree->k_s, (unsigned char *) parent->key + tree->k_s * *index, tree->k_s); } else { memcpy((unsigned char *) cursor->key + tree->k_s, (unsigned char *) cursor->key, tree->k_s); memcpy((unsigned char *) cursor->key, (unsigned char *) sibling->key + tree->k_s * (i - 1), tree->k_s); } memcpy((unsigned char *) parent->key + tree->k_s * *index, (unsigned char *) sibling->key + tree->k_s * (i - 1), tree->k_s); sibling->degree--; cursor->degree++; finished = 1; } else { i = sibling->degree; if (cursor->height) { memcpy((unsigned char *) sibling->key + tree->k_s * i, (unsigned char *) parent->key + tree->k_s * *index, tree->k_s); } else { memcpy((unsigned char *) sibling->key + tree->k_s * i, (unsigned char *) cursor->key, tree->k_s); } memcpy((unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * i, (unsigned char *) cursor->next, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); for (j = 1; j < cursor->degree; j++) { memcpy((unsigned char *) sibling->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * ++i, (unsigned char *) cursor->next + (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t)) * j, (cursor_is_leaf ? tree->v_s : sizeof(abt_node_t))); memcpy((unsigned char *) sibling->key + tree->k_s * i, (unsigned char *) cursor->next + tree->k_s * j, tree->k_s); } sibling->degree = i + 1; free_node(cursor); parent->degree--; cursor = parent; } } free(index); } } stack_destructor(path); stack_destructor(bsi); } void *abt_get_node_key(abt_node_t *node); abt_node_t *abt_new_node(abt_t *tree, uint32_t height, uint32_t degree) { abt_node_t *new_node = malloc(sizeof(*new_node)); if (!new_node) return NULL; new_node->height = 0; new_node->degree = 0; new_node->key = malloc(4 * 4); new_node->next = malloc(8 * 4); return new_node; } static void free_node(abt_node_t *node) { if (node && node->key) { free(node->key); node->key = NULL; } if (node && node->next) { free(node->next); node->next = NULL; } if (node) { free(node); node = NULL; } } void *abt_node_get_key(abt_node_t *node); void abt_draw(abt_t *tree, FILE *stream); static void memswp(void *a, void *b, size_t size) { if (a == b) return; register unsigned char t; while (size--) { t = *(unsigned char *)a; *(unsigned char *)a++ = *(unsigned char *) b; *(unsigned char *)b++ = t; } }
262098.c
#include <u.h> #include <libc.h> #include <fcall.h> /* * Rather than reading /adm/users, which is a lot of work for * a toy program, we assume all groups have the form * NNN:user:user: * meaning that each user is the leader of his own group. */ enum { OPERM = 0x3, /* mask of all permission types in open mode */ Nram = 2048, Maxsize = 512*1024*1024, Maxfdata = 8192 }; typedef struct Fid Fid; typedef struct Ram Ram; struct Fid { short busy; short open; short rclose; int fid; Fid *next; char *user; Ram *ram; }; struct Ram { short busy; short open; long parent; /* index in Ram array */ Qid qid; long perm; char *name; ulong atime; ulong mtime; char *user; char *group; char *muid; char *data; long ndata; }; enum { Pexec = 1, Pwrite = 2, Pread = 4, Pother = 1, Pgroup = 8, Powner = 64 }; ulong path; /* incremented for each new file */ Fid *fids; Ram ram[Nram]; int nram; int mfd[2]; char *user; uchar mdata[IOHDRSZ+Maxfdata]; uchar rdata[Maxfdata]; /* buffer for data in reply */ uchar statbuf[STATMAX]; Fcall thdr; Fcall rhdr; int messagesize = sizeof mdata; Fid * newfid(int); uint ramstat(Ram*, uchar*, uint); void error(char*); void io(void); void *erealloc(void*, ulong); void *emalloc(ulong); char *estrdup(char*); void usage(void); int perm(Fid*, Ram*, int); char *rflush(Fid*), *rversion(Fid*), *rauth(Fid*), *rattach(Fid*), *rwalk(Fid*), *ropen(Fid*), *rcreate(Fid*), *rread(Fid*), *rwrite(Fid*), *rclunk(Fid*), *rremove(Fid*), *rstat(Fid*), *rwstat(Fid*); char *(*fcalls[Tmax])(Fid*); static void initfcalls(void) { fcalls[Tversion]= rversion; fcalls[Tflush]= rflush; fcalls[Tauth]= rauth; fcalls[Tattach]= rattach; fcalls[Twalk]= rwalk; fcalls[Topen]= ropen; fcalls[Tcreate]= rcreate; fcalls[Tread]= rread; fcalls[Twrite]= rwrite; fcalls[Tclunk]= rclunk; fcalls[Tremove]= rremove; fcalls[Tstat]= rstat; fcalls[Twstat]= rwstat; } char Eperm[] = "permission denied"; char Enotdir[] = "not a directory"; char Enoauth[] = "ramfs: authentication not required"; char Enotexist[] = "file does not exist"; char Einuse[] = "file in use"; char Eexist[] = "file exists"; char Eisdir[] = "file is a directory"; char Enotowner[] = "not owner"; char Eisopen[] = "file already open for I/O"; char Excl[] = "exclusive use file already open"; char Ename[] = "illegal name"; char Eversion[] = "unknown 9P version"; char Enotempty[] = "directory not empty"; char Ebadfid[] = "bad fid"; int debug; int private; void notifyf(void *a, char *s) { USED(a); if(strncmp(s, "interrupt", 9) == 0) noted(NCONT); noted(NDFLT); } void main(int argc, char *argv[]) { Ram *r; char *defmnt; int p[2]; int stdio = 0; char *service; initfcalls(); service = "ramfs"; defmnt = nil; ARGBEGIN{ case 'D': debug = 1; break; case 'i': defmnt = 0; stdio = 1; mfd[0] = 0; mfd[1] = 1; break; case 's': defmnt = nil; break; case 'm': defmnt = ARGF(); break; case 'p': private++; break; case 'S': defmnt = 0; service = EARGF(usage()); break; default: usage(); }ARGEND USED(defmnt); if(pipe(p) < 0) error("pipe failed"); if(!stdio){ mfd[0] = p[0]; mfd[1] = p[0]; if(post9pservice(p[1], service, nil) < 0) sysfatal("post9pservice %s: %r", service); } user = getuser(); notify(notifyf); nram = 2; r = &ram[0]; r->busy = 1; r->data = 0; r->ndata = 0; r->perm = DMDIR | 0775; r->qid.type = QTDIR; r->qid.path = 0; r->qid.vers = 0; r->parent = 0; r->user = user; r->group = user; r->muid = user; r->atime = time(0); r->mtime = r->atime; r->name = estrdup("."); r = &ram[1]; r->busy = 1; r->data = 0; r->ndata = 0; r->perm = 0666; r->qid.type = 0; r->qid.path = 1; r->qid.vers = 0; r->parent = 0; r->user = user; r->group = user; r->muid = user; r->atime = time(0); r->mtime = r->atime; r->name = estrdup("file"); if(debug) fmtinstall('F', fcallfmt); switch(rfork(RFFDG|RFPROC|RFNAMEG|RFNOTEG)){ case -1: error("fork"); case 0: close(p[1]); io(); break; default: close(p[0]); /* don't deadlock if child fails */ } exits(0); } char* rversion(Fid *x) { Fid *f; USED(x); for(f = fids; f; f = f->next) if(f->busy) rclunk(f); if(thdr.msize > sizeof mdata) rhdr.msize = sizeof mdata; else rhdr.msize = thdr.msize; messagesize = rhdr.msize; if(strncmp(thdr.version, "9P2000", 6) != 0) return Eversion; rhdr.version = "9P2000"; return 0; } char* rauth(Fid *x) { if(x->busy) return Ebadfid; return "ramfs: no authentication required"; } char* rflush(Fid *f) { USED(f); return 0; } char* rattach(Fid *f) { /* no authentication! */ if(f->busy) return Ebadfid; f->busy = 1; f->rclose = 0; f->ram = &ram[0]; rhdr.qid = f->ram->qid; if(thdr.uname[0]) f->user = estrdup(thdr.uname); else f->user = "none"; if(strcmp(user, "none") == 0) user = f->user; return 0; } char* xclone(Fid *f, Fid **nf) { if(!f->busy) return Ebadfid; if(f->open) return Eisopen; if(f->ram->busy == 0) return Enotexist; *nf = newfid(thdr.newfid); (*nf)->busy = 1; (*nf)->open = 0; (*nf)->rclose = 0; (*nf)->ram = f->ram; (*nf)->user = f->user; /* no ref count; the leakage is minor */ return 0; } char* rwalk(Fid *f) { Ram *r, *fram; char *name; Ram *parent; Fid *nf; char *err; ulong t; int i; if(!f->busy) return Ebadfid; err = nil; nf = nil; rhdr.nwqid = 0; if(thdr.newfid != thdr.fid){ err = xclone(f, &nf); if(err) return err; f = nf; /* walk the new fid */ } fram = f->ram; if(thdr.nwname > 0){ t = time(0); for(i=0; i<thdr.nwname && i<MAXWELEM; i++){ if((fram->qid.type & QTDIR) == 0){ err = Enotdir; break; } if(fram->busy == 0){ err = Enotexist; break; } fram->atime = t; name = thdr.wname[i]; if(strcmp(name, ".") == 0){ Found: rhdr.nwqid++; rhdr.wqid[i] = fram->qid; continue; } parent = &ram[fram->parent]; if(!perm(f, parent, Pexec)){ err = Eperm; break; } if(strcmp(name, "..") == 0){ fram = parent; goto Found; } for(r=ram; r < &ram[nram]; r++) if(r->busy && r->parent==fram-ram && strcmp(name, r->name)==0){ fram = r; goto Found; } break; } if(i==0 && err == nil) err = Enotexist; } if(nf != nil && (err!=nil || rhdr.nwqid<thdr.nwname)){ /* clunk the new fid, which is the one we walked */ fprint(2, "f %d zero busy\n", f->fid); f->busy = 0; f->ram = nil; } if(rhdr.nwqid == thdr.nwname) /* update the fid after a successful walk */ f->ram = fram; assert(f->busy); return err; } char * ropen(Fid *f) { Ram *r; int mode, trunc; if(!f->busy) return Ebadfid; if(f->open) return Eisopen; r = f->ram; if(r->busy == 0) return Enotexist; if(r->perm & DMEXCL) if(r->open) return Excl; mode = thdr.mode; if(r->qid.type & QTDIR){ if(mode != OREAD) return Eperm; rhdr.qid = r->qid; return 0; } if(mode & ORCLOSE){ /* can't remove root; must be able to write parent */ if(r->qid.path==0 || !perm(f, &ram[r->parent], Pwrite)) return Eperm; f->rclose = 1; } trunc = mode & OTRUNC; mode &= OPERM; if(mode==OWRITE || mode==ORDWR || trunc) if(!perm(f, r, Pwrite)) return Eperm; if(mode==OREAD || mode==ORDWR) if(!perm(f, r, Pread)) return Eperm; if(mode==OEXEC) if(!perm(f, r, Pexec)) return Eperm; if(trunc && (r->perm&DMAPPEND)==0){ r->ndata = 0; if(r->data) free(r->data); r->data = 0; r->qid.vers++; } rhdr.qid = r->qid; rhdr.iounit = messagesize-IOHDRSZ; f->open = 1; r->open++; return 0; } char * rcreate(Fid *f) { Ram *r; char *name; long parent, prm; if(!f->busy) return Ebadfid; if(f->open) return Eisopen; if(f->ram->busy == 0) return Enotexist; parent = f->ram - ram; if((f->ram->qid.type&QTDIR) == 0) return Enotdir; /* must be able to write parent */ if(!perm(f, f->ram, Pwrite)) return Eperm; prm = thdr.perm; name = thdr.name; if(strcmp(name, ".")==0 || strcmp(name, "..")==0) return Ename; for(r=ram; r<&ram[nram]; r++) if(r->busy && parent==r->parent) if(strcmp((char*)name, r->name)==0) return Einuse; for(r=ram; r->busy; r++) if(r == &ram[Nram-1]) return "no free ram resources"; r->busy = 1; r->qid.path = ++path; r->qid.vers = 0; if(prm & DMDIR) r->qid.type |= QTDIR; r->parent = parent; free(r->name); r->name = estrdup(name); r->user = f->user; r->group = f->ram->group; r->muid = f->ram->muid; if(prm & DMDIR) prm = (prm&~0777) | (f->ram->perm&prm&0777); else prm = (prm&(~0777|0111)) | (f->ram->perm&prm&0666); r->perm = prm; r->ndata = 0; if(r-ram >= nram) nram = r - ram + 1; r->atime = time(0); r->mtime = r->atime; f->ram->mtime = r->atime; f->ram = r; rhdr.qid = r->qid; rhdr.iounit = messagesize-IOHDRSZ; f->open = 1; if(thdr.mode & ORCLOSE) f->rclose = 1; r->open++; return 0; } char* rread(Fid *f) { Ram *r; uchar *buf; long off; int n, m, cnt; if(!f->busy) return Ebadfid; if(f->ram->busy == 0) return Enotexist; n = 0; rhdr.count = 0; off = thdr.offset; buf = rdata; cnt = thdr.count; if(cnt > messagesize) /* shouldn't happen, anyway */ cnt = messagesize; if(f->ram->qid.type & QTDIR){ for(r=ram+1; off > 0; r++){ if(r->busy && r->parent==f->ram-ram) off -= ramstat(r, statbuf, sizeof statbuf); if(r == &ram[nram-1]) return 0; } for(; r<&ram[nram] && n < cnt; r++){ if(!r->busy || r->parent!=f->ram-ram) continue; m = ramstat(r, buf+n, cnt-n); if(m == 0) break; n += m; } rhdr.data = (char*)rdata; rhdr.count = n; return 0; } r = f->ram; if(off >= r->ndata) return 0; r->atime = time(0); n = cnt; if(off+n > r->ndata) n = r->ndata - off; rhdr.data = r->data+off; rhdr.count = n; return 0; } char* rwrite(Fid *f) { Ram *r; ulong off; int cnt; r = f->ram; if(!f->busy) return Ebadfid; if(r->busy == 0) return Enotexist; off = thdr.offset; if(r->perm & DMAPPEND) off = r->ndata; cnt = thdr.count; if(r->qid.type & QTDIR) return Eisdir; if(off+cnt >= Maxsize) /* sanity check */ return "write too big"; if(off+cnt > r->ndata) r->data = erealloc(r->data, off+cnt); if(off > r->ndata) memset(r->data+r->ndata, 0, off-r->ndata); if(off+cnt > r->ndata) r->ndata = off+cnt; memmove(r->data+off, thdr.data, cnt); r->qid.vers++; r->mtime = time(0); rhdr.count = cnt; return 0; } static int emptydir(Ram *dr) { long didx = dr - ram; Ram *r; for(r=ram; r<&ram[nram]; r++) if(r->busy && didx==r->parent) return 0; return 1; } char * realremove(Ram *r) { if(r->qid.type & QTDIR && !emptydir(r)) return Enotempty; r->ndata = 0; if(r->data) free(r->data); r->data = 0; r->parent = 0; memset(&r->qid, 0, sizeof r->qid); free(r->name); r->name = nil; r->busy = 0; return nil; } char * rclunk(Fid *f) { char *e = nil; if(f->open) f->ram->open--; if(f->rclose) e = realremove(f->ram); fprint(2, "clunk fid %d busy=%d\n", f->fid, f->busy); fprint(2, "f %d zero busy\n", f->fid); f->busy = 0; f->open = 0; f->ram = 0; return e; } char * rremove(Fid *f) { Ram *r; if(f->open) f->ram->open--; fprint(2, "f %d zero busy\n", f->fid); f->busy = 0; f->open = 0; r = f->ram; f->ram = 0; if(r->qid.path == 0 || !perm(f, &ram[r->parent], Pwrite)) return Eperm; ram[r->parent].mtime = time(0); return realremove(r); } char * rstat(Fid *f) { if(!f->busy) return Ebadfid; if(f->ram->busy == 0) return Enotexist; rhdr.nstat = ramstat(f->ram, statbuf, sizeof statbuf); rhdr.stat = statbuf; return 0; } char * rwstat(Fid *f) { Ram *r, *s; Dir dir; if(!f->busy) return Ebadfid; if(f->ram->busy == 0) return Enotexist; convM2D(thdr.stat, thdr.nstat, &dir, (char*)statbuf); r = f->ram; /* * To change length, must have write permission on file. */ if(dir.length!=~0 && dir.length!=r->ndata){ if(!perm(f, r, Pwrite)) return Eperm; } /* * To change name, must have write permission in parent * and name must be unique. */ if(dir.name[0]!='\0' && strcmp(dir.name, r->name)!=0){ if(!perm(f, &ram[r->parent], Pwrite)) return Eperm; for(s=ram; s<&ram[nram]; s++) if(s->busy && s->parent==r->parent) if(strcmp(dir.name, s->name)==0) return Eexist; } /* * To change mode, must be owner or group leader. * Because of lack of users file, leader=>group itself. */ if(dir.mode!=~0 && r->perm!=dir.mode){ if(strcmp(f->user, r->user) != 0) if(strcmp(f->user, r->group) != 0) return Enotowner; } /* * To change group, must be owner and member of new group, * or leader of current group and leader of new group. * Second case cannot happen, but we check anyway. */ if(dir.gid[0]!='\0' && strcmp(r->group, dir.gid)!=0){ if(strcmp(f->user, r->user) == 0) /* if(strcmp(f->user, dir.gid) == 0) */ goto ok; if(strcmp(f->user, r->group) == 0) if(strcmp(f->user, dir.gid) == 0) goto ok; return Enotowner; ok:; } /* all ok; do it */ if(dir.mode != ~0){ dir.mode &= ~DMDIR; /* cannot change dir bit */ dir.mode |= r->perm&DMDIR; r->perm = dir.mode; } if(dir.name[0] != '\0'){ free(r->name); r->name = estrdup(dir.name); } if(dir.gid[0] != '\0') r->group = estrdup(dir.gid); if(dir.length!=~0 && dir.length!=r->ndata){ r->data = erealloc(r->data, dir.length); if(r->ndata < dir.length) memset(r->data+r->ndata, 0, dir.length-r->ndata); r->ndata = dir.length; } ram[r->parent].mtime = time(0); return 0; } uint ramstat(Ram *r, uchar *buf, uint nbuf) { int n; Dir dir; dir.name = r->name; dir.qid = r->qid; dir.mode = r->perm; dir.length = r->ndata; dir.uid = r->user; dir.gid = r->group; dir.muid = r->muid; dir.atime = r->atime; dir.mtime = r->mtime; n = convD2M(&dir, buf, nbuf); if(n > 2) return n; return 0; } Fid * newfid(int fid) { Fid *f, *ff; ff = 0; for(f = fids; f; f = f->next) if(f->fid == fid) return f; else if(!ff && !f->busy) ff = f; if(ff){ ff->fid = fid; return ff; } f = emalloc(sizeof *f); f->ram = nil; f->fid = fid; f->next = fids; fids = f; return f; } void io(void) { char *err, buf[20]; int n, pid, ctl; pid = getpid(); if(private){ snprint(buf, sizeof buf, "/proc/%d/ctl", pid); ctl = open(buf, OWRITE); if(ctl < 0){ fprint(2, "can't protect ramfs\n"); }else{ fprint(ctl, "noswap\n"); fprint(ctl, "private\n"); close(ctl); } } for(;;){ /* * reading from a pipe or a network device * will give an error after a few eof reads. * however, we cannot tell the difference * between a zero-length read and an interrupt * on the processes writing to us, * so we wait for the error. */ n = read9pmsg(mfd[0], mdata, messagesize); if(n < 0) error("mount read"); if(n == 0) error("mount eof"); if(convM2S(mdata, n, &thdr) == 0) continue; if(debug) fprint(2, "ramfs %d:<-%F\n", pid, &thdr); if(!fcalls[thdr.type]) err = "bad fcall type"; else err = (*fcalls[thdr.type])(newfid(thdr.fid)); if(err){ rhdr.type = Rerror; rhdr.ename = err; }else{ rhdr.type = thdr.type + 1; rhdr.fid = thdr.fid; } rhdr.tag = thdr.tag; if(debug) fprint(2, "ramfs %d:->%F\n", pid, &rhdr);/**/ n = convS2M(&rhdr, mdata, messagesize); if(n == 0) error("convS2M error on write"); if(write(mfd[1], mdata, n) != n) error("mount write"); } } int perm(Fid *f, Ram *r, int p) { if((p*Pother) & r->perm) return 1; if(strcmp(f->user, r->group)==0 && ((p*Pgroup) & r->perm)) return 1; if(strcmp(f->user, r->user)==0 && ((p*Powner) & r->perm)) return 1; return 0; } void error(char *s) { fprint(2, "%s: %s: %r\n", argv0, s); exits(s); } void * emalloc(ulong n) { void *p; p = malloc(n); if(!p) error("out of memory"); memset(p, 0, n); return p; } void * erealloc(void *p, ulong n) { p = realloc(p, n); if(!p) error("out of memory"); return p; } char * estrdup(char *q) { char *p; int n; n = strlen(q)+1; p = malloc(n); if(!p) error("out of memory"); memmove(p, q, n); return p; } void usage(void) { fprint(2, "usage: %s [-is] [-m mountpoint]\n", argv0); exits("usage"); }
986890.c
/* Generated by Cython 0.24 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_24" #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if !defined(CYTHON_USE_PYLONG_INTERNALS) && CYTHON_COMPILING_IN_CPYTHON && PY_VERSION_HEX >= 0x02070000 #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #elif CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__facedist #define __PYX_HAVE_API__facedist #include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "math.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) && defined (_M_X64) #define __Pyx_sst_abs(value) _abs64(value) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* None.proto */ #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "facedist.pyx", "__init__.pxd", "type.pxd", }; /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":725 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":726 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":727 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":732 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":733 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":734 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":739 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":740 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":749 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":750 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":754 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":755 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":757 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":760 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":761 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":762 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* None.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif /* None.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif /*--- Type declarations ---*/ /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":764 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":765 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":766 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* ArgTypeTest.proto */ static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); /* GetModuleGlobalName.proto */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /* None.proto */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFormatCheck.proto */ static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); // PROTO /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* GetItemInt.proto */ #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) :\ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) :\ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck)\ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ?\ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) :\ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); /* PyObjectCallMethO.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif /* PyObjectCallOneArg.proto */ static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) /* PyThreadStateGet.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = PyThreadState_GET(); #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #endif /* PyErrFetchRestore.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* ImportFrom.proto */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name); /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* None.proto */ static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; /* None.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(__cplusplus) && CYTHON_CCOMPLEX && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif /* None.proto */ static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* None.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eqf(a, b) ((a)==(b)) #define __Pyx_c_sumf(a, b) ((a)+(b)) #define __Pyx_c_difff(a, b) ((a)-(b)) #define __Pyx_c_prodf(a, b) ((a)*(b)) #define __Pyx_c_quotf(a, b) ((a)/(b)) #define __Pyx_c_negf(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zerof(z) ((z)==(float)0) #define __Pyx_c_conjf(z) (::std::conj(z)) #if 1 #define __Pyx_c_absf(z) (::std::abs(z)) #define __Pyx_c_powf(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zerof(z) ((z)==0) #define __Pyx_c_conjf(z) (conjf(z)) #if 1 #define __Pyx_c_absf(z) (cabsf(z)) #define __Pyx_c_powf(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* None.proto */ static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /* None.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq(a, b) ((a)==(b)) #define __Pyx_c_sum(a, b) ((a)+(b)) #define __Pyx_c_diff(a, b) ((a)-(b)) #define __Pyx_c_prod(a, b) ((a)*(b)) #define __Pyx_c_quot(a, b) ((a)/(b)) #define __Pyx_c_neg(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero(z) ((z)==(double)0) #define __Pyx_c_conj(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs(z) (::std::abs(z)) #define __Pyx_c_pow(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero(z) ((z)==0) #define __Pyx_c_conj(z) (conj(z)) #if 1 #define __Pyx_c_abs(z) (cabs(z)) #define __Pyx_c_pow(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'cython' */ /* Module declarations from 'libc.math' */ /* Module declarations from 'facedist' */ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "facedist" int __pyx_module_is_main_facedist = 0; /* Implementation of 'facedist' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_RuntimeError; static const char __pyx_k_A[] = "A"; static const char __pyx_k_D[] = "D"; static const char __pyx_k_ii[] = "ii"; static const char __pyx_k_jj[] = "jj"; static const char __pyx_k_nn[] = "nn"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_rd[] = "rd"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mean[] = "mean"; static const char __pyx_k_ncol[] = "ncol"; static const char __pyx_k_nrow[] = "nrow"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_cdist[] = "cdist"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_metric[] = "metric"; static const char __pyx_k_float64[] = "float64"; static const char __pyx_k_facedist[] = "facedist"; static const char __pyx_k_euclidean[] = "euclidean"; static const char __pyx_k_mean_dist[] = "mean_dist"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_dok_matrix[] = "dok_matrix"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_scipy_sparse[] = "scipy.sparse"; static const char __pyx_k_scipy_spatial_distance[] = "scipy.spatial.distance"; static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static const char __pyx_k_home_mlode_BA_Moritz_Implementa[] = "/home/mlode/BA-Moritz/Implementation/src/face_recognition/cython_sparse_arr/facedist.pyx"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_A; static PyObject *__pyx_n_s_D; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_cdist; static PyObject *__pyx_n_s_dok_matrix; static PyObject *__pyx_n_s_euclidean; static PyObject *__pyx_n_s_facedist; static PyObject *__pyx_n_s_float64; static PyObject *__pyx_kp_s_home_mlode_BA_Moritz_Implementa; static PyObject *__pyx_n_s_ii; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_jj; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mean; static PyObject *__pyx_n_s_mean_dist; static PyObject *__pyx_n_s_metric; static PyObject *__pyx_n_s_ncol; static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; static PyObject *__pyx_n_s_nn; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_nrow; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_rd; static PyObject *__pyx_n_s_scipy_sparse; static PyObject *__pyx_n_s_scipy_spatial_distance; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_8facedist_mean_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_A); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_codeobj__8; /* "facedist.pyx":21 * # indices. * @cython.wraparound(False) * def mean_dist(np.ndarray A): # <<<<<<<<<<<<<< * * # declare C types for as many of our variables as possible. note that we */ /* Python wrapper */ static PyObject *__pyx_pw_8facedist_1mean_dist(PyObject *__pyx_self, PyObject *__pyx_v_A); /*proto*/ static PyMethodDef __pyx_mdef_8facedist_1mean_dist = {"mean_dist", (PyCFunction)__pyx_pw_8facedist_1mean_dist, METH_O, 0}; static PyObject *__pyx_pw_8facedist_1mean_dist(PyObject *__pyx_self, PyObject *__pyx_v_A) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("mean_dist (wrapper)", 0); if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_A), __pyx_ptype_5numpy_ndarray, 1, "A", 0))) __PYX_ERR(0, 21, __pyx_L1_error) __pyx_r = __pyx_pf_8facedist_mean_dist(__pyx_self, ((PyArrayObject *)__pyx_v_A)); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_8facedist_mean_dist(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_A) { Py_ssize_t __pyx_v_nrow; CYTHON_UNUSED Py_ssize_t __pyx_v_ncol; Py_ssize_t __pyx_v_ii; Py_ssize_t __pyx_v_jj; Py_ssize_t __pyx_v_nn; PyArrayObject *__pyx_v_D = 0; __pyx_t_5numpy_float64_t __pyx_v_rd; __Pyx_LocalBuf_ND __pyx_pybuffernd_D; __Pyx_Buffer __pyx_pybuffer_D; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; PyObject *__pyx_t_7 = NULL; PyArrayObject *__pyx_t_8 = NULL; Py_ssize_t __pyx_t_9; Py_ssize_t __pyx_t_10; Py_ssize_t __pyx_t_11; Py_ssize_t __pyx_t_12; __pyx_t_5numpy_float64_t __pyx_t_13; Py_ssize_t __pyx_t_14; __Pyx_RefNannySetupContext("mean_dist", 0); __pyx_pybuffer_D.pybuffer.buf = NULL; __pyx_pybuffer_D.refcount = 0; __pyx_pybuffernd_D.data = NULL; __pyx_pybuffernd_D.rcbuffer = &__pyx_pybuffer_D; /* "facedist.pyx":27 * cdef: * # Py_ssize_t is just a special platform-specific type for indices * Py_ssize_t nrow = A.shape[0] # <<<<<<<<<<<<<< * Py_ssize_t ncol = A.shape[1] * Py_ssize_t ii, jj, nn */ __pyx_v_nrow = (__pyx_v_A->dimensions[0]); /* "facedist.pyx":28 * # Py_ssize_t is just a special platform-specific type for indices * Py_ssize_t nrow = A.shape[0] * Py_ssize_t ncol = A.shape[1] # <<<<<<<<<<<<<< * Py_ssize_t ii, jj, nn * */ __pyx_v_ncol = (__pyx_v_A->dimensions[1]); /* "facedist.pyx":33 * # this line is particularly expensive, since creating a numpy array * # involves unavoidable Python API overhead * np.ndarray[np.float64_t, ndim=1] D = np.zeros( (nrow*(nrow-1)/2), np.float64) # <<<<<<<<<<<<<< * * np.float64_t rd */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyInt_FromSsize_t(__Pyx_div_Py_ssize_t((__pyx_v_nrow * (__pyx_v_nrow - 1)), 2)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_float64); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; __pyx_t_6 = 0; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); __pyx_t_6 = 1; } } __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); if (__pyx_t_4) { __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); __pyx_t_4 = NULL; } __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_t_5); __pyx_t_2 = 0; __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 33, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 33, __pyx_L1_error) __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_D.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) { __pyx_v_D = ((PyArrayObject *)Py_None); __Pyx_INCREF(Py_None); __pyx_pybuffernd_D.rcbuffer->pybuffer.buf = NULL; __PYX_ERR(0, 33, __pyx_L1_error) } else {__pyx_pybuffernd_D.diminfo[0].strides = __pyx_pybuffernd_D.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_D.diminfo[0].shape = __pyx_pybuffernd_D.rcbuffer->pybuffer.shape[0]; } } __pyx_t_8 = 0; __pyx_v_D = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; /* "facedist.pyx":42 * * #with nogil: * for ii in prange(nrow, nogil=True, schedule='static', num_threads=24): # <<<<<<<<<<<<<< * for jj in range(ii + 1, nrow): * */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { __pyx_t_6 = __pyx_v_nrow; if (1 == 0) abort(); { Py_ssize_t __pyx_parallel_temp0 = 0xbad0bad0; Py_ssize_t __pyx_parallel_temp1 = 0xbad0bad0; Py_ssize_t __pyx_parallel_temp2 = 0xbad0bad0; __pyx_t_5numpy_float64_t __pyx_parallel_temp3 = __PYX_NAN(); const char *__pyx_parallel_filename = NULL; int __pyx_parallel_lineno = 0, __pyx_parallel_clineno = 0; PyObject *__pyx_parallel_exc_type = NULL, *__pyx_parallel_exc_value = NULL, *__pyx_parallel_exc_tb = NULL; int __pyx_parallel_why; __pyx_parallel_why = 0; #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_10 = (__pyx_t_6 - 0 + 1 - 1/abs(1)) / 1; if (__pyx_t_10 > 0) { #ifdef _OPENMP #pragma omp parallel num_threads(24) private(__pyx_t_11, __pyx_t_12, __pyx_t_13, __pyx_t_14) firstprivate(__pyx_t_1, __pyx_t_2, __pyx_t_3, __pyx_t_4, __pyx_t_5, __pyx_t_7) private(__pyx_filename, __pyx_lineno, __pyx_clineno) shared(__pyx_parallel_why, __pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb) #endif /* _OPENMP */ { #ifdef _OPENMP #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif Py_BEGIN_ALLOW_THREADS #endif /* _OPENMP */ #ifdef _OPENMP #pragma omp for firstprivate(__pyx_v_ii) lastprivate(__pyx_v_ii) lastprivate(__pyx_v_jj) lastprivate(__pyx_v_nn) lastprivate(__pyx_v_rd) schedule(static) #endif /* _OPENMP */ for (__pyx_t_9 = 0; __pyx_t_9 < __pyx_t_10; __pyx_t_9++){ if (__pyx_parallel_why < 2) { __pyx_v_ii = (Py_ssize_t)(0 + 1 * __pyx_t_9); /* Initialize private variables to invalid values */ __pyx_v_jj = ((Py_ssize_t)0xbad0bad0); __pyx_v_nn = ((Py_ssize_t)0xbad0bad0); __pyx_v_rd = ((__pyx_t_5numpy_float64_t)__PYX_NAN()); /* "facedist.pyx":43 * #with nogil: * for ii in prange(nrow, nogil=True, schedule='static', num_threads=24): * for jj in range(ii + 1, nrow): # <<<<<<<<<<<<<< * * with gil: */ __pyx_t_11 = __pyx_v_nrow; for (__pyx_t_12 = (__pyx_v_ii + 1); __pyx_t_12 < __pyx_t_11; __pyx_t_12+=1) { __pyx_v_jj = __pyx_t_12; /* "facedist.pyx":45 * for jj in range(ii + 1, nrow): * * with gil: # <<<<<<<<<<<<<< * rd = np.mean(cdist(A[ii], A[jj], metric='euclidean')) * nn = ii+jj*(jj-1)/2 */ { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif /*try:*/ { /* "facedist.pyx":46 * * with gil: * rd = np.mean(cdist(A[ii], A[jj], metric='euclidean')) # <<<<<<<<<<<<<< * nn = ii+jj*(jj-1)/2 * */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_mean); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_cdist); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = __Pyx_GetItemInt(((PyObject *)__pyx_v_A), __pyx_v_ii, Py_ssize_t, 1, PyInt_FromSsize_t, 0, 0, 0); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_2 = __Pyx_GetItemInt(((PyObject *)__pyx_v_A), __pyx_v_jj, Py_ssize_t, 1, PyInt_FromSsize_t, 0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyTuple_New(2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __pyx_t_5 = 0; __pyx_t_2 = 0; __pyx_t_2 = PyDict_New(); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_t_2, __pyx_n_s_metric, __pyx_n_s_euclidean) < 0) __PYX_ERR(0, 46, __pyx_L15_error) __pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_4, __pyx_t_2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = NULL; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_7))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); } } if (!__pyx_t_2) { __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_7, __pyx_t_5); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_GOTREF(__pyx_t_1); } else { __pyx_t_4 = PyTuple_New(1+1); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_2); __pyx_t_2 = NULL; __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0+1, __pyx_t_5); __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_13 = __pyx_PyFloat_AsDouble(__pyx_t_1); if (unlikely((__pyx_t_13 == (npy_float64)-1) && PyErr_Occurred())) __PYX_ERR(0, 46, __pyx_L15_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_v_rd = __pyx_t_13; /* "facedist.pyx":47 * with gil: * rd = np.mean(cdist(A[ii], A[jj], metric='euclidean')) * nn = ii+jj*(jj-1)/2 # <<<<<<<<<<<<<< * * D[nn] = rd */ __pyx_v_nn = (__pyx_v_ii + __Pyx_div_Py_ssize_t((__pyx_v_jj * (__pyx_v_jj - 1)), 2)); } /* "facedist.pyx":45 * for jj in range(ii + 1, nrow): * * with gil: # <<<<<<<<<<<<<< * rd = np.mean(cdist(A[ii], A[jj], metric='euclidean')) * nn = ii+jj*(jj-1)/2 */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif goto __pyx_L16; } __pyx_L15_error: { #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif goto __pyx_L8_error; } __pyx_L16:; } } /* "facedist.pyx":49 * nn = ii+jj*(jj-1)/2 * * D[nn] = rd # <<<<<<<<<<<<<< * * return D */ __pyx_t_14 = __pyx_v_nn; *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_D.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_D.diminfo[0].strides) = __pyx_v_rd; } goto __pyx_L18; __pyx_L8_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #ifdef _OPENMP #pragma omp flush(__pyx_parallel_exc_type) #endif /* _OPENMP */ if (!__pyx_parallel_exc_type) { __Pyx_ErrFetchWithState(&__pyx_parallel_exc_type, &__pyx_parallel_exc_value, &__pyx_parallel_exc_tb); __pyx_parallel_filename = __pyx_filename; __pyx_parallel_lineno = __pyx_lineno; __pyx_parallel_clineno = __pyx_clineno; __Pyx_GOTREF(__pyx_parallel_exc_type); } #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_parallel_why = 4; goto __pyx_L17; __pyx_L17:; #ifdef _OPENMP #pragma omp critical(__pyx_parallel_lastprivates0) #endif /* _OPENMP */ { __pyx_parallel_temp0 = __pyx_v_ii; __pyx_parallel_temp1 = __pyx_v_jj; __pyx_parallel_temp2 = __pyx_v_nn; __pyx_parallel_temp3 = __pyx_v_rd; } __pyx_L18:; #ifdef _OPENMP #pragma omp flush(__pyx_parallel_why) #endif /* _OPENMP */ } } #ifdef _OPENMP Py_END_ALLOW_THREADS #else { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #endif /* _OPENMP */ /* Clean up any temporaries */ __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = NULL; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = NULL; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = NULL; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = NULL; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = NULL; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = NULL; #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif #ifndef _OPENMP } #endif /* _OPENMP */ } } if (__pyx_parallel_exc_type) { /* This may have been overridden by a continue, break or return in another thread. Prefer the error. */ __pyx_parallel_why = 4; } if (__pyx_parallel_why) { __pyx_v_ii = __pyx_parallel_temp0; __pyx_v_jj = __pyx_parallel_temp1; __pyx_v_nn = __pyx_parallel_temp2; __pyx_v_rd = __pyx_parallel_temp3; switch (__pyx_parallel_why) { case 4: { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_GIVEREF(__pyx_parallel_exc_type); __Pyx_ErrRestoreWithState(__pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb); __pyx_filename = __pyx_parallel_filename; __pyx_lineno = __pyx_parallel_lineno; __pyx_clineno = __pyx_parallel_clineno; #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } goto __pyx_L4_error; } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "facedist.pyx":42 * * #with nogil: * for ii in prange(nrow, nogil=True, schedule='static', num_threads=24): # <<<<<<<<<<<<<< * for jj in range(ii + 1, nrow): * */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L4_error: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L1_error; } __pyx_L5:; } } /* "facedist.pyx":51 * D[nn] = rd * * return D # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_D)); __pyx_r = ((PyObject *)__pyx_v_D); goto __pyx_L0; /* "facedist.pyx":21 * # indices. * @cython.wraparound(False) * def mean_dist(np.ndarray A): # <<<<<<<<<<<<<< * * # declare C types for as many of our variables as possible. note that we */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_7); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_D.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("facedist.mean_dist", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_D.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_D); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":203 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":206 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":207 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":209 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":212 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ goto __pyx_L4; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ /*else*/ { __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":217 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 218, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":221 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 222, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":224 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":225 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":230 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":231 * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":232 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L11; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":236 * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":238 * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":242 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef int offset */ __pyx_v_f = NULL; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":250 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ goto __pyx_L14; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ /*else*/ { __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":258 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 259, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":257 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ switch (__pyx_v_t) { case NPY_BYTE: __pyx_v_f = ((char *)"b"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":261 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = ((char *)"B"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":262 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = ((char *)"h"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = ((char *)"H"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = ((char *)"i"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = ((char *)"I"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = ((char *)"l"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = ((char *)"L"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = ((char *)"q"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = ((char *)"Q"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = ((char *)"f"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = ((char *)"d"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = ((char *)"g"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = ((char *)"Zf"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = ((char *)"Zd"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = ((char *)"Zg"); break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = ((char *)"O"); break; default: /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 278, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 278, __pyx_L1_error) break; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * return * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)malloc(0xFF)); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) __PYX_ERR(1, 285, __pyx_L1_error) __pyx_v_f = __pyx_t_7; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = '\x00'; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":294 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":770 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":774 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 774, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":773 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":777 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 777, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":776 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 780, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":779 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 783, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":782 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":790 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * cdef dtype child * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(1, 794, __pyx_L1_error) } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 794, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 794, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 795, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":796 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - <int>(new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 796, __pyx_L1_error) } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 796, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 796, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 799, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":802 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_6) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 803, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":813 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 813, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":816 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":821 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 821, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(1, 823, __pyx_L1_error) /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 826, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":828 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 828, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":829 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 829, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":830 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 830, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":831 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 831, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 832, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 833, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 834, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 835, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 836, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 838, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 839, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 840, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 841, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 842, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 844, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 844, __pyx_L1_error) } __pyx_L15:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":849 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) __PYX_ERR(1, 849, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":785 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":969 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":968 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ goto __pyx_L3; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":971 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = <PyObject*>base * Py_XDECREF(arr.base) */ /*else*/ { Py_INCREF(__pyx_v_base); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":972 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":973 * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":974 * baseptr = <PyObject*>base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":966 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":978 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return <object>arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":977 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":980 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "facedist", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_A, __pyx_k_A, sizeof(__pyx_k_A), 0, 0, 1, 1}, {&__pyx_n_s_D, __pyx_k_D, sizeof(__pyx_k_D), 0, 0, 1, 1}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_cdist, __pyx_k_cdist, sizeof(__pyx_k_cdist), 0, 0, 1, 1}, {&__pyx_n_s_dok_matrix, __pyx_k_dok_matrix, sizeof(__pyx_k_dok_matrix), 0, 0, 1, 1}, {&__pyx_n_s_euclidean, __pyx_k_euclidean, sizeof(__pyx_k_euclidean), 0, 0, 1, 1}, {&__pyx_n_s_facedist, __pyx_k_facedist, sizeof(__pyx_k_facedist), 0, 0, 1, 1}, {&__pyx_n_s_float64, __pyx_k_float64, sizeof(__pyx_k_float64), 0, 0, 1, 1}, {&__pyx_kp_s_home_mlode_BA_Moritz_Implementa, __pyx_k_home_mlode_BA_Moritz_Implementa, sizeof(__pyx_k_home_mlode_BA_Moritz_Implementa), 0, 0, 1, 0}, {&__pyx_n_s_ii, __pyx_k_ii, sizeof(__pyx_k_ii), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_jj, __pyx_k_jj, sizeof(__pyx_k_jj), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mean, __pyx_k_mean, sizeof(__pyx_k_mean), 0, 0, 1, 1}, {&__pyx_n_s_mean_dist, __pyx_k_mean_dist, sizeof(__pyx_k_mean_dist), 0, 0, 1, 1}, {&__pyx_n_s_metric, __pyx_k_metric, sizeof(__pyx_k_metric), 0, 0, 1, 1}, {&__pyx_n_s_ncol, __pyx_k_ncol, sizeof(__pyx_k_ncol), 0, 0, 1, 1}, {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, {&__pyx_n_s_nn, __pyx_k_nn, sizeof(__pyx_k_nn), 0, 0, 1, 1}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_nrow, __pyx_k_nrow, sizeof(__pyx_k_nrow), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_rd, __pyx_k_rd, sizeof(__pyx_k_rd), 0, 0, 1, 1}, {&__pyx_n_s_scipy_sparse, __pyx_k_scipy_sparse, sizeof(__pyx_k_scipy_sparse), 0, 0, 1, 1}, {&__pyx_n_s_scipy_spatial_distance, __pyx_k_scipy_spatial_distance, sizeof(__pyx_k_scipy_spatial_distance), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 43, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(1, 218, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 799, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple_)) __PYX_ERR(1, 218, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 222, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 259, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":799 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 799, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "facedist.pyx":21 * # indices. * @cython.wraparound(False) * def mean_dist(np.ndarray A): # <<<<<<<<<<<<<< * * # declare C types for as many of our variables as possible. note that we */ __pyx_tuple__7 = PyTuple_Pack(8, __pyx_n_s_A, __pyx_n_s_nrow, __pyx_n_s_ncol, __pyx_n_s_ii, __pyx_n_s_jj, __pyx_n_s_nn, __pyx_n_s_D, __pyx_n_s_rd); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); __pyx_codeobj__8 = (PyObject*)__Pyx_PyCode_New(1, 0, 8, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__7, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_mlode_BA_Moritz_Implementa, __pyx_n_s_mean_dist, 21, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__8)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) __PYX_ERR(0, 1, __pyx_L1_error) if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC initfacedist(void); /*proto*/ PyMODINIT_FUNC initfacedist(void) #else PyMODINIT_FUNC PyInit_facedist(void); /*proto*/ PyMODINIT_FUNC PyInit_facedist(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_facedist(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("facedist", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_facedist) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "facedist")) { if (unlikely(PyDict_SetItemString(modules, "facedist", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(2, 9, __pyx_L1_error) __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) __PYX_ERR(1, 155, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) __PYX_ERR(1, 168, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) __PYX_ERR(1, 172, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) __PYX_ERR(1, 181, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) __PYX_ERR(1, 861, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "facedist.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * from scipy.spatial.distance import cdist * from scipy.sparse import dok_matrix */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "facedist.pyx":2 * import numpy as np * from scipy.spatial.distance import cdist # <<<<<<<<<<<<<< * from scipy.sparse import dok_matrix * cimport numpy as np */ __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(__pyx_n_s_cdist); __Pyx_GIVEREF(__pyx_n_s_cdist); PyList_SET_ITEM(__pyx_t_1, 0, __pyx_n_s_cdist); __pyx_t_2 = __Pyx_Import(__pyx_n_s_scipy_spatial_distance, __pyx_t_1, -1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_ImportFrom(__pyx_t_2, __pyx_n_s_cdist); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_cdist, __pyx_t_1) < 0) __PYX_ERR(0, 2, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "facedist.pyx":3 * import numpy as np * from scipy.spatial.distance import cdist * from scipy.sparse import dok_matrix # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ __pyx_t_2 = PyList_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_n_s_dok_matrix); __Pyx_GIVEREF(__pyx_n_s_dok_matrix); PyList_SET_ITEM(__pyx_t_2, 0, __pyx_n_s_dok_matrix); __pyx_t_1 = __Pyx_Import(__pyx_n_s_scipy_sparse, __pyx_t_2, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 3, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_ImportFrom(__pyx_t_1, __pyx_n_s_dok_matrix); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 3, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); if (PyDict_SetItem(__pyx_d, __pyx_n_s_dok_matrix, __pyx_t_2) < 0) __PYX_ERR(0, 3, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "facedist.pyx":21 * # indices. * @cython.wraparound(False) * def mean_dist(np.ndarray A): # <<<<<<<<<<<<<< * * # declare C types for as many of our variables as possible. note that we */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_8facedist_1mean_dist, NULL, __pyx_n_s_facedist); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_mean_dist, __pyx_t_1) < 0) __PYX_ERR(0, 21, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "facedist.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * from scipy.spatial.distance import cdist * from scipy.sparse import dok_matrix */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../../intel/intelpython27/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":976 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init facedist", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init facedist"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* ArgTypeTest */ static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } /* GetModuleGlobalName */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if CYTHON_COMPILING_IN_CPYTHON result = PyDict_GetItem(__pyx_d, name); if (likely(result)) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } /* None */ static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { Py_ssize_t q = a / b; Py_ssize_t r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFormatCheck */ static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } /* GetItemInt */ static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, CYTHON_NCP_UNUSED int wraparound, CYTHON_NCP_UNUSED int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (!PyErr_ExceptionMatches(PyExc_OverflowError)) return NULL; PyErr_Clear(); } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } /* PyObjectCallMethO */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* PyObjectCallOneArg */ #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_Pack(1, arg); if (unlikely(!args)) return NULL; result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } #endif /* PyErrFetchRestore */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* ImportFrom */ static PyObject* __Pyx_ImportFrom(PyObject* module, PyObject* name) { PyObject* value = __Pyx_PyObject_GetAttrStr(module, name); if (unlikely(!value) && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Format(PyExc_ImportError, #if PY_MAJOR_VERSION < 3 "cannot import name %.230s", PyString_AS_STRING(name)); #else "cannot import name %S", name); #endif } return value; } /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } Py_DECREF(obj); view->obj = NULL; } #endif /* None */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif /* None */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(a, a); case 3: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, a); case 4: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_absf(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif /* None */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif /* None */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(a, a); case 3: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, a); case 4: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_abs(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) -1, const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if CYTHON_COMPILING_IN_CPYTHON && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return __Pyx_NewRef(x); m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
940918.c
#include <stdio.h> #include "_cgo_export.h" #ifdef __amd64__ #define BREAKPOINT asm("int3;") #elif __aarch64__ #define BREAKPOINT asm("brk 0;") #endif void helloworld_pt2(int x) { BREAKPOINT; helloWorld(x+1); } void helloworld(int x) { helloworld_pt2(x+1); } void helloworld_pt4(int x) { BREAKPOINT; helloWorld2(x+1); } void helloworld_pt3(int x) { helloworld_pt4(x+1); }
375229.c
/** ****************************************************************************** * @file LowPower.c * @author WI6LABS * @version V1.0.0 * @date 17 - November -2017 * @brief Provides a Low Power interface * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * 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 of STMicroelectronics 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 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 "Arduino.h" #include "low_power.h" #if defined(HAL_PWR_MODULE_ENABLED) && !defined(HAL_PWR_MODULE_ONLY) #ifdef __cplusplus extern "C" { #endif #if defined(UART_IT_WUF) && defined(HAL_UART_MODULE_ENABLED) && !defined(HAL_UART_MODULE_ONLY) /* Save UART handler for callback */ static UART_HandleTypeDef *WakeUpUart = NULL; #endif /* Save callback pointer */ static void (*WakeUpUartCb)(void) = NULL; #ifdef STM32G0xx #define PWR_FLAG_WU PWR_FLAG_WUF #endif /** * @brief Initialize low power mode * @param None * @retval None */ void LowPower_init() { #if !defined(STM32H7xx) && !defined(STM32MP1xx) && !defined(STM32WBxx) /* Enable Power Clock */ __HAL_RCC_PWR_CLK_ENABLE(); #endif /* Allow access to Backup domain */ HAL_PWR_EnableBkUpAccess(); #ifdef __HAL_RCC_WAKEUPSTOP_CLK_CONFIG /* Ensure that HSI is wake-up system clock */ __HAL_RCC_WAKEUPSTOP_CLK_CONFIG(RCC_STOP_WAKEUPCLOCK_HSI); #endif /* Check if the system was resumed from StandBy mode */ if (__HAL_PWR_GET_FLAG(PWR_FLAG_SB) != RESET) { /* Clear Standby flag */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_SB); } /* Clear all related wakeup flags */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); } /** * @brief Configure a pin as wakeup source if compatible. * @param pin: pin to configure * @param mode: pin mode (edge or state). The configuration have to be compatible. * @retval None */ void LowPower_EnableWakeUpPin(uint32_t pin, uint32_t mode) { #if !defined(PWR_WAKEUP_PIN1_HIGH) UNUSED(mode); #endif uint32_t wkup_pin; PinName p = digitalPinToPinName(pin); if (p != NC) { switch (p) { default : #ifdef PWR_WAKEUP_PIN1 case SYS_WKUP1 : wkup_pin = PWR_WAKEUP_PIN1; #ifdef PWR_WAKEUP_PIN1_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN1_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN1 */ #ifdef PWR_WAKEUP_PIN2 case SYS_WKUP2 : wkup_pin = PWR_WAKEUP_PIN2; #ifdef PWR_WAKEUP_PIN2_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN2_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN2 */ #ifdef PWR_WAKEUP_PIN3 case SYS_WKUP3 : wkup_pin = PWR_WAKEUP_PIN3; #ifdef PWR_WAKEUP_PIN3_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN3_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN3 */ #ifdef PWR_WAKEUP_PIN4 case SYS_WKUP4 : wkup_pin = PWR_WAKEUP_PIN4; #ifdef PWR_WAKEUP_PIN4_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN4_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN4 */ #ifdef PWR_WAKEUP_PIN5 case SYS_WKUP5 : wkup_pin = PWR_WAKEUP_PIN5; #ifdef PWR_WAKEUP_PIN5_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN5_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN5 */ #ifdef PWR_WAKEUP_PIN6 case SYS_WKUP6 : wkup_pin = PWR_WAKEUP_PIN6; #ifdef PWR_WAKEUP_PIN6_HIGH if (mode != RISING) { wkup_pin = PWR_WAKEUP_PIN6_LOW; } #endif break; #endif /* PWR_WAKEUP_PIN6 */ #ifdef PWR_WAKEUP_PIN7 case SYS_WKUP7 : wkup_pin = PWR_WAKEUP_PIN7; break; #endif /* PWR_WAKEUP_PIN7 */ #ifdef PWR_WAKEUP_PIN8 case SYS_WKUP8 : wkup_pin = PWR_WAKEUP_PIN8; break; #endif /* PWR_WAKEUP_PIN8 */ } HAL_PWR_EnableWakeUpPin(wkup_pin); } } /** * @brief Enable the sleep mode. * @param None * @retval None */ void LowPower_sleep(uint32_t regulator) { /* * Suspend Tick increment to prevent wakeup by Systick interrupt. * Otherwise the Systick interrupt will wake up the device within * 1ms (HAL time base) */ HAL_SuspendTick(); /* Enter Sleep Mode , wake up is done once User push-button is pressed */ HAL_PWR_EnterSLEEPMode(regulator, PWR_SLEEPENTRY_WFI); /* Resume Tick interrupt if disabled prior to SLEEP mode entry */ HAL_ResumeTick(); if (WakeUpUartCb != NULL) { WakeUpUartCb(); } } /** * @brief Enable the stop mode. * @param obj : pointer to serial_t structure * @retval None */ void LowPower_stop(serial_t *obj) { __disable_irq(); #if defined(UART_IT_WUF) && defined(HAL_UART_MODULE_ENABLED) && !defined(HAL_UART_MODULE_ONLY) if (WakeUpUart != NULL) { HAL_UARTEx_EnableStopMode(WakeUpUart); } #endif #if defined(STM32L0xx) || defined(STM32L1xx) /* Enable Ultra low power mode */ HAL_PWREx_EnableUltraLowPower(); /* Enable the fast wake up from Ultra low power mode */ HAL_PWREx_EnableFastWakeUp(); #endif #ifdef __HAL_RCC_WAKEUPSTOP_CLK_CONFIG /* Select HSI as system clock source after Wake Up from Stop mode */ __HAL_RCC_WAKEUPSTOP_CLK_CONFIG(RCC_STOP_WAKEUPCLOCK_HSI); #endif /* Enter Stop mode */ HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); /* Exit Stop mode reset clocks */ SystemClock_ConfigFromStop(); #if defined(UART_IT_WUF) && defined(HAL_UART_MODULE_ENABLED) && !defined(HAL_UART_MODULE_ONLY) if (WakeUpUart != NULL) { /* In case of WakeUp from UART, reset its clock source to HSI */ uart_config_lowpower(obj); HAL_UARTEx_DisableStopMode(WakeUpUart); } #else UNUSED(obj); #endif __enable_irq(); HAL_Delay(10); if (WakeUpUartCb != NULL) { WakeUpUartCb(); } } /** * @brief Enable the standby mode. The board reset when leaves this mode. * @param None * @retval None */ void LowPower_standby() { __disable_irq(); #if defined(STM32L0xx) || defined(STM32L1xx) /* Enable Ultra low power mode */ HAL_PWREx_EnableUltraLowPower(); /* Enable the fast wake up from Ultra low power mode */ HAL_PWREx_EnableFastWakeUp(); #endif HAL_PWR_EnterSTANDBYMode(); } /** * @brief Enable the shutdown mode.The board reset when leaves this mode. * If shutdown mode not available, use standby mode instead. * @param None * @retval None */ void LowPower_shutdown() { __disable_irq(); #ifdef STM32L4xx /* LSE must be on to use shutdown mode */ if (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == SET) { HAL_PWREx_EnterSHUTDOWNMode(); } else #endif { LowPower_standby(); } } /** * @brief Configure the UART as a wakeup source. A callback can be called when * the chip leaves the low power mode. See board datasheet to check * with which low power mode the UART is compatible. * Warning This function will change UART clock source to HSI * @param serial: pointer to serial * @param FuncPtr: pointer to callback * @retval None */ void LowPower_EnableWakeUpUart(serial_t *serial, void (*FuncPtr)(void)) { #if defined(UART_IT_WUF) && defined(HAL_UART_MODULE_ENABLED) && !defined(HAL_UART_MODULE_ONLY) UART_WakeUpTypeDef WakeUpSelection; if (serial == NULL) { return; } /* Save Uart handler and Serial object */ WakeUpUart = &(serial->handle); /* make sure that no UART transfer is on-going */ while (__HAL_UART_GET_FLAG(WakeUpUart, USART_ISR_BUSY) == SET); /* make sure that UART is ready to receive * (test carried out again later in HAL_UARTEx_StopModeWakeUpSourceConfig) */ while (__HAL_UART_GET_FLAG(WakeUpUart, USART_ISR_REACK) == RESET); /* set the wake-up event: * specify wake-up on RXNE flag */ WakeUpSelection.WakeUpEvent = UART_WAKEUP_ON_READDATA_NONEMPTY; HAL_UARTEx_StopModeWakeUpSourceConfig(WakeUpUart, WakeUpSelection); /* Enable the UART Wake UP from STOP1 mode Interrupt */ __HAL_UART_ENABLE_IT(WakeUpUart, UART_IT_WUF); #else UNUSED(serial); #endif /* Save callback */ WakeUpUartCb = FuncPtr; } /** * @brief Configures system clock after wake-up from STOP * @note Weaked function which can be redefined by user at the sketch level. * By default, call 'SystemClock_Config()'. * @param None * @retval None */ WEAK void SystemClock_ConfigFromStop(void) { SystemClock_Config(); } #ifdef __cplusplus } #endif #endif /* HAL_PWR_MODULE_ENABLED && !HAL_PWR_MODULE_ONLY */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
573557.c
/******************************************************************************* * File Name: isr_AVI.c * Version 1.70 * * Description: * API for controlling the state of an interrupt. * * * Note: * ******************************************************************************** * Copyright 2008-2015, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include <cydevice_trm.h> #include <CyLib.h> #include <isr_AVI.h> #include "cyapicallbacks.h" #if !defined(isr_AVI__REMOVED) /* Check for removal by optimization */ /******************************************************************************* * Place your includes, defines and code here ********************************************************************************/ /* `#START isr_AVI_intc` */ /* `#END` */ #ifndef CYINT_IRQ_BASE #define CYINT_IRQ_BASE 16 #endif /* CYINT_IRQ_BASE */ #ifndef CYINT_VECT_TABLE #define CYINT_VECT_TABLE ((cyisraddress **) CYREG_NVIC_VECT_OFFSET) #endif /* CYINT_VECT_TABLE */ /* Declared in startup, used to set unused interrupts to. */ CY_ISR_PROTO(IntDefaultHandler); /******************************************************************************* * Function Name: isr_AVI_Start ******************************************************************************** * * Summary: * Set up the interrupt and enable it. This function disables the interrupt, * sets the default interrupt vector, sets the priority from the value in the * Design Wide Resources Interrupt Editor, then enables the interrupt to the * interrupt controller. * * Parameters: * None * * Return: * None * *******************************************************************************/ void isr_AVI_Start(void) { /* For all we know the interrupt is active. */ isr_AVI_Disable(); /* Set the ISR to point to the isr_AVI Interrupt. */ isr_AVI_SetVector(&isr_AVI_Interrupt); /* Set the priority. */ isr_AVI_SetPriority((uint8)isr_AVI_INTC_PRIOR_NUMBER); /* Enable it. */ isr_AVI_Enable(); } /******************************************************************************* * Function Name: isr_AVI_StartEx ******************************************************************************** * * Summary: * Sets up the interrupt and enables it. This function disables the interrupt, * sets the interrupt vector based on the address passed in, sets the priority * from the value in the Design Wide Resources Interrupt Editor, then enables * the interrupt to the interrupt controller. * * When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be * used to provide consistent definition across compilers: * * Function definition example: * CY_ISR(MyISR) * { * } * Function prototype example: * CY_ISR_PROTO(MyISR); * * Parameters: * address: Address of the ISR to set in the interrupt vector table. * * Return: * None * *******************************************************************************/ void isr_AVI_StartEx(cyisraddress address) { /* For all we know the interrupt is active. */ isr_AVI_Disable(); /* Set the ISR to point to the isr_AVI Interrupt. */ isr_AVI_SetVector(address); /* Set the priority. */ isr_AVI_SetPriority((uint8)isr_AVI_INTC_PRIOR_NUMBER); /* Enable it. */ isr_AVI_Enable(); } /******************************************************************************* * Function Name: isr_AVI_Stop ******************************************************************************** * * Summary: * Disables and removes the interrupt. * * Parameters: * None * * Return: * None * *******************************************************************************/ void isr_AVI_Stop(void) { /* Disable this interrupt. */ isr_AVI_Disable(); /* Set the ISR to point to the passive one. */ isr_AVI_SetVector(&IntDefaultHandler); } /******************************************************************************* * Function Name: isr_AVI_Interrupt ******************************************************************************** * * Summary: * The default Interrupt Service Routine for isr_AVI. * * Add custom code between the coments to keep the next version of this file * from over writting your code. * * Parameters: * * Return: * None * *******************************************************************************/ CY_ISR(isr_AVI_Interrupt) { #ifdef isr_AVI_INTERRUPT_INTERRUPT_CALLBACK isr_AVI_Interrupt_InterruptCallback(); #endif /* isr_AVI_INTERRUPT_INTERRUPT_CALLBACK */ /* Place your Interrupt code here. */ /* `#START isr_AVI_Interrupt` */ /* `#END` */ } /******************************************************************************* * Function Name: isr_AVI_SetVector ******************************************************************************** * * Summary: * Change the ISR vector for the Interrupt. Note calling isr_AVI_Start * will override any effect this method would have had. To set the vector * before the component has been started use isr_AVI_StartEx instead. * * When defining ISR functions, the CY_ISR and CY_ISR_PROTO macros should be * used to provide consistent definition across compilers: * * Function definition example: * CY_ISR(MyISR) * { * } * * Function prototype example: * CY_ISR_PROTO(MyISR); * * Parameters: * address: Address of the ISR to set in the interrupt vector table. * * Return: * None * *******************************************************************************/ void isr_AVI_SetVector(cyisraddress address) { cyisraddress * ramVectorTable; ramVectorTable = (cyisraddress *) *CYINT_VECT_TABLE; ramVectorTable[CYINT_IRQ_BASE + (uint32)isr_AVI__INTC_NUMBER] = address; } /******************************************************************************* * Function Name: isr_AVI_GetVector ******************************************************************************** * * Summary: * Gets the "address" of the current ISR vector for the Interrupt. * * Parameters: * None * * Return: * Address of the ISR in the interrupt vector table. * *******************************************************************************/ cyisraddress isr_AVI_GetVector(void) { cyisraddress * ramVectorTable; ramVectorTable = (cyisraddress *) *CYINT_VECT_TABLE; return ramVectorTable[CYINT_IRQ_BASE + (uint32)isr_AVI__INTC_NUMBER]; } /******************************************************************************* * Function Name: isr_AVI_SetPriority ******************************************************************************** * * Summary: * Sets the Priority of the Interrupt. * * Note calling isr_AVI_Start or isr_AVI_StartEx will * override any effect this API would have had. This API should only be called * after isr_AVI_Start or isr_AVI_StartEx has been called. * To set the initial priority for the component, use the Design-Wide Resources * Interrupt Editor. * * Note This API has no effect on Non-maskable interrupt NMI). * * Parameters: * priority: Priority of the interrupt, 0 being the highest priority * PSoC 3 and PSoC 5LP: Priority is from 0 to 7. * PSoC 4: Priority is from 0 to 3. * * Return: * None * *******************************************************************************/ void isr_AVI_SetPriority(uint8 priority) { *isr_AVI_INTC_PRIOR = priority << 5; } /******************************************************************************* * Function Name: isr_AVI_GetPriority ******************************************************************************** * * Summary: * Gets the Priority of the Interrupt. * * Parameters: * None * * Return: * Priority of the interrupt, 0 being the highest priority * PSoC 3 and PSoC 5LP: Priority is from 0 to 7. * PSoC 4: Priority is from 0 to 3. * *******************************************************************************/ uint8 isr_AVI_GetPriority(void) { uint8 priority; priority = *isr_AVI_INTC_PRIOR >> 5; return priority; } /******************************************************************************* * Function Name: isr_AVI_Enable ******************************************************************************** * * Summary: * Enables the interrupt to the interrupt controller. Do not call this function * unless ISR_Start() has been called or the functionality of the ISR_Start() * function, which sets the vector and the priority, has been called. * * Parameters: * None * * Return: * None * *******************************************************************************/ void isr_AVI_Enable(void) { /* Enable the general interrupt. */ *isr_AVI_INTC_SET_EN = isr_AVI__INTC_MASK; } /******************************************************************************* * Function Name: isr_AVI_GetState ******************************************************************************** * * Summary: * Gets the state (enabled, disabled) of the Interrupt. * * Parameters: * None * * Return: * 1 if enabled, 0 if disabled. * *******************************************************************************/ uint8 isr_AVI_GetState(void) { /* Get the state of the general interrupt. */ return ((*isr_AVI_INTC_SET_EN & (uint32)isr_AVI__INTC_MASK) != 0u) ? 1u:0u; } /******************************************************************************* * Function Name: isr_AVI_Disable ******************************************************************************** * * Summary: * Disables the Interrupt in the interrupt controller. * * Parameters: * None * * Return: * None * *******************************************************************************/ void isr_AVI_Disable(void) { /* Disable the general interrupt. */ *isr_AVI_INTC_CLR_EN = isr_AVI__INTC_MASK; } /******************************************************************************* * Function Name: isr_AVI_SetPending ******************************************************************************** * * Summary: * Causes the Interrupt to enter the pending state, a software method of * generating the interrupt. * * Parameters: * None * * Return: * None * * Side Effects: * If interrupts are enabled and the interrupt is set up properly, the ISR is * entered (depending on the priority of this interrupt and other pending * interrupts). * *******************************************************************************/ void isr_AVI_SetPending(void) { *isr_AVI_INTC_SET_PD = isr_AVI__INTC_MASK; } /******************************************************************************* * Function Name: isr_AVI_ClearPending ******************************************************************************** * * Summary: * Clears a pending interrupt in the interrupt controller. * * Note Some interrupt sources are clear-on-read and require the block * interrupt/status register to be read/cleared with the appropriate block API * (GPIO, UART, and so on). Otherwise the ISR will continue to remain in * pending state even though the interrupt itself is cleared using this API. * * Parameters: * None * * Return: * None * *******************************************************************************/ void isr_AVI_ClearPending(void) { *isr_AVI_INTC_CLR_PD = isr_AVI__INTC_MASK; } #endif /* End check for removal by optimization */ /* [] END OF FILE */
23261.c
#include <errno.h> #include <limits.h> #include "stdio_impl.h" off_t __ftello_unlocked(FILE* f) { off_t pos = f->seek(f, 0, (f->flags & F_APP) && f->wpos > f->wbase ? SEEK_END : SEEK_CUR); if (pos < 0) return pos; /* Adjust for data in buffer. */ return pos - (f->rend - f->rpos) + (f->wpos - f->wbase); } off_t __ftello(FILE* f) { off_t pos; FLOCK(f); pos = __ftello_unlocked(f); FUNLOCK(f); return pos; } long ftell(FILE* f) { off_t pos = __ftello(f); if (pos > LONG_MAX) { errno = EOVERFLOW; return -1; } return pos; } weak_alias(__ftello, ftello);
554211.c
/*++ /* NAME /* tls_scache 3 /* SUMMARY /* TLS session cache manager /* SYNOPSIS /* #include <tls_scache.h> /* /* TLS_SCACHE *tls_scache_open(dbname, cache_label, verbose, timeout) /* const char *dbname /* const char *cache_label; /* int verbose; /* int timeout; /* /* void tls_scache_close(cache) /* TLS_SCACHE *cache; /* /* int tls_scache_lookup(cache, cache_id, out_session) /* TLS_SCACHE *cache; /* const char *cache_id; /* VSTRING *out_session; /* /* int tls_scache_update(cache, cache_id, session, session_len) /* TLS_SCACHE *cache; /* const char *cache_id; /* const char *session; /* ssize_t session_len; /* /* int tls_scache_sequence(cache, first_next, out_cache_id, /* VSTRING *out_session) /* TLS_SCACHE *cache; /* int first_next; /* char **out_cache_id; /* VSTRING *out_session; /* /* int tls_scache_delete(cache, cache_id) /* TLS_SCACHE *cache; /* const char *cache_id; /* /* TLS_TICKET_KEY *tls_scache_key(keyname, now, timeout) /* unsigned char *keyname; /* time_t now; /* int timeout; /* /* TLS_TICKET_KEY *tls_scache_key_rotate(newkey) /* TLS_TICKET_KEY *newkey; /* DESCRIPTION /* This module maintains Postfix TLS session cache files. /* each session is stored under a lookup key (hostname or /* session ID). /* /* tls_scache_open() opens the specified TLS session cache /* and returns a handle that must be used for subsequent /* access. /* /* tls_scache_close() closes the specified TLS session cache /* and releases memory that was allocated by tls_scache_open(). /* /* tls_scache_lookup() looks up the specified session in the /* specified cache, and applies session timeout restrictions. /* Entries that are too old are silently deleted. /* /* tls_scache_update() updates the specified TLS session cache /* with the specified session information. /* /* tls_scache_sequence() iterates over the specified TLS session /* cache and either returns the first or next entry that has not /* timed out, or returns no data. Entries that are too old are /* silently deleted. Specify TLS_SCACHE_SEQUENCE_NOTHING as the /* third and last argument to disable saving of cache entry /* content or cache entry ID information. This is useful when /* purging expired entries. A result value of zero means that /* the end of the cache was reached. /* /* tls_scache_delete() removes the specified cache entry from /* the specified TLS session cache. /* /* tls_scache_key() locates a TLS session ticket key in a 2-element /* in-memory cache. A null result is returned if no unexpired matching /* key is found. /* /* tls_scache_key_rotate() saves a TLS session tickets key in the /* in-memory cache. /* /* Arguments: /* .IP dbname /* The base name of the session cache file. /* .IP cache_label /* A string that is used in logging and error messages. /* .IP verbose /* Do verbose logging of cache operations? (zero == no) /* .IP timeout /* The time after wich a session cache entry is considered too old. /* .IP first_next /* One of DICT_SEQ_FUN_FIRST (first cache element) or DICT_SEQ_FUN_NEXT /* (next cache element). /* .IP cache_id /* Session cache lookup key. /* .IP session /* Storage for session information. /* .IP session_len /* The size of the session information in bytes. /* .IP out_cache_id /* .IP out_session /* Storage for saving the cache_id or session information of the /* current cache entry. /* /* Specify TLS_SCACHE_DONT_NEED_CACHE_ID to avoid saving /* the session cache ID of the cache entry. /* /* Specify TLS_SCACHE_DONT_NEED_SESSION to avoid /* saving the session information in the cache entry. /* .IP keyname /* Is null when requesting the current encryption keys. Otherwise, /* keyname is a pointer to an array of TLS_TICKET_NAMELEN unsigned /* chars (not NUL terminated) that is an identifier for a key /* previously used to encrypt a session ticket. /* .IP now /* Current epoch time passed by caller. /* .IP timeout /* TLS session ticket encryption lifetime. /* .IP newkey /* TLS session ticket key obtained from tlsmgr(8) to be added to * internal cache. /* DIAGNOSTICS /* These routines terminate with a fatal run-time error /* for unrecoverable database errors. This allows the /* program to restart and reset the database to an /* empty initial state. /* /* tls_scache_open() never returns on failure. All other /* functions return non-zero on success, zero when the /* operation could not be completed. /* LICENSE /* .ad /* .fi /* The Secure Mailer license must be distributed with this software. /* AUTHOR(S) /* Wietse Venema /* IBM T.J. Watson Research /* P.O. Box 704 /* Yorktown Heights, NY 10598, USA /*--*/ /* System library. */ #include <sys_defs.h> #ifdef USE_TLS #include <string.h> #include <stddef.h> /* Utility library. */ #include <msg.h> #include <dict.h> #include <stringops.h> #include <mymalloc.h> #include <hex_code.h> #include <myflock.h> #include <vstring.h> #include <timecmp.h> /* Global library. */ /* TLS library. */ #include <tls_scache.h> /* Application-specific. */ /* * Session cache entry format. */ typedef struct { time_t timestamp; /* time when saved */ char session[1]; /* actually a bunch of bytes */ } TLS_SCACHE_ENTRY; static TLS_TICKET_KEY *keys[2]; /* * SLMs. */ #define STR(x) vstring_str(x) #define LEN(x) VSTRING_LEN(x) /* tls_scache_encode - encode TLS session cache entry */ static VSTRING *tls_scache_encode(TLS_SCACHE *cp, const char *cache_id, const char *session, ssize_t session_len) { TLS_SCACHE_ENTRY *entry; VSTRING *hex_data; ssize_t binary_data_len; /* * Assemble the TLS session cache entry. * * We could eliminate some copying by using incremental encoding, but * sessions are so small that it really does not matter. */ binary_data_len = session_len + offsetof(TLS_SCACHE_ENTRY, session); entry = (TLS_SCACHE_ENTRY *) mymalloc(binary_data_len); entry->timestamp = time((time_t *) 0); memcpy(entry->session, session, session_len); /* * Encode the TLS session cache entry. */ hex_data = vstring_alloc(2 * binary_data_len + 1); hex_encode(hex_data, (char *) entry, binary_data_len); /* * Logging. */ if (cp->verbose) msg_info("write %s TLS cache entry %s: time=%ld [data %ld bytes]", cp->cache_label, cache_id, (long) entry->timestamp, (long) session_len); /* * Clean up. */ myfree((void *) entry); return (hex_data); } /* tls_scache_decode - decode TLS session cache entry */ static int tls_scache_decode(TLS_SCACHE *cp, const char *cache_id, const char *hex_data, ssize_t hex_data_len, VSTRING *out_session) { TLS_SCACHE_ENTRY *entry; VSTRING *bin_data; /* * Sanity check. */ if (hex_data_len < 2 * (offsetof(TLS_SCACHE_ENTRY, session))) { msg_warn("%s TLS cache: truncated entry for %s: %.100s", cp->cache_label, cache_id, hex_data); return (0); } /* * Disassemble the TLS session cache entry. * * No early returns or we have a memory leak. */ #define FREE_AND_RETURN(ptr, x) { vstring_free(ptr); return (x); } bin_data = vstring_alloc(hex_data_len / 2 + 1); if (hex_decode(bin_data, hex_data, hex_data_len) == 0) { msg_warn("%s TLS cache: malformed entry for %s: %.100s", cp->cache_label, cache_id, hex_data); FREE_AND_RETURN(bin_data, 0); } entry = (TLS_SCACHE_ENTRY *) STR(bin_data); /* * Logging. */ if (cp->verbose) msg_info("read %s TLS cache entry %s: time=%ld [data %ld bytes]", cp->cache_label, cache_id, (long) entry->timestamp, (long) (LEN(bin_data) - offsetof(TLS_SCACHE_ENTRY, session))); /* * Other mandatory restrictions. */ if (entry->timestamp + cp->timeout < time((time_t *) 0)) FREE_AND_RETURN(bin_data, 0); /* * Optional output. */ if (out_session != 0) vstring_memcpy(out_session, entry->session, LEN(bin_data) - offsetof(TLS_SCACHE_ENTRY, session)); /* * Clean up. */ FREE_AND_RETURN(bin_data, 1); } /* tls_scache_lookup - load session from cache */ int tls_scache_lookup(TLS_SCACHE *cp, const char *cache_id, VSTRING *session) { const char *hex_data; /* * Logging. */ if (cp->verbose) msg_info("lookup %s session id=%s", cp->cache_label, cache_id); /* * Initialize. Don't leak data. */ if (session) VSTRING_RESET(session); /* * Search the cache database. */ if ((hex_data = dict_get(cp->db, cache_id)) == 0) return (0); /* * Decode entry and delete if expired or malformed. */ if (tls_scache_decode(cp, cache_id, hex_data, strlen(hex_data), session) == 0) { tls_scache_delete(cp, cache_id); return (0); } else { return (1); } } /* tls_scache_update - save session to cache */ int tls_scache_update(TLS_SCACHE *cp, const char *cache_id, const char *buf, ssize_t len) { VSTRING *hex_data; /* * Logging. */ if (cp->verbose) msg_info("put %s session id=%s [data %ld bytes]", cp->cache_label, cache_id, (long) len); /* * Encode the cache entry. */ hex_data = tls_scache_encode(cp, cache_id, buf, len); /* * Store the cache entry. * * XXX Berkeley DB supports huge database keys and values. SDBM seems to * have a finite limit, and DBM simply can't be used at all. */ dict_put(cp->db, cache_id, STR(hex_data)); /* * Clean up. */ vstring_free(hex_data); return (1); } /* tls_scache_sequence - get first/next TLS session cache entry */ int tls_scache_sequence(TLS_SCACHE *cp, int first_next, char **out_cache_id, VSTRING *out_session) { const char *member; const char *value; char *saved_cursor; int found_entry; int keep_entry; char *saved_member; /* * XXX Deleting entries while enumerating a map can he tricky. Some map * types have a concept of cursor and support a "delete the current * element" operation. Some map types without cursors don't behave well * when the current first/next entry is deleted (example: with Berkeley * DB < 2, the "next" operation produces garbage). To avoid trouble, we * delete an expired entry after advancing the current first/next * position beyond it, and ignore client requests to delete the current * entry. */ /* * Find the first or next database entry. Activate the passivated entry * and check the time stamp. Schedule the entry for deletion if it is too * old. * * Save the member (cache id) so that it will not be clobbered by the * tls_scache_lookup() call below. */ found_entry = (dict_seq(cp->db, first_next, &member, &value) == 0); if (found_entry) { keep_entry = tls_scache_decode(cp, member, value, strlen(value), out_session); if (keep_entry && out_cache_id) *out_cache_id = mystrdup(member); saved_member = mystrdup(member); } /* * Delete behind. This is a no-op if an expired cache entry was updated * in the mean time. Use the saved lookup criteria so that the "delete * behind" operation works as promised. * * The delete-behind strategy assumes that all updates are made by a single * process. Otherwise, delete-behind may remove an entry that was updated * after it was scheduled for deletion. */ if (cp->flags & TLS_SCACHE_FLAG_DEL_SAVED_CURSOR) { cp->flags &= ~TLS_SCACHE_FLAG_DEL_SAVED_CURSOR; saved_cursor = cp->saved_cursor; cp->saved_cursor = 0; tls_scache_lookup(cp, saved_cursor, (VSTRING *) 0); myfree(saved_cursor); } /* * Otherwise, clean up if this is not the first iteration. */ else { if (cp->saved_cursor) myfree(cp->saved_cursor); cp->saved_cursor = 0; } /* * Protect the current first/next entry against explicit or implied * client delete requests, and schedule a bad or expired entry for * deletion. Save the lookup criteria so that the "delete behind" * operation will work as promised. */ if (found_entry) { cp->saved_cursor = saved_member; if (keep_entry == 0) cp->flags |= TLS_SCACHE_FLAG_DEL_SAVED_CURSOR; } return (found_entry); } /* tls_scache_delete - delete session from cache */ int tls_scache_delete(TLS_SCACHE *cp, const char *cache_id) { /* * Logging. */ if (cp->verbose) msg_info("delete %s session id=%s", cp->cache_label, cache_id); /* * Do it, unless we would delete the current first/next entry. Some map * types don't have cursors, and some of those don't behave when the * "current" entry is deleted. */ return ((cp->saved_cursor != 0 && strcmp(cp->saved_cursor, cache_id) == 0) || dict_del(cp->db, cache_id) == 0); } /* tls_scache_open - open TLS session cache file */ TLS_SCACHE *tls_scache_open(const char *dbname, const char *cache_label, int verbose, int timeout) { TLS_SCACHE *cp; DICT *dict; /* * Logging. */ if (verbose) msg_info("open %s TLS cache %s", cache_label, dbname); /* * Open the dictionary with O_TRUNC, so that we never have to worry about * opening a damaged file after some process terminated abnormally. */ #ifdef SINGLE_UPDATER #define DICT_FLAGS (DICT_FLAG_DUP_REPLACE | DICT_FLAG_OPEN_LOCK \ | DICT_FLAG_UTF8_REQUEST) #else #define DICT_FLAGS \ (DICT_FLAG_DUP_REPLACE | DICT_FLAG_LOCK | DICT_FLAG_SYNC_UPDATE \ | DICT_FLAG_UTF8_REQUEST) #endif dict = dict_open(dbname, O_RDWR | O_CREAT | O_TRUNC, DICT_FLAGS); /* * Sanity checks. */ if (dict->update == 0) msg_fatal("dictionary %s does not support update operations", dbname); if (dict->delete == 0) msg_fatal("dictionary %s does not support delete operations", dbname); if (dict->sequence == 0) msg_fatal("dictionary %s does not support sequence operations", dbname); /* * Create the TLS_SCACHE object. */ cp = (TLS_SCACHE *) mymalloc(sizeof(*cp)); cp->flags = 0; cp->db = dict; cp->cache_label = mystrdup(cache_label); cp->verbose = verbose; cp->timeout = timeout; cp->saved_cursor = 0; return (cp); } /* tls_scache_close - close TLS session cache file */ void tls_scache_close(TLS_SCACHE *cp) { /* * Logging. */ if (cp->verbose) msg_info("close %s TLS cache %s", cp->cache_label, cp->db->name); /* * Destroy the TLS_SCACHE object. */ dict_close(cp->db); myfree(cp->cache_label); if (cp->saved_cursor) myfree(cp->saved_cursor); myfree((void *) cp); } /* tls_scache_key - find session ticket key for given key name */ TLS_TICKET_KEY *tls_scache_key(unsigned char *keyname, time_t now, int timeout) { int i; /* * The keys array contains 2 elements, the current signing key and the * previous key. * * When name == 0 we are issuing a ticket, otherwise decrypting an existing * ticket with the given key name. For new tickets we always use the * current key if unexpired. For existing tickets, we use either the * current or previous key with a validation expiration that is timeout * longer than the signing expiration. */ if (keyname) { for (i = 0; i < 2 && keys[i]; ++i) { if (memcmp(keyname, keys[i]->name, TLS_TICKET_NAMELEN) == 0) { if (timecmp(keys[i]->tout + timeout, now) > 0) return (keys[i]); break; } } } else if (keys[0]) { if (timecmp(keys[0]->tout, now) > 0) return (keys[0]); } return (0); } /* tls_scache_key_rotate - rotate session ticket keys */ TLS_TICKET_KEY *tls_scache_key_rotate(TLS_TICKET_KEY *newkey) { /* * Allocate or re-use storage of retired key, then overwrite it, since * caller's key data is ephemeral. */ if (keys[1] == 0) keys[1] = (TLS_TICKET_KEY *) mymalloc(sizeof(*newkey)); *keys[1] = *newkey; newkey = keys[1]; /* * Rotate if required, ensuring that the keys are sorted by expiration * time with keys[0] expiring last. */ if (keys[0] == 0 || keys[0]->tout < keys[1]->tout) { keys[1] = keys[0]; keys[0] = newkey; } return (newkey); } #endif
714043.c
/* vl53l0x.c - Driver for ST VL53L0X time of flight sensor */ #define DT_DRV_COMPAT st_vl53l0x /* * Copyright (c) 2017 STMicroelectronics * * SPDX-License-Identifier: Apache-2.0 */ #include <errno.h> #include <kernel.h> #include <drivers/i2c.h> #include <drivers/sensor.h> #include <init.h> #include <drivers/gpio.h> #include <sys/__assert.h> #include <zephyr/types.h> #include <device.h> #include <logging/log.h> #include "vl53l0x_api.h" #include "vl53l0x_platform.h" LOG_MODULE_REGISTER(VL53L0X, CONFIG_SENSOR_LOG_LEVEL); /* All the values used in this driver are coming from ST datasheet and examples. * It can be found here: * http://www.st.com/en/embedded-software/stsw-img005.html * There are also examples of use in the L4 cube FW: * http://www.st.com/en/embedded-software/stm32cubel4.html */ #define VL53L0X_REG_WHO_AM_I 0xC0 #define VL53L0X_CHIP_ID 0xEEAA #define VL53L0X_SETUP_SIGNAL_LIMIT (0.1*65536) #define VL53L0X_SETUP_SIGMA_LIMIT (60*65536) #define VL53L0X_SETUP_MAX_TIME_FOR_RANGING 33000 #define VL53L0X_SETUP_PRE_RANGE_VCSEL_PERIOD 18 #define VL53L0X_SETUP_FINAL_RANGE_VCSEL_PERIOD 14 struct vl53l0x_data { struct device *i2c; VL53L0X_Dev_t vl53l0x; VL53L0X_RangingMeasurementData_t RangingMeasurementData; }; static int vl53l0x_sample_fetch(struct device *dev, enum sensor_channel chan) { struct vl53l0x_data *drv_data = dev->driver_data; VL53L0X_Error ret; __ASSERT_NO_MSG(chan == SENSOR_CHAN_ALL || chan == SENSOR_CHAN_DISTANCE || chan == SENSOR_CHAN_PROX); ret = VL53L0X_PerformSingleRangingMeasurement(&drv_data->vl53l0x, &drv_data->RangingMeasurementData); if (ret < 0) { LOG_ERR("Could not perform measurment (error=%d)", ret); return -EINVAL; } return 0; } static int vl53l0x_channel_get(struct device *dev, enum sensor_channel chan, struct sensor_value *val) { struct vl53l0x_data *drv_data = (struct vl53l0x_data *)dev->driver_data; __ASSERT_NO_MSG(chan == SENSOR_CHAN_DISTANCE || chan == SENSOR_CHAN_PROX); if (chan == SENSOR_CHAN_PROX) { if (drv_data->RangingMeasurementData.RangeMilliMeter <= CONFIG_VL53L0X_PROXIMITY_THRESHOLD) { val->val1 = 1; } else { val->val1 = 0; } val->val2 = 0; } else { val->val1 = drv_data->RangingMeasurementData.RangeMilliMeter / 1000; val->val2 = (drv_data->RangingMeasurementData.RangeMilliMeter % 1000) * 1000; } return 0; } static const struct sensor_driver_api vl53l0x_api_funcs = { .sample_fetch = vl53l0x_sample_fetch, .channel_get = vl53l0x_channel_get, }; static int vl53l0x_setup_single_shot(struct device *dev) { struct vl53l0x_data *drv_data = dev->driver_data; int ret; u8_t VhvSettings; u8_t PhaseCal; u32_t refSpadCount; u8_t isApertureSpads; ret = VL53L0X_StaticInit(&drv_data->vl53l0x); if (ret) { LOG_ERR("VL53L0X_StaticInit failed"); goto exit; } ret = VL53L0X_PerformRefCalibration(&drv_data->vl53l0x, &VhvSettings, &PhaseCal); if (ret) { LOG_ERR("VL53L0X_PerformRefCalibration failed"); goto exit; } ret = VL53L0X_PerformRefSpadManagement(&drv_data->vl53l0x, (uint32_t *)&refSpadCount, &isApertureSpads); if (ret) { LOG_ERR("VL53L0X_PerformRefSpadManagement failed"); goto exit; } ret = VL53L0X_SetDeviceMode(&drv_data->vl53l0x, VL53L0X_DEVICEMODE_SINGLE_RANGING); if (ret) { LOG_ERR("VL53L0X_SetDeviceMode failed"); goto exit; } ret = VL53L0X_SetLimitCheckEnable(&drv_data->vl53l0x, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, 1); if (ret) { LOG_ERR("VL53L0X_SetLimitCheckEnable sigma failed"); goto exit; } ret = VL53L0X_SetLimitCheckEnable(&drv_data->vl53l0x, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, 1); if (ret) { LOG_ERR("VL53L0X_SetLimitCheckEnable signal rate failed"); goto exit; } ret = VL53L0X_SetLimitCheckValue(&drv_data->vl53l0x, VL53L0X_CHECKENABLE_SIGNAL_RATE_FINAL_RANGE, VL53L0X_SETUP_SIGNAL_LIMIT); if (ret) { LOG_ERR("VL53L0X_SetLimitCheckValue signal rate failed"); goto exit; } ret = VL53L0X_SetLimitCheckValue(&drv_data->vl53l0x, VL53L0X_CHECKENABLE_SIGMA_FINAL_RANGE, VL53L0X_SETUP_SIGMA_LIMIT); if (ret) { LOG_ERR("VL53L0X_SetLimitCheckValue sigma failed"); goto exit; } ret = VL53L0X_SetMeasurementTimingBudgetMicroSeconds(&drv_data->vl53l0x, VL53L0X_SETUP_MAX_TIME_FOR_RANGING); if (ret) { LOG_ERR( "VL53L0X_SetMeasurementTimingBudgetMicroSeconds failed"); goto exit; } ret = VL53L0X_SetVcselPulsePeriod(&drv_data->vl53l0x, VL53L0X_VCSEL_PERIOD_PRE_RANGE, VL53L0X_SETUP_PRE_RANGE_VCSEL_PERIOD); if (ret) { LOG_ERR("VL53L0X_SetVcselPulsePeriod pre range failed"); goto exit; } ret = VL53L0X_SetVcselPulsePeriod(&drv_data->vl53l0x, VL53L0X_VCSEL_PERIOD_FINAL_RANGE, VL53L0X_SETUP_FINAL_RANGE_VCSEL_PERIOD); if (ret) { LOG_ERR("VL53L0X_SetVcselPulsePeriod final range failed"); goto exit; } exit: return ret; } static int vl53l0x_init(struct device *dev) { struct vl53l0x_data *drv_data = dev->driver_data; VL53L0X_Error ret; u16_t vl53l0x_id = 0U; VL53L0X_DeviceInfo_t vl53l0x_dev_info; LOG_DBG("enter in %s", __func__); #if DT_INST_NODE_HAS_PROP(0, xshut_gpios) struct device *gpio; /* configure and set VL53L0X_XSHUT_Pin */ gpio = device_get_binding(DT_INST_GPIO_LABEL(0, xshut_gpios)); if (gpio == NULL) { LOG_ERR("Could not get pointer to %s device.", DT_INST_GPIO_LABEL(0, xshut_gpios)); return -EINVAL; } if (gpio_pin_configure(gpio, DT_INST_GPIO_PIN(0, xshut_gpios), GPIO_OUTPUT | GPIO_PULL_UP) < 0) { LOG_ERR("Could not configure GPIO %s %d).", DT_INST_GPIO_LABEL(0, xshut_gpios), DT_INST_GPIO_PIN(0, xshut_gpios)); return -EINVAL; } gpio_pin_set(gpio, DT_INST_GPIO_PIN(0, xshut_gpios), 1); k_sleep(K_MSEC(100)); #endif drv_data->i2c = device_get_binding(DT_INST_BUS_LABEL(0)); if (drv_data->i2c == NULL) { LOG_ERR("Could not get pointer to %s device.", DT_INST_BUS_LABEL(0)); return -EINVAL; } drv_data->vl53l0x.i2c = drv_data->i2c; drv_data->vl53l0x.I2cDevAddr = DT_INST_REG_ADDR(0); /* Get info from sensor */ (void)memset(&vl53l0x_dev_info, 0, sizeof(VL53L0X_DeviceInfo_t)); ret = VL53L0X_GetDeviceInfo(&drv_data->vl53l0x, &vl53l0x_dev_info); if (ret < 0) { LOG_ERR("Could not get info from device."); return -ENODEV; } LOG_DBG("VL53L0X_GetDeviceInfo = %d", ret); LOG_DBG(" Device Name : %s", vl53l0x_dev_info.Name); LOG_DBG(" Device Type : %s", vl53l0x_dev_info.Type); LOG_DBG(" Device ID : %s", vl53l0x_dev_info.ProductId); LOG_DBG(" ProductRevisionMajor : %d", vl53l0x_dev_info.ProductRevisionMajor); LOG_DBG(" ProductRevisionMinor : %d", vl53l0x_dev_info.ProductRevisionMinor); ret = VL53L0X_RdWord(&drv_data->vl53l0x, VL53L0X_REG_WHO_AM_I, (uint16_t *) &vl53l0x_id); if ((ret < 0) || (vl53l0x_id != VL53L0X_CHIP_ID)) { LOG_ERR("Issue on device identification"); return -ENOTSUP; } /* sensor init */ ret = VL53L0X_DataInit(&drv_data->vl53l0x); if (ret < 0) { LOG_ERR("VL53L0X_DataInit return error (%d)", ret); return -ENOTSUP; } ret = vl53l0x_setup_single_shot(dev); if (ret < 0) { return -ENOTSUP; } return 0; } static struct vl53l0x_data vl53l0x_driver; DEVICE_AND_API_INIT(vl53l0x, DT_INST_LABEL(0), vl53l0x_init, &vl53l0x_driver, NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY, &vl53l0x_api_funcs);
592399.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" /*********************************************************************** * Only for plain IPv4 builds **********************************************************************/ #ifdef CURLRES_IPV4 /* plain IPv4 code coming up */ #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "inet_pton.h" /* The last 3 #include files should be in this order */ #include "curl_printf.h" #include "curl_memory.h" #include "memdebug.h" /* * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've * been set and returns TRUE if they are OK. */ bool Curl_ipvalid(struct connectdata *conn) { if(conn->ip_version == CURL_IPRESOLVE_V6) /* An IPv6 address was requested and we can't get/use one */ return FALSE; return TRUE; /* OK, proceed */ } #ifdef CURLRES_SYNCH /* * Curl_getaddrinfo() - the IPv4 synchronous version. * * The original code to this function was from the Dancer source code, written * by Bjorn Reese, it has since been patched and modified considerably. * * gethostbyname_r() is the thread-safe version of the gethostbyname() * function. When we build for plain IPv4, we attempt to use this * function. There are _three_ different gethostbyname_r() versions, and we * detect which one this platform supports in the configure script and set up * the HAVE_GETHOSTBYNAME_R_3, HAVE_GETHOSTBYNAME_R_5 or * HAVE_GETHOSTBYNAME_R_6 defines accordingly. Note that HAVE_GETADDRBYNAME * has the corresponding rules. This is primarily on *nix. Note that some unix * flavours have thread-safe versions of the plain gethostbyname() etc. * */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { Curl_addrinfo *ai = NULL; #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)conn; #endif *waitp = 0; /* synchronous response only */ ai = Curl_ipv4_resolve_r(hostname, port); if(!ai) infof(conn->data, "Curl_ipv4_resolve_r failed for %s\n", hostname); return ai; } #endif /* CURLRES_SYNCH */ #endif /* CURLRES_IPV4 */ #if defined(CURLRES_IPV4) && !defined(CURLRES_ARES) /* * Curl_ipv4_resolve_r() - ipv4 threadsafe resolver function. * * This is used for both synchronous and asynchronous resolver builds, * implying that only threadsafe code and function calls may be used. * */ Curl_addrinfo *Curl_ipv4_resolve_r(const char *hostname, int port) { #if !defined(HAVE_GETADDRINFO_THREADSAFE) && defined(HAVE_GETHOSTBYNAME_R_3) int res; #endif Curl_addrinfo *ai = NULL; struct hostent *h = NULL; struct in_addr in; struct hostent *buf = NULL; if(Curl_inet_pton(AF_INET, hostname, &in) > 0) /* This is a dotted IP address 123.123.123.123-style */ return Curl_ip2addr(AF_INET, &in, hostname, port); #if defined(HAVE_GETADDRINFO_THREADSAFE) else { struct addrinfo hints; char sbuf[12]; char *sbufptr = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_INET; hints.ai_socktype = SOCK_STREAM; if(port) { snprintf(sbuf, sizeof(sbuf), "%d", port); sbufptr = sbuf; } (void)Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &ai); #elif defined(HAVE_GETHOSTBYNAME_R) /* * gethostbyname_r() is the preferred resolve function for many platforms. * Since there are three different versions of it, the following code is * somewhat #ifdef-ridden. */ else { int h_errnop; buf = calloc(1, CURL_HOSTENT_SIZE); if(!buf) return NULL; /* major failure */ /* * The clearing of the buffer is a workaround for a gethostbyname_r bug in * qnx nto and it is also _required_ for some of these functions on some * platforms. */ #if defined(HAVE_GETHOSTBYNAME_R_5) /* Solaris, IRIX and more */ h = gethostbyname_r(hostname, (struct hostent *)buf, (char *)buf + sizeof(struct hostent), CURL_HOSTENT_SIZE - sizeof(struct hostent), &h_errnop); /* If the buffer is too small, it returns NULL and sets errno to * ERANGE. The errno is thread safe if this is compiled with * -D_REENTRANT as then the 'errno' variable is a macro defined to get * used properly for threads. */ if(h) { ; } else #elif defined(HAVE_GETHOSTBYNAME_R_6) /* Linux */ (void)gethostbyname_r(hostname, (struct hostent *)buf, (char *)buf + sizeof(struct hostent), CURL_HOSTENT_SIZE - sizeof(struct hostent), &h, /* DIFFERENCE */ &h_errnop); /* Redhat 8, using glibc 2.2.93 changed the behavior. Now all of a * sudden this function returns EAGAIN if the given buffer size is too * small. Previous versions are known to return ERANGE for the same * problem. * * This wouldn't be such a big problem if older versions wouldn't * sometimes return EAGAIN on a common failure case. Alas, we can't * assume that EAGAIN *or* ERANGE means ERANGE for any given version of * glibc. * * For now, we do that and thus we may call the function repeatedly and * fail for older glibc versions that return EAGAIN, until we run out of * buffer size (step_size grows beyond CURL_HOSTENT_SIZE). * * If anyone has a better fix, please tell us! * * ------------------------------------------------------------------- * * On October 23rd 2003, Dan C dug up more details on the mysteries of * gethostbyname_r() in glibc: * * In glibc 2.2.5 the interface is different (this has also been * discovered in glibc 2.1.1-6 as shipped by Redhat 6). What I can't * explain, is that tests performed on glibc 2.2.4-34 and 2.2.4-32 * (shipped/upgraded by Redhat 7.2) don't show this behavior! * * In this "buggy" version, the return code is -1 on error and 'errno' * is set to the ERANGE or EAGAIN code. Note that 'errno' is not a * thread-safe variable. */ if(!h) /* failure */ #elif defined(HAVE_GETHOSTBYNAME_R_3) /* AIX, Digital Unix/Tru64, HPUX 10, more? */ /* For AIX 4.3 or later, we don't use gethostbyname_r() at all, because of * the plain fact that it does not return unique full buffers on each * call, but instead several of the pointers in the hostent structs will * point to the same actual data! This have the unfortunate down-side that * our caching system breaks down horribly. Luckily for us though, AIX 4.3 * and more recent versions have a "completely thread-safe"[*] libc where * all the data is stored in thread-specific memory areas making calls to * the plain old gethostbyname() work fine even for multi-threaded * programs. * * This AIX 4.3 or later detection is all made in the configure script. * * Troels Walsted Hansen helped us work this out on March 3rd, 2003. * * [*] = much later we've found out that it isn't at all "completely * thread-safe", but at least the gethostbyname() function is. */ if(CURL_HOSTENT_SIZE >= (sizeof(struct hostent) + sizeof(struct hostent_data))) { /* August 22nd, 2000: Albert Chin-A-Young brought an updated version * that should work! September 20: Richard Prescott worked on the buffer * size dilemma. */ res = gethostbyname_r(hostname, (struct hostent *)buf, (struct hostent_data *)((char *)buf + sizeof(struct hostent))); h_errnop = SOCKERRNO; /* we don't deal with this, but set it anyway */ } else res = -1; /* failure, too smallish buffer size */ if(!res) { /* success */ h = buf; /* result expected in h */ /* This is the worst kind of the different gethostbyname_r() interfaces. * Since we don't know how big buffer this particular lookup required, * we can't realloc down the huge alloc without doing closer analysis of * the returned data. Thus, we always use CURL_HOSTENT_SIZE for every * name lookup. Fixing this would require an extra malloc() and then * calling Curl_addrinfo_copy() that subsequent realloc()s down the new * memory area to the actually used amount. */ } else #endif /* HAVE_...BYNAME_R_5 || HAVE_...BYNAME_R_6 || HAVE_...BYNAME_R_3 */ { h = NULL; /* set return code to NULL */ free(buf); } #else /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */ /* * Here is code for platforms that don't have a thread safe * getaddrinfo() nor gethostbyname_r() function or for which * gethostbyname() is the preferred one. */ else { h = gethostbyname((void *)hostname); #endif /* HAVE_GETADDRINFO_THREADSAFE || HAVE_GETHOSTBYNAME_R */ } if(h) { ai = Curl_he2ai(h, port); if(buf) /* used a *_r() function */ free(buf); } return ai; } #endif /* defined(CURLRES_IPV4) && !defined(CURLRES_ARES) */
733705.c
/** * Copyright (c) 2015, Realsil Semiconductor Corporation. All rights reserved. * */ #include <stdio.h> #include <stdarg.h> #include "trace_uart.h" #include "bt_board.h" #include "serial_api.h" #include "serial_ex_api.h" typedef struct _TraceUartInfo { uint8_t *tx_buffer; uint16_t tx_len; uint8_t tx_busy; bool tx_switch; UART_TX_CB tx_cb; } TRACE_UART_INFO; static TRACE_UART_INFO g_uart_obj; serial_t trace_sobj; //=============================interal========================= #ifndef TRACE_SWITCH_CLOSE static void uart_recv_done(uint32_t id) { //do nothing } static uint32_t traceuart_dma_tx_complete(void *data) { TRACE_UART_INFO *trace_pointer = (TRACE_UART_INFO *) data; if(trace_pointer->tx_cb) trace_pointer->tx_cb(); return 0; } #endif //============================================================== bool trace_uart_init(void) { //init if(!CHECK_SW(EFUSE_SW_TRACE_SWITCH)) { platform_debug("trace_uart_init: TRACE OPEN\r\n"); hal_pinmux_unregister(TRACE_TX, 0x01 << 4); hal_pinmux_unregister(TRACE_RX, 0x01 << 4); hal_gpio_pull_ctrl(TRACE_TX, 0); hal_gpio_pull_ctrl(TRACE_RX, 0); serial_init(&trace_sobj, TRACE_TX, TRACE_RX); serial_baud(&trace_sobj, TRACE_UART_BAUDRATE); serial_format(&trace_sobj, 8, ParityNone, 1); serial_send_comp_handler(&trace_sobj, (void *)traceuart_dma_tx_complete, (uint32_t)&g_uart_obj); serial_recv_comp_handler(&trace_sobj, (void *)uart_recv_done, (uint32_t)&g_uart_obj); g_uart_obj.tx_switch = true; } else { g_uart_obj.tx_switch = false; } return true; } bool trace_uart_deinit(void) { //deinit if(!CHECK_SW(EFUSE_SW_TRACE_SWITCH)) { if (g_uart_obj.tx_switch == true) { serial_free(&trace_sobj); g_uart_obj.tx_switch = false; return true; } else { hci_board_debug("\r\n: trace_uart_deinit:no need\r\n"); return false; } } return true; } bool trace_uart_tx(uint8_t *pstr,uint16_t len, UART_TX_CB tx_cb) { g_uart_obj.tx_cb = tx_cb; if(g_uart_obj.tx_switch == false) { //printf("\r\n trace_uart_deinit has been called please call init \r\n"); if(g_uart_obj.tx_cb) g_uart_obj.tx_cb(); return true; } g_uart_obj.tx_cb = tx_cb; serial_send_blocked(&trace_sobj, (char *)pstr, len,len); if (g_uart_obj.tx_cb) { g_uart_obj.tx_cb(); } #if 0 ret = serial_send_stream_dma(&trace_sobj, (char *)pstr,len); if (ret != 0) { printf("%s Error(%d)\n", __FUNCTION__, ret); } #endif return true; } void bt_trace_set_switch(bool flag) { g_uart_obj.tx_switch = flag; }
435826.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> // socket, setsockopt, accept, send, recv #include <sys/socket.h> #include <signal.h> #include <pthread.h> #include <bluetooth/bluetooth.h> #include <bluetooth/l2cap.h> #include "unitooth.h" pthread_t server_thread; pthread_t rcv_handler_theread; static int serv_sock; // server socket static int client_connected = 0;// boolean to signify that client is connected static int client = -1; // client fd static callbackStr onData = NULL; static char recv_buf[1024]; static void *server_daemonL(); static void *recv_handlerL(); int serverL() { return pthread_create(&server_thread, NULL, server_daemonL, NULL); } void *server_daemonL () { char command[64]; // Turn on discoverable sprintf(command, "echo -e 'discoverable on\nquit' | bluetoothctl"); system(command); struct sockaddr_l2 loc_addr = { 0 }; struct sockaddr_l2 rem_addr = { 0 }; char buf[1024] = { 0 }; socklen_t opt = sizeof(rem_addr); //allocate socket serv_sock = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); // bind socket to port 0x1001 of the first available // bluetooth adapter loc_addr.l2_family = AF_BLUETOOTH; loc_addr.l2_bdaddr = *BDADDR_ANY; loc_addr.l2_psm = htobs(0x1001); bind(serv_sock, (struct sockaddr *)&loc_addr, sizeof(loc_addr)); // put socket into listening mode listen(serv_sock, 1); // accept one connection client = accept(serv_sock, (struct sockaddr *)&rem_addr, &opt); client_connected = 1; pthread_create(&rcv_handler_theread, NULL, recv_handlerL, NULL); return NULL; } int sendL (char *msg) { if(!client_connected) { return -1; } return write(client, msg, strlen(msg)); } void *recv_handlerL () { int checkVal = -1; while(1) { checkVal = read(client, recv_buf ,sizeof(recv_buf)); if(checkVal < 0) break; onData(recv_buf); } return NULL; } void set_callbackL (callbackStr callback) { onData = callback; }
593011.c
/* * The Framework was generated by the ACPLT/OV Builder. * * Builder version: 1.0.1 * Date of file generation: 10-Apr-2002 (17:18:25) */ #ifndef OV_COMPILE_LIBRARY_dynov #define OV_COMPILE_LIBRARY_dynov #endif #include "dynov.h" #include "ov_macros.h" OV_DLLFNCEXPORT void dynov_dynstructure_uncheck( OV_INSTPTR_ov_object pobj ) { } OV_DLLFNCEXPORT OV_BOOL dynov_dynstructure_check( OV_INSTPTR_ov_object pobj ) { OV_INSTPTR_ov_object pchild; OV_INSTPTR_dynov_dynstructure pdynstruct; OV_INSTPTR_dynov_dynvariable pdynvar; OV_VTBLPTR_dynov_dynvariable pvtable; OV_BOOL result; pdynstruct = Ov_DynamicPtrCast(dynov_dynstructure, pobj); if (!pdynstruct) return FALSE; pdynstruct->v_size = 0; Ov_ForEachChild(ov_containment, pdynstruct, pchild) { pdynvar = Ov_DynamicPtrCast(dynov_dynvariable, pchild); if (!pdynvar) return FALSE; Ov_GetVTablePtr(dynov_dynvariable, pvtable, pdynvar); result = pvtable->m_check(Ov_PtrUpCast(ov_object, pdynvar)); if (!result) return FALSE; if (pdynvar->v_varprops & OV_VP_DERIVED) return FALSE; pdynvar->v_offset = pdynstruct->v_size; pdynstruct->v_size += pdynvar->v_size; } if (!pdynstruct->v_size) return FALSE; return TRUE; } OV_DLLFNCEXPORT OV_BOOL dynov_dynstructure_isinstantiable_get( OV_INSTPTR_dynov_dynstructure pobj ) { return pobj->v_isinstantiable; } OV_DLLFNCEXPORT OV_RESULT dynov_dynstructure_isinstantiable_set( OV_INSTPTR_dynov_dynstructure pobj, const OV_BOOL value ) { OV_INSTPTR_ov_variable pvar; OV_INSTPTR_dynov_dynclass pdynclass; if ((value) && (!pobj->v_isinstantiable)) { pobj->v_isinstantiable = dynov_dynstructure_check(Ov_PtrUpCast(ov_object,pobj)); if (!pobj->v_isinstantiable) return OV_ERR_STRUCTDEFMISMATCH; } else if ((!value) && (pobj->v_isinstantiable)) { Ov_ForEachChild(ov_construction, pobj, pvar) { pdynclass = Ov_DynamicPtrCast(dynov_dynclass, Ov_GetParent(ov_containment, pvar)); if (pdynclass) if (pdynclass->v_isinstantiable) return OV_ERR_NOACCESS; } pobj->v_isinstantiable = FALSE; } return OV_ERR_OK; } OV_DLLFNCEXPORT OV_ACCESS dynov_dynstructure_getaccess( OV_INSTPTR_ov_object pobj, const OV_ELEMENT *pelem, const OV_TICKET *pticket ) { OV_INSTPTR_dynov_dynstructure pdynstructure; OV_ACCESS access; OV_ACCESS access2; pdynstructure = Ov_StaticPtrCast(dynov_dynstructure, pobj); switch(pelem->elemtype) { case OV_ET_VARIABLE: if (!ov_string_compare(pelem->elemunion.pvar->v_identifier, "isinstantiable")) return OV_AC_READ | OV_AC_WRITE; access = OV_AC_NONE; if (pdynstructure->v_isinstantiable) access = OV_AC_READ; else access = OV_AC_READ | OV_AC_WRITE; if (!ov_string_compare(pelem->elemunion.pvar->v_identifier, "size")) return access; return OV_AC_NONE; case OV_ET_CHILDLINK: return OV_AC_NONE; case OV_ET_PARENTLINK: if (pdynstructure->v_isinstantiable) { access = OV_AC_READ; access2 = OV_AC_READ; } else { access = OV_AC_READ | OV_AC_WRITE; access2 = OV_AC_READ; } if (pelem->elemunion.passoc == passoc_ov_construction) return access2; if (pelem->elemunion.passoc == passoc_dynov_dynconstruction) return access; return OV_AC_NONE; } if ((pdynstructure->v_isinstantiable) || (pobj->v_pouterobject)) return OV_AC_READ; return OV_AC_READ | OV_AC_WRITE | OV_AC_DELETEABLE | OV_AC_RENAMEABLE; }
806469.c
/* ** my_putchar.c for in /home/habi/Piscine1/C/Jour01/my_putchar ** ** Made by HABI Acal ** Login <[email protected]> ** ** Started on Mon Sep 25 13:27:20 2017 HABI Acal ** Last update Mon Sep 25 13:28:48 2017 HABI Acal */ #include <unistd.h> void my_putchar(char c) { write(1, &c, 1); }
555199.c
/* Barrier default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Barrier_intra_dissemination_cnt = { .id = MPIDI_POSIX_Barrier_intra_dissemination_id }; /* Bcast default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Bcast_intra_binomial_cnt = { .id = MPIDI_POSIX_Bcast_intra_binomial_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Bcast_intra_scatter_recursive_doubling_allgather_cnt = { .id = MPIDI_POSIX_Bcast_intra_scatter_recursive_doubling_allgather_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Bcast_intra_scatter_ring_allgather_cnt = { .id = MPIDI_POSIX_Bcast_intra_scatter_ring_allgather_id }; /* Reduce default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_intra_reduce_scatter_gather_cnt = { .id = MPIDI_POSIX_Reduce_intra_reduce_scatter_gather_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_intra_binomial_cnt = { .id = MPIDI_POSIX_Reduce_intra_binomial_id }; /* Allreduce default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allreduce_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Allreduce_intra_recursive_doubling_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allreduce_intra_reduce_scatter_allgather_cnt = { .id = MPIDI_POSIX_Allreduce_intra_reduce_scatter_allgather_id }; /* Alltoall default POSIX containers initialization */ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoall_intra_pairwise_sendrecv_replace_cnt = { .id = MPIDI_POSIX_Alltoall_intra_pairwise_sendrecv_replace_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoall_intra_brucks_cnt = { .id = MPIDI_POSIX_Alltoall_intra_brucks_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoall_intra_scattered_cnt = { .id = MPIDI_POSIX_Alltoall_intra_scattered_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoall_intra_pairwise_cnt = { .id = MPIDI_POSIX_Alltoall_intra_pairwise_id }; /* Alltoallv default POSIX containers initialization */ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoallv_intra_pairwise_sendrecv_replace_cnt = { .id = MPIDI_POSIX_Alltoallv_intra_pairwise_sendrecv_replace_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoallv_intra_scattered_cnt = { .id = MPIDI_POSIX_Alltoallv_intra_scattered_id }; /* Alltoallw default POSIX containers initialization */ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoallw_intra_pairwise_sendrecv_replace_cnt = { .id = MPIDI_POSIX_Alltoallw_intra_pairwise_sendrecv_replace_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Alltoallw_intra_scattered_cnt = { .id = MPIDI_POSIX_Alltoallw_intra_scattered_id }; /* Allgather default POSIX containers initialization */ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgather_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Allgather_intra_recursive_doubling_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgather_intra_brucks_cnt = { .id = MPIDI_POSIX_Allgather_intra_brucks_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgather_intra_ring_cnt = { .id = MPIDI_POSIX_Allgather_intra_ring_id }; /* Allgatherv default POSIX containers initialization */ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgatherv_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Allgatherv_intra_recursive_doubling_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgatherv_intra_brucks_cnt = { .id = MPIDI_POSIX_Allgatherv_intra_brucks_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Allgatherv_intra_ring_cnt = { .id = MPIDI_POSIX_Allgatherv_intra_ring_id }; /* Gather default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Gather_intra_binomial_cnt = { .id = MPIDI_POSIX_Gather_intra_binomial_id }; /* Gatherv default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Gatherv_allcomm_linear_cnt = { .id = MPIDI_POSIX_Gatherv_allcomm_linear_id }; /* Scatter default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Scatter_intra_binomial_cnt = { .id = MPIDI_POSIX_Scatter_intra_binomial_id }; /* Scatterv default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Scatterv_allcomm_linear_cnt = { .id = MPIDI_POSIX_Scatterv_allcomm_linear_id }; /* Reduce_scatter default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_intra_noncommutative_cnt = { .id = MPIDI_POSIX_Reduce_scatter_intra_noncommutative_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_intra_pairwise_cnt = { .id = MPIDI_POSIX_Reduce_scatter_intra_pairwise_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Reduce_scatter_intra_recursive_doubling_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_intra_recursive_halving_cnt = { .id = MPIDI_POSIX_Reduce_scatter_intra_recursive_halving_id }; /* Reduce_scatter_block default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_block_intra_noncommutative_cnt = { .id = MPIDI_POSIX_Reduce_scatter_block_intra_noncommutative_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_block_intra_pairwise_cnt = { .id = MPIDI_POSIX_Reduce_scatter_block_intra_pairwise_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_block_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Reduce_scatter_block_intra_recursive_doubling_id }; const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Reduce_scatter_block_intra_recursive_halving_cnt = { .id = MPIDI_POSIX_Reduce_scatter_block_intra_recursive_halving_id }; /* Scan default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Scan_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Scan_intra_recursive_doubling_id }; /* Exscan default POSIX containers initialization*/ const MPIDI_POSIX_coll_algo_container_t MPIDI_POSIX_Exscan_intra_recursive_doubling_cnt = { .id = MPIDI_POSIX_Exscan_intra_recursive_doubling_id };
230183.c
/* mbed Microcontroller Library * SPDX-License-Identifier: BSD-3-Clause ****************************************************************************** * * Copyright (c) 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 * ****************************************************************************** */ #include "i2c_device.h" #include "mbed_assert.h" #include "mbed_error.h" #include "stm32h7xx_ll_rcc.h" /* Define I2C Device */ #if DEVICE_I2C /** * @brief Get I2C clock source frequency according I2C instance used. * @param i2c I2C instance name. * @retval I2C clock source frequency in Hz. */ uint32_t i2c_get_pclk(I2CName i2c) { uint32_t clocksource; uint32_t pclk = 0; PLL3_ClocksTypeDef pll3_clocks; if ((i2c == I2C_1) || (i2c == I2C_2) || (i2c == I2C_3)) { clocksource = __HAL_RCC_GET_I2C123_SOURCE(); switch (clocksource) { case RCC_I2C123CLKSOURCE_D2PCLK1: pclk = HAL_RCC_GetPCLK1Freq(); break; case RCC_I2C123CLKSOURCE_PLL3: HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks); pclk = pll3_clocks.PLL3_R_Frequency; break; case RCC_I2C123CLKSOURCE_HSI: pclk = HSI_VALUE; break; case RCC_I2C123CLKSOURCE_CSI: pclk = CSI_VALUE; break; default: // should not happend error("I2C123: Invalid clock source"); break; } } #if defined I2C4_BASE else if (i2c == I2C_4) { clocksource = __HAL_RCC_GET_I2C4_SOURCE(); switch (clocksource) { case RCC_I2C4CLKSOURCE_D3PCLK1: pclk = HAL_RCCEx_GetD3PCLK1Freq(); break; case RCC_I2C4CLKSOURCE_PLL3: HAL_RCCEx_GetPLL3ClockFreq(&pll3_clocks); pclk = pll3_clocks.PLL3_R_Frequency; break; case RCC_I2C4CLKSOURCE_HSI: pclk = HSI_VALUE; break; case RCC_I2C4CLKSOURCE_CSI: pclk = CSI_VALUE; break; default: // should not happend error("I2C4: Invalid clock source"); break; } } #endif else { // should not happend error("I2C: unknown instance"); } return pclk; } #endif // DEVICE_I2C
571804.c
// RUN: %clang_cc1 -ffreestanding %s -triple=x86_64-apple-darwin -target-feature +avx512dq -emit-llvm -o - -Wall -Werror | FileCheck %s #include <immintrin.h> __m512i test_mm512_mullo_epi64 (__m512i __A, __m512i __B) { // CHECK-LABEL: @test_mm512_mullo_epi64 // CHECK: mul <8 x i64> return (__m512i) ((__v8di) __A * (__v8di) __B); } __m512i test_mm512_mask_mullo_epi64 (__m512i __W, __mmask8 __U, __m512i __A, __m512i __B) { // CHECK-LABEL: @test_mm512_mask_mullo_epi64 // CHECK: mul <8 x i64> %{{.*}}, %{{.*}} // CHECK: select <8 x i1> %{{.*}}, <8 x i64> %{{.*}}, <8 x i64> %{{.*}} return (__m512i) _mm512_mask_mullo_epi64(__W, __U, __A, __B); } __m512i test_mm512_maskz_mullo_epi64 (__mmask8 __U, __m512i __A, __m512i __B) { // CHECK-LABEL: @test_mm512_maskz_mullo_epi64 // CHECK: mul <8 x i64> %{{.*}}, %{{.*}} // CHECK: select <8 x i1> %{{.*}}, <8 x i64> %{{.*}}, <8 x i64> %{{.*}} return (__m512i) _mm512_maskz_mullo_epi64(__U, __A, __B); } __m512d test_mm512_xor_pd (__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_xor_pd // CHECK: xor <8 x i64> return (__m512d) _mm512_xor_pd(__A, __B); } __m512d test_mm512_mask_xor_pd (__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_xor_pd // CHECK: xor <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_mask_xor_pd(__W, __U, __A, __B); } __m512d test_mm512_maskz_xor_pd (__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_xor_pd // CHECK: xor <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_maskz_xor_pd(__U, __A, __B); } __m512 test_mm512_xor_ps (__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_xor_ps // CHECK: xor <16 x i32> return (__m512) _mm512_xor_ps(__A, __B); } __m512 test_mm512_mask_xor_ps (__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_xor_ps // CHECK: xor <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_mask_xor_ps(__W, __U, __A, __B); } __m512 test_mm512_maskz_xor_ps (__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_xor_ps // CHECK: xor <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_maskz_xor_ps(__U, __A, __B); } __m512d test_mm512_or_pd (__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_or_pd // CHECK: or <8 x i64> return (__m512d) _mm512_or_pd(__A, __B); } __m512d test_mm512_mask_or_pd (__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_or_pd // CHECK: or <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_mask_or_pd(__W, __U, __A, __B); } __m512d test_mm512_maskz_or_pd (__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_or_pd // CHECK: or <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_maskz_or_pd(__U, __A, __B); } __m512 test_mm512_or_ps (__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_or_ps // CHECK: or <16 x i32> return (__m512) _mm512_or_ps(__A, __B); } __m512 test_mm512_mask_or_ps (__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_or_ps // CHECK: or <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_mask_or_ps(__W, __U, __A, __B); } __m512 test_mm512_maskz_or_ps (__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_or_ps // CHECK: or <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_maskz_or_ps(__U, __A, __B); } __m512d test_mm512_and_pd (__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_and_pd // CHECK: and <8 x i64> return (__m512d) _mm512_and_pd(__A, __B); } __m512d test_mm512_mask_and_pd (__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_and_pd // CHECK: and <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_mask_and_pd(__W, __U, __A, __B); } __m512d test_mm512_maskz_and_pd (__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_and_pd // CHECK: and <8 x i64> // CHECK: %[[MASK:.*]] = bitcast i8 %{{.*}} to <8 x i1> // CHECK: select <8 x i1> %[[MASK]], <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_maskz_and_pd(__U, __A, __B); } __m512 test_mm512_and_ps (__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_and_ps // CHECK: and <16 x i32> return (__m512) _mm512_and_ps(__A, __B); } __m512 test_mm512_mask_and_ps (__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_and_ps // CHECK: and <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_mask_and_ps(__W, __U, __A, __B); } __m512 test_mm512_maskz_and_ps (__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_and_ps // CHECK: and <16 x i32> // CHECK: %[[MASK:.*]] = bitcast i16 %{{.*}} to <16 x i1> // CHECK: select <16 x i1> %[[MASK]], <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_maskz_and_ps(__U, __A, __B); } __m512d test_mm512_andnot_pd (__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_andnot_pd // CHECK: xor <8 x i64> %{{.*}}, <i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1> // CHECK: and <8 x i64> return (__m512d) _mm512_andnot_pd(__A, __B); } __m512d test_mm512_mask_andnot_pd (__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_andnot_pd // CHECK: xor <8 x i64> %{{.*}}, <i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1> // CHECK: and <8 x i64> %{{.*}}, %{{.*}} // CHECK: select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_mask_andnot_pd(__W, __U, __A, __B); } __m512d test_mm512_maskz_andnot_pd (__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_andnot_pd // CHECK: xor <8 x i64> %{{.*}}, <i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1, i64 -1> // CHECK: and <8 x i64> %{{.*}}, %{{.*}} // CHECK: select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}} return (__m512d) _mm512_maskz_andnot_pd(__U, __A, __B); } __m512 test_mm512_andnot_ps (__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_andnot_ps // CHECK: xor <16 x i32> %{{.*}}, <i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1> // CHECK: and <16 x i32> return (__m512) _mm512_andnot_ps(__A, __B); } __m512 test_mm512_mask_andnot_ps (__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_andnot_ps // CHECK: xor <16 x i32> %{{.*}}, <i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1> // CHECK: and <16 x i32> %{{.*}}, %{{.*}} // CHECK: select <16 x i1> %{{.*}}, <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_mask_andnot_ps(__W, __U, __A, __B); } __m512 test_mm512_maskz_andnot_ps (__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_andnot_ps // CHECK: xor <16 x i32> %{{.*}}, <i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1, i32 -1> // CHECK: and <16 x i32> %{{.*}}, %{{.*}} // CHECK: select <16 x i1> %{{.*}}, <16 x float> %{{.*}}, <16 x float> %{{.*}} return (__m512) _mm512_maskz_andnot_ps(__U, __A, __B); } __m512i test_mm512_cvtpd_epi64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvtpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_cvtpd_epi64(__A); } __m512i test_mm512_mask_cvtpd_epi64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvtpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_mask_cvtpd_epi64(__W, __U, __A); } __m512i test_mm512_maskz_cvtpd_epi64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvtpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_maskz_cvtpd_epi64(__U, __A); } __m512i test_mm512_cvt_roundpd_epi64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_cvt_roundpd_epi64(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_mask_cvt_roundpd_epi64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_mask_cvt_roundpd_epi64(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_maskz_cvt_roundpd_epi64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvtpd2qq.512 return _mm512_maskz_cvt_roundpd_epi64(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_cvtpd_epu64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvtpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_cvtpd_epu64(__A); } __m512i test_mm512_mask_cvtpd_epu64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvtpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_mask_cvtpd_epu64(__W, __U, __A); } __m512i test_mm512_maskz_cvtpd_epu64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvtpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_maskz_cvtpd_epu64(__U, __A); } __m512i test_mm512_cvt_roundpd_epu64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_cvt_roundpd_epu64(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_mask_cvt_roundpd_epu64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_mask_cvt_roundpd_epu64(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_maskz_cvt_roundpd_epu64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvtpd2uqq.512 return _mm512_maskz_cvt_roundpd_epu64(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_cvtps_epi64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvtps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_cvtps_epi64(__A); } __m512i test_mm512_mask_cvtps_epi64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvtps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_mask_cvtps_epi64(__W, __U, __A); } __m512i test_mm512_maskz_cvtps_epi64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvtps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_maskz_cvtps_epi64(__U, __A); } __m512i test_mm512_cvt_roundps_epi64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_cvt_roundps_epi64(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_mask_cvt_roundps_epi64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_mask_cvt_roundps_epi64(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_maskz_cvt_roundps_epi64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvtps2qq.512 return _mm512_maskz_cvt_roundps_epi64(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_cvtps_epu64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvtps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_cvtps_epu64(__A); } __m512i test_mm512_mask_cvtps_epu64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvtps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_mask_cvtps_epu64(__W, __U, __A); } __m512i test_mm512_maskz_cvtps_epu64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvtps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_maskz_cvtps_epu64(__U, __A); } __m512i test_mm512_cvt_roundps_epu64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_cvt_roundps_epu64(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_mask_cvt_roundps_epu64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_mask_cvt_roundps_epu64(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_maskz_cvt_roundps_epu64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvtps2uqq.512 return _mm512_maskz_cvt_roundps_epu64(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_cvtepi64_pd(__m512i __A) { // CHECK-LABEL: @test_mm512_cvtepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_cvtepi64_pd(__A); } __m512d test_mm512_mask_cvtepi64_pd(__m512d __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvtepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_mask_cvtepi64_pd(__W, __U, __A); } __m512d test_mm512_maskz_cvtepi64_pd(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvtepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_maskz_cvtepi64_pd(__U, __A); } __m512d test_mm512_cvt_roundepi64_pd(__m512i __A) { // CHECK-LABEL: @test_mm512_cvt_roundepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_cvt_roundepi64_pd(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_mask_cvt_roundepi64_pd(__m512d __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_mask_cvt_roundepi64_pd(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_maskz_cvt_roundepi64_pd(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundepi64_pd // CHECK: @llvm.x86.avx512.mask.cvtqq2pd.512 return _mm512_maskz_cvt_roundepi64_pd(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_cvtepi64_ps(__m512i __A) { // CHECK-LABEL: @test_mm512_cvtepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_cvtepi64_ps(__A); } __m256 test_mm512_mask_cvtepi64_ps(__m256 __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvtepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_mask_cvtepi64_ps(__W, __U, __A); } __m256 test_mm512_maskz_cvtepi64_ps(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvtepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_maskz_cvtepi64_ps(__U, __A); } __m256 test_mm512_cvt_roundepi64_ps(__m512i __A) { // CHECK-LABEL: @test_mm512_cvt_roundepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_cvt_roundepi64_ps(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_mask_cvt_roundepi64_ps(__m256 __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_mask_cvt_roundepi64_ps(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_maskz_cvt_roundepi64_ps(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundepi64_ps // CHECK: @llvm.x86.avx512.mask.cvtqq2ps.512 return _mm512_maskz_cvt_roundepi64_ps(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512i test_mm512_cvttpd_epi64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvttpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_cvttpd_epi64(__A); } __m512i test_mm512_mask_cvttpd_epi64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvttpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_mask_cvttpd_epi64(__W, __U, __A); } __m512i test_mm512_maskz_cvttpd_epi64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvttpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_maskz_cvttpd_epi64(__U, __A); } __m512i test_mm512_cvtt_roundpd_epi64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvtt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_cvtt_roundpd_epi64(__A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_mask_cvtt_roundpd_epi64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvtt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_mask_cvtt_roundpd_epi64(__W, __U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_maskz_cvtt_roundpd_epi64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvtt_roundpd_epi64 // CHECK: @llvm.x86.avx512.mask.cvttpd2qq.512 return _mm512_maskz_cvtt_roundpd_epi64(__U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_cvttpd_epu64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvttpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_cvttpd_epu64(__A); } __m512i test_mm512_mask_cvttpd_epu64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvttpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_mask_cvttpd_epu64(__W, __U, __A); } __m512i test_mm512_maskz_cvttpd_epu64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvttpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_maskz_cvttpd_epu64(__U, __A); } __m512i test_mm512_cvtt_roundpd_epu64(__m512d __A) { // CHECK-LABEL: @test_mm512_cvtt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_cvtt_roundpd_epu64(__A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_mask_cvtt_roundpd_epu64(__m512i __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_cvtt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_mask_cvtt_roundpd_epu64(__W, __U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_maskz_cvtt_roundpd_epu64(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_cvtt_roundpd_epu64 // CHECK: @llvm.x86.avx512.mask.cvttpd2uqq.512 return _mm512_maskz_cvtt_roundpd_epu64(__U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_cvttps_epi64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvttps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_cvttps_epi64(__A); } __m512i test_mm512_mask_cvttps_epi64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvttps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_mask_cvttps_epi64(__W, __U, __A); } __m512i test_mm512_maskz_cvttps_epi64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvttps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_maskz_cvttps_epi64(__U, __A); } __m512i test_mm512_cvtt_roundps_epi64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvtt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_cvtt_roundps_epi64(__A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_mask_cvtt_roundps_epi64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvtt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_mask_cvtt_roundps_epi64(__W, __U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_maskz_cvtt_roundps_epi64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvtt_roundps_epi64 // CHECK: @llvm.x86.avx512.mask.cvttps2qq.512 return _mm512_maskz_cvtt_roundps_epi64(__U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_cvttps_epu64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvttps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_cvttps_epu64(__A); } __m512i test_mm512_mask_cvttps_epu64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvttps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_mask_cvttps_epu64(__W, __U, __A); } __m512i test_mm512_maskz_cvttps_epu64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvttps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_maskz_cvttps_epu64(__U, __A); } __m512i test_mm512_cvtt_roundps_epu64(__m256 __A) { // CHECK-LABEL: @test_mm512_cvtt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_cvtt_roundps_epu64(__A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_mask_cvtt_roundps_epu64(__m512i __W, __mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_cvtt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_mask_cvtt_roundps_epu64(__W, __U, __A, _MM_FROUND_CUR_DIRECTION); } __m512i test_mm512_maskz_cvtt_roundps_epu64(__mmask8 __U, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_cvtt_roundps_epu64 // CHECK: @llvm.x86.avx512.mask.cvttps2uqq.512 return _mm512_maskz_cvtt_roundps_epu64(__U, __A, _MM_FROUND_CUR_DIRECTION); } __m512d test_mm512_cvtepu64_pd(__m512i __A) { // CHECK-LABEL: @test_mm512_cvtepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_cvtepu64_pd(__A); } __m512d test_mm512_mask_cvtepu64_pd(__m512d __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvtepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_mask_cvtepu64_pd(__W, __U, __A); } __m512d test_mm512_maskz_cvtepu64_pd(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvtepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_maskz_cvtepu64_pd(__U, __A); } __m512d test_mm512_cvt_roundepu64_pd(__m512i __A) { // CHECK-LABEL: @test_mm512_cvt_roundepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_cvt_roundepu64_pd(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_mask_cvt_roundepu64_pd(__m512d __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_mask_cvt_roundepu64_pd(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_maskz_cvt_roundepu64_pd(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundepu64_pd // CHECK: @llvm.x86.avx512.mask.cvtuqq2pd.512 return _mm512_maskz_cvt_roundepu64_pd(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_cvtepu64_ps(__m512i __A) { // CHECK-LABEL: @test_mm512_cvtepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_cvtepu64_ps(__A); } __m256 test_mm512_mask_cvtepu64_ps(__m256 __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvtepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_mask_cvtepu64_ps(__W, __U, __A); } __m256 test_mm512_maskz_cvtepu64_ps(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvtepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_maskz_cvtepu64_ps(__U, __A); } __m256 test_mm512_cvt_roundepu64_ps(__m512i __A) { // CHECK-LABEL: @test_mm512_cvt_roundepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_cvt_roundepu64_ps(__A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_mask_cvt_roundepu64_ps(__m256 __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_cvt_roundepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_mask_cvt_roundepu64_ps(__W, __U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m256 test_mm512_maskz_cvt_roundepu64_ps(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_cvt_roundepu64_ps // CHECK: @llvm.x86.avx512.mask.cvtuqq2ps.512 return _mm512_maskz_cvt_roundepu64_ps(__U, __A, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } __m512d test_mm512_range_pd(__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_range_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_range_pd(__A, __B, 4); } __m512d test_mm512_mask_range_pd(__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_range_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_mask_range_pd(__W, __U, __A, __B, 4); } __m512d test_mm512_maskz_range_pd(__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_range_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_maskz_range_pd(__U, __A, __B, 4); } __m512d test_mm512_range_round_pd(__m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_range_round_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_range_round_pd(__A, __B, 4, 8); } __m512d test_mm512_mask_range_round_pd(__m512d __W, __mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_mask_range_round_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_mask_range_round_pd(__W, __U, __A, __B, 4, 8); } __m512d test_mm512_maskz_range_round_pd(__mmask8 __U, __m512d __A, __m512d __B) { // CHECK-LABEL: @test_mm512_maskz_range_round_pd // CHECK: @llvm.x86.avx512.mask.range.pd.512 return _mm512_maskz_range_round_pd(__U, __A, __B, 4, 8); } __m128d test_mm512_range_round_sd(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_range_round_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_range_round_sd(__A, __B, 4, 8); } __m128d test_mm512_mask_range_round_sd(__m128d __W, __mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: test_mm512_mask_range_round_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_mask_range_round_sd(__W, __U, __A, __B, 4, 8); } __m128d test_mm512_maskz_range_round_sd(__mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_maskz_range_round_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_maskz_range_round_sd(__U, __A, __B, 4, 8); } __m128d test_mm512_range_round_ss(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_range_round_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_range_round_ss(__A, __B, 4, 8); } __m128d test_mm512_mask_range_round_ss(__m128 __W, __mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm512_mask_range_round_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_mask_range_round_ss(__W, __U, __A, __B, 4, 8); } __m128 test_mm512_maskz_range_round_ss(__mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm512_maskz_range_round_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_maskz_range_round_ss(__U, __A, __B, 4, 8); } __m128d test_mm_range_sd(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_range_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_range_sd(__A, __B, 4); } __m128d test_mm_mask_range_sd(__m128d __W, __mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: test_mm_mask_range_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_mask_range_sd(__W, __U, __A, __B, 4); } __m128d test_mm_maskz_range_sd(__mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_maskz_range_sd // CHECK: @llvm.x86.avx512.mask.range.sd return _mm_maskz_range_sd(__U, __A, __B, 4); } __m128d test_mm_range_ss(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_range_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_range_ss(__A, __B, 4); } __m128d test_mm_mask_range_ss(__m128 __W, __mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_mask_range_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_mask_range_ss(__W, __U, __A, __B, 4); } __m128 test_mm_maskz_range_ss(__mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_maskz_range_ss // CHECK: @llvm.x86.avx512.mask.range.ss return _mm_maskz_range_ss(__U, __A, __B, 4); } __m512 test_mm512_range_ps(__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_range_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_range_ps(__A, __B, 4); } __m512 test_mm512_mask_range_ps(__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_range_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_mask_range_ps(__W, __U, __A, __B, 4); } __m512 test_mm512_maskz_range_ps(__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_range_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_maskz_range_ps(__U, __A, __B, 4); } __m512 test_mm512_range_round_ps(__m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_range_round_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_range_round_ps(__A, __B, 4, 8); } __m512 test_mm512_mask_range_round_ps(__m512 __W, __mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_mask_range_round_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_mask_range_round_ps(__W, __U, __A, __B, 4, 8); } __m512 test_mm512_maskz_range_round_ps(__mmask16 __U, __m512 __A, __m512 __B) { // CHECK-LABEL: @test_mm512_maskz_range_round_ps // CHECK: @llvm.x86.avx512.mask.range.ps.512 return _mm512_maskz_range_round_ps(__U, __A, __B, 4, 8); } __m512d test_mm512_reduce_pd(__m512d __A) { // CHECK-LABEL: @test_mm512_reduce_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_reduce_pd(__A, 4); } __m512d test_mm512_mask_reduce_pd(__m512d __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_reduce_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_mask_reduce_pd(__W, __U, __A, 4); } __m512d test_mm512_maskz_reduce_pd(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_reduce_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_maskz_reduce_pd(__U, __A, 4); } __m512 test_mm512_reduce_ps(__m512 __A) { // CHECK-LABEL: @test_mm512_reduce_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_reduce_ps(__A, 4); } __m512 test_mm512_mask_reduce_ps(__m512 __W, __mmask16 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_mask_reduce_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_mask_reduce_ps(__W, __U, __A, 4); } __m512 test_mm512_maskz_reduce_ps(__mmask16 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_maskz_reduce_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_maskz_reduce_ps(__U, __A, 4); } __m512d test_mm512_reduce_round_pd(__m512d __A) { // CHECK-LABEL: @test_mm512_reduce_round_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_reduce_round_pd(__A, 4, 8); } __m512d test_mm512_mask_reduce_round_pd(__m512d __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_reduce_round_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_mask_reduce_round_pd(__W, __U, __A, 4, 8); } __m512d test_mm512_maskz_reduce_round_pd(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_reduce_round_pd // CHECK: @llvm.x86.avx512.mask.reduce.pd.512 return _mm512_maskz_reduce_round_pd(__U, __A, 4, 8); } __m512 test_mm512_reduce_round_ps(__m512 __A) { // CHECK-LABEL: @test_mm512_reduce_round_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_reduce_round_ps(__A, 4, 8); } __m512 test_mm512_mask_reduce_round_ps(__m512 __W, __mmask16 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_mask_reduce_round_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_mask_reduce_round_ps(__W, __U, __A, 4, 8); } __m512 test_mm512_maskz_reduce_round_ps(__mmask16 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_maskz_reduce_round_ps // CHECK: @llvm.x86.avx512.mask.reduce.ps.512 return _mm512_maskz_reduce_round_ps(__U, __A, 4, 8); } __m128 test_mm_reduce_ss(__m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_reduce_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_reduce_ss(__A, __B, 4); } __m128 test_mm_mask_reduce_ss(__m128 __W, __mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_mask_reduce_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_mask_reduce_ss(__W, __U, __A, __B, 4); } __m128 test_mm_maskz_reduce_ss(__mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_maskz_reduce_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_maskz_reduce_ss(__U, __A, __B, 4); } __m128 test_mm_reduce_round_ss(__m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_reduce_round_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_reduce_round_ss(__A, __B, 4, 8); } __m128 test_mm_mask_reduce_round_ss(__m128 __W, __mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_mask_reduce_round_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_mask_reduce_round_ss(__W, __U, __A, __B, 4, 8); } __m128 test_mm_maskz_reduce_round_ss(__mmask8 __U, __m128 __A, __m128 __B) { // CHECK-LABEL: @test_mm_maskz_reduce_round_ss // CHECK: @llvm.x86.avx512.mask.reduce.ss return _mm_maskz_reduce_round_ss(__U, __A, __B, 4, 8); } __m128d test_mm_reduce_sd(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_reduce_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_reduce_sd(__A, __B, 4); } __m128d test_mm_mask_reduce_sd(__m128d __W, __mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_mask_reduce_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_mask_reduce_sd(__W, __U, __A, __B, 4); } __m128d test_mm_maskz_reduce_sd(__mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_maskz_reduce_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_maskz_reduce_sd(__U, __A, __B, 4); } __m128d test_mm_reduce_round_sd(__m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_reduce_round_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_reduce_round_sd(__A, __B, 4, 8); } __m128d test_mm_mask_reduce_round_sd(__m128d __W, __mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_mask_reduce_round_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_mask_reduce_round_sd(__W, __U, __A, __B, 4, 8); } __m128d test_mm_maskz_reduce_round_sd(__mmask8 __U, __m128d __A, __m128d __B) { // CHECK-LABEL: @test_mm_maskz_reduce_round_sd // CHECK: @llvm.x86.avx512.mask.reduce.sd return _mm_maskz_reduce_round_sd(__U, __A, __B, 4, 8); } __mmask16 test_mm512_movepi32_mask(__m512i __A) { // CHECK-LABEL: @test_mm512_movepi32_mask // CHECK: @llvm.x86.avx512.cvtd2mask.512 return _mm512_movepi32_mask(__A); } __m512i test_mm512_movm_epi32(__mmask16 __A) { // CHECK-LABEL: @test_mm512_movm_epi32 // CHECK: @llvm.x86.avx512.cvtmask2d.512 return _mm512_movm_epi32(__A); } __m512i test_mm512_movm_epi64(__mmask8 __A) { // CHECK-LABEL: @test_mm512_movm_epi64 // CHECK: @llvm.x86.avx512.cvtmask2q.512 return _mm512_movm_epi64(__A); } __mmask8 test_mm512_movepi64_mask(__m512i __A) { // CHECK-LABEL: @test_mm512_movepi64_mask // CHECK: @llvm.x86.avx512.cvtq2mask.512 return _mm512_movepi64_mask(__A); } __m512 test_mm512_broadcast_f32x2(__m128 __A) { // CHECK-LABEL: @test_mm512_broadcast_f32x2 // CHECK: @llvm.x86.avx512.mask.broadcastf32x2 return _mm512_broadcast_f32x2(__A); } __m512 test_mm512_mask_broadcast_f32x2(__m512 __O, __mmask16 __M, __m128 __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_f32x2 // CHECK: @llvm.x86.avx512.mask.broadcastf32x2 return _mm512_mask_broadcast_f32x2(__O, __M, __A); } __m512 test_mm512_maskz_broadcast_f32x2(__mmask16 __M, __m128 __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_f32x2 // CHECK: @llvm.x86.avx512.mask.broadcastf32x2 return _mm512_maskz_broadcast_f32x2(__M, __A); } __m512 test_mm512_broadcast_f32x8(__m256 __A) { // CHECK-LABEL: @test_mm512_broadcast_f32x8 // CHECK: @llvm.x86.avx512.mask.broadcastf32x8 return _mm512_broadcast_f32x8(__A); } __m512 test_mm512_mask_broadcast_f32x8(__m512 __O, __mmask16 __M, __m256 __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_f32x8 // CHECK: @llvm.x86.avx512.mask.broadcastf32x8 return _mm512_mask_broadcast_f32x8(__O, __M, __A); } __m512 test_mm512_maskz_broadcast_f32x8(__mmask16 __M, __m256 __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_f32x8 // CHECK: @llvm.x86.avx512.mask.broadcastf32x8 return _mm512_maskz_broadcast_f32x8(__M, __A); } __m512d test_mm512_broadcast_f64x2(__m128d __A) { // CHECK-LABEL: @test_mm512_broadcast_f64x2 // CHECK: @llvm.x86.avx512.mask.broadcastf64x2 return _mm512_broadcast_f64x2(__A); } __m512d test_mm512_mask_broadcast_f64x2(__m512d __O, __mmask8 __M, __m128d __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_f64x2 // CHECK: @llvm.x86.avx512.mask.broadcastf64x2 return _mm512_mask_broadcast_f64x2(__O, __M, __A); } __m512d test_mm512_maskz_broadcast_f64x2(__mmask8 __M, __m128d __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_f64x2 // CHECK: @llvm.x86.avx512.mask.broadcastf64x2 return _mm512_maskz_broadcast_f64x2(__M, __A); } __m512i test_mm512_broadcast_i32x2(__m128i __A) { // CHECK-LABEL: @test_mm512_broadcast_i32x2 // CHECK: @llvm.x86.avx512.mask.broadcasti32x2 return _mm512_broadcast_i32x2(__A); } __m512i test_mm512_mask_broadcast_i32x2(__m512i __O, __mmask16 __M, __m128i __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_i32x2 // CHECK: @llvm.x86.avx512.mask.broadcasti32x2 return _mm512_mask_broadcast_i32x2(__O, __M, __A); } __m512i test_mm512_maskz_broadcast_i32x2(__mmask16 __M, __m128i __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_i32x2 // CHECK: @llvm.x86.avx512.mask.broadcasti32x2 return _mm512_maskz_broadcast_i32x2(__M, __A); } __m512i test_mm512_broadcast_i32x8(__m256i __A) { // CHECK-LABEL: @test_mm512_broadcast_i32x8 // CHECK: @llvm.x86.avx512.mask.broadcasti32x8 return _mm512_broadcast_i32x8(__A); } __m512i test_mm512_mask_broadcast_i32x8(__m512i __O, __mmask16 __M, __m256i __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_i32x8 // CHECK: @llvm.x86.avx512.mask.broadcasti32x8 return _mm512_mask_broadcast_i32x8(__O, __M, __A); } __m512i test_mm512_maskz_broadcast_i32x8(__mmask16 __M, __m256i __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_i32x8 // CHECK: @llvm.x86.avx512.mask.broadcasti32x8 return _mm512_maskz_broadcast_i32x8(__M, __A); } __m512i test_mm512_broadcast_i64x2(__m128i __A) { // CHECK-LABEL: @test_mm512_broadcast_i64x2 // CHECK: @llvm.x86.avx512.mask.broadcasti64x2 return _mm512_broadcast_i64x2(__A); } __m512i test_mm512_mask_broadcast_i64x2(__m512i __O, __mmask8 __M, __m128i __A) { // CHECK-LABEL: @test_mm512_mask_broadcast_i64x2 // CHECK: @llvm.x86.avx512.mask.broadcasti64x2 return _mm512_mask_broadcast_i64x2(__O, __M, __A); } __m512i test_mm512_maskz_broadcast_i64x2(__mmask8 __M, __m128i __A) { // CHECK-LABEL: @test_mm512_maskz_broadcast_i64x2 // CHECK: @llvm.x86.avx512.mask.broadcasti64x2 return _mm512_maskz_broadcast_i64x2(__M, __A); } __m256 test_mm512_extractf32x8_ps(__m512 __A) { // CHECK-LABEL: @test_mm512_extractf32x8_ps // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> undef, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> return _mm512_extractf32x8_ps(__A, 1); } __m256 test_mm512_mask_extractf32x8_ps(__m256 __W, __mmask8 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_mask_extractf32x8_ps // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> undef, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> // CHECK: select <8 x i1> %{{.*}}, <8 x float> %{{.*}}, <8 x float> %{{.*}} return _mm512_mask_extractf32x8_ps(__W, __U, __A, 1); } __m256 test_mm512_maskz_extractf32x8_ps(__mmask8 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_maskz_extractf32x8_ps // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> undef, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> // CHECK: select <8 x i1> %{{.*}}, <8 x float> %{{.*}}, <8 x float> %{{.*}} return _mm512_maskz_extractf32x8_ps(__U, __A, 1); } __m128d test_mm512_extractf64x2_pd(__m512d __A) { // CHECK-LABEL: @test_mm512_extractf64x2_pd // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> undef, <2 x i32> <i32 6, i32 7> return _mm512_extractf64x2_pd(__A, 3); } __m128d test_mm512_mask_extractf64x2_pd(__m128d __W, __mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_extractf64x2_pd // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> undef, <2 x i32> <i32 6, i32 7> // CHECK: select <2 x i1> %{{.*}}, <2 x double> %{{.*}}, <2 x double> %{{.*}} return _mm512_mask_extractf64x2_pd(__W, __U, __A, 3); } __m128d test_mm512_maskz_extractf64x2_pd(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_maskz_extractf64x2_pd // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> undef, <2 x i32> <i32 6, i32 7> // CHECK: select <2 x i1> %{{.*}}, <2 x double> %{{.*}}, <2 x double> %{{.*}} return _mm512_maskz_extractf64x2_pd(__U, __A, 3); } __m256i test_mm512_extracti32x8_epi32(__m512i __A) { // CHECK-LABEL: @test_mm512_extracti32x8_epi32 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> return _mm512_extracti32x8_epi32(__A, 1); } __m256i test_mm512_mask_extracti32x8_epi32(__m256i __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_extracti32x8_epi32 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> // CHECK: select <8 x i1> %{{.*}}, <8 x i32> %{{.*}}, <8 x i32> %{{.*}} return _mm512_mask_extracti32x8_epi32(__W, __U, __A, 1); } __m256i test_mm512_maskz_extracti32x8_epi32(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_extracti32x8_epi32 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <8 x i32> <i32 8, i32 9, i32 10, i32 11, i32 12, i32 13, i32 14, i32 15> // CHECK: select <8 x i1> %{{.*}}, <8 x i32> %{{.*}}, <8 x i32> %{{.*}} return _mm512_maskz_extracti32x8_epi32(__U, __A, 1); } __m128i test_mm512_extracti64x2_epi64(__m512i __A) { // CHECK-LABEL: @test_mm512_extracti64x2_epi64 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> undef, <2 x i32> <i32 6, i32 7> return _mm512_extracti64x2_epi64(__A, 3); } __m128i test_mm512_mask_extracti64x2_epi64(__m128i __W, __mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_mask_extracti64x2_epi64 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> undef, <2 x i32> <i32 6, i32 7> // CHECK: select <2 x i1> %{{.*}}, <2 x i64> %{{.*}}, <2 x i64> %{{.*}} return _mm512_mask_extracti64x2_epi64(__W, __U, __A, 3); } __m128i test_mm512_maskz_extracti64x2_epi64(__mmask8 __U, __m512i __A) { // CHECK-LABEL: @test_mm512_maskz_extracti64x2_epi64 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> undef, <2 x i32> <i32 6, i32 7> // CHECK: select <2 x i1> %{{.*}}, <2 x i64> %{{.*}}, <2 x i64> %{{.*}} return _mm512_maskz_extracti64x2_epi64(__U, __A, 3); } __m512 test_mm512_insertf32x8(__m512 __A, __m256 __B) { // CHECK-LABEL: @test_mm512_insertf32x8 // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> return _mm512_insertf32x8(__A, __B, 1); } __m512 test_mm512_mask_insertf32x8(__m512 __W, __mmask16 __U, __m512 __A, __m256 __B) { // CHECK-LABEL: @test_mm512_mask_insertf32x8 // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> // CHECK: select <16 x i1> %{{.*}}, <16 x float> %{{.*}}, <16 x float> %{{.*}} return _mm512_mask_insertf32x8(__W, __U, __A, __B, 1); } __m512 test_mm512_maskz_insertf32x8(__mmask16 __U, __m512 __A, __m256 __B) { // CHECK-LABEL: @test_mm512_maskz_insertf32x8 // CHECK: shufflevector <16 x float> %{{.*}}, <16 x float> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> // CHECK: select <16 x i1> %{{.*}}, <16 x float> %{{.*}}, <16 x float> %{{.*}} return _mm512_maskz_insertf32x8(__U, __A, __B, 1); } __m512d test_mm512_insertf64x2(__m512d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_insertf64x2 // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 8, i32 9> return _mm512_insertf64x2(__A, __B, 3); } __m512d test_mm512_mask_insertf64x2(__m512d __W, __mmask8 __U, __m512d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_mask_insertf64x2 // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 8, i32 9> // CHECK: select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}} return _mm512_mask_insertf64x2(__W, __U, __A, __B, 3); } __m512d test_mm512_maskz_insertf64x2(__mmask8 __U, __m512d __A, __m128d __B) { // CHECK-LABEL: @test_mm512_maskz_insertf64x2 // CHECK: shufflevector <8 x double> %{{.*}}, <8 x double> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 8, i32 9> // CHECK: select <8 x i1> %{{.*}}, <8 x double> %{{.*}}, <8 x double> %{{.*}} return _mm512_maskz_insertf64x2(__U, __A, __B, 3); } __m512i test_mm512_inserti32x8(__m512i __A, __m256i __B) { // CHECK-LABEL: @test_mm512_inserti32x8 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> return _mm512_inserti32x8(__A, __B, 1); } __m512i test_mm512_mask_inserti32x8(__m512i __W, __mmask16 __U, __m512i __A, __m256i __B) { // CHECK-LABEL: @test_mm512_mask_inserti32x8 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> // CHECK: select <16 x i1> %{{.*}}, <16 x i32> %{{.*}}, <16 x i32> %{{.*}} return _mm512_mask_inserti32x8(__W, __U, __A, __B, 1); } __m512i test_mm512_maskz_inserti32x8(__mmask16 __U, __m512i __A, __m256i __B) { // CHECK-LABEL: @test_mm512_maskz_inserti32x8 // CHECK: shufflevector <16 x i32> %{{.*}}, <16 x i32> %{{.*}}, <16 x i32> <i32 0, i32 1, i32 2, i32 3, i32 4, i32 5, i32 6, i32 7, i32 16, i32 17, i32 18, i32 19, i32 20, i32 21, i32 22, i32 23> // CHECK: select <16 x i1> %{{.*}}, <16 x i32> %{{.*}}, <16 x i32> %{{.*}} return _mm512_maskz_inserti32x8(__U, __A, __B, 1); } __m512i test_mm512_inserti64x2(__m512i __A, __m128i __B) { // CHECK-LABEL: @test_mm512_inserti64x2 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 8, i32 9, i32 4, i32 5, i32 6, i32 7> return _mm512_inserti64x2(__A, __B, 1); } __m512i test_mm512_mask_inserti64x2(__m512i __W, __mmask8 __U, __m512i __A, __m128i __B) { // CHECK-LABEL: @test_mm512_mask_inserti64x2 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 8, i32 9, i32 4, i32 5, i32 6, i32 7> // CHECK: select <8 x i1> %{{.*}}, <8 x i64> %{{.*}}, <8 x i64> %{{.*}} return _mm512_mask_inserti64x2(__W, __U, __A, __B, 1); } __m512i test_mm512_maskz_inserti64x2(__mmask8 __U, __m512i __A, __m128i __B) { // CHECK-LABEL: @test_mm512_maskz_inserti64x2 // CHECK: shufflevector <8 x i64> %{{.*}}, <8 x i64> %{{.*}}, <8 x i32> <i32 0, i32 1, i32 8, i32 9, i32 4, i32 5, i32 6, i32 7> // CHECK: select <8 x i1> %{{.*}}, <8 x i64> %{{.*}}, <8 x i64> %{{.*}} return _mm512_maskz_inserti64x2(__U, __A, __B, 1); } __mmask8 test_mm512_mask_fpclass_pd_mask(__mmask8 __U, __m512d __A) { // CHECK-LABEL: @test_mm512_mask_fpclass_pd_mask // CHECK: @llvm.x86.avx512.mask.fpclass.pd.512 return _mm512_mask_fpclass_pd_mask(__U, __A, 4); } __mmask8 test_mm512_fpclass_pd_mask(__m512d __A) { // CHECK-LABEL: @test_mm512_fpclass_pd_mask // CHECK: @llvm.x86.avx512.mask.fpclass.pd.512 return _mm512_fpclass_pd_mask(__A, 4); } __mmask16 test_mm512_mask_fpclass_ps_mask(__mmask16 __U, __m512 __A) { // CHECK-LABEL: @test_mm512_mask_fpclass_ps_mask // CHECK: @llvm.x86.avx512.mask.fpclass.ps.512 return _mm512_mask_fpclass_ps_mask(__U, __A, 4); } __mmask16 test_mm512_fpclass_ps_mask(__m512 __A) { // CHECK-LABEL: @test_mm512_fpclass_ps_mask // CHECK: @llvm.x86.avx512.mask.fpclass.ps.512 return _mm512_fpclass_ps_mask(__A, 4); } __mmask8 test_mm_fpclass_sd_mask(__m128 __A) { // CHECK-LABEL: @test_mm_fpclass_sd_mask // CHECK: @llvm.x86.avx512.mask.fpclass.sd return _mm_fpclass_sd_mask (__A, 2); } __mmask8 test_mm_mask_fpclass_sd_mask(__mmask8 __U, __m128 __A) { // CHECK-LABEL: @test_mm_mask_fpclass_sd_mask // CHECK: @llvm.x86.avx512.mask.fpclass.sd return _mm_mask_fpclass_sd_mask (__U, __A, 2); } __mmask8 test_mm_fpclass_ss_mask(__m128 __A) { // CHECK-LABEL: @test_mm_fpclass_ss_mask // CHECK: @llvm.x86.avx512.mask.fpclass.ss return _mm_fpclass_ss_mask ( __A, 2); } __mmask8 test_mm_mask_fpclass_ss_mask(__mmask8 __U, __m128 __A) { // CHECK-LABEL: @test_mm_mask_fpclass_ss_mask // CHECK: @llvm.x86.avx512.mask.fpclass.ss return _mm_mask_fpclass_ss_mask (__U, __A, 2); }
259849.c
/* * jcdctmgr.c * * Copyright (C) 1994, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains the forward-DCT management logic. * This code selects a particular DCT implementation to be used, * and it performs related housekeeping chores including coefficient * quantization. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" #include "jdct.h" /* Private declarations for DCT subsystem */ /* Private subobject for this module */ typedef struct { struct jpeg_forward_dct pub; /* public fields */ /* Pointer to the DCT routine actually in use */ forward_DCT_method_ptr do_dct; /* The actual post-DCT divisors --- not identical to the quant table * entries, because of scaling (especially for an unnormalized DCT). * Each table is given in zigzag order. */ DCTELEM * divisors[NUM_QUANT_TBLS]; #ifdef DCT_FLOAT_SUPPORTED /* Same as above for the floating-point case. */ float_DCT_method_ptr do_float_dct; FAST_FLOAT * float_divisors[NUM_QUANT_TBLS]; #endif } my_fdct_controller; typedef my_fdct_controller * my_fdct_ptr; /* ZAG[i] is the natural-order position of the i'th element of zigzag order. */ static const int ZAG[DCTSIZE2] = { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }; /* * Initialize for a processing pass. * Verify that all referenced Q-tables are present, and set up * the divisor table for each one. * In the current implementation, DCT of all components is done during * the first pass, even if only some components will be output in the * first scan. Hence all components should be examined here. */ METHODDEF void start_pass_fdctmgr (j_compress_ptr cinfo) { my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; int ci, qtblno, i; jpeg_component_info *compptr; JQUANT_TBL * qtbl; DCTELEM * dtbl; for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components; ci++, compptr++) { qtblno = compptr->quant_tbl_no; /* Make sure specified quantization table is present */ if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo->quant_tbl_ptrs[qtblno] == NULL) ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno); qtbl = cinfo->quant_tbl_ptrs[qtblno]; /* Compute divisors for this quant table */ /* We may do this more than once for same table, but it's not a big deal */ switch (cinfo->dct_method) { #ifdef DCT_ISLOW_SUPPORTED case JDCT_ISLOW: /* For LL&M IDCT method, divisors are equal to raw quantization * coefficients multiplied by 8 (to counteract scaling). */ if (fdct->divisors[qtblno] == NULL) { fdct->divisors[qtblno] = (DCTELEM *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, DCTSIZE2 * SIZEOF(DCTELEM)); } dtbl = fdct->divisors[qtblno]; for (i = 0; i < DCTSIZE2; i++) { dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3; } break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: { /* For AA&N IDCT method, divisors are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * We apply a further scale factor of 8. */ #define CONST_BITS 14 static const INT16 aanscales[DCTSIZE2] = { /* precomputed values scaled up by 14 bits: in natural order */ 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270, 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906, 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315, 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520, 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552, 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446, 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247 }; SHIFT_TEMPS if (fdct->divisors[qtblno] == NULL) { fdct->divisors[qtblno] = (DCTELEM *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, DCTSIZE2 * SIZEOF(DCTELEM)); } dtbl = fdct->divisors[qtblno]; for (i = 0; i < DCTSIZE2; i++) { dtbl[i] = (DCTELEM) DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i], (INT32) aanscales[ZAG[i]]), CONST_BITS-3); } } break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: { /* For float AA&N IDCT method, divisors are equal to quantization * coefficients scaled by scalefactor[row]*scalefactor[col], where * scalefactor[0] = 1 * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7 * We apply a further scale factor of 8. * What's actually stored is 1/divisor so that the inner loop can * use a multiplication rather than a division. */ FAST_FLOAT * fdtbl; int row, col; static const double aanscalefactor[DCTSIZE] = { 1.0, 1.387039845, 1.306562965, 1.175875602, 1.0, 0.785694958, 0.541196100, 0.275899379 }; if (fdct->float_divisors[qtblno] == NULL) { fdct->float_divisors[qtblno] = (FAST_FLOAT *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, DCTSIZE2 * SIZEOF(FAST_FLOAT)); } fdtbl = fdct->float_divisors[qtblno]; for (i = 0; i < DCTSIZE2; i++) { row = ZAG[i] >> 3; col = ZAG[i] & 7; fdtbl[i] = (FAST_FLOAT) (1.0 / (((double) qtbl->quantval[i] * aanscalefactor[row] * aanscalefactor[col] * 8.0))); } } break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } } } /* * Perform forward DCT on one or more blocks of a component. * * The input samples are taken from the sample_data[] array starting at * position start_row/start_col, and moving to the right for any additional * blocks. The quantized, zigzagged coefficients are returned in coef_blocks[]. */ METHODDEF void forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY sample_data, JBLOCKROW coef_blocks, JDIMENSION start_row, JDIMENSION start_col, JDIMENSION num_blocks) /* This version is used for integer DCT implementations. */ { /* This routine is heavily used, so it's worth coding it tightly. */ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; forward_DCT_method_ptr do_dct = fdct->do_dct; DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no]; DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */ JDIMENSION bi; sample_data += start_row; /* fold in the vertical offset once */ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) { /* Load data into workspace, applying unsigned->signed conversion */ { register DCTELEM *workspaceptr; register JSAMPROW elemptr; register int elemr; workspaceptr = workspace; for (elemr = 0; elemr < DCTSIZE; elemr++) { elemptr = sample_data[elemr] + start_col; #if DCTSIZE == 8 /* unroll the inner loop */ *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; #else { register int elemc; for (elemc = DCTSIZE; elemc > 0; elemc--) { *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; } } #endif } } /* Perform the DCT */ (*do_dct) (workspace); /* Quantize/descale the coefficients, and store into coef_blocks[] */ { register DCTELEM temp, qval; register int i; register JCOEFPTR output_ptr = coef_blocks[bi]; for (i = 0; i < DCTSIZE2; i++) { qval = divisors[i]; temp = workspace[ZAG[i]]; /* Divide the coefficient value by qval, ensuring proper rounding. * Since C does not specify the direction of rounding for negative * quotients, we have to force the dividend positive for portability. * * In most files, at least half of the output values will be zero * (at default quantization settings, more like three-quarters...) * so we should ensure that this case is fast. On many machines, * a comparison is enough cheaper than a divide to make a special test * a win. Since both inputs will be nonnegative, we need only test * for a < b to discover whether a/b is 0. * If your machine's division is fast enough, define FAST_DIVIDE. */ #ifdef FAST_DIVIDE #define DIVIDE_BY(a,b) a /= b #else #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0 #endif if (temp < 0) { temp = -temp; temp += qval>>1; /* for rounding */ DIVIDE_BY(temp, qval); temp = -temp; } else { temp += qval>>1; /* for rounding */ DIVIDE_BY(temp, qval); } output_ptr[i] = (JCOEF) temp; } } } } #ifdef DCT_FLOAT_SUPPORTED METHODDEF void forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr, JSAMPARRAY sample_data, JBLOCKROW coef_blocks, JDIMENSION start_row, JDIMENSION start_col, JDIMENSION num_blocks) /* This version is used for floating-point DCT implementations. */ { /* This routine is heavily used, so it's worth coding it tightly. */ my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct; float_DCT_method_ptr do_dct = fdct->do_float_dct; FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no]; FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */ JDIMENSION bi; sample_data += start_row; /* fold in the vertical offset once */ for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) { /* Load data into workspace, applying unsigned->signed conversion */ { register FAST_FLOAT *workspaceptr; register JSAMPROW elemptr; register int elemr; workspaceptr = workspace; for (elemr = 0; elemr < DCTSIZE; elemr++) { elemptr = sample_data[elemr] + start_col; #if DCTSIZE == 8 /* unroll the inner loop */ *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); *workspaceptr++ = (float) (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE); #else { register int elemc; for (elemc = DCTSIZE; elemc > 0; elemc--) { *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE; } } #endif } } /* Perform the DCT */ (*do_dct) (workspace); /* Quantize/descale the coefficients, and store into coef_blocks[] */ { register FAST_FLOAT temp; register int i; register JCOEFPTR output_ptr = coef_blocks[bi]; for (i = 0; i < DCTSIZE2; i++) { /* Apply the quantization and scaling factor */ temp = workspace[ZAG[i]] * divisors[i]; /* Round to nearest integer. * Since C does not specify the direction of rounding for negative * quotients, we have to force the dividend positive for portability. * The maximum coefficient size is +-16K (for 12-bit data), so this * code should work for either 16-bit or 32-bit ints. */ output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384); } } } } #endif /* DCT_FLOAT_SUPPORTED */ /* * Initialize FDCT manager. */ GLOBAL void jinit_forward_dct (j_compress_ptr cinfo) { my_fdct_ptr fdct; int i; fdct = (my_fdct_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(my_fdct_controller)); cinfo->fdct = (struct jpeg_forward_dct *) fdct; fdct->pub.start_pass = start_pass_fdctmgr; switch (cinfo->dct_method) { #ifdef DCT_ISLOW_SUPPORTED case JDCT_ISLOW: fdct->pub.forward_DCT = forward_DCT; fdct->do_dct = jpeg_fdct_islow; break; #endif #ifdef DCT_IFAST_SUPPORTED case JDCT_IFAST: fdct->pub.forward_DCT = forward_DCT; fdct->do_dct = jpeg_fdct_ifast; break; #endif #ifdef DCT_FLOAT_SUPPORTED case JDCT_FLOAT: fdct->pub.forward_DCT = forward_DCT_float; fdct->do_float_dct = jpeg_fdct_float; break; #endif default: ERREXIT(cinfo, JERR_NOT_COMPILED); break; } /* Mark divisor tables unallocated */ for (i = 0; i < NUM_QUANT_TBLS; i++) { fdct->divisors[i] = NULL; #ifdef DCT_FLOAT_SUPPORTED fdct->float_divisors[i] = NULL; #endif } }
478871.c
/* scan.c: SCANNING FUNCTIONS * * $Id$ * Copyright (c) 2001-2020 Ravenbrook Limited. * See end of file for license. * * .outside: The code in this file is written as if *outside* the MPS, * and so is restricted to facilities in the MPS interface. MPS users * are invited to read this code and use it as a basis for their own * scanners. See topic "Area Scanners" in the MPS manual. * * TODO: Design document. */ #include "mps.h" #include "mpstd.h" /* for MPS_BUILD_MV */ #ifdef MPS_BUILD_MV /* MSVC warning 4127 = conditional expression is constant */ /* Objects to: MPS_SCAN_AREA(1). */ #pragma warning( disable : 4127 ) #endif #define MPS_SCAN_AREA(test) \ MPS_SCAN_BEGIN(ss) { \ mps_word_t *p = base; \ while (p < (mps_word_t *)limit) { \ mps_word_t word = *p; \ mps_word_t tag_bits = word & mask; \ if (test) { \ mps_addr_t ref = (mps_addr_t)(word ^ tag_bits); \ if (MPS_FIX1(ss, ref)) { \ mps_res_t res = MPS_FIX2(ss, &ref); \ if (res != MPS_RES_OK) \ return res; \ *p = (mps_word_t)ref | tag_bits; \ } \ } \ ++p; \ } \ } MPS_SCAN_END(ss); /* mps_scan_area -- scan contiguous area of references * * This is a convenience function for scanning the contiguous area * [base, limit). I.e., it calls Fix on all words from base up to * limit, inclusive of base and exclusive of limit. * * This scanner is appropriate for use when all words in the area are * simple untagged references. */ mps_res_t mps_scan_area(mps_ss_t ss, void *base, void *limit, void *closure) { mps_word_t mask = 0; (void)closure; /* unused */ MPS_SCAN_AREA(1); return MPS_RES_OK; } /* mps_scan_area_masked -- scan area masking off tag bits * * Like mps_scan_area, but removes tag bits before fixing references, * and restores them afterwards. * * For example, if mask is 7, then this scanner will clear the bottom * three bits of each word before fixing. * * This scanner is useful when all words in the area must be treated * as references no matter what tag they have. */ mps_res_t mps_scan_area_masked(mps_ss_t ss, void *base, void *limit, void *closure) { mps_scan_tag_t tag = closure; mps_word_t mask = tag->mask; MPS_SCAN_AREA(1); return MPS_RES_OK; } /* mps_scan_area_tagged -- scan area selecting by tag * * Like mps_scan_area_masked, except only references whose masked bits * match a particular tag pattern are fixed. * * For example, if mask is 7 and pattern is 5, then this scanner will * only fix words whose low order bits are 0b101. */ mps_res_t mps_scan_area_tagged(mps_ss_t ss, void *base, void *limit, void *closure) { mps_scan_tag_t tag = closure; mps_word_t mask = tag->mask; mps_word_t pattern = tag->pattern; MPS_SCAN_AREA(tag_bits == pattern); return MPS_RES_OK; } /* mps_scan_area_tagged_or_zero -- scan area selecting by tag or zero * * Like mps_scan_area_tagged, except references whose masked bits are * zero are fixed in addition to those that match the pattern. * * For example, if mask is 7 and pattern is 3, then this scanner will * fix words whose low order bits are 0b011 and words whose low order * bits are 0b000, but not any others. * * This scanner is most useful for ambiguously scanning the stack and * registers when using an optimising C compiler and non-zero tags on * references, since the compiler is likely to leave untagged * addresses of objects around which must not be ignored. */ mps_res_t mps_scan_area_tagged_or_zero(mps_ss_t ss, void *base, void *limit, void *closure) { mps_scan_tag_t tag = closure; mps_word_t mask = tag->mask; mps_word_t pattern = tag->pattern; MPS_SCAN_AREA(tag_bits == 0 || tag_bits == pattern); return MPS_RES_OK; } /* C. COPYRIGHT AND LICENSE * * Copyright (C) 2001-2020 Ravenbrook Limited <http://www.ravenbrook.com/>. * * 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 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 * 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. */
697261.c
/* { dg-do run { target i?86-*-linux* } } */ /* { dg-options "-O2 -fomit-frame-pointer" } */ extern void abort (void); extern void exit (int); struct s { struct { int a; } a; int b; struct { struct { int a; } a; struct t { struct t *a, *b; } b; } c; }; int bar(int (*fn)(void *), void *arg, unsigned long flags) { return 0; } int baz(void *x) { return 0; } void do_check (struct s *) asm ("do_check") __attribute__((regparm(1))); void do_check(struct s *x) { if (x->a.a || x->b || x->c.a.a) abort(); if (x->c.b.a != &x->c.b || x->c.b.b != &x->c.b) abort(); } #define NT "\n\t" asm ("\n" "___checkme:" NT "pushl %eax; pushl %ebx; pushl %ecx; pushl %edx; pushl %esi; pushl %edi" NT "pushl $0; pushl $0; pushl $0; pushl $0; pushl $0" NT "pushl $0; pushl $0; pushl $0; pushl $0; pushl $0" NT "movl %ecx, %eax" NT "call do_check" NT "popl %eax; popl %eax; popl %eax; popl %eax; popl %eax" NT "popl %eax; popl %eax; popl %eax; popl %eax; popl %eax" NT "popl %edi; popl %esi; popl %edx; popl %ecx; popl %ebx; popl %eax" NT "ret" ); extern inline void do_asm(struct s * x) { asm volatile("call ___checkme" : : "c" (x) : "memory"); } int foo(void) { struct s x = { { 0 }, 0, { { 0 }, { &x.c.b, &x.c.b } } }; bar(baz, &x, 1); do_asm(&x); bar(baz, &x, 1); do_asm(&x); return 0; } int main() { foo(); exit(0); }
759014.c
/* * Copyright (c) 2017-2018 The Linux Foundation. All rights reserved. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /** * DOC: reg_db.c * This file implements QCA regulatory database. * Current implementation conforms to database version 30. */ #include <qdf_types.h> #include <qdf_trace.h> #include "reg_db.h" enum country_code { CTRY_AFGHANISTAN = 4, CTRY_ALAND_ISLANDS = 248, CTRY_ALBANIA = 8, CTRY_ALGERIA = 12, CTRY_AMERICAN_SAMOA = 16, CTRY_ANDORRA = 20, CTRY_ANGUILLA = 660, CTRY_ANTIGUA_AND_BARBUDA = 28, CTRY_ARGENTINA = 32, CTRY_ARMENIA = 51, CTRY_MYANMAR = 104, CTRY_ARUBA = 533, CTRY_AUSTRALIA = 36, CTRY_AUSTRIA = 40, CTRY_AZERBAIJAN = 31, CTRY_BAHAMAS = 44, CTRY_BAHRAIN = 48, CTRY_BANGLADESH = 50, CTRY_BARBADOS = 52, CTRY_BELARUS = 112, CTRY_BELGIUM = 56, CTRY_BELIZE = 84, CTRY_BERMUDA = 60, CTRY_BHUTAN = 64, CTRY_BOLIVIA = 68, CTRY_BOSNIA_HERZ = 70, CTRY_BRAZIL = 76, CTRY_BRUNEI_DARUSSALAM = 96, CTRY_BULGARIA = 100, CTRY_BURKINA_FASO = 854, CTRY_CAMBODIA = 116, CTRY_CAMEROON = 120, CTRY_CANADA = 124, CTRY_CAYMAN_ISLANDS = 136, CTRY_CENTRAL_AFRICA_REPUBLIC = 140, CTRY_CHAD = 148, CTRY_CHILE = 152, CTRY_CHINA = 156, CTRY_CHRISTMAS_ISLAND = 162, CTRY_COLOMBIA = 170, CTRY_COOK_ISLANDS = 184, CTRY_COSTA_RICA = 188, CTRY_COTE_DIVOIRE = 384, CTRY_CROATIA = 191, CTRY_CYPRUS = 196, CTRY_CZECH = 203, CTRY_DENMARK = 208, CTRY_DOMINICA = 212, CTRY_DOMINICAN_REPUBLIC = 214, CTRY_ECUADOR = 218, CTRY_EGYPT = 818, CTRY_EL_SALVADOR = 222, CTRY_ESTONIA = 233, CTRY_ETHIOPIA = 231, CTRY_FALKLAND_ISLANDS = 238, CTRY_FAROE_ISLANDS = 234, CTRY_FINLAND = 246, CTRY_FRANCE = 250, CTRY_FRENCH_GUIANA = 254, CTRY_FRENCH_POLYNESIA = 258, CTRY_FRENCH_SOUTHERN_TERRITORIES = 260, CTRY_GEORGIA = 268, CTRY_GERMANY = 276, CTRY_GHANA = 288, CTRY_GIBRALTAR = 292, CTRY_GREECE = 300, CTRY_GREENLAND = 304, CTRY_GRENADA = 308, CTRY_GUADELOUPE = 312, CTRY_GUAM = 316, CTRY_GUATEMALA = 320, CTRY_GUERNSEY = 831, CTRY_GUYANA = 328, CTRY_HAITI = 332, CTRY_HEARD_ISLAND_AND_MCDONALD_ISLANDS = 334, CTRY_HOLY_SEE = 336, CTRY_HONDURAS = 340, CTRY_HONG_KONG = 344, CTRY_HUNGARY = 348, CTRY_ICELAND = 352, CTRY_INDIA = 356, CTRY_INDONESIA = 360, CTRY_IRAQ = 368, CTRY_IRELAND = 372, CTRY_ISLE_OF_MAN = 833, CTRY_ISRAEL = 376, CTRY_ITALY = 380, CTRY_JAMAICA = 388, CTRY_JERSEY = 832, CTRY_JORDAN = 400, CTRY_KAZAKHSTAN = 398, CTRY_KENYA = 404, CTRY_KOREA_ROC = 410, CTRY_KUWAIT = 414, CTRY_LATVIA = 428, CTRY_LEBANON = 422, CTRY_LESOTHO = 426, CTRY_LIECHTENSTEIN = 438, CTRY_LITHUANIA = 440, CTRY_LUXEMBOURG = 442, CTRY_MACAU = 446, CTRY_MACEDONIA = 807, CTRY_MALAWI = 454, CTRY_MALAYSIA = 458, CTRY_MALDIVES = 462, CTRY_MALTA = 470, CTRY_MARSHALL_ISLANDS = 584, CTRY_MARTINIQUE = 474, CTRY_MAURITANIA = 478, CTRY_MAURITIUS = 480, CTRY_MAYOTTE = 175, CTRY_MEXICO = 484, CTRY_MICRONESIA = 583, CTRY_MOLDOVA = 498, CTRY_MONACO = 492, CTRY_MONGOLIA = 496, CTRY_MONTENEGRO = 499, CTRY_MONTSERRAT = 500, CTRY_MOROCCO = 504, CTRY_NAMIBIA = 516, CTRY_NEPAL = 524, CTRY_NETHERLANDS = 528, CTRY_NETHERLANDS_ANTILLES = 530, CTRY_NEW_CALEDONIA = 540, CTRY_NEW_ZEALAND = 554, CTRY_NIGERIA = 566, CTRY_NORTHERN_MARIANA_ISLANDS = 580, CTRY_NICARAGUA = 558, CTRY_NIUE = 570, CTRY_NORFOLK_ISLAND = 574, CTRY_NORWAY = 578, CTRY_OMAN = 512, CTRY_PAKISTAN = 586, CTRY_PALAU = 585, CTRY_PANAMA = 591, CTRY_PAPUA_NEW_GUINEA = 598, CTRY_PARAGUAY = 600, CTRY_PERU = 604, CTRY_PHILIPPINES = 608, CTRY_POLAND = 616, CTRY_PORTUGAL = 620, CTRY_PUERTO_RICO = 630, CTRY_QATAR = 634, CTRY_REUNION = 638, CTRY_ROMANIA = 642, CTRY_RUSSIA = 643, CTRY_RWANDA = 646, CTRY_SAINT_BARTHELEMY = 652, CTRY_SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA = 654, CTRY_SAINT_KITTS_AND_NEVIS = 659, CTRY_SAINT_LUCIA = 662, CTRY_SAINT_MARTIN = 663, CTRY_SAINT_PIERRE_AND_MIQUELON = 666, CTRY_SAINT_VINCENT_AND_THE_GRENADIENS = 670, CTRY_SAMOA = 882, CTRY_SAN_MARINO = 674, CTRY_SAO_TOME_AND_PRINCIPE = 678, CTRY_SAUDI_ARABIA = 682, CTRY_SENEGAL = 686, CTRY_SERBIA = 688, CTRY_SINGAPORE = 702, CTRY_SINT_MAARTEN = 534, CTRY_SLOVAKIA = 703, CTRY_SLOVENIA = 705, CTRY_SOUTH_AFRICA = 710, CTRY_SPAIN = 724, CTRY_SURINAME = 740, CTRY_SRI_LANKA = 144, CTRY_SVALBARD_AND_JAN_MAYEN = 744, CTRY_SWEDEN = 752, CTRY_SWITZERLAND = 756, CTRY_TAIWAN = 158, CTRY_TANZANIA = 834, CTRY_THAILAND = 764, CTRY_TOGO = 768, CTRY_TRINIDAD_Y_TOBAGO = 780, CTRY_TUNISIA = 788, CTRY_TURKEY = 792, CTRY_TURKS_AND_CAICOS = 796, CTRY_UGANDA = 800, CTRY_UKRAINE = 804, CTRY_UAE = 784, CTRY_UNITED_KINGDOM = 826, CTRY_UNITED_STATES = 840, CTRY_UNITED_STATES_MINOR_OUTLYING_ISLANDS = 581, CTRY_URUGUAY = 858, CTRY_UZBEKISTAN = 860, CTRY_VANUATU = 548, CTRY_VENEZUELA = 862, CTRY_VIET_NAM = 704, CTRY_VIRGIN_ISLANDS = 850, CTRY_VIRGIN_ISLANDS_BRITISH = 92, CTRY_WALLIS_AND_FUTUNA = 876, CTRY_YEMEN = 887, CTRY_ZIMBABWE = 716, CTRY_JAPAN = 392, CTRY_JAPAN15 = 4015, CTRY_XA = 4100, }; enum reg_domain { NULL1_WORLD = 0x03, FCC1_FCCA = 0x10, FCC1_WORLD = 0x11, FCC2_FCCA = 0x20, FCC2_WORLD = 0x21, FCC2_ETSIC = 0x22, FCC3_FCCA = 0x3A, FCC3_WORLD = 0x3B, FCC3_ETSIC = 0x3F, FCC4_FCCA = 0x12, FCC5_FCCA = 0x13, FCC6_WORLD = 0x23, FCC6_FCCA = 0x14, FCC8_FCCA = 0x16, FCC9_FCCA = 0x17, FCC10_FCCA = 0x18, FCC11_WORLD = 0x19, FCC13_WORLD = 0xE4, FCC14_FCCB = 0xE6, ETSI1_WORLD = 0x37, ETSI3_WORLD = 0x36, ETSI4_WORLD = 0x30, ETSI8_WORLD = 0x3D, ETSI9_WORLD = 0x3E, ETSI10_WORLD = 0x24, ETSI10_FCCA = 0x25, ETSI11_WORLD = 0x26, ETSI12_WORLD = 0x28, ETSI13_WORLD = 0x27, ETSI14_WORLD = 0x29, ETSI15_WORLD = 0x31, APL1_WORLD = 0x52, APL1_ETSIC = 0x55, APL2_WORLD = 0x45, APL2_ETSIC = 0x56, APL2_ETSID = 0x41, APL4_WORLD = 0x42, APL6_WORLD = 0x5B, APL8_WORLD = 0x5D, APL9_WORLD = 0x5E, APL9_MKKC = 0x48, APL9_KRRA = 0x43, APL10_WORLD = 0x5F, APL11_FCCA = 0x4F, APL12_WORLD = 0x51, APL13_WORLD = 0x5A, APL14_WORLD = 0x57, APL15_WORLD = 0x59, APL16_WORLD = 0x70, APL16_ETSIC = 0x6D, APL17_ETSIC = 0xE7, APL17_ETSID = 0xE0, APL19_ETSIC = 0x71, APL20_WORLD = 0xE5, APL23_WORLD = 0xE3, APL24_ETSIC = 0xE2, MKK3_MKKC = 0x82, MKK5_MKKA = 0x99, MKK5_MKKC = 0x88, MKK11_MKKC = 0xD7, MKK16_MKKC = 0xDF, MKK17_MKKC = 0xE1, WORLD_60 = 0x60, WORLD_61 = 0x61, WORLD_62 = 0x62, WORLD_63 = 0x63, WORLD_65 = 0x65, WORLD_64 = 0x64, WORLD_66 = 0x66, WORLD_69 = 0x69, WORLD_67 = 0x67, WORLD_68 = 0x68, WORLD_6A = 0x6A, WORLD_6C = 0x6C, }; #ifndef CONFIG_MCL_REGDB const struct country_code_to_reg_domain g_all_countries[] = { {CTRY_AFGHANISTAN, ETSI1_WORLD, "AF", 40, 160, 0}, {CTRY_ALAND_ISLANDS, FCC3_WORLD, "AX", 40, 160, 0}, {CTRY_ALBANIA, ETSI1_WORLD, "AL", 40, 160, 0}, {CTRY_ALGERIA, APL13_WORLD, "DZ", 40, 160, 0}, {CTRY_AMERICAN_SAMOA, FCC3_FCCA, "AS", 40, 160, 0}, {CTRY_ANDORRA, ETSI3_WORLD, "AD", 40, 160, 0}, {CTRY_ANGUILLA, ETSI1_WORLD, "AI", 40, 160, 0}, {CTRY_ANTIGUA_AND_BARBUDA, ETSI1_WORLD, "AG", 40, 160, 0}, {CTRY_ARGENTINA, APL16_ETSIC, "AR", 40, 160, 0}, {CTRY_ARMENIA, ETSI4_WORLD, "AM", 40, 20, 0}, {CTRY_ARUBA, ETSI1_WORLD, "AW", 40, 160, 0}, {CTRY_AUSTRALIA, FCC6_WORLD, "AU", 40, 160, 0}, {CTRY_AUSTRIA, ETSI1_WORLD, "AT", 40, 160, 0}, {CTRY_AZERBAIJAN, ETSI4_WORLD, "AZ", 40, 160, 0}, {CTRY_BAHAMAS, FCC3_WORLD, "BS", 40, 160, 0}, {CTRY_BAHRAIN, APL15_WORLD, "BH", 40, 20, 0}, {CTRY_BANGLADESH, APL1_WORLD, "BD", 40, 160, 0}, {CTRY_BARBADOS, FCC2_WORLD, "BB", 40, 160, 0}, {CTRY_BELARUS, ETSI1_WORLD, "BY", 40, 160, 0}, {CTRY_BELGIUM, ETSI1_WORLD, "BE", 40, 160, 0}, {CTRY_BELIZE, ETSI8_WORLD, "BZ", 40, 160, 0}, {CTRY_BERMUDA, FCC3_FCCA, "BM", 40, 160, 0}, {CTRY_BHUTAN, ETSI1_WORLD, "BT", 40, 160, 0}, {CTRY_BOLIVIA, APL8_WORLD, "BO", 40, 160, 0}, {CTRY_BOSNIA_HERZ, ETSI1_WORLD, "BA", 40, 160, 0}, {CTRY_BRAZIL, FCC3_ETSIC, "BR", 40, 160, 0}, {CTRY_BRUNEI_DARUSSALAM, APL6_WORLD, "BN", 40, 160, 0}, {CTRY_BULGARIA, ETSI1_WORLD, "BG", 40, 160, 0}, {CTRY_BURKINA_FASO, FCC3_WORLD, "BF", 40, 160, 0}, {CTRY_CAMBODIA, ETSI1_WORLD, "KH", 40, 160, 0}, {CTRY_CAMEROON, ETSI1_WORLD, "CM", 40, 160, 0}, {CTRY_CANADA, FCC6_FCCA, "CA", 40, 160, 0}, {CTRY_CAYMAN_ISLANDS, FCC3_WORLD, "KY", 40, 160, 0}, {CTRY_CENTRAL_AFRICA_REPUBLIC, FCC3_WORLD, "CF", 40, 40, 0}, {CTRY_CHAD, ETSI1_WORLD, "TD", 40, 160, 0}, {CTRY_CHILE, FCC13_WORLD, "CL", 40, 160, 0}, {CTRY_CHINA, APL14_WORLD, "CN", 40, 160, 0}, {CTRY_CHRISTMAS_ISLAND, FCC3_WORLD, "CX", 40, 160, 0}, {CTRY_COLOMBIA, FCC3_WORLD, "CO", 40, 160, 0}, {CTRY_COOK_ISLANDS, FCC3_WORLD, "CK", 40, 160, 0}, {CTRY_COSTA_RICA, FCC3_WORLD, "CR", 40, 160, 0}, {CTRY_COTE_DIVOIRE, FCC3_WORLD, "CI", 40, 160, 0}, {CTRY_CROATIA, ETSI1_WORLD, "HR", 40, 160, 0}, {CTRY_CYPRUS, ETSI1_WORLD, "CY", 40, 160, 0}, {CTRY_CZECH, ETSI1_WORLD, "CZ", 40, 160, 0}, {CTRY_DENMARK, ETSI1_WORLD, "DK", 40, 160, 0}, {CTRY_DOMINICA, FCC1_FCCA, "DM", 40, 160, 0}, {CTRY_DOMINICAN_REPUBLIC, FCC3_FCCA, "DO", 40, 160, 0}, {CTRY_ECUADOR, FCC3_WORLD, "EC", 40, 20, 0}, {CTRY_EGYPT, ETSI3_WORLD, "EG", 40, 160, 0}, {CTRY_EL_SALVADOR, FCC1_WORLD, "SV", 40, 20, 0}, {CTRY_ESTONIA, ETSI1_WORLD, "EE", 40, 160, 0}, {CTRY_ETHIOPIA, ETSI1_WORLD, "ET", 40, 160, 0}, {CTRY_FALKLAND_ISLANDS, ETSI1_WORLD, "FK", 40, 160, 0}, {CTRY_FAROE_ISLANDS, ETSI1_WORLD, "FO", 40, 160, 0}, {CTRY_FINLAND, ETSI1_WORLD, "FI", 40, 160, 0}, {CTRY_FRANCE, ETSI1_WORLD, "FR", 40, 160, 0}, {CTRY_FRENCH_GUIANA, ETSI1_WORLD, "GF", 40, 160, 0}, {CTRY_FRENCH_POLYNESIA, ETSI1_WORLD, "PF", 40, 160, 0}, {CTRY_FRENCH_SOUTHERN_TERRITORIES, ETSI1_WORLD, "TF", 40, 160, 0}, {CTRY_GEORGIA, ETSI1_WORLD, "GE", 40, 160, 0}, {CTRY_GERMANY, ETSI1_WORLD, "DE", 40, 160, 0}, {CTRY_GHANA, FCC3_WORLD, "GH", 40, 160, 0}, {CTRY_GIBRALTAR, ETSI1_WORLD, "GI", 40, 160, 0}, {CTRY_GREECE, ETSI1_WORLD, "GR", 40, 160, 0}, {CTRY_GREENLAND, ETSI1_WORLD, "GL", 40, 160, 0}, {CTRY_GRENADA, FCC3_FCCA, "GD", 40, 160, 0}, {CTRY_GUADELOUPE, ETSI1_WORLD, "GP", 40, 160, 0}, {CTRY_GUAM, FCC3_FCCA, "GU", 40, 160, 0}, {CTRY_GUATEMALA, ETSI1_WORLD, "GT", 40, 160, 0}, {CTRY_GUERNSEY, ETSI1_WORLD, "GG", 40, 160, 0}, {CTRY_GUYANA, APL1_ETSIC, "GY", 40, 160, 0}, {CTRY_HAITI, FCC3_FCCA, "HT", 40, 160, 0}, {CTRY_HEARD_ISLAND_AND_MCDONALD_ISLANDS, FCC6_WORLD, "HM", 40, 160, 0}, {CTRY_HOLY_SEE, ETSI1_WORLD, "VA", 40, 160, 0}, {CTRY_HONDURAS, FCC3_WORLD, "HN", 40, 160, 0}, {CTRY_HONG_KONG, FCC3_WORLD, "HK", 40, 160, 0}, {CTRY_HUNGARY, ETSI1_WORLD, "HU", 40, 160, 0}, {CTRY_ICELAND, ETSI1_WORLD, "IS", 40, 160, 0}, {CTRY_INDIA, APL19_ETSIC, "IN", 40, 160, 0}, {CTRY_INDONESIA, APL2_ETSID, "ID", 40, 80, 0}, {CTRY_IRAQ, ETSI1_WORLD, "IQ", 40, 160, 0}, {CTRY_IRELAND, ETSI1_WORLD, "IE", 40, 160, 0}, {CTRY_ISLE_OF_MAN, ETSI1_WORLD, "IM", 40, 160, 0}, {CTRY_ISRAEL, ETSI3_WORLD, "IL", 40, 160, 0}, {CTRY_ITALY, ETSI1_WORLD, "IT", 40, 160, 0}, {CTRY_JAMAICA, FCC13_WORLD, "JM", 40, 160, 0}, {CTRY_JERSEY, ETSI1_WORLD, "JE", 40, 160, 0}, {CTRY_JORDAN, APL4_WORLD, "JO", 40, 160, 0}, {CTRY_KAZAKHSTAN, MKK5_MKKC, "KZ", 40, 160, 0}, {CTRY_KENYA, ETSI13_WORLD, "KE", 40, 160, 0}, {CTRY_KOREA_ROC, APL9_MKKC, "KR", 40, 160, 0}, {CTRY_KUWAIT, ETSI3_WORLD, "KW", 40, 160, 0}, {CTRY_LATVIA, ETSI1_WORLD, "LV", 40, 160, 0}, {CTRY_LEBANON, FCC3_WORLD, "LB", 40, 160, 0}, {CTRY_LESOTHO, ETSI1_WORLD, "LS", 40, 160, 0}, {CTRY_LIECHTENSTEIN, ETSI1_WORLD, "LI", 40, 160, 0}, {CTRY_LITHUANIA, ETSI1_WORLD, "LT", 40, 160, 0}, {CTRY_LUXEMBOURG, ETSI1_WORLD, "LU", 40, 160, 0}, {CTRY_MACAU, FCC3_WORLD, "MO", 40, 160, 0}, {CTRY_MACEDONIA, ETSI1_WORLD, "MK", 40, 160, 0}, {CTRY_MALAWI, ETSI1_WORLD, "MW", 40, 160, 0}, {CTRY_MALAYSIA, FCC11_WORLD, "MY", 40, 160, 0}, {CTRY_MALDIVES, APL6_WORLD, "MV", 40, 160, 0}, {CTRY_MALTA, ETSI1_WORLD, "MT", 40, 160, 0}, {CTRY_MARSHALL_ISLANDS, FCC3_FCCA, "MH", 40, 160, 0}, {CTRY_MARTINIQUE, ETSI1_WORLD, "MQ", 40, 160, 0}, {CTRY_MAURITANIA, ETSI1_WORLD, "MR", 40, 160, 0}, {CTRY_MAURITIUS, ETSI1_WORLD, "MU", 40, 160, 0}, {CTRY_MAYOTTE, ETSI1_WORLD, "YT", 40, 160, 0}, {CTRY_MEXICO, FCC3_ETSIC, "MX", 40, 160, 0}, {CTRY_MICRONESIA, FCC3_FCCA, "FM", 40, 160, 0}, {CTRY_MOLDOVA, ETSI1_WORLD, "MD", 40, 160, 0}, {CTRY_MONACO, ETSI1_WORLD, "MC", 40, 160, 0}, {CTRY_MONGOLIA, FCC3_WORLD, "MN", 40, 160, 0}, {CTRY_MONTENEGRO, ETSI1_WORLD, "ME", 40, 160, 0}, {CTRY_MONTSERRAT, ETSI1_WORLD, "MS", 40, 160, 0}, {CTRY_MOROCCO, ETSI3_WORLD, "MA", 40, 160, 0}, {CTRY_MYANMAR, APL1_WORLD, "MM", 40, 160, 0}, {CTRY_NAMIBIA, APL20_WORLD, "NA", 40, 160, 0}, {CTRY_NEPAL, APL23_WORLD, "NP", 40, 160, 0}, {CTRY_NETHERLANDS, ETSI1_WORLD, "NL", 40, 160, 0}, {CTRY_NETHERLANDS_ANTILLES, ETSI1_WORLD, "AN", 40, 160, 0}, {CTRY_NEW_CALEDONIA, ETSI1_WORLD, "NC", 40, 160, 0}, {CTRY_NEW_ZEALAND, FCC3_ETSIC, "NZ", 40, 160, 0}, {CTRY_NIGERIA, APL8_WORLD, "NG", 40, 160, 0}, {CTRY_NORTHERN_MARIANA_ISLANDS, FCC3_FCCA, "MP", 40, 160, 0}, {CTRY_NICARAGUA, FCC3_FCCA, "NI", 40, 160, 0}, {CTRY_NIUE, ETSI1_WORLD, "NU", 40, 160, 0}, {CTRY_NORFOLK_ISLAND, FCC6_WORLD, "NF", 40, 160, 0}, {CTRY_NORWAY, ETSI1_WORLD, "NO", 40, 160, 0}, {CTRY_OMAN, ETSI1_WORLD, "OM", 40, 160, 0}, {CTRY_PAKISTAN, APL1_ETSIC, "PK", 40, 160, 0}, {CTRY_PALAU, FCC3_FCCA, "PW", 40, 160, 0}, {CTRY_PANAMA, FCC14_FCCB, "PA", 40, 160, 0}, {CTRY_PAPUA_NEW_GUINEA, FCC3_WORLD, "PG", 40, 160, 0}, {CTRY_PARAGUAY, FCC3_WORLD, "PY", 40, 160, 0}, {CTRY_PERU, FCC3_WORLD, "PE", 40, 160, 0}, {CTRY_PHILIPPINES, FCC3_WORLD, "PH", 40, 160, 0}, {CTRY_POLAND, ETSI1_WORLD, "PL", 40, 160, 0}, {CTRY_PORTUGAL, ETSI1_WORLD, "PT", 40, 160, 0}, {CTRY_PUERTO_RICO, FCC3_FCCA, "PR", 40, 160, 0}, {CTRY_QATAR, ETSI14_WORLD, "QA", 40, 160, 0}, {CTRY_REUNION, ETSI1_WORLD, "RE", 40, 160, 0}, {CTRY_ROMANIA, ETSI1_WORLD, "RO", 40, 160, 0}, {CTRY_RUSSIA, ETSI8_WORLD, "RU", 40, 160, 0}, {CTRY_RWANDA, FCC3_WORLD, "RW", 40, 160, 0}, {CTRY_SAINT_BARTHELEMY, ETSI1_WORLD, "BL", 40, 160, 0}, {CTRY_SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA, ETSI1_WORLD, "SH", 40, 160, 0}, {CTRY_SAINT_KITTS_AND_NEVIS, APL10_WORLD, "KN", 40, 160, 0}, {CTRY_SAINT_LUCIA, APL10_WORLD, "LC", 40, 160, 0}, {CTRY_SAINT_MARTIN, ETSI1_WORLD, "MF", 40, 160, 0}, {CTRY_SAINT_PIERRE_AND_MIQUELON, ETSI1_WORLD, "PM", 40, 160, 0}, {CTRY_SAINT_VINCENT_AND_THE_GRENADIENS, ETSI1_WORLD, "VC" , 40, 160, 0}, {CTRY_SAMOA, ETSI1_WORLD, "WS", 40, 40, 0}, {CTRY_SAN_MARINO, FCC3_FCCA, "SM", 40, 160, 0}, {CTRY_SAO_TOME_AND_PRINCIPE, FCC3_WORLD, "ST", 40, 160, 0}, {CTRY_SAUDI_ARABIA, ETSI15_WORLD, "SA", 40, 160, 0}, {CTRY_SENEGAL, FCC13_WORLD, "SN", 40, 160, 0}, {CTRY_SERBIA, ETSI1_WORLD, "RS", 40, 160, 0}, {CTRY_SINGAPORE, FCC3_WORLD, "SG", 40, 160, 0}, {CTRY_SINT_MAARTEN, ETSI1_WORLD, "SX", 40, 160, 0}, {CTRY_SLOVAKIA, ETSI1_WORLD, "SK", 40, 160, 0}, {CTRY_SLOVENIA, ETSI1_WORLD, "SI", 40, 160, 0}, {CTRY_SOUTH_AFRICA, FCC3_WORLD, "ZA", 40, 160, 0}, {CTRY_SPAIN, ETSI1_WORLD, "ES", 40, 160, 0}, {CTRY_SURINAME, ETSI1_WORLD, "SR", 40, 160, 0}, {CTRY_SRI_LANKA, FCC3_WORLD, "LK", 40, 20, 0}, {CTRY_SVALBARD_AND_JAN_MAYEN, FCC6_WORLD, "SJ", 40, 160, 0}, {CTRY_SWEDEN, ETSI1_WORLD, "SE", 40, 160, 0}, {CTRY_SWITZERLAND, ETSI1_WORLD, "CH", 40, 160, 0}, {CTRY_TAIWAN, FCC3_FCCA, "TW", 40, 160, 0}, {CTRY_TANZANIA, APL1_WORLD, "TZ", 40, 160, 0}, {CTRY_THAILAND, FCC3_WORLD, "TH", 40, 160, 0}, {CTRY_TOGO, ETSI1_WORLD, "TG", 40, 40, 0}, {CTRY_TRINIDAD_Y_TOBAGO, FCC3_WORLD, "TT", 40, 160, 0}, {CTRY_TUNISIA, ETSI3_WORLD, "TN", 40, 160, 0}, {CTRY_TURKEY, ETSI1_WORLD, "TR", 40, 160, 0}, {CTRY_TURKS_AND_CAICOS, FCC3_WORLD, "TC", 40, 160, 0}, {CTRY_UGANDA, FCC3_WORLD, "UG", 40, 160, 0}, {CTRY_UKRAINE, ETSI9_WORLD, "UA", 40, 160, 0}, {CTRY_UAE, FCC3_WORLD, "AE", 40, 160, 0}, {CTRY_UNITED_KINGDOM, ETSI1_WORLD, "GB", 40, 160, 0}, {CTRY_UNITED_STATES, FCC8_FCCA, "US", 40, 160, 0}, {CTRY_UNITED_STATES_MINOR_OUTLYING_ISLANDS, FCC8_FCCA, "UM", 40, 160, 0}, {CTRY_URUGUAY, FCC2_WORLD, "UY", 40, 160, 0}, {CTRY_UZBEKISTAN, ETSI3_WORLD, "UZ", 40, 160, 0}, {CTRY_VANUATU, FCC3_WORLD, "VU", 40, 160, 0}, {CTRY_VENEZUELA, FCC2_ETSIC, "VE", 40, 160, 0}, {CTRY_VIET_NAM, FCC3_WORLD, "VN", 40, 80, 0}, {CTRY_VIRGIN_ISLANDS, FCC3_FCCA, "VI", 40, 160, 0}, {CTRY_VIRGIN_ISLANDS_BRITISH, ETSI1_WORLD, "VG", 40, 160, 0}, {CTRY_WALLIS_AND_FUTUNA, ETSI1_WORLD, "WF", 40, 160, 0}, {CTRY_YEMEN, NULL1_WORLD, "YE", 40, 0, 0}, {CTRY_ZIMBABWE, ETSI1_WORLD, "ZW", 40, 160, 0}, {CTRY_JAPAN, MKK5_MKKC, "JP", 40, 160, 0}, {CTRY_JAPAN15, MKK5_MKKC, "JP", 40, 160, 0}, }; #else #ifdef WLAN_FEATURE_DSRC const struct country_code_to_reg_domain g_all_countries[] = { {CTRY_AFGHANISTAN, ETSI1_WORLD, "AF", 40, 160, 0}, {CTRY_ALAND_ISLANDS, FCC3_WORLD, "AX", 40, 160, 0}, {CTRY_ALBANIA, ETSI13_WORLD, "AL", 40, 160, 0}, {CTRY_ALGERIA, APL13_WORLD, "DZ", 40, 160, 0}, {CTRY_AMERICAN_SAMOA, FCC3_FCCA, "AS", 40, 160, 0}, {CTRY_ANDORRA, ETSI3_WORLD, "AD", 40, 160, 0}, {CTRY_ANGUILLA, ETSI1_WORLD, "AI", 40, 160, 0}, {CTRY_ANTIGUA_AND_BARBUDA, ETSI10_WORLD, "AG", 40, 160, 0}, {CTRY_ARGENTINA, APL17_ETSIC, "AR", 40, 160, 0}, {CTRY_ARMENIA, ETSI4_WORLD, "AM", 40, 20, 0}, {CTRY_ARUBA, ETSI1_WORLD, "AW", 40, 160, 0}, {CTRY_AUSTRALIA, FCC6_WORLD, "AU", 40, 160, 0}, {CTRY_AUSTRIA, ETSI10_WORLD, "AT", 40, 160, 0}, {CTRY_AZERBAIJAN, ETSI4_WORLD, "AZ", 40, 160, 0}, {CTRY_BAHAMAS, FCC3_WORLD, "BS", 40, 160, 0}, {CTRY_BAHRAIN, APL15_WORLD, "BH", 40, 20, 0}, {CTRY_BANGLADESH, APL1_WORLD, "BD", 40, 160, 0}, {CTRY_BARBADOS, FCC2_WORLD, "BB", 40, 160, 0}, {CTRY_BELARUS, ETSI1_WORLD, "BY", 40, 160, 0}, {CTRY_BELGIUM, ETSI10_WORLD, "BE", 40, 160, 0}, {CTRY_BELIZE, ETSI8_WORLD, "BZ", 40, 160, 0}, {CTRY_BERMUDA, FCC3_FCCA, "BM", 40, 160, 0}, {CTRY_BHUTAN, ETSI1_WORLD, "BT", 40, 160, 0}, {CTRY_BOLIVIA, APL8_WORLD, "BO", 40, 160, 0}, {CTRY_BOSNIA_HERZ, ETSI13_WORLD, "BA", 40, 160, 0}, {CTRY_BRAZIL, FCC3_ETSIC, "BR", 40, 160, 0}, {CTRY_BRUNEI_DARUSSALAM, APL6_WORLD, "BN", 40, 160, 0}, {CTRY_BULGARIA, ETSI10_WORLD, "BG", 40, 160, 0}, {CTRY_BURKINA_FASO, FCC3_WORLD, "BF", 40, 160, 0}, {CTRY_CAMBODIA, ETSI1_WORLD, "KH", 40, 160, 0}, {CTRY_CAMEROON, ETSI1_WORLD, "CM", 40, 160, 0}, {CTRY_CANADA, FCC3_FCCA, "CA", 40, 160, 0}, {CTRY_CAYMAN_ISLANDS, FCC3_WORLD, "KY", 40, 160, 0}, {CTRY_CENTRAL_AFRICA_REPUBLIC, FCC3_WORLD, "CF", 40, 40, 0}, {CTRY_CHAD, ETSI1_WORLD, "TD", 40, 160, 0}, {CTRY_CHILE, FCC13_WORLD, "CL", 40, 160, 0}, {CTRY_CHINA, APL14_WORLD, "CN", 40, 160, 0}, {CTRY_CHRISTMAS_ISLAND, FCC3_WORLD, "CX", 40, 160, 0}, {CTRY_COLOMBIA, FCC3_WORLD, "CO", 40, 160, 0}, {CTRY_COOK_ISLANDS, FCC3_WORLD, "CK", 40, 160, 0}, {CTRY_COSTA_RICA, FCC3_WORLD, "CR", 40, 160, 0}, {CTRY_COTE_DIVOIRE, FCC3_WORLD, "CI", 40, 160, 0}, {CTRY_CROATIA, ETSI10_WORLD, "HR", 40, 160, 0}, {CTRY_CYPRUS, ETSI10_WORLD, "CY", 40, 160, 0}, {CTRY_CZECH, ETSI10_WORLD, "CZ", 40, 160, 0}, {CTRY_DENMARK, ETSI10_WORLD, "DK", 40, 160, 0}, {CTRY_DOMINICA, FCC2_FCCA, "DM", 40, 160, 0}, {CTRY_DOMINICAN_REPUBLIC, FCC3_FCCA, "DO", 40, 160, 0}, {CTRY_ECUADOR, FCC3_WORLD, "EC", 40, 20, 0}, {CTRY_EGYPT, ETSI3_WORLD, "EG", 40, 160, 0}, {CTRY_EL_SALVADOR, FCC2_WORLD, "SV", 40, 20, 0}, {CTRY_ESTONIA, ETSI10_WORLD, "EE", 40, 160, 0}, {CTRY_ETHIOPIA, ETSI1_WORLD, "ET", 40, 160, 0}, {CTRY_FALKLAND_ISLANDS, ETSI10_WORLD, "FK", 40, 160, 0}, {CTRY_FAROE_ISLANDS, ETSI10_WORLD, "FO", 40, 160, 0}, {CTRY_FINLAND, ETSI10_WORLD, "FI", 40, 160, 0}, {CTRY_FRANCE, ETSI10_WORLD, "FR", 40, 160, 0}, {CTRY_FRENCH_GUIANA, ETSI10_WORLD, "GF", 40, 160, 0}, {CTRY_FRENCH_POLYNESIA, ETSI10_WORLD, "PF", 40, 160, 0}, {CTRY_FRENCH_SOUTHERN_TERRITORIES, ETSI10_WORLD, "TF", 40, 160, 0}, {CTRY_GEORGIA, ETSI1_WORLD, "GE", 40, 160, 0}, {CTRY_GERMANY, ETSI10_WORLD, "DE", 40, 160, 0}, {CTRY_GHANA, FCC3_WORLD, "GH", 40, 160, 0}, {CTRY_GIBRALTAR, ETSI10_WORLD, "GI", 40, 160, 0}, {CTRY_GREECE, ETSI10_WORLD, "GR", 40, 160, 0}, {CTRY_GREENLAND, ETSI10_WORLD, "GL", 40, 160, 0}, {CTRY_GRENADA, FCC3_FCCA, "GD", 40, 160, 0}, {CTRY_GUADELOUPE, ETSI1_WORLD, "GP", 40, 160, 0}, {CTRY_GUAM, FCC10_FCCA, "GU", 40, 160, 0}, {CTRY_GUATEMALA, ETSI1_WORLD, "GT", 40, 160, 0}, {CTRY_GUERNSEY, ETSI10_WORLD, "GG", 40, 160, 0}, {CTRY_GUYANA, APL1_ETSIC, "GY", 40, 160, 0}, {CTRY_HAITI, FCC3_FCCA, "HT", 40, 160, 0}, {CTRY_HEARD_ISLAND_AND_MCDONALD_ISLANDS, FCC6_WORLD, "HM", 40, 160, 0}, {CTRY_HOLY_SEE, ETSI10_WORLD, "VA", 40, 160, 0}, {CTRY_HONDURAS, FCC13_WORLD, "HN", 40, 160, 0}, {CTRY_HONG_KONG, FCC3_WORLD, "HK", 40, 160, 0}, {CTRY_HUNGARY, ETSI10_WORLD, "HU", 40, 160, 0}, {CTRY_ICELAND, ETSI10_WORLD, "IS", 40, 160, 0}, {CTRY_INDIA, APL15_WORLD, "IN", 40, 160, 0}, {CTRY_INDONESIA, APL2_ETSID, "ID", 40, 80, 0}, {CTRY_IRAQ, ETSI1_WORLD, "IQ", 40, 160, 0}, {CTRY_IRELAND, ETSI10_WORLD, "IE", 40, 160, 0}, {CTRY_ISLE_OF_MAN, ETSI10_WORLD, "IM", 40, 160, 0}, {CTRY_ISRAEL, ETSI3_WORLD, "IL", 40, 160, 0}, {CTRY_ITALY, ETSI10_WORLD, "IT", 40, 160, 0}, {CTRY_JAMAICA, FCC13_WORLD, "JM", 40, 160, 0}, {CTRY_JERSEY, ETSI10_WORLD, "JE", 40, 160, 0}, {CTRY_JORDAN, APL4_WORLD, "JO", 40, 160, 0}, {CTRY_KAZAKHSTAN, MKK5_MKKC, "KZ", 40, 160, 0}, {CTRY_KENYA, ETSI13_WORLD, "KE", 40, 160, 0}, {CTRY_KOREA_ROC, APL9_MKKC, "KR", 40, 160, 0}, {CTRY_KUWAIT, ETSI3_WORLD, "KW", 40, 160, 0}, {CTRY_LATVIA, ETSI10_WORLD, "LV", 40, 160, 0}, {CTRY_LEBANON, FCC3_WORLD, "LB", 40, 160, 0}, {CTRY_LESOTHO, ETSI1_WORLD, "LS", 40, 160, 0}, {CTRY_LIECHTENSTEIN, ETSI10_WORLD, "LI", 40, 160, 0}, {CTRY_LITHUANIA, ETSI10_WORLD, "LT", 40, 160, 0}, {CTRY_LUXEMBOURG, ETSI10_WORLD, "LU", 40, 160, 0}, {CTRY_MACAU, FCC3_WORLD, "MO", 40, 160, 0}, {CTRY_MACEDONIA, ETSI13_WORLD, "MK", 40, 160, 0}, {CTRY_MALAWI, ETSI1_WORLD, "MW", 40, 160, 0}, {CTRY_MALAYSIA, FCC11_WORLD, "MY", 40, 160, 0}, {CTRY_MALDIVES, APL6_WORLD, "MV", 40, 160, 0}, {CTRY_MALTA, ETSI10_WORLD, "MT", 40, 160, 0}, {CTRY_MARSHALL_ISLANDS, FCC3_FCCA, "MH", 40, 160, 0}, {CTRY_MARTINIQUE, ETSI10_WORLD, "MQ", 40, 160, 0}, {CTRY_MAURITANIA, ETSI1_WORLD, "MR", 40, 160, 0}, {CTRY_MAURITIUS, ETSI13_WORLD, "MU", 40, 160, 0}, {CTRY_MAYOTTE, ETSI1_WORLD, "YT", 40, 160, 0}, {CTRY_MEXICO, FCC3_ETSIC, "MX", 40, 160, 0}, {CTRY_MICRONESIA, FCC3_FCCA, "FM", 40, 160, 0}, {CTRY_MOLDOVA, ETSI13_WORLD, "MD", 40, 160, 0}, {CTRY_MONACO, ETSI10_WORLD, "MC", 40, 160, 0}, {CTRY_MONGOLIA, FCC3_WORLD, "MN", 40, 160, 0}, {CTRY_MONTENEGRO, ETSI10_WORLD, "ME", 40, 160, 0}, {CTRY_MONTSERRAT, ETSI10_WORLD, "MS", 40, 160, 0}, {CTRY_MOROCCO, ETSI3_WORLD, "MA", 40, 160, 0}, {CTRY_MYANMAR, APL1_WORLD, "MM", 40, 160, 0}, {CTRY_NAMIBIA, APL20_WORLD, "NA", 40, 160, 0}, {CTRY_NEPAL, APL23_WORLD, "NP", 40, 160, 0}, {CTRY_NETHERLANDS, ETSI10_WORLD, "NL", 40, 160, 0}, {CTRY_NETHERLANDS_ANTILLES, ETSI10_WORLD, "AN", 40, 160, 0}, {CTRY_NEW_CALEDONIA, ETSI10_WORLD, "NC", 40, 160, 0}, {CTRY_NEW_ZEALAND, FCC3_ETSIC, "NZ", 40, 160, 0}, {CTRY_NIGERIA, APL8_WORLD, "NG", 40, 160, 0}, {CTRY_NORTHERN_MARIANA_ISLANDS, FCC10_FCCA, "MP", 40, 160, 0}, {CTRY_NICARAGUA, FCC3_FCCA, "NI", 40, 160, 0}, {CTRY_NIUE, ETSI10_WORLD, "NU", 40, 160, 0}, {CTRY_NORFOLK_ISLAND, FCC6_WORLD, "NF", 40, 160, 0}, {CTRY_NORWAY, ETSI10_WORLD, "NO", 40, 160, 0}, {CTRY_OMAN, ETSI1_WORLD, "OM", 40, 160, 0}, {CTRY_PAKISTAN, APL1_ETSIC, "PK", 40, 160, 0}, {CTRY_PALAU, FCC3_FCCA, "PW", 40, 160, 0}, {CTRY_PANAMA, FCC14_FCCB, "PA", 40, 160, 0}, {CTRY_PAPUA_NEW_GUINEA, FCC3_WORLD, "PG", 40, 160, 0}, {CTRY_PARAGUAY, FCC3_WORLD, "PY", 40, 160, 0}, {CTRY_PERU, FCC3_WORLD, "PE", 40, 160, 0}, {CTRY_PHILIPPINES, FCC3_WORLD, "PH", 40, 160, 0}, {CTRY_POLAND, ETSI10_WORLD, "PL", 40, 160, 0}, {CTRY_PORTUGAL, ETSI10_WORLD, "PT", 40, 160, 0}, {CTRY_PUERTO_RICO, FCC10_FCCA, "PR", 40, 160, 0}, {CTRY_QATAR, ETSI14_WORLD, "QA", 40, 160, 0}, {CTRY_REUNION, ETSI1_WORLD, "RE", 40, 160, 0}, {CTRY_ROMANIA, ETSI10_WORLD, "RO", 40, 160, 0}, {CTRY_RUSSIA, ETSI8_WORLD, "RU", 40, 160, 0}, {CTRY_RWANDA, FCC3_WORLD, "RW", 40, 160, 0}, {CTRY_SAINT_BARTHELEMY, ETSI1_WORLD, "BL", 40, 160, 0}, {CTRY_SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA, ETSI10_WORLD, "SH", 40, 160, 0}, {CTRY_SAINT_KITTS_AND_NEVIS, APL10_WORLD, "KN", 40, 160, 0}, {CTRY_SAINT_LUCIA, APL10_WORLD, "LC", 40, 160, 0}, {CTRY_SAINT_MARTIN, ETSI1_WORLD, "MF", 40, 160, 0}, {CTRY_SAINT_PIERRE_AND_MIQUELON, ETSI13_WORLD, "PM", 40, 160, 0}, {CTRY_SAINT_VINCENT_AND_THE_GRENADIENS, ETSI13_WORLD, "VC", 40, 160, 0}, {CTRY_SAMOA, ETSI1_WORLD, "WS", 40, 40, 0}, {CTRY_SAN_MARINO, FCC3_FCCA, "SM", 40, 160, 0}, {CTRY_SAO_TOME_AND_PRINCIPE, FCC3_WORLD, "ST", 40, 160, 0}, {CTRY_SAUDI_ARABIA, ETSI15_WORLD, "SA", 40, 160, 0}, {CTRY_SENEGAL, FCC13_WORLD, "SN", 40, 160, 0}, {CTRY_SERBIA, ETSI13_WORLD, "RS", 40, 160, 0}, {CTRY_SINGAPORE, FCC3_WORLD, "SG", 40, 160, 0}, {CTRY_SINT_MAARTEN, ETSI10_WORLD, "SX", 40, 160, 0}, {CTRY_SLOVAKIA, ETSI10_WORLD, "SK", 40, 160, 0}, {CTRY_SLOVENIA, ETSI10_WORLD, "SI", 40, 160, 0}, {CTRY_SOUTH_AFRICA, FCC3_WORLD, "ZA", 40, 160, 0}, {CTRY_SPAIN, ETSI10_WORLD, "ES", 40, 160, 0}, {CTRY_SURINAME, ETSI1_WORLD, "SR", 40, 160, 0}, {CTRY_SRI_LANKA, FCC3_WORLD, "LK", 40, 20, 0}, {CTRY_SVALBARD_AND_JAN_MAYEN, FCC6_WORLD, "SJ", 40, 160, 0}, {CTRY_SWEDEN, ETSI10_WORLD, "SE", 40, 160, 0}, {CTRY_SWITZERLAND, ETSI10_WORLD, "CH", 40, 160, 0}, {CTRY_TAIWAN, FCC3_FCCA, "TW", 40, 160, 0}, {CTRY_TANZANIA, APL1_WORLD, "TZ", 40, 160, 0}, {CTRY_THAILAND, FCC3_WORLD, "TH", 40, 160, 0}, {CTRY_TOGO, ETSI1_WORLD, "TG", 40, 40, 0}, {CTRY_TRINIDAD_Y_TOBAGO, FCC3_WORLD, "TT", 40, 160, 0}, {CTRY_TUNISIA, ETSI3_WORLD, "TN", 40, 160, 0}, {CTRY_TURKEY, ETSI13_WORLD, "TR", 40, 160, 0}, {CTRY_TURKS_AND_CAICOS, FCC3_WORLD, "TC", 40, 160, 0}, {CTRY_UGANDA, FCC3_WORLD, "UG", 40, 160, 0}, {CTRY_UKRAINE, ETSI9_WORLD, "UA", 40, 160, 0}, {CTRY_UAE, FCC3_WORLD, "AE", 40, 160, 0}, {CTRY_UNITED_KINGDOM, ETSI10_WORLD, "GB", 40, 160, 0}, {CTRY_UNITED_STATES, FCC10_FCCA, "US", 40, 160, 0}, {CTRY_UNITED_STATES_MINOR_OUTLYING_ISLANDS, FCC10_FCCA, "UM", 40, 160, 0}, {CTRY_URUGUAY, FCC2_WORLD, "UY", 40, 160, 0}, {CTRY_UZBEKISTAN, ETSI3_WORLD, "UZ", 40, 160, 0}, {CTRY_VANUATU, FCC3_WORLD, "VU", 40, 160, 0}, {CTRY_VENEZUELA, FCC2_ETSIC, "VE", 40, 160, 0}, {CTRY_VIET_NAM, FCC3_WORLD, "VN", 40, 80, 0}, {CTRY_VIRGIN_ISLANDS, FCC10_FCCA, "VI", 40, 160, 0}, {CTRY_VIRGIN_ISLANDS_BRITISH, ETSI10_WORLD, "VG", 40, 160, 0}, {CTRY_WALLIS_AND_FUTUNA, ETSI1_WORLD, "WF", 40, 160, 0}, {CTRY_YEMEN, NULL1_WORLD, "YE", 40, 0, 0}, {CTRY_ZIMBABWE, ETSI1_WORLD, "ZW", 40, 160, 0}, {CTRY_JAPAN, MKK5_MKKC, "JP", 40, 160, 0}, {CTRY_XA, MKK5_MKKA, "XA", 40, 160, 0}, }; #else const struct country_code_to_reg_domain g_all_countries[] = { {CTRY_AFGHANISTAN, ETSI1_WORLD, "AF", 40, 160, 0}, {CTRY_ALAND_ISLANDS, FCC3_WORLD, "AX", 40, 160, 0}, {CTRY_ALBANIA, ETSI13_WORLD, "AL", 40, 160, 0}, {CTRY_ALGERIA, APL13_WORLD, "DZ", 40, 160, 0}, {CTRY_AMERICAN_SAMOA, FCC3_FCCA, "AS", 40, 160, 0}, {CTRY_ANDORRA, ETSI3_WORLD, "AD", 40, 160, 0}, {CTRY_ANGUILLA, ETSI1_WORLD, "AI", 40, 160, 0}, {CTRY_ANTIGUA_AND_BARBUDA, ETSI13_WORLD, "AG", 40, 160, 0}, {CTRY_ARGENTINA, APL17_ETSIC, "AR", 40, 160, 0}, {CTRY_ARMENIA, ETSI4_WORLD, "AM", 40, 20, 0}, {CTRY_ARUBA, ETSI1_WORLD, "AW", 40, 160, 0}, {CTRY_AUSTRALIA, FCC6_WORLD, "AU", 40, 160, 0}, {CTRY_AUSTRIA, ETSI13_WORLD, "AT", 40, 160, 0}, {CTRY_AZERBAIJAN, ETSI4_WORLD, "AZ", 40, 160, 0}, {CTRY_BAHAMAS, FCC3_WORLD, "BS", 40, 160, 0}, {CTRY_BAHRAIN, APL15_WORLD, "BH", 40, 20, 0}, {CTRY_BANGLADESH, APL1_WORLD, "BD", 40, 160, 0}, {CTRY_BARBADOS, FCC2_WORLD, "BB", 40, 160, 0}, {CTRY_BELARUS, ETSI1_WORLD, "BY", 40, 160, 0}, {CTRY_BELGIUM, ETSI13_WORLD, "BE", 40, 160, 0}, {CTRY_BELIZE, ETSI8_WORLD, "BZ", 40, 160, 0}, {CTRY_BERMUDA, FCC3_FCCA, "BM", 40, 160, 0}, {CTRY_BHUTAN, ETSI1_WORLD, "BT", 40, 160, 0}, {CTRY_BOLIVIA, APL8_WORLD, "BO", 40, 160, 0}, {CTRY_BOSNIA_HERZ, ETSI13_WORLD, "BA", 40, 160, 0}, {CTRY_BRAZIL, FCC3_ETSIC, "BR", 40, 160, 0}, {CTRY_BRUNEI_DARUSSALAM, APL6_WORLD, "BN", 40, 160, 0}, {CTRY_BULGARIA, ETSI13_WORLD, "BG", 40, 160, 0}, {CTRY_BURKINA_FASO, FCC3_WORLD, "BF", 40, 160, 0}, {CTRY_CAMBODIA, ETSI1_WORLD, "KH", 40, 160, 0}, {CTRY_CAMEROON, ETSI1_WORLD, "CM", 40, 160, 0}, {CTRY_CANADA, FCC6_FCCA, "CA", 40, 160, 0}, {CTRY_CAYMAN_ISLANDS, FCC3_WORLD, "KY", 40, 160, 0}, {CTRY_CENTRAL_AFRICA_REPUBLIC, FCC3_WORLD, "CF", 40, 40, 0}, {CTRY_CHAD, ETSI1_WORLD, "TD", 40, 160, 0}, {CTRY_CHILE, FCC13_WORLD, "CL", 40, 160, 0}, {CTRY_CHINA, APL14_WORLD, "CN", 40, 160, 0}, {CTRY_CHRISTMAS_ISLAND, FCC3_WORLD, "CX", 40, 160, 0}, {CTRY_COLOMBIA, FCC3_WORLD, "CO", 40, 160, 0}, {CTRY_COOK_ISLANDS, FCC3_WORLD, "CK", 40, 160, 0}, {CTRY_COSTA_RICA, FCC3_WORLD, "CR", 40, 160, 0}, {CTRY_COTE_DIVOIRE, FCC3_WORLD, "CI", 40, 160, 0}, {CTRY_CROATIA, ETSI13_WORLD, "HR", 40, 160, 0}, {CTRY_CYPRUS, ETSI13_WORLD, "CY", 40, 160, 0}, {CTRY_CZECH, ETSI13_WORLD, "CZ", 40, 160, 0}, {CTRY_DENMARK, ETSI13_WORLD, "DK", 40, 160, 0}, {CTRY_DOMINICA, FCC2_FCCA, "DM", 40, 160, 0}, {CTRY_DOMINICAN_REPUBLIC, FCC3_FCCA, "DO", 40, 160, 0}, {CTRY_ECUADOR, FCC3_WORLD, "EC", 40, 20, 0}, {CTRY_EGYPT, ETSI3_WORLD, "EG", 40, 160, 0}, {CTRY_EL_SALVADOR, FCC2_WORLD, "SV", 40, 20, 0}, {CTRY_ESTONIA, ETSI13_WORLD, "EE", 40, 160, 0}, {CTRY_ETHIOPIA, ETSI1_WORLD, "ET", 40, 160, 0}, {CTRY_FALKLAND_ISLANDS, ETSI13_WORLD, "FK", 40, 160, 0}, {CTRY_FAROE_ISLANDS, ETSI13_WORLD, "FO", 40, 160, 0}, {CTRY_FINLAND, ETSI13_WORLD, "FI", 40, 160, 0}, {CTRY_FRANCE, ETSI13_WORLD, "FR", 40, 160, 0}, {CTRY_FRENCH_GUIANA, ETSI13_WORLD, "GF", 40, 160, 0}, {CTRY_FRENCH_POLYNESIA, ETSI13_WORLD, "PF", 40, 160, 0}, {CTRY_FRENCH_SOUTHERN_TERRITORIES, ETSI13_WORLD, "TF", 40, 160, 0}, {CTRY_GEORGIA, ETSI1_WORLD, "GE", 40, 160, 0}, {CTRY_GERMANY, ETSI13_WORLD, "DE", 40, 160, 0}, {CTRY_GHANA, FCC3_WORLD, "GH", 40, 160, 0}, {CTRY_GIBRALTAR, ETSI1_WORLD, "GI", 40, 160, 0}, {CTRY_GREECE, ETSI13_WORLD, "GR", 40, 160, 0}, {CTRY_GREENLAND, ETSI1_WORLD, "GL", 40, 160, 0}, {CTRY_GRENADA, FCC3_FCCA, "GD", 40, 160, 0}, {CTRY_GUADELOUPE, ETSI1_WORLD, "GP", 40, 160, 0}, {CTRY_GUAM, FCC3_FCCA, "GU", 40, 160, 0}, {CTRY_GUATEMALA, ETSI1_WORLD, "GT", 40, 160, 0}, {CTRY_GUERNSEY, ETSI13_WORLD, "GG", 40, 160, 0}, {CTRY_GUYANA, APL1_ETSIC, "GY", 40, 160, 0}, {CTRY_HAITI, FCC3_FCCA, "HT", 40, 160, 0}, {CTRY_HEARD_ISLAND_AND_MCDONALD_ISLANDS, FCC6_WORLD, "HM", 40, 160, 0}, {CTRY_HOLY_SEE, ETSI13_WORLD, "VA", 40, 160, 0}, {CTRY_HONDURAS, FCC13_WORLD, "HN", 40, 160, 0}, {CTRY_HONG_KONG, FCC3_WORLD, "HK", 40, 160, 0}, {CTRY_HUNGARY, ETSI13_WORLD, "HU", 40, 160, 0}, {CTRY_ICELAND, ETSI13_WORLD, "IS", 40, 160, 0}, {CTRY_INDIA, APL19_ETSIC, "IN", 40, 160, 0}, {CTRY_INDONESIA, APL2_ETSID, "ID", 40, 80, 0}, {CTRY_IRAQ, ETSI1_WORLD, "IQ", 40, 160, 0}, {CTRY_IRELAND, ETSI13_WORLD, "IE", 40, 160, 0}, {CTRY_ISLE_OF_MAN, ETSI13_WORLD, "IM", 40, 160, 0}, {CTRY_ISRAEL, ETSI3_WORLD, "IL", 40, 160, 0}, {CTRY_ITALY, ETSI13_WORLD, "IT", 40, 160, 0}, {CTRY_JAMAICA, FCC13_WORLD, "JM", 40, 160, 0}, {CTRY_JERSEY, ETSI13_WORLD, "JE", 40, 160, 0}, {CTRY_JORDAN, APL4_WORLD, "JO", 40, 160, 0}, {CTRY_KAZAKHSTAN, MKK5_MKKC, "KZ", 40, 160, 0}, {CTRY_KENYA, ETSI13_WORLD, "KE", 40, 160, 0}, {CTRY_KOREA_ROC, APL9_MKKC, "KR", 40, 160, 0}, {CTRY_KUWAIT, ETSI3_WORLD, "KW", 40, 160, 0}, {CTRY_LATVIA, ETSI13_WORLD, "LV", 40, 160, 0}, {CTRY_LEBANON, FCC3_WORLD, "LB", 40, 160, 0}, {CTRY_LESOTHO, ETSI1_WORLD, "LS", 40, 160, 0}, {CTRY_LIECHTENSTEIN, ETSI13_WORLD, "LI", 40, 160, 0}, {CTRY_LITHUANIA, ETSI13_WORLD, "LT", 40, 160, 0}, {CTRY_LUXEMBOURG, ETSI13_WORLD, "LU", 40, 160, 0}, {CTRY_MACAU, FCC3_WORLD, "MO", 40, 160, 0}, {CTRY_MACEDONIA, ETSI13_WORLD, "MK", 40, 160, 0}, {CTRY_MALAWI, ETSI1_WORLD, "MW", 40, 160, 0}, {CTRY_MALAYSIA, FCC11_WORLD, "MY", 40, 160, 0}, {CTRY_MALDIVES, APL6_WORLD, "MV", 40, 160, 0}, {CTRY_MALTA, ETSI13_WORLD, "MT", 40, 160, 0}, {CTRY_MARSHALL_ISLANDS, FCC3_FCCA, "MH", 40, 160, 0}, {CTRY_MARTINIQUE, ETSI13_WORLD, "MQ", 40, 160, 0}, {CTRY_MAURITANIA, ETSI1_WORLD, "MR", 40, 160, 0}, {CTRY_MAURITIUS, ETSI13_WORLD, "MU", 40, 160, 0}, {CTRY_MAYOTTE, ETSI1_WORLD, "YT", 40, 160, 0}, {CTRY_MEXICO, FCC3_ETSIC, "MX", 40, 160, 0}, {CTRY_MICRONESIA, FCC3_FCCA, "FM", 40, 160, 0}, {CTRY_MOLDOVA, ETSI13_WORLD, "MD", 40, 160, 0}, {CTRY_MONACO, ETSI13_WORLD, "MC", 40, 160, 0}, {CTRY_MONGOLIA, FCC3_WORLD, "MN", 40, 160, 0}, {CTRY_MONTENEGRO, ETSI13_WORLD, "ME", 40, 160, 0}, {CTRY_MONTSERRAT, ETSI13_WORLD, "MS", 40, 160, 0}, {CTRY_MOROCCO, ETSI3_WORLD, "MA", 40, 160, 0}, {CTRY_MYANMAR, APL1_WORLD, "MM", 40, 160, 0}, {CTRY_NAMIBIA, APL20_WORLD, "NA", 40, 160, 0}, {CTRY_NEPAL, APL23_WORLD, "NP", 40, 160, 0}, {CTRY_NETHERLANDS, ETSI13_WORLD, "NL", 40, 160, 0}, {CTRY_NETHERLANDS_ANTILLES, ETSI13_WORLD, "AN", 40, 160, 0}, {CTRY_NEW_CALEDONIA, ETSI13_WORLD, "NC", 40, 160, 0}, {CTRY_NEW_ZEALAND, FCC3_ETSIC, "NZ", 40, 160, 0}, {CTRY_NIGERIA, APL8_WORLD, "NG", 40, 160, 0}, {CTRY_NORTHERN_MARIANA_ISLANDS, FCC3_FCCA, "MP", 40, 160, 0}, {CTRY_NICARAGUA, FCC3_FCCA, "NI", 40, 160, 0}, {CTRY_NIUE, ETSI13_WORLD, "NU", 40, 160, 0}, {CTRY_NORFOLK_ISLAND, FCC6_WORLD, "NF", 40, 160, 0}, {CTRY_NORWAY, ETSI13_WORLD, "NO", 40, 160, 0}, {CTRY_OMAN, ETSI1_WORLD, "OM", 40, 160, 0}, {CTRY_PAKISTAN, APL1_ETSIC, "PK", 40, 160, 0}, {CTRY_PALAU, FCC3_FCCA, "PW", 40, 160, 0}, {CTRY_PANAMA, FCC14_FCCB, "PA", 40, 160, 0}, {CTRY_PAPUA_NEW_GUINEA, FCC3_WORLD, "PG", 40, 160, 0}, {CTRY_PARAGUAY, FCC3_WORLD, "PY", 40, 160, 0}, {CTRY_PERU, FCC3_WORLD, "PE", 40, 160, 0}, {CTRY_PHILIPPINES, FCC3_WORLD, "PH", 40, 160, 0}, {CTRY_POLAND, ETSI13_WORLD, "PL", 40, 160, 0}, {CTRY_PORTUGAL, ETSI13_WORLD, "PT", 40, 160, 0}, {CTRY_PUERTO_RICO, FCC3_FCCA, "PR", 40, 160, 0}, {CTRY_QATAR, ETSI14_WORLD, "QA", 40, 160, 0}, {CTRY_REUNION, ETSI1_WORLD, "RE", 40, 160, 0}, {CTRY_ROMANIA, ETSI13_WORLD, "RO", 40, 160, 0}, {CTRY_RUSSIA, ETSI8_WORLD, "RU", 40, 160, 0}, {CTRY_RWANDA, FCC3_WORLD, "RW", 40, 160, 0}, {CTRY_SAINT_BARTHELEMY, ETSI1_WORLD, "BL", 40, 160, 0}, {CTRY_SAINT_HELENA_ASCENSION_AND_TRISTAN_DA_CUNHA, ETSI13_WORLD, "SH", 40, 160, 0}, {CTRY_SAINT_KITTS_AND_NEVIS, APL10_WORLD, "KN", 40, 160, 0}, {CTRY_SAINT_LUCIA, APL10_WORLD, "LC", 40, 160, 0}, {CTRY_SAINT_MARTIN, ETSI1_WORLD, "MF", 40, 160, 0}, {CTRY_SAINT_PIERRE_AND_MIQUELON, ETSI13_WORLD, "PM", 40, 160, 0}, {CTRY_SAINT_VINCENT_AND_THE_GRENADIENS, ETSI13_WORLD, "VC", 40, 160, 0}, {CTRY_SAMOA, ETSI1_WORLD, "WS", 40, 40, 0}, {CTRY_SAN_MARINO, FCC3_FCCA, "SM", 40, 160, 0}, {CTRY_SAO_TOME_AND_PRINCIPE, FCC3_WORLD, "ST", 40, 160, 0}, {CTRY_SAUDI_ARABIA, ETSI15_WORLD, "SA", 40, 160, 0}, {CTRY_SENEGAL, FCC13_WORLD, "SN", 40, 160, 0}, {CTRY_SERBIA, ETSI13_WORLD, "RS", 40, 160, 0}, {CTRY_SINGAPORE, FCC3_WORLD, "SG", 40, 160, 0}, {CTRY_SINT_MAARTEN, ETSI13_WORLD, "SX", 40, 160, 0}, {CTRY_SLOVAKIA, ETSI13_WORLD, "SK", 40, 160, 0}, {CTRY_SLOVENIA, ETSI13_WORLD, "SI", 40, 160, 0}, {CTRY_SOUTH_AFRICA, FCC3_WORLD, "ZA", 40, 160, 0}, {CTRY_SPAIN, ETSI13_WORLD, "ES", 40, 160, 0}, {CTRY_SURINAME, ETSI1_WORLD, "SR", 40, 160, 0}, {CTRY_SRI_LANKA, FCC3_WORLD, "LK", 40, 20, 0}, {CTRY_SVALBARD_AND_JAN_MAYEN, FCC6_WORLD, "SJ", 40, 160, 0}, {CTRY_SWEDEN, ETSI13_WORLD, "SE", 40, 160, 0}, {CTRY_SWITZERLAND, ETSI13_WORLD, "CH", 40, 160, 0}, {CTRY_TAIWAN, FCC3_FCCA, "TW", 40, 160, 0}, {CTRY_TANZANIA, APL1_WORLD, "TZ", 40, 160, 0}, {CTRY_THAILAND, FCC3_WORLD, "TH", 40, 160, 0}, {CTRY_TOGO, ETSI1_WORLD, "TG", 40, 40, 0}, {CTRY_TRINIDAD_Y_TOBAGO, FCC3_WORLD, "TT", 40, 160, 0}, {CTRY_TUNISIA, ETSI3_WORLD, "TN", 40, 160, 0}, {CTRY_TURKEY, ETSI13_WORLD, "TR", 40, 160, 0}, {CTRY_TURKS_AND_CAICOS, FCC3_WORLD, "TC", 40, 160, 0}, {CTRY_UGANDA, FCC3_WORLD, "UG", 40, 160, 0}, {CTRY_UKRAINE, ETSI9_WORLD, "UA", 40, 160, 0}, {CTRY_UAE, FCC3_WORLD, "AE", 40, 160, 0}, {CTRY_UNITED_KINGDOM, ETSI13_WORLD, "GB", 40, 160, 0}, {CTRY_UNITED_STATES, FCC3_FCCA, "US", 40, 160, 0}, {CTRY_UNITED_STATES_MINOR_OUTLYING_ISLANDS, FCC3_FCCA, "UM", 40, 160, 0}, {CTRY_URUGUAY, FCC2_WORLD, "UY", 40, 160, 0}, {CTRY_UZBEKISTAN, ETSI3_WORLD, "UZ", 40, 160, 0}, {CTRY_VANUATU, FCC3_WORLD, "VU", 40, 160, 0}, {CTRY_VENEZUELA, FCC2_ETSIC, "VE", 40, 160, 0}, {CTRY_VIET_NAM, FCC3_WORLD, "VN", 40, 80, 0}, {CTRY_VIRGIN_ISLANDS, FCC3_FCCA, "VI", 40, 160, 0}, {CTRY_VIRGIN_ISLANDS_BRITISH, ETSI13_WORLD, "VG", 40, 160, 0}, {CTRY_WALLIS_AND_FUTUNA, ETSI1_WORLD, "WF", 40, 160, 0}, {CTRY_YEMEN, NULL1_WORLD, "YE", 40, 0, 0}, {CTRY_ZIMBABWE, ETSI1_WORLD, "ZW", 40, 160, 0}, {CTRY_JAPAN, MKK5_MKKC, "JP", 40, 160, 0}, {CTRY_XA, MKK5_MKKA, "XA", 40, 160, 0}, }; #endif #endif enum reg_domains_2g { FCCA, FCCB, WORLD, MKKA, MKKC, ETSIC, ETSID, KRRA, WORLD_2G_1, WORLD_2G_2, WORLD_2G_3, REG_DOMAINS_2G_MAX, }; enum reg_domains_5g { NULL1, FCC1, FCC2, FCC3, FCC4, FCC5, FCC6, FCC8, FCC10, FCC11, FCC13, FCC14, ETSI1, ETSI3, ETSI4, ETSI8, ETSI9, ETSI10, ETSI11, ETSI12, ETSI13, ETSI14, ETSI15, APL1, APL2, APL4, APL6, APL8, APL9, APL10, APL11, APL12, APL13, APL14, APL15, APL16, APL17, APL19, APL20, APL23, APL24, MKK3, MKK4, MKK5, MKK9, MKK10, MKK11, MKK16, MKK17, WORLD_5G_1, WORLD_5G_2, REG_DOMAINS_5G_MAX, }; const struct reg_domain_pair g_reg_dmn_pairs[] = { {NULL1_WORLD, NULL1, WORLD}, {FCC1_FCCA, FCC1, FCCA}, {FCC1_WORLD, FCC1, WORLD}, {FCC2_FCCA, FCC2, FCCA}, {FCC2_WORLD, FCC2, WORLD}, {FCC2_ETSIC, FCC2, ETSIC}, {FCC3_FCCA, FCC3, FCCA}, {FCC3_WORLD, FCC3, WORLD}, {FCC3_ETSIC, FCC3, ETSIC}, {FCC4_FCCA, FCC4, FCCA}, {FCC5_FCCA, FCC5, FCCA}, {FCC6_WORLD, FCC6, WORLD}, {FCC6_FCCA, FCC6, FCCA}, {FCC8_FCCA, FCC8, FCCA}, {FCC11_WORLD, FCC11, WORLD}, {FCC13_WORLD, FCC13, WORLD}, {FCC14_FCCB, FCC14, FCCB}, {ETSI1_WORLD, ETSI1, WORLD}, {ETSI3_WORLD, ETSI3, WORLD}, {ETSI4_WORLD, ETSI4, WORLD}, {ETSI8_WORLD, ETSI8, WORLD}, {ETSI9_WORLD, ETSI9, WORLD}, {ETSI10_WORLD, ETSI10, WORLD}, {ETSI10_FCCA, ETSI10, FCCA}, {ETSI11_WORLD, ETSI11, WORLD}, {ETSI12_WORLD, ETSI12, WORLD}, {ETSI13_WORLD, ETSI13, WORLD}, {ETSI14_WORLD, ETSI14, WORLD}, {ETSI15_WORLD, ETSI15, WORLD}, {APL1_WORLD, APL1, WORLD}, {APL1_ETSIC, APL1, ETSIC}, {APL2_WORLD, APL2, WORLD}, {APL2_ETSIC, APL2, ETSIC}, {APL2_ETSID, APL2, ETSID}, {APL4_WORLD, APL4, WORLD}, {APL6_WORLD, APL6, WORLD}, {APL8_WORLD, APL8, WORLD}, {APL9_WORLD, APL9, WORLD}, {APL9_MKKC, APL9, MKKC}, {APL9_KRRA, APL9, KRRA}, {APL10_WORLD, APL10, WORLD}, {APL11_FCCA, APL11, FCCA}, {APL12_WORLD, APL12, WORLD}, {APL13_WORLD, APL13, WORLD}, {APL14_WORLD, APL14, WORLD}, {APL15_WORLD, APL15, WORLD}, {APL16_WORLD, APL16, WORLD}, {APL16_ETSIC, APL16, ETSIC}, {APL17_ETSIC, APL17, ETSIC}, {APL17_ETSID, APL17, ETSID}, {APL19_ETSIC, APL19, ETSIC}, {APL20_WORLD, APL20, WORLD}, {APL23_WORLD, APL23, WORLD}, {APL24_ETSIC, APL24, ETSIC}, {MKK3_MKKC, MKK3, MKKC}, {MKK5_MKKA, MKK5, MKKA}, {MKK5_MKKC, MKK5, MKKC}, {MKK11_MKKC, MKK11, MKKC}, {MKK16_MKKC, MKK16, MKKC}, {MKK17_MKKC, MKK17, MKKC}, {WORLD_60, WORLD_5G_2, WORLD_2G_3}, {WORLD_61, WORLD_5G_2, WORLD_2G_3}, {WORLD_62, WORLD_5G_2, WORLD_2G_3}, {WORLD_63, WORLD_5G_1, WORLD_2G_2}, {WORLD_65, WORLD_5G_1, WORLD_2G_2}, {WORLD_64, WORLD_5G_1, WORLD_2G_1}, {WORLD_66, WORLD_5G_2, WORLD_2G_1}, {WORLD_69, WORLD_5G_2, WORLD_2G_1}, {WORLD_67, WORLD_5G_2, WORLD_2G_2}, {WORLD_68, WORLD_5G_2, WORLD_2G_2}, {WORLD_6A, WORLD_5G_2, WORLD_2G_2}, {WORLD_6C, WORLD_5G_2, WORLD_2G_2}, }; enum reg_rules_2g { CHAN_1_11_1, CHAN_1_11_2, CHAN_1_11_3, CHAN_1_13_1, CHAN_1_13_2, CHAN_1_13_3, CHAN_1_13_4, CHAN_1_13_5, CHAN_12_12_1, CHAN_12_13_1, CHAN_14_1, CHAN_14_2, }; const struct regulatory_rule reg_rules_2g[] = { [CHAN_1_11_1] = {2402, 2472, 40, 30, 0}, [CHAN_1_11_2] = {2402, 2472, 40, 20, 0}, [CHAN_1_11_3] = {2402, 2472, 40, 36, 0}, [CHAN_1_13_1] = {2402, 2482, 40, 20, 0}, [CHAN_1_13_2] = {2402, 2482, 40, 30, 0}, [CHAN_1_13_3] = {2402, 2482, 40, 36, 0}, [CHAN_1_13_4] = {2402, 2482, 40, 23, 0}, [CHAN_1_13_5] = {2402, 2482, 20, 20, 0}, [CHAN_12_12_1] = {2457, 2477, 20, 20, REGULATORY_CHAN_NO_IR}, [CHAN_12_13_1] = {2457, 2482, 20, 20, REGULATORY_CHAN_NO_IR}, [CHAN_14_1] = {2474, 2494, 20, 23, REGULATORY_CHAN_NO_OFDM}, [CHAN_14_2] = {2474, 2494, 20, 20, REGULATORY_CHAN_NO_OFDM | REGULATORY_CHAN_NO_IR}, }; const struct regdomain regdomains_2g[] = { [FCCA] = {CTL_FCC, DFS_UNINIT_REG, 0, 6, 1, {CHAN_1_11_1} }, [FCCB] = {CTL_FCC, DFS_UNINIT_REG, 0, 6, 1, {CHAN_1_11_3} }, [WORLD] = {CTL_ETSI, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_13_1} }, [MKKA] = {CTL_MKK, DFS_UNINIT_REG, 0, 0, 2, {CHAN_1_13_4, CHAN_14_1} }, [MKKC] = {CTL_MKK, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_13_4} }, [ETSIC] = {CTL_ETSI, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_13_2} }, [ETSID] = {CTL_ETSI, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_13_5} }, [KRRA] = {CTL_KOR, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_13_4} }, [WORLD_2G_1] = {CTL_NONE, DFS_UNINIT_REG, 0, 0, 1, {CHAN_1_11_2} }, [WORLD_2G_2] = {CTL_NONE, DFS_UNINIT_REG, 0, 0, 2, {CHAN_1_11_2, CHAN_12_13_1} }, [WORLD_2G_3] = {CTL_NONE, DFS_UNINIT_REG, 0, 0, 2, {CHAN_1_11_2, CHAN_12_12_1} }, }; enum reg_rules_5g { CHAN_4910_4990_1, CHAN_4940_4990_1, CHAN_5030_5090_1, CHAN_5170_5250_1, CHAN_5170_5250_2, CHAN_5170_5250_3, CHAN_5170_5250_4, CHAN_5170_5250_5, CHAN_5170_5250_6, CHAN_5170_5250_7, CHAN_5170_5250_8, CHAN_5170_5250_9, CHAN_5170_5330_1, CHAN_5170_5330_2, CHAN_5250_5330_1, CHAN_5250_5330_2, CHAN_5250_5330_3, CHAN_5250_5330_4, CHAN_5250_5330_5, CHAN_5250_5330_6, CHAN_5250_5330_7, CHAN_5250_5330_8, CHAN_5250_5330_9, CHAN_5250_5330_10, CHAN_5250_5330_11, CHAN_5250_5330_12, CHAN_5250_5330_13, CHAN_5250_5330_14, CHAN_5490_5730_1, CHAN_5490_5730_2, CHAN_5490_5730_3, CHAN_5490_5730_4, CHAN_5490_5730_5, CHAN_5490_5730_6, CHAN_5490_5730_7, CHAN_5490_5710_1, CHAN_5490_5710_2, CHAN_5490_5710_3, CHAN_5490_5710_4, CHAN_5490_5710_5, CHAN_5490_5710_6, CHAN_5490_5710_7, CHAN_5490_5590_1, CHAN_5490_5590_2, CHAN_5490_5590_3, CHAN_5490_5570_1, CHAN_5490_5650_2, CHAN_5490_5670_1, CHAN_5490_5670_2, CHAN_5490_5630_1, CHAN_5650_5730_1, CHAN_5650_5730_2, CHAN_5650_5730_3, CHAN_5735_5835_1, CHAN_5735_5835_2, CHAN_5735_5835_3, CHAN_5735_5835_4, CHAN_5735_5835_5, CHAN_5735_5835_6, CHAN_5735_5835_7, CHAN_5735_5835_8, CHAN_5735_5875_1, CHAN_5735_5875_2, CHAN_5735_5875_3, CHAN_5735_5875_4, CHAN_5735_5875_5, CHAN_5735_5815_1, CHAN_5735_5815_2, CHAN_5735_5815_3, CHAN_5735_5815_4, CHAN_5735_5775_1, CHAN_5835_5855_1, CHAN_5855_5875_1, CHAN_5850_5925_1, CHAN_5850_5925_2, }; const struct regulatory_rule reg_rules_5g[] = { [CHAN_4910_4990_1] = {4910, 4990, 20, 20, 0}, [CHAN_4940_4990_1] = {4940, 4990, 20, 33, 0}, [CHAN_5030_5090_1] = {5030, 5090, 20, 20, 0}, [CHAN_5170_5250_1] = {5170, 5250, 80, 17, 0}, [CHAN_5170_5250_2] = {5170, 5250, 80, 23, 0}, [CHAN_5170_5250_3] = {5170, 5250, 80, 20, 0}, [CHAN_5170_5250_4] = {5170, 5250, 80, 30, 0}, [CHAN_5170_5250_5] = {5170, 5250, 80, 24, 0}, [CHAN_5170_5250_6] = {5170, 5250, 80, 18, 0}, [CHAN_5170_5250_7] = {5170, 5250, 80, 20, REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5170_5250_8] = {5170, 5250, 80, 23, REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5170_5250_9] = {5170, 5250, 40, 30, 0}, [CHAN_5170_5330_1] = {5170, 5330, 160, 20, REGULATORY_CHAN_NO_IR}, [CHAN_5170_5330_2] = {5170, 5330, 160, 24, 0}, [CHAN_5250_5330_1] = {5250, 5330, 80, 23, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_2] = {5250, 5330, 80, 20, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_3] = {5250, 5330, 80, 18, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_4] = {5250, 5330, 80, 30, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_5] = {5250, 5330, 80, 23, 0}, [CHAN_5250_5330_6] = {5250, 5330, 80, 30, 0}, [CHAN_5250_5330_7] = {5250, 5330, 80, 24, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_8] = {5250, 5330, 80, 36, 0}, [CHAN_5250_5330_9] = {5250, 5330, 80, 20, 0}, [CHAN_5250_5330_10] = {5250, 5330, 80, 24, 0}, [CHAN_5250_5330_11] = {5250, 5330, 80, 20, REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5250_5330_12] = {5250, 5330, 80, 23, REGULATORY_CHAN_RADAR | REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5250_5330_13] = {5250, 5330, 40, 30, REGULATORY_CHAN_RADAR}, [CHAN_5250_5330_14] = {5250, 5330, 80, 20, REGULATORY_CHAN_RADAR | REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5490_5730_1] = {5490, 5730, 160, 24, REGULATORY_CHAN_RADAR}, [CHAN_5490_5730_2] = {5490, 5730, 160, 20, REGULATORY_CHAN_NO_IR}, [CHAN_5490_5730_3] = {5490, 5730, 160, 30, 0}, [CHAN_5490_5730_4] = {5490, 5730, 160, 24, 0}, [CHAN_5490_5730_5] = {5490, 5730, 160, 30, REGULATORY_CHAN_RADAR}, [CHAN_5490_5730_6] = {5490, 5730, 160, 23, REGULATORY_CHAN_RADAR}, [CHAN_5490_5730_7] = {5490, 5730, 160, 20, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_1] = {5490, 5710, 160, 30, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_2] = {5490, 5710, 160, 20, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_3] = {5490, 5710, 160, 27, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_4] = {5490, 5710, 40, 30, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_5] = {5490, 5710, 160, 24, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_6] = {5490, 5710, 160, 26, REGULATORY_CHAN_RADAR}, [CHAN_5490_5710_7] = {5490, 5710, 160, 23, REGULATORY_CHAN_RADAR}, [CHAN_5490_5590_1] = {5490, 5590, 80, 24, REGULATORY_CHAN_RADAR}, [CHAN_5490_5590_2] = {5490, 5590, 80, 30, 0}, [CHAN_5490_5590_3] = {5490, 5590, 80, 36, 0}, [CHAN_5490_5570_1] = {5490, 5570, 80, 30, REGULATORY_CHAN_RADAR}, [CHAN_5490_5650_2] = {5490, 5650, 160, 24, REGULATORY_CHAN_RADAR}, [CHAN_5490_5670_1] = {5490, 5670, 160, 20, REGULATORY_CHAN_RADAR}, [CHAN_5490_5670_2] = {5490, 5670, 160, 23, REGULATORY_CHAN_RADAR}, [CHAN_5490_5630_1] = {5490, 5630, 80, 30, REGULATORY_CHAN_RADAR}, [CHAN_5650_5730_1] = {5650, 5730, 80, 24, REGULATORY_CHAN_RADAR}, [CHAN_5650_5730_2] = {5650, 5730, 80, 30, 0}, [CHAN_5650_5730_3] = {5650, 5730, 80, 36, 0}, [CHAN_5735_5835_1] = {5735, 5835, 80, 23, 0}, [CHAN_5735_5835_2] = {5735, 5835, 80, 30, 0}, [CHAN_5735_5835_3] = {5735, 5835, 80, 20, 0}, [CHAN_5735_5835_4] = {5735, 5835, 80, 33, 0}, [CHAN_5735_5835_5] = {5735, 5835, 80, 20, REGULATORY_CHAN_NO_IR}, [CHAN_5735_5835_6] = {5735, 5835, 80, 24, 0}, [CHAN_5735_5835_7] = {5735, 5835, 80, 36, 0}, [CHAN_5735_5835_8] = {5735, 5835, 80, 23, REGULATORY_CHAN_RADAR}, [CHAN_5735_5875_1] = {5735, 5875, 20, 27, REGULATORY_CHAN_RADAR}, [CHAN_5735_5875_2] = {5735, 5875, 20, 30, 0}, [CHAN_5735_5875_3] = {5735, 5875, 80, 30, 0}, [CHAN_5735_5875_4] = {5735, 5875, 80, 14, 0}, [CHAN_5735_5875_5] = {5735, 5875, 80, 20, REGULATORY_CHAN_RADAR}, [CHAN_5735_5815_1] = {5735, 5815, 80, 30, 0}, [CHAN_5735_5815_2] = {5735, 5815, 80, 30, REGULATORY_CHAN_RADAR}, [CHAN_5735_5815_3] = {5735, 5815, 80, 23, REGULATORY_CHAN_INDOOR_ONLY}, [CHAN_5735_5815_4] = {5735, 5815, 20, 20, 0}, [CHAN_5735_5775_1] = {5735, 5775, 40, 23, 0}, [CHAN_5835_5855_1] = {5835, 5855, 20, 30, 0}, [CHAN_5855_5875_1] = {5855, 5875, 20, 30, 0}, [CHAN_5850_5925_1] = {5850, 5925, 20, 24, 0}, [CHAN_5850_5925_2] = {5850, 5925, 20, 30, 0}, }; const struct regdomain regdomains_5g[] = { [FCC1] = {CTL_FCC, DFS_FCC_REG, 2, 6, 3, {CHAN_5170_5250_1, CHAN_5250_5330_1, CHAN_5735_5835_2} }, [FCC2] = {CTL_FCC, DFS_FCC_REG, 2, 6, 3, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5735_5835_2} }, [FCC3] = {CTL_FCC, DFS_FCC_REG, 2, 6, 4, {CHAN_5170_5250_5, CHAN_5250_5330_7, CHAN_5490_5730_1, CHAN_5735_5835_2} }, [FCC4] = {CTL_FCC, DFS_FCC_REG, 2, 6, 1, {CHAN_4940_4990_1} }, [FCC5] = {CTL_FCC, DFS_UNINIT_REG, 2, 6, 2, {CHAN_5170_5250_4, CHAN_5735_5835_2} }, [FCC6] = {CTL_FCC, DFS_FCC_REG, 2, 6, 5, {CHAN_5170_5250_5, CHAN_5250_5330_7, CHAN_5490_5590_1, CHAN_5650_5730_1, CHAN_5735_5835_2} }, [FCC8] = {CTL_FCC, DFS_FCC_REG, 2, 6, 4, {CHAN_5170_5250_4, CHAN_5250_5330_7, CHAN_5490_5730_1, CHAN_5735_5835_2} }, [FCC10] = {CTL_FCC, DFS_FCC_REG, 2, 0, 5, {CHAN_5170_5250_4, CHAN_5250_5330_7, CHAN_5490_5730_1, CHAN_5735_5835_2, CHAN_5850_5925_1} }, [FCC11] = {CTL_FCC, DFS_FCC_REG, 2, 6, 4, {CHAN_5170_5250_5, CHAN_5250_5330_7, CHAN_5490_5650_2, CHAN_5735_5835_6} }, [FCC13] = {CTL_FCC, DFS_UNINIT_REG, 2, 0, 4, {CHAN_5170_5330_2, CHAN_5250_5330_10, CHAN_5490_5730_4, CHAN_5735_5835_2} }, [FCC14] = {CTL_FCC, DFS_UNINIT_REG, 2, 0, 4, {CHAN_5170_5250_4, CHAN_5250_5330_10, CHAN_5490_5730_4, CHAN_5735_5835_2} }, [ETSI1] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 3, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5490_5710_1} }, [ETSI3] = {CTL_ETSI, DFS_ETSI_REG, 5, 0, 2, {CHAN_5170_5250_2, CHAN_5250_5330_1} }, [ETSI4] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 2, {CHAN_5170_5250_6, CHAN_5250_5330_3} }, [ETSI8] = {CTL_ETSI, DFS_UNINIT_REG, 20, 0, 4, {CHAN_5170_5250_2, CHAN_5250_5330_5, CHAN_5490_5730_3, CHAN_5735_5835_2} }, [ETSI9] = {CTL_ETSI, DFS_ETSI_REG, 20, 0, 4, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5490_5710_5, CHAN_5735_5835_6} }, [ETSI10] = {CTL_ETSI, DFS_ETSI_REG, 10, 0, 4, {CHAN_5170_5250_7, CHAN_5250_5330_14, CHAN_5490_5710_3, CHAN_5850_5925_2} }, [ETSI11] = {CTL_ETSI, DFS_ETSI_REG, 10, 0, 4, {CHAN_5170_5250_7, CHAN_5250_5330_14, CHAN_5490_5710_3, CHAN_5735_5875_1} }, [ETSI12] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 4, {CHAN_5170_5250_7, CHAN_5250_5330_14, CHAN_5490_5730_6, CHAN_5735_5835_8} }, [ETSI13] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 4, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5490_5730_5, CHAN_5735_5875_4} }, [ETSI14] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 4, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5490_5730_7, CHAN_5735_5875_5} }, [ETSI15] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 4, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5490_5730_5, CHAN_5735_5815_2} }, [APL1] = {CTL_ETSI, DFS_UNINIT_REG, 2, 0, 1, {CHAN_5735_5835_2} }, [APL2] = {CTL_ETSI, DFS_UNINIT_REG, 2, 0, 1, {CHAN_5735_5815_4} }, [APL4] = {CTL_ETSI, DFS_UNINIT_REG, 2, 0, 2, {CHAN_5170_5250_2, CHAN_5735_5835_1} }, [APL6] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 3, {CHAN_5170_5250_3, CHAN_5250_5330_2, CHAN_5735_5835_3} }, [APL8] = {CTL_FCC, DFS_ETSI_REG, 2, 0, 2, {CHAN_5250_5330_4, CHAN_5735_5835_2} }, [APL9] = {CTL_MKK, DFS_KR_REG, 2, 6, 4, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5490_5730_6, CHAN_5735_5835_1} }, [APL10] = {CTL_ETSI, DFS_FCC_REG, 2, 6, 4, {CHAN_5170_5250_2, CHAN_5250_5330_4, CHAN_5490_5710_1, CHAN_5735_5815_1} }, [APL11] = { CTL_ETSI, DFS_FCC_REG, 2, 0, 4, {CHAN_5170_5250_9, CHAN_5250_5330_13, CHAN_5490_5710_4, CHAN_5735_5875_2} }, [APL12] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 3, {CHAN_5170_5250_2, CHAN_5490_5570_1, CHAN_5735_5775_1} }, [APL13] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 3, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5490_5670_2} }, [APL14] = {CTL_MKK, DFS_CN_REG, 2, 0, 3, {CHAN_5170_5250_2, CHAN_5250_5330_1, CHAN_5735_5835_4} }, [APL15] = {CTL_FCC, DFS_UNINIT_REG, 2, 0, 3, {CHAN_5170_5250_2, CHAN_5250_5330_5, CHAN_5735_5835_4} }, [APL16] = {CTL_FCC, DFS_UNINIT_REG, 2, 0, 5, {CHAN_5170_5250_1, CHAN_5250_5330_6, CHAN_5490_5590_2, CHAN_5650_5730_2, CHAN_5735_5835_2} }, [APL17] = {CTL_FCC, DFS_UNINIT_REG, 2, 0, 5, {CHAN_5170_5250_2, CHAN_5250_5330_8, CHAN_5490_5590_3, CHAN_5650_5730_3, CHAN_5735_5835_7} }, [APL19] = {CTL_FCC, DFS_FCC_REG, 2, 0, 4, {CHAN_5170_5250_4, CHAN_5250_5330_7, CHAN_5490_5730_1, CHAN_5735_5875_3} }, [APL20] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 4, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5490_5730_5, CHAN_5735_5835_4} }, [APL23] = {CTL_ETSI, DFS_UNINIT_REG, 2, 0, 3, {CHAN_5170_5250_7, CHAN_5250_5330_11, CHAN_5735_5835_3} }, [APL24] = {CTL_ETSI, DFS_ETSI_REG, 2, 0, 3, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5735_5815_3} }, [MKK3] = {CTL_MKK, DFS_UNINIT_REG, 2, 0, 1, {CHAN_5170_5250_3} }, [MKK5] = {CTL_MKK, DFS_MKK_REG, 2, 0, 3, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5490_5710_7} }, [MKK11] = {CTL_MKK, DFS_MKK_REG, 2, 0, 5, {CHAN_4910_4990_1, CHAN_5170_5250_2, CHAN_5030_5090_1, CHAN_5250_5330_1, CHAN_5490_5710_7} }, [MKK16] = {CTL_MKK, DFS_MKK_REG, 2, 0, 1, {CHAN_5490_5710_6} }, [MKK17] = {CTL_MKK, DFS_MKK_REG, 2, 0, 3, {CHAN_5170_5250_8, CHAN_5250_5330_12, CHAN_5490_5710_7} }, [WORLD_5G_1] = {CTL_NONE, DFS_UNINIT_REG, 2, 0, 2, {CHAN_5170_5330_1, CHAN_5735_5835_5} }, [WORLD_5G_2] = {CTL_NONE, DFS_UNINIT_REG, 2, 0, 3, {CHAN_5170_5330_1, CHAN_5490_5730_2, CHAN_5735_5835_5} }, }; const uint32_t reg_2g_sub_dmn_code[REG_DOMAINS_2G_MAX] = { [FCCA] = 0x0A10, [FCCB] = 0x0B90, [WORLD] = 0x0199, [MKKA] = 0x0A40, [MKKC] = 0x0A50, [ETSIC] = 0x0C30, [ETSID] = 0x0F30, [KRRA] = 0x0A60, }; const uint32_t reg_5g_sub_dmn_code[REG_DOMAINS_5G_MAX] = { [NULL1] = 0x0198, [FCC1] = 0x0110, [FCC2] = 0x0120, [FCC3] = 0x0160, [FCC4] = 0x0165, [FCC5] = 0x0510, [FCC6] = 0x0610, [FCC8] = 0x0810, [FCC10] = 0x0B10, [FCC11] = 0x0B20, [FCC13] = 0x0B60, [FCC14] = 0x0B70, [ETSI1] = 0x0130, [ETSI3] = 0x0330, [ETSI4] = 0x0430, [ETSI8] = 0x0830, [ETSI9] = 0x0930, [ETSI10] = 0x0D30, [ETSI11] = 0x0E30, [ETSI12] = 0x0E38, [ETSI13] = 0x0E39, [ETSI14] = 0x0E40, [ETSI15] = 0x0E41, [APL1] = 0x0150, [APL2] = 0x0250, [APL4] = 0x0450, [APL6] = 0x0650, [APL8] = 0x0850, [APL9] = 0x0950, [APL10] = 0x1050, [APL11] = 0x1150, [APL12] = 0x1160, [APL13] = 0x1170, [APL14] = 0x1180, [APL15] = 0x1190, [APL16] = 0x1200, [APL17] = 0x1210, [APL23] = 0x1280, [APL20] = 0x1250, [APL23] = 0x1280, [MKK3] = 0x0340, [MKK5] = 0x0540, [MKK11] = 0x1140, [MKK16] = 0x1640, [MKK17] = 0x1650, }; QDF_STATUS reg_get_num_countries(int *num_countries) { *num_countries = QDF_ARRAY_SIZE(g_all_countries); return QDF_STATUS_SUCCESS; } QDF_STATUS reg_get_num_reg_dmn_pairs(int *num_reg_dmn) { *num_reg_dmn = QDF_ARRAY_SIZE(g_reg_dmn_pairs); return QDF_STATUS_SUCCESS; } QDF_STATUS reg_get_default_country(uint16_t *default_country) { *default_country = CTRY_UNITED_STATES; return QDF_STATUS_SUCCESS; } bool reg_etsi13_regdmn(uint8_t reg_dmn) { return reg_dmn == ETSI13; }
49570.c
/* -*- Mode: c; c-basic-offset: 4 -*- */ /* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2006, 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <syslog.h> #include <pwd.h> #include <time.h> #if defined(DARWIN) || defined(DARWIN9) #include <malloc/malloc.h> #else #include <malloc.h> #endif /* We pass through only a limited set of environment variables. By * comparison, sudo strips only LD_LIBRARY_PATH. We are being overly * cautious - intentionally - JDK implementation is very sensitive to * JAVA_HOME in particular, but there are a lot of VM/JDK back door * environment variables. */ static const char *AllowedEnv[] = { "HOSTNAME", "DISPLAY", "HOME", "LANG", "PATH", "LOGNAME", "USER", "TZ" }; extern char **environ; static int IsAllowedEnv(const char *env) { int alsize = sizeof(AllowedEnv) / sizeof(char *); int i; for (i = 0; i < alsize; i++) { int compareLen = strlen(AllowedEnv[i]); if (strncmp(env, AllowedEnv[i], compareLen) == 0) { if (env[compareLen] == '=') { return 1; } } } return 0; } static void StripEnv() { int i, currentEnvSize = 0; char **newEnv, **iter; iter = environ; while (*iter != NULL) { currentEnvSize++; iter++; } /* +1 for terminator NULL */ newEnv = (char **)calloc(currentEnvSize+1, sizeof(*newEnv)); if (newEnv == NULL) { environ = NULL; return; } int newEnvNextLocation = 0; for (i = 0; i < currentEnvSize; i++) { if (IsAllowedEnv(environ[i])) { newEnv[newEnvNextLocation++] = environ[i]; } } environ = newEnv; } #ifndef UNRESTRICTED_JVM_ARGS /* Mailbox server JVM starts as root and then drops priveleges to run * as the zimbra Unix user. Zimbra Unix user is allowed to modify JVM * options. We preclude the Zimbra Unix user from specifying certain * options - code that runs when root must be from files owned by root. */ static const char *DisallowedJVMArgs[] = { "-Djava.class.path", "-Djava.endorsed.dirs", "-Djava.ext.dirs" "-Djava.library.path", "-Dsun.boot.class.path", "-Dsun.boot.library.path", "-Xbootclasspath", "-Xrun", "-agentlib", "-agentpath", "-classpath", "-javaagent", }; #endif static char **newArgv; static int newArgCount = 0; static int newArgCapacity = 0; static int IsAllowedJVMArg(const char *arg) { #ifndef UNRESTRICTED_JVM_ARGS int alsize = sizeof(DisallowedJVMArgs) / sizeof(char *); int i; for (i = 0; i < alsize; i++) { int compareLen = strlen(DisallowedJVMArgs[i]); if (strncmp(arg, DisallowedJVMArgs[i], compareLen) == 0) { return 0; } } return 1; #else return 1; #endif } static void NewArgEnsureCapacity(int thisManyMore) { if (newArgCapacity == 0) { newArgCapacity = 32; newArgv = (char **)malloc(sizeof(*newArgv) * newArgCapacity); } /* the -1 here is so we have room to stick a NULL to terminate newArgv */ if ((newArgCapacity - 1) <= (newArgCount + thisManyMore)) { newArgCapacity = newArgCapacity * 2; newArgv = (char **)realloc(newArgv, sizeof(*newArgv) * newArgCapacity); } } static void AddArg(char *arg) { NewArgEnsureCapacity(1); newArgv[newArgCount++] = arg; newArgv[newArgCount] = NULL; } static void AddArgFmt(const char *fmt, ...) #ifdef __GNUC__ __attribute__((format(printf, 1, 2))) #endif ; extern void syslog(int priority, const char *message, ...) #ifdef __GNUC__ __attribute__((format(printf, 2, 3))) #endif ; static void AddArgFmt(const char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); AddArg(strdup(buf)); } static void ShowNewArgs() { char **e = newArgv; int i = 0; while (*e != NULL) { syslog(LOG_INFO, "mailboxd/JVM arg: [%2d] %s", i, *e); i++; e++; } } static void ShowNewEnv() { char **e = environ; while (*e != NULL) { syslog(LOG_INFO, "mailboxd/JVM env: %s", *e); e++; } } /* * Grace Interval: amount of time in seconds we wait for the * mailboxd/JVM process to respond to SIGTERM before sending a SIGKILL. * Also, after a SIGKILL has been sent (because there was no response * to SIGTERM), if another grace interval has elapsed and the * mailboxd/JVM process has still not shutdown, the manager process * exits after logging a severe error. Default is 60 seconds. */ #define GRACE_INTERVAL_OPTION "--grace-interval=" static int GraceInterval = 60; /* * Double Exit Interval: if they mailboxd/JVM abnormally shuts down * twice in this interval, the manager process does not restart the * mailboxd/JVM again and instead just exits. If there is a fatal * configuration error that causes the mailboxd/JVM to shutdown so * quickly, it does make sense to keep restarting it over and over * again and be a CPU hog. Default is 60 seconds. */ #define DOUBLE_EXIT_INTERVAL_OPTION "--double-exit-interval=" static int DoubleExitInterval = 60; #define VERBOSE_OPTION "--verbose" static int Verbose = 0; /* * Whether the signal received by the manager process was to shutdown * or to bounce the mailboxd/JVM. */ static int ShutdownRequested = 0; static int BounceRequested = 0; /* * The process id of the mailboxd/JVM process. */ static pid_t MailboxdPid = 0; static pid_t GetPidFromFile(const char *pidFile) { FILE *fp = NULL; struct stat sb; pid_t pid; if (stat(pidFile, &sb) < 0) { if (errno == ENOENT) { syslog(LOG_INFO, "file %s does not exist", pidFile); goto NO_INSTANCE; } /* Failed for some other reason: perm denied, etc */ syslog(LOG_ERR, "stat(%s) failed: %s", pidFile, strerror(errno)); exit(1); } if (!S_ISREG(sb.st_mode)) { syslog(LOG_ERR, "%s is not a regular file: %s", pidFile, strerror(errno)); exit(1); } fp = fopen(pidFile, "r"); if (fp == NULL) { syslog(LOG_WARNING, "fopen(%s) failed: %s", pidFile, strerror(errno)); goto NO_INSTANCE; } if (fscanf(fp, "%d", &pid) < 0) { syslog(LOG_WARNING, "did not find a number in %s", pidFile); goto NO_INSTANCE; } if (kill(pid, 0) < 0) { syslog(LOG_INFO, "stale pid %d found in %s: %s", pid, pidFile, strerror(errno)); goto NO_INSTANCE; } /* PID found, and there is an associated process. */ if (fp != NULL) { fclose(fp); } return pid; NO_INSTANCE: if (fp != NULL) { fclose(fp); } syslog(LOG_INFO, "assuming no other instance is running"); return -1; } static pid_t GetPidOfRunningManagerInstance() { pid_t managerPid; managerPid = GetPidFromFile(MAILBOXD_MANAGER_PIDFILE); if (managerPid != -1) { return managerPid; } /* We used to record manager's pid in zmmailboxd.pid. This was unfortunate because the name seems to imply that the pid in that file is the pid of the mailbox/java process. Some customers were tripping over this. We now record the manager's pid in zmmailboxd_manager.pid. While we transition across this file name change, we read the old file name to make sure there are no stale manager processes running. Shouldn't be if there was a proper shutdown at before upgrade. The following lines of code below should eventually be removed */ managerPid = GetPidFromFile(MAILBOXD_MANAGER_DEPRECATED_PIDFILE); return managerPid; } static void RecordPid(const char *which, const char *pidFile, int pidToWrite) { char buf[64]; int pidfd = -1; int len, wrote; /* Reset the mask so the pid file has the exact permissions we say * it should have. */ umask(0); pidfd = creat(pidFile, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (pidfd < 0) { syslog(LOG_ERR, "could not create %s: %s", pidFile, strerror(errno)); exit(1); } len = snprintf(buf, sizeof(buf), "%d\n", pidToWrite); wrote = write(pidfd, buf, len); if (wrote != len) { syslog(LOG_ERR, "wrote only %d of %d to %s: %s", wrote, len, pidFile, strerror(errno)); exit(1); } syslog(LOG_INFO, "wrote %s pid %d to %s", which, pidToWrite, pidFile); close(pidfd); } static void StartMailboxd() { FILE *fp; struct passwd *pw; if ((MailboxdPid = fork()) != 0) { /* In parent process (manager) */ return; } /* In child process (mailboxd/JVM) */ /* For informational purposes only, write the the server pid to a file. Note that this is not authoritative because only the running nanny/manager process knows the true pid of the mailboxd/JVM that is running right now. */ RecordPid("java", MAILBOXD_JAVA_PIDFILE, getpid()); /* It is customary to not inherit umask and to clear the umask completely so applications can set whatever exact permissions it is that they want. However, Java programs can not set permissions for new files, so we default the mask to something reasonable. */ umask(027); /* Redirect mailboxd stdout and stderr to mailboxd.out */ fp = fopen(MAILBOXD_OUTFILE, "a"); if (fp != NULL) { dup2(fileno(fp), fileno(stdout)); dup2(fileno(fp), fileno(stderr)); /* Change mailboxd.out ownership */ pw = getpwnam(ZIMBRA_USER); if (pw) { fchown(fileno(fp), pw->pw_uid, pw->pw_gid); } else { syslog(LOG_WARNING, "can't change ownership of %s: user %s not found: %s", MAILBOXD_OUTFILE, ZIMBRA_USER, strerror(errno)); } fclose(fp); } else { syslog(LOG_WARNING, "opening output file %s failed: %s", MAILBOXD_OUTFILE, strerror(errno)); } fclose(stdin); #ifdef DARWIN { int tfd; setpgrp(0, getpid()); if ((tfd = open("/dev/tty", O_RDWR)) >= 0) { ioctl(tfd, TIOCNOTTY, (char *)0); /* lose control tty */ close(tfd); } } #else setpgrp(); #endif execv(JAVA_BINARY, newArgv); } /* * Try to gracefully stop mailboxd/JVM by sending it a SIGTERM. If that * fails, send it a SIGKILL. If even that fails, then abort the * manager process, something has occurred. */ static void StopMailboxd() { int i = 0; if (kill(MailboxdPid, SIGTERM) < 0) { syslog(LOG_INFO, "mailboxd/JVM process is not running (kill: %s)", strerror(errno)); return; } for (i = 0; i < GraceInterval; i++) { pid_t res; int status; sleep(1); res = waitpid(MailboxdPid, &status, WNOHANG); if (res == -1) { syslog(LOG_INFO, "mailboxd/JVM process not running (waitpid: %s)", strerror(errno)); return; } else if (res > 0) { syslog(LOG_INFO, "mailboxd/JVM process exited (waitpid expected %d got %d)", MailboxdPid, res); return; } /* Loop to wait another second ... */ } syslog(LOG_INFO, "mailboxd/JVM process did not exit after %d seconds, sending SIGKILL", GraceInterval); if (kill(MailboxdPid, SIGKILL) < 0) { syslog(LOG_INFO, "mailboxd/JVM process is not running (kill: %s)", strerror(errno)); return; } for (i = 0; i < GraceInterval; i++) { pid_t res; int status; sleep(1); res = waitpid(MailboxdPid, &status, WNOHANG); if (res == -1) { syslog(LOG_INFO, "mailboxd/JVM process not running (waitpid: %s)", strerror(errno)); return; } else if (res > 0) { syslog(LOG_INFO, "mailboxd/JVM process exited (waitpid expected %d got %d)", MailboxdPid, res); return; } /* Loop and wait another second ... */ } /* Not sure what to do here, even SIGKILL failed. */ syslog(LOG_ERR, "manager exiting: mailboxd/JVM process could not be killed"); exit(1); } static void CheckJavaBinaryExists() { struct stat sb; if (stat(JAVA_BINARY, &sb) < 0) { syslog(LOG_ERR, "stat failed for java binary: %s: %s", JAVA_BINARY, strerror(errno)); exit(1); } if (sb.st_uid == getuid()) { if (!(sb.st_mode & S_IXUSR)) { syslog(LOG_ERR, "java binary is not executable by user: %s", JAVA_BINARY); exit(1); } } else { if (!(sb.st_mode & S_IXOTH)) { syslog(LOG_ERR, "java binary is not executable by other: %s", JAVA_BINARY); exit(1); } } } /* This signal handler shuts down the mailboxd/JVM process. When it * returns the mailboxd/JVM process should not be running. */ static void StopHandler(int signal) { if (signal == SIGTERM) { ShutdownRequested = 1; syslog(LOG_INFO, "shutdown requested, sending TERM signal to %d", MailboxdPid); } else { BounceRequested = 1; syslog(LOG_INFO, "bounce requested, sending TERM signal to %d", MailboxdPid); } StopMailboxd(); } static void ThreadDumpHandler(int signal) { syslog(LOG_INFO, "sending SIQUIT to mailboxd/JVM process %d", MailboxdPid); if (kill(MailboxdPid, SIGQUIT) < 0) { syslog(LOG_INFO, "mailboxd/JVM process is not running (kill: %s)", strerror(errno)); return; } } static void Start(int nextArg, int argc, char *argv[]) { int i; time_t lastExit = 0; pid_t otherInstance; CheckJavaBinaryExists(); syslog(LOG_INFO, "checking if another instance of manager is already running"); otherInstance = GetPidOfRunningManagerInstance(); if (otherInstance != -1) { syslog(LOG_ERR, "another instance of manager is already running (pid=%d)", otherInstance); exit(1); } /* first argument must be name of binary */ AddArg(JAVA_BINARY); for (i = nextArg; i < argc; i++) { if (IsAllowedJVMArg(argv[i])) { AddArg(argv[i]); } else { syslog(LOG_ERR, "JVM option: %s: not allowed\n", argv[i]); exit(1); } } /* REMIND: Do we need this? Seems applicable only when -jar option * is present? * AddArg("-jre-no-restrict-search"); */ AddArgFmt("-Djava.io.tmpdir=%s/work", MAILBOXD_HOME); AddArgFmt("-Djava.library.path=%s", ZIMBRA_LIB); AddArgFmt("-Djava.endorsed.dirs=%s/common/endorsed", MAILBOXD_HOME); AddArgFmt("-Dzimbra.config=%s", ZIMBRA_CONFIG); /* We don't want these things being passed in from command line */ AddArgFmt("-Djetty.home=%s", MAILBOXD_HOME); AddArgFmt("-DSTART=%s/etc/start.config", MAILBOXD_HOME); AddArg("-jar"); AddArgFmt("%s/start.jar", MAILBOXD_HOME); AddArg("OPTIONS=Server,jsp,jmx,resources,websocket,ext,jta,plus,rewrite,setuid"); AddArgFmt("%s/etc/jetty.properties", MAILBOXD_HOME); AddArgFmt("%s/etc/jetty-setuid.xml", MAILBOXD_HOME); AddArgFmt("%s/etc/jetty.xml", MAILBOXD_HOME); if (Verbose) { ShowNewEnv(); ShowNewArgs(); } /* Now daemonize the manager process. */ if (fork() != 0) { exit(0); } /* We are in manager child process. */ setsid(); chdir(MAILBOXD_CWD); /* Note that the PID that is written is the PID of the launcher * process, not that of the JVM. */ RecordPid("manager", MAILBOXD_MANAGER_PIDFILE, getpid()); /* On SIGTERM, we set ShutdownRequested to true. */ signal(SIGTERM, StopHandler); /* On SIGHUP, we go ahead and shutdown mailboxd, but do not set ShutdownRequested to true. */ signal(SIGHUP, StopHandler); /* On SIGQUIT, we forward the SIGQUIT on to the mailboxd/JVM process. */ signal(SIGQUIT, ThreadDumpHandler); while (1) { StartMailboxd(); syslog(LOG_INFO, "manager started mailboxd/JVM with pid %d", MailboxdPid); wait(NULL); syslog(LOG_INFO, "manager woke up from wait on mailboxd/JVM with pid %d", MailboxdPid); if (ShutdownRequested) { unlink(MAILBOXD_MANAGER_PIDFILE); unlink(MAILBOXD_JAVA_PIDFILE); unlink(MAILBOXD_MANAGER_DEPRECATED_PIDFILE); break; } if (BounceRequested) { BounceRequested = 0; lastExit = 0; /* Pretend as though the process has never crashed before, by not setting lastExit. */ continue; } if (lastExit > 0) { time_t now = time(NULL); if ((now - lastExit) < DoubleExitInterval) { syslog(LOG_ERR, "mailboxd/JVM exited twice in %d seconds (tolerance=%d)", (int)(now - lastExit), DoubleExitInterval); exit(1); } /* Any subsequent time child crashed ... */ lastExit = now; } else { /* First time child crashed... */ lastExit = time(NULL); } } } static void Usage(const char *progname) { syslog(LOG_ERR, "Incorrect arguments. Usage: %s [%sseconds] [%sseconds] [%s] { start | stop | restart | status | threaddump } [allowed JVM options ... ] ", progname, DOUBLE_EXIT_INTERVAL_OPTION, GRACE_INTERVAL_OPTION, VERBOSE_OPTION); exit(1); } static void Stop() { int i; pid_t managerPid; managerPid = GetPidOfRunningManagerInstance(); if (managerPid == -1) { syslog(LOG_ERR, "no manager process is running"); exit(1); } if (kill(managerPid, SIGTERM) < 0) { syslog(LOG_ERR, "could not send SIGTERM to manager process (pid=%d): %s", managerPid, strerror(errno)); exit(1); } syslog(LOG_INFO, "waiting for manager process %d to die", managerPid); for (i = 0; i < GraceInterval; i++) { sleep(1); if (kill(managerPid, 0) < 0) { syslog(LOG_INFO, "manager process %d died, shutdown completed", managerPid); return; } } syslog(LOG_ERR, "manager process %d could not died in %d seconds", managerPid, GraceInterval); } static void Restart() { pid_t managerPid = GetPidOfRunningManagerInstance(); if (managerPid == -1) { syslog(LOG_ERR, "no manager process is running"); exit(1); } if (kill(managerPid, SIGHUP) < 0) { syslog(LOG_ERR, "could not send SIGHUP to manager process (pid=%d): %s", managerPid, strerror(errno)); exit(1); } } /* Exit 0 or 1 based on whether manager is running */ static void Status() { pid_t managerPid = GetPidOfRunningManagerInstance(); if (managerPid == -1) { syslog(LOG_ERR, "no manager process is running"); exit(1); } if (kill(managerPid, 0) < 0) { syslog(LOG_ERR, "could not send signal 0 to manager process (pid=%d): %s", managerPid, strerror(errno)); exit(1); } /* syslog(LOG_DEBUG, "status OK"); */ exit(0); } static void ThreadDump() { pid_t managerPid = GetPidOfRunningManagerInstance(); if (managerPid == -1) { syslog(LOG_ERR, "no manager process is running"); exit(1); } if (kill(managerPid, SIGQUIT) < 0) { syslog(LOG_ERR, "could not send SIGQUIT to manager process (pid=%d): %s", managerPid, strerror(errno)); exit(1); } } int main(int argc, char *argv[]) { int nextArg; const char *progname; const char *action; progname = (argc > 0 && argv[0] != NULL) ? argv[0] : "mailboxdmgr"; if (strrchr(progname, '/') > 0) { progname = strrchr(progname, '/') + 1; if (*progname == '\0') { progname = "mailboxdmgr"; } } openlog(progname, LOG_PID, LOG_MAIL); StripEnv(); /* TODO: warn if files are not owned by root */ nextArg = 1; action = NULL; while (nextArg < argc) { if (strncmp(argv[nextArg], DOUBLE_EXIT_INTERVAL_OPTION, sizeof(DOUBLE_EXIT_INTERVAL_OPTION)) == 0) { char *value = argv[nextArg] + sizeof(DOUBLE_EXIT_INTERVAL_OPTION); DoubleExitInterval = atoi(value); if (DoubleExitInterval < 1) { Usage(progname); } } else if (strncmp(argv[nextArg], GRACE_INTERVAL_OPTION, sizeof(GRACE_INTERVAL_OPTION)) == 0) { char *value = argv[nextArg] + sizeof(GRACE_INTERVAL_OPTION); GraceInterval = atoi(value); if (GraceInterval < 1) { Usage(progname); } } else if (strcmp(argv[nextArg], VERBOSE_OPTION) == 0) { Verbose = 1; } else { action = argv[nextArg++]; break; } nextArg++; } if (action == NULL) { Usage(progname); } if (access("zmmailboxdmgr.verbose", F_OK) == 0) { Verbose = 1; } if (strcmp(action, "start") == 0) { syslog(LOG_INFO, "start requested"); Start(nextArg, argc, argv); } else if (strcmp(action, "stop") == 0) { syslog(LOG_INFO, "stop requested"); Stop(); } else if (strcmp(action, "restart") == 0) { syslog(LOG_INFO, "restart requested"); Restart(); } else if (strcmp(action, "status") == 0) { /* syslog(LOG_DEBUG, "status requested"); */ Status(); } else if (strcmp(action, "threaddump") == 0) { syslog(LOG_INFO, "threaddump requested"); ThreadDump(); } else { syslog(LOG_ERR, "unknown action %s requested", action); exit(1); } return 0; }
519246.c
/** * Unit tests for the @em next and @em next_n algorithms. */ #include <nstl/algorithm/next.h> #include <seatest.h> #define Traits (self_type nstl_pint) \ (diff_traits (self_type nstl_ptrdiff_t)) \ (traversal_category nstl_random_access_traversal_tag) NSTL_INSTANTIATE(NSTL_NEXT(Traits)) NSTL_INSTANTIATE(NSTL_NEXT_N(Traits)) #define next nstl_next(nstl_pint) #define next_n nstl_next_n(nstl_pint) static void test_should_return_iterator_to_next(void) { nstl_int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; nstl_pint iter = array; assert_true(next(iter) == next_n(iter, 1)); assert_true(next(iter) == array + 1); } static void test_should_return_iterator_to_nth_next(void) { nstl_int array[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; nstl_pint iter = array; assert_true(next_n(iter, 5) == array + 5); } #undef next_n #undef next extern void test_fixture_next(void) { test_fixture_start(); run_test(test_should_return_iterator_to_next); run_test(test_should_return_iterator_to_nth_next); test_fixture_end(); }
437575.c
#include<stdio.h> #include<math.h> #include<stdlib.h> #include "campovski.h" // needed for int_to_arr function char is_palindrome(int n); int main() { int largest = 100; // 10000 = 100 * 100 for (int x = 10; x <= 99; x++) { for (int y = x; y <= 99; y++) { if (is_palindrome(x*y) && x * y >= largest) largest = x * y; } } printf("%d\n", largest); return 0; } char is_palindrome(int n) { char* n_arr = int_to_arr(n); int l = floor(log10(abs(n))) + 1; for (int i = 0; i < (int) l/2; i++) { if (n_arr[i] != n_arr[l-i-1]) return 0; } return 1; }
410233.c
/* * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) * From ASN.1 module "X2AP-PDU" * found in "/home/liu/openairinterface5g/openair2/X2AP/MESSAGES/ASN1/R11.2/X2AP-PDU.asn" * `asn1c -gen-PER` */ #include "X2ap-InitiatingMessage.h" static asn_TYPE_member_t asn_MBR_X2ap_InitiatingMessage_1[] = { { ATF_NOFLAGS, 0, offsetof(struct X2ap_InitiatingMessage, procedureCode), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_X2ap_ProcedureCode, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "procedureCode" }, { ATF_NOFLAGS, 0, offsetof(struct X2ap_InitiatingMessage, criticality), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_X2ap_Criticality, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "criticality" }, { ATF_NOFLAGS, 0, offsetof(struct X2ap_InitiatingMessage, value), (ASN_TAG_CLASS_CONTEXT | (2 << 2)), +1, /* EXPLICIT tag at current level */ &asn_DEF_ANY, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "value" }, }; static ber_tlv_tag_t asn_DEF_X2ap_InitiatingMessage_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_TYPE_tag2member_t asn_MAP_X2ap_InitiatingMessage_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* procedureCode at 37 */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* criticality at 38 */ { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* value at 40 */ }; static asn_SEQUENCE_specifics_t asn_SPC_X2ap_InitiatingMessage_specs_1 = { sizeof(struct X2ap_InitiatingMessage), offsetof(struct X2ap_InitiatingMessage, _asn_ctx), asn_MAP_X2ap_InitiatingMessage_tag2el_1, 3, /* Count of tags in the map */ 0, 0, 0, /* Optional elements (not needed) */ -1, /* Start extensions */ -1 /* Stop extensions */ }; asn_TYPE_descriptor_t asn_DEF_X2ap_InitiatingMessage = { "X2ap-InitiatingMessage", "X2ap-InitiatingMessage", SEQUENCE_free, SEQUENCE_print, SEQUENCE_constraint, SEQUENCE_decode_ber, SEQUENCE_encode_der, SEQUENCE_decode_xer, SEQUENCE_encode_xer, SEQUENCE_decode_uper, SEQUENCE_encode_uper, SEQUENCE_decode_aper, SEQUENCE_encode_aper, SEQUENCE_compare, 0, /* Use generic outmost tag fetcher */ asn_DEF_X2ap_InitiatingMessage_tags_1, sizeof(asn_DEF_X2ap_InitiatingMessage_tags_1) /sizeof(asn_DEF_X2ap_InitiatingMessage_tags_1[0]), /* 1 */ asn_DEF_X2ap_InitiatingMessage_tags_1, /* Same as above */ sizeof(asn_DEF_X2ap_InitiatingMessage_tags_1) /sizeof(asn_DEF_X2ap_InitiatingMessage_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ asn_MBR_X2ap_InitiatingMessage_1, 3, /* Elements count */ &asn_SPC_X2ap_InitiatingMessage_specs_1 /* Additional specs */ };
964085.c
/* matriz.c Autor: Orlando Enrico Liz Silvério Silva */ #include <stdio.h> #include <stdlib.h> #include "matriz.h" // Aloca a matriz. Size é definido na struct pra poder percorrer // a matriz de forma direta, sem a necessidade de parâmetros adicionais void criaMatriz(Matriz *matrix, int n) { matrix->n = n; matrix->mat = (int**) calloc(matrix->n, sizeof(int*)); int i; for (i = 0; i < matrix->n; i++) { matrix->mat[i] = (int*) calloc(matrix->n, sizeof(int)); } } // Libera a memória alocada para a matriz (Perceba a utilização de "size" aqui) void liberaMatriz(Matriz *matrix) { int i; for (i = 0; i < matrix->n; i++) { free(matrix->mat[i]); } free(matrix->mat); }
650061.c
/*--------------------------------------------------------------------*/ /*--- Client-space code for DRD. drd_pthread_intercepts.c ---*/ /*--------------------------------------------------------------------*/ /* This file is part of DRD, a thread error detector. Copyright (C) 2006-2015 Bart Van Assche <[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. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. The GNU General Public License is contained in the file COPYING. */ /* --------------------------------------------------------------------- ALL THE CODE IN THIS FILE RUNS ON THE SIMULATED CPU. These functions are not called directly - they're the targets of code redirection or load notifications (see pub_core_redir.h for info). They're named weirdly so that the intercept code can find them when the shared object is initially loaded. Note that this filename has the "drd_" prefix because it can appear in stack traces, and the "drd_" makes it a little clearer that it originates from Valgrind. ------------------------------------------------------------------ */ /* * Define _GNU_SOURCE to make sure that pthread_spinlock_t is available when * compiling with older glibc versions (2.3 or before). */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <assert.h> /* assert() */ #include <errno.h> #include <pthread.h> /* pthread_mutex_t */ #include <semaphore.h> /* sem_t */ #include <stdint.h> /* uintptr_t */ #include <stdio.h> /* fprintf() */ #include <stdlib.h> /* malloc(), free() */ #include <unistd.h> /* confstr() */ #include "config.h" /* HAVE_PTHREAD_MUTEX_ADAPTIVE_NP etc. */ #ifdef HAVE_USABLE_LINUX_FUTEX_H #include <asm/unistd.h> /* __NR_futex */ #include <linux/futex.h> /* FUTEX_WAIT */ #ifndef FUTEX_PRIVATE_FLAG #define FUTEX_PRIVATE_FLAG 0 #endif #endif #include "drd_basics.h" /* DRD_() */ #include "drd_clientreq.h" #include "pub_tool_redir.h" /* VG_WRAP_FUNCTION_ZZ() */ #if defined(VGO_solaris) /* * Solaris usually provides pthread_* functions on top of Solaris threading * and synchronization functions. Usually both need to be intercepted because * pthread_* ones might not call the Solaris ones (see for example sem_wait()). * Such approach is required to correctly report misuse of the POSIX threads * API. * Therefore DRD intercepts and instruments all such functions but due to * DRD_(thread_enter_synchr)() and DRD_(thread_leave_synchr)() guards in * handle_client_request(), only the top-most function is handled. * So the right thing(TM) happens, as expected. * The only exception is when pthread_* function is a weak alias to the Solaris * threading/synchronization function. In such case only one needs to be * intercepted to avoid redirection ambiguity. * * Intercepted functions rely on the fact that: * - pthread_mutex_t == mutex_t * - pthread_cond_t == cond_t * - sem_t == sema_t * - pthread_rwlock_t == rwlock_t * * It is necessary to intercept also internal libc synchronization functions * for two reasons: * - For read-write locks the unlocking function is shared * - Functions lmutex_lock/lmutex_unlock guard many critical sections in libc * which will be otherwise reported by DRD */ #include <synch.h> #include <thread.h> #include "pub_tool_vki.h" /* * Solaris provides higher throughput, parallelism and scalability than other * operating systems, at the cost of more fine-grained locking activity. * This means for example that when a thread is created under Linux, just one * big lock in glibc is used for all thread setup. Solaris libc uses several * fine-grained locks and the creator thread resumes its activities as soon * as possible, leaving for example stack and TLS setup activities to the * created thread. * * This situation confuses DRD as it assumes there is some false ordering * in place between creator and created thread; and therefore many types of * race conditions in the application would not be reported. To prevent such * false ordering, command line option --ignore-thread-creation is set to * 'yes' by default on Solaris. All activity (loads, stores, client requests) * is therefore ignored during: * - pthread_create() call in the creator thread [libc.so] * - thread creation phase (stack and TLS setup) in the created thread [libc.so] * * As explained in the comments for _ti_bind_guard(), whenever the runtime * linker has to perform any activity (such as resolving a symbol), it protects * its data structures by calling into rt_bind_guard() which in turn invokes * _ti_bind_guard() in libc. Pointers to _ti_bind_guard() and _ti_bind_clear() * are passed from libc to runtime linker in _ld_libc() call during libc_init(). * All activity is also ignored during: * - runtime dynamic linker work between rt_bind_guard() and rt_bind_clear() * calls [ld.so] * * This also means that DRD does not report race conditions in libc (when * --ignore-thread-creation=yes) and runtime linker itself (unconditionally) * during these ignored sequences. */ /* * Original function pointers for _ti_bind_guard() and _ti_bind_clear() * from libc. They are intercepted in function wrapper of _ld_libc(). */ typedef int (*drd_rtld_guard_fn)(int flags); static drd_rtld_guard_fn DRD_(rtld_bind_guard) = NULL; static drd_rtld_guard_fn DRD_(rtld_bind_clear) = NULL; #endif /* * Notes regarding thread creation: * - sg_init() runs on the context of the created thread and copies the vector * clock of the creator thread. This only works reliably if the creator * thread waits until this copy has been performed. * - DRD_(thread_compute_minimum_vc)() does not take the vector clocks into * account that are involved in thread creation and for which the * corresponding thread has not yet been created. So not waiting until the * created thread has been started would make it possible that segments get * discarded that should not yet be discarded. Or: some data races are not * detected. */ /** * Macro for generating a Valgrind interception function. * @param[in] ret_ty Return type of the function to be generated. * @param[in] zf Z-encoded name of the interception function. * @param[in] implf Name of the function that implements the intercept. * @param[in] arg_decl Argument declaration list enclosed in parentheses. * @param[in] argl Argument list enclosed in parentheses. */ #ifdef VGO_darwin static int never_true; #define PTH_FUNC(ret_ty, zf, implf, argl_decl, argl) \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBPTHREAD_SONAME,zf) argl_decl; \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBPTHREAD_SONAME,zf) argl_decl \ { \ ret_ty pth_func_result = implf argl; \ /* Apparently inserting a function call in wrapper functions */ \ /* is sufficient to avoid misaligned stack errors. */ \ if (never_true) \ fflush(stdout); \ return pth_func_result; \ } #elif defined(VGO_solaris) /* On Solaris, libpthread is just a filter library on top of libc. * Threading and synchronization functions in runtime linker are not * intercepted. */ #define PTH_FUNC(ret_ty, zf, implf, argl_decl, argl) \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBC_SONAME,zf) argl_decl; \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBC_SONAME,zf) argl_decl \ { return implf argl; } #else #define PTH_FUNC(ret_ty, zf, implf, argl_decl, argl) \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBPTHREAD_SONAME,zf) argl_decl; \ ret_ty VG_WRAP_FUNCTION_ZZ(VG_Z_LIBPTHREAD_SONAME,zf) argl_decl \ { return implf argl; } #endif /** * Macro for generating three Valgrind interception functions: one with the * Z-encoded name zf, one with ZAZa ("@*") appended to the name zf and one * with ZDZa ("$*") appended to the name zf. The second generated interception * function will intercept versioned symbols on Linux, and the third will * intercept versioned symbols on Darwin. */ #define PTH_FUNCS(ret_ty, zf, implf, argl_decl, argl) \ PTH_FUNC(ret_ty, zf, implf, argl_decl, argl); \ PTH_FUNC(ret_ty, zf ## ZAZa, implf, argl_decl, argl); \ PTH_FUNC(ret_ty, zf ## ZDZa, implf, argl_decl, argl); /* * Not inlining one of the intercept functions will cause the regression * tests to fail because this would cause an additional stackfram to appear * in the output. The __always_inline macro guarantees that inlining will * happen, even when compiling with optimization disabled. */ #undef __always_inline /* since already defined in <cdefs.h> */ #if __GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 2 #define __always_inline __inline__ __attribute__((always_inline)) #else #define __always_inline __inline__ #endif /* Local data structures. */ typedef struct { pthread_mutex_t mutex; int counter; int waiters; } DrdSema; typedef struct { void* (*start)(void*); void* arg; int detachstate; DrdSema* wrapper_started; } DrdPosixThreadArgs; /* Local function declarations. */ static void DRD_(init)(void) __attribute__((constructor)); static void DRD_(check_threading_library)(void); static void DRD_(set_main_thread_state)(void); static void DRD_(sema_init)(DrdSema* sema); static void DRD_(sema_destroy)(DrdSema* sema); static void DRD_(sema_down)(DrdSema* sema); static void DRD_(sema_up)(DrdSema* sema); /* Function definitions. */ /** * Shared library initialization function. The function init() is called after * dlopen() has loaded the shared library with DRD client intercepts because * the constructor attribute was specified in the declaration of this function. * Note: do specify the -nostdlib option to gcc when linking this code into a * shared library because doing so would cancel the effect of the constructor * attribute ! Using the gcc option -nodefaultlibs is fine because this last * option preserves the shared library initialization code that calls * constructor and destructor functions. */ static void DRD_(init)(void) { DRD_(check_threading_library)(); DRD_(set_main_thread_state)(); #if defined(VGO_solaris) if ((DRD_(rtld_bind_guard) == NULL) || (DRD_(rtld_bind_clear) == NULL)) { fprintf(stderr, "Bind guard functions for the runtime linker (ld.so.1) were not intercepted.\n" "This means the interface between libc and runtime linker changed and DRD\n" "needs to be ported properly. Giving up.\n"); abort(); } #endif } static __always_inline void DRD_(ignore_mutex_ordering)(pthread_mutex_t *mutex) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DRD_IGNORE_MUTEX_ORDERING, mutex, 0, 0, 0, 0); } static void DRD_(sema_init)(DrdSema* sema) { DRD_IGNORE_VAR(*sema); pthread_mutex_init(&sema->mutex, NULL); DRD_(ignore_mutex_ordering)(&sema->mutex); sema->counter = 0; sema->waiters = 0; } static void DRD_(sema_destroy)(DrdSema* sema) { pthread_mutex_destroy(&sema->mutex); } static void DRD_(sema_down)(DrdSema* sema) { int res = ENOSYS; pthread_mutex_lock(&sema->mutex); if (sema->counter == 0) { sema->waiters++; while (sema->counter == 0) { pthread_mutex_unlock(&sema->mutex); #ifdef HAVE_USABLE_LINUX_FUTEX_H if (syscall(__NR_futex, (UWord)&sema->counter, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, 0) == 0) res = 0; else res = errno; #endif /* * Invoke sched_yield() on non-Linux systems, if the futex syscall has * not been invoked or if this code has been built on a Linux system * where __NR_futex is defined and is run on a Linux system that does * not support the futex syscall. */ if (res != 0 && res != EWOULDBLOCK) sched_yield(); pthread_mutex_lock(&sema->mutex); } sema->waiters--; } sema->counter--; pthread_mutex_unlock(&sema->mutex); } static void DRD_(sema_up)(DrdSema* sema) { pthread_mutex_lock(&sema->mutex); sema->counter++; #ifdef HAVE_USABLE_LINUX_FUTEX_H if (sema->waiters > 0) syscall(__NR_futex, (UWord)&sema->counter, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, 1); #endif pthread_mutex_unlock(&sema->mutex); } /** * POSIX threads and DRD each have their own mutex type identification. * Convert POSIX threads' mutex type to DRD's mutex type. In the code below * if-statements are used to test the value of 'kind' instead of a switch * statement because some of the PTHREAD_MUTEX_ macro's may have the same * value. */ static MutexT DRD_(pthread_to_drd_mutex_type)(int kind) { /* * See also PTHREAD_MUTEX_KIND_MASK_NP in glibc source file * <nptl/pthreadP.h>. */ kind &= PTHREAD_MUTEX_RECURSIVE | PTHREAD_MUTEX_ERRORCHECK | PTHREAD_MUTEX_NORMAL | PTHREAD_MUTEX_DEFAULT; if (kind == PTHREAD_MUTEX_RECURSIVE) return mutex_type_recursive_mutex; else if (kind == PTHREAD_MUTEX_ERRORCHECK) return mutex_type_errorcheck_mutex; else if (kind == PTHREAD_MUTEX_NORMAL) return mutex_type_default_mutex; else if (kind == PTHREAD_MUTEX_DEFAULT) return mutex_type_default_mutex; #if defined(HAVE_PTHREAD_MUTEX_ADAPTIVE_NP) else if (kind == PTHREAD_MUTEX_ADAPTIVE_NP) return mutex_type_default_mutex; #endif else return mutex_type_invalid_mutex; } #if defined(VGO_solaris) /** * Solaris threads and DRD each have their own mutex type identification. * Convert Solaris threads' mutex type to DRD's mutex type. */ static MutexT DRD_(thread_to_drd_mutex_type)(int type) { if (type & LOCK_RECURSIVE) { return mutex_type_recursive_mutex; } else if (type & LOCK_ERRORCHECK) { return mutex_type_errorcheck_mutex; } else { return mutex_type_default_mutex; } } #endif /* VGO_solaris */ #define IS_ALIGNED(p) (((uintptr_t)(p) & (sizeof(*(p)) - 1)) == 0) /** * Read the mutex type stored in the client memory used for the mutex * implementation. * * @note This function depends on the implementation of the POSIX threads * library -- the POSIX standard does not define the name of the member in * which the mutex type is stored. * @note The function mutex_type() has been declared inline in order * to avoid that it shows up in call stacks (drd/tests/...exp* files). * @note glibc stores the mutex type in the lowest two bits, and uses the * higher bits for flags like PTHREAD_MUTEXATTR_FLAG_ROBUST and * PTHREAD_MUTEXATTR_FLAG_PSHARED. */ static __always_inline MutexT DRD_(mutex_type)(pthread_mutex_t* mutex) { #if defined(HAVE_PTHREAD_MUTEX_T__M_KIND) /* glibc + LinuxThreads. */ if (IS_ALIGNED(&mutex->__m_kind)) { const int kind = mutex->__m_kind & 3; return DRD_(pthread_to_drd_mutex_type)(kind); } #elif defined(HAVE_PTHREAD_MUTEX_T__DATA__KIND) /* glibc + NPTL. */ if (IS_ALIGNED(&mutex->__data.__kind)) { const int kind = mutex->__data.__kind & 3; return DRD_(pthread_to_drd_mutex_type)(kind); } #elif defined(VGO_solaris) const int type = ((mutex_t *) mutex)->vki_mutex_type; return DRD_(thread_to_drd_mutex_type)(type); #else /* * Another POSIX threads implementation. The mutex type won't be printed * when enabling --trace-mutex=yes. */ #endif return mutex_type_unknown; } /** * Tell DRD whether 'tid' is a joinable thread or a detached thread. */ static void DRD_(set_joinable)(const pthread_t tid, const int joinable) { assert(joinable == 0 || joinable == 1); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__SET_JOINABLE, tid, joinable, 0, 0, 0); } /** Tell DRD that the calling thread is about to enter pthread_create(). */ static __always_inline void DRD_(entering_pthread_create)(void) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__ENTERING_PTHREAD_CREATE, 0, 0, 0, 0, 0); } /** Tell DRD that the calling thread has left pthread_create(). */ static __always_inline void DRD_(left_pthread_create)(void) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__LEFT_PTHREAD_CREATE, 0, 0, 0, 0, 0); } /** * Entry point for newly created threads. This function is called from the * thread created by pthread_create(). */ static void* DRD_(thread_wrapper)(void* arg) { DrdPosixThreadArgs* arg_ptr; DrdPosixThreadArgs arg_copy; arg_ptr = (DrdPosixThreadArgs*)arg; arg_copy = *arg_ptr; VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__SET_PTHREADID, pthread_self(), 0, 0, 0, 0); DRD_(set_joinable)(pthread_self(), arg_copy.detachstate == PTHREAD_CREATE_JOINABLE); /* * Only set 'wrapper_started' after VG_USERREQ__SET_PTHREADID and * DRD_(set_joinable)() have been invoked to avoid a race with * a pthread_detach() invocation for this thread from another thread. */ DRD_(sema_up)(arg_copy.wrapper_started); return (arg_copy.start)(arg_copy.arg); } /** * Return 1 if the LinuxThreads implementation of POSIX Threads has been * detected, and 0 otherwise. * * @see For more information about the confstr() function, see also * http://www.opengroup.org/onlinepubs/009695399/functions/confstr.html */ static int DRD_(detected_linuxthreads)(void) { #if defined(linux) #if defined(_CS_GNU_LIBPTHREAD_VERSION) /* Linux with a recent glibc. */ HChar buffer[256]; unsigned len; len = confstr(_CS_GNU_LIBPTHREAD_VERSION, buffer, sizeof(buffer)); assert(len <= sizeof(buffer)); return len > 0 && buffer[0] == 'l'; #else /* Linux without _CS_GNU_LIBPTHREAD_VERSION: most likely LinuxThreads. */ return 1; #endif #else /* Another OS than Linux, hence no LinuxThreads. */ return 0; #endif } /** * Stop and print an error message in case a non-supported threading * library implementation (LinuxThreads) has been detected. */ static void DRD_(check_threading_library)(void) { if (DRD_(detected_linuxthreads)()) { if (getenv("LD_ASSUME_KERNEL")) { fprintf(stderr, "Detected the LinuxThreads threading library. Sorry, but DRD only supports\n" "the newer NPTL (Native POSIX Threads Library). Please try to rerun DRD\n" "after having unset the environment variable LD_ASSUME_KERNEL. Giving up.\n" ); } else { fprintf(stderr, "Detected the LinuxThreads threading library. Sorry, but DRD only supports\n" "the newer NPTL (Native POSIX Threads Library). Please try to rerun DRD\n" "after having upgraded to a newer version of your Linux distribution.\n" "Giving up.\n" ); } abort(); } } /** * The main thread is the only thread not created by pthread_create(). * Update DRD's state information about the main thread. */ static void DRD_(set_main_thread_state)(void) { // Make sure that DRD knows about the main thread's POSIX thread ID. VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__SET_PTHREADID, pthread_self(), 0, 0, 0, 0); } /* * Note: as of today there exist three different versions of pthread_create * in Linux: * - pthread_create@GLIBC_2.0 * - pthread_create@@GLIBC_2.1 * - pthread_create@@GLIBC_2.2.5 * As an example, in libpthread-2.3.4 both pthread_create@GLIBC_2.0 and * pthread_create@@GLIBC_2.1 are defined, while in libpthread-2.9 all three * versions have been implemented. In any glibc version where more than one * pthread_create function has been implemented, older versions call the * newer versions. Or: the pthread_create* wrapper defined below can be * called recursively. Any code in this wrapper should take this in account. * As an example, it is not safe to invoke the DRD_STOP_RECORDING * / DRD_START_RECORDING client requests from the pthread_create wrapper. * See also the implementation of pthread_create@GLIBC_2.0 in * glibc-2.9/nptl/pthread_create.c. */ static __always_inline int pthread_create_intercept(pthread_t* thread, const pthread_attr_t* attr, void* (*start)(void*), void* arg) { int ret; OrigFn fn; DrdSema wrapper_started; DrdPosixThreadArgs thread_args; VALGRIND_GET_ORIG_FN(fn); DRD_(sema_init)(&wrapper_started); thread_args.start = start; thread_args.arg = arg; thread_args.wrapper_started = &wrapper_started; /* * Find out whether the thread will be started as a joinable thread * or as a detached thread. If no thread attributes have been specified, * this means that the new thread will be started as a joinable thread. */ thread_args.detachstate = PTHREAD_CREATE_JOINABLE; if (attr) { if (pthread_attr_getdetachstate(attr, &thread_args.detachstate) != 0) assert(0); } assert(thread_args.detachstate == PTHREAD_CREATE_JOINABLE || thread_args.detachstate == PTHREAD_CREATE_DETACHED); DRD_(entering_pthread_create)(); CALL_FN_W_WWWW(ret, fn, thread, attr, DRD_(thread_wrapper), &thread_args); DRD_(left_pthread_create)(); if (ret == 0) { /* Wait until the thread wrapper started. */ DRD_(sema_down)(&wrapper_started); } DRD_(sema_destroy)(&wrapper_started); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DRD_START_NEW_SEGMENT, pthread_self(), 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZucreate, pthread_create_intercept, (pthread_t *thread, const pthread_attr_t *attr, void *(*start) (void *), void *arg), (thread, attr, start, arg)); #if defined(VGO_solaris) /* Solaris also provides thr_create() in addition to pthread_create(). * Both pthread_create(3C) and thr_create(3C) are based on private * _thrp_create(). */ static __always_inline int thr_create_intercept(void *stk, size_t stksize, void *(*start)(void *), void *arg, long flags, thread_t *new_thread) { int ret; OrigFn fn; DrdSema wrapper_started; DrdPosixThreadArgs thread_args; VALGRIND_GET_ORIG_FN(fn); DRD_(sema_init)(&wrapper_started); thread_args.start = start; thread_args.arg = arg; thread_args.wrapper_started = &wrapper_started; /* * Find out whether the thread will be started as a joinable thread * or as a detached thread. */ if (flags & THR_DETACHED) thread_args.detachstate = PTHREAD_CREATE_DETACHED; else thread_args.detachstate = PTHREAD_CREATE_JOINABLE; DRD_(entering_pthread_create)(); CALL_FN_W_6W(ret, fn, stk, stksize, DRD_(thread_wrapper), &thread_args, flags, new_thread); DRD_(left_pthread_create)(); if (ret == 0) { /* Wait until the thread wrapper started. */ DRD_(sema_down)(&wrapper_started); } DRD_(sema_destroy)(&wrapper_started); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__DRD_START_NEW_SEGMENT, pthread_self(), 0, 0, 0, 0); return ret; } PTH_FUNCS(int, thrZucreate, thr_create_intercept, (void *stk, size_t stksize, void *(*start)(void *), void *arg, long flags, thread_t *new_thread), (stk, stksize, start, arg, flags, new_thread)); #endif /* VGO_solaris */ #if defined(VGO_solaris) /* * Intercepts for _ti_bind_guard() and _ti_bind_clear() functions from libc. * These are intercepted during _ld_libc() call by identifying CI_BIND_GUARD * and CI_BIND_CLEAR, to provide resilience against function renaming. */ static __always_inline int DRD_(_ti_bind_guard_intercept)(int flags) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__RTLD_BIND_GUARD, flags, 0, 0, 0, 0); return DRD_(rtld_bind_guard)(flags); } static __always_inline int DRD_(_ti_bind_clear_intercept)(int flags) { int ret = DRD_(rtld_bind_clear)(flags); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__RTLD_BIND_CLEAR, flags, 0, 0, 0, 0); return ret; } /* * Wrapped _ld_libc() from the runtime linker ld.so.1. */ void VG_WRAP_FUNCTION_ZZ(VG_Z_LD_SO_1, ZuldZulibc)(vki_Lc_interface *ptr); void VG_WRAP_FUNCTION_ZZ(VG_Z_LD_SO_1, ZuldZulibc)(vki_Lc_interface *ptr) { OrigFn fn; int tag; VALGRIND_GET_ORIG_FN(fn); vki_Lc_interface *funcs = ptr; for (tag = funcs->ci_tag; tag != 0; tag = (++funcs)->ci_tag) { switch (tag) { case VKI_CI_BIND_GUARD: if (funcs->vki_ci_un.ci_func != DRD_(_ti_bind_guard_intercept)) { DRD_(rtld_bind_guard) = funcs->vki_ci_un.ci_func; funcs->vki_ci_un.ci_func = DRD_(_ti_bind_guard_intercept); } break; case VKI_CI_BIND_CLEAR: if (funcs->vki_ci_un.ci_func != DRD_(_ti_bind_clear_intercept)) { DRD_(rtld_bind_clear) = funcs->vki_ci_un.ci_func; funcs->vki_ci_un.ci_func = DRD_(_ti_bind_clear_intercept); } break; } } CALL_FN_v_W(fn, ptr); } #endif /* VGO_solaris */ static __always_inline int pthread_join_intercept(pthread_t pt_joinee, void **thread_return) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); /* * Avoid that the sys_futex(td->tid) call invoked by the NPTL pthread_join() * implementation triggers a (false positive) race report. */ ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN(); CALL_FN_W_WW(ret, fn, pt_joinee, thread_return); if (ret == 0) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_THREAD_JOIN, pt_joinee, 0, 0, 0, 0); } ANNOTATE_IGNORE_READS_AND_WRITES_END(); return ret; } PTH_FUNCS(int, pthreadZujoin, pthread_join_intercept, (pthread_t pt_joinee, void **thread_return), (pt_joinee, thread_return)); #if defined(VGO_solaris) /* Solaris also provides thr_join() in addition to pthread_join(). * Both pthread_join(3C) and thr_join(3C) are based on private _thrp_join(). * * :TODO: No functionality is currently provided for joinee == 0 and departed. * This would require another client request, of course. */ static __always_inline int thr_join_intercept(thread_t joinee, thread_t *departed, void **thread_return) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); CALL_FN_W_WWW(ret, fn, joinee, departed, thread_return); if (ret == 0) { VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_THREAD_JOIN, joinee, 0, 0, 0, 0); } return ret; } PTH_FUNCS(int, thrZujoin, thr_join_intercept, (thread_t joinee, thread_t *departed, void **thread_return), (joinee, departed, thread_return)); #endif /* VGO_solaris */ static __always_inline int pthread_detach_intercept(pthread_t pt_thread) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); CALL_FN_W_W(ret, fn, pt_thread); DRD_(set_joinable)(pt_thread, 0); return ret; } PTH_FUNCS(int, pthreadZudetach, pthread_detach_intercept, (pthread_t thread), (thread)); // NOTE: be careful to intercept only pthread_cancel() and not // pthread_cancel_init() on Linux. static __always_inline int pthread_cancel_intercept(pthread_t pt_thread) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_THREAD_CANCEL, pt_thread, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, pt_thread); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_THREAD_CANCEL, pt_thread, ret==0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZucancel, pthread_cancel_intercept, (pthread_t thread), (thread)) static __always_inline int pthread_once_intercept(pthread_once_t *once_control, void (*init_routine)(void)) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); /* * Ignore any data races triggered by the implementation of pthread_once(). * Necessary for Darwin. This is not necessary for Linux but doesn't have * any known adverse effects. */ DRD_IGNORE_VAR(*once_control); ANNOTATE_IGNORE_READS_AND_WRITES_BEGIN(); CALL_FN_W_WW(ret, fn, once_control, init_routine); ANNOTATE_IGNORE_READS_AND_WRITES_END(); DRD_STOP_IGNORING_VAR(*once_control); return ret; } PTH_FUNCS(int, pthreadZuonce, pthread_once_intercept, (pthread_once_t *once_control, void (*init_routine)(void)), (once_control, init_routine)); static __always_inline int pthread_mutex_init_intercept(pthread_mutex_t *mutex, const pthread_mutexattr_t* attr) { int ret; OrigFn fn; int mt; VALGRIND_GET_ORIG_FN(fn); mt = PTHREAD_MUTEX_DEFAULT; if (attr) pthread_mutexattr_gettype(attr, &mt); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_INIT, mutex, DRD_(pthread_to_drd_mutex_type)(mt), 0, 0, 0); CALL_FN_W_WW(ret, fn, mutex, attr); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_INIT, mutex, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZumutexZuinit, pthread_mutex_init_intercept, (pthread_mutex_t *mutex, const pthread_mutexattr_t* attr), (mutex, attr)); #if defined(VGO_solaris) static __always_inline int mutex_init_intercept(mutex_t *mutex, int type, void *arg) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_INIT, mutex, DRD_(thread_to_drd_mutex_type)(type), 0, 0, 0); CALL_FN_W_WWW(ret, fn, mutex, type, arg); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_INIT, mutex, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, mutexZuinit, mutex_init_intercept, (mutex_t *mutex, int type, void *arg), (mutex, type, arg)); #endif /* VGO_solaris */ static __always_inline int pthread_mutex_destroy_intercept(pthread_mutex_t* mutex) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_DESTROY, mutex, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_DESTROY, mutex, DRD_(mutex_type)(mutex), 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_mutex_destroy is a weak alias to mutex_destroy. */ PTH_FUNCS(int, mutexZudestroy, pthread_mutex_destroy_intercept, (pthread_mutex_t *mutex), (mutex)); #else PTH_FUNCS(int, pthreadZumutexZudestroy, pthread_mutex_destroy_intercept, (pthread_mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ static __always_inline int pthread_mutex_lock_intercept(pthread_mutex_t* mutex) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, mutex, DRD_(mutex_type)(mutex), 0, 0, 0); CALL_FN_W_W(ret, fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, mutex, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_mutex_lock is a weak alias to mutex_lock. */ PTH_FUNCS(int, mutexZulock, pthread_mutex_lock_intercept, (pthread_mutex_t *mutex), (mutex)); #else PTH_FUNCS(int, pthreadZumutexZulock, pthread_mutex_lock_intercept, (pthread_mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ #if defined(VGO_solaris) /* Internal to libc. Mutex is usually initialized only implicitly, * by zeroing mutex_t structure. */ static __always_inline void lmutex_lock_intercept(mutex_t *mutex) { OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, mutex, DRD_(mutex_type)((pthread_mutex_t *) mutex), False /* try_lock */, 0, 0); CALL_FN_v_W(fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, mutex, True /* took_lock */, 0, 0, 0); } PTH_FUNCS(void, lmutexZulock, lmutex_lock_intercept, (mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ static __always_inline int pthread_mutex_trylock_intercept(pthread_mutex_t* mutex) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, mutex, DRD_(mutex_type)(mutex), 1, 0, 0); CALL_FN_W_W(ret, fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, mutex, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_mutex_trylock is a weak alias to mutex_trylock. */ PTH_FUNCS(int, mutexZutrylock, pthread_mutex_trylock_intercept, (pthread_mutex_t *mutex), (mutex)); #else PTH_FUNCS(int, pthreadZumutexZutrylock, pthread_mutex_trylock_intercept, (pthread_mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ static __always_inline int pthread_mutex_timedlock_intercept(pthread_mutex_t *mutex, const struct timespec *abs_timeout) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, mutex, DRD_(mutex_type)(mutex), 0, 0, 0); CALL_FN_W_WW(ret, fn, mutex, abs_timeout); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, mutex, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZumutexZutimedlock, pthread_mutex_timedlock_intercept, (pthread_mutex_t *mutex, const struct timespec *abs_timeout), (mutex, abs_timeout)); #if defined(VGO_solaris) PTH_FUNCS(int, pthreadZumutexZureltimedlockZunp, pthread_mutex_timedlock_intercept, (pthread_mutex_t *mutex, const struct timespec *timeout), (mutex, timeout)); #endif /* VGO_solaris */ static __always_inline int pthread_mutex_unlock_intercept(pthread_mutex_t *mutex) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_UNLOCK, mutex, DRD_(mutex_type)(mutex), 0, 0, 0); CALL_FN_W_W(ret, fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_UNLOCK, mutex, 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_mutex_unlock is a weak alias to mutex_unlock. */ PTH_FUNCS(int, mutexZuunlock, pthread_mutex_unlock_intercept, (pthread_mutex_t *mutex), (mutex)); #else PTH_FUNCS(int, pthreadZumutexZuunlock, pthread_mutex_unlock_intercept, (pthread_mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ #if defined(VGO_solaris) /* Internal to libc. */ static __always_inline void lmutex_unlock_intercept(mutex_t *mutex) { OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_UNLOCK, mutex, DRD_(mutex_type)((pthread_mutex_t *) mutex), 0, 0, 0); CALL_FN_v_W(fn, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_UNLOCK, mutex, 0, 0, 0, 0); } PTH_FUNCS(void, lmutexZuunlock, lmutex_unlock_intercept, (mutex_t *mutex), (mutex)); #endif /* VGO_solaris */ static __always_inline int pthread_cond_init_intercept(pthread_cond_t* cond, const pthread_condattr_t* attr) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_INIT, cond, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, cond, attr); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_INIT, cond, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZucondZuinit, pthread_cond_init_intercept, (pthread_cond_t* cond, const pthread_condattr_t* attr), (cond, attr)); #if defined(VGO_solaris) static __always_inline int cond_init_intercept(cond_t *cond, int type, void *arg) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_INIT, cond, 0, 0, 0, 0); CALL_FN_W_WWW(ret, fn, cond, type, arg); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_INIT, cond, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, condZuinit, cond_init_intercept, (cond_t *cond, int type, void *arg), (cond, type, arg)); #endif /* VGO_solaris */ static __always_inline int pthread_cond_destroy_intercept(pthread_cond_t* cond) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_DESTROY, cond, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, cond); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_DESTROY, cond, ret==0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_cond_destroy is a weak alias to cond_destroy. */ PTH_FUNCS(int, condZudestroy, pthread_cond_destroy_intercept, (pthread_cond_t *cond), (cond)); #else PTH_FUNCS(int, pthreadZucondZudestroy, pthread_cond_destroy_intercept, (pthread_cond_t* cond), (cond)); #endif /* VGO_solaris */ static __always_inline int pthread_cond_wait_intercept(pthread_cond_t *cond, pthread_mutex_t *mutex) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_WAIT, cond, mutex, DRD_(mutex_type)(mutex), 0, 0); CALL_FN_W_WW(ret, fn, cond, mutex); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_WAIT, cond, mutex, 1, 0, 0); return ret; } PTH_FUNCS(int, pthreadZucondZuwait, pthread_cond_wait_intercept, (pthread_cond_t *cond, pthread_mutex_t *mutex), (cond, mutex)); #if defined(VGO_solaris) PTH_FUNCS(int, condZuwait, pthread_cond_wait_intercept, (pthread_cond_t *cond, pthread_mutex_t *mutex), (cond, mutex)); #endif /* VGO_solaris */ static __always_inline int pthread_cond_timedwait_intercept(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec* abstime) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_WAIT, cond, mutex, DRD_(mutex_type)(mutex), 0, 0); CALL_FN_W_WWW(ret, fn, cond, mutex, abstime); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_WAIT, cond, mutex, 1, 0, 0); return ret; } PTH_FUNCS(int, pthreadZucondZutimedwait, pthread_cond_timedwait_intercept, (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec* abstime), (cond, mutex, abstime)); #if defined(VGO_solaris) PTH_FUNCS(int, condZutimedwait, pthread_cond_timedwait_intercept, (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *timeout), (cond, mutex, timeout)); PTH_FUNCS(int, condZureltimedwait, pthread_cond_timedwait_intercept, (pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *timeout), (cond, mutex, timeout)); #endif /* VGO_solaris */ // NOTE: be careful to intercept only pthread_cond_signal() and not Darwin's // pthread_cond_signal_thread_np(). The former accepts one argument; the latter // two. Intercepting all pthread_cond_signal* functions will cause only one // argument to be passed to pthread_cond_signal_np() and hence will cause this // last function to crash. static __always_inline int pthread_cond_signal_intercept(pthread_cond_t* cond) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_SIGNAL, cond, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, cond); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_SIGNAL, cond, 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_cond_signal is a weak alias to cond_signal. */ PTH_FUNCS(int, condZusignal, pthread_cond_signal_intercept, (pthread_cond_t *cond), (cond)); #else PTH_FUNCS(int, pthreadZucondZusignal, pthread_cond_signal_intercept, (pthread_cond_t* cond), (cond)); #endif /* VGO_solaris */ static __always_inline int pthread_cond_broadcast_intercept(pthread_cond_t* cond) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_COND_BROADCAST, cond, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, cond); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_COND_BROADCAST, cond, 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_cond_broadcast is a weak alias to cond_broadcast. */ PTH_FUNCS(int, condZubroadcast, pthread_cond_broadcast_intercept, (pthread_cond_t *cond), (cond)); #else PTH_FUNCS(int, pthreadZucondZubroadcast, pthread_cond_broadcast_intercept, (pthread_cond_t* cond), (cond)); #endif /* VGO_solaris */ #if defined(HAVE_PTHREAD_SPIN_LOCK) \ && !defined(DISABLE_PTHREAD_SPINLOCK_INTERCEPT) static __always_inline int pthread_spin_init_intercept(pthread_spinlock_t *spinlock, int pshared) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SPIN_INIT_OR_UNLOCK, spinlock, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, spinlock, pshared); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SPIN_INIT_OR_UNLOCK, spinlock, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZuspinZuinit, pthread_spin_init_intercept, (pthread_spinlock_t *spinlock, int pshared), (spinlock, pshared)); static __always_inline int pthread_spin_destroy_intercept(pthread_spinlock_t *spinlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_DESTROY, spinlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, spinlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_DESTROY, spinlock, mutex_type_spinlock, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZuspinZudestroy, pthread_spin_destroy_intercept, (pthread_spinlock_t *spinlock), (spinlock)); static __always_inline int pthread_spin_lock_intercept(pthread_spinlock_t *spinlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, spinlock, mutex_type_spinlock, 0, 0, 0); CALL_FN_W_W(ret, fn, spinlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, spinlock, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZuspinZulock, pthread_spin_lock_intercept, (pthread_spinlock_t *spinlock), (spinlock)); static __always_inline int pthread_spin_trylock_intercept(pthread_spinlock_t *spinlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_MUTEX_LOCK, spinlock, mutex_type_spinlock, 0, 0, 0); CALL_FN_W_W(ret, fn, spinlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_MUTEX_LOCK, spinlock, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZuspinZutrylock, pthread_spin_trylock_intercept, (pthread_spinlock_t *spinlock), (spinlock)); static __always_inline int pthread_spin_unlock_intercept(pthread_spinlock_t *spinlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SPIN_INIT_OR_UNLOCK, spinlock, mutex_type_spinlock, 0, 0, 0); CALL_FN_W_W(ret, fn, spinlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SPIN_INIT_OR_UNLOCK, spinlock, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZuspinZuunlock, pthread_spin_unlock_intercept, (pthread_spinlock_t *spinlock), (spinlock)); #endif // HAVE_PTHREAD_SPIN_LOCK #if defined(HAVE_PTHREAD_BARRIER_INIT) static __always_inline int pthread_barrier_init_intercept(pthread_barrier_t* barrier, const pthread_barrierattr_t* attr, unsigned count) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_BARRIER_INIT, barrier, pthread_barrier, count, 0, 0); CALL_FN_W_WWW(ret, fn, barrier, attr, count); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_BARRIER_INIT, barrier, pthread_barrier, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZubarrierZuinit, pthread_barrier_init_intercept, (pthread_barrier_t* barrier, const pthread_barrierattr_t* attr, unsigned count), (barrier, attr, count)); static __always_inline int pthread_barrier_destroy_intercept(pthread_barrier_t* barrier) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_BARRIER_DESTROY, barrier, pthread_barrier, 0, 0, 0); CALL_FN_W_W(ret, fn, barrier); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_BARRIER_DESTROY, barrier, pthread_barrier, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZubarrierZudestroy, pthread_barrier_destroy_intercept, (pthread_barrier_t* barrier), (barrier)); static __always_inline int pthread_barrier_wait_intercept(pthread_barrier_t* barrier) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_BARRIER_WAIT, barrier, pthread_barrier, 0, 0, 0); CALL_FN_W_W(ret, fn, barrier); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_BARRIER_WAIT, barrier, pthread_barrier, ret == 0 || ret == PTHREAD_BARRIER_SERIAL_THREAD, ret == PTHREAD_BARRIER_SERIAL_THREAD, 0); return ret; } PTH_FUNCS(int, pthreadZubarrierZuwait, pthread_barrier_wait_intercept, (pthread_barrier_t* barrier), (barrier)); #endif // HAVE_PTHREAD_BARRIER_INIT static __always_inline int sem_init_intercept(sem_t *sem, int pshared, unsigned int value) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_INIT, sem, pshared, value, 0, 0); CALL_FN_W_WWW(ret, fn, sem, pshared, value); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_INIT, sem, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZuinit, sem_init_intercept, (sem_t *sem, int pshared, unsigned int value), (sem, pshared, value)); #if defined(VGO_solaris) static __always_inline int sema_init_intercept(sema_t *sem, unsigned int value, int type, void *arg) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_INIT, sem, type == USYNC_PROCESS ? 1 : 0, value, 0, 0); CALL_FN_W_WWWW(ret, fn, sem, value, type, arg); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_INIT, sem, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semaZuinit, sema_init_intercept, (sema_t *sem, unsigned int value, int type, void *arg), (sem, value, type, arg)); #endif /* VGO_solaris */ static __always_inline int sem_destroy_intercept(sem_t *sem) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_DESTROY, sem, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, sem); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_DESTROY, sem, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZudestroy, sem_destroy_intercept, (sem_t *sem), (sem)); #if defined(VGO_solaris) PTH_FUNCS(int, semaZudestroy, sem_destroy_intercept, (sem_t *sem), (sem)); #endif /* VGO_solaris */ static __always_inline sem_t* sem_open_intercept(const char *name, int oflag, mode_t mode, unsigned int value) { sem_t *ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_OPEN, name, oflag, mode, value, 0); CALL_FN_W_WWWW(ret, fn, name, oflag, mode, value); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_OPEN, ret != SEM_FAILED ? ret : 0, name, oflag, mode, value); return ret; } PTH_FUNCS(sem_t *, semZuopen, sem_open_intercept, (const char *name, int oflag, mode_t mode, unsigned int value), (name, oflag, mode, value)); static __always_inline int sem_close_intercept(sem_t *sem) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_CLOSE, sem, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, sem); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_CLOSE, sem, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZuclose, sem_close_intercept, (sem_t *sem), (sem)); static __always_inline int sem_wait_intercept(sem_t *sem) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_WAIT, sem, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, sem); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_WAIT, sem, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZuwait, sem_wait_intercept, (sem_t *sem), (sem)); #if defined(VGO_solaris) PTH_FUNCS(int, semaZuwait, sem_wait_intercept, (sem_t *sem), (sem)); #endif /* VGO_solaris */ static __always_inline int sem_trywait_intercept(sem_t *sem) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_WAIT, sem, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, sem); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_WAIT, sem, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZutrywait, sem_trywait_intercept, (sem_t *sem), (sem)); #if defined(VGO_solaris) PTH_FUNCS(int, semaZutrywait, sem_trywait_intercept, (sem_t *sem), (sem)); #endif /* VGO_solaris */ static __always_inline int sem_timedwait_intercept(sem_t *sem, const struct timespec *abs_timeout) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_WAIT, sem, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, sem, abs_timeout); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_WAIT, sem, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZutimedwait, sem_timedwait_intercept, (sem_t *sem, const struct timespec *abs_timeout), (sem, abs_timeout)); #if defined(VGO_solaris) PTH_FUNCS(int, semaZutimedwait, sem_timedwait_intercept, (sem_t *sem, const struct timespec *timeout), (sem, timeout)); PTH_FUNCS(int, semaZureltimedwait, sem_timedwait_intercept, (sem_t *sem, const struct timespec *timeout), (sem, timeout)); #endif /* VGO_solaris */ static __always_inline int sem_post_intercept(sem_t *sem) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_SEM_POST, sem, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, sem); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_SEM_POST, sem, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, semZupost, sem_post_intercept, (sem_t *sem), (sem)); #if defined(VGO_solaris) PTH_FUNCS(int, semaZupost, sem_post_intercept, (sem_t *sem), (sem)); #endif /* VGO_solaris */ /* Android's pthread.h doesn't say anything about rwlocks, hence these functions have to be conditionally compiled. */ #if defined(HAVE_PTHREAD_RWLOCK_T) static __always_inline int pthread_rwlock_init_intercept(pthread_rwlock_t* rwlock, const pthread_rwlockattr_t* attr) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_INIT, rwlock, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, rwlock, attr); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_INIT, rwlock, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZurwlockZuinit, pthread_rwlock_init_intercept, (pthread_rwlock_t* rwlock, const pthread_rwlockattr_t* attr), (rwlock, attr)); #if defined(VGO_solaris) static __always_inline int rwlock_init_intercept(rwlock_t *rwlock, int type, void *arg) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_INIT, rwlock, 0, 0, 0, 0); CALL_FN_W_WWW(ret, fn, rwlock, type, arg); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_INIT, rwlock, 0, 0, 0, 0); return ret; } PTH_FUNCS(int, rwlockZuinit, rwlock_init_intercept, (rwlock_t *rwlock, int type, void *arg), (rwlock, type, arg)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_destroy_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_DESTROY, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_DESTROY, rwlock, 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_destroy is a weak alias to rwlock_destroy. */ PTH_FUNCS(int, rwlockZudestroy, pthread_rwlock_destroy_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZudestroy, pthread_rwlock_destroy_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_rdlock_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_RDLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_RDLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_rdlock is a weak alias to rw_rdlock. */ PTH_FUNCS(int, rwZurdlock, pthread_rwlock_rdlock_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZurdlock, pthread_rwlock_rdlock_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ #if defined(VGO_solaris) /* Internal to libc. */ static __always_inline void lrw_rdlock_intercept(rwlock_t *rwlock) { OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_RDLOCK, rwlock, 0, 0, 0, 0); CALL_FN_v_W(fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_RDLOCK, rwlock, True /* took_lock */, 0, 0, 0); } PTH_FUNCS(void, lrwZurdlock, lrw_rdlock_intercept, (rwlock_t *rwlock), (rwlock)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_wrlock_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_WRLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_WRLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_wrlock is a weak alias to rw_wrlock. */ PTH_FUNCS(int, rwZuwrlock, pthread_rwlock_wrlock_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZuwrlock, pthread_rwlock_wrlock_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ #if defined(VGO_solaris) /* Internal to libc. */ static __always_inline void lrw_wrlock_intercept(rwlock_t *rwlock) { OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_WRLOCK, rwlock, 0, 0, 0, 0); CALL_FN_v_W(fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_WRLOCK, rwlock, True /* took_lock */, 0, 0, 0); } PTH_FUNCS(void, lrwZuwrlock, lrw_wrlock_intercept, (rwlock_t *rwlock), (rwlock)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_timedrdlock_intercept(pthread_rwlock_t* rwlock, const struct timespec *timeout) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_RDLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, rwlock, timeout); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_RDLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZurwlockZutimedrdlock, pthread_rwlock_timedrdlock_intercept, (pthread_rwlock_t* rwlock, const struct timespec *timeout), (rwlock, timeout)); #if defined(VGO_solaris) PTH_FUNCS(int, pthreadZurwlockZureltimedrdlockZunp, pthread_rwlock_timedrdlock_intercept, (pthread_rwlock_t *rwlock, const struct timespec *timeout), (rwlock, timeout)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_timedwrlock_intercept(pthread_rwlock_t* rwlock, const struct timespec *timeout) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_WRLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_WW(ret, fn, rwlock, timeout); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_WRLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } PTH_FUNCS(int, pthreadZurwlockZutimedwrlock, pthread_rwlock_timedwrlock_intercept, (pthread_rwlock_t* rwlock, const struct timespec *timeout), (rwlock, timeout)); #if defined(VGO_solaris) PTH_FUNCS(int, pthreadZurwlockZureltimedwrlockZunp, pthread_rwlock_timedwrlock_intercept, (pthread_rwlock_t *rwlock, const struct timespec *timeout), (rwlock, timeout)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_tryrdlock_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_RDLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_RDLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_tryrdlock is a weak alias to rw_tryrdlock. */ PTH_FUNCS(int, rwZutryrdlock, pthread_rwlock_tryrdlock_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZutryrdlock, pthread_rwlock_tryrdlock_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_trywrlock_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_WRLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_WRLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_trywrlock is a weak alias to rw_trywrlock. */ PTH_FUNCS(int, rwZutrywrlock, pthread_rwlock_trywrlock_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZutrywrlock, pthread_rwlock_trywrlock_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ static __always_inline int pthread_rwlock_unlock_intercept(pthread_rwlock_t* rwlock) { int ret; OrigFn fn; VALGRIND_GET_ORIG_FN(fn); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__PRE_RWLOCK_UNLOCK, rwlock, 0, 0, 0, 0); CALL_FN_W_W(ret, fn, rwlock); VALGRIND_DO_CLIENT_REQUEST_STMT(VG_USERREQ__POST_RWLOCK_UNLOCK, rwlock, ret == 0, 0, 0, 0); return ret; } #if defined(VGO_solaris) /* On Solaris, pthread_rwlock_unlock is a weak alias to rw_unlock. */ PTH_FUNCS(int, rwZuunlock, pthread_rwlock_unlock_intercept, (pthread_rwlock_t *rwlock), (rwlock)); #else PTH_FUNCS(int, pthreadZurwlockZuunlock, pthread_rwlock_unlock_intercept, (pthread_rwlock_t* rwlock), (rwlock)); #endif /* VGO_solaris */ #endif /* defined(HAVE_PTHREAD_RWLOCK_T) */
677727.c
/* libFLAC - Free Lossless Audio Codec library * Copyright (C) 2001-2009 Josh Coalson * Copyright (C) 2011-2013 Xiph.Org Foundation * * 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 the Xiph.org Foundation 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 FOUNDATION 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 HAVE_CONFIG_H # include <config.h> #endif #include "private/cpu.h" #include <stdlib.h> #include <stdio.h> #if defined FLAC__CPU_IA32 # include <signal.h> #elif defined FLAC__CPU_PPC # if !defined FLAC__NO_ASM # if defined FLAC__SYS_DARWIN # include <sys/sysctl.h> # include <mach/mach.h> # include <mach/mach_host.h> # include <mach/host_info.h> # include <mach/machine.h> # ifndef CPU_SUBTYPE_POWERPC_970 # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100) # endif # else /* FLAC__SYS_DARWIN */ # include <signal.h> # include <setjmp.h> static sigjmp_buf jmpbuf; static volatile sig_atomic_t canjump = 0; static void sigill_handler (int sig) { if (!canjump) { signal (sig, SIG_DFL); raise (sig); } canjump = 0; siglongjmp (jmpbuf, 1); } # endif /* FLAC__SYS_DARWIN */ # endif /* FLAC__NO_ASM */ #endif /* FLAC__CPU_PPC */ #if defined (__NetBSD__) || defined(__OpenBSD__) #include <sys/param.h> #include <sys/sysctl.h> #include <machine/cpu.h> #endif #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) #include <sys/types.h> #include <sys/sysctl.h> #endif #if defined(__APPLE__) /* how to get sysctlbyname()? */ #endif /* these are flags in EDX of CPUID AX=00000001 */ static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000; static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000; static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000; static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000; static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000; /* these are flags in ECX of CPUID AX=00000001 */ static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001; static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200; /* these are flags in EDX of CPUID AX=80000001 */ static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000; static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000; static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000; /* * Extra stuff needed for detection of OS support for SSE on IA-32 */ #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS # if defined(__linux__) /* * If the OS doesn't support SSE, we will get here with a SIGILL. We * modify the return address to jump over the offending SSE instruction * and also the operation following it that indicates the instruction * executed successfully. In this way we use no global variables and * stay thread-safe. * * 3 + 3 + 6: * 3 bytes for "xorps xmm0,xmm0" * 3 bytes for estimate of how long the follwing "inc var" instruction is * 6 bytes extra in case our estimate is wrong * 12 bytes puts us in the NOP "landing zone" */ # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */ # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR static void sigill_handler_sse_os(int signal, struct sigcontext sc) { (void)signal; sc.eip += 3 + 3 + 6; } # else # include <sys/ucontext.h> static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc) { (void)signal, (void)si; ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6; } # endif # elif defined(_MSC_VER) # include <windows.h> # define USE_TRY_CATCH_FLAVOR /* sigill_handler flavor resulted in several crash reports on win32 */ # ifdef USE_TRY_CATCH_FLAVOR # else LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep) { if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) { ep->ContextRecord->Eip += 3 + 3 + 6; return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } # endif # endif #endif void FLAC__cpu_info(FLAC__CPUInfo *info) { /* * IA32-specific */ #ifdef FLAC__CPU_IA32 info->type = FLAC__CPUINFO_TYPE_IA32; #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */ info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false; info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */ info->data.ia32.cmov = false; info->data.ia32.mmx = false; info->data.ia32.fxsr = false; info->data.ia32.sse = false; info->data.ia32.sse2 = false; info->data.ia32.sse3 = false; info->data.ia32.ssse3 = false; info->data.ia32._3dnow = false; info->data.ia32.ext3dnow = false; info->data.ia32.extmmx = false; if(info->data.ia32.cpuid) { /* http://www.sandpile.org/ia32/cpuid.htm */ FLAC__uint32 flags_edx, flags_ecx; FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx); info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false; info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false; info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false; info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false; info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false; info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false; info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false; #ifdef FLAC__USE_3DNOW flags_edx = FLAC__cpu_info_extended_amd_asm_ia32(); info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false; info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false; info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false; #else info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false; #endif #ifdef DEBUG fprintf(stderr, "CPU info (IA-32):\n"); fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n'); fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n'); fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n'); fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n'); fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n'); fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n'); fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n'); fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n'); fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n'); fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n'); fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n'); fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n'); #endif /* * now have to check for OS support of SSE/SSE2 */ if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) { #if defined FLAC__NO_SSE_OS /* assume user knows better than us; turn it off */ info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; #elif defined FLAC__SSE_OS /* assume user knows better than us; leave as detected above */ #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__) int sse = 0; size_t len; /* at least one of these must work: */ len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse); len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */ if(!sse) info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; #elif defined(__NetBSD__) || defined (__OpenBSD__) # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__) int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE }; size_t len = sizeof(val); if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val) info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; else { /* double-check SSE2 */ mib[1] = CPU_SSE2; len = sizeof(val); if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val) info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; } # else info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; # endif #elif defined(__linux__) int sse = 0; struct sigaction sigill_save; #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR) #else struct sigaction sigill_sse; sigill_sse.sa_sigaction = sigill_handler_sse_os; __sigemptyset(&sigill_sse.sa_mask); sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */ if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save)) #endif { /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */ /* see sigill_handler_sse_os() for an explanation of the following: */ asm volatile ( "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */ "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */ "incl %0\n\t" /* SIGILL handler will jump over this */ /* landing zone */ "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */ "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */ "nop\n\t" "nop" /* SIGILL jump lands here if "inc" is 1 byte */ : "=r"(sse) : "r"(sse) ); sigaction(SIGILL, &sigill_save, NULL); } if(!sse) info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; #elif defined(_MSC_VER) # ifdef USE_TRY_CATCH_FLAVOR _try { __asm { # if _MSC_VER <= 1200 /* VC6 assembler doesn't know SSE, have to emit bytecode instead */ _emit 0x0F _emit 0x57 _emit 0xC0 # else xorps xmm0,xmm0 # endif } } _except(EXCEPTION_EXECUTE_HANDLER) { if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION) info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; } # else int sse = 0; LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os); /* see GCC version above for explanation */ /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */ /* http://www.codeproject.com/cpp/gccasm.asp */ /* http://www.hick.org/~mmiller/msvc_inline_asm.html */ __asm { # if _MSC_VER <= 1200 /* VC6 assembler doesn't know SSE, have to emit bytecode instead */ _emit 0x0F _emit 0x57 _emit 0xC0 # else xorps xmm0,xmm0 # endif inc sse nop nop nop nop nop nop nop nop nop } SetUnhandledExceptionFilter(save); if(!sse) info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; # endif #else /* no way to test, disable to be safe */ info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false; #endif #ifdef DEBUG fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n'); #endif } } #else info->use_asm = false; #endif /* * PPC-specific */ #elif defined FLAC__CPU_PPC info->type = FLAC__CPUINFO_TYPE_PPC; # if !defined FLAC__NO_ASM info->use_asm = true; # ifdef FLAC__USE_ALTIVEC # if defined FLAC__SYS_DARWIN { int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT }; size_t len = sizeof(val); info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val); } { host_basic_info_data_t hostInfo; mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount); info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970); } # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */ { /* no Darwin, do it the brute-force way */ /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */ info->data.ppc.altivec = 0; info->data.ppc.ppc64 = 0; signal (SIGILL, sigill_handler); canjump = 0; if (!sigsetjmp (jmpbuf, 1)) { canjump = 1; asm volatile ( "mtspr 256, %0\n\t" "vand %%v0, %%v0, %%v0" : : "r" (-1) ); info->data.ppc.altivec = 1; } canjump = 0; if (!sigsetjmp (jmpbuf, 1)) { int x = 0; canjump = 1; /* PPC64 hardware implements the cntlzd instruction */ asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) ); info->data.ppc.ppc64 = 1; } signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */ } # endif # else /* !FLAC__USE_ALTIVEC */ info->data.ppc.altivec = 0; info->data.ppc.ppc64 = 0; # endif # else info->use_asm = false; # endif /* * unknown CPI */ #else info->type = FLAC__CPUINFO_TYPE_UNKNOWN; info->use_asm = false; #endif }
507082.c
// SPDX-License-Identifier: BSD-2-Clause /* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ #include "tomcrypt_private.h" /** @file der_encode_sequence_ex.c ASN.1 DER, encode a SEQUENCE, Tom St Denis */ #ifdef LTC_DER /** Encode a SEQUENCE @param list The list of items to encode @param inlen The number of items in the list @param out [out] The destination @param outlen [in/out] The size of the output @param type_of LTC_ASN1_SEQUENCE or LTC_ASN1_SET/LTC_ASN1_SETOF @return CRYPT_OK on success */ int der_encode_sequence_ex(const ltc_asn1_list *list, unsigned long inlen, unsigned char *out, unsigned long *outlen, int type_of) { int err; ltc_asn1_type type; unsigned long size, x, y, z, i; void *data; LTC_ARGCHK(list != NULL); LTC_ARGCHK(out != NULL); LTC_ARGCHK(outlen != NULL); /* get size of output that will be required */ y = 0; z = 0; if ((err = der_length_sequence_ex(list, inlen, &y, &z)) != CRYPT_OK) return CRYPT_INVALID_ARG; /* too big ? */ if (*outlen < y) { *outlen = y; err = CRYPT_BUFFER_OVERFLOW; goto LBL_ERR; } /* store header */ x = 0; out[x++] = (type_of == LTC_ASN1_SEQUENCE) ? 0x30 : 0x31; y = *outlen - x; if ((err = der_encode_asn1_length(z, &out[x], &y)) != CRYPT_OK) { goto LBL_ERR; } x += y; /* store data */ *outlen -= x; for (i = 0; i < inlen; i++) { type = list[i].type; size = list[i].size; data = list[i].data; if (type == LTC_ASN1_EOL) { break; } switch (type) { case LTC_ASN1_BOOLEAN: z = *outlen; if ((err = der_encode_boolean(*((int *)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_INTEGER: z = *outlen; if ((err = der_encode_integer(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SHORT_INTEGER: z = *outlen; if ((err = der_encode_short_integer(*((unsigned long*)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_LONG_INTEGER: z = *outlen; if ((err = der_encode_long_integer(*((unsigned long*)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_BIT_STRING: z = *outlen; if ((err = der_encode_bit_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_RAW_BIT_STRING: z = *outlen; if ((err = der_encode_raw_bit_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_OCTET_STRING: z = *outlen; if ((err = der_encode_octet_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_NULL: out[x] = 0x05; out[x+1] = 0x00; z = 2; break; case LTC_ASN1_OBJECT_IDENTIFIER: z = *outlen; if ((err = der_encode_object_identifier(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_IA5_STRING: z = *outlen; if ((err = der_encode_ia5_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_PRINTABLE_STRING: z = *outlen; if ((err = der_encode_printable_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_UTF8_STRING: z = *outlen; if ((err = der_encode_utf8_string(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_UTCTIME: z = *outlen; if ((err = der_encode_utctime(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_GENERALIZEDTIME: z = *outlen; if ((err = der_encode_generalizedtime(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SET: z = *outlen; if ((err = der_encode_set(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SETOF: z = *outlen; if ((err = der_encode_setof(data, size, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_SEQUENCE: z = *outlen; if ((err = der_encode_sequence_ex(data, size, out + x, &z, type)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_CUSTOM_TYPE: z = *outlen; if ((err = der_encode_custom_type(&list[i], out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_EXP_TAG: z = *outlen; if ((err = der_encode_exp_tag(data, out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_ENUMERATED: z = *outlen; if ((err = der_encode_enumerated(*((unsigned long*)data), out + x, &z)) != CRYPT_OK) { goto LBL_ERR; } break; case LTC_ASN1_CHOICE: case LTC_ASN1_EOL: case LTC_ASN1_TELETEX_STRING: default: err = CRYPT_INVALID_ARG; goto LBL_ERR; } x += z; *outlen -= z; } *outlen = x; err = CRYPT_OK; LBL_ERR: return err; } #endif /* ref: $Format:%D$ */ /* git commit: $Format:%H$ */ /* commit time: $Format:%ai$ */
208789.c
/* * (C) Copyright 2015 Kurento (http://kurento.org/) * * 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 <gst/check/gstcheck.h> #include <gst/gst.h> #include "../../src/gst-plugins/commons/kmselementpadtype.h" #define KMS_VIDEO_PREFIX "video_src_" #define KMS_AUDIO_PREFIX "audio_src_" #define VIDEO_SINK "video-sink" G_DEFINE_QUARK (VIDEO_SINK, video_sink); #define BITRATE 500000 static gboolean quit_main_loop_idle (gpointer data) { GMainLoop *loop = data; g_main_loop_quit (loop); return FALSE; } static void bus_msg (GstBus * bus, GstMessage * msg, gpointer pipe) { switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR:{ gchar *error_file = g_strdup_printf ("error-%s", GST_OBJECT_NAME (pipe)); GST_ERROR ("Error: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, error_file); g_free (error_file); fail ("Error received on bus"); break; } case GST_MESSAGE_WARNING:{ gchar *warn_file = g_strdup_printf ("warning-%s", GST_OBJECT_NAME (pipe)); GST_WARNING ("Warning: %" GST_PTR_FORMAT, msg); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), GST_DEBUG_GRAPH_SHOW_ALL, warn_file); g_free (warn_file); break; } default: break; } } static void fakesink_hand_off_check_size (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; static gsize size = 0; GMainLoop *loop = (GMainLoop *) data; size += gst_buffer_get_size (buf); if (count++ >= 60) { gsize bitrate = size * 8 / (count / 30); // TODO: Count for size GST_INFO ("Bitrate is: %ld bits", bitrate); fail_if (abs (bitrate - BITRATE) > BITRATE * 0.15); g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static void fakesink_hand_off (GstElement * fakesink, GstBuffer * buf, GstPad * pad, gpointer data) { static int count = 0; GMainLoop *loop = (GMainLoop *) data; if (count++ > 40) { g_object_set (G_OBJECT (fakesink), "signal-handoffs", FALSE, NULL); g_idle_add (quit_main_loop_idle, loop); } } static gboolean timeout_check (gpointer pipeline) { if (GST_IS_BIN (pipeline)) { gchar *timeout_file = g_strdup_printf ("timeout-%s", GST_OBJECT_NAME (pipeline)); GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipeline), GST_DEBUG_GRAPH_SHOW_ALL, timeout_file); g_free (timeout_file); } return FALSE; } typedef struct _KmsConnectData { GstElement *src; GstBin *pipe; const gchar *pad_prefix; gulong id; } KmsConnectData; static gboolean connect_sink_async (GstElement * passthrough, GstElement * src, GstElement * pipe, const gchar * pad_prefix) { GstPad *pad = gst_element_get_static_pad (passthrough, pad_prefix); if (pad == NULL) { return FALSE; } gst_bin_add (GST_BIN (pipe), src); gst_element_link_pads (src, NULL, passthrough, pad_prefix); gst_element_sync_state_with_parent (src); g_object_unref (pad); return TRUE; } static void connect_sink_on_srcpad_added (GstElement * element, GstPad * pad) { GstElement *sink; GstPad *sinkpad; GST_DEBUG_OBJECT (element, "Added pad %" GST_PTR_FORMAT, pad); if (g_str_has_prefix (GST_PAD_NAME (pad), KMS_AUDIO_PREFIX)) { GST_ERROR_OBJECT (pad, "Not connecting audio stream, it is not expected"); return; } else if (g_str_has_prefix (GST_PAD_NAME (pad), KMS_VIDEO_PREFIX)) { GST_DEBUG_OBJECT (pad, "Connecting video stream"); sink = g_object_get_qdata (G_OBJECT (element), video_sink_quark ()); } else { GST_TRACE_OBJECT (pad, "Not src pad type"); return; } sinkpad = gst_element_get_static_pad (sink, "sink"); gst_pad_link (pad, sinkpad); g_object_unref (sinkpad); gst_element_sync_state_with_parent (sink); } static gboolean kms_element_request_srcpad (GstElement * src, KmsElementPadType pad_type) { gchar *padname; gboolean ret; g_signal_emit_by_name (src, "request-new-pad", pad_type, NULL, GST_PAD_SRC, &padname); ret = padname != NULL; g_free (padname); return ret; } static void on_pad_added_cb (GstElement * element, GstPad * pad, gpointer user_data) { GST_DEBUG_OBJECT (element, "Pad added %" GST_PTR_FORMAT, pad); if (gst_pad_get_direction (pad) == GST_PAD_SRC) { connect_sink_on_srcpad_added (element, pad); } } GST_START_TEST (check_connecion) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *passthrough = gst_element_factory_make ("passthrough", NULL); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); KmsConnectData data; data.src = videotestsrc; data.pipe = GST_BIN (pipeline); data.pad_prefix = "sink_video_default"; g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off), loop); g_object_set_qdata (G_OBJECT (passthrough), video_sink_quark (), fakesink); g_signal_connect (passthrough, "pad-added", G_CALLBACK (on_pad_added_cb), &data); mark_point (); gst_bin_add_many (GST_BIN (pipeline), passthrough, fakesink, NULL); mark_point (); fail_unless (kms_element_request_srcpad (passthrough, KMS_ELEMENT_PAD_TYPE_VIDEO)); fail_if (!connect_sink_async (passthrough, videotestsrc, pipeline, data.pad_prefix)); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; GST_START_TEST (check_bitrate) { GMainLoop *loop = g_main_loop_new (NULL, TRUE); GstElement *pipeline = gst_pipeline_new (__FUNCTION__); GstElement *videotestsrc = gst_element_factory_make ("videotestsrc", NULL); GstElement *fakesink = gst_element_factory_make ("fakesink", NULL); GstElement *passthrough = gst_element_factory_make ("passthrough", NULL); GstElement *capsfilter = gst_element_factory_make ("capsfilter", NULL); GstCaps *caps = gst_caps_from_string ("video/x-vp8,framerate=30/1"); GstBus *bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); KmsConnectData data; data.src = videotestsrc; data.pipe = GST_BIN (pipeline); data.pad_prefix = "sink_video_default"; g_object_set (G_OBJECT (videotestsrc), "is-live", TRUE, NULL); gst_bus_add_signal_watch (bus); g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); g_object_set (G_OBJECT (fakesink), "sync", TRUE, "signal-handoffs", TRUE, "async", FALSE, NULL); g_signal_connect (G_OBJECT (fakesink), "handoff", G_CALLBACK (fakesink_hand_off_check_size), loop); g_object_set (capsfilter, "caps", caps, NULL); gst_caps_unref (caps); g_object_set (passthrough, "min-output-bitrate", BITRATE, "max-output-bitrate", BITRATE, NULL); g_object_set_qdata (G_OBJECT (passthrough), video_sink_quark (), capsfilter); g_signal_connect (passthrough, "pad-added", G_CALLBACK (on_pad_added_cb), NULL); mark_point (); gst_bin_add_many (GST_BIN (pipeline), passthrough, capsfilter, fakesink, NULL); gst_element_link (capsfilter, fakesink); mark_point (); fail_if (!connect_sink_async (passthrough, videotestsrc, pipeline, data.pad_prefix)); fail_unless (kms_element_request_srcpad (passthrough, KMS_ELEMENT_PAD_TYPE_VIDEO)); mark_point (); gst_element_set_state (pipeline, GST_STATE_PLAYING); mark_point (); g_timeout_add_seconds (10, timeout_check, pipeline); mark_point (); g_main_loop_run (loop); mark_point (); gst_element_set_state (pipeline, GST_STATE_NULL); gst_bus_remove_signal_watch (bus); g_object_unref (bus); g_object_unref (pipeline); g_main_loop_unref (loop); } GST_END_TEST; /* Suite initialization */ static Suite * passthrough_suite (void) { Suite *s = suite_create ("filterelement"); TCase *tc_chain = tcase_create ("element"); suite_add_tcase (s, tc_chain); tcase_add_test (tc_chain, check_connecion); tcase_add_test (tc_chain, check_bitrate); return s; } GST_CHECK_MAIN (passthrough);
781358.c
#include "stdio_impl.h" #include <string.h> #include <stdlib.h> #include <inttypes.h> #include <errno.h> ssize_t getdelim(char **restrict s, size_t *restrict n, int delim, FILE *restrict f) { char *tmp; unsigned char *z; size_t k; size_t i=0; int c; FLOCK(f); if (!n || !s) { f->mode |= f->mode-1; f->flags |= F_ERR; FUNLOCK(f); errno = EINVAL; return -1; } if (!*s) *n=0; for (;;) { if (f->rpos != f->rend) { z = memchr(f->rpos, delim, f->rend - f->rpos); k = z ? z - f->rpos + 1 : f->rend - f->rpos; } else { z = 0; k = 0; } if (i+k >= *n) { size_t m = i+k+2; if (!z && m < SIZE_MAX/4) m += m/2; tmp = realloc(*s, m); if (!tmp) { m = i+k+2; tmp = realloc(*s, m); if (!tmp) { /* Copy as much as fits and ensure no * pushback remains in the FILE buf. */ k = *n-i; memcpy(*s+i, f->rpos, k); f->rpos += k; f->mode |= f->mode-1; f->flags |= F_ERR; FUNLOCK(f); errno = ENOMEM; return -1; } } *s = tmp; *n = m; } if (k) { memcpy(*s+i, f->rpos, k); f->rpos += k; i += k; } if (z) break; if ((c = getc_unlocked(f)) == EOF) { if (!i || !feof(f)) { FUNLOCK(f); return -1; } break; } /* If the byte read by getc won't fit without growing the * output buffer, push it back for next iteration. */ if (i+1 >= *n) *--f->rpos = c; else if (((*s)[i++] = c) == delim) break; } (*s)[i] = 0; FUNLOCK(f); return i; } weak_alias(getdelim, __getdelim);
854572.c
/* * $Id: stdlib_mulsi3.c,v 1.3 2006-01-08 12:04:26 clib2devs Exp $ */ __asm(" \n\ .text \n\ .align 2 \n\ \n\ .globl __mulsi3 \n\ \n\ __mulsi3: \n\ mullw r3, r3, r4 \n\ blr \n\ ");
760596.c
#include "zram_cache.h" static int lra_empty = 0; extern unsigned int cache_size; #define ZEBRA_NATIVE 1 #ifdef EVICTION_POLICY_RANDOM #else static long lra_ptr = 0; #endif static struct _cache_entry *lra_head = NULL; struct _zebra_cache zebra_cache; int zebra_cache_init(){ INIT_RADIX_TREE(&zebra_cache.pages, GFP_ATOMIC); #ifdef EVICTION_POLICY_RANDOM #else lra_ptr = 0; #endif lra_head = (struct _cache_entry *) vmalloc(sizeof(struct _cache_entry) * cache_size); if (!lra_head) { return -1; } return 0; } int fill_lra(void){ int ret = -1; struct page *tmp_page = NULL; int kj = 0; if((lra_head != NULL) && (lra_empty == 0)) { printk("Creating LRA Array\n"); for(kj=0; kj < cache_size; kj++){ lra_head[kj].flag = EMPTY; lra_head[kj].dirty = 0; // tmp_page = alloc_page(__GFP_HIGHMEM | GFP_NOIO | __GFP_ZERO); #ifdef ZEBRA_NATIVE tmp_page = alloc_page(__GFP_HIGHMEM & (~__GFP_RECLAIM)); #else tmp_page = get_guard_cachepage();// alloc_page(__GFP_HIGHMEM | GFP_NOIO | __GFP_ZERO); #endif if(!tmp_page) printk("Could not allocate page for cache %d \n", kj); lra_head[kj].page = tmp_page; //get_guard_cachepage(); tmp_page = NULL; } #ifdef EVICTION_POLICY_RANDOM printk(" Cache eviction policy is RANDOM_EVICTION lra addr : %p, len : %d and (allocated count= %d)\n", lra_head, cache_size, kj); #else printk(" Cache eviction policy is LEAST RECENTLY ADDED lra addr : %p, len : %d and lraptr is : %ld (allocated count= %d)\n", lra_head, cache_size, lra_ptr, kj); #endif lra_empty = 1; ret = 0; } else{ pr_err("Error creating LRA\n"); printk("Error creating LRA\n"); } return ret; } static struct _cache_entry *zebra_lookup_cache_page(u32 index) { struct _cache_entry *cache_entry = NULL; cache_entry = radix_tree_lookup(&zebra_cache.pages, index); if(cache_entry){ if(index != cache_entry->blkid){ printk("BUG LOOKUP ERROR index %d != blkid %d\n", index, cache_entry->blkid); BUG_ON(cache_entry->blkid != index); //BUG_ON(cache_entry && cache_entry->page && cache_entry->page->index != index); return NULL; } else{ // trace_printk("zebra_lookup_cache_page %d == %d (blkid %d)\n", index, cache_entry->page->index, cache_entry->blkid); } } return cache_entry; } int zebra_delete_cache_page(u32 index){ struct _cache_entry *cache_entry = NULL; //printk("DELETING index : %d\n", index); // spin_lock_irqsave(&zebra_lock, zebra_lock_flags); cache_entry = radix_tree_delete(&zebra_cache.pages, index); if(cache_entry){ return 0; } else{ printk("BUG DELETE deleted Wrong entry? : %d flag is %d\n", index, cache_entry->flag); BUG_ON(!cache_entry); return -1; } } struct _cache_entry * zebra_find_free_slot(){ struct _cache_entry *evict_entry = NULL; #ifdef EVICTION_POLICY_RANDOM long index = get_random_int() % cache_size; evict_entry = &lra_head[index]; #else evict_entry = &lra_head[lra_ptr]; lra_ptr = (lra_ptr + 1) % cache_size; #endif while(evict_entry->flag == RESERVED){ #ifdef EVICTION_POLICY_RANDOM index = get_random_int() % cache_size; evict_entry = &lra_head[index]; #else lra_ptr = (lra_ptr + 1) % cache_size; evict_entry = &lra_head[lra_ptr]; #endif } return evict_entry; } int zebra_update_cache(u32 index, struct page *page){ int ret = -1; struct _cache_entry *cache_entry = NULL; // struct page *page = NULL; struct page * cache_page = NULL; void *user_mem = NULL; void *cache_mem = NULL; cache_entry = zebra_lookup_cache_page(index); if(cache_entry && (cache_entry->flag != RESERVED)) { // page = bvec->bv_page; cache_page = cache_entry->page; cache_mem = kmap_atomic(cache_page); user_mem = kmap_atomic(page); memcpy(cache_mem, user_mem, PAGE_SIZE); kunmap_atomic(user_mem); kunmap_atomic(cache_mem); cache_entry->flag = VALID; cache_entry->dirty = 1; ret = 0; } return ret; } int zebra_insert_cache_page(struct _cache_entry *cache_entry, struct page *page, u32 index, int write) { struct _cache_entry *tmp_cache_entry = NULL; // struct page *page = NULL; struct page * cache_page = NULL; void *user_mem = NULL; void *cache_mem = NULL; //printk("Inserting %d == %d (blkid %d)\n", index, cache_entry->page->index, cache_entry->blkid); if((cache_entry->flag != RESERVED) && (cache_entry->flag != EMPTY) ){ printk("BUG INSERT? ??? index = %d, flag = %d (blkid %d)\n", index, cache_entry->flag, cache_entry->blkid); BUG_ON(cache_entry->flag != RESERVED); } // page = bvec->bv_page; cache_page = cache_entry->page; cache_mem = kmap_atomic(cache_page); user_mem = kmap_atomic(page); memcpy(cache_mem, user_mem, PAGE_SIZE); kunmap_atomic(user_mem); kunmap_atomic(cache_mem); cache_entry->page->index = index; cache_entry->blkid = index; cache_entry->flag = VALID; cache_entry->dirty = write; // (radix_tree_preload(GFP_NOIO)) ??? /* if (radix_tree_preload(GFP_ATOMIC)) { printk("ERROR: radix_tree_preload failed inside flush_to_disk\n"); return -1; } */ if (radix_tree_insert(&zebra_cache.pages, index, cache_entry)) { printk("BUG INSERT ERROR %u == %u (blkid %u)\n", (unsigned int) index, (unsigned int)cache_entry->page->index, (unsigned int)cache_entry->blkid); tmp_cache_entry = radix_tree_lookup(&zebra_cache.pages, index); BUG_ON(!tmp_cache_entry); BUG_ON(!tmp_cache_entry->page); BUG_ON(tmp_cache_entry->page->index != index); } // radix_tree_preload_end(); return 0; } int zebra_read_from_cache(u32 index, struct page *page){ int ret = -1; struct _cache_entry *cache_entry = NULL; // struct page *page = NULL; struct page * cache_page = NULL; void *user_mem = NULL; void *cache_mem = NULL; cache_entry = zebra_lookup_cache_page(index); if(cache_entry && (cache_entry->flag == VALID)){ // page = bvec->bv_page; cache_page = cache_entry->page; user_mem = kmap_atomic(page); cache_mem = kmap_atomic(cache_page); memcpy(user_mem , cache_mem, PAGE_SIZE); kunmap_atomic(user_mem); kunmap_atomic(cache_mem); ret = 0; } return ret; }
19938.c
/* * File : LCD_Program.c * Description : This file includes LCD Driver implementations for Atmega32 * Author : Ahmed Elmogy Embedded SW Engineer * Date : 5/2/2020 * Git account : https://github.com/AhmedElmougy * mail : [email protected] */ #include "LSTD_Types.h" #include "LUTILS.h" #include "LMath_Interface.h" #include "LDELAY_Interface.h" #include "MDIO_Interface.h" #include "HLCD_Privte.h" #include "HLCD_Config.h" #include "HLCD_Interface.h" /*============================================================================================================================================== * Global variables *==============================================================================================================================================*/ /*Initialize display with cursor and display enabled*/ u8 DisplayAndCursorCommand = 0b00001111; /*initialize font size with 7 Dot size, 2 lines and, 4Bit Modes */ u8 FontSizeAndLineCommand = 0b00101000; /*============================================================================================================================================== * Private Modules *==============================================================================================================================================*/ static void HLCD_voidWriteCommand(u8 Copy_u8Command); static void HLCD_voidWriteData(u8 Copy_u8Data); /*============================================================================================================================================== * Public Modules *==============================================================================================================================================*/ /*================================================================================================= * 8 Bit Mode *=================================================================================================*/ #if (HLCD_MODE == HLCD_8BIT) /* * Prototype : u8 HLCD_voidWriteCommand(u8 Copy_u8Command); * Description : write command to LCD * Arguments : u8 Command * return : void */ void HLCD_voidWriteCommand(u8 Copy_u8Command) { /*Set RW pin 0 (Write Mode selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RW,MDIO_LOW) ; /*Set RS pin 0 (Instruction register selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RS,MDIO_LOW) ; /*output instruction data to Data Bus*/ switch(Copy_u8Command) { /*if command value is 1 clear data register and output 1 to it*/ case 1 : { MDIO_u8WriteReg(DataREG,MDIO_LOW); MDIO_u8WriteBit(DataREG,HLCD_DATA_REG_PIN0,MDIO_HIGH); } break; /*else output command to data register*/ default : { MDIO_u8WriteReg(DataREG,Copy_u8Command); } }/*end of switch case*/ /*Set EN pin 1 (LCD Read data )*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH); //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW) ; }/*end of HLCD_u8WriteCommand()*/ /* * Prototype : void HLCD_voidWriteData(u8 Copy_u8Data); * Description : write Data to LCD * Arguments : u8 Data * return : void */ void HLCD_voidWriteData(u8 Copy_u8Data) { /*Set RW pin 0 (Write Mode selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RW,MDIO_LOW); /*Set RS pin 1 (Data register selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RS,MDIO_HIGH); /*output data to Data Bus*/ /*output instruction data to Data Bus*/ switch(Copy_u8Data) { /*if Data value is 1 clear data register and output 1 to it*/ case 1 : { MDIO_u8WriteReg(DataREG,MDIO_LOW); MDIO_u8WriteBit(DataREG,HLCD_DATA_REG_PIN0,MDIO_HIGH); } break; /*else output Data to data register*/ default : { MDIO_u8WriteReg(DataREG,Copy_u8Data); } }/*end of switch case*/ /*Set EN pin 1 (LCD Read data )*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH); //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW); }/*end of HLCD_u8WriteData()*/ /*================================================================================================= * 4 Bit Mode *=================================================================================================*/ #elif (HLCD_MODE == HLCD_4BIT) /* * Prototype : u8 HLCD_voidWriteCommand(u8 Copy_u8Command); * Description : write command to LCD * Arguments : u8 Command * return : void */ void HLCD_voidWriteCommand(u8 Copy_u8Data) { /*Set RW pin 0 (Write Mode selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RW,MDIO_LOW) ; /*Set RS pin 0 (Instruction register selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RS,MDIO_LOW) ; /*output first 4 bits instruction data to Data Bus*/ for(u8 i=4;i<8;i++) { /*Output value of Instruction bit i at Data Register DIO Pin i*/ MDIO_u8WriteBit(DataREG,i,L_UTILS_GET_BIT(Copy_u8Data,i)); } /*latch sent data*/ /*Set EN pin 1 (LCD Read data )*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH) ; //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW) ; /*output second 4 bits instruction to data bus*/ for(u8 i=0;i<4;i++) { /*Output value of Instruction bit i at Data Register DIO Pin i*/ MDIO_u8WriteBit(DataREG,i+4,L_UTILS_GET_BIT(Copy_u8Data,i)); } /*latch sent data*/ /*Set EN pin 1 (LCD Read data )*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH) ; //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW) ; }/*end of HLCD_voidWriteCommand()*/ /* * Prototype : void HLCD_voidWriteData(u8 Copy_u8Data); * Description : write Data to LCD * Arguments : u8 Data * return : void */ void HLCD_voidWriteData(u8 Copy_u8Data) { /*Set RW pin 0 (Write Mode selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RW,MDIO_LOW) ; /*Set RS pin 1 (Data register selected)*/ MDIO_u8WriteBit(ContREG,HLCD_RS,MDIO_HIGH) ; /*output first 4 Data bits to Data Bus*/ for(u8 i=4;i<8;i++) { /*Output value of Data bit i at Data register DIO Pin i*/ MDIO_u8WriteBit(DataREG,i,L_UTILS_GET_BIT(Copy_u8Data,i)); } /*latch sent data*/ /*Set EN pin 1 (LCD Read data )*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH) ; //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW) ; /*output second 4 bits Data to data bus*/ for(u8 i=0;i<4;i++) { /*Output value of Data bit i at Data register DIO Pin i*/ MDIO_u8WriteBit(DataREG,i+4,L_UTILS_GET_BIT(Copy_u8Data,i)); } /*latch sent data*/ /*Set EN pin 1 (LCD Read data)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_HIGH) ; //_delay_ms(2); LDelay_voidDelay_ms(2); /*Set EN pin 0 (LCD Write data to its reg)*/ MDIO_u8WriteBit(ContREG,HLCD_EN,MDIO_LOW) ; }/*end of HLCD_voidWriteData()*/ #endif /*end of Mode select*/ /* * Prototype : void HLCD_voidInitializeLCD(void); * Description : Initialize LCD in a desired data and control registers * in 4 bit mode control and data register must be the same register * Arguments : void * return : void */ void HLCD_voidInitializeLCD(void) { /*============================================================== * Configure LCD pins direction *==============================================================*/ /*Configure RS Pin output*/ MDIO_u8SetDirectionBit(ContREG,HLCD_RS,MDIO_OUTPUT); /*Configure RW Pin output*/ MDIO_u8SetDirectionBit(ContREG,HLCD_RW,MDIO_OUTPUT); /*Configure EN Pin output*/ MDIO_u8SetDirectionBit(ContREG,HLCD_EN,MDIO_OUTPUT); /*Configure Data register output*/ MDIO_u8SetDirectionReg(DataREG,MDIO_OUTPUT); //_delay_ms(50); LDelay_voidDelay_ms(50); /*============================================================== * Choose font size and number of lines *==============================================================*/ /*Set Font size value 5*7 dots or 5*10 dots*/ L_UTILS_SET_BIT_VALUE(FontSizeAndLineCommand,HLCD_FONT_BIT,HLCD_FONT_SIZE); /*Set number of lines 1 or 2*/ L_UTILS_SET_BIT_VALUE(FontSizeAndLineCommand,HLCD_LINE_BIT,HLCD_LINE_MODE); /*============================================================== * LCD initialization sequence *============================================================== * 8Bit Mode initialization *====================================*/ #if (HLCD_MODE == HLCD_8BIT) /*Choose 8Bit mode in function set instruction*/ L_UTILS_SET_BIT(FontSizeAndLineCommand,HLCD_DATALENGTH_BIT); /*send Function set instruction*/ HLCD_voidWriteCommand(FontSizeAndLineCommand); //_delay_ms(1); LDelay_voidDelay_ms(1); /*==================================== * 4Bit Mode initialization *====================================*/ #elif (HLCD_MODE == HLCD_4BIT) /*send 4BIT Function set instruction two times*/ HLCD_voidWriteCommand(HLCD_FN_SET_4BIT); /*send Function set instruction for font and number of lines*/ HLCD_voidWriteCommand(FontSizeAndLineCommand); //_delay_ms(1); LDelay_voidDelay_ms(1); #endif /*send Display ON OFF instruction*/ HLCD_voidWriteCommand(DisplayAndCursorCommand); //_delay_ms(1); LDelay_voidDelay_ms(1); /*send Display clear instruction*/ HLCD_voidWriteCommand(HLCD_DISP_CLEAR); //_delay_ms(2); LDelay_voidDelay_ms(2); /*send ENTRY MODE set instruction*/ HLCD_voidWriteCommand(HLCD_ENTRY_MODE); //_delay_ms(2); LDelay_voidDelay_ms(2); /*============================================================================= * Initialize custom made characters with pre-configured arrays' values *=============================================================================*/ /*jump to CGRAM address*/ HLCD_voidWriteCommand(HLCD_CGRAM_ADDRESS); /*fill GCRAM with HLCD_u8CustomCharArray values*/ for (u8 i = 0 ; i < 8 ; i++) { for (u8 j = 0 ; j < 8 ; j++) { HLCD_voidWriteData(HLCD_u8CustomCharArray[i][j]); }/*end of j loop*/ }/*end of i loop*/ /*return to DDRAM address 1*/ HLCD_voidWriteCommand(HLCD_DDRAM_ADD1); }/*end of HLCD_u8InitializeLCD()*/ /* * Prototype : void HLCD_voidClearLCD(void); * Description : clear LCD and return cursor to first position * Arguments : void * return : void */ void HLCD_voidClearLCD(void) { /*send Display clear instruction*/ HLCD_voidWriteCommand(HLCD_DISP_CLEAR); }/*end of HLCD_voidClearLCD()*/ /* * Prototype : void HLCD_voidReturnHome(void); * Description : return cursor to first position LCD content doesn't affect * Arguments : void * return : void */ void HLCD_voidReturnHome(void) { /*send Return home instruction*/ HLCD_voidWriteCommand(HLCD_RET_HOME); }/*end of HLCD_voidReturnHome()*/ /* * Prototype : void HLCD_voidSelectLine(u8 Copy_u8Line); * Description : Select line 1 or 2 in LCD * Arguments : choose line from (HLCD_LINE1 or HLCD_LINE2) * return : void */ void HLCD_voidSelectLine(u8 Copy_u8Line) { /*choose line*/ switch(Copy_u8Line) { case HLCD_LINE1 : { HLCD_voidWriteCommand(HLCD_DDRAM_ADD1); } break; case HLCD_LINE2 : { HLCD_voidWriteCommand(HLCD_DDRAM_ADD2); } break; }/*end of line switch case*/ }/*end of HLCD_voidSelectLine()*/ /* * Prototype : void HLCD_voidSetCursorPosition(u8 Copy_u8Line,u8 Copy_u8Position); * Description : set cursor in specific position (choose line and position in line from 1 to 16) * Arguments : line HLCD_LINE1 or HLCD_LINE2 * Position from 1 to 16 * return : void */ void HLCD_voidSetCursorPosition(u8 Copy_u8Line,u8 Copy_u8Position) { /*choose line*/ switch(Copy_u8Line) { case HLCD_LINE1 : { HLCD_voidWriteCommand(HLCD_DDRAM_ADD1+ Copy_u8Position -1); } break; case HLCD_LINE2 : { HLCD_voidWriteCommand(HLCD_DDRAM_ADD2+ Copy_u8Position -1); } break; }/*end of line switch case*/ }/*end of HLCD_voidSetCursorPosition()*/ /* * Prototype : void HLCD_voidDisplayChar(u8 Copy_u8CharData); * Description : Output character to current cursor position * Arguments : Char_Data : Character to be displayed a number (0-9) or a character * return : void */ void HLCD_voidDisplayChar(u8 Copy_u8CharData) { /*check character type*/ if( (Copy_u8CharData >= 0) && (Copy_u8CharData < 10) ) { /*if character is number*/ HLCD_voidWriteData((Copy_u8CharData+'0')); } else { /*if character is char*/ HLCD_voidWriteData(Copy_u8CharData); }/*end of character type check*/ }/*end of HLCD_voidDisplayChar*/ /* * Prototype : void HLCD_voidDisplayChar(u8 Copy_u8CharData); * Description : Output String or a number to LCD at current cursor position * Arguments : DataPointer: pointer to data stream to be displayed it could be * - Number of type u32 but function can handle up to 10 digit number (0,1,...,4294967296) * - u8 character string * Data type: HLCD_NUMBER or HLCD_STRING * return : void */ void HLCD_voidDisplayString(u32 *Copy_u32StringDataPtr,u8 Copy_u8DataType) { /*String pointer*/ u8 *Local_u8StringData = (u8 *)Copy_u32StringDataPtr; /*single digit*/ u8 Local_u8Digit = 0; /*number value*/ u32 Local_u32NumberValue = 0; /*remainder used in number display calculations*/ u32 Local_u32Remainder = 0; /*check data type*/ if (Copy_u8DataType == HLCD_NUMBER) /*number type check*/ { /*store number value to be displayed*/ Local_u32NumberValue = *Copy_u32StringDataPtr; /*if number is zero*/ if (Local_u32NumberValue == 0) { /*display zero*/ HLCD_voidDisplayChar(Local_u8Digit); } else { /*loop each digit in number*/ for (u8 i=0;i<10;i++) { /*check if that digit 10^i exists starting from 10th digit until first existent digit reached*/ if ( (Local_u32NumberValue / LMATH_u32GetExponential( 10 , (9-i))) != 0) { /*if first digit found loop number digits*/ for (u8 j=i;j<10;j++) { /*get current value and display it*/ /*calculate remaining digits to be displayed*/ Local_u32Remainder = Local_u32NumberValue % LMATH_u32GetExponential(10,(9-j)); /*calculate current digit*/ Local_u8Digit = Local_u32NumberValue / LMATH_u32GetExponential(10,(9-j)); /*prepare number value with remaining digits*/ Local_u32NumberValue = Local_u32Remainder; /*display current digit*/ HLCD_voidDisplayChar(Local_u8Digit); }/*end of number digits for loop*/ break; /*exit loop*/ }/*end of digits existence check*/ }/*end of digits loop*/ }/*end of zero check*/ } else if(Copy_u8DataType == HLCD_STRING)/*string type check*/ { /*check if null char reached*/ while(*Local_u8StringData!='\0') { /*display current char in string*/ HLCD_voidDisplayChar(*Local_u8StringData++); }/*end of string loop*/ }/*end of type check*/ }/*end of */ /* * Prototype : void HLCD_voidShiftRight(void); * Description : Shift all display right one step * Arguments : void * return : void */ void HLCD_voidShiftRight(void) { /*send shift right instruction*/ HLCD_voidWriteCommand(HLCD_DISP_SHIFT_RIGHT); }/*end of HLCD_voidShiftRight()*/ /* * Prototype : void HLCD_voidShiftLeft(void); * Description : Shift all display left one step * Arguments : void * return : void */ void HLCD_voidShiftLeft(void) { /*send shift left instruction*/ HLCD_voidWriteCommand(HLCD_DISP_SHIFT_LEFT); }/*end of HLCD_voidShiftLeft()*/ /* * Prototype : void HLCD_voidCursorShiftRight(u8 Copy_u8Steps); * Description : shift cursor position number of steps right * Arguments : Number of Steps * return : void */ void HLCD_voidCursorShiftRight(u8 Copy_u8Steps) { /*loop steps*/ for(u8 i = 0 ; i < Copy_u8Steps ; i++) { /*Shift cursor one step right instruction*/ HLCD_voidWriteCommand(HLCD_CURSOR_SHIFT_RIGHT); }/*end of steps for loop*/ }/*end of HLCD_voidCursorShiftRight()*/ /* * Prototype : void HLCD_voidCursorShiftLeft(u8 Copy_u8Steps); * Description : shift cursor position number of steps Left * Arguments : Number of Steps * return : void */ void HLCD_voidCursorShiftLeft(u8 Copy_u8Steps) { /*loop steps*/ for(u8 i = 0 ; i < Copy_u8Steps ; i++) { /*Shift cursor one step Left instruction*/ HLCD_voidWriteCommand(HLCD_CURSOR_SHIFT_LEFT); }/*end of steps for loop*/ }/*end of HLCD_voidCursorShiftLeft()*/ /* * Prototype : void HLCD_voidCursorDisplayOnOff(u8 Copy_u8Status); * Description : set cursor display on and off * Arguments : Status : HLCD_ON or HLCD_OFF * return : void */ void HLCD_voidCursorDisplayOnOff(u8 Copy_u8Status) { /*Set Display status value (on or off)*/ L_UTILS_SET_BIT_VALUE(DisplayAndCursorCommand,HLCD_CURSOR_BIT,Copy_u8Status); /*Send command*/ HLCD_voidWriteCommand(DisplayAndCursorCommand); }/*end of HLCD_voidCursorDisplayOnOff()*/ /* * Prototype : void HLCD_voidCursorBlinkOnOff(u8 Copy_u8Status); * Description : set cursor blinking on and off * Arguments : Status : HLCD_ON or HLCD_OFF * return : void */ void HLCD_voidCursorBlinkOnOff(u8 Copy_u8Status) { /*Set Cursor status value (on or off)*/ L_UTILS_SET_BIT_VALUE(DisplayAndCursorCommand,HLCD_BLINK_BIT,Copy_u8Status); /*Send command*/ HLCD_voidWriteCommand(DisplayAndCursorCommand); }/*end of HLCD_voidCursorBlinkOnOff()*/ /* * Prototype : void HLCD_voidScreenDisplayOnOff(u8 Copy_u8Status); * Description : set Whole display on & off * Arguments : Status : HLCD_ON or HLCD_OFF * return : void */ void HLCD_voidScreenDisplayOnOff(u8 Copy_u8Status) { /*Set Display status value (on or off)*/ L_UTILS_SET_BIT_VALUE(DisplayAndCursorCommand,HLCD_DISP_BIT,Copy_u8Status); /*Send command*/ HLCD_voidWriteCommand(DisplayAndCursorCommand); }/*end of HLCD_voidDisplayOnOff()*/ /* * Prototype : void HLCD_voidDisplayCustomChar(u8 Copy_SlotNumber); * Description : use custom character from CGRAM * Arguments : slot number : from (HLCD_CUST_CHAR_1, HLCD_CUST_CHAR_2,...HLCD_CUST_CHAR_8) * return : void */ void HLCD_voidDisplayCustomChar(u8 Copy_SlotNumber) { /*slot in range check*/ if ( (Copy_SlotNumber >= 0) && (Copy_SlotNumber<8) ) { /*Display Custom character in that slot*/ HLCD_voidWriteData(Copy_SlotNumber); }/*end of slot number range check*/ }/*end of HLCD_voidDisplayCustomChar()*/ /*============================================================================================================================================== * EOF *==============================================================================================================================================*/
873234.c
#include "header.h" void init(List *list) { // Fungsi untuk membuat list kosong list->top = NULL; list->_size = 0; }
246905.c
/*------------------------------------------------------------------------- * * vacuumlazy.c * Concurrent ("lazy") vacuuming. * * * The major space usage for LAZY VACUUM is storage for the array of dead * tuple TIDs, with the next biggest need being storage for per-disk-page * free space info. We want to ensure we can vacuum even the very largest * relations with finite memory space usage. To do that, we set upper bounds * on the number of tuples and pages we will keep track of at once. * * We are willing to use at most maintenance_work_mem (or perhaps * autovacuum_work_mem) memory space to keep track of dead tuples. We * initially allocate an array of TIDs of that size, with an upper limit that * depends on table size (this limit ensures we don't allocate a huge area * uselessly for vacuuming small tables). If the array threatens to overflow, * we suspend the heap scan phase and perform a pass of index cleanup and page * compaction, then resume the heap scan with an empty TID array. * * If we're processing a table with no indexes, we can just vacuum each page * as we go; there's no need to save up multiple tuples to minimize the number * of index scans performed. So we don't use maintenance_work_mem memory for * the TID array, just enough to hold as many heap tuples as fit on one page. * * * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/commands/vacuumlazy.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include <math.h> #include "access/genam.h" #include "access/heapam.h" #include "access/heapam_xlog.h" #include "access/htup_details.h" #include "access/multixact.h" #include "access/transam.h" #include "access/visibilitymap.h" #include "access/xlog.h" #include "catalog/catalog.h" #include "catalog/storage.h" #include "commands/dbcommands.h" #include "commands/progress.h" #include "commands/vacuum.h" #include "miscadmin.h" #include "pgstat.h" #include "portability/instr_time.h" #include "postmaster/autovacuum.h" #include "storage/bufmgr.h" #include "storage/freespace.h" #include "storage/lmgr.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/pg_rusage.h" #include "utils/timestamp.h" #include "utils/tqual.h" /* * Space/time tradeoff parameters: do these need to be user-tunable? * * To consider truncating the relation, we want there to be at least * REL_TRUNCATE_MINIMUM or (relsize / REL_TRUNCATE_FRACTION) (whichever * is less) potentially-freeable pages. */ #define REL_TRUNCATE_MINIMUM 1000 #define REL_TRUNCATE_FRACTION 16 /* * Timing parameters for truncate locking heuristics. * * These were not exposed as user tunable GUC values because it didn't seem * that the potential for improvement was great enough to merit the cost of * supporting them. */ #define VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL 20 /* ms */ #define VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL 50 /* ms */ #define VACUUM_TRUNCATE_LOCK_TIMEOUT 5000 /* ms */ /* * Guesstimation of number of dead tuples per page. This is used to * provide an upper limit to memory allocated when vacuuming small * tables. */ #define LAZY_ALLOC_TUPLES MaxHeapTuplesPerPage /* * Before we consider skipping a page that's marked as clean in * visibility map, we must've seen at least this many clean pages. */ #define SKIP_PAGES_THRESHOLD ((BlockNumber) 32) typedef struct LVRelStats { /* hasindex = true means two-pass strategy; false means one-pass */ bool hasindex; /* Overall statistics about rel */ BlockNumber old_rel_pages; /* previous value of pg_class.relpages */ BlockNumber rel_pages; /* total number of pages */ BlockNumber scanned_pages; /* number of pages we examined */ BlockNumber pinskipped_pages; /* # of pages we skipped due to a pin */ BlockNumber frozenskipped_pages; /* # of frozen pages we skipped */ double scanned_tuples; /* counts only tuples on scanned pages */ double old_rel_tuples; /* previous value of pg_class.reltuples */ double new_rel_tuples; /* new estimated total # of tuples */ double new_dead_tuples; /* new estimated total # of dead tuples */ BlockNumber pages_removed; double tuples_deleted; BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */ /* List of TIDs of tuples we intend to delete */ /* NB: this list is ordered by TID address */ int num_dead_tuples; /* current # of entries */ int max_dead_tuples; /* # slots allocated in array */ ItemPointer dead_tuples; /* array of ItemPointerData */ int num_index_scans; TransactionId latestRemovedXid; bool lock_waiter_detected; } LVRelStats; /* A few variables that don't seem worth passing around as parameters */ static int elevel = -1; static TransactionId OldestXmin; static TransactionId FreezeLimit; static MultiXactId MultiXactCutoff; static BufferAccessStrategy vac_strategy; /* non-export function prototypes */ static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive); static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats); static bool lazy_check_needs_freeze(Buffer buf, bool *hastup); static void lazy_vacuum_index(Relation indrel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats); static void lazy_cleanup_index(Relation indrel, IndexBulkDeleteResult *stats, LVRelStats *vacrelstats); static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer); static bool should_attempt_truncation(LVRelStats *vacrelstats); static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats); static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats); static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks); static void lazy_record_dead_tuple(LVRelStats *vacrelstats, ItemPointer itemptr); static bool lazy_tid_reaped(ItemPointer itemptr, void *state); static int vac_cmp_itemptr(const void *left, const void *right); static bool heap_page_is_all_visible(Relation rel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen); /* * lazy_vacuum_rel() -- perform LAZY VACUUM for one heap relation * * This routine vacuums a single heap, cleans out its indexes, and * updates its relpages and reltuples statistics. * * At entry, we have already established a transaction and opened * and locked the relation. */ void lazy_vacuum_rel(Relation onerel, int options, VacuumParams *params, BufferAccessStrategy bstrategy) { LVRelStats *vacrelstats; Relation *Irel; int nindexes; PGRUsage ru0; TimestampTz starttime = 0; long secs; int usecs; double read_rate, write_rate; bool aggressive; /* should we scan all unfrozen pages? */ bool scanned_all_unfrozen; /* actually scanned all such pages? */ TransactionId xidFullScanLimit; MultiXactId mxactFullScanLimit; BlockNumber new_rel_pages; double new_rel_tuples; BlockNumber new_rel_allvisible; double new_live_tuples; TransactionId new_frozen_xid; MultiXactId new_min_multi; Assert(params != NULL); /* measure elapsed time iff autovacuum logging requires it */ if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0) { pg_rusage_init(&ru0); starttime = GetCurrentTimestamp(); } if (options & VACOPT_VERBOSE) elevel = INFO; else elevel = DEBUG2; pgstat_progress_start_command(PROGRESS_COMMAND_VACUUM, RelationGetRelid(onerel)); vac_strategy = bstrategy; vacuum_set_xid_limits(onerel, params->freeze_min_age, params->freeze_table_age, params->multixact_freeze_min_age, params->multixact_freeze_table_age, &OldestXmin, &FreezeLimit, &xidFullScanLimit, &MultiXactCutoff, &mxactFullScanLimit); /* * We request an aggressive scan if either the table's frozen Xid is now * older than or equal to the requested Xid full-table scan limit; or if * the table's minimum MultiXactId is older than or equal to the requested * mxid full-table scan limit. */ aggressive = TransactionIdPrecedesOrEquals(onerel->rd_rel->relfrozenxid, xidFullScanLimit); aggressive |= MultiXactIdPrecedesOrEquals(onerel->rd_rel->relminmxid, mxactFullScanLimit); vacrelstats = (LVRelStats *) palloc0(sizeof(LVRelStats)); vacrelstats->old_rel_pages = onerel->rd_rel->relpages; vacrelstats->old_rel_tuples = onerel->rd_rel->reltuples; vacrelstats->num_index_scans = 0; vacrelstats->pages_removed = 0; vacrelstats->lock_waiter_detected = false; /* Open all indexes of the relation */ vac_open_indexes(onerel, RowExclusiveLock, &nindexes, &Irel); vacrelstats->hasindex = (nindexes > 0); /* Do the vacuuming */ lazy_scan_heap(onerel, vacrelstats, Irel, nindexes, aggressive); /* Done with indexes */ vac_close_indexes(nindexes, Irel, NoLock); /* * Compute whether we actually scanned the whole relation. If we did, we * can adjust relfrozenxid and relminmxid. * * NB: We need to check this before truncating the relation, because that * will change ->rel_pages. */ if ((vacrelstats->scanned_pages + vacrelstats->frozenskipped_pages) < vacrelstats->rel_pages) { Assert(!aggressive); scanned_all_unfrozen = false; } else scanned_all_unfrozen = true; /* * Optionally truncate the relation. */ if (should_attempt_truncation(vacrelstats)) lazy_truncate_heap(onerel, vacrelstats); /* Report that we are now doing final cleanup */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_FINAL_CLEANUP); /* Vacuum the Free Space Map */ FreeSpaceMapVacuum(onerel); /* * Update statistics in pg_class. * * A corner case here is that if we scanned no pages at all because every * page is all-visible, we should not update relpages/reltuples, because * we have no new information to contribute. In particular this keeps us * from replacing relpages=reltuples=0 (which means "unknown tuple * density") with nonzero relpages and reltuples=0 (which means "zero * tuple density") unless there's some actual evidence for the latter. * * We do update relallvisible even in the corner case, since if the table * is all-visible we'd definitely like to know that. But clamp the value * to be not more than what we're setting relpages to. * * Also, don't change relfrozenxid/relminmxid if we skipped any pages, * since then we don't know for certain that all tuples have a newer xmin. */ new_rel_pages = vacrelstats->rel_pages; new_rel_tuples = vacrelstats->new_rel_tuples; if (vacrelstats->scanned_pages == 0 && new_rel_pages > 0) { new_rel_pages = vacrelstats->old_rel_pages; new_rel_tuples = vacrelstats->old_rel_tuples; } visibilitymap_count(onerel, &new_rel_allvisible, NULL); if (new_rel_allvisible > new_rel_pages) new_rel_allvisible = new_rel_pages; new_frozen_xid = scanned_all_unfrozen ? FreezeLimit : InvalidTransactionId; new_min_multi = scanned_all_unfrozen ? MultiXactCutoff : InvalidMultiXactId; vac_update_relstats(onerel, new_rel_pages, new_rel_tuples, new_rel_allvisible, vacrelstats->hasindex, new_frozen_xid, new_min_multi, false); /* report results to the stats collector, too */ new_live_tuples = new_rel_tuples - vacrelstats->new_dead_tuples; if (new_live_tuples < 0) new_live_tuples = 0; /* just in case */ pgstat_report_vacuum(RelationGetRelid(onerel), onerel->rd_rel->relisshared, new_live_tuples, vacrelstats->new_dead_tuples); pgstat_progress_end_command(); /* and log the action if appropriate */ if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0) { TimestampTz endtime = GetCurrentTimestamp(); if (params->log_min_duration == 0 || TimestampDifferenceExceeds(starttime, endtime, params->log_min_duration)) { StringInfoData buf; TimestampDifference(starttime, endtime, &secs, &usecs); read_rate = 0; write_rate = 0; if ((secs > 0) || (usecs > 0)) { read_rate = (double) BLCKSZ *VacuumPageMiss / (1024 * 1024) / (secs + usecs / 1000000.0); write_rate = (double) BLCKSZ *VacuumPageDirty / (1024 * 1024) / (secs + usecs / 1000000.0); } /* * This is pretty messy, but we split it up so that we can skip * emitting individual parts of the message when not applicable. */ initStringInfo(&buf); appendStringInfo(&buf, _("automatic vacuum of table \"%s.%s.%s\": index scans: %d\n"), get_database_name(MyDatabaseId), get_namespace_name(RelationGetNamespace(onerel)), RelationGetRelationName(onerel), vacrelstats->num_index_scans); appendStringInfo(&buf, _("pages: %u removed, %u remain, %u skipped due to pins, %u skipped frozen\n"), vacrelstats->pages_removed, vacrelstats->rel_pages, vacrelstats->pinskipped_pages, vacrelstats->frozenskipped_pages); appendStringInfo(&buf, _("tuples: %.0f removed, %.0f remain, %.0f are dead but not yet removable\n"), vacrelstats->tuples_deleted, vacrelstats->new_rel_tuples, vacrelstats->new_dead_tuples); appendStringInfo(&buf, _("buffer usage: %d hits, %d misses, %d dirtied\n"), VacuumPageHit, VacuumPageMiss, VacuumPageDirty); appendStringInfo(&buf, _("avg read rate: %.3f MB/s, avg write rate: %.3f MB/s\n"), read_rate, write_rate); appendStringInfo(&buf, _("system usage: %s"), pg_rusage_show(&ru0)); ereport(LOG, (errmsg_internal("%s", buf.data))); pfree(buf.data); } } } /* * For Hot Standby we need to know the highest transaction id that will * be removed by any change. VACUUM proceeds in a number of passes so * we need to consider how each pass operates. The first phase runs * heap_page_prune(), which can issue XLOG_HEAP2_CLEAN records as it * progresses - these will have a latestRemovedXid on each record. * In some cases this removes all of the tuples to be removed, though * often we have dead tuples with index pointers so we must remember them * for removal in phase 3. Index records for those rows are removed * in phase 2 and index blocks do not have MVCC information attached. * So before we can allow removal of any index tuples we need to issue * a WAL record containing the latestRemovedXid of rows that will be * removed in phase three. This allows recovery queries to block at the * correct place, i.e. before phase two, rather than during phase three * which would be after the rows have become inaccessible. */ static void vacuum_log_cleanup_info(Relation rel, LVRelStats *vacrelstats) { /* * Skip this for relations for which no WAL is to be written, or if we're * not trying to support archive recovery. */ if (!RelationNeedsWAL(rel) || !XLogIsNeeded()) return; /* * No need to write the record at all unless it contains a valid value */ if (TransactionIdIsValid(vacrelstats->latestRemovedXid)) (void) log_heap_cleanup_info(rel->rd_node, vacrelstats->latestRemovedXid); } /* * lazy_scan_heap() -- scan an open heap relation * * This routine prunes each page in the heap, which will among other * things truncate dead tuples to dead line pointers, defragment the * page, and set commit status bits (see heap_page_prune). It also builds * lists of dead tuples and pages with free space, calculates statistics * on the number of live tuples in the heap, and marks pages as * all-visible if appropriate. When done, or when we run low on space for * dead-tuple TIDs, invoke vacuuming of indexes and call lazy_vacuum_heap * to reclaim dead line pointers. * * If there are no indexes then we can reclaim line pointers on the fly; * dead line pointers need only be retained until all index pointers that * reference them have been killed. */ static void lazy_scan_heap(Relation onerel, LVRelStats *vacrelstats, Relation *Irel, int nindexes, bool aggressive) { BlockNumber nblocks, blkno; HeapTupleData tuple; char *relname; BlockNumber empty_pages, vacuumed_pages; double num_tuples, tups_vacuumed, nkeep, nunused; IndexBulkDeleteResult **indstats; int i; PGRUsage ru0; Buffer vmbuffer = InvalidBuffer; BlockNumber next_unskippable_block; bool skipping_blocks; xl_heap_freeze_tuple *frozen; StringInfoData buf; const int initprog_index[] = { PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_TOTAL_HEAP_BLKS, PROGRESS_VACUUM_MAX_DEAD_TUPLES }; int64 initprog_val[3]; pg_rusage_init(&ru0); relname = RelationGetRelationName(onerel); ereport(elevel, (errmsg("vacuuming \"%s.%s\"", get_namespace_name(RelationGetNamespace(onerel)), relname))); empty_pages = vacuumed_pages = 0; num_tuples = tups_vacuumed = nkeep = nunused = 0; indstats = (IndexBulkDeleteResult **) palloc0(nindexes * sizeof(IndexBulkDeleteResult *)); nblocks = RelationGetNumberOfBlocks(onerel); vacrelstats->rel_pages = nblocks; vacrelstats->scanned_pages = 0; vacrelstats->nonempty_pages = 0; vacrelstats->latestRemovedXid = InvalidTransactionId; lazy_space_alloc(vacrelstats, nblocks); frozen = palloc(sizeof(xl_heap_freeze_tuple) * MaxHeapTuplesPerPage); /* Report that we're scanning the heap, advertising total # of blocks */ initprog_val[0] = PROGRESS_VACUUM_PHASE_SCAN_HEAP; initprog_val[1] = nblocks; initprog_val[2] = vacrelstats->max_dead_tuples; pgstat_progress_update_multi_param(3, initprog_index, initprog_val); /* * Except when aggressive is set, we want to skip pages that are * all-visible according to the visibility map, but only when we can skip * at least SKIP_PAGES_THRESHOLD consecutive pages. Since we're reading * sequentially, the OS should be doing readahead for us, so there's no * gain in skipping a page now and then; that's likely to disable * readahead and so be counterproductive. Also, skipping even a single * page means that we can't update relfrozenxid, so we only want to do it * if we can skip a goodly number of pages. * * When aggressive is set, we can't skip pages just because they are * all-visible, but we can still skip pages that are all-frozen, since * such pages do not need freezing and do not affect the value that we can * safely set for relfrozenxid or relminmxid. * * Before entering the main loop, establish the invariant that * next_unskippable_block is the next block number >= blkno that's not we * can't skip based on the visibility map, either all-visible for a * regular scan or all-frozen for an aggressive scan. We set it to * nblocks if there's no such block. We also set up the skipping_blocks * flag correctly at this stage. * * Note: The value returned by visibilitymap_get_status could be slightly * out-of-date, since we make this test before reading the corresponding * heap page or locking the buffer. This is OK. If we mistakenly think * that the page is all-visible or all-frozen when in fact the flag's just * been cleared, we might fail to vacuum the page. It's easy to see that * skipping a page when aggressive is not set is not a very big deal; we * might leave some dead tuples lying around, but the next vacuum will * find them. But even when aggressive *is* set, it's still OK if we miss * a page whose all-frozen marking has just been cleared. Any new XIDs * just added to that page are necessarily newer than the GlobalXmin we * computed, so they'll have no effect on the value to which we can safely * set relfrozenxid. A similar argument applies for MXIDs and relminmxid. * * We will scan the table's last page, at least to the extent of * determining whether it has tuples or not, even if it should be skipped * according to the above rules; except when we've already determined that * it's not worth trying to truncate the table. This avoids having * lazy_truncate_heap() take access-exclusive lock on the table to attempt * a truncation that just fails immediately because there are tuples in * the last page. This is worth avoiding mainly because such a lock must * be replayed on any hot standby, where it can be disruptive. */ for (next_unskippable_block = 0; next_unskippable_block < nblocks; next_unskippable_block++) { uint8 vmstatus; vmstatus = visibilitymap_get_status(onerel, next_unskippable_block, &vmbuffer); if (aggressive) { if ((vmstatus & VISIBILITYMAP_ALL_FROZEN) == 0) break; } else { if ((vmstatus & VISIBILITYMAP_ALL_VISIBLE) == 0) break; } vacuum_delay_point(); } if (next_unskippable_block >= SKIP_PAGES_THRESHOLD) skipping_blocks = true; else skipping_blocks = false; for (blkno = 0; blkno < nblocks; blkno++) { Buffer buf; Page page; OffsetNumber offnum, maxoff; bool tupgone, hastup; int prev_dead_count; int nfrozen; Size freespace; bool all_visible_according_to_vm = false; bool all_visible; bool all_frozen = true; /* provided all_visible is also true */ bool has_dead_tuples; TransactionId visibility_cutoff_xid = InvalidTransactionId; /* see note above about forcing scanning of last page */ #define FORCE_CHECK_PAGE() \ (blkno == nblocks - 1 && should_attempt_truncation(vacrelstats)) pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno); if (blkno == next_unskippable_block) { /* Time to advance next_unskippable_block */ for (next_unskippable_block++; next_unskippable_block < nblocks; next_unskippable_block++) { uint8 vmskipflags; vmskipflags = visibilitymap_get_status(onerel, next_unskippable_block, &vmbuffer); if (aggressive) { if ((vmskipflags & VISIBILITYMAP_ALL_FROZEN) == 0) break; } else { if ((vmskipflags & VISIBILITYMAP_ALL_VISIBLE) == 0) break; } vacuum_delay_point(); } /* * We know we can't skip the current block. But set up * skipping_all_visible_blocks to do the right thing at the * following blocks. */ if (next_unskippable_block - blkno > SKIP_PAGES_THRESHOLD) skipping_blocks = true; else skipping_blocks = false; /* * Normally, the fact that we can't skip this block must mean that * it's not all-visible. But in an aggressive vacuum we know only * that it's not all-frozen, so it might still be all-visible. */ if (aggressive && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer)) all_visible_according_to_vm = true; } else { /* * The current block is potentially skippable; if we've seen a * long enough run of skippable blocks to justify skipping it, and * we're not forced to check it, then go ahead and skip. * Otherwise, the page must be at least all-visible if not * all-frozen, so we can set all_visible_according_to_vm = true. */ if (skipping_blocks && !FORCE_CHECK_PAGE()) { /* * Tricky, tricky. If this is in aggressive vacuum, the page * must have been all-frozen at the time we checked whether it * was skippable, but it might not be any more. We must be * careful to count it as a skipped all-frozen page in that * case, or else we'll think we can't update relfrozenxid and * relminmxid. If it's not an aggressive vacuum, we don't * know whether it was all-frozen, so we have to recheck; but * in this case an approximate answer is OK. */ if (aggressive || VM_ALL_FROZEN(onerel, blkno, &vmbuffer)) vacrelstats->frozenskipped_pages++; continue; } all_visible_according_to_vm = true; } vacuum_delay_point(); /* * If we are close to overrunning the available space for dead-tuple * TIDs, pause and do a cycle of vacuuming before we tackle this page. */ if ((vacrelstats->max_dead_tuples - vacrelstats->num_dead_tuples) < MaxHeapTuplesPerPage && vacrelstats->num_dead_tuples > 0) { const int hvp_index[] = { PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_NUM_INDEX_VACUUMS }; int64 hvp_val[2]; /* * Before beginning index vacuuming, we release any pin we may * hold on the visibility map page. This isn't necessary for * correctness, but we do it anyway to avoid holding the pin * across a lengthy, unrelated operation. */ if (BufferIsValid(vmbuffer)) { ReleaseBuffer(vmbuffer); vmbuffer = InvalidBuffer; } /* Log cleanup info before we touch indexes */ vacuum_log_cleanup_info(onerel, vacrelstats); /* Report that we are now vacuuming indexes */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_INDEX); /* Remove index entries */ for (i = 0; i < nindexes; i++) lazy_vacuum_index(Irel[i], &indstats[i], vacrelstats); /* * Report that we are now vacuuming the heap. We also increase * the number of index scans here; note that by using * pgstat_progress_update_multi_param we can update both * parameters atomically. */ hvp_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_HEAP; hvp_val[1] = vacrelstats->num_index_scans + 1; pgstat_progress_update_multi_param(2, hvp_index, hvp_val); /* Remove tuples from heap */ lazy_vacuum_heap(onerel, vacrelstats); /* * Forget the now-vacuumed tuples, and press on, but be careful * not to reset latestRemovedXid since we want that value to be * valid. */ vacrelstats->num_dead_tuples = 0; vacrelstats->num_index_scans++; /* Report that we are once again scanning the heap */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_SCAN_HEAP); } /* * Pin the visibility map page in case we need to mark the page * all-visible. In most cases this will be very cheap, because we'll * already have the correct page pinned anyway. However, it's * possible that (a) next_unskippable_block is covered by a different * VM page than the current block or (b) we released our pin and did a * cycle of index vacuuming. * */ visibilitymap_pin(onerel, blkno, &vmbuffer); buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno, RBM_NORMAL, vac_strategy); /* We need buffer cleanup lock so that we can prune HOT chains. */ if (!ConditionalLockBufferForCleanup(buf)) { /* * If we're not performing an aggressive scan to guard against XID * wraparound, and we don't want to forcibly check the page, then * it's OK to skip vacuuming pages we get a lock conflict on. They * will be dealt with in some future vacuum. */ if (!aggressive && !FORCE_CHECK_PAGE()) { ReleaseBuffer(buf); vacrelstats->pinskipped_pages++; continue; } /* * Read the page with share lock to see if any xids on it need to * be frozen. If not we just skip the page, after updating our * scan statistics. If there are some, we wait for cleanup lock. * * We could defer the lock request further by remembering the page * and coming back to it later, or we could even register * ourselves for multiple buffers and then service whichever one * is received first. For now, this seems good enough. * * If we get here with aggressive false, then we're just forcibly * checking the page, and so we don't want to insist on getting * the lock; we only need to know if the page contains tuples, so * that we can update nonempty_pages correctly. It's convenient * to use lazy_check_needs_freeze() for both situations, though. */ LockBuffer(buf, BUFFER_LOCK_SHARE); if (!lazy_check_needs_freeze(buf, &hastup)) { UnlockReleaseBuffer(buf); vacrelstats->scanned_pages++; vacrelstats->pinskipped_pages++; if (hastup) vacrelstats->nonempty_pages = blkno + 1; continue; } if (!aggressive) { /* * Here, we must not advance scanned_pages; that would amount * to claiming that the page contains no freezable tuples. */ UnlockReleaseBuffer(buf); vacrelstats->pinskipped_pages++; if (hastup) vacrelstats->nonempty_pages = blkno + 1; continue; } LockBuffer(buf, BUFFER_LOCK_UNLOCK); LockBufferForCleanup(buf); /* drop through to normal processing */ } vacrelstats->scanned_pages++; page = BufferGetPage(buf); if (PageIsNew(page)) { /* * An all-zeroes page could be left over if a backend extends the * relation but crashes before initializing the page. Reclaim such * pages for use. * * We have to be careful here because we could be looking at a * page that someone has just added to the relation and not yet * been able to initialize (see RelationGetBufferForTuple). To * protect against that, release the buffer lock, grab the * relation extension lock momentarily, and re-lock the buffer. If * the page is still uninitialized by then, it must be left over * from a crashed backend, and we can initialize it. * * We don't really need the relation lock when this is a new or * temp relation, but it's probably not worth the code space to * check that, since this surely isn't a critical path. * * Note: the comparable code in vacuum.c need not worry because * it's got exclusive lock on the whole relation. */ LockBuffer(buf, BUFFER_LOCK_UNLOCK); LockRelationForExtension(onerel, ExclusiveLock); UnlockRelationForExtension(onerel, ExclusiveLock); LockBufferForCleanup(buf); if (PageIsNew(page)) { ereport(WARNING, (errmsg("relation \"%s\" page %u is uninitialized --- fixing", relname, blkno))); PageInit(page, BufferGetPageSize(buf), 0); empty_pages++; } freespace = PageGetHeapFreeSpace(page); MarkBufferDirty(buf); UnlockReleaseBuffer(buf); RecordPageWithFreeSpace(onerel, blkno, freespace); continue; } if (PageIsEmpty(page)) { empty_pages++; freespace = PageGetHeapFreeSpace(page); /* empty pages are always all-visible and all-frozen */ if (!PageIsAllVisible(page)) { START_CRIT_SECTION(); /* mark buffer dirty before writing a WAL record */ MarkBufferDirty(buf); /* * It's possible that another backend has extended the heap, * initialized the page, and then failed to WAL-log the page * due to an ERROR. Since heap extension is not WAL-logged, * recovery might try to replay our record setting the page * all-visible and find that the page isn't initialized, which * will cause a PANIC. To prevent that, check whether the * page has been previously WAL-logged, and if not, do that * now. */ if (RelationNeedsWAL(onerel) && PageGetLSN(page) == InvalidXLogRecPtr) log_newpage_buffer(buf, true); PageSetAllVisible(page); visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr, vmbuffer, InvalidTransactionId, VISIBILITYMAP_ALL_VISIBLE | VISIBILITYMAP_ALL_FROZEN); END_CRIT_SECTION(); } UnlockReleaseBuffer(buf); RecordPageWithFreeSpace(onerel, blkno, freespace); continue; } /* * Prune all HOT-update chains in this page. * * We count tuples removed by the pruning step as removed by VACUUM. */ tups_vacuumed += heap_page_prune(onerel, buf, OldestXmin, false, &vacrelstats->latestRemovedXid); /* * Now scan the page to collect vacuumable items and check for tuples * requiring freezing. */ all_visible = true; has_dead_tuples = false; nfrozen = 0; hastup = false; prev_dead_count = vacrelstats->num_dead_tuples; maxoff = PageGetMaxOffsetNumber(page); /* * Note: If you change anything in the loop below, also look at * heap_page_is_all_visible to see if that needs to be changed. */ for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid; itemid = PageGetItemId(page, offnum); /* Unused items require no processing, but we count 'em */ if (!ItemIdIsUsed(itemid)) { nunused += 1; continue; } /* Redirect items mustn't be touched */ if (ItemIdIsRedirected(itemid)) { hastup = true; /* this page won't be truncatable */ continue; } ItemPointerSet(&(tuple.t_self), blkno, offnum); /* * DEAD item pointers are to be vacuumed normally; but we don't * count them in tups_vacuumed, else we'd be double-counting (at * least in the common case where heap_page_prune() just freed up * a non-HOT tuple). */ if (ItemIdIsDead(itemid)) { lazy_record_dead_tuple(vacrelstats, &(tuple.t_self)); all_visible = false; continue; } Assert(ItemIdIsNormal(itemid)); tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid); tuple.t_len = ItemIdGetLength(itemid); tuple.t_tableOid = RelationGetRelid(onerel); tupgone = false; switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf)) { case HEAPTUPLE_DEAD: /* * Ordinarily, DEAD tuples would have been removed by * heap_page_prune(), but it's possible that the tuple * state changed since heap_page_prune() looked. In * particular an INSERT_IN_PROGRESS tuple could have * changed to DEAD if the inserter aborted. So this * cannot be considered an error condition. * * If the tuple is HOT-updated then it must only be * removed by a prune operation; so we keep it just as if * it were RECENTLY_DEAD. Also, if it's a heap-only * tuple, we choose to keep it, because it'll be a lot * cheaper to get rid of it in the next pruning pass than * to treat it like an indexed tuple. */ if (HeapTupleIsHotUpdated(&tuple) || HeapTupleIsHeapOnly(&tuple)) nkeep += 1; else tupgone = true; /* we can delete the tuple */ all_visible = false; break; case HEAPTUPLE_LIVE: /* Tuple is good --- but let's do some validity checks */ if (onerel->rd_rel->relhasoids && !OidIsValid(HeapTupleGetOid(&tuple))) elog(WARNING, "relation \"%s\" TID %u/%u: OID is invalid", relname, blkno, offnum); /* * Is the tuple definitely visible to all transactions? * * NB: Like with per-tuple hint bits, we can't set the * PD_ALL_VISIBLE flag if the inserter committed * asynchronously. See SetHintBits for more info. Check * that the tuple is hinted xmin-committed because of * that. */ if (all_visible) { TransactionId xmin; if (!HeapTupleHeaderXminCommitted(tuple.t_data)) { all_visible = false; break; } /* * The inserter definitely committed. But is it old * enough that everyone sees it as committed? */ xmin = HeapTupleHeaderGetXmin(tuple.t_data); if (!TransactionIdPrecedes(xmin, OldestXmin)) { all_visible = false; break; } /* Track newest xmin on page. */ if (TransactionIdFollows(xmin, visibility_cutoff_xid)) visibility_cutoff_xid = xmin; } break; case HEAPTUPLE_RECENTLY_DEAD: /* * If tuple is recently deleted then we must not remove it * from relation. */ nkeep += 1; all_visible = false; break; case HEAPTUPLE_INSERT_IN_PROGRESS: /* This is an expected case during concurrent vacuum */ all_visible = false; break; case HEAPTUPLE_DELETE_IN_PROGRESS: /* This is an expected case during concurrent vacuum */ all_visible = false; break; default: elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result"); break; } if (tupgone) { lazy_record_dead_tuple(vacrelstats, &(tuple.t_self)); HeapTupleHeaderAdvanceLatestRemovedXid(tuple.t_data, &vacrelstats->latestRemovedXid); tups_vacuumed += 1; has_dead_tuples = true; } else { num_tuples += 1; hastup = true; /* * Each non-removable tuple must be checked to see if it needs * freezing. Note we already have exclusive buffer lock. */ if (heap_prepare_freeze_tuple(tuple.t_data, FreezeLimit, MultiXactCutoff, &frozen[nfrozen])) frozen[nfrozen++].offset = offnum; else if (heap_tuple_needs_eventual_freeze(tuple.t_data)) all_frozen = false; } } /* scan along page */ /* * If we froze any tuples, mark the buffer dirty, and write a WAL * record recording the changes. We must log the changes to be * crash-safe against future truncation of CLOG. */ if (nfrozen > 0) { START_CRIT_SECTION(); MarkBufferDirty(buf); /* execute collected freezes */ for (i = 0; i < nfrozen; i++) { ItemId itemid; HeapTupleHeader htup; itemid = PageGetItemId(page, frozen[i].offset); htup = (HeapTupleHeader) PageGetItem(page, itemid); heap_execute_freeze_tuple(htup, &frozen[i]); } /* Now WAL-log freezing if necessary */ if (RelationNeedsWAL(onerel)) { XLogRecPtr recptr; recptr = log_heap_freeze(onerel, buf, FreezeLimit, frozen, nfrozen); PageSetLSN(page, recptr); } END_CRIT_SECTION(); } /* * If there are no indexes then we can vacuum the page right now * instead of doing a second scan. */ if (nindexes == 0 && vacrelstats->num_dead_tuples > 0) { /* Remove tuples from heap */ lazy_vacuum_page(onerel, blkno, buf, 0, vacrelstats, &vmbuffer); has_dead_tuples = false; /* * Forget the now-vacuumed tuples, and press on, but be careful * not to reset latestRemovedXid since we want that value to be * valid. */ vacrelstats->num_dead_tuples = 0; vacuumed_pages++; } freespace = PageGetHeapFreeSpace(page); /* mark page all-visible, if appropriate */ if (all_visible && !all_visible_according_to_vm) { uint8 flags = VISIBILITYMAP_ALL_VISIBLE; if (all_frozen) flags |= VISIBILITYMAP_ALL_FROZEN; /* * It should never be the case that the visibility map page is set * while the page-level bit is clear, but the reverse is allowed * (if checksums are not enabled). Regardless, set the both bits * so that we get back in sync. * * NB: If the heap page is all-visible but the VM bit is not set, * we don't need to dirty the heap page. However, if checksums * are enabled, we do need to make sure that the heap page is * dirtied before passing it to visibilitymap_set(), because it * may be logged. Given that this situation should only happen in * rare cases after a crash, it is not worth optimizing. */ PageSetAllVisible(page); MarkBufferDirty(buf); visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr, vmbuffer, visibility_cutoff_xid, flags); } /* * As of PostgreSQL 9.2, the visibility map bit should never be set if * the page-level bit is clear. However, it's possible that the bit * got cleared after we checked it and before we took the buffer * content lock, so we must recheck before jumping to the conclusion * that something bad has happened. */ else if (all_visible_according_to_vm && !PageIsAllVisible(page) && VM_ALL_VISIBLE(onerel, blkno, &vmbuffer)) { elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u", relname, blkno); visibilitymap_clear(onerel, blkno, vmbuffer); } /* * It's possible for the value returned by GetOldestXmin() to move * backwards, so it's not wrong for us to see tuples that appear to * not be visible to everyone yet, while PD_ALL_VISIBLE is already * set. The real safe xmin value never moves backwards, but * GetOldestXmin() is conservative and sometimes returns a value * that's unnecessarily small, so if we see that contradiction it just * means that the tuples that we think are not visible to everyone yet * actually are, and the PD_ALL_VISIBLE flag is correct. * * There should never be dead tuples on a page with PD_ALL_VISIBLE * set, however. */ else if (PageIsAllVisible(page) && has_dead_tuples) { elog(WARNING, "page containing dead tuples is marked as all-visible in relation \"%s\" page %u", relname, blkno); PageClearAllVisible(page); MarkBufferDirty(buf); visibilitymap_clear(onerel, blkno, vmbuffer); } /* * If the page is marked as all-visible but not all-frozen, we should * so mark it. Note that all_frozen is only valid if all_visible is * true, so we must check both. */ else if (all_visible_according_to_vm && all_visible && all_frozen && !VM_ALL_FROZEN(onerel, blkno, &vmbuffer)) { /* * We can pass InvalidTransactionId as the cutoff XID here, * because setting the all-frozen bit doesn't cause recovery * conflicts. */ visibilitymap_set(onerel, blkno, buf, InvalidXLogRecPtr, vmbuffer, InvalidTransactionId, VISIBILITYMAP_ALL_FROZEN); } UnlockReleaseBuffer(buf); /* Remember the location of the last page with nonremovable tuples */ if (hastup) vacrelstats->nonempty_pages = blkno + 1; /* * If we remembered any tuples for deletion, then the page will be * visited again by lazy_vacuum_heap, which will compute and record * its post-compaction free space. If not, then we're done with this * page, so remember its free space as-is. (This path will always be * taken if there are no indexes.) */ if (vacrelstats->num_dead_tuples == prev_dead_count) RecordPageWithFreeSpace(onerel, blkno, freespace); } /* report that everything is scanned and vacuumed */ pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_SCANNED, blkno); pfree(frozen); /* save stats for use later */ vacrelstats->scanned_tuples = num_tuples; vacrelstats->tuples_deleted = tups_vacuumed; vacrelstats->new_dead_tuples = nkeep; /* now we can compute the new value for pg_class.reltuples */ vacrelstats->new_rel_tuples = vac_estimate_reltuples(onerel, false, nblocks, vacrelstats->scanned_pages, num_tuples); /* * Release any remaining pin on visibility map page. */ if (BufferIsValid(vmbuffer)) { ReleaseBuffer(vmbuffer); vmbuffer = InvalidBuffer; } /* If any tuples need to be deleted, perform final vacuum cycle */ /* XXX put a threshold on min number of tuples here? */ if (vacrelstats->num_dead_tuples > 0) { const int hvp_index[] = { PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_NUM_INDEX_VACUUMS }; int64 hvp_val[2]; /* Log cleanup info before we touch indexes */ vacuum_log_cleanup_info(onerel, vacrelstats); /* Report that we are now vacuuming indexes */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_INDEX); /* Remove index entries */ for (i = 0; i < nindexes; i++) lazy_vacuum_index(Irel[i], &indstats[i], vacrelstats); /* Report that we are now vacuuming the heap */ hvp_val[0] = PROGRESS_VACUUM_PHASE_VACUUM_HEAP; hvp_val[1] = vacrelstats->num_index_scans + 1; pgstat_progress_update_multi_param(2, hvp_index, hvp_val); /* Remove tuples from heap */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_VACUUM_HEAP); lazy_vacuum_heap(onerel, vacrelstats); vacrelstats->num_index_scans++; } /* report all blocks vacuumed; and that we're cleaning up */ pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno); pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_INDEX_CLEANUP); /* Do post-vacuum cleanup and statistics update for each index */ for (i = 0; i < nindexes; i++) lazy_cleanup_index(Irel[i], indstats[i], vacrelstats); /* If no indexes, make log report that lazy_vacuum_heap would've made */ if (vacuumed_pages) ereport(elevel, (errmsg("\"%s\": removed %.0f row versions in %u pages", RelationGetRelationName(onerel), tups_vacuumed, vacuumed_pages))); /* * This is pretty messy, but we split it up so that we can skip emitting * individual parts of the message when not applicable. */ initStringInfo(&buf); appendStringInfo(&buf, _("%.0f dead row versions cannot be removed yet.\n"), nkeep); appendStringInfo(&buf, _("There were %.0f unused item pointers.\n"), nunused); appendStringInfo(&buf, ngettext("Skipped %u page due to buffer pins.\n", "Skipped %u pages due to buffer pins.\n", vacrelstats->pinskipped_pages), vacrelstats->pinskipped_pages); appendStringInfo(&buf, ngettext("%u page is entirely empty.\n", "%u pages are entirely empty.\n", empty_pages), empty_pages); appendStringInfo(&buf, _("%s."), pg_rusage_show(&ru0)); ereport(elevel, (errmsg("\"%s\": found %.0f removable, %.0f nonremovable row versions in %u out of %u pages", RelationGetRelationName(onerel), tups_vacuumed, num_tuples, vacrelstats->scanned_pages, nblocks), errdetail_internal("%s", buf.data))); pfree(buf.data); } /* * lazy_vacuum_heap() -- second pass over the heap * * This routine marks dead tuples as unused and compacts out free * space on their pages. Pages not having dead tuples recorded from * lazy_scan_heap are not visited at all. * * Note: the reason for doing this as a second pass is we cannot remove * the tuples until we've removed their index entries, and we want to * process index entry removal in batches as large as possible. */ static void lazy_vacuum_heap(Relation onerel, LVRelStats *vacrelstats) { int tupindex; int npages; PGRUsage ru0; Buffer vmbuffer = InvalidBuffer; pg_rusage_init(&ru0); npages = 0; tupindex = 0; while (tupindex < vacrelstats->num_dead_tuples) { BlockNumber tblk; Buffer buf; Page page; Size freespace; vacuum_delay_point(); tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]); buf = ReadBufferExtended(onerel, MAIN_FORKNUM, tblk, RBM_NORMAL, vac_strategy); if (!ConditionalLockBufferForCleanup(buf)) { ReleaseBuffer(buf); ++tupindex; continue; } tupindex = lazy_vacuum_page(onerel, tblk, buf, tupindex, vacrelstats, &vmbuffer); /* Now that we've compacted the page, record its available space */ page = BufferGetPage(buf); freespace = PageGetHeapFreeSpace(page); UnlockReleaseBuffer(buf); RecordPageWithFreeSpace(onerel, tblk, freespace); npages++; } if (BufferIsValid(vmbuffer)) { ReleaseBuffer(vmbuffer); vmbuffer = InvalidBuffer; } ereport(elevel, (errmsg("\"%s\": removed %d row versions in %d pages", RelationGetRelationName(onerel), tupindex, npages), errdetail("%s.", pg_rusage_show(&ru0)))); } /* * lazy_vacuum_page() -- free dead tuples on a page * and repair its fragmentation. * * Caller must hold pin and buffer cleanup lock on the buffer. * * tupindex is the index in vacrelstats->dead_tuples of the first dead * tuple for this page. We assume the rest follow sequentially. * The return value is the first tupindex after the tuples of this page. */ static int lazy_vacuum_page(Relation onerel, BlockNumber blkno, Buffer buffer, int tupindex, LVRelStats *vacrelstats, Buffer *vmbuffer) { Page page = BufferGetPage(buffer); OffsetNumber unused[MaxOffsetNumber]; int uncnt = 0; TransactionId visibility_cutoff_xid; bool all_frozen; pgstat_progress_update_param(PROGRESS_VACUUM_HEAP_BLKS_VACUUMED, blkno); START_CRIT_SECTION(); for (; tupindex < vacrelstats->num_dead_tuples; tupindex++) { BlockNumber tblk; OffsetNumber toff; ItemId itemid; tblk = ItemPointerGetBlockNumber(&vacrelstats->dead_tuples[tupindex]); if (tblk != blkno) break; /* past end of tuples for this block */ toff = ItemPointerGetOffsetNumber(&vacrelstats->dead_tuples[tupindex]); itemid = PageGetItemId(page, toff); ItemIdSetUnused(itemid); unused[uncnt++] = toff; } PageRepairFragmentation(page); /* * Mark buffer dirty before we write WAL. */ MarkBufferDirty(buffer); /* XLOG stuff */ if (RelationNeedsWAL(onerel)) { XLogRecPtr recptr; recptr = log_heap_clean(onerel, buffer, NULL, 0, NULL, 0, unused, uncnt, vacrelstats->latestRemovedXid); PageSetLSN(page, recptr); } /* * End critical section, so we safely can do visibility tests (which * possibly need to perform IO and allocate memory!). If we crash now the * page (including the corresponding vm bit) might not be marked all * visible, but that's fine. A later vacuum will fix that. */ END_CRIT_SECTION(); /* * Now that we have removed the dead tuples from the page, once again * check if the page has become all-visible. The page is already marked * dirty, exclusively locked, and, if needed, a full page image has been * emitted in the log_heap_clean() above. */ if (heap_page_is_all_visible(onerel, buffer, &visibility_cutoff_xid, &all_frozen)) PageSetAllVisible(page); /* * All the changes to the heap page have been done. If the all-visible * flag is now set, also set the VM all-visible bit (and, if possible, the * all-frozen bit) unless this has already been done previously. */ if (PageIsAllVisible(page)) { uint8 vm_status = visibilitymap_get_status(onerel, blkno, vmbuffer); uint8 flags = 0; /* Set the VM all-frozen bit to flag, if needed */ if ((vm_status & VISIBILITYMAP_ALL_VISIBLE) == 0) flags |= VISIBILITYMAP_ALL_VISIBLE; if ((vm_status & VISIBILITYMAP_ALL_FROZEN) == 0 && all_frozen) flags |= VISIBILITYMAP_ALL_FROZEN; Assert(BufferIsValid(*vmbuffer)); if (flags != 0) visibilitymap_set(onerel, blkno, buffer, InvalidXLogRecPtr, *vmbuffer, visibility_cutoff_xid, flags); } return tupindex; } /* * lazy_check_needs_freeze() -- scan page to see if any tuples * need to be cleaned to avoid wraparound * * Returns true if the page needs to be vacuumed using cleanup lock. * Also returns a flag indicating whether page contains any tuples at all. */ static bool lazy_check_needs_freeze(Buffer buf, bool *hastup) { Page page = BufferGetPage(buf); OffsetNumber offnum, maxoff; HeapTupleHeader tupleheader; *hastup = false; /* If we hit an uninitialized page, we want to force vacuuming it. */ if (PageIsNew(page)) return true; /* Quick out for ordinary empty page. */ if (PageIsEmpty(page)) return false; maxoff = PageGetMaxOffsetNumber(page); for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid; itemid = PageGetItemId(page, offnum); /* this should match hastup test in count_nondeletable_pages() */ if (ItemIdIsUsed(itemid)) *hastup = true; /* dead and redirect items never need freezing */ if (!ItemIdIsNormal(itemid)) continue; tupleheader = (HeapTupleHeader) PageGetItem(page, itemid); if (heap_tuple_needs_freeze(tupleheader, FreezeLimit, MultiXactCutoff, buf)) return true; } /* scan along page */ return false; } /* * lazy_vacuum_index() -- vacuum one index relation. * * Delete all the index entries pointing to tuples listed in * vacrelstats->dead_tuples, and update running statistics. */ static void lazy_vacuum_index(Relation indrel, IndexBulkDeleteResult **stats, LVRelStats *vacrelstats) { IndexVacuumInfo ivinfo; PGRUsage ru0; pg_rusage_init(&ru0); ivinfo.index = indrel; ivinfo.analyze_only = false; ivinfo.estimated_count = true; ivinfo.message_level = elevel; ivinfo.num_heap_tuples = vacrelstats->old_rel_tuples; ivinfo.strategy = vac_strategy; /* Do bulk deletion */ *stats = index_bulk_delete(&ivinfo, *stats, lazy_tid_reaped, (void *) vacrelstats); ereport(elevel, (errmsg("scanned index \"%s\" to remove %d row versions", RelationGetRelationName(indrel), vacrelstats->num_dead_tuples), errdetail("%s.", pg_rusage_show(&ru0)))); } /* * lazy_cleanup_index() -- do post-vacuum cleanup for one index relation. */ static void lazy_cleanup_index(Relation indrel, IndexBulkDeleteResult *stats, LVRelStats *vacrelstats) { IndexVacuumInfo ivinfo; PGRUsage ru0; pg_rusage_init(&ru0); ivinfo.index = indrel; ivinfo.analyze_only = false; ivinfo.estimated_count = (vacrelstats->scanned_pages < vacrelstats->rel_pages); ivinfo.message_level = elevel; ivinfo.num_heap_tuples = vacrelstats->new_rel_tuples; ivinfo.strategy = vac_strategy; stats = index_vacuum_cleanup(&ivinfo, stats); if (!stats) return; /* * Now update statistics in pg_class, but only if the index says the count * is accurate. */ if (!stats->estimated_count) vac_update_relstats(indrel, stats->num_pages, stats->num_index_tuples, 0, false, InvalidTransactionId, InvalidMultiXactId, false); ereport(elevel, (errmsg("index \"%s\" now contains %.0f row versions in %u pages", RelationGetRelationName(indrel), stats->num_index_tuples, stats->num_pages), errdetail("%.0f index row versions were removed.\n" "%u index pages have been deleted, %u are currently reusable.\n" "%s.", stats->tuples_removed, stats->pages_deleted, stats->pages_free, pg_rusage_show(&ru0)))); pfree(stats); } /* * should_attempt_truncation - should we attempt to truncate the heap? * * Don't even think about it unless we have a shot at releasing a goodly * number of pages. Otherwise, the time taken isn't worth it. * * This is split out so that we can test whether truncation is going to be * called for before we actually do it. If you change the logic here, be * careful to depend only on fields that lazy_scan_heap updates on-the-fly. */ static bool should_attempt_truncation(LVRelStats *vacrelstats) { BlockNumber possibly_freeable; possibly_freeable = vacrelstats->rel_pages - vacrelstats->nonempty_pages; if (possibly_freeable > 0 && (possibly_freeable >= REL_TRUNCATE_MINIMUM || possibly_freeable >= vacrelstats->rel_pages / REL_TRUNCATE_FRACTION) && old_snapshot_threshold < 0) return true; else return false; } /* * lazy_truncate_heap - try to truncate off any empty pages at the end */ static void lazy_truncate_heap(Relation onerel, LVRelStats *vacrelstats) { BlockNumber old_rel_pages = vacrelstats->rel_pages; BlockNumber new_rel_pages; PGRUsage ru0; int lock_retry; pg_rusage_init(&ru0); /* Report that we are now truncating */ pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, PROGRESS_VACUUM_PHASE_TRUNCATE); /* * Loop until no more truncating can be done. */ do { /* * We need full exclusive lock on the relation in order to do * truncation. If we can't get it, give up rather than waiting --- we * don't want to block other backends, and we don't want to deadlock * (which is quite possible considering we already hold a lower-grade * lock). */ vacrelstats->lock_waiter_detected = false; lock_retry = 0; while (true) { if (ConditionalLockRelation(onerel, AccessExclusiveLock)) break; /* * Check for interrupts while trying to (re-)acquire the exclusive * lock. */ CHECK_FOR_INTERRUPTS(); if (++lock_retry > (VACUUM_TRUNCATE_LOCK_TIMEOUT / VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL)) { /* * We failed to establish the lock in the specified number of * retries. This means we give up truncating. */ vacrelstats->lock_waiter_detected = true; ereport(elevel, (errmsg("\"%s\": stopping truncate due to conflicting lock request", RelationGetRelationName(onerel)))); return; } pg_usleep(VACUUM_TRUNCATE_LOCK_WAIT_INTERVAL); } /* * Now that we have exclusive lock, look to see if the rel has grown * whilst we were vacuuming with non-exclusive lock. If so, give up; * the newly added pages presumably contain non-deletable tuples. */ new_rel_pages = RelationGetNumberOfBlocks(onerel); if (new_rel_pages != old_rel_pages) { /* * Note: we intentionally don't update vacrelstats->rel_pages with * the new rel size here. If we did, it would amount to assuming * that the new pages are empty, which is unlikely. Leaving the * numbers alone amounts to assuming that the new pages have the * same tuple density as existing ones, which is less unlikely. */ UnlockRelation(onerel, AccessExclusiveLock); return; } /* * Scan backwards from the end to verify that the end pages actually * contain no tuples. This is *necessary*, not optional, because * other backends could have added tuples to these pages whilst we * were vacuuming. */ new_rel_pages = count_nondeletable_pages(onerel, vacrelstats); if (new_rel_pages >= old_rel_pages) { /* can't do anything after all */ UnlockRelation(onerel, AccessExclusiveLock); return; } /* * Okay to truncate. */ RelationTruncate(onerel, new_rel_pages); /* * We can release the exclusive lock as soon as we have truncated. * Other backends can't safely access the relation until they have * processed the smgr invalidation that smgrtruncate sent out ... but * that should happen as part of standard invalidation processing once * they acquire lock on the relation. */ UnlockRelation(onerel, AccessExclusiveLock); /* * Update statistics. Here, it *is* correct to adjust rel_pages * without also touching reltuples, since the tuple count wasn't * changed by the truncation. */ vacrelstats->pages_removed += old_rel_pages - new_rel_pages; vacrelstats->rel_pages = new_rel_pages; ereport(elevel, (errmsg("\"%s\": truncated %u to %u pages", RelationGetRelationName(onerel), old_rel_pages, new_rel_pages), errdetail("%s.", pg_rusage_show(&ru0)))); old_rel_pages = new_rel_pages; } while (new_rel_pages > vacrelstats->nonempty_pages && vacrelstats->lock_waiter_detected); } /* * Rescan end pages to verify that they are (still) empty of tuples. * * Returns number of nondeletable pages (last nonempty page + 1). */ static BlockNumber count_nondeletable_pages(Relation onerel, LVRelStats *vacrelstats) { BlockNumber blkno; instr_time starttime; /* Initialize the starttime if we check for conflicting lock requests */ INSTR_TIME_SET_CURRENT(starttime); /* Strange coding of loop control is needed because blkno is unsigned */ blkno = vacrelstats->rel_pages; while (blkno > vacrelstats->nonempty_pages) { Buffer buf; Page page; OffsetNumber offnum, maxoff; bool hastup; /* * Check if another process requests a lock on our relation. We are * holding an AccessExclusiveLock here, so they will be waiting. We * only do this once per VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL, and we * only check if that interval has elapsed once every 32 blocks to * keep the number of system calls and actual shared lock table * lookups to a minimum. */ if ((blkno % 32) == 0) { instr_time currenttime; instr_time elapsed; INSTR_TIME_SET_CURRENT(currenttime); elapsed = currenttime; INSTR_TIME_SUBTRACT(elapsed, starttime); if ((INSTR_TIME_GET_MICROSEC(elapsed) / 1000) >= VACUUM_TRUNCATE_LOCK_CHECK_INTERVAL) { if (LockHasWaitersRelation(onerel, AccessExclusiveLock)) { ereport(elevel, (errmsg("\"%s\": suspending truncate due to conflicting lock request", RelationGetRelationName(onerel)))); vacrelstats->lock_waiter_detected = true; return blkno; } starttime = currenttime; } } /* * We don't insert a vacuum delay point here, because we have an * exclusive lock on the table which we want to hold for as short a * time as possible. We still need to check for interrupts however. */ CHECK_FOR_INTERRUPTS(); blkno--; buf = ReadBufferExtended(onerel, MAIN_FORKNUM, blkno, RBM_NORMAL, vac_strategy); /* In this phase we only need shared access to the buffer */ LockBuffer(buf, BUFFER_LOCK_SHARE); page = BufferGetPage(buf); if (PageIsNew(page) || PageIsEmpty(page)) { /* PageIsNew probably shouldn't happen... */ UnlockReleaseBuffer(buf); continue; } hastup = false; maxoff = PageGetMaxOffsetNumber(page); for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum)) { ItemId itemid; itemid = PageGetItemId(page, offnum); /* * Note: any non-unused item should be taken as a reason to keep * this page. We formerly thought that DEAD tuples could be * thrown away, but that's not so, because we'd not have cleaned * out their index entries. */ if (ItemIdIsUsed(itemid)) { hastup = true; break; /* can stop scanning */ } } /* scan along page */ UnlockReleaseBuffer(buf); /* Done scanning if we found a tuple here */ if (hastup) return blkno + 1; } /* * If we fall out of the loop, all the previously-thought-to-be-empty * pages still are; we need not bother to look at the last known-nonempty * page. */ return vacrelstats->nonempty_pages; } /* * lazy_space_alloc - space allocation decisions for lazy vacuum * * See the comments at the head of this file for rationale. */ static void lazy_space_alloc(LVRelStats *vacrelstats, BlockNumber relblocks) { long maxtuples; int vac_work_mem = IsAutoVacuumWorkerProcess() && autovacuum_work_mem != -1 ? autovacuum_work_mem : maintenance_work_mem; if (vacrelstats->hasindex) { maxtuples = (vac_work_mem * 1024L) / sizeof(ItemPointerData); maxtuples = Min(maxtuples, INT_MAX); maxtuples = Min(maxtuples, MaxAllocSize / sizeof(ItemPointerData)); /* curious coding here to ensure the multiplication can't overflow */ if ((BlockNumber) (maxtuples / LAZY_ALLOC_TUPLES) > relblocks) maxtuples = relblocks * LAZY_ALLOC_TUPLES; /* stay sane if small maintenance_work_mem */ maxtuples = Max(maxtuples, MaxHeapTuplesPerPage); } else { maxtuples = MaxHeapTuplesPerPage; } vacrelstats->num_dead_tuples = 0; vacrelstats->max_dead_tuples = (int) maxtuples; vacrelstats->dead_tuples = (ItemPointer) palloc(maxtuples * sizeof(ItemPointerData)); } /* * lazy_record_dead_tuple - remember one deletable tuple */ static void lazy_record_dead_tuple(LVRelStats *vacrelstats, ItemPointer itemptr) { /* * The array shouldn't overflow under normal behavior, but perhaps it * could if we are given a really small maintenance_work_mem. In that * case, just forget the last few tuples (we'll get 'em next time). */ if (vacrelstats->num_dead_tuples < vacrelstats->max_dead_tuples) { vacrelstats->dead_tuples[vacrelstats->num_dead_tuples] = *itemptr; vacrelstats->num_dead_tuples++; pgstat_progress_update_param(PROGRESS_VACUUM_NUM_DEAD_TUPLES, vacrelstats->num_dead_tuples); } } /* * lazy_tid_reaped() -- is a particular tid deletable? * * This has the right signature to be an IndexBulkDeleteCallback. * * Assumes dead_tuples array is in sorted order. */ static bool lazy_tid_reaped(ItemPointer itemptr, void *state) { LVRelStats *vacrelstats = (LVRelStats *) state; ItemPointer res; res = (ItemPointer) bsearch((void *) itemptr, (void *) vacrelstats->dead_tuples, vacrelstats->num_dead_tuples, sizeof(ItemPointerData), vac_cmp_itemptr); return (res != NULL); } /* * Comparator routines for use with qsort() and bsearch(). */ static int vac_cmp_itemptr(const void *left, const void *right) { BlockNumber lblk, rblk; OffsetNumber loff, roff; lblk = ItemPointerGetBlockNumber((ItemPointer) left); rblk = ItemPointerGetBlockNumber((ItemPointer) right); if (lblk < rblk) return -1; if (lblk > rblk) return 1; loff = ItemPointerGetOffsetNumber((ItemPointer) left); roff = ItemPointerGetOffsetNumber((ItemPointer) right); if (loff < roff) return -1; if (loff > roff) return 1; return 0; } /* * Check if every tuple in the given page is visible to all current and future * transactions. Also return the visibility_cutoff_xid which is the highest * xmin amongst the visible tuples. Set *all_frozen to true if every tuple * on this page is frozen. */ static bool heap_page_is_all_visible(Relation rel, Buffer buf, TransactionId *visibility_cutoff_xid, bool *all_frozen) { Page page = BufferGetPage(buf); BlockNumber blockno = BufferGetBlockNumber(buf); OffsetNumber offnum, maxoff; bool all_visible = true; *visibility_cutoff_xid = InvalidTransactionId; *all_frozen = true; /* * This is a stripped down version of the line pointer scan in * lazy_scan_heap(). So if you change anything here, also check that code. */ maxoff = PageGetMaxOffsetNumber(page); for (offnum = FirstOffsetNumber; offnum <= maxoff && all_visible; offnum = OffsetNumberNext(offnum)) { ItemId itemid; HeapTupleData tuple; itemid = PageGetItemId(page, offnum); /* Unused or redirect line pointers are of no interest */ if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid)) continue; ItemPointerSet(&(tuple.t_self), blockno, offnum); /* * Dead line pointers can have index pointers pointing to them. So * they can't be treated as visible */ if (ItemIdIsDead(itemid)) { all_visible = false; break; } Assert(ItemIdIsNormal(itemid)); tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid); tuple.t_len = ItemIdGetLength(itemid); tuple.t_tableOid = RelationGetRelid(rel); switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf)) { case HEAPTUPLE_LIVE: { TransactionId xmin; /* Check comments in lazy_scan_heap. */ if (!HeapTupleHeaderXminCommitted(tuple.t_data)) { all_visible = false; break; } /* * The inserter definitely committed. But is it old enough * that everyone sees it as committed? */ xmin = HeapTupleHeaderGetXmin(tuple.t_data); if (!TransactionIdPrecedes(xmin, OldestXmin)) { all_visible = false; break; } /* Track newest xmin on page. */ if (TransactionIdFollows(xmin, *visibility_cutoff_xid)) *visibility_cutoff_xid = xmin; /* Check whether this tuple is already frozen or not */ if (all_visible && *all_frozen && heap_tuple_needs_eventual_freeze(tuple.t_data)) *all_frozen = false; } break; case HEAPTUPLE_DEAD: case HEAPTUPLE_RECENTLY_DEAD: case HEAPTUPLE_INSERT_IN_PROGRESS: case HEAPTUPLE_DELETE_IN_PROGRESS: all_visible = false; break; default: elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result"); break; } } /* scan along page */ /* * We don't bother clearing *all_frozen when the page is discovered not to * be all-visible, so do that now if necessary. The page might fail to be * all-frozen for other reasons anyway, but if it's not all-visible, then * it definitely isn't all-frozen. */ if (!all_visible) *all_frozen = false; return all_visible; }
187426.c
/* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2006-2007 Nokia Corporation * Copyright (C) 2004-2008 Marcel Holtmann <[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. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <sys/socket.h> #include <sys/un.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <stdint.h> #include <bluetooth/bluetooth.h> #include <bluetooth/sdp.h> #include <dbus/dbus.h> #include <glib.h> #include "logging.h" #include "ipc.h" #include "device.h" #include "manager.h" #include "avdtp.h" #include "a2dp.h" #include "headset.h" #include "sink.h" #include "unix.h" #include "glib-helper.h" typedef enum { TYPE_NONE, TYPE_HEADSET, TYPE_SINK, TYPE_SOURCE } service_type_t; typedef void (*notify_cb_t) (struct audio_device *dev, void *data); struct a2dp_data { struct avdtp *session; struct avdtp_stream *stream; struct a2dp_sep *sep; }; struct headset_data { headset_lock_t lock; }; struct unix_client { struct audio_device *dev; GSList *caps; service_type_t type; char *interface; union { struct a2dp_data a2dp; struct headset_data hs; } d; int sock; int access_mode; int data_fd; /* To be deleted once two phase configuration is fully implemented */ unsigned int req_id; unsigned int cb_id; gboolean (*cancel) (struct audio_device *dev, unsigned int id); }; static GSList *clients = NULL; static int unix_sock = -1; static void client_free(struct unix_client *client) { struct a2dp_data *a2dp; switch (client->type) { case TYPE_SINK: case TYPE_SOURCE: a2dp = &client->d.a2dp; if (client->cb_id > 0) avdtp_stream_remove_cb(a2dp->session, a2dp->stream, client->cb_id); if (a2dp->sep) a2dp_sep_unlock(a2dp->sep, a2dp->session); if (a2dp->session) avdtp_unref(a2dp->session); break; default: break; } if (client->cancel && client->req_id > 0) client->cancel(client->dev, client->req_id); if (client->sock >= 0) close(client->sock); if (client->caps) { g_slist_foreach(client->caps, (GFunc) g_free, NULL); g_slist_free(client->caps); } g_free(client->interface); g_free(client); } /* Pass file descriptor through local domain sockets (AF_LOCAL, formerly * AF_UNIX) and the sendmsg() system call with the cmsg_type field of a "struct * cmsghdr" set to SCM_RIGHTS and the data being an integer value equal to the * handle of the file descriptor to be passed. */ static int unix_sendmsg_fd(int sock, int fd) { char cmsg_b[CMSG_SPACE(sizeof(int))], m = 'm'; struct cmsghdr *cmsg; struct iovec iov = { &m, sizeof(m) }; struct msghdr msgh; memset(&msgh, 0, sizeof(msgh)); msgh.msg_iov = &iov; msgh.msg_iovlen = 1; msgh.msg_control = &cmsg_b; msgh.msg_controllen = CMSG_LEN(sizeof(int)); cmsg = CMSG_FIRSTHDR(&msgh); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; cmsg->cmsg_len = CMSG_LEN(sizeof(int)); /* Initialize the payload */ (*(int *) CMSG_DATA(cmsg)) = fd; return sendmsg(sock, &msgh, MSG_NOSIGNAL); } static void unix_ipc_sendmsg(struct unix_client *client, const bt_audio_msg_header_t *msg) { info("Audio API: sending %s", bt_audio_strmsg(msg->msg_type)); if (send(client->sock, msg, BT_AUDIO_IPC_PACKET_SIZE, 0) < 0) error("Error %s(%d)", strerror(errno), errno); } static void unix_ipc_error(struct unix_client *client, int type, int err) { char buf[BT_AUDIO_IPC_PACKET_SIZE]; bt_audio_rsp_msg_header_t *rsp_hdr = (void *) buf; if (!g_slist_find(clients, client)) return; memset(buf, 0, sizeof(buf)); rsp_hdr->msg_h.msg_type = type; rsp_hdr->posix_errno = err; unix_ipc_sendmsg(client, &rsp_hdr->msg_h); } static service_type_t select_service(struct audio_device *dev, const char *interface) { if (!interface) { if (dev->sink && avdtp_is_connected(&dev->src, &dev->dst)) return TYPE_SINK; else if (dev->headset && headset_is_active(dev)) return TYPE_HEADSET; else if (dev->sink) return TYPE_SINK; else if (dev->headset) return TYPE_HEADSET; } else if (!strcmp(interface, AUDIO_SINK_INTERFACE) && dev->sink) return TYPE_SINK; else if (!strcmp(interface, AUDIO_HEADSET_INTERFACE) && dev->headset) return TYPE_HEADSET; return TYPE_NONE; } static void stream_state_changed(struct avdtp_stream *stream, avdtp_state_t old_state, avdtp_state_t new_state, struct avdtp_error *err, void *user_data) { struct unix_client *client = user_data; struct a2dp_data *a2dp; if (!g_slist_find(clients, client)) { debug("Client disconnected in stream_state_changed"); return; } a2dp = &client->d.a2dp; switch (new_state) { case AVDTP_STATE_IDLE: if (a2dp->sep) { a2dp_sep_unlock(a2dp->sep, a2dp->session); a2dp->sep = NULL; } client->dev = NULL; if (a2dp->session) { avdtp_unref(a2dp->session); a2dp->session = NULL; } a2dp->stream = NULL; client->cb_id = 0; break; default: break; } } static void headset_discovery_complete(struct audio_device *dev, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_getcapabilities_rsp *rsp = (void *) buf; client->req_id = 0; if (!dev) goto failed; memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_GETCAPABILITIES_RSP; rsp->transport = BT_CAPABILITIES_TRANSPORT_SCO; rsp->sampling_rate = 8000; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); return; failed: error("discovery failed"); unix_ipc_error(client, BT_SETCONFIGURATION_RSP, EIO); client->dev = NULL; } static void headset_setup_complete(struct audio_device *dev, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_setconfiguration_rsp *rsp = (void *) buf; struct headset_data *hs = &client->d.hs; client->req_id = 0; if (!dev) goto failed; switch (client->access_mode) { case BT_CAPABILITIES_ACCESS_MODE_READ: hs->lock = HEADSET_LOCK_READ; break; case BT_CAPABILITIES_ACCESS_MODE_WRITE: hs->lock = HEADSET_LOCK_WRITE; break; case BT_CAPABILITIES_ACCESS_MODE_READWRITE: hs->lock = HEADSET_LOCK_READ | HEADSET_LOCK_WRITE; break; default: hs->lock = 0; break; } if (!headset_lock(dev, hs->lock)) { error("Unable to lock headset"); goto failed; } memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_SETCONFIGURATION_RSP; rsp->transport = BT_CAPABILITIES_TRANSPORT_SCO; rsp->access_mode = client->access_mode; rsp->link_mtu = 48; client->data_fd = headset_get_sco_fd(dev); unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); return; failed: error("config failed"); unix_ipc_error(client, BT_SETCONFIGURATION_RSP, EIO); client->dev = NULL; } static void headset_resume_complete(struct audio_device *dev, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_streamstart_rsp *rsp = (void *) buf; struct bt_streamfd_ind *ind = (void *) buf; client->req_id = 0; if (!dev) goto failed; memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_STREAMSTART_RSP; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); memset(buf, 0, sizeof(buf)); ind->h.msg_type = BT_STREAMFD_IND; unix_ipc_sendmsg(client, &ind->h); client->data_fd = headset_get_sco_fd(dev); if (unix_sendmsg_fd(client->sock, client->data_fd) < 0) { error("unix_sendmsg_fd: %s(%d)", strerror(errno), errno); goto failed; } return; failed: error("resume failed"); unix_ipc_error(client, BT_STREAMSTART_RSP, EIO); client->dev = NULL; } static void a2dp_discovery_complete(struct avdtp *session, GSList *seps, struct avdtp_error *err, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_getcapabilities_rsp *rsp = (void *) buf; struct a2dp_data *a2dp = &client->d.a2dp; struct sbc_codec_cap *sbc_cap = NULL; struct mpeg_codec_cap *mpeg_cap = NULL; GSList *l; if (!g_slist_find(clients, client)) { debug("Client disconnected during discovery"); return; } if (err) goto failed; memset(buf, 0, sizeof(buf)); client->req_id = 0; rsp->rsp_h.msg_h.msg_type = BT_GETCAPABILITIES_RSP; rsp->transport = BT_CAPABILITIES_TRANSPORT_A2DP; for (l = seps; l; l = g_slist_next(l)) { struct avdtp_remote_sep *rsep = l->data; struct avdtp_service_capability *cap; struct avdtp_media_codec_capability *codec_cap; cap = avdtp_get_codec(rsep); if (cap->category != AVDTP_MEDIA_CODEC) continue; codec_cap = (void *) cap->data; if (codec_cap->media_codec_type == A2DP_CODEC_SBC && !sbc_cap) sbc_cap = (void *) codec_cap; if (codec_cap->media_codec_type == A2DP_CODEC_MPEG12 && !mpeg_cap) mpeg_cap = (void *) codec_cap; } /* endianess prevent direct cast */ if (sbc_cap) { rsp->sbc_capabilities.channel_mode = sbc_cap->channel_mode; rsp->sbc_capabilities.frequency = sbc_cap->frequency; rsp->sbc_capabilities.allocation_method = sbc_cap->allocation_method; rsp->sbc_capabilities.subbands = sbc_cap->subbands; rsp->sbc_capabilities.block_length = sbc_cap->block_length; rsp->sbc_capabilities.min_bitpool = sbc_cap->min_bitpool; rsp->sbc_capabilities.max_bitpool = sbc_cap->max_bitpool; } if (mpeg_cap) { rsp->mpeg_capabilities.channel_mode = mpeg_cap->channel_mode; rsp->mpeg_capabilities.crc = mpeg_cap->crc; rsp->mpeg_capabilities.layer = mpeg_cap->layer; rsp->mpeg_capabilities.frequency = mpeg_cap->frequency; rsp->mpeg_capabilities.mpf = mpeg_cap->mpf; rsp->mpeg_capabilities.bitrate = mpeg_cap->bitrate; } unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); return; failed: error("discovery failed"); unix_ipc_error(client, BT_GETCAPABILITIES_RSP, EIO); avdtp_unref(a2dp->session); a2dp->session = NULL; a2dp->stream = NULL; } static void a2dp_config_complete(struct avdtp *session, struct a2dp_sep *sep, struct avdtp_stream *stream, struct avdtp_error *err, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_setconfiguration_rsp *rsp = (void *) buf; struct a2dp_data *a2dp = &client->d.a2dp; uint16_t imtu, omtu; GSList *caps; if (!g_slist_find(clients, client)) { debug("Client disconnected in a2dp_config_complete"); return; } if (err) goto failed; memset(buf, 0, sizeof(buf)); client->req_id = 0; if (!stream) goto failed; if (!a2dp_sep_lock(sep, session)) { error("Unable to lock A2DP source SEP"); goto failed; } a2dp->sep = sep; a2dp->stream = stream; if (!avdtp_stream_get_transport(stream, &client->data_fd, &imtu, &omtu, &caps)) { error("Unable to get stream transport"); goto failed; } rsp->rsp_h.msg_h.msg_type = BT_SETCONFIGURATION_RSP; rsp->transport = BT_CAPABILITIES_TRANSPORT_A2DP; client->access_mode = BT_CAPABILITIES_ACCESS_MODE_WRITE; rsp->access_mode = client->access_mode; /* FIXME: Use imtu when fd_opt is CFG_FD_OPT_READ */ rsp->link_mtu = omtu; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); client->cb_id = avdtp_stream_add_cb(session, stream, stream_state_changed, client); return; failed: error("config failed"); if (a2dp->sep) { a2dp_sep_unlock(a2dp->sep, a2dp->session); a2dp->sep = NULL; } unix_ipc_error(client, BT_SETCONFIGURATION_RSP, EIO); avdtp_unref(a2dp->session); a2dp->session = NULL; a2dp->stream = NULL; } static void a2dp_resume_complete(struct avdtp *session, struct avdtp_error *err, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_streamstart_rsp *rsp = (void *) buf; struct bt_streamfd_ind *ind = (void *) buf; struct a2dp_data *a2dp = &client->d.a2dp; if (!g_slist_find(clients, client)) { debug("Client disconnected in a2dp_resume_complete"); return; } if (err) goto failed; memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_STREAMSTART_RSP; rsp->rsp_h.posix_errno = 0; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); memset(buf, 0, sizeof(buf)); ind->h.msg_type = BT_STREAMFD_IND; unix_ipc_sendmsg(client, &ind->h); if (unix_sendmsg_fd(client->sock, client->data_fd) < 0) { error("unix_sendmsg_fd: %s(%d)", strerror(errno), errno); goto failed; } return; failed: error("resume failed"); if (a2dp->sep) { a2dp_sep_unlock(a2dp->sep, a2dp->session); a2dp->sep = NULL; } unix_ipc_error(client, BT_STREAMSTART_RSP, EIO); avdtp_unref(a2dp->session); a2dp->session = NULL; a2dp->stream = NULL; } static void a2dp_suspend_complete(struct avdtp *session, struct avdtp_error *err, void *user_data) { struct unix_client *client = user_data; char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_streamstart_rsp *rsp = (void *) buf; struct a2dp_data *a2dp = &client->d.a2dp; if (!g_slist_find(clients, client)) { debug("Client disconnected in a2dp_suspend_complete"); return; } if (err) goto failed; memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_STREAMSTOP_RSP; rsp->rsp_h.posix_errno = 0; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); return; failed: error("suspend failed"); if (a2dp->sep) { a2dp_sep_unlock(a2dp->sep, a2dp->session); a2dp->sep = NULL; } unix_ipc_error(client, BT_STREAMSTOP_RSP, EIO); avdtp_unref(a2dp->session); a2dp->session = NULL; a2dp->stream = NULL; } static void start_discovery(struct audio_device *dev, struct unix_client *client) { struct a2dp_data *a2dp; int err = 0; client->type = select_service(dev, client->interface); switch (client->type) { case TYPE_SINK: a2dp = &client->d.a2dp; if (!a2dp->session) a2dp->session = avdtp_get(&dev->src, &dev->dst); if (!a2dp->session) { error("Unable to get a session"); goto failed; } err = avdtp_discover(a2dp->session, a2dp_discovery_complete, client); if (err) goto failed; break; case TYPE_HEADSET: headset_discovery_complete(dev, client); break; default: error("No known services for device"); goto failed; } client->dev = dev; return; failed: unix_ipc_error(client, BT_GETCAPABILITIES_RSP, err ? : EIO); } static void start_config(struct audio_device *dev, struct unix_client *client) { struct a2dp_data *a2dp; unsigned int id; client->type = select_service(dev, client->interface); switch (client->type) { case TYPE_SINK: a2dp = &client->d.a2dp; if (!a2dp->session) a2dp->session = avdtp_get(&dev->src, &dev->dst); if (!a2dp->session) { error("Unable to get a session"); goto failed; } id = a2dp_source_config(a2dp->session, a2dp_config_complete, client->caps, client); client->cancel = a2dp_source_cancel; break; case TYPE_HEADSET: id = headset_request_stream(dev, headset_setup_complete, client); client->cancel = headset_cancel_stream; break; default: error("No known services for device"); goto failed; } if (id == 0) { error("config failed"); goto failed; } client->req_id = id; client->dev = dev; return; failed: unix_ipc_error(client, BT_SETCONFIGURATION_RSP, EIO); } static void start_resume(struct audio_device *dev, struct unix_client *client) { struct a2dp_data *a2dp; unsigned int id; client->type = select_service(dev, client->interface); switch (client->type) { case TYPE_SINK: a2dp = &client->d.a2dp; if (!a2dp->session) a2dp->session = avdtp_get(&dev->src, &dev->dst); if (!a2dp->session) { error("Unable to get a session"); goto failed; } if (!a2dp->sep) { error("Unable to get a sep"); goto failed; } id = a2dp_source_resume(a2dp->session, a2dp->sep, a2dp_resume_complete, client); client->cancel = a2dp_source_cancel; if (id == 0) { error("resume failed"); goto failed; } break; case TYPE_HEADSET: headset_resume_complete(dev, client); break; default: error("No known services for device"); goto failed; } return; failed: unix_ipc_error(client, BT_STREAMSTART_RSP, EIO); } static void start_suspend(struct audio_device *dev, struct unix_client *client) { struct a2dp_data *a2dp; unsigned int id; client->type = select_service(dev, client->interface); switch (client->type) { case TYPE_SINK: a2dp = &client->d.a2dp; if (!a2dp->session) a2dp->session = avdtp_get(&dev->src, &dev->dst); if (!a2dp->session) { error("Unable to get a session"); goto failed; } if (!a2dp->sep) { error("Unable to get a sep"); goto failed; } id = a2dp_source_suspend(a2dp->session, a2dp->sep, a2dp_suspend_complete, client); client->cancel = a2dp_source_cancel; break; case TYPE_HEADSET: id = headset_request_stream(dev, headset_setup_complete, client); client->cancel = headset_cancel_stream; break; default: error("No known services for device"); goto failed; } if (id == 0) { error("suspend failed"); goto failed; } return; failed: unix_ipc_error(client, BT_STREAMSTOP_RSP, EIO); } static void create_cb(struct audio_device *dev, void *user_data) { struct unix_client *client = user_data; if (!g_slist_find(clients, client)) { debug("Client disconnected during device creation"); return; } if (!dev) unix_ipc_error(client, BT_GETCAPABILITIES_RSP, EIO); else start_discovery(dev, client); } static void handle_getcapabilities_req(struct unix_client *client, struct bt_getcapabilities_req *req) { struct audio_device *dev; bdaddr_t bdaddr; str2ba(req->device, &bdaddr); if (client->interface) { g_free(client->interface); client->interface = NULL; } if (req->transport == BT_CAPABILITIES_TRANSPORT_SCO) client->interface = g_strdup(AUDIO_HEADSET_INTERFACE); else if (req->transport == BT_CAPABILITIES_TRANSPORT_A2DP) client->interface = g_strdup(AUDIO_SINK_INTERFACE); if (!manager_find_device(&bdaddr, NULL, FALSE)) { if (!(req->flags & BT_FLAG_AUTOCONNECT)) goto failed; if (!bacmp(&bdaddr, BDADDR_ANY)) goto failed; if (!manager_create_device(&bdaddr, create_cb, client)) goto failed; return; } dev = manager_find_device(&bdaddr, client->interface, TRUE); if (!dev) { if (req->flags & BT_FLAG_AUTOCONNECT) dev = manager_find_device(&bdaddr, client->interface, FALSE); else goto failed; } if (!dev) goto failed; start_discovery(dev, client); return; failed: unix_ipc_error(client, BT_GETCAPABILITIES_RSP, EIO); } static int handle_sco_transport(struct unix_client *client, struct bt_setconfiguration_req *req) { client->interface = g_strdup(AUDIO_HEADSET_INTERFACE); info("config sco - device = %s access_mode = %u", req->device, req->access_mode); return 0; } static int handle_a2dp_transport(struct unix_client *client, struct bt_setconfiguration_req *req) { struct avdtp_service_capability *media_transport, *media_codec; struct sbc_codec_cap sbc_cap; struct mpeg_codec_cap mpeg_cap; client->interface = g_strdup(AUDIO_SINK_INTERFACE); if (client->caps) { g_slist_foreach(client->caps, (GFunc) g_free, NULL); g_slist_free(client->caps); client->caps = NULL; } media_transport = avdtp_service_cap_new(AVDTP_MEDIA_TRANSPORT, NULL, 0); client->caps = g_slist_append(client->caps, media_transport); info("config a2dp - device = %s access_mode = %u", req->device, req->access_mode); if (req->mpeg_capabilities.frequency) { memset(&mpeg_cap, 0, sizeof(mpeg_cap)); mpeg_cap.cap.media_type = AVDTP_MEDIA_TYPE_AUDIO; mpeg_cap.cap.media_codec_type = A2DP_CODEC_MPEG12; mpeg_cap.channel_mode = req->mpeg_capabilities.channel_mode; mpeg_cap.crc = req->mpeg_capabilities.crc; mpeg_cap.layer = req->mpeg_capabilities.layer; mpeg_cap.frequency = req->mpeg_capabilities.frequency; mpeg_cap.mpf = req->mpeg_capabilities.mpf; mpeg_cap.bitrate = req->mpeg_capabilities.bitrate; media_codec = avdtp_service_cap_new(AVDTP_MEDIA_CODEC, &mpeg_cap, sizeof(mpeg_cap)); info("codec mpeg12 - frequency = %u channel_mode = %u " "layer = %u crc = %u mpf = %u bitrate = %u", mpeg_cap.frequency, mpeg_cap.channel_mode, mpeg_cap.layer, mpeg_cap.crc, mpeg_cap.mpf, mpeg_cap.bitrate); } else if (req->sbc_capabilities.frequency) { memset(&sbc_cap, 0, sizeof(sbc_cap)); sbc_cap.cap.media_type = AVDTP_MEDIA_TYPE_AUDIO; sbc_cap.cap.media_codec_type = A2DP_CODEC_SBC; sbc_cap.channel_mode = req->sbc_capabilities.channel_mode; sbc_cap.frequency = req->sbc_capabilities.frequency; sbc_cap.allocation_method = req->sbc_capabilities.allocation_method; sbc_cap.subbands = req->sbc_capabilities.subbands; sbc_cap.block_length = req->sbc_capabilities.block_length; sbc_cap.min_bitpool = req->sbc_capabilities.min_bitpool; sbc_cap.max_bitpool = req->sbc_capabilities.max_bitpool; media_codec = avdtp_service_cap_new(AVDTP_MEDIA_CODEC, &sbc_cap, sizeof(sbc_cap)); info("codec sbc - frequency = %u channel_mode = %u " "allocation = %u subbands = %u blocks = %u " "bitpool = %u", sbc_cap.frequency, sbc_cap.channel_mode, sbc_cap.allocation_method, sbc_cap.subbands, sbc_cap.block_length, sbc_cap.max_bitpool); } else return -EINVAL; client->caps = g_slist_append(client->caps, media_codec); return 0; } static void handle_setconfiguration_req(struct unix_client *client, struct bt_setconfiguration_req *req) { struct audio_device *dev; bdaddr_t bdaddr; int err = 0; if (!req->access_mode) { err = EINVAL; goto failed; } str2ba(req->device, &bdaddr); if (client->interface) { g_free(client->interface); client->interface = NULL; } if (req->transport == BT_CAPABILITIES_TRANSPORT_SCO) { err = handle_sco_transport(client, req); if (err < 0) { err = -err; goto failed; } } else if (req->transport == BT_CAPABILITIES_TRANSPORT_A2DP) { err = handle_a2dp_transport(client, req); if (err < 0) { err = -err; goto failed; } } if (!manager_find_device(&bdaddr, NULL, FALSE)) { if (!bacmp(&bdaddr, BDADDR_ANY)) goto failed; if (!manager_create_device(&bdaddr, create_cb, client)) goto failed; return; } dev = manager_find_device(&bdaddr, client->interface, TRUE); if (!dev) dev = manager_find_device(&bdaddr, client->interface, FALSE); if (!dev) goto failed; client->access_mode = req->access_mode; start_config(dev, client); return; failed: unix_ipc_error(client, BT_SETCONFIGURATION_RSP, err ? : EIO); } static void handle_streamstart_req(struct unix_client *client, struct bt_streamstart_req *req) { if (!client->dev) goto failed; start_resume(client->dev, client); return; failed: unix_ipc_error(client, BT_STREAMSTART_RSP, EIO); } static void handle_streamstop_req(struct unix_client *client, struct bt_streamstop_req *req) { if (!client->dev) goto failed; start_suspend(client->dev, client); return; failed: unix_ipc_error(client, BT_STREAMSTOP_RSP, EIO); } static void handle_control_req(struct unix_client *client, struct bt_control_req *req) { /* FIXME: really implement that */ char buf[BT_AUDIO_IPC_PACKET_SIZE]; struct bt_setconfiguration_rsp *rsp = (void *) buf; memset(buf, 0, sizeof(buf)); rsp->rsp_h.msg_h.msg_type = BT_CONTROL_RSP; rsp->rsp_h.posix_errno = 0; unix_ipc_sendmsg(client, &rsp->rsp_h.msg_h); } static gboolean client_cb(GIOChannel *chan, GIOCondition cond, gpointer data) { char buf[BT_AUDIO_IPC_PACKET_SIZE]; bt_audio_msg_header_t *msghdr = (void *) buf; struct unix_client *client = data; int len; struct a2dp_data *a2dp; struct headset_data *hs; const char *type; if (cond & G_IO_NVAL) return FALSE; if (!g_slist_find(clients, client)) { debug("Client disconnected in client_cb"); return TRUE; } a2dp = &client->d.a2dp; hs = &client->d.hs; if (cond & (G_IO_HUP | G_IO_ERR)) { debug("Unix client disconnected (fd=%d)", client->sock); switch (client->type) { case TYPE_HEADSET: if (client->dev) headset_unlock(client->dev, hs->lock); break; case TYPE_SOURCE: case TYPE_SINK: if (a2dp->sep) { a2dp_sep_unlock(a2dp->sep, a2dp->session); a2dp->sep = NULL; } break; default: break; } if (client->cancel && client->req_id > 0) client->cancel(client->dev, client->req_id); goto failed; } memset(buf, 0, sizeof(buf)); len = recv(client->sock, buf, sizeof(buf), MSG_WAITALL); if (len < 0) { error("recv: %s (%d)", strerror(errno), errno); goto failed; } if ((type = bt_audio_strmsg(msghdr->msg_type))) info("Audio API: received %s", type); switch (msghdr->msg_type) { case BT_GETCAPABILITIES_REQ: handle_getcapabilities_req(client, (struct bt_getcapabilities_req *) msghdr); break; case BT_SETCONFIGURATION_REQ: handle_setconfiguration_req(client, (struct bt_setconfiguration_req *) msghdr); break; case BT_STREAMSTART_REQ: handle_streamstart_req(client, (struct bt_streamstart_req *) msghdr); break; case BT_STREAMSTOP_REQ: handle_streamstop_req(client, (struct bt_streamstop_req *) msghdr); break; case BT_CONTROL_REQ: handle_control_req(client, (struct bt_control_req *) msghdr); break; default: error("Audio API: received unexpected packet type %d", msghdr->msg_type); } return TRUE; failed: clients = g_slist_remove(clients, client); client_free(client); return FALSE; } static gboolean server_cb(GIOChannel *chan, GIOCondition cond, gpointer data) { struct sockaddr_un addr; socklen_t addrlen; int sk, cli_sk; struct unix_client *client; GIOChannel *io; if (cond & G_IO_NVAL) return FALSE; if (cond & (G_IO_HUP | G_IO_ERR)) { g_io_channel_close(chan); return FALSE; } sk = g_io_channel_unix_get_fd(chan); memset(&addr, 0, sizeof(addr)); addrlen = sizeof(addr); cli_sk = accept(sk, (struct sockaddr *) &addr, &addrlen); if (cli_sk < 0) { error("accept: %s (%d)", strerror(errno), errno); return TRUE; } debug("Accepted new client connection on unix socket (fd=%d)", cli_sk); client = g_new0(struct unix_client, 1); client->sock = cli_sk; clients = g_slist_append(clients, client); io = g_io_channel_unix_new(cli_sk); g_io_add_watch(io, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, client_cb, client); g_io_channel_unref(io); return TRUE; } int unix_init(void) { GIOChannel *io; struct sockaddr_un addr = { AF_UNIX, BT_IPC_SOCKET_NAME }; int sk, err; sk = socket(PF_LOCAL, SOCK_STREAM, 0); if (sk < 0) { err = errno; error("Can't create unix socket: %s (%d)", strerror(err), err); return -err; } if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { error("Can't bind unix socket: %s (%d)", strerror(errno), errno); close(sk); return -1; } set_nonblocking(sk); unix_sock = sk; listen(sk, 1); io = g_io_channel_unix_new(sk); g_io_add_watch(io, G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_NVAL, server_cb, NULL); g_io_channel_unref(io); info("Unix socket created: %d", sk); return 0; } void unix_exit(void) { g_slist_foreach(clients, (GFunc) client_free, NULL); g_slist_free(clients); close(unix_sock); unix_sock = -1; }
746158.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: modaouch <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/04/16 14:57:00 by modaouch #+# #+# */ /* Updated: 2018/10/22 18:53:07 by modaouch ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" void ft_putnbr(int n) { long nb; nb = n; if (nb < 0) { ft_putchar('-'); nb *= -1; } if (nb > 9) { ft_putnbr(nb / 10); ft_putnbr(nb % 10); } else ft_putchar(nb + '0'); }
209401.c
/* * libwebsockets - small server side websockets and web server implementation * * Copyright (C) 2010 - 2019 Andy Green <[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 "private-lib-core.h" static void lws_uv_sultimer_cb(uv_timer_t *timer #if UV_VERSION_MAJOR == 0 , int status #endif ) { struct lws_context_per_thread *pt = lws_container_of(timer, struct lws_context_per_thread, uv.sultimer); lws_usec_t us; lws_pt_lock(pt, __func__); us = __lws_sul_service_ripe(&pt->pt_sul_owner, lws_now_usecs()); if (us) uv_timer_start(&pt->uv.sultimer, lws_uv_sultimer_cb, LWS_US_TO_MS(us), 0); lws_pt_unlock(pt); } static void lws_uv_idle(uv_idle_t *handle #if UV_VERSION_MAJOR == 0 , int status #endif ) { struct lws_context_per_thread *pt = lws_container_of(handle, struct lws_context_per_thread, uv.idle); lws_usec_t us; lws_service_do_ripe_rxflow(pt); /* * is there anybody with pending stuff that needs service forcing? */ if (!lws_service_adjust_timeout(pt->context, 1, pt->tid)) /* -1 timeout means just do forced service */ _lws_plat_service_forced_tsi(pt->context, pt->tid); /* account for sultimer */ lws_pt_lock(pt, __func__); us = __lws_sul_service_ripe(&pt->pt_sul_owner, lws_now_usecs()); if (us) uv_timer_start(&pt->uv.sultimer, lws_uv_sultimer_cb, LWS_US_TO_MS(us), 0); lws_pt_unlock(pt); /* there is nobody who needs service forcing, shut down idle */ uv_idle_stop(handle); } static void lws_io_cb(uv_poll_t *watcher, int status, int revents) { struct lws *wsi = (struct lws *)((uv_handle_t *)watcher)->data; struct lws_context *context = wsi->context; struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; struct lws_pollfd eventfd; if (pt->is_destroyed) return; #if defined(WIN32) || defined(_WIN32) eventfd.fd = watcher->socket; #else eventfd.fd = watcher->io_watcher.fd; #endif eventfd.events = 0; eventfd.revents = 0; if (status < 0) { /* * At this point status will be an UV error, like UV_EBADF, * we treat all errors as LWS_POLLHUP * * You might want to return; instead of servicing the fd in * some cases */ if (status == UV_EAGAIN) return; eventfd.events |= LWS_POLLHUP; eventfd.revents |= LWS_POLLHUP; } else { if (revents & UV_READABLE) { eventfd.events |= LWS_POLLIN; eventfd.revents |= LWS_POLLIN; } if (revents & UV_WRITABLE) { eventfd.events |= LWS_POLLOUT; eventfd.revents |= LWS_POLLOUT; } } lws_service_fd_tsi(context, &eventfd, wsi->tsi); if (pt->destroy_self) { lws_context_destroy(pt->context); return; } uv_idle_start(&pt->uv.idle, lws_uv_idle); } /* * This does not actually stop the event loop. The reason is we have to pass * libuv handle closures through its event loop. So this tries to close all * wsi, and set a flag; when all the wsi closures are finalized then we * actually stop the libuv event loops. */ static void lws_libuv_stop(struct lws_context *context) { struct lws_context_per_thread *pt; int n, m; lwsl_err("%s\n", __func__); if (context->requested_kill) { lwsl_err("%s: ignoring\n", __func__); return; } context->requested_kill = 1; m = context->count_threads; context->being_destroyed = 1; /* * Phase 1: start the close of every dynamic uv handle */ while (m--) { pt = &context->pt[m]; if (pt->pipe_wsi) { uv_poll_stop(pt->pipe_wsi->w_read.uv.pwatcher); lws_destroy_event_pipe(pt->pipe_wsi); pt->pipe_wsi = NULL; } for (n = 0; (unsigned int)n < context->pt[m].fds_count; n++) { struct lws *wsi = wsi_from_fd(context, pt->fds[n].fd); if (!wsi) continue; lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY, __func__ /* no protocol close */); n--; } } lwsl_info("%s: started closing all wsi\n", __func__); /* we cannot have completed... there are at least the cancel pipes */ } static void lws_uv_signal_handler(uv_signal_t *watcher, int signum) { struct lws_context *context = watcher->data; if (context->eventlib_signal_cb) { context->eventlib_signal_cb((void *)watcher, signum); return; } lwsl_err("internal signal handler caught signal %d\n", signum); lws_libuv_stop(watcher->data); } static const int sigs[] = { SIGINT, SIGTERM, SIGSEGV, SIGFPE, SIGHUP }; /* * Closing Phase 2: Close callback for a static UV asset */ static void lws_uv_close_cb_sa(uv_handle_t *handle) { struct lws_context *context = LWS_UV_REFCOUNT_STATIC_HANDLE_TO_CONTEXT(handle); int n; lwsl_info("%s: sa left %d: dyn left: %d\n", __func__, context->count_event_loop_static_asset_handles, context->count_wsi_allocated); /* any static assets left? */ if (LWS_UV_REFCOUNT_STATIC_HANDLE_DESTROYED(handle) || context->count_wsi_allocated) return; /* * That's it... all wsi were down, and now every * static asset lws had a UV handle for is down. * * Stop the loop so we can get out of here. */ for (n = 0; n < context->count_threads; n++) { struct lws_context_per_thread *pt = &context->pt[n]; if (pt->uv.io_loop && !pt->event_loop_foreign) uv_stop(pt->uv.io_loop); } if (!context->pt[0].event_loop_foreign) { lwsl_info("%s: calling lws_context_destroy2\n", __func__); lws_context_destroy2(context); } lwsl_info("%s: all done\n", __func__); } /* * These must be called by protocols that want to use libuv objects directly... * * .... when the libuv object is created... */ void lws_libuv_static_refcount_add(uv_handle_t *h, struct lws_context *context) { LWS_UV_REFCOUNT_STATIC_HANDLE_NEW(h, context); } /* * ... and in the close callback when the object is closed. */ void lws_libuv_static_refcount_del(uv_handle_t *h) { lws_uv_close_cb_sa(h); } static void lws_uv_close_cb(uv_handle_t *handle) { } static void lws_uv_walk_cb(uv_handle_t *handle, void *arg) { if (!uv_is_closing(handle)) uv_close(handle, lws_uv_close_cb); } void lws_close_all_handles_in_loop(uv_loop_t *loop) { uv_walk(loop, lws_uv_walk_cb, NULL); } void lws_libuv_stop_without_kill(const struct lws_context *context, int tsi) { if (context->pt[tsi].uv.io_loop) uv_stop(context->pt[tsi].uv.io_loop); } uv_loop_t * lws_uv_getloop(struct lws_context *context, int tsi) { if (context->pt[tsi].uv.io_loop) return context->pt[tsi].uv.io_loop; return NULL; } int lws_libuv_check_watcher_active(struct lws *wsi) { uv_handle_t *h = (uv_handle_t *)wsi->w_read.uv.pwatcher; if (!h) return 0; return uv_is_active(h); } #if defined(LWS_WITH_PLUGINS) && (UV_VERSION_MAJOR > 0) int lws_uv_plugins_init(struct lws_context *context, const char * const *d) { struct lws_plugin_capability lcaps; struct lws_plugin *plugin; lws_plugin_init_func initfunc; int m, ret = 0; void *v; uv_dirent_t dent; uv_fs_t req; char path[256]; uv_lib_t lib; int pofs = 0; #if defined(__MINGW32__) || !defined(WIN32) pofs = 3; #endif lib.errmsg = NULL; lib.handle = NULL; uv_loop_init(&context->uv.loop); lwsl_notice(" Plugins:\n"); while (d && *d) { lwsl_notice(" Scanning %s\n", *d); m =uv_fs_scandir(&context->uv.loop, &req, *d, 0, NULL); if (m < 1) { lwsl_err("Scandir on %s failed\n", *d); return 1; } while (uv_fs_scandir_next(&req, &dent) != UV_EOF) { if (strlen(dent.name) < 7) continue; lwsl_notice(" %s\n", dent.name); lws_snprintf(path, sizeof(path) - 1, "%s/%s", *d, dent.name); if (uv_dlopen(path, &lib)) { uv_dlerror(&lib); lwsl_err("Error loading DSO: %s\n", lib.errmsg); uv_dlclose(&lib); goto bail; } /* we could open it, can we get his init function? */ #if !defined(WIN32) && !defined(__MINGW32__) m = lws_snprintf(path, sizeof(path) - 1, "init_%s", dent.name + pofs /* snip lib... */); path[m - 3] = '\0'; /* snip the .so */ #else m = lws_snprintf(path, sizeof(path) - 1, "init_%s", dent.name + pofs); path[m - 4] = '\0'; /* snip the .dll */ #endif if (uv_dlsym(&lib, path, &v)) { uv_dlerror(&lib); lwsl_err("%s: Failed to get '%s' on %s: %s\n", __func__, path, dent.name, lib.errmsg); uv_dlclose(&lib); goto bail; } initfunc = (lws_plugin_init_func)v; lcaps.api_magic = LWS_PLUGIN_API_MAGIC; m = initfunc(context, &lcaps); if (m) { lwsl_err("Init %s failed %d\n", dent.name, m); goto skip; } plugin = lws_malloc(sizeof(*plugin), "plugin"); if (!plugin) { uv_dlclose(&lib); lwsl_err("OOM\n"); goto bail; } plugin->list = context->plugin_list; context->plugin_list = plugin; lws_strncpy(plugin->name, dent.name, sizeof(plugin->name)); plugin->lib = lib; plugin->caps = lcaps; context->plugin_protocol_count += lcaps.count_protocols; context->plugin_extension_count += lcaps.count_extensions; continue; skip: uv_dlclose(&lib); } bail: uv_fs_req_cleanup(&req); d++; } return ret; } int lws_uv_plugins_destroy(struct lws_context *context) { struct lws_plugin *plugin = context->plugin_list, *p; lws_plugin_destroy_func func; char path[256]; int pofs = 0; void *v; int m; #if defined(__MINGW32__) || !defined(WIN32) pofs = 3; #endif if (!plugin) return 0; while (plugin) { p = plugin; #if !defined(WIN32) && !defined(__MINGW32__) m = lws_snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + pofs); path[m - 3] = '\0'; #else m = lws_snprintf(path, sizeof(path) - 1, "destroy_%s", plugin->name + pofs); path[m - 4] = '\0'; #endif if (uv_dlsym(&plugin->lib, path, &v)) { uv_dlerror(&plugin->lib); lwsl_err("Failed to get %s on %s: %s", path, plugin->name, plugin->lib.errmsg); } else { func = (lws_plugin_destroy_func)v; m = func(context); if (m) lwsl_err("Destroying %s failed %d\n", plugin->name, m); } uv_dlclose(&p->lib); plugin = p->list; p->list = NULL; free(p); } context->plugin_list = NULL; while (uv_loop_close(&context->uv.loop)) ; return 0; } #endif static int elops_init_context_uv(struct lws_context *context, const struct lws_context_creation_info *info) { int n; context->eventlib_signal_cb = info->signal_cb; for (n = 0; n < context->count_threads; n++) context->pt[n].w_sigint.context = context; return 0; } static int elops_destroy_context1_uv(struct lws_context *context) { struct lws_context_per_thread *pt; int n, m = 0; for (n = 0; n < context->count_threads; n++) { int budget = 10000; pt = &context->pt[n]; /* only for internal loops... */ if (!pt->event_loop_foreign) { while (budget-- && (m = uv_run(pt->uv.io_loop, UV_RUN_NOWAIT))) ; if (m) lwsl_info("%s: tsi %d: not all closed\n", __func__, n); } } /* call destroy2 if internal loop */ return !context->pt[0].event_loop_foreign; } static int elops_destroy_context2_uv(struct lws_context *context) { struct lws_context_per_thread *pt; int n, internal = 0; for (n = 0; n < context->count_threads; n++) { pt = &context->pt[n]; /* only for internal loops... */ if (!pt->event_loop_foreign && pt->uv.io_loop) { internal = 1; if (!context->finalize_destroy_after_internal_loops_stopped) uv_stop(pt->uv.io_loop); else { #if UV_VERSION_MAJOR > 0 uv_loop_close(pt->uv.io_loop); #endif lws_free_set_NULL(pt->uv.io_loop); } } } return internal; } static int elops_wsi_logical_close_uv(struct lws *wsi) { if (!lws_socket_is_valid(wsi->desc.sockfd)) return 0; if (wsi->listener || wsi->event_pipe) { lwsl_debug("%s: %p: %d %d stop listener / pipe poll\n", __func__, wsi, wsi->listener, wsi->event_pipe); if (wsi->w_read.uv.pwatcher) uv_poll_stop(wsi->w_read.uv.pwatcher); } lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi); /* * libuv has to do his own close handle processing asynchronously */ lws_libuv_closehandle(wsi); return 1; /* do not complete the wsi close, uv close cb will do it */ } static int elops_check_client_connect_ok_uv(struct lws *wsi) { if (lws_libuv_check_watcher_active(wsi)) { lwsl_warn("Waiting for libuv watcher to close\n"); return 1; } return 0; } static void lws_libuv_closewsi_m(uv_handle_t* handle) { lws_sockfd_type sockfd = (lws_sockfd_type)(lws_intptr_t)handle->data; lwsl_debug("%s: sockfd %d\n", __func__, sockfd); compatible_close(sockfd); lws_free(handle); } static void elops_close_handle_manually_uv(struct lws *wsi) { uv_handle_t *h = (uv_handle_t *)wsi->w_read.uv.pwatcher; lwsl_debug("%s: lws_libuv_closehandle: wsi %p\n", __func__, wsi); /* * the "manual" variant only closes the handle itself and the * related fd. handle->data is the fd. */ h->data = (void *)(lws_intptr_t)wsi->desc.sockfd; /* * We take responsibility to close / destroy these now. * Remove any trace from the wsi. */ wsi->desc.sockfd = LWS_SOCK_INVALID; wsi->w_read.uv.pwatcher = NULL; wsi->told_event_loop_closed = 1; uv_close(h, lws_libuv_closewsi_m); } static int elops_accept_uv(struct lws *wsi) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; wsi->w_read.context = wsi->context; wsi->w_read.uv.pwatcher = lws_malloc(sizeof(*wsi->w_read.uv.pwatcher), "uvh"); if (!wsi->w_read.uv.pwatcher) return -1; if (wsi->role_ops->file_handle) uv_poll_init(pt->uv.io_loop, wsi->w_read.uv.pwatcher, (int)(long long)wsi->desc.filefd); else uv_poll_init_socket(pt->uv.io_loop, wsi->w_read.uv.pwatcher, wsi->desc.sockfd); ((uv_handle_t *)wsi->w_read.uv.pwatcher)->data = (void *)wsi; return 0; } static void elops_io_uv(struct lws *wsi, int flags) { struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi]; struct lws_io_watcher *w = &wsi->w_read; int current_events = w->actual_events & (UV_READABLE | UV_WRITABLE); lwsl_debug("%s: %p: %d\n", __func__, wsi, flags); /* w->context is set after the loop is initialized */ if (!pt->uv.io_loop || !w->context) { lwsl_info("%s: no io loop yet\n", __func__); return; } if (!((flags & (LWS_EV_START | LWS_EV_STOP)) && (flags & (LWS_EV_READ | LWS_EV_WRITE)))) { lwsl_err("%s: assert: flags %d", __func__, flags); assert(0); } if (!w->uv.pwatcher || wsi->told_event_loop_closed) { lwsl_err("%s: no watcher\n", __func__); return; } if (flags & LWS_EV_START) { if (flags & LWS_EV_WRITE) current_events |= UV_WRITABLE; if (flags & LWS_EV_READ) current_events |= UV_READABLE; uv_poll_start(w->uv.pwatcher, current_events, lws_io_cb); } else { if (flags & LWS_EV_WRITE) current_events &= ~UV_WRITABLE; if (flags & LWS_EV_READ) current_events &= ~UV_READABLE; if (!(current_events & (UV_READABLE | UV_WRITABLE))) uv_poll_stop(w->uv.pwatcher); else uv_poll_start(w->uv.pwatcher, current_events, lws_io_cb); } w->actual_events = current_events; } static int elops_init_vhost_listen_wsi_uv(struct lws *wsi) { struct lws_context_per_thread *pt; int n; if (!wsi) return 0; if (wsi->w_read.context) return 0; pt = &wsi->context->pt[(int)wsi->tsi]; if (!pt->uv.io_loop) return 0; wsi->w_read.context = wsi->context; wsi->w_read.uv.pwatcher = lws_malloc(sizeof(*wsi->w_read.uv.pwatcher), "uvh"); if (!wsi->w_read.uv.pwatcher) return -1; n = uv_poll_init_socket(pt->uv.io_loop, wsi->w_read.uv.pwatcher, wsi->desc.sockfd); if (n) { lwsl_err("uv_poll_init failed %d, sockfd=%p\n", n, (void *)(lws_intptr_t)wsi->desc.sockfd); return -1; } ((uv_handle_t *)wsi->w_read.uv.pwatcher)->data = (void *)wsi; elops_io_uv(wsi, LWS_EV_START | LWS_EV_READ); return 0; } static void elops_run_pt_uv(struct lws_context *context, int tsi) { if (context->pt[tsi].uv.io_loop) uv_run(context->pt[tsi].uv.io_loop, 0); } static void elops_destroy_pt_uv(struct lws_context *context, int tsi) { struct lws_context_per_thread *pt = &context->pt[tsi]; int m, ns; lwsl_info("%s: %d\n", __func__, tsi); if (!lws_check_opt(context->options, LWS_SERVER_OPTION_LIBUV)) return; if (!pt->uv.io_loop) return; if (pt->event_loop_destroy_processing_done) return; pt->event_loop_destroy_processing_done = 1; if (!pt->event_loop_foreign) { uv_signal_stop(&pt->w_sigint.uv.watcher); ns = LWS_ARRAY_SIZE(sigs); if (lws_check_opt(context->options, LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN)) ns = 2; for (m = 0; m < ns; m++) { uv_signal_stop(&pt->uv.signals[m]); uv_close((uv_handle_t *)&pt->uv.signals[m], lws_uv_close_cb_sa); } } else lwsl_debug("%s: not closing pt signals\n", __func__); uv_timer_stop(&pt->uv.sultimer); uv_close((uv_handle_t *)&pt->uv.sultimer, lws_uv_close_cb_sa); uv_idle_stop(&pt->uv.idle); uv_close((uv_handle_t *)&pt->uv.idle, lws_uv_close_cb_sa); } /* * This needs to be called after vhosts have been defined. * * If later, after server start, another vhost is added, this must be * called again to bind the vhost */ int elops_init_pt_uv(struct lws_context *context, void *_loop, int tsi) { struct lws_context_per_thread *pt = &context->pt[tsi]; struct lws_vhost *vh = context->vhost_list; int status = 0, n, ns, first = 1; uv_loop_t *loop = (uv_loop_t *)_loop; if (!pt->uv.io_loop) { if (!loop) { loop = lws_malloc(sizeof(*loop), "libuv loop"); if (!loop) { lwsl_err("OOM\n"); return -1; } #if UV_VERSION_MAJOR > 0 uv_loop_init(loop); #else lwsl_err("This libuv is too old to work...\n"); return 1; #endif pt->event_loop_foreign = 0; } else { lwsl_notice(" Using foreign event loop...\n"); pt->event_loop_foreign = 1; } pt->uv.io_loop = loop; uv_idle_init(loop, &pt->uv.idle); LWS_UV_REFCOUNT_STATIC_HANDLE_NEW(&pt->uv.idle, context); ns = LWS_ARRAY_SIZE(sigs); if (lws_check_opt(context->options, LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN)) ns = 2; if (!pt->event_loop_foreign) { assert(ns <= (int)LWS_ARRAY_SIZE(pt->uv.signals)); for (n = 0; n < ns; n++) { uv_signal_init(loop, &pt->uv.signals[n]); LWS_UV_REFCOUNT_STATIC_HANDLE_NEW(&pt->uv.signals[n], context); pt->uv.signals[n].data = pt->context; uv_signal_start(&pt->uv.signals[n], lws_uv_signal_handler, sigs[n]); } } } else first = 0; /* * Initialize the accept wsi read watcher with all the listening sockets * and register a callback for read operations * * We have to do it here because the uv loop(s) are not * initialized until after context creation. */ while (vh) { if (elops_init_vhost_listen_wsi_uv(vh->lserv_wsi) == -1) return -1; vh = vh->vhost_next; } if (!first) return status; uv_timer_init(pt->uv.io_loop, &pt->uv.sultimer); LWS_UV_REFCOUNT_STATIC_HANDLE_NEW(&pt->uv.sultimer, context); return status; } static void lws_libuv_closewsi(uv_handle_t* handle) { struct lws *wsi = (struct lws *)handle->data; struct lws_context *context = lws_get_context(wsi); struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; #if defined(LWS_WITH_SERVER) int lspd = 0; #endif lwsl_info("%s: %p\n", __func__, wsi); /* * We get called back here for every wsi that closes */ #if defined(LWS_WITH_SERVER) if (wsi->role_ops == &role_ops_listen && wsi->context->deprecated) { lspd = 1; context->deprecation_pending_listen_close_count--; if (!context->deprecation_pending_listen_close_count) lspd = 2; } #endif lws_pt_lock(pt, __func__); __lws_close_free_wsi_final(wsi); lws_pt_unlock(pt); /* it's our job to close the handle finally */ lws_free(handle); #if defined(LWS_WITH_SERVER) if (lspd == 2 && context->deprecation_cb) { lwsl_notice("calling deprecation callback\n"); context->deprecation_cb(); } #endif lwsl_info("%s: sa left %d: dyn left: %d (rk %d)\n", __func__, context->count_event_loop_static_asset_handles, context->count_wsi_allocated, context->requested_kill); /* * eventually, we closed all the wsi... */ if (context->requested_kill && !context->count_wsi_allocated) { struct lws_vhost *vh = context->vhost_list; int m; /* * Start Closing Phase 2: close of static handles */ lwsl_info("%s: all lws dynamic handles down, closing static\n", __func__); for (m = 0; m < context->count_threads; m++) elops_destroy_pt_uv(context, m); /* protocols may have initialized libuv objects */ while (vh) { lws_vhost_destroy1(vh); vh = vh->vhost_next; } if (!context->count_event_loop_static_asset_handles && context->pt[0].event_loop_foreign) { lwsl_info("%s: call lws_context_destroy2\n", __func__); lws_context_destroy2(context); } } } void lws_libuv_closehandle(struct lws *wsi) { uv_handle_t* handle; if (!wsi->w_read.uv.pwatcher) return; if (wsi->told_event_loop_closed) { // assert(0); return; } lwsl_debug("%s: %p\n", __func__, wsi); wsi->told_event_loop_closed = 1; /* * The normal close path attaches the related wsi as the * handle->data. */ handle = (uv_handle_t *)wsi->w_read.uv.pwatcher; /* ensure we can only do this once */ wsi->w_read.uv.pwatcher = NULL; uv_close(handle, lws_libuv_closewsi); } struct lws_event_loop_ops event_loop_ops_uv = { /* name */ "libuv", /* init_context */ elops_init_context_uv, /* destroy_context1 */ elops_destroy_context1_uv, /* destroy_context2 */ elops_destroy_context2_uv, /* init_vhost_listen_wsi */ elops_init_vhost_listen_wsi_uv, /* init_pt */ elops_init_pt_uv, /* wsi_logical_close */ elops_wsi_logical_close_uv, /* check_client_connect_ok */ elops_check_client_connect_ok_uv, /* close_handle_manually */ elops_close_handle_manually_uv, /* accept */ elops_accept_uv, /* io */ elops_io_uv, /* run_pt */ elops_run_pt_uv, /* destroy_pt */ elops_destroy_pt_uv, /* destroy wsi */ NULL, /* periodic_events_available */ 0, };
893772.c
/* ********************************************************************************************************* * uC/TCP-IP * The Embedded TCP/IP Suite * * Copyright 2004-2021 Silicon Laboratories Inc. www.silabs.com * * SPDX-License-Identifier: APACHE-2.0 * * This software is subject to an open source license and is distributed by * Silicon Laboratories Inc. pursuant to the terms of the Apache License, * Version 2.0 available at www.apache.org/licenses/LICENSE-2.0. * ********************************************************************************************************* */ /* ********************************************************************************************************* * * NETWORK DEVICE DRIVER * * Xilinx Local Link Hard TEMAC Driver (Mode DMA) * Support Both Soft and Hard DMA * * Filename : net_dev_xps_ll_temac_dma.c * Version : V3.06.01 ********************************************************************************************************* * Note(s) : (1) Assumes uC/TCP-IP V2.20.00 (or more recent version) is included in the project build. * * (2) This driver version does not support the extended Multicast mode. ********************************************************************************************************* */ /* ********************************************************************************************************* * INCLUDE FILES ********************************************************************************************************* */ #define MICRIUM_SOURCE #define NET_DEV_XPS_LL_TEMAC_MODULE #include <Source/net.h> #include <Source/net_util.h> #include <IF/net_if.h> #include <IF/net_if_ether.h> #include <cpu_cache.h> #include "net_dev_xps_ll_temac_dma.h" #ifdef NET_IF_ETHER_MODULE_EN /* ********************************************************************************************************* * LOCAL DEFINES ********************************************************************************************************* */ #define TEMAC_INDIRECT_REG_ACCESS_DLY_MS 1 /* Delay for indirect register access */ #define TEMAC_INDIRECT_REG_ACCESS_TO_CNT 4 /* Timeout count for indirect register access */ #define TEMAC_MDIO_DIV_DFT 29 #define DMA_NO_CHANGE 0x0000 /* Shift constants for selected masks */ #define DMA_CR_IRQ_TIMEOUT_SHIFT 24 #define DMA_CR_IRQ_COUNT_SHIFT 16 #define DMA_CR_MSB_ADDR_SHIFT 12 #define TEMAC_EMMC_LINKSPD_10 0x00000000 /* TEMAC_EMCFG_LINKSPD_MASK for 10 Mbit */ #define TEMAC_EMMC_LINKSPD_100 0x40000000 /* TEMAC_EMCFG_LINKSPD_MASK for 100 Mbit */ #define TEMAC_EMMC_LINKSPD_1000 0x80000000 /* TEMAC_EMCFG_LINKSPD_MASK for 1000 Mbit */ #define DMA_USERAPP4_INIT_VAL 0xFFFFFFFF /* Constant used to init DMA_AppData4 filed in Rx DMA desc */ #define DMA_DESC_ALIGN 64 /* DMA descriptors alignment */ #define MDC_FREQ_MAX 2500000 /* MDC Max Freq 2.5MHz */ #define MCAST_TAB_ENTRIES_NUM 4 /* Mulicast table entries number */ #define INT_DISABLE 0 #define INT_ENABLE 1 /* ********************************************************************************************************* * LOCAL DATA TYPES * * Note(s) : (1) Instance specific data area structures should be defined below. The data area * structure typically includes error counters and variables used to track the * state of the device. Variables required for correct operation of the device * MUST NOT be defined globally and should instead be included within the instance * specific data area structure and referenced as pif->Dev_Data structure members. * * (2) DMA based devices may require more than one type of descriptor. Each descriptor * type should be defined below. An example descriptor has been provided. * * (3) The Tail pointer is used to keep the current DMA receive chain tail position, * this pointer will be updated each time completed receive descriptor are processed * by the software. * * (4) All device drivers MUST track the addresses of ALL buffers that have been * transmitted and not yet acknowledged through transmit complete interrupts. ********************************************************************************************************* */ typedef struct dev_desc DEV_DESC; /* ----------------- DMA DESCRIPTOR DATA TYPE ----------------- */ struct dev_desc { CPU_REG32 DMA_NextDescAddr; /* DMA Next descriptor address. */ CPU_REG32 DMA_CurrBufAddr; /* DMA Current buffer address. */ CPU_REG32 DMA_CurrBufLen; /* DMA Current buffer len */ CPU_REG32 DMA_CtrlAndStatus; /* DMA Control and status. */ CPU_REG32 DMA_AppData1; /* DMA Application specific Data */ CPU_REG32 DMA_AppData2; /* DMA Application specific Data */ CPU_REG32 DMA_AppData3; /* DMA Application specific Data */ CPU_REG32 DMA_AppData4; /* DMA Application specific Data */ CPU_REG08 RSVD[32]; /* DMA Desc must be 64 bytes aligned */ }; /* ------------------- DEVICE INSTANCE DATA ------------------- */ typedef struct net_dev_data { #if (NET_CTR_CFG_STAT_EN == DEF_ENABLED) NET_CTR StatRxCtrRx; NET_CTR StatRxCtrRxISR; NET_CTR StatTxCtrTxISR; NET_CTR StatRxCtrTaskSignalSelf; NET_CTR StatRxCtrTaskSignalNone; #endif #if (NET_CTR_CFG_ERR_EN == DEF_ENABLED) NET_CTR ErrRxCtrDataAreaAlloc; NET_CTR ErrRxCtrTaskSignalFail; #endif MEM_POOL RxDescPool; MEM_POOL TxDescPool; DEV_DESC *RxBufDescPtrStart; DEV_DESC *RxBufDescPtrCur; DEV_DESC *RxBufDescPtrEnd; DEV_DESC *RxBufDescPtrTail; /* See Note #3. */ DEV_DESC *TxBufDescPtrStart; DEV_DESC *TxBufDescPtrCur; DEV_DESC *TxBufDescCompPtr; /* See Note #4. */ DEV_DESC *TxBufDescPtrEnd; CPU_ADDR DMA_AddrBase; CPU_ADDR DMA_AddrRx; CPU_ADDR DMA_AddrTx; } NET_DEV_DATA; /* ********************************************************************************************************* * LOCAL FUNCTION PROTOTYPES * * Note(s) : (1) Device driver functions may be arbitrarily named. However, it is recommended that device * driver functions be named using the names provided below. All driver function prototypes * should be located within the driver C source file ('net_dev_&&&.c') & be declared as * static functions to prevent name clashes with other network protocol suite device drivers. ********************************************************************************************************* */ /* -------- FNCT'S COMMON TO ALL DEV'S -------- */ static void NetDev_Init (NET_IF *pif, NET_ERR *perr); static void NetDev_Start (NET_IF *pif, NET_ERR *perr); static void NetDev_Stop (NET_IF *pif, NET_ERR *perr); static void NetDev_Rx (NET_IF *pif, CPU_INT08U **p_data, CPU_INT16U *size, NET_ERR *perr); static void NetDev_Tx (NET_IF *pif, CPU_INT08U *p_data, CPU_INT16U size, NET_ERR *perr); static void NetDev_AddrMulticastAdd (NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT08U addr_hw_len, NET_ERR *perr); static void NetDev_AddrMulticastRemove(NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT08U addr_hw_len, NET_ERR *perr); static void NetDev_ISR_Handler (NET_IF *pif, NET_DEV_ISR_TYPE type); static void NetDev_IO_Ctrl (NET_IF *pif, CPU_INT08U opt, void *p_data, NET_ERR *perr); static void NetDev_MII_Rd (NET_IF *pif, CPU_INT08U phy_addr, CPU_INT08U reg_addr, CPU_INT16U *p_data, NET_ERR *perr); static void NetDev_MII_Wr (NET_IF *pif, CPU_INT08U phy_addr, CPU_INT08U reg_addr, CPU_INT16U data, NET_ERR *perr); /* ----- FNCT'S COMMON TO DMA-BASED DEV'S ----- */ static void NetDev_RxDescInit (NET_IF *pif, NET_ERR *perr); static void NetDev_RxDescFreeAll (NET_IF *pif, NET_ERR *perr); static void NetDev_RxDescPtrCurInc (NET_IF *pif); static void NetDev_TxDescInit (NET_IF *pif, NET_ERR *perr); /* ------ FNCT'S FOR XPS_LL_TEMAC DEV'S ------- */ static void NetDev_SetCoalesce (NET_IF *pif, CPU_INT32U dma_ch_addr, CPU_INT08U cntr, CPU_INT08U timer_val); static void NetDev_DMA_Reset (NET_IF *pif, NET_ERR *perr); static void NetDev_DMA_ErrRecover (NET_IF *pif, NET_ERR *perr); static void NetDev_DMA_EnDisChInt (NET_IF *pif, CPU_INT32U dma_ch_addr, CPU_INT08U en); #ifdef NET_MCAST_MODULE_EN static void NetDev_AddrMulticastGet (NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT32U entry, NET_ERR *perr); #endif static void NetDev_IndirectWr_32 (NET_IF *pif, CPU_INT32U reg_offset, CPU_INT32U val); static CPU_INT32U NetDev_IndirectRd_32 (NET_IF *pif, CPU_INT32U reg_offset); /* ********************************************************************************************************* * LOCAL TABLES ********************************************************************************************************* */ #ifdef NET_MCAST_MODULE_EN /* Addr used to chk avail entries in multicast tbl */ static CPU_INT08U Multicast_FreeHW_Addr1[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static CPU_INT08U Multicast_FreeHW_Addr2[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; #endif /* ********************************************************************************************************* * NETWORK DEVICE DRIVER API * * Note(s) : (1) Device driver API structures are used by applications during calls to NetIF_Add(). This * API structure allows higher layers to call specific device driver functions via function * pointer instead of by name. This enables the network protocol suite to compile & operate * with multiple device drivers. * * (2) In most cases, the API structure provided below SHOULD suffice for most device drivers * exactly as is with the exception that the API structure's name which MUST be unique & * SHOULD clearly identify the device being implemented. For example, the Cirrus Logic * CS8900A Ethernet controller's API structure should be named NetDev_API_CS8900A[]. * * The API structure MUST also be externally declared in the device driver header file * ('net_dev_&&&.h') with the exact same name & type. ********************************************************************************************************* */ /* XPS_LL_TEMAC dev API fnct ptrs : */ const NET_DEV_API_ETHER NetDev_API_XPS_LL_TEMAC_DMA = { NetDev_Init, /* Init/add */ NetDev_Start, /* Start */ NetDev_Stop, /* Stop */ NetDev_Rx, /* Rx */ NetDev_Tx, /* Tx */ NetDev_AddrMulticastAdd, /* Multicast addr add */ NetDev_AddrMulticastRemove, /* Multicast addr remove */ NetDev_ISR_Handler, /* ISR handler */ NetDev_IO_Ctrl, /* I/O ctrl */ NetDev_MII_Rd, /* Phy reg rd */ NetDev_MII_Wr /* Phy reg wr */ }; /* ********************************************************************************************************* * REGISTER DEFINITIONS * * Note(s) : (1) Device register definitions SHOULD NOT be absolute & SHOULD use the provided base address * within the device configuration structure (see 'net_dev_cfg.c'), as well as each device's * register definition structure in order to properly resolve register addresses at run-time * by mapping the device register definition structure onto an interface's base address. * * (2) The device register definition structure MUST take into account appropriate register * offsets & apply reserved space as required. The registers listed within the register * definition structure MUST reflect the exact ordering and data sizes illustrated in the * device user guide. * * (3) Device registers SHOULD be declared as volatile variables so that compilers do NOT cache * register values but MUST perform the steps to read or write each register value for every * register read or write access. * * An example device register structure is provided below. ********************************************************************************************************* */ typedef struct net_dev { CPU_REG32 TEMAC_REG_RAF; /* Reset and address filter register */ CPU_REG32 TEMAC_REG_TPF; /* Transmit pause frame regsiter */ CPU_REG32 TEMAC_REG_IFGP; /* Transmit inter-frame gap adjustement register */ CPU_REG32 TEMAC_REG_IS; /* Interrupt status register */ CPU_REG32 TEMAC_REG_IP; /* Interrupt pending register */ CPU_REG32 TEMAC_REG_IE; /* Interrupt enable register */ CPU_REG32 TEMAC_REG_TTAG; /* Tx VLAN TAG register */ CPU_REG32 TEMAC_REG_RTAG; /* Rx VLAN TAG register */ CPU_REG32 TEMAC_REG_MSW; /* Most significant word data register */ CPU_REG32 TEMAC_REG_LSW; /* Least significant word data register */ CPU_REG32 TEMAC_REG_CTL; /* Control register */ CPU_REG32 TEMAC_REG_RDY; /* Ready status register */ CPU_REG32 TEMAC_REG_UAWL; /* Unicast address, extended/new multicast mode register */ CPU_REG32 TEMAC_REG_UAWU; /* Unicast address, extended/new multicast mode register */ CPU_REG32 TEMAC_REG_TPID0; /* TPID0 register */ CPU_REG32 TEMAC_REG_TPID1; /* TPID1 register */ } NET_DEV; /* ********************************************************************************************************* * TEMAC CORE REGSITERS ADDRESS ********************************************************************************************************* */ /* These registers are accessed indirecly through the regsiters */ /* MSW, LSW and CTL */ #define TEMAC_REG_RCW0 0x00000200 /* Rx configuration word 0 */ #define TEMAC_REG_RCW1 0x00000240 /* Rx configuration word 1 */ #define TEMAC_REG_TC 0x00000280 /* Tx configuration */ #define TEMAC_REG_FCC 0x000002C0 /* Flow control configuration */ #define TEMAC_REG_EMMC 0x00000300 /* EMAC mode configuration */ #define TEMAC_REG_PHYC 0x00000320 /* RGMII/SGMII configuration */ #define TEMAC_REG_MC 0x00000340 /* Management configuration */ #define TEMAC_REG_UAW0 0x00000380 /* Unicast address word 0 */ #define TEMAC_REG_UAW1 0x00000384 /* Unicast address word 1 */ #define TEMAC_REG_MAW0 0x00000388 /* Multicast address word 0 */ #define TEMAC_REG_MAW1 0x0000038C /* Multicast address word 1 */ #define TEMAC_REG_AFM 0x00000390 /* Address Filter (promiscuous) mode */ #define TEMAC_REG_TIS 0x000003A0 /* Interrupt status */ #define TEMAC_REG_TIE 0x000003A4 /* Interrupt enable */ #define TEMAC_REG_MIIMWD 0x000003B0 /* MII management write data */ #define TEMAC_REG_MIIMAI 0x000003B4 /* MII management access initiate */ /* ********************************************************************************************************* * REGISTER BIT DEFINITIONS * * Note(s) : (1) All necessary register bit definitions should be defined within this section. ********************************************************************************************************* */ /* ********************************************************************************************************* * TEMAC REGISTER BIT MASKS ********************************************************************************************************* */ /* ----------- Reset and Address filter bit masks ------------- */ #define TEMAC_MASK_RAF_HTRST 0x00000001 /* TEMAC Reset */ #define TEMAC_MASK_RAF_MCSTREJ 0x00000002 /* Reject receive multicast destination address */ #define TEMAC_MASK_RAF_BCSTREJ 0x00000004 /* Reject receive broadcast destination address */ #define TEMAC_MASK_RAF_TXVTAGMODE 0x00000018 /* Tx VLAN TAG mode */ #define TEMAC_MASK_RAF_RXVTAGMODE 0x00000060 /* Rx VLAN TAG mode */ #define TEMAC_MASK_RAF_TXVSTRPMODE 0x00000180 /* Tx VLAN STRIP mode */ #define TEMAC_MASK_RAF_RXVSTRPMODE 0x00000600 /* Rx VLAN STRIP mode */ #define TEMAC_MASK_RAF_NEWFNCENBL 0x00000800 /* New function mode */ #define TEMAC_MASK_RAF_EMULTIFLTRENBL 0x00001000 /* Multicast Filtering mode */ #define TEMAC_RAF_TXVTAGMODE_SHIFT 3 /* Tx Tag mode shift bits */ #define TEMAC_RAF_RXVTAGMODE_SHIFT 5 /* Rx Tag mode shift bits */ #define TEMAC_RAF_TXVSTRPMODE_SHIFT 7 /* Tx strip mode shift bits */ #define TEMAC_RAF_RXVSTRPMODE_SHIFT 9 /* Rx Strip mode shift bits */ /* ---------- Transmit Pause Frame Register bit masks --------- */ #define TEMAC_MASK_TPF_TPFV 0x0000FFFF /* Tx pause frame value */ /* --- Transmit Inter-Frame Gap Adjustement Reg. bit masks --- */ #define TEMAC_MASK_TFGP_IFGP 0x0000007F /* Transmit inter-frame gap adjustment value */ /* -------------- Interrupt register bit masks -------------- */ #define TEMAC_MASK_INT_HARDACSCMPLT 0x00000001 /* Hard register access complete */ #define TEMAC_MASK_INT_AUTONEG 0x00000002 /* Auto negotiation complete */ #define TEMAC_MASK_INT_RC 0x00000004 /* Receive complete */ #define TEMAC_MASK_INT_RXRJECT 0x00000008 /* Receive frame rejected */ #define TEMAC_MASK_INT_RXFIFOOVR 0x00000010 /* Receive fifo overrun */ #define TEMAC_MASK_INT_TC 0x00000020 /* Transmit complete */ #define TEMAC_MASK_INT_RXDCM_LOCK 0x00000040 /* Rx Dcm Lock */ #define TEMAC_MASK_INT_MGT_LOCK 0x00000080 /* MGT clock Lock */ #define TEMAC_MASK_INT_ALL 0x0000003F /* All the ints */ /* INT bits that indicate receive errors */ #define TEMAC_MASK_INT_RECV_ERROR (TEMAC_MASK_INT_RXRJECT | \ TEMAC_MASK_INT_RXFIFOOVR) /* ---------------- Control register bit masks ---------------- */ #define TEMAC_MASK_CTL_WEN 0x00008000 /* Write Enable */ /* ------ Receive Configuration Word 1 (RCW1) bit masks ------- */ #define TEMAC_MASK_RCW1_RST 0x80000000 /* Reset */ #define TEMAC_MASK_RCW1_JUM 0x40000000 /* Jumbo frame enable */ #define TEMAC_MASK_RCW1_FCS 0x20000000 /* In-Band FCS enable (FCS not stripped) */ #define TEMAC_MASK_RCW1_RX 0x10000000 /* Receiver enable */ #define TEMAC_MASK_RCW1_VLAN 0x08000000 /* VLAN frame enable */ #define TEMAC_MASK_RCW1_HD 0x04000000 /* Half duplex mode */ #define TEMAC_MASK_RCW1_LT_DIS 0x02000000 /* Length/type field valid check disable */ #define TEMAC_MASK_RCW1_PAUSEADDR 0x0000FFFF /* Pause frame source address */ /* --------- Transmitter Configuration (TC) bit masks --------- */ #define TEMAC_MASK_TC_RST 0x80000000 /* Reset */ #define TEMAC_MASK_TC_JUM 0x40000000 /* Jumbo frame enable */ #define TEMAC_MASK_TC_FCS 0x20000000 /* In-Band FCS enable (FCS not generated) */ #define TEMAC_MASK_TC_TX 0x10000000 /* Transmitter enable */ #define TEMAC_MASK_TC_VLAN 0x08000000 /* VLAN frame enable */ #define TEMAC_MASK_TC_HD 0x04000000 /* Half duplex mode */ #define TEMAC_MASK_TC_IFG 0x02000000 /* Inter-frame gap adjustment enable */ /* ------------------ Ready Status bit masks ------------------ */ #define TEMAC_MASK_RDY_FABR_RR 0x00000001 /* Fabric read ready */ #define TEMAC_MASK_RDY_MIIM_RR 0x00000002 /* MII management read ready */ #define TEMAC_MASK_RDY_MIIM_WR 0x00000004 /* MII management write ready */ #define TEMAC_MASK_RDY_AF_RR 0x00000008 /* Address filter read ready */ #define TEMAC_MASK_RDY_AF_WR 0x00000010 /* Address filter write ready */ #define TEMAC_MASK_RDY_CFG_RR 0x00000020 /* Configuration register read ready */ #define TEMAC_MASK_RDY_CFG_WR 0x00000040 /* Configuration register write ready */ #define TEMAC_MASK_RDY_HARD_ACS_RDY 0x00010000 /* Hard register access ready */ /* --------------- EMAC mode Configuration (EMMC) ------------- */ #define TEMAC_MASK_EMMC_LINKSPEED 0xC0000000 /* Link speed */ #define TEMAC_MASK_EMMC_RGMII 0x20000000 /* RGMII mode enable */ #define TEMAC_MASK_EMMC_SGMII 0x10000000 /* SGMII mode enable */ #define TEMAC_MASK_EMMC_GPCS 0x08000000 /* 1000BaseX mode enable */ #define TEMAC_MASK_EMMC_HOST 0x04000000 /* Host interface enable */ /* ------ EMAC Management Configuration (MC) bit masks -------- */ #define TEMAC_MASK_MC_MDIOEN 0x00000040 /* MII management enable */ #define TEMAC_MC_CLOCK_DIVIDE_MAX 0x3F /* Maximum MDIO divisor */ /* ---------- EMAC Unicast Address Register Word 1 ------------ */ #define TEMAC_MASK_UAW1_UNICASTADDR 0x0000FFFF /* Station address bits [47:32] */ /* Station address bits [31:0] */ /* are stored in register UAW0 */ /* ------ Media Independent Interface Management (MIIM) ------- */ #define TEMAC_MASK_MIIM_REGAD 0x1F /* MII Phy register address (REGAD) */ #define TEMAC_MASK_MIIM_PHYAD 0x03E0 /* MII Phy address (PHYAD) */ #define TEMAC_MIIM_PHYAD_SHIFT 5 /* MII Shift bits for PHYAD */ /* --------- EMAC Multicast address word 1 register ----------- */ #define TEMAC_MASK_MCAST_RNW 0x00800000 /* Multicast address table register read enable */ #define TEMAC_MAW1_ADDR_SHIFT 16 /* Num. of bits to shift to select the Mcast table entry */ /* ********************************************************************************************************* * DMA ENGINE REGISTERS * * Note(s) : (1) DMA_USE_DCR: is defined in net_bsp.h depending on the hw configuration. * This constant should be defined if the driver is using a Hard DMA. * This constant is equivalent to Xilinx constant XPAR_XLLDMA_USE_DCR which is defined * in xparameters.h file generated automatically when BSP and libraries are created ********************************************************************************************************* */ /* DMA_USE_DCR: see note (1) */ #ifdef DMA_USE_DCR #define DMA_TX_BASE_OFFSET 0x00000000 /* TX channel registers base offset */ #define DMA_RX_BASE_OFFSET 0x00000008 /* RX channel registers base offset */ #define DMA_GLB_CR_REG 0x00000010 /* DMA control register */ /* -------------- DMA TX and RX channel registers ------------- */ #define DMA_REG_NDESC 0x00000000 /* Next descriptor pointer */ #define DMA_REG_BUFA 0x00000001 /* Current buffer address */ #define DMA_REG_BUFL 0x00000002 /* Current buffer len */ #define DMA_REG_CDESC 0x00000003 /* Current descriptor pointer */ #define DMA_REG_TDESC 0x00000004 /* Tail descriptor pointer */ #define DMA_REG_CR 0x00000005 /* Channel control */ #define DMA_REG_IRQ 0x00000006 /* Interrupt register */ #define DMA_REG_SR 0x00000007 /* Status */ #else /* Non-DCR interface is used */ #define DMA_TX_BASE_OFFSET 0x00000000 /* TX channel registers base offset */ #define DMA_RX_BASE_OFFSET 0x00000020 /* RX channel registers base offset */ #define DMA_GLB_CR_REG 0x00000040 /* DMA control register */ /* -------------- DMA TX and RX channel registers ------------- */ #define DMA_REG_NDESC 0x00000000 /* Next descriptor pointer */ #define DMA_REG_BUFA 0x00000004 /* Current buffer address */ #define DMA_REG_BUFL 0x00000008 /* Current buffer len */ #define DMA_REG_CDESC 0x0000000C /* Current descriptor pointer */ #define DMA_REG_TDESC 0x00000010 /* Tail descriptor pointer */ #define DMA_REG_CR 0x00000014 /* Channel control */ #define DMA_REG_IRQ 0x00000018 /* Interrupt register */ #define DMA_REG_SR 0x0000001C /* Status */ #endif /* ********************************************************************************************************* * DMA REGISTER BIT MASKS ********************************************************************************************************* */ /* ---------------- XLL DMACR Register bitmasks --------------- */ #define DMA_MASK_CR_TX_PAUSE 0x20000000 /* Pause TX channel */ #define DMA_MASK_CR_RX_PAUSE 0x10000000 /* Pause RX channel */ #define DMA_MASK_CR_PLB_ERR_DIS 0x00000020 /* Disable PLB error detection */ #define DMA_MASK_CR_RX_OVFL_ERR_DIS 0x00000010 /* Disable error when 2 or 4 bit coalesce counter overflows */ #define DMA_MASK_CR_TX_OVFL_ERR_DIS 0x00000008 /* Disable error when 2 or 4 bit coalesce counter overflows */ #define DMA_MASK_CR_TAIL_PTR_EN 0x00000004 /* Enable use of tail pointer register */ #define DMA_MASK_CR_EN_ARB_HOLD 0x00000002 /* Enable arbitration hold */ #define DMA_MASK_CR_SW_RST 0x00000001 /* Assert Software reset for both channels */ /* ----------- DMA TX and RX CR Resgister bitmasks ------------ */ #define DMA_MASK_CR_IRQ_TIMEOUT 0xFF000000 /* Interrupt coalesce waitbound timeout */ #define DMA_MASK_CR_IRQ_COUNT 0x00FF0000 /* Interrupt coalesce count threshold */ #define DMA_MASK_CR_MSB_ADDR 0x0000F000 /* MSB address of DMA buf. and descrip. for 36 bit addressing */ #define DMA_MASK_CR_APP_EN 0x00000800 /* Application data mask enable */ #define DMA_MASK_CR_USE_1_BIT_CNT 0x00000400 /* Turn 4 and 2 bit interrupt counters into 1 bit counters */ #define DMA_MASK_CR_USE_INT_ON_END 0x00000200 /* Use interrupt-on-end */ #define DMA_MASK_CR_LD_IRQ_CNT 0x00000100 /* Load IRQ_COUNT */ #define DMA_MASK_CR_IRQ_EN 0x00000080 /* Master interrupt enable */ #define DMA_MASK_CR_IRQ_ERR_EN 0x00000004 /* Enable error interrupt */ #define DMA_MASK_CR_IRQ_DLY_EN 0x00000002 /* Enable coalesce delay interrupt */ #define DMA_MASK_CR_IRQ_COALESCE_EN 0x00000001 /* Enable coalesce count interrupt */ #define DMA_MASK_CR_IRQ_ALL_EN 0x00000087 /* All interrupt enable bits */ /* ------------ DMA TX and RX SR Resgister bitmasks ----------- */ #define DMA_MASK_SR_IRQ_ON_END 0x00000040 /* IRQ on end has occurred */ #define DMA_MASK_SR_STOP_ON_END 0x00000020 /* Stop on end has occurred */ #define DMA_MASK_SR_COMPLETED 0x00000010 /* Descriptor completed */ #define DMA_MASK_SR_SOP 0x00000008 /* Current BD has SOP set */ #define DMA_MASK_SR_EOP 0x00000004 /* Current BD has EOP set */ #define DMA_MASK_SR_BUSY 0x00000002 /* Channel is busy */ /* --------- DMA_TX_IRQ_REG & DMA_RX_IRQ_REG bitmasks --------- */ #define DMA_MASK_IRQ_WRQ_EMPTY 0x00004000 /* Write Command Queue Empty -- RX channel Only */ #define DMA_MASK_IRQ_COALESCE_COUNTER 0x00003C00 /* Coalesce IRQ 4 bit counter */ #define DMA_MASK_IRQ_DLY_COUNTER 0x00000300 /* Coalesce delay IRQ 2 bit counter */ #define DMA_MASK_IRQ_PLB_RD_ERR 0x00000010 /* PLB Read Error IRQ */ #define DMA_MASK_IRQ_PLB_WR_ERR 0x00000008 /* PLB Write Error IRQ */ #define DMA_MASK_IRQ_ERR 0x00000004 /* Error IRQ */ #define DMA_MASK_IRQ_DLY 0x00000002 /* Coalesce delay IRQ */ #define DMA_MASK_IRQ_COALESCE 0x00000001 /* Coalesce threshold IRQ */ #define DMA_MASK_IRQ_ALL_ERR 0x0000001C /* All error interrupt */ /* ---- DMA_BD_STSCTRL_USR0_OFFSET descriptor word bitmasks --- */ #define DMA_MASK_BD_STSCTRL_ERR 0x80000000 /* DMA error */ #define DMA_MASK_BD_STSCTRL_IOE 0x40000000 /* Interrupt on end */ #define DMA_MASK_BD_STSCTRL_SOE 0x20000000 /* Stop on end */ #define DMA_MASK_BD_STSCTRL_COMPLETED 0x10000000 /* DMA completed */ #define DMA_MASK_BD_STSCTRL_SOP 0x08000000 /* Start of packet */ #define DMA_MASK_BD_STSCTRL_EOP 0x04000000 /* End of packet */ #define DMA_MASK_BD_STSCTRL_BUSY 0x02000000 /* DMA channel busy */ #define DMA_MASK_BD_STSCTRL 0xFF000000 /* Status/Control field */ #define DMA_MASK_BD_STSCTRL_USR0 0x00FFFFFF /* User field #0 */ /* ********************************************************************************************************* * NetDev_Init() * * Description : (1) Initialize Network Driver Layer : * * (a) Initialize required clock sources * (b) Initialize external interrupt controller * (c) Initialize external GPIO controller * (d) Initialize driver state variables * (e) Allocate memory for device DMA descriptors * (f) Initialize additional device registers * (1) (R)MII mode / Phy bus type * (2) Disable device interrupts * (3) Disable device receiver and transmitter * (4) Other necessary device initialization * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No Error. * NET_DEV_ERR_INIT General initialization error. * NET_BUF_ERR_POOL_MEM_ALLOC Memory allocation failed. * * Return(s) : none. * * Caller(s) : NetIF_Ether_IF_Add() via 'pdev_api->Init()'. * * Note(s) : (2) The application developer SHOULD define NetDev_CfgClk() within net_bsp.c * in order to properly enable clocks for specified network interface. In * some cases, a device may require clocks to be enabled for BOTH the device * and accessory peripheral modules such as GPIO. A call to this function * MAY need to occur BEFORE any device register accesses are made. In the * event that a device does NOT require any external clocks to be enabled, * it is recommended that the device driver still call the NetBSP fuction * which may in turn leave the section for the specific interface number * empty. * * (3) The application developer SHOULD define NetDev_CfgGPIO() within net_bsp.c * in order to properly configure any necessary GPIO necessary for the device * to operate properly. Micrium recommends defining and calling this NetBSP * function even if no additional GPIO initialization is required. * * (4) The application developer SHOULD define NetDev_CfgIntCtrl() within net_bsp.c * in order to properly enable interrupts on an external or CPU integrated * interrupt controller. Interrupt sources that are specific to the DEVICE * hardware MUST NOT be initialized from within NetDev_CfgIntCtrl() and * SHOULD only be modified from within the device driver. * * (a) External interrupt sources are cleared within the NetBSP first level * ISR handler either before or after the call to the device driver ISR * handler function. The device driver ISR handler function SHOULD only * clear the device specific interrupts and NOT external or CPU interrupt * controller interrupt sources. * * (5) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. * * (6) All device drivers that store instance specific data MUST declare all * instance specific variables within the device data area defined above. * * (7) Drivers SHOULD validate device configuration values and set *perr to * NET_DEV_ERR_INVALID_CFG if unacceptible values have been specified. Fields * of interest generally include, but are not limited to : * * (a) pdev_cfg->RxBufPoolType : * * (1) NET_IF_MEM_TYPE_MAIN * (2) NET_IF_MEM_TYPE_DEDICATED * * (b) pdev_cfg->TxBufPoolType : * * (1) NET_IF_MEM_TYPE_MAIN * (2) NET_IF_MEM_TYPE_DEDICATED * * (c) pdev_cfg->RxBufAlignOctets * (d) pdev_cfg->TxBufAlignOctets * (e) pdev_cfg->RxBufDescNbr * (f) pdev_cfg->TxBufDescnbr * * (8) Descriptors are typically required to be contiguous in memory. Allocation of * descriptors MUST occur as a single contigous block of memory. The driver may * use pointer arithmetic to sub-divide and traverse the descriptor list. * * (9) NetDev_Init() should exit with : * * (a) All device interrupt source disabled. External interrupt controllers * should however be ready to accept interrupt requests. * (b) All device interrupt sources cleared. * (c) Both the receiver and transmitter disabled. * * (10) Some drivers MAY require knowledge of the Phy configuration in order * to properly configure the MAC with the correct Phy bus mode, speed and * duplex settings. If a driver requires access to the Phy configuration, * then the driver MUST validate the pif->Phy_Cfg pointer by checking for * a NULL pointer BEFORE attempting to access members of the Phy * configuration structure. Phy configuration fields of interest generally * include, but are not limited to : * * (a) pphy_cfg->Type : * * (1) NET_PHY_TYPE_INT Phy integrated with MAC. * (2) NET_PHY_TYPE_EXT Phy externally attached to MAC. * * (b) pphy_cfg->BusMode : * * (1) NET_PHY_BUS_MODE_MII Phy bus mode configured to MII. * (2) NET_PHY_BUS_MODE_RMII Phy bus mode configured to RMII. * (3) NET_PHY_BUS_MODE_SMII Phy bus mode configured to SMII. * * (c) pphy_cfg->Spd : * * (1) NET_PHY_SPD_0 Phy link speed unknown or NOT linked. * (2) NET_PHY_SPD_10 Phy link speed configured to 10 mbit/s. * (3) NET_PHY_SPD_100 Phy link speed configured to 100 mbit/s. * (4) NET_PHY_SPD_1000 Phy link speed configured to 1000 mbit/s. * (5) NET_PHY_SPD_AUTO Phy link speed configured for auto-negotiation. * * (d) pphy_cfg->Duplex : * * (1) NET_PHY_DUPLEX_UNKNOWN Phy link duplex unknown or link not established. * (2) NET_PHY_DUPLEX_HALF Phy link duplex configured to half duplex. * (3) NET_PHY_DUPLEX_FULL Phy link duplex configured to full duplex. * (4) NET_PHY_DUPLEX_AUTO Phy link duplex configured for auto-negotiation. ********************************************************************************************************* */ static void NetDev_Init (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; NET_DEV *pdev; NET_BUF_SIZE buf_size_max; NET_BUF_SIZE buf_ix; CPU_SIZE_T reqd_octets; CPU_SIZE_T nbytes; LIB_ERR lib_err; CPU_INT32U reg_val; CPU_INT32U reg_val1; CPU_INT32U timeout_cnt; CPU_INT32U reset_mask; CPU_INT32U input_freq; CPU_INT32U mdc_div; /* ------------ OBTAIN REFERENCE TO CFGs/REGs/BSP ------------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; pdev = (NET_DEV *)pdev_cfg->BaseAddr; pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* ------------------- VALIDATE DEVICE CFG -------------------- */ /* Validate Rx buf alignment. */ if ((pdev_cfg->RxBufAlignOctets % DMA_DESC_ALIGN != 0)) { *perr = NET_DEV_ERR_INVALID_CFG; /* Rx DESC. MUST be aligned to DMA_DESC_ALIGN BYTE boundary. */ return; } /* Validate Rx buf ix offset. */ if (pdev_cfg->RxBufIxOffset != 0u) { *perr = NET_DEV_ERR_INVALID_CFG; return; } /* Validate Rx buf size. */ buf_ix = NET_IF_IX_RX; buf_size_max = NetBuf_GetMaxSize((NET_IF_NBR )pif->Nbr, (NET_TRANSACTION)NET_TRANSACTION_RX, (NET_BUF *)0, (NET_BUF_SIZE )buf_ix); if (buf_size_max < NET_IF_ETHER_FRAME_MAX_SIZE) { *perr = NET_DEV_ERR_INVALID_CFG; return; } /* Validate Tx buf alignment. */ if ((pdev_cfg->TxBufAlignOctets % DMA_DESC_ALIGN != 0)) { *perr = NET_DEV_ERR_INVALID_CFG; /* Tx DESC. MUST be aligned to DMA_DESC_ALIGN BYTE boundary. */ return; } /* Validate Tx buf ix offset. */ if (pdev_cfg->TxBufIxOffset != 0u) { *perr = NET_DEV_ERR_INVALID_CFG; return; } /* ----------------- ALLOCATE DEV DATA AREA ------------------- */ pif->Dev_Data = Mem_HeapAlloc((CPU_SIZE_T ) sizeof(NET_DEV_DATA), (CPU_SIZE_T ) 4, /* Check if this value should be 4 or a define constant */ (CPU_SIZE_T *)&reqd_octets, (LIB_ERR *)&lib_err); if (pif->Dev_Data == (void *)0) { *perr = NET_DEV_ERR_MEM_ALLOC; return; } pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Get DMA base, RX, and TX channel base address's */ /* (see net_bsp.h). These addresses will be used to address */ /* the DMA registers */ pdev_data->DMA_AddrBase = pdev_bsp->DMA_AddrGet(); pdev_data->DMA_AddrTx = pdev_bsp->DMA_AddrGet() + DMA_TX_BASE_OFFSET; pdev_data->DMA_AddrRx = pdev_bsp->DMA_AddrGet() + DMA_RX_BASE_OFFSET; /* ---------------- ALLOCATE DESCRIPTOR LISTS ----------------- */ nbytes = pdev_cfg->RxDescNbr * sizeof(DEV_DESC); /* Allocate Rx desc buf's. */ pdev_data->RxBufDescPtrStart = Mem_HeapAlloc((CPU_SIZE_T ) nbytes, (CPU_SIZE_T ) pdev_cfg->RxBufAlignOctets, (CPU_SIZE_T *)&reqd_octets, (LIB_ERR *)&lib_err); if (pdev_data->RxBufDescPtrStart == (void *)0) { *perr = NET_DEV_ERR_MEM_ALLOC; return; } nbytes = pdev_cfg->TxDescNbr * sizeof(DEV_DESC); /* Allocate Tx desc's. */ pdev_data->TxBufDescPtrStart = Mem_HeapAlloc((CPU_SIZE_T ) nbytes, (CPU_SIZE_T ) pdev_cfg->TxBufAlignOctets, (CPU_SIZE_T *)&reqd_octets, (LIB_ERR *)&lib_err); if (pdev_data->TxBufDescPtrStart == (void *)0) { *perr = NET_DEV_ERR_MEM_ALLOC; return; } /* ----------------------- TEMAC RESET ------------------------ */ timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; reg_val = pdev->TEMAC_REG_IS; reg_val &= TEMAC_MASK_INT_MGT_LOCK; while (timeout_cnt > 0 && reg_val == 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); reg_val = pdev->TEMAC_REG_IS; reg_val &= TEMAC_MASK_INT_MGT_LOCK; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_INIT; return; } /* --------------- Stop the device and reset HW --------------- */ pdev->TEMAC_REG_IE = 0; /* Disable interrupts */ /* Disable the receiver */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val &= ~TEMAC_MASK_RCW1_RX; NetDev_IndirectWr_32(pif, TEMAC_REG_RCW1, reg_val); /* Get the interrupt pending register value */ reg_val = pdev->TEMAC_REG_IP; if (reg_val & TEMAC_MASK_INT_RXRJECT) { pdev->TEMAC_REG_IS = TEMAC_MASK_INT_RXRJECT; /* Set the interrupt status register to clear the interrupt */ } /* Reset the receiver */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val |= TEMAC_MASK_RCW1_RST; NetDev_IndirectWr_32(pif, TEMAC_REG_RCW1, reg_val); /* Reset the transmitter */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val |= TEMAC_MASK_TC_RST; NetDev_IndirectWr_32(pif, TEMAC_REG_TC, reg_val); /* Check if reset done */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val1 = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val |= reg_val1; reset_mask = TEMAC_MASK_RCW1_RST | TEMAC_MASK_TC_RST; /* loop until the reset is done */ timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while ((reg_val & reset_mask) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val1 = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val |= reg_val1; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_INIT; return; } /* Reset Hard core */ reg_val = pdev->TEMAC_REG_RAF; reg_val |= TEMAC_MASK_RAF_HTRST; pdev->TEMAC_REG_RAF = reg_val; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; /* Check the ready hard access bit */ reg_val = pdev->TEMAC_REG_RDY; while (!(reg_val & TEMAC_MASK_RDY_HARD_ACS_RDY) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); reg_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_INIT; return; } reg_val = pdev->TEMAC_REG_IS; reg_val &= TEMAC_MASK_INT_MGT_LOCK; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (timeout_cnt > 0 && reg_val == 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); reg_val = pdev->TEMAC_REG_IS; reg_val &= TEMAC_MASK_INT_MGT_LOCK; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_INIT; return; } /* --------------------- Set MDIO Divisor --------------------- */ /* HOSTCLK freq */ /* MDC freq = ----------------------- */ /* (1 + Divisor) * 2 */ /* */ /* HOSTCLK freq is the bus clock frequency in MHz */ /* MDC freq is the MDIO clock freq. in MHz to the PHY */ /* MDC freq should not exceed 2.5 MHz */ /* Get MDC clk input freq. */ input_freq = pdev_bsp->ClkFreqGet(pif, perr); if (*perr != NET_DEV_ERR_NONE) { *perr = NET_DEV_ERR_INIT; return; } mdc_div = input_freq / MDC_FREQ_MAX; mdc_div >>= 1; mdc_div -= 1; /* Set the MDIO divisor */ NetDev_IndirectWr_32(pif, TEMAC_REG_MC, mdc_div | TEMAC_MASK_MC_MDIOEN); /* ------------------------- DMA INIT ------------------------- */ /* Reset the DMA */ NetDev_DMA_Reset(pif, perr); if (*perr != NET_DEV_ERR_NONE) { *perr = NET_DEV_ERR_INIT; return; } /* Configure ext int ctrl'r. */ pdev_bsp->CfgIntCtrl(pif, perr); if (*perr != NET_DEV_ERR_NONE) { return; } *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_Start() * * Description : (1) Start network interface hardware : * * (a) Initialize transmit semaphore count * (b) Initialize hardware address registers * (c) Initialize receive and transmit descriptors * (d) Clear all pending interrupt sources * (e) Enable supported interrupts * (f) Enable the transmitter and receiver * (g) Start / Enable DMA if required * * * Argument(s) : pif Pointer to a network interface. * --- Argument validated in NetIF_Start(). * * perr Pointer to variable that will receive the return error code from this function : * * NET_DEV_ERR_NONE Ethernet device successfully started. * * - RETURNED BY NetIF_AddrHW_SetHandler() : -- * NET_IF_ERR_NULL_PTR Argument(s) passed a NULL pointer. * NET_ERR_FAULT_NULL_FNCT Invalid NULL function pointer. * NET_IF_ERR_INVALID_CFG Invalid/NULL API configuration. * NET_IF_ERR_INVALID_STATE Invalid network interface state. * NET_IF_ERR_INVALID_ADDR Invalid hardware address. * NET_IF_ERR_INVALID_ADDR_LEN Invalid hardware address length. * * - RETURNED BY NetIF_DevCfgTxRdySignal() : - * NET_IF_ERR_INVALID_IF Invalid network interface number. * NET_OS_ERR_INIT_DEV_TX_RDY_VAL Invalid device transmit ready signal. * * ---- RETURNED BY NetDev_RxDescInit() : ----- * !!!! * * ---- RETURNED BY NetDev_TxDescInit() : ----- * !!!! * * Return(s) : none. * * Caller(s) : NetIF_Ether_IF_Start() via 'pdev_api->Start()'. * * Note(s) : (2) Many DMA devices may generate only one interrupt for several ready receive * descriptors. In order to accommodate this, it is recommended that all DMA * based drivers count the number of ready receive descriptors during the * receive event and signal the receive task accordingly ONLY for those * NEW descriptors which have not yet been accounted for. Each time a * descriptor is processed (or discarded) the count for acknowledged and * unprocessed frames should be decremented by 1. This function initializes the * acknowledged receive descriptor count to 0. * (3) Setting the maximum number of frames queued for transmission is optional. By * default, all network interfaces are configured to block until the previous frame * has completed transmission. However, DMA based interfaces may have several * frames configured for transmission before blocking is required. The number * of queued transmit frames depends on the number of configured transmit * descriptors. * * (4) The physical hardware address should not be configured from NetDev_Init(). Instead, * it should be configured from within NetDev_Start() to allow for the proper use * of NetIF_Ether_HW_AddrSet(), hard coded hardware addresses from the device * configuration structure, or auto-loading EEPROM's. Changes to the physical address * only take effect when the device transitions from the DOWN to UP state. * * (5) The device hardware address is set from one of the data sources below. Each source * is listed in the order of precedence. * * (a) Device Configuration Structure Configure a valid HW address during * compile time. * * Configure either "00:00:00:00:00:00" or * an empty string, "", in order to * configure the HW address using using * method (b). * * (b) NetIF_Ether_HW_AddrSet() Call NetIF_Ether_HW_AddrSet() if the HW * address needs to be configured via * run-time from a different data * source. E.g. Non auto-loading * memory such as I2C or SPI EEPROM. * (see Note #3). * * (c) Auto-Loading via EEPROM. If neither options a) or b) are used, * the IF layer will use the HW address * obtained from the network hardware * address registers. ********************************************************************************************************* */ static void NetDev_Start (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; NET_DEV *pdev; CPU_INT32U reg_val; CPU_INT32U mac_addr_tmp; CPU_INT08U hw_addr[NET_IF_ETHER_ADDR_SIZE]; CPU_INT08U hw_addr_len; CPU_BOOLEAN hw_addr_cfg; NET_ERR err; pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; pdev = (NET_DEV *)pdev_cfg->BaseAddr; pdev_data = (NET_DEV_DATA *)pif->Dev_Data; pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; #if (NET_CTR_CFG_STAT_EN == DEF_ENABLED) pdev_data->StatRxCtrRx = 0; pdev_data->StatRxCtrRxISR = 0; pdev_data->StatTxCtrTxISR = 0; pdev_data->StatRxCtrTaskSignalSelf = 0; pdev_data->StatRxCtrTaskSignalNone = 0; #endif #if (NET_CTR_CFG_ERR_EN == DEF_ENABLED) pdev_data->ErrRxCtrDataAreaAlloc = 0; pdev_data->ErrRxCtrTaskSignalFail = 0; #endif /* -------------------- CFG TX RDY SIGNAL --------------------- */ NetIF_DevCfgTxRdySignal(pif, /* See Note #3. */ pdev_cfg->TxDescNbr, perr); if (*perr != NET_IF_ERR_NONE) { return; } /* ----------------------- CFG HW ADDR ------------------------ */ hw_addr_cfg = DEF_NO; /* See Notes #4 & #5. */ NetASCII_Str_to_MAC(pdev_cfg->HW_AddrStr, /* Get configured HW MAC address string, if any ... */ &hw_addr[0], /* ... (see Note #5a). */ &err); if (err == NET_ASCII_ERR_NONE) { NetIF_AddrHW_SetHandler((NET_IF_NBR ) pif->Nbr, (CPU_INT08U *)&hw_addr[0], (CPU_INT08U ) sizeof(hw_addr), (NET_ERR *)&err); } if (err == NET_IF_ERR_NONE) { /* If no errors, configure device HW MAC address. */ hw_addr_cfg = DEF_YES; } else { /* Else get app-configured IF layer HW MAC address, ... */ /* ... if any (see Note #5b). */ hw_addr_len = sizeof(hw_addr); NetIF_AddrHW_GetHandler(pif->Nbr, &hw_addr[0], &hw_addr_len, &err); if (err == NET_IF_ERR_NONE) { hw_addr_cfg = NetIF_AddrHW_IsValidHandler(pif->Nbr, &hw_addr[0], &err); } else { hw_addr_cfg = DEF_NO; } if (hw_addr_cfg != DEF_YES) { /* Else attempt to get device's automatically loaded ... */ /* ... HW MAC address, if any (see Note #5c). */ mac_addr_tmp = NetDev_IndirectRd_32(pif, TEMAC_REG_UAW0); hw_addr[0] = (mac_addr_tmp >> (0 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; hw_addr[1] = (mac_addr_tmp >> (1 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; hw_addr[2] = (mac_addr_tmp >> (2 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; hw_addr[3] = (mac_addr_tmp >> (3 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; mac_addr_tmp = NetDev_IndirectRd_32(pif, TEMAC_REG_UAW1); hw_addr[4] = (mac_addr_tmp >> (0 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; hw_addr[5] = (mac_addr_tmp >> (1 * DEF_INT_08_NBR_BITS)) & DEF_INT_08_MASK; NetIF_AddrHW_SetHandler((NET_IF_NBR ) pif->Nbr, /* Configure IF layer to use automatically-loaded ... */ (CPU_INT08U *)&hw_addr[0], /* ... HW MAC address. */ (CPU_INT08U ) sizeof(hw_addr), (NET_ERR *) perr); if (*perr != NET_IF_ERR_NONE) { /* No valid HW MAC address configured, return error. */ return; } } } if (hw_addr_cfg == DEF_YES) { /* If necessary, set device HW MAC address. */ /* Set MAC bits [31: 0] in UAW0 */ mac_addr_tmp = (((CPU_INT32U)hw_addr[0] << (0 * DEF_INT_08_NBR_BITS)) | ((CPU_INT32U)hw_addr[1] << (1 * DEF_INT_08_NBR_BITS)) | ((CPU_INT32U)hw_addr[2] << (2 * DEF_INT_08_NBR_BITS)) | ((CPU_INT32U)hw_addr[3] << (3 * DEF_INT_08_NBR_BITS))); NetDev_IndirectWr_32(pif, TEMAC_REG_UAW0, mac_addr_tmp); /* Don't change reserved bits in UAW1 register */ mac_addr_tmp = NetDev_IndirectRd_32(pif, TEMAC_REG_UAW1); mac_addr_tmp &= ~TEMAC_MASK_UAW1_UNICASTADDR; /* Set MAC bits [47:32] in UAW1 */ mac_addr_tmp = (((CPU_INT32U)hw_addr[4] << (0 * DEF_INT_08_NBR_BITS)) | ((CPU_INT32U)hw_addr[5] << (1 * DEF_INT_08_NBR_BITS))); NetDev_IndirectWr_32(pif, TEMAC_REG_UAW1, mac_addr_tmp); } #ifdef NET_MCAST_MODULE_EN /* Allow multicast address filtering */ reg_val = pdev->TEMAC_REG_RAF; reg_val &= ~TEMAC_MASK_RAF_MCSTREJ; pdev->TEMAC_REG_RAF = reg_val; #endif NetDev_RxDescInit(pif, perr); /* Init Rx desc's. */ if (*perr != NET_DEV_ERR_NONE) { return; } NetDev_TxDescInit(pif, perr); /* Init Tx desc'c. */ if (*perr != NET_DEV_ERR_NONE) { return; } /* ------------------- SET TEMAC OPTIONS ---------------------- */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val &= ~TEMAC_MASK_RCW1_JUM; /* Jumbo frame disabled */ reg_val &= ~TEMAC_MASK_RCW1_FCS; /* In-Band FCS (frame check sequence) disabled */ reg_val &= ~TEMAC_MASK_RCW1_VLAN; /* VLAN frame disabled */ reg_val &= ~TEMAC_MASK_RCW1_HD; /* Full duplex mode enabled */ reg_val |= TEMAC_MASK_RCW1_RX; /* Enable Temac Receiver */ NetDev_IndirectWr_32(pif, TEMAC_REG_RCW1, reg_val); reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val &= ~TEMAC_MASK_TC_JUM; reg_val &= ~TEMAC_MASK_TC_FCS; reg_val &= ~TEMAC_MASK_TC_VLAN; reg_val &= ~TEMAC_MASK_TC_HD; reg_val |= TEMAC_MASK_TC_TX; /* Enable Temac Transmitter */ NetDev_IndirectWr_32(pif, TEMAC_REG_TC, reg_val); /* Enable Temac interrupts to handle errors */ pdev->TEMAC_REG_IE = TEMAC_MASK_INT_RXRJECT | /* Receive frame rejected */ TEMAC_MASK_INT_RXFIFOOVR; /* Receive fifo overrun */ /* ---------------- ENABLE DMA INTERRUPTS --------------------- */ /* Enable DMA RX interrupt. */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_CR); reg_val |= DMA_MASK_CR_IRQ_EN | /* Master interrupt enable */ DMA_MASK_CR_IRQ_ERR_EN | /* Enable error interrupt */ DMA_MASK_CR_IRQ_DLY_EN | /* Enable coalesce delay interrupt */ DMA_MASK_CR_IRQ_COALESCE_EN; /* Enable coalesce count interrupt */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CR, reg_val); /* Enable DMA TX interrupt. */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_CR); reg_val |= DMA_MASK_CR_IRQ_EN | /* Master interrupt enable */ DMA_MASK_CR_IRQ_ERR_EN | /* Enable error interrupt */ DMA_MASK_CR_IRQ_DLY_EN | /* Enable coalesce delay interrupt */ DMA_MASK_CR_IRQ_COALESCE_EN; /* Enable coalesce count interrupt */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CR, reg_val); (void)&pdev_data; /* Prevent compiler warning. */ *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_Stop() * * Description : (1) Shutdown network interface hardware : * * (a) Disable the receiver and transmitter * (b) Disable receive and transmit interrupts * (c) Clear pending interrupt requests * (d) Free ALL receive descriptors (Return ownership to hardware) * (e) Deallocate ALL transmit buffers * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No Error * * Return(s) : none. * * Caller(s) : NetIF_Ether_IF_Stop() via 'pdev_api->Stop()'. * * Note(s) : (2) (a) (1) It is recommended that a device driver should only post all currently-used, * i.e. not-fully-transmitted, transmit buffers to the network interface transmit * deallocation queue. * * (2) However, a driver MAY attempt to post all queued &/or transmitted buffers. * The network interface transmit deallocation task will silently ignore any * unknown or duplicate transmit buffers. This allows device drivers to * indiscriminately & easily post all transmit buffers without determining * which buffers have NOT yet been transmitted. * * (b) (1) Device drivers should assume that the network interface transmit deallocation * queue is large enough to post all currently-used transmit buffers. * * (2) If the transmit deallocation queue is NOT large enough to post all transmit * buffers, some transmit buffers may/will be leaked/lost. * * (3) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. ********************************************************************************************************* */ static void NetDev_Stop (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; NET_DEV *pdev; DEV_DESC *pdesc; CPU_INT08U i; NET_ERR err; CPU_INT32U reg_val; /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct (see Note #3). */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ /* ----------- OBTAIN REFERENCE TO DEVICE BSP AREA ----------- */ /* Obtain ptr to dev bsp area */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* ------------------- DISABLE TEMAC RX & TX ------------------ */ pdev->TEMAC_REG_IE = 0; /* Disable Temac interrupts */ /* Disable Temac receiver */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val &= ~TEMAC_MASK_RCW1_RX; NetDev_IndirectWr_32(pif, TEMAC_REG_RCW1, reg_val); /* Disable Temac Transmitter */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val &= ~TEMAC_MASK_TC_TX; NetDev_IndirectWr_32(pif, TEMAC_REG_TC, reg_val); /* Get the interrupt pending register value */ reg_val = pdev->TEMAC_REG_IP; if (reg_val & TEMAC_MASK_INT_RXRJECT) { pdev->TEMAC_REG_IS = TEMAC_MASK_INT_RXRJECT; /* set the interrupt status register to clear the interrupt */ } /* -------------------- DISABLE DMA RX & TX ------------------- */ /* Disable TX channel interrupts */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_CR); reg_val &= ~DMA_MASK_CR_IRQ_ALL_EN; pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CR, reg_val); /* Disable RX channel interrupts */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_CR); reg_val &= ~DMA_MASK_CR_IRQ_ALL_EN; pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CR, reg_val); /* Clear TX channel interrupts register */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_IRQ); pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_IRQ, reg_val); /* Clear RX channel interrupts register */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_IRQ); pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_IRQ, reg_val); /* ------------------- FREE RX DESCRIPTORS -------------------- */ NetDev_RxDescFreeAll(pif, perr); if (*perr != NET_DEV_ERR_NONE) { return; } /* ------------------ FREE USED TX DESCRIPTORS ---------------- */ pdesc = &pdev_data->TxBufDescPtrStart[0]; for (i = 0; i < pdev_cfg->TxDescNbr; i++) { /* Dealloc ALL tx bufs (see Note #2a2). */ NetIF_TxDeallocTaskPost((CPU_INT08U *)pdesc->DMA_CurrBufAddr, &err); (void)&err; /* Ignore possible dealloc err (see Note #2b2). */ pdesc++; } *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_Rx() * * Description : (1) This function returns a pointer to the received data to the caller : * (a) Decrement frame counter * (b) Determine which receive descriptor caused the interrupt * (c) Obtain pointer to data area to replace existing data area * (d) Reconfigure descriptor with pointer to new data area * (e) Set return values. Pointer to received data area and size * (f) Update current receive descriptor pointer * (g) Increment statistic counters * * Argument(s) : pif Pointer to the interface requiring service. * * p_data Pointer to pointer to received DMA data area. The received data * area address should be returned to the stack by dereferencing * p_data as *p_data = (address of receive data area). * * size Pointer to size. The number of bytes received should be returned * to the stack by dereferencing size as *size = (number of bytes). * * perr Pointer to return error code. * NET_DEV_ERR_NONE No Error * NET_DEV_ERR_RX Generic Rx error. * NET_DEV_ERR_INVALID_SIZE Invalid Rx frame size. * NET_BUF error codes Potential NET_BUF error codes * * Return(s) : none. * * Caller(s) : NetIF_RxPkt() via 'pdev_api->Rx()'. * * Note(s) : (2) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. * * (3) If a receive error occurs and the descriptor is invalid then the function * SHOULD return 0 for the size, a NULL pointer to the data area AND an * error equal to NET_DEV_ERR_RX. * * (a) If the next expected ready / valid descriptor is NOT owned by * software, then there is descriptor pointer corruption and the * driver should NOT increment the current receive descriptor * pointer. * (b) If the descriptor IS valid, but an error is indicated within * the descriptor status bits, or length field, then the driver * MUST increment the current receive descriptor pointer and discard * the received frame. * (c) If a new data area is unavailable, the driver MUST increment * the current receive descriptor pointer and discard the received * frame. This will invoke the DMA to re-use the existing configured * data area. * * (4) Check the DMA_AppData4 field which is initialized with DMA_USERAPP4_INIT_VAL * constant and will store the length of the received frame. * In RX channel case, if "EOP" flag set but its DMA_AppData4 has value * DMA_USERAPP4_INIT_VAL, this means hardware has not completed updating the * RX decriptor structure ********************************************************************************************************* */ static void NetDev_Rx (NET_IF *pif, CPU_INT08U **p_data, CPU_INT16U *size, NET_ERR *perr) { NET_DEV_DATA *pdev_data; DEV_DESC *pdesc; CPU_INT08U *pbuf_new; CPU_INT16S len; /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ pdesc = pdev_data->RxBufDescPtrCur; /* Obtain ptr to next ready desc. */ /* Invalidate the current desc. to be sure to get the recent */ /* copie that was recently updated by the DMA Engine */ CPU_CacheDataInvalidate(pdesc, sizeof(DEV_DESC)); *size = (CPU_INT16U )0; *p_data = (CPU_INT08U *)0; /* ----------------- CHECK FOR RECEIVE ERRORS ----------------- */ /* Check for the End of packet bit and receive errors */ if (!(pdesc->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_EOP) || (pdesc->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_ERR)) { NetDev_RxDescPtrCurInc(pif); /* Discard received frame (see Note #3b) */ *perr = (NET_ERR )NET_DEV_ERR_RX; return; } if (pdesc->DMA_AppData4 == DMA_USERAPP4_INIT_VAL) { /* see Note #4 */ NetDev_RxDescPtrCurInc(pif); /* Discard received frame (see Note #3b) */ *perr = (NET_ERR )NET_DEV_ERR_RX; return; } len = pdesc->DMA_AppData4 & 0x3FFF; /* Received Frame size */ if (len < NET_IF_ETHER_FRAME_MIN_SIZE) { /* If frame is a runt. */ NetDev_RxDescPtrCurInc(pif); /* Discard received frame (see Note #3b) */ *perr = (NET_ERR )NET_DEV_ERR_INVALID_SIZE; return; } /* -------------- OBTAIN PTR TO NEW DMA DATA AREA ------------- */ pbuf_new = NetBuf_GetDataPtr((NET_IF *)pif, (NET_TRANSACTION)NET_TRANSACTION_RX, (NET_BUF_SIZE )NET_IF_ETHER_FRAME_MAX_SIZE, (NET_BUF_SIZE )NET_IF_IX_RX, (NET_BUF_SIZE *)0, (NET_BUF_SIZE *)0, (NET_BUF_TYPE *)0, (NET_ERR *)perr); if (*perr != NET_BUF_ERR_NONE) { /* If unable to get a buffer. */ NetDev_RxDescPtrCurInc(pif); /* Discard received frame (see Note #3b) */ NET_CTR_ERR_INC(pdev_data->ErrRxCtrDataAreaAlloc); return; } /* Invalidate the cache to get the recent received data */ CPU_CacheDataInvalidate((CPU_VOID *)pdesc->DMA_CurrBufAddr , len); *size = len; /* Return the size of the recv'd frame. */ /* Return a ptr to the newly recv'd data. */ *p_data = (CPU_INT08U *)pdesc->DMA_CurrBufAddr; pdesc->DMA_CurrBufAddr = (CPU_REG32)pbuf_new; /* Update the desc to point to a new data area */ NET_CTR_STAT_INC(pdev_data->StatRxCtrRx); /* Increment the current descriptor and check for other */ NetDev_RxDescPtrCurInc(pif); /* completed descriptors */ *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_Tx() * * Description : (1) This function transmits the specified data : * * (a) Check if the transmitter is ready. * (b) Configure the next transmit descriptor for pointer to data and data size. * (c) Issue the transmit command. * (d) Increment pointer to next transmit descriptor * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No Error * NET_DEV_ERR_TX_BUSY No Tx descriptors available * * Return(s) : none. * * Caller(s) : NetIF_TxPkt() via 'pdev_api->Tx()'. * * Note(s) : (2) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. * * (3) Care should be taken to avoid skipping transmit descriptors while selecting * the next available descriptor. Software MUST track the descriptor which * is expected to generate the next transmit complete interrupt. Skipping * descriptors, unless carefully accounted for, may make it difficult to * know which descriptor will complete transmission next. Some device * drivers may find it useful to adjust pdev_data->TxBufDescCompPtr after * having selected the next available transmit descriptor. ********************************************************************************************************* */ static void NetDev_Tx (NET_IF *pif, CPU_INT08U *p_data, CPU_INT16U size, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_DATA *pdev_data; DEV_DESC *pdesc; CPU_INT32U desc_status; CPU_SR_ALLOC(); /* -------------- OBTAIN REFERENCE TO DEVICE BSP -------------- */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* Obtain ptr to dev bsp. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ pdesc = pdev_data->TxBufDescPtrCur; /* Obtain ptr to next available Tx descriptor. */ /* Invalidate Cache to be sure to read recent desc. status */ CPU_CacheDataInvalidate((CPU_VOID *)pdesc, sizeof(DEV_DESC)); CPU_CRITICAL_ENTER(); /* This routine reads shared data. Disable interrupts! */ desc_status = pdesc->DMA_CtrlAndStatus; CPU_CRITICAL_EXIT(); if (!(desc_status & DMA_MASK_BD_STSCTRL_COMPLETED)) { /* If the current desc. is not completed, return an error */ *perr = NET_DEV_ERR_TX_BUSY; return; } /* Populate the current descriptor fields */ pdesc->DMA_CurrBufLen = size; pdesc->DMA_CurrBufAddr = (CPU_REG32)p_data; pdesc->DMA_CtrlAndStatus = DMA_MASK_BD_STSCTRL_SOP | /* Set the Start of packet bit */ DMA_MASK_BD_STSCTRL_EOP; /* Set the End of packet bit */ /* Mark the current descriptor as not completed */ pdesc->DMA_CtrlAndStatus &= ~DMA_MASK_BD_STSCTRL_COMPLETED ; /* Flush the populated desc. and the data to be transmitted. */ /* This will allow the DMA to see the changes */ CPU_CacheDataFlush((CPU_VOID *)pdesc, sizeof(DEV_DESC)); CPU_CacheDataFlush((CPU_VOID *)pdesc->DMA_CurrBufAddr , size); /* Update the Tail register to start processing the desc. */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_TDESC, (CPU_INT32U)pdesc); /* update the current descriptor with the next desc. address */ pdev_data->TxBufDescPtrCur = (DEV_DESC *)pdev_data->TxBufDescPtrCur->DMA_NextDescAddr; *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_AddrMulticastAdd() * * Description : Configure hardware address filtering to accept specified hardware address. * * Argument(s) : pif Pointer to an Ethernet network interface. * --- Argument validated in NetIF_AddrHW_SetHandler(). * * paddr_hw Pointer to hardware address. * -------- Argument checked in NetIF_AddrHW_SetHandler(). * * addr_len Length of hardware address. * * perr Pointer to variable that will receive the return error code from this function : * * NET_DEV_ERR_NONE Hardware address successfully configured. * NET_DEV_ERR_ADDR_MULTICAST_ADD Error adding Muticast address. * * Return(s) : none. * * Caller(s) : NetIF_Ether_AddrMulticastAdd() via 'pdev_api->AddrMulticastAdd()'. * * Note(s) : (1) A multicast table entry is available if its value is either * 0x00.0x00.0x00.0x00.0x00.0x00 or 0xFF.0xFF.0xFF.0xFF.0xFF.0xFF ********************************************************************************************************* */ static void NetDev_AddrMulticastAdd (NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT08U addr_hw_len, NET_ERR *perr) { #ifdef NET_MCAST_MODULE_EN NET_DEV *pdev; NET_DEV_CFG_ETHER *pdev_cfg; CPU_INT32U reg_val1; CPU_INT32U reg_val2; CPU_INT32U mcast_entry; CPU_INT08U i; CPU_INT08U l_hw_addr[6]; CPU_BOOLEAN free_entry; CPU_INT32U rdy_val; CPU_INT16U timeout_cnt; /* ------------ OBTAIN REFERENCE TO DEVICE REGISTERS ---------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ free_entry = DEF_NO; /* Assumes no entry is available in the Multicast table */ /* Get the first available entry in the Multicast Table */ /* if the multicast addr. is not already stored */ for (i = 0; i < MCAST_TAB_ENTRIES_NUM; i++) { NetDev_AddrMulticastGet(pif, &l_hw_addr[0], i, perr); if (*perr != NET_DEV_ERR_NONE) { *perr = NET_DEV_ERR_ADDR_MCAST_ADD; return; } /* Check if the hw addr. is already present */ if (Mem_Cmp((void *)&l_hw_addr[0], (void *) paddr_hw, addr_hw_len) == DEF_YES) { *perr = NET_DEV_ERR_NONE; /* Mutlicast hw addr. exists, so do nothing */ return; } /* Check if current Multicast table entry is available */ /* see Note #1 */ if (free_entry == DEF_NO) { free_entry = Mem_Cmp((void *)&l_hw_addr[0], (void *)&Multicast_FreeHW_Addr1[0], addr_hw_len); free_entry |= Mem_Cmp((void *)&l_hw_addr[0], (void *)&Multicast_FreeHW_Addr2[0], addr_hw_len); if (free_entry == DEF_YES) { mcast_entry = i; } } } if (free_entry == DEF_NO) { *perr = NET_DEV_ERR_ADDR_MCAST_ADD; return; } /* Set HW addr bits [31:0] */ reg_val1 = paddr_hw[0] & 0x000000FF; reg_val1 |= paddr_hw[1] << 8; reg_val1 |= paddr_hw[2] << 16; reg_val1 |= paddr_hw[3] << 24; /* Set HW addr bits [47:32] */ reg_val2 = paddr_hw[4] & 0x000000FF; reg_val2 |= paddr_hw[5] << 8; /* Make sure the RNW bit in the TEMAC_REG_MAW1 is set to 0 */ /* for write */ reg_val2 &= ~TEMAC_MASK_MCAST_RNW; /* Set the Mcast table entry */ reg_val2 |= (mcast_entry << TEMAC_MAW1_ADDR_SHIFT); /* Write to Hw */ NetDev_IndirectWr_32(pif, TEMAC_REG_MAW0, reg_val1); /* Poll the Rdy register until the opration completes or */ /* timeout occurs */ rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (!(rdy_val & TEMAC_MASK_RDY_AF_WR) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_ADDR_MCAST_ADD; return; } NetDev_IndirectWr_32(pif, TEMAC_REG_MAW1, reg_val2); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (!(rdy_val & TEMAC_MASK_RDY_AF_WR) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_ADDR_MCAST_ADD; return; } #else (void)&pif; /* Prevent 'variable unused' compiler warnings. */ (void)&paddr_hw; (void)&addr_hw_len; #endif *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_AddrMulticastRemove() * * Description : Configure hardware address filtering to reject specified hardware address. * * Argument(s) : pif Pointer to an Ethernet network interface. * --- Argument validated in NetIF_AddrHW_SetHandler(). * * paddr_hw Pointer to hardware address. * -------- Argument checked in NetIF_AddrHW_SetHandler(). * * addr_len Length of hardware address. * * perr Pointer to variable that will receive the return error code from this function : * * NET_DEV_ERR_NONE Hardware address successfully removed. * NET_DEV_ERR_ADDR_MULTICAST_REMOVE Error removing the Multicast Hw addr. * Return(s) : none. * * Caller(s) : NetIF_Ether_AddrMulticastAdd() via 'pdev_api->AddrMulticastRemove()'. * * Note(s) : none. ********************************************************************************************************* */ static void NetDev_AddrMulticastRemove (NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT08U addr_hw_len, NET_ERR *perr) { #ifdef NET_MCAST_MODULE_EN NET_DEV *pdev; NET_DEV_CFG_ETHER *pdev_cfg; CPU_INT32U reg_val1; CPU_INT32U reg_val2; CPU_INT08U mcast_entry; CPU_INT08U i; CPU_INT08U l_hw_addr[6]; CPU_INT32U rdy_val; CPU_INT16U timeout_cnt; /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* Find the entry corresponding to the mulicast hw addr. */ for (i = 0; i < MCAST_TAB_ENTRIES_NUM; i++) { NetDev_AddrMulticastGet(pif, &l_hw_addr[0], i, perr); if (*perr != NET_DEV_ERR_NONE) { *perr = NET_DEV_ERR_ADDR_MCAST_REMOVE; return; } /* Check if the hw addr. is present */ if (Mem_Cmp((void *)&l_hw_addr[0], (void *) paddr_hw, addr_hw_len) == DEF_YES) { mcast_entry = i; break; } } /* Do nothing If the mutlicast hw addr. was not found */ if (i == MCAST_TAB_ENTRIES_NUM) { *perr = NET_DEV_ERR_NONE; return; } /* Set multicast table entry to 0 to clear the hw addr */ reg_val1 = 0; reg_val2 = 0; /* Make sure the RNW bit in the TEMAC_REG_MAW1 is set to 0 */ /* for write */ reg_val2 &= ~TEMAC_MASK_MCAST_RNW; /* Set the Multicat table entry address */ reg_val2 |= (mcast_entry << TEMAC_MAW1_ADDR_SHIFT); /* Write to Hw */ NetDev_IndirectWr_32(pif, TEMAC_REG_MAW0, reg_val1); /* Poll the Rdy register until the opration completes or */ /* timeout occurs */ rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (!(rdy_val & TEMAC_MASK_RDY_AF_WR) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_ADDR_MCAST_REMOVE; return; } NetDev_IndirectWr_32(pif, TEMAC_REG_MAW1, reg_val2); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (!(rdy_val & TEMAC_MASK_RDY_AF_WR) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); rdy_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_ADDR_MCAST_REMOVE; return; } #else (void)&pif; /* Prevent 'variable unused' compiler warnings. */ (void)&paddr_hw; (void)&addr_hw_len; #endif *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_ISR_Handler() * * Description : This function serves as the device Interrupt Service Routine Handler. This ISR * handler MUST service and clear all necessary and enabled interrupt events for * the device. * * Argument(s) : pif Pointer to interface requiring service. * --- * * type Network Interface defined argument representing the type of ISR in progress. Codes * for Rx, Tx, Overrun, Jabber, etc... are defined within net_if.h and are passed * into this function by the corresponding Net BSP ISR handler function. The Net * BSP ISR handler function may be called by a specific ISR vector and therefore * know which ISR type code to pass. Otherwise, the Net BSP may pass * NET_DEV_ISR_TYPE_UNKNOWN and the device driver MAY ignore the parameter when * the ISR type can be deduced by reading an available interrupt status register. * * Type codes that are defined within net_if.c include but are not limited to : * NET_DEV_ISR_TYPE_RX * NET_DEV_ISR_TYPE_TX_COMPLETE * NET_DEV_ISR_TYPE_UNKNOWN * * Return(s) : none. * * Caller(s) : Specific first- or second-level BSP ISR handler. * * Note(s) : (1) This function is called via function pointer from the context of an ISR. * * (2) In the case of an interrupt occurring prior to Network Protocol Stack initialization, * the device driver should ensure that the interrupt source is cleared in order * to prevent the potential for an infinite interrupt loop during system initialization. * * (3) Many DMA devices generate only one interrupt event for several ready receive * descriptors. In order to accommodate this, it is recommended that all DMA based * drivers count the number of ready receive descriptors during the receive event * and signal the receive task for ONLY newly received descriptors which have not * yet been signaled for during the last receive interrupt event. * * (4) Many DMA devices generate only one interrupt event for several transmit * complete descriptors. In this case, the driver MUST determine which descriptors * have completed transmission and post each descriptor data area address to * the transmit deallocation task. The code provided below assumes one * interrupt per transmit event which may not necessarily be the case for all * devices. ********************************************************************************************************* */ static void NetDev_ISR_Handler (NET_IF *pif, NET_DEV_ISR_TYPE type) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; NET_DEV *pdev; DEV_DESC *pdesc; CPU_INT08U *p_data; NET_ERR err; CPU_INT32U irq_status; (void)&type; /* Prevent compiler warning if arg 'type' not req'd. */ /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* ------------- OBTAIN REFERENCE TO DEVICE BSP --------------- */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* Obtain ptr to the dev cfg struct. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ /* ------------------ TEMAC error interrupts ----------------- */ irq_status = pdev->TEMAC_REG_IP; if (irq_status != 0) { pdev->TEMAC_REG_IS |= irq_status; /* Clear error interrupt */ return; } /* ------------------ DMA TX channel interrupts --------------- */ irq_status = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_IRQ); /* Acknowledge pending interrupts */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_IRQ, irq_status); /* If an error occurs, reset the DMA to recover from the error */ if (irq_status & DMA_MASK_IRQ_ALL_ERR) { NetDev_DMA_ErrRecover(pif, &err); return; } /* Transmission complete interrupt */ if (irq_status & (DMA_MASK_IRQ_DLY | DMA_MASK_IRQ_COALESCE)) { NET_CTR_STAT_INC(pdev_data->StatTxCtrTxISR); pdesc = pdev_data->TxBufDescCompPtr; pdesc->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; pdesc->DMA_CtrlAndStatus |= DMA_MASK_BD_STSCTRL_COMPLETED; p_data = (CPU_INT08U *)pdesc->DMA_CurrBufAddr; NetIF_TxDeallocTaskPost(p_data, &err); NetIF_DevTxRdySignal(pif); /* Signal Net IF that Tx resources are available. */ pdev_data->TxBufDescCompPtr = (DEV_DESC *)pdev_data->TxBufDescCompPtr->DMA_NextDescAddr; /* This return is important to keep. If a previous RX interrupt */ /* has occured, the RX task will run until reading all completed*/ /* descriptors while RX interrupts are disabled */ return; } /* ---------------- DMA RX channel interrupts ----------------- */ irq_status = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_IRQ); /* Acknowledge pending interrupts */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_IRQ, irq_status); /* If an error occured, reset the DMA to recover from the error */ if (irq_status & DMA_MASK_IRQ_ALL_ERR) { NetDev_DMA_ErrRecover(pif, &err); return; } /* Check if reception was done, if so, signal it to the stack */ if (irq_status & (DMA_MASK_IRQ_DLY | DMA_MASK_IRQ_COALESCE)) { NET_CTR_STAT_INC(pdev_data->StatRxCtrRxISR); pdesc = pdev_data->RxBufDescPtrCur; CPU_CacheDataInvalidate((CPU_VOID *)pdesc, sizeof(DEV_DESC)); if (!(pdesc->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_COMPLETED)) { return; } /* Disable DMA RX channel interrupts until all completed desc. */ /* are read by the Receive Task NetDev_Rx() function */ NetDev_DMA_EnDisChInt(pif, pdev_data->DMA_AddrRx, INT_DISABLE); NetIF_RxTaskSignal(pif->Nbr, &err); /* Signal Net IF RxQ Task for each new rdy descriptor. */ switch (err) { case NET_IF_ERR_NONE: NET_CTR_STAT_INC(pdev_data->StatRxCtrTaskSignalSelf); break; case NET_IF_ERR_RX_Q_FULL: case NET_IF_ERR_RX_Q_SIGNAL_FAULT: default: NET_CTR_ERR_INC(pdev_data->ErrRxCtrTaskSignalFail); break; } } } /* ********************************************************************************************************* * NetDev_IO_Ctrl() * * Description : This function provides a mechanism for the Phy driver to update the MAC link * and duplex settings, as well as a method for the application and link state * timer to obtain the current link status. Additional user specified driver * functionality MAY be added if necessary. * * Argument(s) : pif Pointer to interface requiring service. * * opt Option code representing desired function to perform. The Network Protocol Suite * specifies the option codes below. Additional option codes may be defined by the * driver developer in the driver's header file. * NET_IF_IO_CTRL_LINK_STATE_GET * NET_IF_IO_CTRL_LINK_STATE_UPDATE * * Driver defined operation codes MUST be defined starting from 20 or higher * to prevent clashing with the pre-defined operation code types. See the * device driver header file for more details. * * data Pointer to optional data for either sending or receiving additional function * arguments or return data. * * perr Pointer to return error code. * NET_IF_ERR_INVALID_IO_CTRL_OPT Invalid option number specified. * NET_ERR_FAULT_NULL_FNCT Null interface function pointer encountered. * * NET_DEV_ERR_NONE IO Ctrl operation completed successfully. * NET_DEV_ERR_NULL_PTR Null argument pointer passed. * * NET_PHY_ERR_NULL_PTR Pointer argument(s) passed NULL pointer(s). * NET_PHY_ERR_TIMEOUT_RESET Phy reset time-out. * NET_PHY_ERR_TIMEOUT_AUTO_NEG Auto-Negotiation time-out. * NET_PHY_ERR_TIMEOUT_REG_RD Phy register read time-out. * NET_PHY_ERR_TIMEOUT_REG_WR Phy register write time-out. * * Return(s) : none. * * Caller(s) : NetIF_Ether_IO_CtrlHandler() via 'pdev_api->IO_Ctrl()', * NetPhy_LinkStateGet() via 'pdev_api->IO_Ctrl()'. * * Note(s) : (1) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. ********************************************************************************************************* */ static void NetDev_IO_Ctrl (NET_IF *pif, CPU_INT08U opt, void *p_data, NET_ERR *perr) { NET_DEV_LINK_ETHER *plink_state; NET_PHY_API_ETHER *pphy_api; CPU_INT16U duplex; CPU_INT16U spd; CPU_INT32U reg_val; switch (opt) { /* -------------- PERFORM SPECIFIED OPERATION ----------------- */ case NET_IF_IO_CTRL_LINK_STATE_GET_INFO: plink_state = (NET_DEV_LINK_ETHER *)p_data; if (plink_state == (NET_DEV_LINK_ETHER *)0) { *perr = NET_DEV_ERR_NULL_PTR; return; } pphy_api = (NET_PHY_API_ETHER *)pif->Ext_API; if (pphy_api == (void *)0) { *perr = NET_ERR_FAULT_NULL_FNCT; return; } pphy_api->LinkStateGet(pif, plink_state, perr); if (*perr != NET_PHY_ERR_NONE) { return; } *perr = NET_DEV_ERR_NONE; break; case NET_IF_IO_CTRL_LINK_STATE_UPDATE: plink_state = (NET_DEV_LINK_ETHER *)p_data; duplex = NET_PHY_DUPLEX_UNKNOWN; if (plink_state->Duplex != duplex) { switch (plink_state->Duplex) { /* Update duplex register setting on device. */ case NET_PHY_DUPLEX_FULL: /* The full duplex mode is set by default after Reset */ /* Setup the TEMAC TX in Full duplex mode */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TC); reg_val &= ~TEMAC_MASK_TC_HD; NetDev_IndirectWr_32(pif, TEMAC_REG_TC, reg_val); /* Setup the TEMAC RX in Full duplex mode */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_RCW1); reg_val &= ~TEMAC_MASK_RCW1_HD; NetDev_IndirectWr_32(pif, TEMAC_REG_RCW1, reg_val); break; case NET_PHY_DUPLEX_HALF: /* Half duplex mode not supported (see Xilinx document DS537) */ break; default: break; } } reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_EMMC); spd = NET_PHY_SPD_0; reg_val &= ~TEMAC_MASK_EMMC_LINKSPEED; if (plink_state->Spd != spd) { switch (plink_state->Spd) { /* Update speed register setting on device. */ case NET_PHY_SPD_10: reg_val |= TEMAC_EMMC_LINKSPD_10; /* 10Base-T */ NetDev_IndirectWr_32(pif, TEMAC_REG_EMMC, reg_val); break; case NET_PHY_SPD_100: reg_val |= TEMAC_EMMC_LINKSPD_100; /* 100Base-T */ NetDev_IndirectWr_32(pif, TEMAC_REG_EMMC, reg_val); break; case NET_PHY_SPD_1000: reg_val |= TEMAC_EMMC_LINKSPD_1000; /* 1000Base-T */ NetDev_IndirectWr_32(pif, TEMAC_REG_EMMC, reg_val); break; default: break; } } *perr = NET_DEV_ERR_NONE; break; default: *perr = NET_IF_ERR_INVALID_IO_CTRL_OPT; break; } } /* ********************************************************************************************************* * NetDev_MII_Rd() * * Description : Write data over the (R)MII bus to the specified Phy register. * * Argument(s) : pif Pointer to the interface requiring service. * * phy_addr (R)MII bus address of the Phy requiring service. * * reg_addr Phy register number to write to. * * p_data Pointer to variable to store returned register data. * * perr Pointer to return error code. * NET_DEV_ERR_NULL_PTR Pointer argument(s) passed NULL pointer(s). * NET_PHY_ERR_NONE MII write completed successfully. * NET_PHY_ERR_TIMEOUT_REG_RD Register read time-out. * * Return(s) : none. * * Caller(s) : Various Phy functions. * * Note(s) : (1) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. ********************************************************************************************************* */ static void NetDev_MII_Rd (NET_IF *pif, CPU_INT08U phy_addr, CPU_INT08U reg_addr, CPU_INT16U *p_data, NET_ERR *perr) { NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV *pdev; CPU_INT32U reg_val; CPU_INT32U int_en_reg; CPU_INT32U timeout_cnt; #if (NET_ERR_CFG_ARG_CHK_DBG_EN == DEF_ENABLED) if (p_data == (CPU_INT16U *)0) { *perr = NET_DEV_ERR_NULL_PTR; return; } #endif /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* Check if a Hard access can be done */ reg_val = pdev->TEMAC_REG_RDY; if (!(reg_val & TEMAC_MASK_RDY_HARD_ACS_RDY)) { *perr = NET_PHY_ERR_TIMEOUT_REG_RD; return; } /* NetDev_MII_Rd will poll for the status. The HardAcsCmplt */ /* bit is cleared in the IE reg so that the application code */ /* above doesn't also receive the interrupt. */ /* */ /* NetDev_MII_Rd saves the state of the IE reg so that it can */ /* clear the HardAcsCmplt bit and later restore the state of */ /* the IE register. Since */ int_en_reg = pdev->TEMAC_REG_IE; int_en_reg &= ~TEMAC_MASK_INT_HARDACSCMPLT; pdev->TEMAC_REG_IE = int_en_reg; /* Indirectly write the PHYAD and REGAD so we can read the PHY */ /* register back out in the LSW register. */ reg_val = reg_addr & TEMAC_MASK_MIIM_REGAD; reg_val |= ((phy_addr << TEMAC_MIIM_PHYAD_SHIFT) & TEMAC_MASK_MIIM_PHYAD); pdev->TEMAC_REG_LSW = reg_val; pdev->TEMAC_REG_CTL = TEMAC_REG_MIIMAI; /* Wait until the value is ready to be read. */ timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; do { reg_val = pdev->TEMAC_REG_RDY; timeout_cnt--; KAL_Dly(1); } while (!(reg_val & TEMAC_MASK_RDY_MIIM_RR) && timeout_cnt > 0); if (timeout_cnt == 0) { *perr = NET_PHY_ERR_TIMEOUT_REG_RD; return; } *p_data = pdev->TEMAC_REG_LSW; /* Read data */ /* clear the MIIM WST bit, and then write it back out. */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TIS); reg_val &= ~TEMAC_MASK_RDY_MIIM_RR; NetDev_IndirectWr_32(pif, TEMAC_REG_TIS, reg_val); pdev->TEMAC_REG_IE = int_en_reg; /* Restore the state of the IE reg */ *perr = NET_PHY_ERR_NONE; } /* ********************************************************************************************************* * NetDev_MII_Wr() * * Description : Write data over the (R)MII bus to the specified Phy register. * * Argument(s) : pif Pointer to the interface requiring service. * * phy_addr (R)MII bus address of the Phy requiring service. * * reg_addr Phy register number to write to. * * data Data to write to the specified Phy register. * * perr Pointer to return error code. * NET_PHY_ERR_NONE MII write completed successfully. * NET_PHY_ERR_TIMEOUT_REG_WR Register write time-out. * * Return(s) : none. * * Caller(s) : Various Phy functions. * * Note(s) : (1) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. ********************************************************************************************************* */ static void NetDev_MII_Wr (NET_IF *pif, CPU_INT08U phy_addr, CPU_INT08U reg_addr, CPU_INT16U data, NET_ERR *perr) { NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV *pdev; CPU_INT32U reg_val; CPU_INT32U int_en_reg; CPU_INT32U timeout_cnt; /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* Check if a Hard access can be done */ reg_val = pdev->TEMAC_REG_RDY; if (!(reg_val & TEMAC_MASK_RDY_HARD_ACS_RDY)) { *perr = NET_PHY_ERR_TIMEOUT_REG_WR; return; } /* NetDev_MII_Wr will poll for the status. The HardAcsCmplt */ /* bit is cleared in the IE reg so that the application code */ /* above doesn't also receive the interrupt. */ /* */ /* NetDev_MII_Wr saves the state of the IE reg so that it can */ /* clear the HardAcsCmplt bit and later restore the state of */ /* the IE register. Since */ int_en_reg = pdev->TEMAC_REG_IE; int_en_reg &= ~TEMAC_MASK_INT_HARDACSCMPLT; pdev->TEMAC_REG_IE = int_en_reg; /* Indirectly write the data to the MIIMWD register, and then */ /* indirectly write PHYAD and REGAD so the value in MIIMWD will */ /* get written to the PHY. */ NetDev_IndirectWr_32(pif, TEMAC_REG_MIIMWD, data); reg_val = reg_addr & TEMAC_MASK_MIIM_REGAD; reg_val |= ((phy_addr << TEMAC_MIIM_PHYAD_SHIFT) & TEMAC_MASK_MIIM_PHYAD); NetDev_IndirectWr_32(pif, TEMAC_REG_MIIMAI, reg_val); /* Wait until the value is ready to be read. */ timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; do { reg_val = pdev->TEMAC_REG_RDY; timeout_cnt--; KAL_Dly(1); } while (!(reg_val & TEMAC_MASK_RDY_MIIM_WR) && timeout_cnt > 0); if (timeout_cnt == 0) { *perr = NET_PHY_ERR_TIMEOUT_REG_WR; return; } /* clear the MIIM WST bit, and then write it back out. */ reg_val = NetDev_IndirectRd_32(pif, TEMAC_REG_TIS); reg_val &= TEMAC_MASK_RDY_MIIM_WR; NetDev_IndirectWr_32(pif, TEMAC_REG_TIS, reg_val); /* Restore the state of the IE reg */ pdev->TEMAC_REG_IE = int_en_reg; (void)&pdev; /* Prevent compilation warnings for variable set & ... */ *perr = NET_PHY_ERR_NONE; } /* ********************************************************************************************************* * NetDev_RxDescInit() * * Description : (1) This function initializes the Rx descriptor list for the specified interface : * (a) Obtain reference to the Rx descriptor(s) memory block * (b) Initialize Rx descriptor pointers * (c) Obtain Rx descriptor data areas * (d) Initialize hardware registers * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No error * NET_IF_MGR_ERR_nnnn Various Network Interface management error codes * NET_BUF_ERR_nnn Various Network buffer error codes * Return(s) : none. * * Caller(s) : NetDev_Start(). * * Note(s) : (2) Memory allocation for the descriptors MUST be performed BEFORE calling this * function. This ensures that multiple calls to this function do NOT allocate * additional memory to the interface and that the Rx descriptors may be safely * re-initialized by calling this function. * * (3) All Rx descriptors are allocated as ONE memory block. This removes the * necessity to ensure that descriptor blocks are returned to the descriptor * pool in the opposite order in which they were allocated; doing so would * ensure that each memory block address was contiguous to the one before * and after it. If the descriptors are NOT contiguous, then software * MUST NOT assign a pointer to the pool start address and use pointer * arithmetic to navigate the descriptor list. Since pointer arithmetic * is a convenient way to navigate the descriptor list, ONE block is allocated * and the driver uses pointer arithmetic to slice the block into descriptor * sized units. * * (4) In RX channel case, if "EOP" flag set but its DMA_AppData4 has value * DMA_USERAPP4_INIT_VAL, this means hardware has not completed updating the * RX decriptor structure ********************************************************************************************************* */ static void NetDev_RxDescInit (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; DEV_DESC *pdesc; CPU_INT16U i; /* ------------- OBTAIN REFERENCE TO DEVICE BSP --------------- */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* Obtain ptr to the dev bsp struct */ /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ pdesc = pdev_data->RxBufDescPtrStart; /* Obtain ptr to next ready desc. */ /* ------------------ INIT DESCRIPTOR PTRS ------------------- */ pdev_data->RxBufDescPtrCur = (DEV_DESC *)pdesc; pdev_data->RxBufDescPtrEnd = (DEV_DESC *)pdesc + (pdev_cfg->RxDescNbr - 1); pdev_data->RxBufDescPtrTail = pdev_data->RxBufDescPtrEnd; /* -------------------- INIT RX DESCRIPTORS ------------------- */ for (i = 0; i < pdev_cfg->RxDescNbr; i++) { pdesc->DMA_CurrBufLen = pdev_cfg->RxBufLargeSize; pdesc->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; pdesc->DMA_AppData1 = 0; pdesc->DMA_AppData2 = 0; pdesc->DMA_AppData3 = 0; pdesc->DMA_AppData4 = DMA_USERAPP4_INIT_VAL; /* See Note #4 */ pdesc->DMA_CurrBufAddr = (CPU_REG32)NetBuf_GetDataPtr((NET_IF *)pif, (NET_TRANSACTION)NET_TRANSACTION_RX, (NET_BUF_SIZE )NET_IF_ETHER_FRAME_MAX_SIZE, (NET_BUF_SIZE )NET_IF_IX_RX, (NET_BUF_SIZE *)0, (NET_BUF_SIZE *)0, (NET_BUF_TYPE *)0, (NET_ERR *)perr); if (*perr != NET_BUF_ERR_NONE) { return; } if (pdesc == (pdev_data->RxBufDescPtrEnd)) { /* Chain the last Descriptor in the list. */ pdesc->DMA_NextDescAddr = (CPU_REG32)pdev_data->RxBufDescPtrStart; } else { /* Point to next descriptor in the list. */ pdesc->DMA_NextDescAddr = (CPU_REG32)(pdesc + 1); } /* Flush the current desc. in case of data cache enabled */ CPU_CacheDataFlush(pdesc, sizeof(DEV_DESC)); pdesc++; } /* ----------------- INIT HARDWARE REGISTERS ------------------ */ /* Configure the DMA RX Channel Current Desc Register */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CDESC, (CPU_INT32U)pdev_data->RxBufDescPtrStart); /* Configure the DMA RX Channel TAIL Desc Register */ /* This will allow the DMA RX channel to start */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_TDESC, (CPU_INT32U)(pdev_data->RxBufDescPtrEnd)); *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_RxDescFreeAll() * * Description : (1) This function returns the descriptor memory block and descriptor data area * memory blocks back to their respective memory pools : * * (a) Free Rx descriptor data areas * (b) Free Rx descriptor memory block * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No error * NET_IF_MGR_ERR_nnnn Various Network Interface management error codes * NET_BUF_ERR_nnn Various Network buffer error codes * Return(s) : none. * * Caller(s) : NetDev_Stop(). * * Note(s) : (2) No mechanism exists to free a memory pool. However, ALL receive buffers * and the Rx descriptor blocks MUST be returned to their respective pools. ********************************************************************************************************* */ static void NetDev_RxDescFreeAll(NET_IF *pif, NET_ERR *perr) { NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; MEM_POOL *pmem_pool; DEV_DESC *pdesc; LIB_ERR lib_err; CPU_INT16U i; CPU_INT08U *pdesc_data; /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ /* ------------ OBTAIN REFERENCE TO RX DESC POOL -------------- */ pmem_pool = (MEM_POOL *)&pdev_data->RxDescPool; /* ----------------- FREE RX DESC DATA AREAS ------------------ */ pdesc = pdev_data->RxBufDescPtrStart; for (i = 0; i < pdev_cfg->RxDescNbr; i++) { /* Free Rx descriptor ring. */ pdesc_data = (CPU_INT08U *)(pdesc->DMA_CurrBufAddr); NetBuf_FreeBufDataAreaRx(pif->Nbr, pdesc_data); /* Return data area to Rx data area pool. */ pdesc++; } /* -------------------- FREE RX DESC BLOCK -------------------- */ Mem_PoolBlkFree( pmem_pool, /* Return Rx descriptor block to Rx descriptor pool. */ pdev_data->RxBufDescPtrStart, &lib_err); if (lib_err != LIB_MEM_ERR_NONE) { *perr = NET_ERR_FAULT_MEM_ALLOC; return; } *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_RxDescPtrCurInc() * * Description : (1) Increment current descriptor pointer to next receive descriptor : * * (a) Return ownership of current descriptor back to DMA. * (b) Point to the next descriptor. * * Argument(s) : pif Pointer to interface requiring service. * --- * * Return(s) : none. * * Caller(s) : NetDev_Rx(). * * Note(s) : none. ********************************************************************************************************* */ static void NetDev_RxDescPtrCurInc (NET_IF *pif) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_DATA *pdev_data; DEV_DESC *pdesc; NET_ERR err; /* ----------- OBTAIN REFERENCE TO DEVICE BSP AREA ------------ */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* Obtain ptr to dev bsp struct */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ pdesc = pdev_data->RxBufDescPtrCur; pdesc->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; /* Free the current desc. and flush cache memory if enabled */ pdesc->DMA_AppData4 = DMA_USERAPP4_INIT_VAL; CPU_CacheDataFlush(pdesc, sizeof(DEV_DESC)); /* Update the DMA RX Channel tail register */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_TDESC, (CPU_INT32U)pdev_data->RxBufDescPtrCur); pdev_data->RxBufDescPtrTail = pdev_data->RxBufDescPtrCur; /* Check if there are other completed RX frames */ pdev_data->RxBufDescPtrCur = (DEV_DESC *)pdesc->DMA_NextDescAddr; pdesc = pdev_data->RxBufDescPtrCur; CPU_CacheDataInvalidate((CPU_VOID *)pdesc, sizeof(DEV_DESC)); /* Check if the desc marked as completed. */ if ((pdesc->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_COMPLETED)) { NetIF_RxTaskSignal(pif->Nbr, &err); /* Signal Net IF RxQ Task for each new rdy Desc. */ switch (err) { case NET_IF_ERR_NONE: NET_CTR_STAT_INC(pdev_data->StatRxCtrTaskSignalSelf); break; case NET_IF_ERR_RX_Q_FULL: case NET_IF_ERR_RX_Q_SIGNAL_FAULT: default: NET_CTR_ERR_INC(pdev_data->ErrRxCtrTaskSignalFail); break; } } else { /* Re-enable DMA Rx Interrupt as it was disabled when the */ /* previous DMA Rx int. occured. This is done to prevent */ /* errors reading a descriptor which have been processed */ NetDev_DMA_EnDisChInt(pif, pdev_data->DMA_AddrRx, INT_ENABLE); NET_CTR_STAT_INC(pdev_data->StatRxCtrTaskSignalNone); } } /* ********************************************************************************************************* * NetDev_TxDescInit() * * Description : (1) This function initializes the Tx descriptor list for the specified interface : * * (a) Obtain reference to the Rx descriptor(s) memory block * (b) Initialize Tx descriptor pointers * (c) Obtain Rx descriptor data areas * (d) Initialize hardware registers * * Argument(s) : pif Pointer to the interface requiring service. * * perr Pointer to return error code. * NET_DEV_ERR_NONE No error * NET_IF_MGR_ERR_nnnn Various Network Interface management error codes * NET_BUF_ERR_nnn Various Network buffer error codes * Return(s) : none. * * Caller(s) : NetDev_Start(). * * Note(s) : (2) All functions that require device register access MUST obtain reference * to the device hardware register space PRIOR to attempting to access * any registers. Register definitions SHOULD NOT be absolute and SHOULD * use the provided base address within the device configuration structure, * as well as the device register definition structure in order to properly * resolve register addresses during run-time. * * (3) All Tx descriptors are allocated as ONE memory block. This removes the * necessity to ensure that descriptor blocks are returned to the descriptor * pool in the opposite order in which they were allocated; doing so would * ensure that each memory block address was contiguous to the one before * and after it. If the descriptors are NOT contiguous, then software * MUST NOT assign a pointer to the pool start address and use pointer * arithmetic to navigate the descriptor list. Since pointer arithmetic * is a convenient way to navigate the descriptor list, ONE block is allocated * and the driver uses pointer arithmetic to slice the block into descriptor * sized units. ********************************************************************************************************* */ static void NetDev_TxDescInit (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV_DATA *pdev_data; DEV_DESC *pdesc; CPU_INT16U i; /* -------------- OBTAIN REFERENCE TO DEVICE BSP ------------- */ pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; /* Obtain ptr to the dev bsp struct. */ /* ----------- OBTAIN REFERENCE TO DEVICE REGISTERS ----------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ /* ----------- OBTAIN REFERENCE TO DEVICE DATA AREA ----------- */ pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to dev data area. */ /* ------------------- INIT DESCRIPTOR PTRS ------------------ */ pdesc = (DEV_DESC *)pdev_data->TxBufDescPtrStart; pdev_data->TxBufDescCompPtr = (DEV_DESC *)pdev_data->TxBufDescPtrStart; pdev_data->TxBufDescPtrEnd = (DEV_DESC *)pdesc + (pdev_cfg->TxDescNbr - 1); pdev_data->TxBufDescPtrCur = (DEV_DESC *)pdev_data->TxBufDescPtrStart; for (i = 0; i < pdev_cfg->TxDescNbr; i++) { /* Init Tx desc ring. */ pdesc->DMA_CurrBufAddr = 0; pdesc->DMA_CurrBufLen = 0; pdesc->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; pdesc->DMA_CtrlAndStatus |= DMA_MASK_BD_STSCTRL_COMPLETED; pdesc->DMA_AppData1 = 0; pdesc->DMA_AppData2 = 0; pdesc->DMA_AppData3 = 0; pdesc->DMA_AppData4 = 0; /* Chain the last Descriptor in the list */ if (pdesc == (pdev_data->TxBufDescPtrEnd)) { pdesc->DMA_NextDescAddr = (CPU_REG32)pdev_data->TxBufDescPtrStart; } else { /* Point to next descriptor in the list. */ pdesc->DMA_NextDescAddr = (CPU_REG32)(pdesc + 1); } CPU_CacheDataFlush(pdesc, sizeof(DEV_DESC)); pdesc++; } /* ----------------- INIT HARDWARE REGISTERS ------------------ */ /* Configure the DMA TX Current Desc. Register with the Ring */ /* start address. */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CDESC, (CPU_INT32U)pdev_data->TxBufDescPtrStart); *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_SetCoalesce() * * Description : Configure interrupt coalescing for the given DMA channel * * Argument(s) : pif Pointer to the interface requiring service * * dma_ch_addr DMA Channel offset * * cntr The completed packet count before generating an interrupt * Valid value 1 to 255 or DMA_NO_CHANGE to leave the counter value * inchanged * * timer_val Dly before generating an interrupt if no activity was detected. This allow * the software to read any pending completed descriptors especially if cntr * (previous parameter) is greater than 1. * * Return(s) : none. * * Caller(s) : NetDev_DMA_Reset(). * * Note(s) : none ********************************************************************************************************* */ static void NetDev_SetCoalesce (NET_IF *pif, CPU_INT32U dma_ch_addr, CPU_INT08U cntr, CPU_INT08U timer_val) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; CPU_INT32U dma_ctr_reg; pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; dma_ctr_reg = pdev_bsp->DMA_Rd32(dma_ch_addr + DMA_REG_CR); if (cntr != DMA_NO_CHANGE) { dma_ctr_reg &= ~DMA_MASK_CR_IRQ_COUNT; dma_ctr_reg |= cntr << DMA_CR_IRQ_COUNT_SHIFT; dma_ctr_reg |= DMA_MASK_CR_LD_IRQ_CNT; } if (timer_val != DMA_NO_CHANGE) { dma_ctr_reg &= ~DMA_MASK_CR_IRQ_TIMEOUT; dma_ctr_reg |= timer_val << DMA_CR_IRQ_TIMEOUT_SHIFT; dma_ctr_reg |= DMA_MASK_CR_LD_IRQ_CNT; } pdev_bsp->DMA_Wr32(dma_ch_addr + DMA_REG_CR, dma_ctr_reg); } /* ********************************************************************************************************* * NetDev_DMA_Reset() * * Description : Reset the DMA. * * Argument(s) : pif Pointer to the interface requiring service * * perr Pointer to return error code * * NET_DEV_ERR_RST code returned if DMA reset failed. * NET_DEV_ERR_NONE no error occured during the DMA reset * * Return(s) : none. * * Caller(s) : NetDev_Init(), * NetDev_DMARecover(). * * Note(s) : none ********************************************************************************************************* */ static void NetDev_DMA_Reset (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_DATA *pdev_data; CPU_INT32U reg_val; CPU_INT32U timeout_cnt; pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; pdev_data = (NET_DEV_DATA *)pif->Dev_Data; /* Obtain ptr to the dev data area. */ /* Reset the DMA */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrBase + DMA_GLB_CR_REG, DMA_MASK_CR_SW_RST); reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrBase + DMA_GLB_CR_REG); /* wait for DMA reset completion */ timeout_cnt = 2; while ((reg_val & DMA_MASK_CR_SW_RST) && timeout_cnt > 0) { KAL_Dly(2); reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrBase + DMA_GLB_CR_REG); timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_ERR_RST; return; } /* ----------------- DISABLE ALL INTERRUPTS ------------------- */ /* Disable TX channel interrupts */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_CR); reg_val &= ~DMA_MASK_CR_IRQ_ALL_EN; pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CR, reg_val); /* Disable RX channel interrupts */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_CR); reg_val &= ~DMA_MASK_CR_IRQ_ALL_EN; pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CR, reg_val); /* Clear TX channel Interrupts register */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_IRQ); pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_IRQ, reg_val); /* Clear RX channel Interrupts register */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_IRQ); pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_IRQ, reg_val); /* Configure the DMA in normal mode and disable overflow errors */ /* for RX and TX DMA Channels */ reg_val = DMA_MASK_CR_TAIL_PTR_EN | DMA_MASK_CR_RX_OVFL_ERR_DIS | DMA_MASK_CR_TX_OVFL_ERR_DIS; pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrBase + DMA_GLB_CR_REG, reg_val); /* TX/RX Channel coalescing setting */ NetDev_SetCoalesce(pif, pdev_data->DMA_AddrTx, 1, 1); NetDev_SetCoalesce(pif, pdev_data->DMA_AddrRx, 1, 1); *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_DMA_ErrRecover() * * Description : Recover from DMA error interrupts. * * Argument(s) : pif Pointer to interface requiring service. * * perr Pointer to return error code * * NET_DEV_ERR_RST Reset error code returned by NetDev_DMA_Reset() * NET_DEV_ERR_NONE no error occured during the DMA reset * * Return(s) : none. * * Caller(s) : NetDev_ISR_Handler(). * * Note(s) : none ********************************************************************************************************* */ static void NetDev_DMA_ErrRecover (NET_IF *pif, NET_ERR *perr) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; NET_DEV_DATA *pdev_data; CPU_INT32U reg_val; DEV_DESC *pdesc; DEV_DESC *pdesc_tmp; CPU_INT08U *p_data; NetDev_DMA_Reset(pif, perr); /* Reset the DMA and disable DMA interrupts */ if (*perr != NET_DEV_ERR_NONE) { return; } pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; pdev_data = (NET_DEV_DATA *)pif->Dev_Data; pdesc = (DEV_DESC *)pdev_data->RxBufDescPtrCur; /* Check if there are valid completed RX descriptors */ CPU_CacheDataInvalidate((CPU_VOID *)pdesc, sizeof(DEV_DESC)); while ((pdesc->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_COMPLETED)) { pdesc = (DEV_DESC*)pdesc->DMA_NextDescAddr; CPU_CacheDataInvalidate((CPU_VOID *)pdesc, sizeof(DEV_DESC)); if (pdesc == pdev_data->RxBufDescPtrTail) { break; } } /* Re-initialiaze the RX descriptors located between the last */ /* completed and the tail descriptor */ pdesc_tmp = pdesc; while (pdesc_tmp != pdev_data->RxBufDescPtrCur) { if (pdesc_tmp->DMA_CtrlAndStatus & DMA_MASK_BD_STSCTRL_COMPLETED) { pdesc_tmp->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; pdesc_tmp->DMA_AppData1 = 0; pdesc_tmp->DMA_AppData2 = 0; pdesc_tmp->DMA_AppData3 = 0; pdesc_tmp->DMA_AppData4 = DMA_USERAPP4_INIT_VAL; CPU_CacheDataFlush(pdesc_tmp, sizeof(DEV_DESC)); } pdesc_tmp = (DEV_DESC*)pdesc_tmp->DMA_NextDescAddr; } /* Configure the DMA RX Channel Current Desc Register */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CDESC, (CPU_INT32U)pdesc); /* Configure the DMA RX Channel tail Desc Register */ /* This will allow the DMA RX channel to start */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_TDESC, (CPU_INT32U)pdev_data->RxBufDescPtrTail); /* Configure the DMA TX Current Desc. Register with the current */ /* TX descriptor address. */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CDESC, (CPU_INT32U)pdev_data->TxBufDescPtrCur); /* The DMA TX channel is restarted, so we need to synchronize */ /* TxBufDescCompPtr and give back the data buffer to the stack */ pdesc = pdev_data->TxBufDescCompPtr; pdesc->DMA_CtrlAndStatus = ~DMA_MASK_BD_STSCTRL; pdesc->DMA_CtrlAndStatus |= DMA_MASK_BD_STSCTRL_COMPLETED; p_data = (CPU_INT08U *)pdesc->DMA_CurrBufAddr; NetIF_TxDeallocTaskPost(p_data, perr); /* The DMA TX channel is restarted so we signal Net IF */ /* that Tx resources are available. */ NetIF_DevTxRdySignal(pif); pdev_data->TxBufDescCompPtr = (DEV_DESC *)pdev_data->TxBufDescCompPtr->DMA_NextDescAddr; /* ---------------- ENABLE DMA INTERRUPTS --------------------- */ /* Enable DMA RX interrupt. */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrRx + DMA_REG_CR); reg_val |= DMA_MASK_CR_IRQ_EN | /* Master interrupt enable */ DMA_MASK_CR_IRQ_ERR_EN | /* Enable error interrupt */ DMA_MASK_CR_IRQ_DLY_EN | /* Enable coalesce delay interrupt */ DMA_MASK_CR_IRQ_COALESCE_EN; /* Enable coalesce count */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrRx + DMA_REG_CR, reg_val); /* Enable DMA TX interrupt. */ reg_val = pdev_bsp->DMA_Rd32(pdev_data->DMA_AddrTx + DMA_REG_CR); reg_val |= DMA_MASK_CR_IRQ_EN | /* Master interrupt enable */ DMA_MASK_CR_IRQ_ERR_EN | /* Enable error interrupt */ DMA_MASK_CR_IRQ_DLY_EN | /* Enable coalesce delay interrupt */ DMA_MASK_CR_IRQ_COALESCE_EN; /* Enable coalesce count */ pdev_bsp->DMA_Wr32(pdev_data->DMA_AddrTx + DMA_REG_CR, reg_val); *perr = NET_DEV_ERR_NONE; } /* ********************************************************************************************************* * NetDev_DMA_EnDisChanInt() * * Description : Enable or disable a DMA channel interrupts * * Argument(s) : dma_ch_addr DMA Channel address * * en indicates if interrupts should be enabled or disabled * * Return(s) : none. * * Caller(s) : NetDev_ISR_Handler(), * NetDev_RxDescPtrCurInc(). * * Note(s) : none ********************************************************************************************************* */ static void NetDev_DMA_EnDisChInt (NET_IF *pif, CPU_INT32U dma_ch_addr, CPU_INT08U en) { NET_DEV_BSP_XPS_LL_TEMAC_DMA *pdev_bsp; CPU_INT32U reg_val; pdev_bsp = (NET_DEV_BSP_XPS_LL_TEMAC_DMA *)pif->Dev_BSP; reg_val = pdev_bsp->DMA_Rd32(dma_ch_addr + DMA_REG_CR); if (en > 0) { reg_val |= DMA_MASK_CR_IRQ_EN; /* Master interrupt enable */ } else { reg_val &= ~DMA_MASK_CR_IRQ_EN; /* Master interrupt disable */ } pdev_bsp->DMA_Wr32(dma_ch_addr + DMA_REG_CR, reg_val); } /* ********************************************************************************************************* * NetDev_AddrMulticastGet() * * Description : Get the Multicast address stored at a given entry in the multicast table * * Argument(s) : pif Pointer to an Ethernet network interface. * --- Argument validated in NetIF_AddrHW_SetHandler(). * * paddr_hw Pointer to hardware address. * -------- Argument checked in NetIF_AddrHW_SetHandler(). * * entry Multicast table entry from where the address will be read * * perr Pointer to variable that will receive the return error code from this function : * * NET_DEV_ERR_NONE Hardware address successfully returned. * * NET_DEV_MCAST_TAB_ERR_RD Error during Multicast table entry read. * * Return(s) : none. * * Caller(s) : NetDev_AddrMulticastAdd(), NetDev_AddrMulticastRemove(). * * Note(s) : none. ********************************************************************************************************* */ #ifdef NET_MCAST_MODULE_EN static void NetDev_AddrMulticastGet (NET_IF *pif, CPU_INT08U *paddr_hw, CPU_INT32U entry, NET_ERR *perr) { NET_DEV *pdev; NET_DEV_CFG_ETHER *pdev_cfg; CPU_INT32U reg_val1; CPU_INT32U reg_val2; CPU_INT32U rdy_reg_val; CPU_INT16U timeout_cnt; /* ------------ OBTAIN REFERENCE TO DEVICE REGISTERS ---------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct. */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ /* Prepare for read the Muticast entry table */ reg_val2 = (TEMAC_MASK_MCAST_RNW | (entry << TEMAC_MAW1_ADDR_SHIFT)); NetDev_IndirectWr_32(pif, TEMAC_REG_MAW1, reg_val2); /* Read the hw address from TEMAC_REG_LSW and TEMAC_REG_MSW */ rdy_reg_val = pdev->TEMAC_REG_RDY; timeout_cnt = TEMAC_INDIRECT_REG_ACCESS_TO_CNT; while (!(rdy_reg_val & TEMAC_MASK_RDY_AF_RR) && timeout_cnt > 0) { KAL_Dly(TEMAC_INDIRECT_REG_ACCESS_DLY_MS); rdy_reg_val = pdev->TEMAC_REG_RDY; timeout_cnt--; } if (timeout_cnt == 0) { *perr = NET_DEV_MCAST_TAB_ERR_RD; return; } /* After requisting a read to the Multicast table, data should */ /* be available from the LSW and MSW registers */ reg_val1 = pdev->TEMAC_REG_LSW; reg_val2 = pdev->TEMAC_REG_MSW; paddr_hw[0] = (CPU_INT08U)(reg_val1); paddr_hw[1] = (CPU_INT08U)(reg_val1 >> 8); paddr_hw[2] = (CPU_INT08U)(reg_val1 >> 16); paddr_hw[3] = (CPU_INT08U)(reg_val1 >> 24); paddr_hw[4] = (CPU_INT08U)(reg_val2); paddr_hw[5] = (CPU_INT08U)(reg_val2 >> 8); *perr = NET_DEV_ERR_NONE; } #endif /* ********************************************************************************************************* * NetDev_IndirectWr_32() * * Description : Write TEMAC register which is indirectly accessed. * * Argument(s) : pif Pointer to the interface requiring service. * * reg_offset Offset of the register to write to. * * val Value to write to register. * * Return(s) : none. * * Caller(s) : various. * * Note(s) : none ********************************************************************************************************* */ static void NetDev_IndirectWr_32 (NET_IF *pif, CPU_INT32U reg_offset, CPU_INT32U val) { NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV *pdev; /* -------- OBTAIN REFERENCE TO DEVICE REGISTERS --------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ pdev->TEMAC_REG_LSW = val; pdev->TEMAC_REG_CTL = reg_offset | TEMAC_MASK_CTL_WEN; } /* ********************************************************************************************************* * NetDev_IndirectRd_32() * * Description : Read TEMAC register which is indirectly accessed. * * Argument(s) : pif Pointer to the interface requiring service. * * reg_offset Offset of the register to read from. * * Return(s) : Value read from register. * * Caller(s) : various. * * Note(s) : none ********************************************************************************************************* */ static CPU_INT32U NetDev_IndirectRd_32 (NET_IF *pif, CPU_INT32U reg_offset) { NET_DEV_CFG_ETHER *pdev_cfg; NET_DEV *pdev; CPU_INT32U reg_val; /* -------- OBTAIN REFERENCE TO DEVICE REGISTERS --------- */ pdev_cfg = (NET_DEV_CFG_ETHER *)pif->Dev_Cfg; /* Obtain ptr to the dev cfg struct */ pdev = (NET_DEV *)pdev_cfg->BaseAddr; /* Overlay dev reg struct on top of dev base addr. */ pdev->TEMAC_REG_CTL = reg_offset; reg_val = pdev->TEMAC_REG_LSW; return (reg_val); } #endif /* NET_IF_ETHER_MODULE_EN */
327332.c
// https://practice.geeksforgeeks.org/problems/recamans-sequence/0 #include<stdio.h> #include<stdlib.h> void printRecman(int n) { int* hashMap = (int*)calloc(100000,sizeof(int)); int* arr = (int*)calloc(n+1,sizeof(int)); int i; for(i=0;i<100000;i++) { hashMap[i]=0; } arr[0]=0; hashMap[0]=1; for(i=1;i<=n;i++) { int test = arr[i-1] - i; if(test>0&&hashMap[test]==0) { arr[i] = test; hashMap[test]++; } else { arr[i] = test + 2*i; hashMap[test+2*i]++; } } for(i=0;i<n;i++) { printf("%d ",arr[i]); } free(arr); free(hashMap); } int main() { int t; scanf("%d",&t); while(t--) { int n; scanf("%d",&n); printRecman(n); printf("\n"); } return 0; }
912803.c
/* comedi/drivers/multiq3.c Hardware driver for Quanser Consulting MultiQ-3 board COMEDI - Linux Control and Measurement Device Interface Copyright (C) 1999 Anders Blomdell <[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. 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* Driver: multiq3 Description: Quanser Consulting MultiQ-3 Author: Anders Blomdell <[email protected]> Status: works Devices: [Quanser Consulting] MultiQ-3 (multiq3) */ #include <linux/interrupt.h> #include "../comedidev.h" #include <linux/ioport.h> #define MULTIQ3_SIZE 16 /* * MULTIQ-3 port offsets */ #define MULTIQ3_DIGIN_PORT 0 #define MULTIQ3_DIGOUT_PORT 0 #define MULTIQ3_DAC_DATA 2 #define MULTIQ3_AD_DATA 4 #define MULTIQ3_AD_CS 4 #define MULTIQ3_STATUS 6 #define MULTIQ3_CONTROL 6 #define MULTIQ3_CLK_DATA 8 #define MULTIQ3_ENC_DATA 12 #define MULTIQ3_ENC_CONTROL 14 /* * flags for CONTROL register */ #define MULTIQ3_AD_MUX_EN 0x0040 #define MULTIQ3_AD_AUTOZ 0x0080 #define MULTIQ3_AD_AUTOCAL 0x0100 #define MULTIQ3_AD_SH 0x0200 #define MULTIQ3_AD_CLOCK_4M 0x0400 #define MULTIQ3_DA_LOAD 0x1800 #define MULTIQ3_CONTROL_MUST 0x0600 /* * flags for STATUS register */ #define MULTIQ3_STATUS_EOC 0x008 #define MULTIQ3_STATUS_EOC_I 0x010 /* * flags for encoder control */ #define MULTIQ3_CLOCK_DATA 0x00 #define MULTIQ3_CLOCK_SETUP 0x18 #define MULTIQ3_INPUT_SETUP 0x41 #define MULTIQ3_QUAD_X4 0x38 #define MULTIQ3_BP_RESET 0x01 #define MULTIQ3_CNTR_RESET 0x02 #define MULTIQ3_TRSFRPR_CTR 0x08 #define MULTIQ3_TRSFRCNTR_OL 0x10 #define MULTIQ3_EFLAG_RESET 0x06 #define MULTIQ3_TIMEOUT 30 struct multiq3_private { unsigned int ao_readback[2]; }; #define devpriv ((struct multiq3_private *)dev->private) static int multiq3_ai_insn_read(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { int i, n; int chan; unsigned int hi, lo; chan = CR_CHAN(insn->chanspec); outw(MULTIQ3_CONTROL_MUST | MULTIQ3_AD_MUX_EN | (chan << 3), dev->iobase + MULTIQ3_CONTROL); for (i = 0; i < MULTIQ3_TIMEOUT; i++) { if (inw(dev->iobase + MULTIQ3_STATUS) & MULTIQ3_STATUS_EOC) break; } if (i == MULTIQ3_TIMEOUT) return -ETIMEDOUT; for (n = 0; n < insn->n; n++) { outw(0, dev->iobase + MULTIQ3_AD_CS); for (i = 0; i < MULTIQ3_TIMEOUT; i++) { if (inw(dev->iobase + MULTIQ3_STATUS) & MULTIQ3_STATUS_EOC_I) break; } if (i == MULTIQ3_TIMEOUT) return -ETIMEDOUT; hi = inb(dev->iobase + MULTIQ3_AD_CS); lo = inb(dev->iobase + MULTIQ3_AD_CS); data[n] = (((hi << 8) | lo) + 0x1000) & 0x1fff; } return n; } static int multiq3_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { int i; int chan = CR_CHAN(insn->chanspec); for (i = 0; i < insn->n; i++) data[i] = devpriv->ao_readback[chan]; return i; } static int multiq3_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { int i; int chan = CR_CHAN(insn->chanspec); for (i = 0; i < insn->n; i++) { outw(MULTIQ3_CONTROL_MUST | MULTIQ3_DA_LOAD | chan, dev->iobase + MULTIQ3_CONTROL); outw(data[i], dev->iobase + MULTIQ3_DAC_DATA); outw(MULTIQ3_CONTROL_MUST, dev->iobase + MULTIQ3_CONTROL); devpriv->ao_readback[chan] = data[i]; } return i; } static int multiq3_di_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { data[1] = inw(dev->iobase + MULTIQ3_DIGIN_PORT); return insn->n; } static int multiq3_do_insn_bits(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { s->state &= ~data[0]; s->state |= (data[0] & data[1]); outw(s->state, dev->iobase + MULTIQ3_DIGOUT_PORT); data[1] = s->state; return insn->n; } static int multiq3_encoder_insn_read(struct comedi_device *dev, struct comedi_subdevice *s, struct comedi_insn *insn, unsigned int *data) { int n; int chan = CR_CHAN(insn->chanspec); int control = MULTIQ3_CONTROL_MUST | MULTIQ3_AD_MUX_EN | (chan << 3); for (n = 0; n < insn->n; n++) { int value; outw(control, dev->iobase + MULTIQ3_CONTROL); outb(MULTIQ3_BP_RESET, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_TRSFRCNTR_OL, dev->iobase + MULTIQ3_ENC_CONTROL); value = inb(dev->iobase + MULTIQ3_ENC_DATA); value |= (inb(dev->iobase + MULTIQ3_ENC_DATA) << 8); value |= (inb(dev->iobase + MULTIQ3_ENC_DATA) << 16); data[n] = (value + 0x800000) & 0xffffff; } return n; } static void encoder_reset(struct comedi_device *dev) { struct comedi_subdevice *s = &dev->subdevices[4]; int chan; for (chan = 0; chan < s->n_chan; chan++) { int control = MULTIQ3_CONTROL_MUST | MULTIQ3_AD_MUX_EN | (chan << 3); outw(control, dev->iobase + MULTIQ3_CONTROL); outb(MULTIQ3_EFLAG_RESET, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_BP_RESET, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_CLOCK_DATA, dev->iobase + MULTIQ3_ENC_DATA); outb(MULTIQ3_CLOCK_SETUP, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_INPUT_SETUP, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_QUAD_X4, dev->iobase + MULTIQ3_ENC_CONTROL); outb(MULTIQ3_CNTR_RESET, dev->iobase + MULTIQ3_ENC_CONTROL); } } /* options[0] - I/O port options[1] - irq options[2] - number of encoder chips installed */ static int multiq3_attach(struct comedi_device *dev, struct comedi_devconfig *it) { int result = 0; unsigned long iobase; unsigned int irq; struct comedi_subdevice *s; iobase = it->options[0]; printk(KERN_INFO "comedi%d: multiq3: 0x%04lx ", dev->minor, iobase); if (!request_region(iobase, MULTIQ3_SIZE, "multiq3")) { printk(KERN_ERR "comedi%d: I/O port conflict\n", dev->minor); return -EIO; } dev->iobase = iobase; irq = it->options[1]; if (irq) printk(KERN_WARNING "comedi%d: irq = %u ignored\n", dev->minor, irq); else printk(KERN_WARNING "comedi%d: no irq\n", dev->minor); dev->board_name = "multiq3"; result = comedi_alloc_subdevices(dev, 5); if (result) return result; result = alloc_private(dev, sizeof(struct multiq3_private)); if (result < 0) return result; s = &dev->subdevices[0]; /* ai subdevice */ s->type = COMEDI_SUBD_AI; s->subdev_flags = SDF_READABLE | SDF_GROUND; s->n_chan = 8; s->insn_read = multiq3_ai_insn_read; s->maxdata = 0x1fff; s->range_table = &range_bipolar5; s = &dev->subdevices[1]; /* ao subdevice */ s->type = COMEDI_SUBD_AO; s->subdev_flags = SDF_WRITABLE; s->n_chan = 8; s->insn_read = multiq3_ao_insn_read; s->insn_write = multiq3_ao_insn_write; s->maxdata = 0xfff; s->range_table = &range_bipolar5; s = &dev->subdevices[2]; /* di subdevice */ s->type = COMEDI_SUBD_DI; s->subdev_flags = SDF_READABLE; s->n_chan = 16; s->insn_bits = multiq3_di_insn_bits; s->maxdata = 1; s->range_table = &range_digital; s = &dev->subdevices[3]; /* do subdevice */ s->type = COMEDI_SUBD_DO; s->subdev_flags = SDF_WRITABLE; s->n_chan = 16; s->insn_bits = multiq3_do_insn_bits; s->maxdata = 1; s->range_table = &range_digital; s->state = 0; s = &dev->subdevices[4]; /* encoder (counter) subdevice */ s->type = COMEDI_SUBD_COUNTER; s->subdev_flags = SDF_READABLE | SDF_LSAMPL; s->n_chan = it->options[2] * 2; s->insn_read = multiq3_encoder_insn_read; s->maxdata = 0xffffff; s->range_table = &range_unknown; encoder_reset(dev); return 0; } static void multiq3_detach(struct comedi_device *dev) { if (dev->iobase) release_region(dev->iobase, MULTIQ3_SIZE); if (dev->irq) free_irq(dev->irq, dev); } static struct comedi_driver multiq3_driver = { .driver_name = "multiq3", .module = THIS_MODULE, .attach = multiq3_attach, .detach = multiq3_detach, }; module_comedi_driver(multiq3_driver); MODULE_AUTHOR("Comedi http://www.comedi.org"); MODULE_DESCRIPTION("Comedi low-level driver"); MODULE_LICENSE("GPL");
428439.c
/* * Copyright 2017, Data61, CSIRO (ABN 41 687 119 230) * * SPDX-License-Identifier: BSD-2-Clause */ /* Include Kconfig variables. */ #include <autoconf.h> #include <sel4test-driver/gen_config.h> #include <sel4debug/register_dump.h> #include <vka/capops.h> #include "test.h" #include "timer.h" #include <sel4rpc/server.h> #include <sel4testsupport/testreporter.h> /* Bootstrap test type. */ static inline void bootstrap_set_up_test_type(uintptr_t e) { ZF_LOGD("setting up bootstrap test type\n"); } static inline void bootstrap_tear_down_test_type(uintptr_t e) { ZF_LOGD("tearing down bootstrap test type\n"); } static inline void bootstrap_set_up(uintptr_t e) { ZF_LOGD("set up bootstrap test\n"); } static inline void bootstrap_tear_down(uintptr_t e) { ZF_LOGD("tear down bootstrap test\n"); } static inline test_result_t bootstrap_run_test(struct testcase *test, uintptr_t e) { return test->function(e); } static DEFINE_TEST_TYPE(BOOTSTRAP, BOOTSTRAP, bootstrap_set_up_test_type, bootstrap_tear_down_test_type, bootstrap_set_up, bootstrap_tear_down, bootstrap_run_test); /* Basic test type. Each test is launched as its own process. */ /* copy untyped caps into a processes cspace, return the cap range they can be found in */ static seL4_SlotRegion copy_untypeds_to_process(sel4utils_process_t *process, vka_object_t *untypeds, int num_untypeds, driver_env_t env) { seL4_SlotRegion range = {0}; for (int i = 0; i < num_untypeds; i++) { seL4_CPtr slot = sel4utils_copy_cap_to_process(process, &env->vka, untypeds[i].cptr); /* set up the cap range */ if (i == 0) { range.start = slot; } range.end = slot; } assert((range.end - range.start) + 1 == num_untypeds); return range; } static void handle_timer_requests(driver_env_t env, sel4test_output_t test_output) { seL4_MessageInfo_t info; uint64_t timeServer_ns; seL4_Word timeServer_timeoutType; switch (test_output) { case SEL4TEST_TIME_TIMEOUT: timeServer_timeoutType = seL4_GetMR(1); timeServer_ns = sel4utils_64_get_mr(2); timeout(env, timeServer_ns, timeServer_timeoutType); info = seL4_MessageInfo_new(seL4_Fault_NullFault, 0, 0, 1); seL4_SetMR(0, 0); api_reply(env->reply.cptr, info); break; case SEL4TEST_TIME_TIMESTAMP: timeServer_ns = timestamp(env); sel4utils_64_set_mr(1, timeServer_ns); info = seL4_MessageInfo_new(seL4_Fault_NullFault, 0, 0, SEL4UTILS_64_WORDS + 1); seL4_SetMR(0, 0); api_reply(env->reply.cptr, info); break; case SEL4TEST_TIME_RESET: timer_reset(env); info = seL4_MessageInfo_new(seL4_Fault_NullFault, 0, 0, 1); seL4_SetMR(0, 0); api_reply(env->reply.cptr, info); break; default: ZF_LOGF("Invalid time request"); break; } } /* This function waits on: * Timer interrupts (from hardware) * Requests from tests (sel4driver acts as a server) * Results from sel4test/tests */ static int sel4test_driver_wait(driver_env_t env, struct testcase *test) { seL4_MessageInfo_t info; sel4test_output_t test_output; int result = SUCCESS; seL4_Word badge = 0; sel4rpc_server_env_t rpc_server; // siagraw: we start and rpc server to listen for requests form the test binary. sel4rpc_server_init(&rpc_server, &env->vka, sel4rpc_default_handler, env, &env->reply, &env->simple); while (1) { /* wait for tests to finish or fault, receive test request or report result */ info = api_recv(env->test_process.fault_endpoint.cptr, &badge, env->reply.cptr); test_output = seL4_GetMR(0); /* FIXME: Assumptions made at the time of writing this code: * 1) fault sync EP cap has a badge of 0 * 2) notification_cap bound to sel4test-driver TCB, and has a non zero badge. * 3) sel4test-driver only sets up and expects timer interrupts. If, in the * future, other types of interrupts are to be handled, the following code would * be wrong, and would need refactoring. * * For now, assume it is a timer interrupt, handle it and signal any test processes * that might be waiting on it. */ if (badge != 0) { assert(config_set(CONFIG_HAVE_TIMER)); } if (config_set(CONFIG_HAVE_TIMER) && badge != 0) { /* handle timer interrupts in hardware */ handle_timer_interrupts(env, badge); /* Driver does extra work to check whether timeout succeeded and signals * clients/tests */ int error = tm_update(&env->tm); ZF_LOGF_IF(error, "Failed to update time manager"); continue; } if (sel4test_isTimerRPC(test_output)) { if (config_set(CONFIG_HAVE_TIMER)) { handle_timer_requests(env, test_output); continue; } else { ZF_LOGF("Requesting a timer service from sel4test-driver while there is no" "supported HW timer."); } } else if (test_output == SEL4TEST_PROTOBUF_RPC) { sel4rpc_server_recv(&rpc_server); continue; } result = test_output; if (seL4_MessageInfo_get_label(info) != seL4_Fault_NullFault) { sel4utils_print_fault_message(info, test->name); printf("Register of root thread in test (may not be the thread that faulted)\n"); sel4debug_dump_registers(env->test_process.thread.tcb.cptr); result = FAILURE; } if (config_set(CONFIG_HAVE_TIMER)) { timer_cleanup(env); } return result; } } void basic_set_up(uintptr_t e) { int error; driver_env_t env = (driver_env_t)e; sel4utils_process_config_t config = process_config_default_simple(&env->simple, TESTS_APP, env->init->priority); config = process_config_mcp(config, seL4_MaxPrio); config = process_config_auth(config, simple_get_tcb(&env->simple)); config = process_config_create_cnode(config, TEST_PROCESS_CSPACE_SIZE_BITS); error = sel4utils_configure_process_custom(&(env->test_process), &env->vka, &env->vspace, config); assert(error == 0); /* set up caps about the process */ env->init->stack_pages = CONFIG_SEL4UTILS_STACK_SIZE / PAGE_SIZE_4K; env->init->stack = env->test_process.thread.stack_top - CONFIG_SEL4UTILS_STACK_SIZE; env->init->page_directory = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, env->test_process.pd.cptr); env->init->root_cnode = SEL4UTILS_CNODE_SLOT; env->init->tcb = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, env->test_process.thread.tcb.cptr); if (config_set(CONFIG_HAVE_TIMER)) { env->init->timer_ntfn = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, env->timer_notify_test.cptr); } env->init->domain = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, simple_get_init_cap(&env->simple, seL4_CapDomain)); env->init->asid_pool = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, simple_get_init_cap(&env->simple, seL4_CapInitThreadASIDPool)); env->init->asid_ctrl = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, simple_get_init_cap(&env->simple, seL4_CapASIDControl)); #ifdef CONFIG_IOMMU env->init->io_space = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, simple_get_init_cap(&env->simple, seL4_CapIOSpace)); #endif /* CONFIG_IOMMU */ #ifdef CONFIG_TK1_SMMU env->init->io_space_caps = arch_copy_iospace_caps_to_process(&(env->test_process), &env); #endif env->init->cores = simple_get_core_count(&env->simple); /* copy the sched ctrl caps to the remote process */ if (config_set(CONFIG_KERNEL_MCS)) { seL4_CPtr sched_ctrl = simple_get_sched_ctrl(&env->simple, 0); env->init->sched_ctrl = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, sched_ctrl); for (int i = 1; i < env->init->cores; i++) { sched_ctrl = simple_get_sched_ctrl(&env->simple, i); sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, sched_ctrl); } } /* setup data about untypeds */ env->init->untypeds = copy_untypeds_to_process(&(env->test_process), env->untypeds, env->num_untypeds, env); /* copy the fault endpoint - we wait on the endpoint for a message * or a fault to see when the test finishes */ env->endpoint = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, env->test_process.fault_endpoint.cptr); /* copy the device frame, if any */ if (env->init->device_frame_cap) { env->init->device_frame_cap = sel4utils_copy_cap_to_process(&(env->test_process), &env->vka, env->device_obj.cptr); } /* map the cap into remote vspace */ env->remote_vaddr = vspace_share_mem(&env->vspace, &(env->test_process).vspace, env->init, 1, PAGE_BITS_4K, seL4_AllRights, 1); printf("Driver page is mapped at in test VSpace at %p\n", env->remote_vaddr); assert(env->remote_vaddr != 0); /* WARNING: DO NOT COPY MORE CAPS TO THE PROCESS BEYOND THIS POINT, * AS THE SLOTS WILL BE CONSIDERED FREE AND OVERRIDDEN BY THE TEST PROCESS. */ /* set up free slot range */ env->init->cspace_size_bits = TEST_PROCESS_CSPACE_SIZE_BITS; if (env->init->device_frame_cap) { env->init->free_slots.start = env->init->device_frame_cap + 1; } else { env->init->free_slots.start = env->endpoint + 1; } env->init->free_slots.end = (1u << TEST_PROCESS_CSPACE_SIZE_BITS); assert(env->init->free_slots.start < env->init->free_slots.end); } test_result_t basic_run_test(struct testcase *test, uintptr_t e) { int error; driver_env_t env = (driver_env_t)e; /* copy test name */ strncpy(env->init->name, test->name, TEST_NAME_MAX); /* ensure string is null terminated */ env->init->name[TEST_NAME_MAX - 1] = '\0'; #ifdef CONFIG_DEBUG_BUILD seL4_DebugNameThread(env->test_process.thread.tcb.cptr, env->init->name); #endif /* set up args for the test process */ seL4_Word argc = 2; char string_args[argc][WORD_STRING_SIZE]; char *argv[argc]; sel4utils_create_word_args(string_args, argv, argc, env->endpoint, env->remote_vaddr); /* spawn the process */ error = sel4utils_spawn_process_v(&(env->test_process), &env->vka, &env->vspace, argc, argv, 1); ZF_LOGF_IF(error != 0, "Failed to start test process!"); if (config_set(CONFIG_HAVE_TIMER)) { error = tm_alloc_id_at(&env->tm, TIMER_ID); ZF_LOGF_IF(error != 0, "Failed to alloc time id %d", TIMER_ID); } int num_res = sel4utils_walk_vspace(&env->test_process.vspace, &env->vka); printf("\twalker found %d reservations stack addr is %p\n", num_res, &num_res); /* wait on it to finish or fault, report result */ int result = sel4test_driver_wait(env, test); test_assert(result == SUCCESS); return result; } void basic_tear_down(uintptr_t e) { driver_env_t env = (driver_env_t)e; /* unmap the env->init data frame */ vspace_unmap_pages(&(env->test_process).vspace, env->remote_vaddr, 1, PAGE_BITS_4K, NULL); /* reset all the untypeds for the next test */ for (int i = 0; i < env->num_untypeds; i++) { cspacepath_t path; vka_cspace_make_path(&env->vka, env->untypeds[i].cptr, &path); vka_cnode_revoke(&path); } /* destroy the process */ sel4utils_destroy_process(&(env->test_process), &env->vka); } DEFINE_TEST_TYPE(BASIC, BASIC, NULL, NULL, basic_set_up, basic_tear_down, basic_run_test);
300474.c
#include <emscripten.h> // For emscripten_get_device_pixel_ratio() #include <emscripten/html5.h> // For Emscripten HTML5 WebGL context creation API #include <webgl/webgl1.h> // For Emscripten WebGL API headers (see also webgl/webgl1_ext.h and webgl/webgl2.h) #include <string.h> // For NULL and strcmp() #include <assert.h> // For assert() void upload_unicode_char_to_texture(int unicodeChar, int charSize, int applyShadow); void load_texture_from_url(GLuint texture, const char *url, int *outWidth, int *outHeight); static EMSCRIPTEN_WEBGL_CONTEXT_HANDLE glContext; static GLuint quad, colorPos, matPos, solidColor; static float pixelWidth, pixelHeight; static GLuint compile_shader(GLenum shaderType, const char *src) { GLuint shader = glCreateShader(shaderType); glShaderSource(shader, 1, &src, NULL); glCompileShader(shader); return shader; } static GLuint create_program(GLuint vertexShader, GLuint fragmentShader) { GLuint program = glCreateProgram(); glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); glBindAttribLocation(program, 0, "pos"); glLinkProgram(program); glUseProgram(program); return program; } static GLuint create_texture() { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); return texture; } void init_webgl(int width, int height) { double dpr = emscripten_get_device_pixel_ratio(); emscripten_set_element_css_size("canvas", width / dpr, height / dpr); emscripten_set_canvas_element_size("canvas", width, height); EmscriptenWebGLContextAttributes attrs; emscripten_webgl_init_context_attributes(&attrs); attrs.alpha = 0; #if MAX_WEBGL_VERSION >= 2 attrs.majorVersion = 2; #endif glContext = emscripten_webgl_create_context("canvas", &attrs); assert(glContext); emscripten_webgl_make_context_current(glContext); pixelWidth = 2.f / width; pixelHeight = 2.f / height; static const char vertex_shader[] = "attribute vec4 pos;" "varying vec2 uv;" "uniform mat4 mat;" "void main(){" "uv=pos.xy;" "gl_Position=mat*pos;" "}"; GLuint vs = compile_shader(GL_VERTEX_SHADER, vertex_shader); static const char fragment_shader[] = "precision lowp float;" "uniform sampler2D tex;" "varying vec2 uv;" "uniform vec4 color;" "void main(){" "gl_FragColor=color*texture2D(tex,uv);" "}"; GLuint fs = compile_shader(GL_FRAGMENT_SHADER, fragment_shader); GLuint program = create_program(vs, fs); colorPos = glGetUniformLocation(program, "color"); matPos = glGetUniformLocation(program, "mat"); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glGenBuffers(1, &quad); glBindBuffer(GL_ARRAY_BUFFER, quad); const float pos[] = { 0, 0, 1, 0, 0, 1, 1, 1 }; glBufferData(GL_ARRAY_BUFFER, sizeof(pos), pos, GL_STATIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); solidColor = create_texture(); unsigned int whitePixel = 0xFFFFFFFFu; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &whitePixel); } typedef void (*tick_func)(double t, double dt); static EM_BOOL tick(double time, void *userData) { static double t0; double dt = time - t0; t0 = time; tick_func f = (tick_func)(userData); f(time, dt); return EM_TRUE; } void clear_screen(float r, float g, float b, float a) { glClearColor(r, g, b, a); glClear(GL_COLOR_BUFFER_BIT); } static void fill_textured_rectangle(float x0, float y0, float x1, float y1, float r, float g, float b, float a, GLuint texture) { float mat[16] = { (x1-x0)*pixelWidth, 0, 0, 0, 0, (y1-y0)*pixelHeight, 0, 0, 0, 0, 1, 0, x0*pixelWidth-1.f, y0*pixelHeight-1.f, 0, 1}; glUniformMatrix4fv(matPos, 1, 0, mat); glUniform4f(colorPos, r, g, b, a); glBindTexture(GL_TEXTURE_2D, texture); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } void fill_solid_rectangle(float x0, float y0, float x1, float y1, float r, float g, float b, float a) { fill_textured_rectangle(x0, y0, x1, y1, r, g, b, a, solidColor); } typedef struct Texture { // Image char *url; int w, h; GLuint texture; } Texture; #define MAX_TEXTURES 256 static Texture textures[MAX_TEXTURES] = {}; static Texture *find_or_cache_url(const char *url) { for(int i = 0; i < MAX_TEXTURES; ++i) // Naive O(n) lookup for tiny code size if (!strcmp(textures[i].url, url)) return textures+i; else if (!textures[i].url) { textures[i].url = strdup(url); textures[i].texture = create_texture(); load_texture_from_url(textures[i].texture, url, &textures[i].w, &textures[i].h); return textures+i; } return 0; // fail } void fill_image(float x0, float y0, float scale, float r, float g, float b, float a, const char *url) { Texture *t = find_or_cache_url(url); fill_textured_rectangle(x0, y0, x0 + t->w * scale, y0 + t->h * scale, r, g, b, a, t->texture); } typedef struct Glyph { // Font unsigned int ch; int charSize; int shadow; GLuint texture; } Glyph; #define MAX_GLYPHS 256 static Glyph glyphs[MAX_GLYPHS] = {}; static Glyph *find_or_cache_character(unsigned int ch, int charSize, int shadow) { for(int i = 0; i < MAX_TEXTURES; ++i) // Naive O(n) lookup for tiny code size if (glyphs[i].ch == ch && glyphs[i].charSize == charSize && glyphs[i].shadow == shadow) return glyphs+i; else if (!glyphs[i].ch) { glyphs[i].ch = ch; glyphs[i].charSize = charSize; glyphs[i].shadow = shadow; glyphs[i].texture = create_texture(); upload_unicode_char_to_texture(ch, charSize, shadow); return glyphs+i; } return 0; // fail } void fill_char(float x0, float y0, float r, float g, float b, float a, unsigned int ch, int charSize, int shadow) { fill_textured_rectangle(x0, y0, x0+charSize, y0+charSize, r, g, b, a, find_or_cache_character(ch, charSize, shadow)->texture); } void fill_text(float x0, float y0, float r, float g, float b, float a, const char *str, float spacing, int charSize, int shadow) { while(*str) { fill_char(x0, y0, r, g, b, a, *str++, charSize, shadow); x0 += spacing; } }
140626.c
// SPDX-License-Identifier: GPL-2.0+ /* * Copyright (C) 2013-2015 Synopsys, Inc. All rights reserved. */ #include <asm/cache.h> #include <common.h> int init_cache_f_r(void) { sync_n_cleanup_cache_all(); return 0; }
167160.c
/* * Copyright (C) 2020 Vmware * Sarita Patra * * 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; see the file COPYING; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <zebra.h> #include "lib/northbound.h" #include "lib/routemap.h" #include "ospf6_routemap_nb.h" /* clang-format off */ const struct frr_yang_module_info frr_ospf_route_map_info = { .name = "frr-ospf-route-map", .nodes = { { .xpath = "/frr-route-map:lib/route-map/entry/set-action/rmap-set-action/frr-ospf-route-map:metric-type", .cbs = { .modify = lib_route_map_entry_set_action_rmap_set_action_metric_type_modify, .destroy = lib_route_map_entry_set_action_rmap_set_action_metric_type_destroy, } }, { .xpath = NULL, }, } }; const struct frr_yang_module_info frr_ospf6_route_map_info = { .name = "frr-ospf6-route-map", .nodes = { { .xpath = "/frr-route-map:lib/route-map/entry/set-action/rmap-set-action/frr-ospf6-route-map:ipv6-address", .cbs = { .modify = lib_route_map_entry_set_action_rmap_set_action_ipv6_address_modify, .destroy = lib_route_map_entry_set_action_rmap_set_action_ipv6_address_destroy, } }, { .xpath = NULL, }, } };
206417.c
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.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.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * [email protected] */ /*! \file message_queue.c * \brief this is the implementation of a message queue * \author Cedric Roux * \date November 2015 * \version 1.0 * \email: [email protected] * @ingroup _mac */ #include "message_queue.h" #include "log.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> message_queue_t *new_message_queue(void) { message_queue_t *ret = NULL; ret = calloc(1, sizeof(message_queue_t)); if (ret == NULL) goto error; ret->mutex = calloc(1, sizeof(pthread_mutex_t)); if (ret->mutex == NULL) goto error; if (pthread_mutex_init(ret->mutex, NULL)) goto error; ret->cond = calloc(1, sizeof(pthread_cond_t)); if (ret->cond == NULL) goto error; if (pthread_cond_init(ret->cond, NULL)) goto error; return ret; error: LOG_E(MAC, "%s: an error occured\n", __FUNCTION__); if (ret != NULL) { free(ret->mutex); free(ret->cond); memset(ret, 0, sizeof(message_queue_t)); free(ret); } return NULL; } int message_put(message_queue_t *queue, void *data, int size, int priority) { message_t *m = NULL; m = calloc(1, sizeof(message_t)); if (m == NULL) goto error; m->data = data; m->size = size; m->priority = priority; m->next = NULL; if (pthread_mutex_lock(queue->mutex)) goto error; if (queue->count == 0) queue->head = m; else queue->tail->next = m; queue->tail = m; queue->count++; if (pthread_cond_signal(queue->cond)) { LOG_E(MAC, "%s:%d:%s: fatal error\n", __FILE__, __LINE__, __FUNCTION__); pthread_mutex_unlock(queue->mutex); exit(1); } if (pthread_mutex_unlock(queue->mutex)) { LOG_E(MAC, "%s:%d:%s: fatal error\n", __FILE__, __LINE__, __FUNCTION__); exit(1); } return 0; error: free(m); LOG_E(MAC, "%s: an error occured\n", __FUNCTION__); return -1; } int message_get(message_queue_t *queue, void **data, int *size, int *priority) { message_t *m; if (pthread_mutex_lock(queue->mutex)) goto error; while (queue->count == 0) { if (pthread_cond_wait(queue->cond, queue->mutex)) { pthread_mutex_unlock(queue->mutex); goto error; } } m = queue->head; queue->head = queue->head->next; if (queue->head == NULL) queue->tail = NULL; queue->count--; if (pthread_mutex_unlock(queue->mutex)) goto error; *data = m->data; *size = m->size; *priority = m->priority; free(m); return 0; error: LOG_E(MAC, "%s: an error occured\n", __FUNCTION__); return -1; } /* when calling this function, the queue must not be used anymore (we don't lock it) */ /* we suppose that the data pointer in messages was allocated by malloc/calloc/realloc */ void destroy_message_queue(message_queue_t *queue) { while (queue->head) { message_t *m = queue->head; queue->head = queue->head->next; free(m->data); memset(m, 0, sizeof(message_t)); free(m); } free(queue->mutex); free(queue->cond); memset(queue, 0, sizeof(message_queue_t)); free(queue); } #ifdef TEST /* some very basic tests */ int main(void) { void *data; int size; int priority; message_queue_t *q; char *s; q = new_message_queue(); if (q == NULL) goto error; if (message_put(q, "hello", 6, 0)) goto error; if (message_put(q, "world", 6, 1)) goto error; if (message_get(q, &data, &size, &priority)) goto error; printf("message:\n data: '%s'\n size: %d\n priority: %d\n", (char *)data, size, priority); if (message_get(q, &data, &size, &priority)) goto error; printf("message:\n data: '%s'\n size: %d\n priority: %d\n", (char *)data, size, priority); /* let's put a message before destroying the queue */ s = malloc(10); if (s == NULL) goto error; sprintf(s, "hello"); if (message_put(q, s, 6, 0)) goto error; destroy_message_queue(q); return 0; error: printf("error\n"); return 1; } #endif
814860.c
sv1 = sv1_q1; ss1 = ss1_q1; sv2 = sv2_q1; ss2 = ss2_q1; sv3 = sv3_q2; ss3 = ss3_q2; sv4 = sv4_q2; ss4 = ss4_q2; w.resize(10000,0.); if(isud){FCtr = 4.*2.;} if(!isud){FCtr = 4.*2.;} if(quark_1.getMass() == 0.0037){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_0037_0037(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0037(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0037(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_0037_0037(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0037(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0037(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.0200){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_0200_0200(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0200(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0200(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_0200_0200(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0200(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0200(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.0500){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_0500_0500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0500(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_0500_0500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0500(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.0855){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_0855_0855(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0855(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0855(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_0855_0855(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0855(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_0855(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.1500){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_1500_1500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_1500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_1500(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_1500_1500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_1500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_1500(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.2100){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_2100_2100(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_2100(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_2100(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_2100_2100(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_2100(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_2100(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.3500){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_3500_3500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_3500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_3500(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_3500_3500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_3500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_3500(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.5000){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_5000_5000(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_5000(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_5000(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_5000_5000(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_5000(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_5000(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.6500){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_6500_6500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_6500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_6500(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_6500_6500(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_6500(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_6500(0,std::real(l_l+q_l+0.25*q_q))); } else if(quark_1.getMass() == 0.7950){ ampl = 0.5*( ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_7950(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_7950(0,std::real(l_l+q_l+0.25*q_q))+ ns_data_v2::amplitudes::diquark::axialvector::fit::m_7950_7950(0,std::real(l_l+p_l+0.25*p_p)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_7950(0,std::real(l_l+2.*p_l+q_l+p_p+p_q+0.25*q_q)) *ns_data_v2::amplitudes::diquark::scalar::fit::m_7950_7950(0,std::real(l_l+p_l+2.*q_l+0.25*p_p+p_q+q_q)) *ns_data_v2::amplitudes::meson::vector::fit::m_7950_7950(0,std::real(l_l+q_l+0.25*q_q))); } w[1]=1./(-Q_Q*Q_p*p_p+pow(Q_p,3)); w[2]=Q_Q; w[3]=Q_p; w[4]=Q_q; w[5]=p_q; w[6]=q_q; w[7]=q_l; w[8]=p_p; w[9]=p_l; w[10]=Q_l; w[11]=l_l; w[12]=1./(Q_Q*pow(p_p,2)-pow(Q_p,2)*p_p); w[13]=pow(p_p,-1); w[14]=1./(3.E+0*Q_Q*pow(p_p,3)-3.E+0*pow(Q_p,2)*pow(p_p,2)); w[15]=ss3*sv4*sv2; w[16]=i_*ampl; w[17]=w[16]*sv1; w[18]=w[17]*PM12m; w[19]=w[18]*w[15]; w[20]=ss4*sv3*sv2; w[21]=w[18]*w[20]; w[22]=w[19]-w[21]; w[23]=ss1*sv2; w[24]=sv3*sv4; w[25]=w[23]*w[24]*w[16]; w[24]=w[24]*ss2; w[26]=w[24]*w[17]; w[27]=w[26]-w[25]; w[28]=w[27]*PM12m; w[29]=w[22]-w[28]; w[30]=w[29]*w[6]; w[31]=w[29]*w[7]; w[32]=w[30]+w[31]; w[32]=w[32]*w[9]; w[33]=w[25]*PM12m; w[34]=w[33]-w[21]; w[35]=w[34]*w[11]; w[36]=w[16]*PM12m; w[23]=ss3*w[23]*w[36]; w[37]=sv3*ss2; w[36]=w[36]*ss1; w[38]=w[37]*w[36]; w[23]=w[23]-w[38]; w[23]=w[23]*ss4; w[35]=w[35]+w[23]; w[39]=2.E+0*w[33]; w[40]=w[39]*w[7]; w[41]=w[33]*w[6]; w[40]=w[41]+w[40]+w[35]; w[42]=w[40]*w[5]; w[43]=w[29]*w[11]; w[44]=ss2*ss3*sv4; w[36]=w[36]*w[44]; w[43]=w[43]+w[36]; w[45]=w[17]*ss2; w[16]=w[16]*ss1; w[46]=w[16]*sv2; w[47]=w[45]-w[46]; w[48]=ss3*PM12m; w[49]=w[47]*w[48]; w[49]=w[49]+w[38]; w[49]=w[49]*ss4; w[50]=w[28]*w[6]; w[51]=w[49]-w[43]+w[50]; w[52]=2.E+0*PM12m; w[53]=w[52]*w[27]; w[54]=w[53]*w[7]; w[55]=-w[54]-w[51]; w[56]=w[55]*w[7]; w[57]=w[22]*w[11]; w[58]=w[38]*ss4; w[59]=w[58]-w[36]; w[57]=w[57]-w[59]; w[60]=w[57]*w[6]; w[56]=w[60]+w[56]; w[60]=w[34]*w[7]; w[60]=w[60]+w[41]; w[61]=w[60]*w[8]; w[62]=w[56]+w[61]; w[32]=w[32]+w[42]+w[62]; w[42]=-w[28]-3.E+0*w[22]; w[63]=w[42]*w[7]; w[64]=w[22]*w[6]; w[63]=w[63]-w[64]; w[65]=5.E-1*w[26]; w[66]=w[65]+w[25]; w[66]=w[66]*PM12m; w[67]=5.E-1*w[19]; w[68]=w[67]-w[21]; w[66]=w[66]-w[68]; w[69]=w[66]*w[5]; w[63]=w[69]+5.E-1*w[63]; w[63]=w[63]*w[2]; w[69]=w[19]+w[21]; w[70]=w[26]+w[25]; w[71]=w[70]*PM12m; w[72]=w[69]-w[71]; w[73]=w[72]*w[7]; w[74]=w[71]*w[6]; w[75]=w[73]-w[74]; w[76]=2.E+0*w[75]; w[77]=w[72]*w[9]; w[78]=2.E+0*w[21]; w[79]=w[78]*w[5]; w[80]=-w[77]+w[76]+w[79]; w[81]=2.E+0*w[4]; w[80]=w[80]*w[81]; w[82]=w[72]*w[5]; w[76]=w[76]+w[82]; w[83]=2.E+0*w[10]; w[76]=w[76]*w[83]; w[32]=-w[63]-8.E+0*w[32]+w[80]+w[76]; w[63]=PM11p*w[4]; w[32]=w[32]*w[63]; w[76]=w[22]-w[71]; w[80]=w[76]*w[6]; w[84]=w[80]+w[73]; w[85]=w[63]*w[3]; w[86]=2.E+0*w[85]; w[84]=w[84]*w[86]; w[32]=w[32]+w[84]; w[32]=w[32]*w[3]; w[84]=w[69]-w[28]; w[84]=w[84]*w[7]; w[35]=w[84]+w[35]-w[41]; w[35]=w[35]*w[8]; w[84]=w[34]*w[8]; w[86]=w[49]-w[84]; w[87]=-w[43]+w[86]-w[50]; w[88]=w[29]*w[9]; w[89]=w[54]-w[88]+w[87]; w[89]=w[89]*w[9]; w[90]=w[33]*w[8]; w[91]=w[90]+w[57]; w[92]=w[39]*w[5]; w[93]=w[92]+w[91]; w[94]=2.E+0*w[9]; w[95]=w[34]*w[94]; w[96]=w[95]+w[93]-w[54]; w[96]=w[96]*w[5]; w[35]=-w[35]+w[89]-w[96]; w[89]=w[94]*w[72]; w[96]=w[72]*w[8]; w[52]=w[52]*w[70]; w[97]=w[52]*w[5]; w[98]=w[96]-w[97]; w[89]=w[89]+w[98]; w[99]=w[81]+w[83]; w[99]=w[99]*w[89]; w[100]=w[66]*w[8]; w[101]=5.E-1*w[9]; w[102]=w[101]*w[42]; w[103]=w[22]*w[5]; w[104]=5.E-1*w[103]; w[102]=w[102]-w[104]; w[100]=w[100]+w[102]; w[100]=w[100]*w[2]; w[35]=w[99]-w[100]+8.E+0*w[35]; w[35]=w[35]*w[4]; w[99]=-w[77]+w[92]-w[54]; w[99]=w[99]*w[5]; w[105]=w[39]*w[6]; w[73]=w[105]-w[73]; w[105]=w[73]*w[8]; w[106]=w[53]*w[9]; w[107]=w[106]*w[6]; w[99]=w[99]-w[105]+w[107]; w[108]=4.E+0*w[10]; w[99]=w[99]*w[108]; w[109]=w[88]*w[5]; w[110]=w[31]*w[8]; w[109]=w[109]-w[110]; w[109]=w[109]*w[2]; w[99]=w[99]-w[109]; w[35]=w[35]-2.E+0*w[99]; w[35]=w[35]*w[63]; w[32]=w[35]-w[32]; w[35]=-w[1]*w[32]; w[99]=w[28]*w[7]; w[87]=4.E+0*w[99]+w[87]; w[109]=w[87]-w[95]; w[109]=w[109]*w[9]; w[110]=w[39]-w[21]; w[110]=w[110]*w[94]; w[93]=w[110]+w[93]; w[111]=w[93]-w[54]; w[111]=w[111]*w[5]; w[105]=w[105]+w[109]-w[111]; w[105]=w[105]*w[5]; w[109]=w[62]*w[8]; w[111]=3.E+0*w[25]; w[112]=w[111]-w[26]; w[112]=w[112]*PM12m; w[112]=w[112]+w[22]; w[113]=w[112]*w[6]; w[114]=2.E+0*w[7]; w[115]=w[114]*w[34]; w[113]=w[115]+w[113]; w[115]=w[113]*w[8]; w[115]=w[115]-w[107]; w[115]=w[115]*w[9]; w[105]=w[105]+w[115]+w[109]; w[109]=w[52]-w[69]; w[115]=w[109]*w[94]; w[98]=w[115]-w[98]; w[98]=w[98]*w[5]; w[116]=w[52]*w[7]; w[116]=w[116]+w[74]; w[117]=w[69]+w[71]; w[118]=w[117]*w[11]; w[45]=w[45]+w[46]; w[46]=w[45]*w[48]; w[38]=w[46]+w[38]; w[38]=w[38]*ss4; w[36]=w[38]+w[36]; w[38]=w[118]+w[36]; w[46]=w[33]+w[21]; w[48]=w[46]*w[8]; w[118]=w[38]+w[48]; w[119]=w[118]+w[116]; w[120]=w[119]*w[8]; w[18]=w[18]*w[24]; w[24]=w[18]-w[19]; w[121]=w[24]-w[78]; w[122]=w[121]*w[8]; w[122]=w[122]-w[77]; w[122]=w[122]*w[94]; w[98]=-w[120]+w[122]+w[98]; w[122]=w[117]*w[2]; w[123]=1.25E-1*w[122]; w[124]=w[123]*w[8]; w[98]=w[124]+2.E+0*w[98]; w[124]=w[98]*w[4]; w[105]=-w[124]+8.E+0*w[105]; w[124]=w[103]+w[88]; w[125]=w[124]*w[5]; w[126]=w[64]+w[31]; w[127]=w[8]*w[126]; w[125]=w[127]-w[125]; w[127]=5.E-1*w[2]; w[125]=w[125]*w[127]; w[125]=w[125]-w[105]; w[125]=w[125]*w[63]; w[128]=w[21]*w[9]; w[79]=w[79]+4.E+0*w[128]; w[128]=w[114]*w[69]; w[118]=w[79]-w[74]+w[128]+w[118]; w[128]=w[118]*w[5]; w[129]=w[114]*w[24]; w[129]=w[129]-w[80]; w[130]=w[129]*w[8]; w[131]=w[75]*w[94]; w[128]=w[128]-w[130]+w[131]; w[130]=w[22]+w[28]; w[132]=w[130]*w[9]; w[133]=w[132]-w[48]; w[133]=w[133]*w[4]; w[134]=w[123]*w[5]; w[128]=-w[133]-w[134]+2.E+0*w[128]; w[128]=w[128]*w[63]; w[133]=w[130]*w[7]; w[134]=w[46]*w[5]; w[133]=w[133]-w[134]; w[85]=w[133]*w[85]; w[85]=w[128]+w[85]; w[85]=w[85]*w[3]; w[125]=w[125]+w[85]; w[125]=w[12]*w[125]; w[35]=w[35]+w[125]; w[125]=w[43]-w[58]; w[128]=w[94]*w[29]; w[133]=w[125]+w[128]; w[133]=w[133]*w[5]; w[135]=w[51]-w[128]; w[135]=w[135]*w[9]; w[133]=w[133]-w[135]; w[133]=w[133]*w[5]; w[135]=pow(w[9],2); w[136]=w[135]*w[50]; w[133]=w[133]-w[136]; w[133]=w[133]*w[13]; w[136]=w[114]*w[29]; w[136]=w[136]+w[30]; w[136]=w[136]*w[9]; w[137]=w[34]*w[9]; w[138]=w[33]*w[5]; w[137]=w[137]+w[138]; w[31]=w[137]-w[31]; w[31]=w[31]*w[5]; w[139]=w[51]+w[99]; w[139]=w[139]*w[7]; w[140]=w[125]*w[6]; w[31]=w[133]-w[140]-w[136]+w[31]+w[139]; w[61]=w[61]-w[31]; w[133]=3.333333333E-1*w[5]; w[136]=w[133]*w[76]; w[139]=3.333333333E-1*w[21]; w[140]=w[139]-w[19]; w[141]=w[140]+3.333333333E-1*w[71]; w[142]=w[141]*w[9]; w[136]=w[136]-w[142]; w[142]=w[13]*w[5]; w[136]=w[136]*w[142]; w[141]=w[141]*w[7]; w[80]=w[136]+w[141]-3.333333333E-1*w[80]; w[136]=w[80]*w[127]; w[141]=w[33]-w[19]; w[143]=w[141]*w[9]; w[138]=w[143]+w[138]; w[138]=w[138]*w[142]; w[143]=w[141]*w[7]; w[138]=w[138]-w[143]-w[41]; w[143]=1.333333333E+0*w[10]; w[144]=-w[138]*w[143]; w[61]=w[144]+2.666666666E+0*w[61]+w[136]; w[61]=PM11Lp*w[61]; w[136]=2.E+0*w[25]; w[144]=w[136]-w[26]; w[144]=w[144]*PM12m; w[145]=w[144]-w[22]; w[146]=w[5]*w[9]; w[145]=w[145]*w[146]; w[147]=2.E+0*w[19]; w[148]=w[21]+w[144]-w[147]; w[149]=w[148]*w[135]; w[145]=w[145]+w[149]; w[150]=6.666666666E-1*w[13]; w[145]=w[145]*w[150]; w[151]=w[19]+w[139]+3.333333333E-1*w[28]; w[151]=w[151]*w[11]; w[152]=1.333333333E+0*w[9]; w[153]=w[152]*w[46]; w[151]=w[151]+w[153]+3.333333333E-1*w[36]; w[154]=3.333333333E-1*w[74]; w[155]=w[151]+w[154]; w[156]=3.333333333E-1*w[26]; w[157]=w[156]+w[25]; w[157]=w[157]*PM12m; w[158]=3.333333333E-1*w[19]; w[159]=w[157]-w[158]; w[160]=w[159]+w[139]; w[160]=w[160]*w[5]; w[161]=6.666666666E-1*w[7]; w[162]=w[161]*w[18]; w[145]=w[145]+w[162]+w[160]+w[155]; w[162]=3.333333333E-1*w[48]; w[163]=w[162]+w[145]; w[164]=4.166666666E-2*w[122]; w[165]=3.333333333E-1*w[10]; w[166]=-w[141]*w[165]; w[163]=w[166]+2.E+0*w[163]-w[164]; w[163]=PM11Lp*w[163]; w[166]=w[4]*PM11Lp; w[167]=w[166]*w[71]; w[168]=1.666666666E-1*w[167]; w[163]=w[163]-w[168]; w[163]=w[4]*w[163]; w[61]=w[61]+w[163]; w[61]=w[4]*w[61]; w[163]=w[78]-w[19]; w[169]=w[163]-w[144]; w[170]=6.666666666E-1*w[9]; w[171]=w[169]*w[170]; w[50]=3.333333333E-1*w[50]+w[171]+w[49]-w[43]+1.333333333E+0*w[99]; w[15]=w[17]*w[15]; w[17]=w[17]*w[20]; w[20]=w[15]-w[17]; w[171]=w[20]-w[27]; w[172]=w[171]*w[11]; w[44]=w[16]*w[44]; w[172]=w[172]+w[44]; w[173]=w[27]*w[6]; w[47]=w[47]*ss3; w[16]=w[37]*w[16]; w[37]=w[47]+w[16]; w[37]=w[37]*ss4; w[47]=-w[172]+w[173]+w[37]; w[174]=3.333333333E-1*PM12Lm; w[175]=w[47]*w[174]; w[175]=w[175]-w[50]; w[175]=w[9]*w[175]; w[176]=-w[22]+6.666666666E-1*w[28]; w[176]=w[176]*w[11]; w[156]=w[156]-w[25]; w[156]=w[156]*PM12m; w[158]=w[156]-w[158]; w[177]=6.666666666E-1*w[21]; w[178]=w[177]+w[158]; w[178]=w[178]*w[94]; w[179]=6.666666666E-1*w[5]; w[180]=w[179]*w[33]; w[59]=-w[176]-w[178]-6.666666666E-1*w[99]+w[180]-w[59]; w[176]=w[16]*ss4; w[178]=w[176]-w[172]; w[181]=w[178]*w[174]; w[181]=w[181]+w[59]; w[181]=w[5]*w[181]; w[175]=w[175]+w[181]; w[175]=w[5]*w[175]; w[181]=w[135]*w[174]*w[173]; w[175]=w[181]+w[175]; w[175]=w[13]*w[175]; w[181]=w[174]*w[25]; w[181]=w[181]+w[33]; w[181]=w[181]*w[5]; w[182]=w[17]-w[25]; w[183]=w[182]*w[174]; w[183]=w[183]-w[34]; w[183]=w[183]*w[9]; w[181]=w[181]-w[183]; w[183]=w[20]+w[27]; w[184]=w[183]*w[174]; w[185]=w[158]-w[139]; w[186]=-w[184]-w[185]; w[186]=w[7]*w[186]; w[187]=3.333333333E-1*w[11]; w[169]=w[169]*w[187]; w[23]=w[169]-w[23]; w[169]=-w[23]+3.333333333E-1*w[41]; w[186]=w[169]+w[186]+w[181]; w[186]=w[5]*w[186]; w[188]=w[27]*w[7]; w[172]=w[188]-w[172]; w[37]=w[37]+w[172]; w[173]=w[173]+w[37]; w[173]=w[173]*w[7]; w[188]=w[178]*w[6]; w[173]=w[173]+w[188]; w[188]=w[25]*w[6]; w[189]=w[182]*w[7]; w[188]=w[188]-w[189]; w[189]=-w[8]*w[188]; w[189]=-w[173]+w[189]; w[189]=PM12Lm*w[189]; w[190]=w[183]*PM12Lm; w[191]=w[190]*w[9]; w[192]=w[6]*w[191]; w[189]=w[192]+w[189]; w[175]=w[175]+3.333333333E-1*w[189]+w[186]; w[186]=w[190]-w[72]; w[186]=w[186]*w[133]; w[189]=2.E+0*w[26]; w[192]=w[189]-w[25]; w[193]=w[192]+w[20]; w[193]=w[193]*PM12Lm; w[194]=w[193]-w[72]; w[194]=w[9]*w[194]; w[195]=w[71]*w[5]; w[194]=w[194]+w[195]; w[194]=w[5]*w[194]; w[196]=w[15]-w[25]; w[197]=2.E+0*w[17]; w[189]=w[189]-w[197]; w[198]=w[196]+w[189]; w[199]=w[198]*PM12Lm; w[200]=w[199]*w[135]; w[194]=w[200]+w[194]; w[194]=w[194]*w[150]; w[201]=w[15]-w[27]; w[201]=w[17]+3.333333333E-1*w[201]; w[201]=w[201]*w[11]; w[45]=w[45]*ss3; w[16]=w[45]+w[16]; w[16]=w[16]*ss4; w[16]=w[16]+w[44]; w[16]=w[201]+3.333333333E-1*w[16]; w[44]=w[70]*w[6]; w[45]=w[16]+3.333333333E-1*w[44]; w[201]=w[161]*w[25]; w[201]=w[201]+w[45]; w[201]=w[201]*PM12Lm; w[202]=w[170]*w[190]; w[203]=w[17]+w[25]; w[204]=w[203]*w[174]; w[205]=w[204]*w[8]; w[202]=w[202]-w[205]; w[186]=w[194]+w[186]+w[201]+w[202]; w[194]=w[70]*PM12Lm; w[205]=w[194]*w[4]; w[206]=1.666666666E-1*w[205]; w[207]=w[15]+w[70]; w[208]=w[207]+w[17]; w[209]=w[208]*PM12Lm; w[210]=w[209]*w[2]; w[210]=4.166666666E-2*w[210]; w[211]=w[17]-w[26]; w[212]=w[211]*w[174]; w[213]=-w[10]*w[212]; w[186]=w[206]+w[213]+2.E+0*w[186]-w[210]; w[186]=w[4]*w[186]; w[213]=5.E+0*w[21]; w[214]=5.E+0*w[19]; w[215]=w[28]+w[213]-w[214]; w[215]=3.333333333E-1*w[215]; w[207]=-w[17]+3.333333333E-1*w[207]; w[216]=PM12Lm*w[207]; w[216]=w[215]+w[216]; w[216]=w[9]*w[216]; w[217]=w[20]+w[70]; w[218]=w[217]*w[174]; w[218]=w[218]-w[22]; w[218]=w[5]*w[218]; w[216]=w[216]+w[218]; w[216]=w[216]*w[142]; w[218]=3.333333333E-1*w[6]; w[218]=w[217]*w[218]; w[219]=w[207]*w[7]; w[218]=w[219]+w[218]; w[219]=5.E-1*PM12Lm; w[220]=-w[218]*w[219]; w[221]=w[78]+5.E-1*w[24]; w[222]=w[221]*w[133]; w[216]=5.E-1*w[216]+w[220]+w[222]; w[216]=w[2]*w[216]; w[220]=w[211]*PM12Lm; w[223]=w[220]-w[72]; w[223]=w[223]*w[9]; w[224]=w[26]*PM12Lm; w[224]=w[224]-w[71]; w[224]=w[224]*w[5]; w[223]=w[224]-w[223]; w[223]=w[223]*w[142]; w[224]=w[211]*w[7]; w[225]=w[26]*w[6]; w[224]=w[225]-w[224]; w[224]=w[224]*PM12Lm; w[225]=w[34]*w[5]; w[223]=w[223]-w[224]-w[225]; w[143]=-w[223]*w[143]; w[143]=w[186]+w[143]+8.E+0*w[175]+w[216]; w[143]=w[143]*w[63]; w[175]=w[71]+w[213]+w[214]; w[175]=w[175]*w[187]; w[163]=w[163]+w[71]; w[163]=w[163]*w[179]; w[186]=w[161]*w[117]; w[187]=w[78]+w[33]; w[152]=w[187]*w[152]; w[152]=w[152]+w[175]+w[163]+w[186]+w[154]+w[36]; w[154]=w[20]+w[25]; w[154]=w[154]*w[161]; w[45]=w[154]+w[45]; w[45]=w[45]*PM12Lm; w[154]=-w[45]+w[152]; w[154]=w[5]*w[154]; w[163]=w[198]*w[7]; w[175]=w[192]*w[6]; w[163]=w[175]+w[163]; w[163]=w[163]*PM12Lm; w[175]=-w[170]*w[163]; w[154]=w[175]+w[154]; w[154]=w[13]*w[154]; w[114]=w[114]+w[6]; w[114]=w[114]*w[183]; w[175]=-w[114]*w[174]; w[183]=w[204]+w[46]; w[186]=w[5]*w[183]; w[154]=w[154]+w[175]+w[186]; w[175]=w[208]*w[174]; w[175]=w[175]-w[117]; w[175]=1.25E-1*w[175]; w[186]=w[2]*w[142]*w[175]; w[187]=w[220]+w[130]; w[192]=w[10]*w[13]; w[198]=w[192]*w[133]; w[204]=w[187]*w[198]; w[189]=w[196]-w[189]; w[196]=w[189]*PM12Lm; w[208]=w[9]*w[196]; w[213]=2.E+0*w[5]; w[214]=w[194]*w[213]; w[208]=w[208]-w[214]; w[216]=3.333333333E-1*w[13]; w[224]=w[216]*w[4]; w[208]=w[208]*w[224]; w[154]=w[208]+w[204]+2.E+0*w[154]+w[186]; w[154]=w[154]*w[63]; w[136]=w[136]+w[26]; w[136]=w[136]*PM12m; w[136]=w[136]-w[147]-w[21]; w[186]=w[136]*w[9]; w[186]=w[186]+w[97]; w[186]=w[186]*w[13]; w[186]=w[186]-w[72]; w[186]=w[186]*w[166]; w[179]=w[179]*w[76]; w[18]=w[18]-w[22]; w[18]=w[18]*w[161]; w[18]=w[18]+w[155]-w[179]; w[18]=w[18]*w[5]; w[148]=w[148]*w[7]; w[144]=w[144]*w[6]; w[144]=w[144]+w[148]; w[144]=w[144]*w[170]; w[18]=w[18]+w[144]; w[18]=w[18]*w[13]; w[30]=w[134]+w[30]; w[18]=w[18]+3.333333333E-1*w[30]; w[30]=w[142]*w[164]; w[134]=w[141]*w[198]; w[30]=w[134]-2.E+0*w[18]+w[30]; w[30]=PM11Lp*w[30]; w[30]=w[30]+3.333333333E-1*w[186]; w[30]=w[4]*w[30]; w[134]=3.333333333E-1*w[7]; w[136]=w[136]*w[134]; w[144]=w[133]*w[72]; w[136]=5.E-1*w[74]+w[136]-w[144]; w[136]=w[136]*w[166]; w[148]=w[189]*w[134]; w[44]=-w[148]+5.E-1*w[44]; w[44]=w[44]*PM12Lm; w[148]=w[121]*w[133]; w[148]=w[44]+w[148]; w[148]=w[148]*w[63]; w[148]=-w[136]+w[148]; w[148]=w[3]*w[13]*w[148]; w[30]=w[148]+w[30]+w[154]; w[30]=w[3]*w[30]; w[30]=w[30]+w[61]+w[143]; w[61]=w[37]*PM12Lm; w[43]=w[99]-w[43]; w[99]=w[49]+w[43]; w[99]=-w[128]+2.E+0*w[99]-w[61]; w[99]=w[9]*w[99]; w[143]=w[43]+w[58]; w[148]=w[176]+w[172]; w[154]=w[148]*PM12Lm; w[155]=-w[128]+2.E+0*w[143]-w[154]; w[155]=w[5]*w[155]; w[99]=w[99]+w[155]; w[99]=w[99]*w[216]; w[155]=w[182]*PM12Lm; w[172]=-w[155]+2.E+0*w[34]; w[176]=3.333333333E-1*w[9]; w[172]=w[172]*w[176]; w[176]=w[25]*PM12Lm; w[39]=w[176]+w[39]; w[39]=w[39]*w[133]; w[39]=w[172]+w[39]; w[172]=w[185]*w[7]; w[169]=w[172]-w[169]; w[99]=w[99]+w[169]-w[39]; w[99]=w[13]*w[99]; w[172]=3.333333333E-1*w[25]; w[182]=-3.333333333E-1*w[15]+w[172]+w[211]; w[182]=w[182]*PM12Lm; w[185]=6.666666666E-1*w[72]-w[182]; w[185]=w[185]*w[94]; w[172]=w[172]+w[26]; w[189]=-w[172]-6.666666666E-1*w[15]+1.333333333E+0*w[17]; w[189]=w[189]*PM12Lm; w[198]=-6.666666666E-1*w[109]-w[189]; w[198]=w[5]*w[198]; w[185]=w[185]+w[198]; w[185]=w[13]*w[185]; w[198]=w[190]+w[72]; w[185]=6.666666666E-1*w[198]+w[185]; w[204]=w[83]*w[13]; w[185]=w[185]*w[204]; w[208]=-3.333333333E-1*w[17]+w[172]-w[15]; w[211]=w[208]*w[219]; w[211]=3.333333333E-1*w[29]+w[211]; w[211]=w[9]*w[211]; w[225]=w[70]-5.E-1*w[20]; w[226]=PM12Lm*w[225]; w[226]=w[226]+w[22]; w[226]=w[226]*w[133]; w[211]=w[211]+w[226]; w[211]=w[13]*w[211]; w[65]=w[25]-w[65]; w[65]=PM12m*w[65]; w[65]=w[65]+w[68]; w[65]=3.333333333E-1*w[65]+w[211]; w[68]=w[2]*w[13]; w[65]=w[65]*w[68]; w[211]=2.E+0*w[109]; w[226]=-w[25]+5.E+0*w[26]; w[227]=w[226]-w[197]; w[227]=w[227]*PM12Lm; w[228]=-w[211]+w[227]; w[228]=w[9]*w[228]; w[229]=w[194]-w[52]; w[230]=w[229]*w[213]; w[228]=w[228]+w[230]; w[228]=w[13]*w[228]; w[230]=w[71]-w[19]; w[228]=w[228]-2.E+0*w[230]+w[190]; w[228]=w[4]*w[228]*w[150]; w[65]=w[228]+w[185]+8.E+0*w[99]+w[65]; w[65]=PM11p*w[65]; w[99]=w[55]+w[84]; w[185]=w[99]+w[88]; w[185]=w[185]*w[9]; w[228]=w[88]+w[91]; w[228]=w[228]*w[5]; w[231]=w[40]*w[8]; w[185]=w[231]+w[185]+w[228]; w[100]=w[100]+8.E+0*w[185]; w[100]=w[100]*w[2]; w[111]=w[111]+w[26]; w[111]=w[111]*PM12m; w[111]=w[111]-w[69]; w[111]=w[111]*w[8]; w[185]=w[53]*w[5]; w[111]=w[111]+w[185]-w[106]; w[111]=w[111]*w[108]; w[89]=w[89]*w[2]; w[228]=w[28]*w[9]; w[231]=w[228]-w[90]; w[232]=w[231]*w[4]; w[89]=w[111]+w[89]-8.E+0*w[232]; w[89]=w[89]*w[81]; w[111]=w[84]+w[195]-w[77]; w[111]=w[111]*w[2]; w[232]=w[185]-w[96]; w[233]=w[232]*w[83]; w[111]=w[111]-w[233]; w[111]=w[111]*w[108]; w[89]=-w[89]+w[100]+w[111]; w[89]=w[89]*PM11p; w[100]=w[24]*w[94]; w[111]=w[100]+w[92]; w[233]=w[111]-w[99]; w[234]=w[42]*w[127]; w[235]=w[108]*w[72]; w[233]=-8.E+0*w[233]+w[234]-w[235]; w[233]=w[233]*w[10]; w[111]=w[111]-w[91]; w[109]=w[109]*w[108]; w[234]=4.E+0*w[4]; w[236]=w[234]*w[71]; w[237]=w[127]*w[22]; w[109]=-8.E+0*w[111]+w[109]+w[236]-w[237]; w[109]=w[109]*w[4]; w[111]=w[76]*w[5]; w[100]=w[111]-w[100]; w[111]=2.E+0*w[2]; w[100]=w[100]*w[111]; w[100]=w[100]+w[233]+w[109]; w[100]=w[100]*PM11p; w[66]=w[66]*w[2]; w[109]=w[230]*w[234]; w[40]=-w[235]+8.E+0*w[40]+w[66]+w[109]; w[66]=w[3]*PM11p; w[40]=w[40]*w[66]; w[40]=w[100]+w[40]; w[40]=w[40]*w[3]; w[40]=w[89]-w[40]; w[89]=w[12]*w[40]; w[43]=w[43]-w[128]; w[58]=w[43]+w[58]; w[58]=w[58]*w[5]; w[49]=w[43]+w[49]; w[100]=w[49]*w[9]; w[58]=w[58]+w[100]; w[58]=w[58]*w[13]; w[58]=w[58]-w[137]; w[58]=2.666666666E+0*w[58]; w[100]=-w[13]*w[58]; w[67]=-5.E-1*w[21]+w[67]+w[71]; w[67]=w[67]*w[133]; w[109]=w[159]-w[21]; w[109]=w[109]*w[101]; w[67]=w[67]+w[109]; w[67]=w[67]*w[13]; w[109]=3.333333333E-1*w[72]; w[67]=w[67]-w[109]; w[137]=-w[67]*w[68]; w[159]=-1.333333333E+0*w[19]+w[177]+w[157]; w[159]=w[159]*w[5]; w[140]=w[140]-w[156]; w[140]=w[140]*w[94]; w[140]=w[159]+w[140]; w[156]=pow(w[13],2); w[159]=w[140]*w[156]*w[83]; w[100]=w[159]+w[100]+w[137]; w[100]=PM11Lp*w[100]; w[137]=w[147]+w[28]; w[137]=w[137]*w[134]; w[137]=w[137]+w[151]; w[151]=-w[179]+w[137]; w[151]=w[151]*w[13]; w[159]=3.333333333E-1*w[46]; w[151]=w[151]+w[159]; w[177]=2.E+0*w[13]; w[233]=w[151]*w[177]; w[235]=-w[156]*w[164]; w[236]=w[156]*w[72]; w[238]=-w[165]*w[236]; w[233]=w[238]+w[233]+w[235]; w[233]=PM11Lp*w[233]; w[153]=w[179]-w[153]; w[179]=w[197]-w[27]; w[179]=w[179]*w[134]; w[16]=w[179]+w[16]; w[16]=w[16]*PM12Lm; w[179]=2.E+0*w[11]; w[197]=-w[7]-w[179]; w[197]=w[69]*w[197]; w[197]=-w[36]+w[197]; w[197]=6.666666666E-1*w[197]+w[16]+w[153]; w[197]=w[13]*w[197]; w[235]=2.E+0*w[46]; w[203]=w[203]*PM12Lm; w[238]=w[235]+w[203]; w[197]=-3.333333333E-1*w[238]+w[197]; w[197]=w[197]*w[177]; w[239]=-w[117]+5.E-1*w[209]; w[240]=8.333333333E-2*w[2]; w[239]=w[239]*w[240]; w[240]=-w[70]+w[15]+w[17]; w[241]=w[10]*w[240]; w[70]=w[70]*w[4]; w[241]=-w[70]+w[241]; w[241]=w[174]*w[241]; w[241]=-w[239]+w[241]; w[241]=w[156]*w[241]; w[197]=w[197]+w[241]; w[197]=PM11p*w[197]; w[241]=3.333333333E-1*w[3]; w[242]=-PM11Lp+PM11p; w[236]=w[241]*w[236]*w[242]; w[242]=w[156]*w[167]; w[197]=w[236]+w[197]+w[233]+3.333333333E-1*w[242]; w[197]=w[3]*w[197]; w[25]=-w[26]+5.E+0*w[25]; w[25]=w[25]*PM12m; w[26]=w[25]-w[147]; w[26]=w[26]*w[9]; w[26]=w[26]+w[97]; w[26]=w[26]*w[13]; w[26]=w[26]+w[29]; w[26]=w[26]*w[166]; w[147]=w[150]*w[26]; w[65]=w[89]+w[197]+w[65]+w[100]+w[147]; w[65]=w[3]*w[65]; w[89]=w[199]+w[72]; w[89]=w[89]*w[135]; w[15]=-w[226]-2.E+0*w[15]+4.E+0*w[17]; w[15]=w[15]*PM12Lm; w[100]=w[211]+w[15]; w[100]=w[9]*w[100]; w[147]=-w[5]*w[229]; w[100]=w[100]+w[147]; w[100]=w[5]*w[100]; w[100]=-2.E+0*w[89]+w[100]; w[100]=w[100]*w[216]; w[38]=w[38]+w[116]; w[116]=w[121]-w[190]; w[116]=w[116]*w[170]; w[38]=-w[116]+3.333333333E-1*w[38]; w[116]=-w[198]*w[133]; w[100]=w[100]+w[116]-w[16]-w[38]; w[100]=w[13]*w[100]; w[116]=w[203]-w[46]; w[116]=3.333333333E-1*w[116]; w[100]=w[116]+w[100]; w[147]=w[209]+w[117]; w[166]=4.166666666E-2*w[68]; w[147]=w[147]*w[166]; w[100]=2.E+0*w[100]+w[147]; w[100]=w[2]*w[100]; w[166]=w[5]*w[198]; w[27]=w[27]*PM12Lm; w[53]=w[27]-w[53]; w[197]=w[5]+w[9]; w[197]=w[197]*w[142]; w[199]=w[53]*w[197]; w[55]=w[199]+w[166]-w[95]+w[61]-w[55]; w[55]=w[13]*w[55]; w[55]=w[55]-w[155]-w[34]; w[166]=w[171]*PM12Lm; w[171]=w[166]+w[29]; w[199]=w[127]*w[13]; w[171]=w[171]*w[199]; w[203]=w[220]*w[108]; w[209]=w[13]*w[203]; w[55]=w[209]+8.E+0*w[55]+w[171]; w[55]=w[55]*w[165]; w[57]=w[154]-w[57]; w[139]=-w[184]+w[158]+w[139]; w[158]=w[9]*w[139]; w[171]=w[146]+w[135]; w[209]=-w[216]*w[53]*w[171]; w[57]=w[209]-w[180]+3.333333333E-1*w[57]+w[158]; w[57]=w[13]*w[57]; w[158]=-w[33]+w[176]; w[57]=3.333333333E-1*w[158]+w[57]; w[20]=w[20]*PM12Lm; w[158]=w[20]+w[22]; w[158]=w[158]*w[68]; w[17]=-w[172]+6.666666666E-1*w[17]; w[17]=w[17]*PM12Lm; w[172]=w[204]*w[17]; w[180]=-w[150]*w[205]; w[57]=w[180]+w[172]+8.E+0*w[57]+1.666666666E-1*w[158]; w[57]=w[4]*w[57]; w[55]=w[57]+w[100]+w[55]; w[55]=PM11p*w[55]; w[57]=w[112]*w[8]; w[57]=w[57]-w[106]; w[57]=w[57]*w[9]; w[100]=w[91]*w[8]; w[158]=w[231]*w[213]; w[57]=w[57]+w[100]-w[158]; w[100]=w[237]*w[8]; w[57]=-w[100]+8.E+0*w[57]; w[57]=w[57]*w[4]; w[100]=-9.E+0*w[21]+w[230]; w[100]=w[8]*w[100]; w[100]=w[97]+w[100]+w[115]; w[100]=w[5]*w[100]; w[21]=-1.E+1*w[21]+w[24]; w[21]=w[8]*w[21]; w[21]=w[21]-w[77]; w[21]=w[21]*w[94]; w[21]=w[100]-5.E+0*w[120]+w[21]; w[100]=w[8]*w[122]; w[21]=2.E+0*w[21]+6.25E-1*w[100]; w[21]=w[2]*w[21]; w[100]=w[99]*w[8]; w[84]=w[84]*w[94]; w[100]=w[100]+w[84]; w[120]=w[232]+w[106]; w[120]=w[120]*w[5]; w[120]=w[120]+w[100]; w[120]=8.E+0*w[120]; w[122]=-9.E+0*w[28]-7.E+0*w[22]; w[158]=w[122]*w[127]*w[8]; w[158]=-w[120]+w[158]; w[158]=w[10]*w[158]; w[21]=-w[57]+w[21]+w[158]; w[21]=PM11p*w[21]; w[158]=w[24]*w[8]; w[77]=-w[158]+w[82]+w[77]; w[77]=w[77]*w[108]; w[82]=w[76]*w[8]; w[52]=w[52]*w[9]; w[82]=-w[82]+w[52]+w[97]; w[82]=w[82]*w[81]; w[95]=w[95]+w[99]; w[99]=w[95]*w[9]; w[93]=w[93]*w[5]; w[93]=w[93]+w[99]; w[77]=8.E+0*w[93]+w[77]-w[82]; w[82]=5.E+0*w[48]+w[102]; w[82]=w[2]*w[82]; w[82]=w[82]+w[77]; w[82]=PM11p*w[82]; w[79]=w[79]+w[119]; w[93]=w[130]*w[10]; w[79]=2.E+0*w[79]+w[93]-w[123]; w[79]=w[79]*PM11p; w[66]=w[66]*w[46]; w[66]=w[79]-w[66]; w[66]=w[66]*w[3]; w[79]=w[82]+w[66]; w[79]=w[3]*w[79]; w[21]=w[21]+w[79]; w[21]=w[3]*w[21]; w[79]=-w[9]*w[100]; w[82]=w[91]+w[110]+w[92]; w[92]=w[5]*w[8]; w[93]=-w[82]*w[92]; w[79]=w[79]+w[93]; w[93]=w[96]*w[9]; w[96]=-w[5]*w[96]; w[99]=pow(w[8],2); w[24]=w[24]*w[99]; w[24]=w[96]+w[24]-w[93]; w[24]=w[10]*w[24]; w[76]=-w[76]*w[99]; w[96]=w[97]*w[8]; w[52]=w[8]*w[52]; w[52]=w[96]+w[76]+w[52]; w[52]=w[52]*w[234]; w[42]=-w[9]*w[42]; w[42]=w[103]+w[42]; w[42]=w[8]*w[42]; w[76]=-w[99]*w[235]; w[42]=w[76]+w[42]; w[42]=w[2]*w[42]; w[24]=w[52]+8.E+0*w[24]+1.6E+1*w[79]+w[42]; w[24]=PM11p*w[2]*w[24]; w[21]=2.E+0*w[24]+w[21]; w[21]=w[3]*w[21]; w[24]=w[99]*w[95]; w[42]=w[185]+w[106]; w[42]=w[8]*w[42]; w[52]=w[99]*w[72]; w[42]=-w[52]+w[42]; w[42]=w[5]*w[42]; w[24]=w[42]+w[24]; w[42]=w[99]*w[2]; w[76]=-w[29]*w[42]; w[24]=1.6E+1*w[24]+w[76]; w[24]=w[24]*w[83]; w[76]=w[91]*w[99]; w[79]=w[112]*w[99]; w[91]=-w[8]*w[106]; w[79]=w[79]+w[91]; w[79]=w[9]*w[79]; w[91]=w[99]*w[33]; w[95]=-w[8]*w[228]; w[91]=w[91]+w[95]; w[91]=w[91]*w[213]; w[76]=w[91]+w[76]+w[79]; w[42]=-w[22]*w[42]; w[42]=1.6E+1*w[76]+w[42]; w[42]=w[42]*w[81]; w[24]=w[42]+w[24]; w[24]=w[2]*w[24]; w[42]=w[115]*w[8]; w[42]=w[96]+w[42]-w[52]; w[42]=w[42]*w[5]; w[52]=w[119]*w[99]; w[76]=w[121]*w[99]; w[76]=w[76]-w[93]; w[76]=w[76]*w[94]; w[42]=-w[52]+w[42]+w[76]; w[52]=w[127]*w[117]; w[76]=w[52]*w[99]; w[42]=w[76]+8.E+0*w[42]; w[76]=-w[42]*pow(w[2],2); w[24]=w[76]+w[24]; w[24]=PM11p*w[24]; w[21]=w[24]+w[21]; w[21]=w[14]*w[21]; w[24]=-4.E+0*w[19]+w[25]+w[78]; w[24]=w[24]*w[9]; w[24]=w[24]+w[195]; w[24]=w[24]*w[5]; w[24]=w[24]+2.E+0*w[149]; w[24]=w[24]*w[216]; w[24]=w[24]+w[160]+w[137]; w[25]=-w[13]*w[24]; w[25]=-w[159]+w[25]; w[76]=w[164]*w[13]; w[25]=2.E+0*w[25]+w[76]; w[25]=w[2]*w[25]; w[78]=w[28]*w[5]; w[78]=w[78]+w[228]; w[78]=w[78]*w[142]; w[79]=w[29]*w[5]; w[78]=w[78]-w[79]; w[49]=w[49]+w[78]; w[49]=w[13]*w[49]; w[49]=w[49]-w[34]; w[29]=w[127]*w[29]; w[79]=w[141]*w[108]; w[79]=w[79]-w[29]; w[81]=-w[13]*w[79]; w[49]=8.E+0*w[49]+w[81]; w[49]=w[49]*w[165]; w[25]=w[25]+w[49]; w[25]=PM11Lp*w[25]; w[28]=w[135]*w[28]; w[49]=w[228]*w[5]; w[28]=w[28]+w[49]; w[28]=w[28]*w[13]; w[28]=w[28]-w[143]+w[88]; w[49]=-w[13]*w[28]; w[49]=-w[33]+w[49]; w[81]=w[13]*w[237]; w[49]=8.E+0*w[49]+w[81]; w[19]=-w[157]+6.666666666E-1*w[19]; w[81]=w[19]*w[204]; w[49]=3.333333333E-1*w[49]+w[81]; w[49]=PM11Lp*w[49]; w[81]=-w[150]*w[167]; w[49]=w[49]+w[81]; w[49]=w[4]*w[49]; w[21]=w[21]+w[55]+w[25]+w[49]+w[65]; w[25]=w[1]*w[40]; w[40]=w[2]*w[98]; w[29]=w[8]*w[29]; w[29]=-w[120]+w[29]; w[29]=w[10]*w[29]; w[29]=-w[57]+w[40]+w[29]; w[29]=PM11p*w[29]; w[40]=w[48]+w[102]; w[40]=w[2]*w[40]; w[40]=w[40]+w[77]; w[40]=PM11p*w[40]; w[40]=w[40]+w[66]; w[40]=w[3]*w[40]; w[29]=w[29]+w[40]; w[29]=w[12]*w[29]; w[25]=w[25]+w[29]; w[29]=w[37]*w[174]; w[29]=w[29]-w[50]; w[29]=w[9]*w[29]; w[37]=w[148]*w[174]; w[37]=w[37]+w[59]; w[37]=w[5]*w[37]; w[29]=w[29]+w[37]; w[29]=w[13]*w[29]; w[29]=w[29]-w[169]+w[181]; w[37]=-2.E+0*w[72]-w[227]; w[37]=w[9]*w[37]; w[40]=w[71]-w[194]; w[40]=w[40]*w[213]; w[37]=w[37]+w[40]; w[37]=w[13]*w[37]; w[37]=w[37]-w[198]; w[37]=w[4]*w[37]; w[40]=-PM12Lm*w[208]; w[40]=w[215]+w[40]; w[40]=w[40]*w[101]; w[49]=-w[225]*w[174]; w[49]=-5.E-1*w[22]+w[49]; w[49]=w[5]*w[49]; w[40]=w[40]+w[49]; w[40]=w[13]*w[40]; w[40]=3.333333333E-1*w[221]+w[40]; w[40]=w[2]*w[40]; w[49]=-w[109]+w[182]; w[49]=w[49]*w[94]; w[50]=6.666666666E-1*w[71]+w[189]; w[50]=w[5]*w[50]; w[49]=w[49]+w[50]; w[49]=w[13]*w[49]; w[50]=-w[190]+w[34]; w[49]=6.666666666E-1*w[50]+w[49]; w[49]=w[49]*w[83]; w[29]=6.666666666E-1*w[37]+w[49]+8.E+0*w[29]+w[40]; w[29]=PM11p*w[29]; w[37]=-w[16]+w[152]; w[37]=w[13]*w[37]; w[37]=w[37]+w[183]; w[40]=-PM12Lm*w[240]; w[40]=w[40]+w[130]; w[49]=w[216]*w[10]; w[40]=w[40]*w[49]; w[50]=w[68]*w[175]; w[55]=w[13]*w[174]*w[70]; w[37]=w[55]+w[40]+2.E+0*w[37]+w[50]; w[37]=PM11p*w[37]; w[40]=w[72]*w[49]; w[40]=w[40]-2.E+0*w[151]+w[76]; w[40]=PM11Lp*w[40]; w[50]=PM11Lp*w[72]; w[55]=PM11p*w[121]; w[50]=w[50]+w[55]; w[50]=w[241]*w[13]*w[50]; w[55]=-w[216]*w[167]; w[37]=w[50]+w[37]+w[40]+w[55]; w[37]=w[3]*w[37]; w[40]=w[2]*w[67]; w[50]=-w[140]*w[204]; w[40]=w[50]+w[58]+w[40]; w[40]=PM11Lp*w[40]; w[26]=w[37]+w[29]+w[40]-6.666666666E-1*w[26]; w[26]=w[3]*w[26]; w[15]=-w[9]*w[15]; w[29]=w[5]*w[194]; w[15]=w[15]+w[29]; w[15]=w[5]*w[15]; w[15]=2.E+0*w[200]+w[15]; w[15]=w[15]*w[216]; w[29]=w[184]*w[5]; w[15]=w[15]+w[29]+w[16]+w[202]; w[15]=2.E+0*w[15]-w[210]; w[15]=w[2]*w[15]; w[16]=-w[5]*w[190]; w[37]=w[8]*w[155]; w[40]=-w[27]*w[197]; w[16]=w[40]+w[16]-w[61]+w[37]; w[37]=-w[127]*w[166]; w[16]=-w[203]+8.E+0*w[16]+w[37]; w[16]=w[16]*w[165]; w[37]=-w[8]*w[176]; w[27]=w[13]*w[27]*w[171]; w[27]=w[27]+w[191]-w[154]+w[37]; w[20]=-w[127]*w[20]; w[20]=8.E+0*w[27]+w[20]; w[17]=-w[83]*w[17]; w[17]=6.666666666E-1*w[205]+3.333333333E-1*w[20]+w[17]; w[17]=w[4]*w[17]; w[15]=w[17]+w[15]+w[16]; w[15]=PM11p*w[15]; w[16]=w[162]+w[24]; w[16]=2.E+0*w[16]-w[164]; w[16]=w[2]*w[16]; w[17]=-w[86]-w[43]-w[78]; w[17]=8.E+0*w[17]+w[79]; w[17]=w[17]*w[165]; w[16]=w[16]+w[17]; w[16]=PM11Lp*w[16]; w[17]=w[90]+w[28]; w[17]=8.E+0*w[17]-w[237]; w[19]=-w[19]*w[83]; w[17]=3.333333333E-1*w[17]+w[19]; w[17]=PM11Lp*w[17]; w[17]=w[17]+6.666666666E-1*w[167]; w[17]=w[4]*w[17]; w[15]=w[26]+w[15]+w[16]+w[17]; w[16]=-w[12]*w[32]; w[17]=PM12Lm*w[114]; w[19]=-w[5]*w[238]; w[17]=w[19]+w[17]-w[129]; w[19]=-w[69]*w[179]; w[20]=-w[7]*w[71]; w[19]=w[20]+w[19]-w[36]-w[74]; w[19]=6.666666666E-1*w[19]+w[45]+w[153]; w[19]=w[5]*w[19]; w[20]=w[163]+w[75]; w[20]=w[20]*w[170]; w[19]=w[20]+w[19]; w[19]=w[13]*w[19]; w[17]=3.333333333E-1*w[17]+w[19]; w[17]=w[17]*w[177]; w[19]=-w[5]*w[239]; w[20]=w[133]*w[10]; w[24]=-w[187]*w[20]; w[19]=w[24]+w[19]; w[19]=w[156]*w[19]; w[24]=-w[196]-w[130]; w[24]=w[9]*w[24]; w[24]=w[24]+w[214]; w[24]=w[13]*w[24]; w[24]=w[24]+w[46]; w[24]=w[24]*w[224]; w[17]=w[24]+w[17]+w[19]; w[17]=w[17]*w[63]; w[18]=w[18]*w[177]; w[19]=-w[5]*w[164]; w[20]=-w[141]*w[20]; w[19]=w[20]+w[19]; w[19]=w[156]*w[19]; w[18]=w[18]+w[19]; w[18]=PM11Lp*w[18]; w[19]=-w[216]*w[186]; w[18]=w[18]+w[19]; w[18]=w[4]*w[18]; w[19]=w[130]*w[134]; w[19]=w[144]+w[19]-w[44]; w[19]=w[19]*w[63]; w[19]=w[136]+w[19]; w[19]=w[3]*w[156]*w[19]; w[16]=w[16]+w[19]+w[18]+w[17]; w[16]=w[3]*w[16]; w[17]=w[13]*w[31]; w[17]=w[17]-w[60]; w[18]=-w[80]*w[199]; w[19]=1.333333333E+0*w[192]; w[20]=w[138]*w[19]; w[17]=w[20]+2.666666666E+0*w[17]+w[18]; w[17]=PM11Lp*w[17]; w[18]=-w[13]*w[145]; w[18]=-w[159]+w[18]; w[20]=w[141]*w[49]; w[18]=w[20]+2.E+0*w[18]+w[76]; w[18]=PM11Lp*w[18]; w[20]=w[13]*w[168]; w[18]=w[18]+w[20]; w[18]=w[4]*w[18]; w[17]=w[17]+w[18]; w[17]=w[4]*w[17]; w[18]=-PM12Lm*w[47]; w[18]=-w[128]+2.E+0*w[51]+w[18]; w[18]=w[9]*w[18]; w[20]=-PM12Lm*w[178]; w[20]=-w[128]-2.E+0*w[125]+w[20]; w[20]=w[5]*w[20]; w[18]=w[18]+w[20]; w[18]=w[5]*w[18]; w[20]=-w[135]*w[6]*w[53]; w[18]=w[20]+w[18]; w[18]=w[18]*w[216]; w[20]=PM12Lm*w[173]; w[20]=w[20]-w[56]; w[24]=w[184]-1.333333333E+0*w[33]; w[24]=w[7]*w[24]; w[23]=-w[41]+w[23]+w[24]-w[39]; w[23]=w[5]*w[23]; w[24]=w[6]*w[139]; w[26]=-w[34]*w[161]; w[24]=w[26]+w[24]; w[24]=w[9]*w[24]; w[18]=w[18]+w[23]+3.333333333E-1*w[20]+w[24]; w[18]=w[13]*w[18]; w[20]=PM12Lm*w[188]; w[20]=w[20]-w[60]; w[18]=3.333333333E-1*w[20]+w[18]; w[20]=w[71]-w[193]; w[20]=w[20]*w[146]; w[20]=-w[89]+w[20]; w[20]=w[20]*w[150]; w[20]=w[20]-w[29]-w[201]-w[38]; w[20]=w[13]*w[20]; w[20]=w[116]+w[20]; w[23]=w[192]*w[212]; w[24]=-w[13]*w[206]; w[20]=w[24]+w[23]+2.E+0*w[20]+w[147]; w[20]=w[4]*w[20]; w[23]=PM12Lm*w[218]; w[23]=3.333333333E-1*w[126]+w[23]; w[24]=-w[207]*w[219]; w[24]=6.666666666E-1*w[22]+w[24]; w[24]=w[9]*w[24]; w[26]=-w[217]*w[219]; w[22]=w[26]+w[22]; w[22]=w[22]*w[133]; w[22]=w[24]+w[22]; w[22]=w[22]*w[142]; w[22]=w[22]+5.E-1*w[23]-w[222]; w[22]=w[22]*w[68]; w[19]=w[223]*w[19]; w[18]=w[20]+w[19]+8.E+0*w[18]+w[22]; w[18]=w[18]*w[63]; w[19]=w[8]*w[87]; w[19]=w[19]-w[84]; w[19]=w[9]*w[19]; w[20]=w[54]-w[82]; w[20]=w[20]*w[92]; w[22]=w[73]*w[99]; w[19]=w[20]+w[22]+w[19]; w[19]=w[5]*w[19]; w[20]=w[62]*w[99]; w[22]=w[113]*w[99]; w[23]=-w[8]*w[107]; w[22]=w[22]+w[23]; w[22]=w[9]*w[22]; w[19]=w[19]+w[20]+w[22]; w[20]=-w[126]*w[99]; w[22]=w[124]*w[92]; w[20]=w[20]+w[22]; w[20]=w[2]*w[20]; w[19]=1.6E+1*w[19]+w[20]; w[19]=w[19]*w[111]; w[20]=-w[4]*w[2]*w[42]; w[19]=w[19]+w[20]; w[19]=w[19]*w[63]; w[20]=-w[104]+4.E+0*w[48]-5.E-1*w[88]; w[20]=w[5]*w[20]; w[22]=w[7]*w[122]; w[22]=w[64]+w[22]; w[22]=w[8]*w[22]; w[20]=5.E-1*w[22]+w[20]; w[20]=w[2]*w[20]; w[20]=w[20]-w[105]; w[20]=w[20]*w[63]; w[20]=w[20]+w[85]; w[20]=w[3]*w[20]; w[22]=-w[118]*w[92]; w[23]=w[129]*w[99]; w[24]=-w[8]*w[131]; w[22]=w[22]+w[23]+w[24]; w[23]=w[52]*w[92]; w[24]=w[8]*w[132]; w[26]=-w[46]*w[99]; w[24]=w[26]+w[24]; w[24]=w[24]*w[234]; w[22]=w[24]+8.E+0*w[22]+w[23]; w[22]=w[63]*w[2]*w[22]; w[20]=w[22]+w[20]; w[20]=w[3]*w[20]; w[19]=w[19]+w[20]; w[19]=w[14]*w[19]; w[16]=w[19]+w[17]+w[18]+w[16]; K31[SI_K31(ip,izp,0,iq,izq,0)] += wj * FCtr * w[16]; K31[SI_K31(ip,izp,0,iq,izq,1)] += wj * FCtr * w[21]; K31[SI_K31(ip,izp,1,iq,izq,0)] += wj * FCtr * w[35]; K31[SI_K31(ip,izp,1,iq,izq,1)] += wj * FCtr * w[25]; K31[SI_K31(ip,izp,2,iq,izq,0)] += wj * FCtr * w[30]; K31[SI_K31(ip,izp,2,iq,izq,1)] += wj * FCtr * w[15];
221351.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <omp.h> #include <math.h> #define min(a,b) (((a)<(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) #define max(a,b) (((a)>(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #define floord(n,d) floor(((double)(n))/((double)(d))) #define ceild(n,d) ceil(((double)(n))/((double)(d))) double ** Q; double ** Qbp; double ** Pbp; double ** Pu; double ** M; int Ebp = 0; // Energy weight of base pair -2, -1, 0, 1, 2 int RT = 1; // 'Normalized' temperature 1,2,3,4,5 float ERT; int l = 0; //minimum loop length 0-5 int delta = 1; // Base pair weighting 1-5 char * RNA; //only ACGU int N; int DIM; #include "../mem.h" int paired(int i, int j) { char nt1 = RNA[i]; char nt2 = RNA[j]; if ((nt1 == 'A' && nt2 == 'U') || (nt1 == 'U' && nt2 == 'A') || (nt1 == 'G' && nt2 == 'C') || (nt1 == 'C' && nt2 == 'G') || (nt1 == 'G' && nt2 == 'U') || (nt1 == 'U' && nt2 == 'G')){ return 1;} else return 0; } int main(int argc, char *argv[]){ int num_proc=1; int i,j,k,ll,p,q; int c0, c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13,c15; int t1, t2, t3, t4, t5, t6,t7; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; ERT = exp((float)-Ebp/(float)RT); srand(time(NULL)); if(argc > 1) num_proc = atoi(argv[1]); int kind=1; N = 8; DIM = 12; if(argc > 2) N = atoi(argv[2]); DIM = N+10; if(argc > 3) kind = atoi(argv[3]); omp_set_num_threads(num_proc); //printf(" -exp(Ebp/RT) = %5.3f\n", ERT); RNA = (char*) malloc(DIM * sizeof(char*)); //read from FASTA file rand_seq(RNA, N); //printf("Sequence: "); //for(i=0; i<N; i++) // printf("%c", RNA[i]); //printf("\n\n"); Q = memd(); Qbp = memd(); Pbp = memd(); Pu = memd(); M = memd(); rna_array_init(Q, 1, 1); rna_array_init(Qbp, 0, 0); rna_array_init(Pbp, 0, 0); rna_array_init(Pu, 0, 0); rna_array_init(M, 0, 0); double start = omp_get_wtime(); // compute the partition functions Q and Qbp if(kind==1){ #pragma scop for(i=0; i<N; i++){ for(j=i+1; j<N; j++){ Pbp[i][j] = (Q[0][i]*Q[j][N-1]*Qbp[i][j])/Q[0][N-1]; // Pbp[i][j] = (Q[1][i]*Q[j+1][N]*Qbp[i][j])/Q[0][N-1]; for(p=0; p<i; p++){ for(q=j+1; q<N; q++){ Pbp[i][j] += (Pbp[p][q] * ERT * Q[p+1][i] * Qbp[i][j] * Q[j+1][q-1]) / (Qbp[p][q] ==0 ? 1 : Qbp[p][q]) ; } } } } #pragma endscop } if(kind==2) // pluto { printf("pluto\n"); lbp=0; ubp=floord(N-2,16); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7) for (t2=lbp;t2<=ubp;t2++) { for (t3=t2;t3<=floord(N-1,16);t3++) { for (t4=16*t2;t4<=min(min(N-2,16*t2+15),16*t3+14);t4++) { lbv=max(16*t3,t4+1); ubv=min(N-1,16*t3+15); #pragma ivdep #pragma vector always for (t5=lbv;t5<=ubv;t5++) { Pbp[t4][t5] = (Q[0][t4]*Q[t5][N-1]*Qbp[t4][t5])/Q[0][N-1];; } } } } /* for (t2=0;t2<=floord(N-4,8);t2++) { lbp=max(0,ceild(16*t2-N+3,16)); ubp=floord(t2,2); #pragma omp parallel for private(lbv,ubv,t4,t5,t6,t7) for (t3=lbp;t3<=ubp;t3++) { for (t4=max(16*t2-16*t3,16*t3+1);t4<=min(N-3,16*t2-16*t3+15);t4++) { for (t5=16*t3;t5<=min(16*t3+15,t4-1);t5++) { for (t6=t4+1;t6<=N-2;t6++) { for (t7=t6+1;t7<=N-1;t7++) { Pbp[t4][t6] += (Pbp[t5][t7] * ERT * Q[t5+1][t4] * Qbp[t4][t6] * Q[t6+1][t7-1]) / (Qbp[t5][t7] ==0 ? 1 : Qbp[t5][t7]); } } } } } } */ if (N >= 4) { for (t1=1;t1<=floord(17*N-52,16);t1++) { lbp=max(0,t1-N+3); ubp=floord(t1-1,17); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6) for (t2=lbp;t2<=ubp;t2++) { for (t4=16*t2;t4<=min(16*t2+15,t1-t2-1);t4++) { for (t5=t1-t2+1;t5<=N-2;t5++) { for (t6=t5+1;t6<=N-1;t6++) { Pbp[(t1-t2)][t5] += (Pbp[t4][t6] * ERT * Q[t4+1][(t1-t2)] * Qbp[(t1-t2)][t5] * Q[t5+1][t6-1]) / (Qbp[t4][t6] ==0 ? 1 : Qbp[t4][t6]); } } } } } } } if(kind==3) // traco { printf("traco\n"); lbp=0; ubp=floord(N-2,16); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7) for (t2=lbp;t2<=ubp;t2++) { for (t3=t2;t3<=floord(N-1,16);t3++) { for (t4=16*t2;t4<=min(min(N-2,16*t2+15),16*t3+14);t4++) { lbv=max(16*t3,t4+1); ubv=min(N-1,16*t3+15); #pragma ivdep #pragma vector always for (t5=lbv;t5<=ubv;t5++) { Pbp[t4][t5] = (Q[0][t4]*Q[t5][N-1]*Qbp[t4][t5])/Q[0][N-1];; } } } } for( c1 = 1; c1 < N - 2; c1 += 1) #pragma omp parallel for schedule(dynamic, 1) for( c3 = 0; c3 <= (N - c1 - 3) / 16; c3 += 1) for( c5 = 0; c5 <= (c1 - 1) / 16; c5 += 1) for( c7 = 0; c7 <= -c3 + (N - c1 - 3) / 16; c7 += 1) for( c11 = c1 + 16 * c3 + 1; c11 <= min(c1 + 16 * c3 + 16, N - 16 * c7 - 2); c11 += 1) { if (N >= 16 * c7 + c11 + 18) { for( c15 = 16 * c7 + c11 + 1; c15 <= 16 * c7 + c11 + 16; c15 += 1) Pbp[c1][c11] += (Pbp[16*c5][c15] * ERT * Q[16*c5+1][c1] * Qbp[c1][c11] * Q[c11+1][c15-1]) / (Qbp[16*c5][c15] ==0 ? 1 : Qbp[16*c5][c15]) ; } else { for( c13 = 16 * c5; c13 <= min(c1 - 1, 16 * c5 + 15); c13 += 1) { if (c13 >= 16 * c5 + 1) for( c15 = c11 + 1; c15 <= 16 * c7 + c11; c15 += 1) Pbp[c1][c11] += (Pbp[c13][c15] * ERT * Q[c13+1][c1] * Qbp[c1][c11] * Q[c11+1][c15-1]) / (Qbp[c13][c15] ==0 ? 1 : Qbp[c13][c15]) ; for( c15 = 16 * c7 + c11 + 1; c15 < N; c15 += 1) Pbp[c1][c11] += (Pbp[c13][c15] * ERT * Q[c13+1][c1] * Qbp[c1][c11] * Q[c11+1][c15-1]) / (Qbp[c13][c15] ==0 ? 1 : Qbp[c13][c15]) ; } } } } if(kind==4) // traco tstile { } double stop = omp_get_wtime(); printf("%.4f\n",stop - start); //printf("Q\n"); //rna_array_print(Q); //printf("Qbp\n"); //rna_array_print(Qbp); exit(0); printf("Pbp\n"); rna_array_print(Pbp); #pragma scop for(i=N-1; i>=0; i--){ for(j=i+1; j<N; j++){ Pu[i][j] = (Q[0][i]*Q[j][N-1]*1)/Q[0][N-1]; for(p=0; p<i; p++){ for(q=j+1; q<N; q++){ Pu[i][j] += (Pbp[p][q] * ERT * Q[p+1][i] * 1 * Q[j+1][q-1]) / (Qbp[p][q] ==0 ? 1 : Qbp[p][q]) ; } } } } #pragma endscop printf("Pu\n"); rna_array_print(Pu); double * Puu = (double*)malloc(DIM * sizeof(double)); #pragma scop for(i=0; i<=N; i++){ Puu[i] = 1; for(j=i+1; j<N; j++){ Puu[i] += -1 * Pbp[i][j+1]; } for(k=0; k<i; k++){ Puu[i] += -1 * Pbp[k][i+1]; } } #pragma endscop printf("Puu\n"); for(i=0; i<N-1; i++) printf("%3.3f ", Puu[i]); printf("\n"); #pragma scop for(i=N-1; i>=0; i--){ for(j=i+1; j<N; j++){ for(k=0; k<j-i-l; k++){ M[i][j] = MAX(M[i][j], M[i][k+i-1] + M[k+i+1][j-1] + delta*Pbp[k+i][j])*paired(k+i,j-1); } M[i][j] = MAX(M[i][j], M[i][j-1] + Puu[j-1]); } } #pragma endscop printf("M\n"); rna_array_print(M); return 0; }
720884.c
/** * @author zuri * @date mardi 7 janvier 2020, 18:44:43 (UTC+0100) */ #include <zrlib/base/Iterator/FilterIterator.h> #include <assert.h> #include <string.h> // ============================================================================ #define ZRFILTERITERATOR_ITERATOR(FIT) (&(FIT)->iterator) #define ZRFILTERITERATORSIZE(NBFILTERS) (sizeof(ZRFilterIterator) + (sizeof(ZRFilterIterator_fvalidate_t) * NBFILTERS)) typedef struct ZRFilterIteratorS ZRFilterIterator; struct ZRFilterIteratorS { ZRIterator iterator; ZRIteratorStrategy strategyArea; size_t nbFilters; void *data; ZRAllocator *allocator; ZRIterator *subject; unsigned hasNextComputed :2; ZRFilterIterator_fvalidate_t fvalidates[]; }; static bool fhasNext_OR(ZRIterator *iterator) { ZRFilterIterator *const fiterator = (ZRFilterIterator*)iterator; switch (fiterator->hasNextComputed) { // Subject consumed case 0b10: return false; case 1: return true; case 0: { size_t const nbFilters = fiterator->nbFilters; void *const data = fiterator->data; ZRFilterIterator_fvalidate_t *const fvalidates = fiterator->fvalidates; for (;;) { if (!ZRIterator_hasNext(fiterator->subject)) { fiterator->hasNextComputed = 0b10; return false; } ZRIterator_next(fiterator->subject); void *current = ZRIterator_current(fiterator->subject); for (size_t i = 0; i < nbFilters; i++) { if (fvalidates[i](current, data)) { fiterator->hasNextComputed = 1; return true; } } } } } // Normally never happen return false; } static bool fhasNext_AND(ZRIterator *iterator) { ZRFilterIterator *const fiterator = (ZRFilterIterator*)iterator; switch (fiterator->hasNextComputed) { // Subject consumed case 0b10: return false; case 1: return true; case 0: { size_t const nbFilters = fiterator->nbFilters; void *const data = fiterator->data; ZRFilterIterator_fvalidate_t *const fvalidates = fiterator->fvalidates; for (;;) { if (!ZRIterator_hasNext(fiterator->subject)) { fiterator->hasNextComputed = 0b10; return false; } ZRIterator_next(fiterator->subject); void *current = ZRIterator_current(fiterator->subject); for (size_t i = 0; i < nbFilters; i++) { if (!fvalidates[i](current, data)) goto END; } fiterator->hasNextComputed = 1; return true; END: ; } break; } } // Normally never happen return false; } static void fnext(ZRIterator *iterator) { ZRFilterIterator *const fiterator = (ZRFilterIterator*)iterator; switch (fiterator->hasNextComputed) { case 0b10: break; case 0: ZRITERATOR_HASNEXT((ZRIterator*)fiterator); fnext(ZRFILTERITERATOR_ITERATOR(fiterator)); break; case 1: fiterator->hasNextComputed = 0; break; } } static void* fcurrent(ZRIterator *iterator) { ZRFilterIterator *const fiterator = (ZRFilterIterator*)iterator; return ZRITERATOR_CURRENT(fiterator->subject); } static void fdestroy(ZRIterator *iterator) { ZRFilterIterator *const fiterator = (ZRFilterIterator*)iterator; ZRITERATOR_DESTROY(fiterator->subject); ZRFREE(fiterator->allocator, fiterator); } ZRIterator* ZRFilterIterator_create(ZRIterator *subject, void *data, size_t nbFilters, ZRFilterIterator_fvalidate_t fvalidates[nbFilters], enum ZRFilterIteratorOpE op, ZRAllocator *allocator) { assert(nbFilters > 0); ZRFilterIterator *it = ZRALLOC(allocator, ZRFILTERITERATORSIZE(nbFilters)); *it = (ZRFilterIterator ) { // .iterator = { // .strategy = &it->strategyArea, // },// .data = data, // .nbFilters = nbFilters, // .subject = subject, // .allocator = allocator, // .hasNextComputed = 0, // }; it->strategyArea = (ZRIteratorStrategy ) { // .fhasNext = (ZRIterator_fhasNext_t)(op == ZRFilterIteratorOp_AND ? fhasNext_AND : fhasNext_OR), // .fnext = (ZRIterator_fnext_t)fnext, // .fcurrent = (ZRIterator_fcurrent_t)fcurrent, // .fdestroy = (ZRIterator_fdestroy_t)fdestroy, // }; memcpy(it->fvalidates, fvalidates, sizeof(*fvalidates) * nbFilters); return (ZRIterator*)it; } ZRIterator* ZRFilterIterator_createOr(ZRIterator *subject, void *data, size_t nbFilters, ZRFilterIterator_fvalidate_t fvalidates[nbFilters], ZRAllocator *allocator) { return ZRFilterIterator_create(subject, data, nbFilters, fvalidates, ZRFilterIteratorOp_OR, allocator); } ZRIterator* ZRFilterIterator_createAnd(ZRIterator *subject, void *data, size_t nbFilters, ZRFilterIterator_fvalidate_t fvalidates[nbFilters], ZRAllocator *allocator) { return ZRFilterIterator_create(subject, data, nbFilters, fvalidates, ZRFilterIteratorOp_AND, allocator); } ZRIterator* ZRFilterIterator_create1(ZRIterator *subject, void *data, ZRFilterIterator_fvalidate_t fvalidate, ZRAllocator *allocator) { return ZRFilterIterator_create(subject, data, 1, &fvalidate, ZRFilterIteratorOp_OR, allocator); }
1270.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_max_preinc_04.c Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-04.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: max Set data to the max value for int * GoodSource: Set data to a small, non-zero number (two) * Sinks: increment * GoodSink: Ensure there will not be an overflow before incrementing data * BadSink : Increment data, which can cause an overflow * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) * * */ #include "std_testcase.h" /* The two variables below are declared "const", so a tool should be able to identify that reads of these will always return their initialized values. */ static const int STATIC_CONST_TRUE = 1; /* true */ static const int STATIC_CONST_FALSE = 0; /* false */ #ifndef OMITBAD void CWE190_Integer_Overflow__int_max_preinc_04_bad() { int data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Use the maximum value for this type */ data = INT_MAX; } if(STATIC_CONST_TRUE) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodB2G1() { int data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Use the maximum value for this type */ data = INT_MAX; } if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { ++data; int result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ static void goodB2G2() { int data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* POTENTIAL FLAW: Use the maximum value for this type */ data = INT_MAX; } if(STATIC_CONST_TRUE) { /* FIX: Add a check to prevent an overflow from occurring */ if (data < INT_MAX) { ++data; int result = data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } /* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_TRUE to STATIC_CONST_FALSE */ static void goodG2B1() { int data; /* Initialize data */ data = 0; if(STATIC_CONST_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(STATIC_CONST_TRUE) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ static void goodG2B2() { int data; /* Initialize data */ data = 0; if(STATIC_CONST_TRUE) { /* FIX: Use a small, non-zero value that will not cause an integer overflow in the sinks */ data = 2; } if(STATIC_CONST_TRUE) { { /* POTENTIAL FLAW: Incrementing data could cause an overflow */ ++data; int result = data; printIntLine(result); } } } void CWE190_Integer_Overflow__int_max_preinc_04_good() { goodB2G1(); goodB2G2(); goodG2B1(); goodG2B2(); } #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()..."); CWE190_Integer_Overflow__int_max_preinc_04_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE190_Integer_Overflow__int_max_preinc_04_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
953699.c
/* * Benchmarks contributed by Divyesh Unadkat[1,2], Supratik Chakraborty[1], Ashutosh Gupta[1] * [1] Indian Institute of Technology Bombay, Mumbai * [2] TCS Innovation labs, Pune * */ extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } extern int __VERIFIER_nondet_int(void); int N; int main() { N = __VERIFIER_nondet_int(); if(N <= 0) return 1; __VERIFIER_assume(N <= 2147483647/sizeof(int)); int i, j; int sum[1]; int a[N]; int b[N]; for (i = 0; i < N; i++) { b[i] = 1; } sum[0] = 0; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { sum[0] = sum[0] + a[i]; } } for (i = 0; i < N; i++) { for (j = 0; j < i+1; j++) { b[j] = b[j] + sum[0]; } } for (i = 0; i < N; i++) { __VERIFIER_assert(b[i] == (N-i) * sum[0]); } }
168176.c
/** * WinPR: Windows Portable Runtime * Schannel Security Package (OpenSSL) * * Copyright 2012-2014 Marc-Andre Moreau <[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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "schannel_openssl.h" #ifdef WITH_OPENSSL #include <winpr/crt.h> #include <winpr/sspi.h> #include <winpr/ssl.h> #include <winpr/print.h> #include <winpr/crypto.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/bio.h> struct _SCHANNEL_OPENSSL { SSL* ssl; SSL_CTX* ctx; BOOL connected; BIO* bioRead; BIO* bioWrite; BYTE* ReadBuffer; BYTE* WriteBuffer; }; #include "../../log.h" #define TAG WINPR_TAG("sspi.schannel") char* openssl_get_ssl_error_string(int ssl_error) { switch (ssl_error) { case SSL_ERROR_ZERO_RETURN: return "SSL_ERROR_ZERO_RETURN"; case SSL_ERROR_WANT_READ: return "SSL_ERROR_WANT_READ"; case SSL_ERROR_WANT_WRITE: return "SSL_ERROR_WANT_WRITE"; case SSL_ERROR_SYSCALL: return "SSL_ERROR_SYSCALL"; case SSL_ERROR_SSL: return "SSL_ERROR_SSL"; } return "SSL_ERROR_UNKNOWN"; } int schannel_openssl_client_init(SCHANNEL_OPENSSL* context) { int status; long options = 0; context->ctx = SSL_CTX_new(SSLv23_client_method()); if (!context->ctx) { WLog_ERR(TAG, "SSL_CTX_new failed"); return -1; } /** * SSL_OP_NO_COMPRESSION: * * The Microsoft RDP server does not advertise support * for TLS compression, but alternative servers may support it. * This was observed between early versions of the FreeRDP server * and the FreeRDP client, and caused major performance issues, * which is why we're disabling it. */ #ifdef SSL_OP_NO_COMPRESSION options |= SSL_OP_NO_COMPRESSION; #endif /** * SSL_OP_TLS_BLOCK_PADDING_BUG: * * The Microsoft RDP server does *not* support TLS padding. * It absolutely needs to be disabled otherwise it won't work. */ options |= SSL_OP_TLS_BLOCK_PADDING_BUG; /** * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: * * Just like TLS padding, the Microsoft RDP server does not * support empty fragments. This needs to be disabled. */ options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; SSL_CTX_set_options(context->ctx, options); context->ssl = SSL_new(context->ctx); if (!context->ssl) { WLog_ERR(TAG, "SSL_new failed"); goto out_ssl_new_failed; } context->bioRead = BIO_new(BIO_s_mem()); if (!context->bioRead) { WLog_ERR(TAG, "BIO_new failed"); goto out_bio_read_failed; } status = BIO_set_write_buf_size(context->bioRead, SCHANNEL_CB_MAX_TOKEN); if (status != 1) { WLog_ERR(TAG, "BIO_set_write_buf_size on bioRead failed"); goto out_set_write_buf_read; } context->bioWrite = BIO_new(BIO_s_mem()); if (!context->bioWrite) { WLog_ERR(TAG, "BIO_new failed"); goto out_bio_write_failed; } status = BIO_set_write_buf_size(context->bioWrite, SCHANNEL_CB_MAX_TOKEN); if (status != 1) { WLog_ERR(TAG, "BIO_set_write_buf_size on bioWrite failed"); goto out_set_write_buf_write; } status = BIO_make_bio_pair(context->bioRead, context->bioWrite); if (status != 1) { WLog_ERR(TAG, "BIO_make_bio_pair failed"); goto out_bio_pair; } SSL_set_bio(context->ssl, context->bioRead, context->bioWrite); context->ReadBuffer = (BYTE*) malloc(SCHANNEL_CB_MAX_TOKEN); if (!context->ReadBuffer) { WLog_ERR(TAG, "Failed to allocate ReadBuffer"); goto out_read_alloc; } context->WriteBuffer = (BYTE*) malloc(SCHANNEL_CB_MAX_TOKEN); if (!context->WriteBuffer) { WLog_ERR(TAG, "Failed to allocate ReadBuffer"); goto out_write_alloc; } return 0; out_write_alloc: free(context->ReadBuffer); out_read_alloc: out_bio_pair: out_set_write_buf_write: BIO_free_all(context->bioWrite); out_bio_write_failed: out_set_write_buf_read: BIO_free_all(context->bioRead); out_bio_read_failed: SSL_free(context->ssl); out_ssl_new_failed: SSL_CTX_free(context->ctx); return -1; } int schannel_openssl_server_init(SCHANNEL_OPENSSL* context) { int status; long options = 0; context->ctx = SSL_CTX_new(SSLv23_server_method()); if (!context->ctx) { WLog_ERR(TAG, "SSL_CTX_new failed"); return -1; } /* * SSL_OP_NO_SSLv2: * * We only want SSLv3 and TLSv1, so disable SSLv2. * SSLv3 is used by, eg. Microsoft RDC for Mac OS X. */ options |= SSL_OP_NO_SSLv2; /** * SSL_OP_NO_COMPRESSION: * * The Microsoft RDP server does not advertise support * for TLS compression, but alternative servers may support it. * This was observed between early versions of the FreeRDP server * and the FreeRDP client, and caused major performance issues, * which is why we're disabling it. */ #ifdef SSL_OP_NO_COMPRESSION options |= SSL_OP_NO_COMPRESSION; #endif /** * SSL_OP_TLS_BLOCK_PADDING_BUG: * * The Microsoft RDP server does *not* support TLS padding. * It absolutely needs to be disabled otherwise it won't work. */ options |= SSL_OP_TLS_BLOCK_PADDING_BUG; /** * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: * * Just like TLS padding, the Microsoft RDP server does not * support empty fragments. This needs to be disabled. */ options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; SSL_CTX_set_options(context->ctx, options); if (SSL_CTX_use_RSAPrivateKey_file(context->ctx, "/tmp/localhost.key", SSL_FILETYPE_PEM) <= 0) { WLog_ERR(TAG, "SSL_CTX_use_RSAPrivateKey_file failed"); goto out_rsa_key; } context->ssl = SSL_new(context->ctx); if (!context->ssl) { WLog_ERR(TAG, "SSL_new failed"); goto out_ssl_new; } if (SSL_use_certificate_file(context->ssl, "/tmp/localhost.crt", SSL_FILETYPE_PEM) <= 0) { WLog_ERR(TAG, "SSL_use_certificate_file failed"); goto out_use_certificate; } context->bioRead = BIO_new(BIO_s_mem()); if (!context->bioRead) { WLog_ERR(TAG, "BIO_new failed"); goto out_bio_read; } status = BIO_set_write_buf_size(context->bioRead, SCHANNEL_CB_MAX_TOKEN); if (status != 1) { WLog_ERR(TAG, "BIO_set_write_buf_size failed for bioRead"); goto out_set_write_buf_read; } context->bioWrite = BIO_new(BIO_s_mem()); if (!context->bioWrite) { WLog_ERR(TAG, "BIO_new failed"); goto out_bio_write; } status = BIO_set_write_buf_size(context->bioWrite, SCHANNEL_CB_MAX_TOKEN); if (status != 1) { WLog_ERR(TAG, "BIO_set_write_buf_size failed for bioWrite"); goto out_set_write_buf_write; } status = BIO_make_bio_pair(context->bioRead, context->bioWrite); if (status != 1) { WLog_ERR(TAG, "BIO_make_bio_pair failed"); goto out_bio_pair; } SSL_set_bio(context->ssl, context->bioRead, context->bioWrite); context->ReadBuffer = (BYTE*) malloc(SCHANNEL_CB_MAX_TOKEN); if (!context->ReadBuffer) { WLog_ERR(TAG, "Failed to allocate memory for ReadBuffer"); goto out_read_buffer; } context->WriteBuffer = (BYTE*) malloc(SCHANNEL_CB_MAX_TOKEN); if (!context->WriteBuffer) { WLog_ERR(TAG, "Failed to allocate memory for WriteBuffer"); goto out_write_buffer; } return 0; out_write_buffer: free(context->ReadBuffer); out_read_buffer: out_bio_pair: out_set_write_buf_write: BIO_free_all(context->bioWrite); out_bio_write: out_set_write_buf_read: BIO_free_all(context->bioRead); out_bio_read: out_use_certificate: SSL_free(context->ssl); out_ssl_new: out_rsa_key: SSL_CTX_free(context->ctx); return -1; } SECURITY_STATUS schannel_openssl_client_process_tokens(SCHANNEL_OPENSSL* context, PSecBufferDesc pInput, PSecBufferDesc pOutput) { int status; int ssl_error; PSecBuffer pBuffer; if (!context->connected) { if (pInput) { if (pInput->cBuffers < 1) return SEC_E_INVALID_TOKEN; pBuffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); if (!pBuffer) return SEC_E_INVALID_TOKEN; status = BIO_write(context->bioRead, pBuffer->pvBuffer, pBuffer->cbBuffer); } status = SSL_connect(context->ssl); if (status < 0) { ssl_error = SSL_get_error(context->ssl, status); WLog_ERR(TAG, "SSL_connect error: %s", openssl_get_ssl_error_string(ssl_error)); } if (status == 1) context->connected = TRUE; status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); if (pOutput->cBuffers < 1) return SEC_E_INVALID_TOKEN; pBuffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); if (!pBuffer) return SEC_E_INVALID_TOKEN; if (status > 0) { if (pBuffer->cbBuffer < (unsigned long) status) return SEC_E_INSUFFICIENT_MEMORY; CopyMemory(pBuffer->pvBuffer, context->ReadBuffer, status); pBuffer->cbBuffer = status; return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; } else { pBuffer->cbBuffer = 0; return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; } } return SEC_E_OK; } SECURITY_STATUS schannel_openssl_server_process_tokens(SCHANNEL_OPENSSL* context, PSecBufferDesc pInput, PSecBufferDesc pOutput) { int status; int ssl_error; PSecBuffer pBuffer; if (!context->connected) { if (pInput->cBuffers < 1) return SEC_E_INVALID_TOKEN; pBuffer = sspi_FindSecBuffer(pInput, SECBUFFER_TOKEN); if (!pBuffer) return SEC_E_INVALID_TOKEN; status = BIO_write(context->bioRead, pBuffer->pvBuffer, pBuffer->cbBuffer); status = SSL_accept(context->ssl); if (status < 0) { ssl_error = SSL_get_error(context->ssl, status); WLog_ERR(TAG, "SSL_accept error: %s", openssl_get_ssl_error_string(ssl_error)); } if (status == 1) context->connected = TRUE; status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); if (pOutput->cBuffers < 1) return SEC_E_INVALID_TOKEN; pBuffer = sspi_FindSecBuffer(pOutput, SECBUFFER_TOKEN); if (!pBuffer) return SEC_E_INVALID_TOKEN; if (status > 0) { if (pBuffer->cbBuffer < (unsigned long) status) return SEC_E_INSUFFICIENT_MEMORY; CopyMemory(pBuffer->pvBuffer, context->ReadBuffer, status); pBuffer->cbBuffer = status; return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; } else { pBuffer->cbBuffer = 0; return (context->connected) ? SEC_E_OK : SEC_I_CONTINUE_NEEDED; } } return SEC_E_OK; } SECURITY_STATUS schannel_openssl_encrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) { int status; int ssl_error; PSecBuffer pStreamBodyBuffer; PSecBuffer pStreamHeaderBuffer; PSecBuffer pStreamTrailerBuffer; pStreamHeaderBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_STREAM_HEADER); pStreamBodyBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); pStreamTrailerBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_STREAM_TRAILER); if ((!pStreamHeaderBuffer) || (!pStreamBodyBuffer) || (!pStreamTrailerBuffer)) return SEC_E_INVALID_TOKEN; status = SSL_write(context->ssl, pStreamBodyBuffer->pvBuffer, pStreamBodyBuffer->cbBuffer); if (status < 0) { ssl_error = SSL_get_error(context->ssl, status); WLog_ERR(TAG, "SSL_write: %s", openssl_get_ssl_error_string(ssl_error)); } status = BIO_read(context->bioWrite, context->ReadBuffer, SCHANNEL_CB_MAX_TOKEN); if (status > 0) { size_t ustatus = (size_t)status; size_t length; size_t offset = 0; length = (pStreamHeaderBuffer->cbBuffer > ustatus) ? ustatus : pStreamHeaderBuffer->cbBuffer; CopyMemory(pStreamHeaderBuffer->pvBuffer, &context->ReadBuffer[offset], length); ustatus -= length; offset += length; length = (pStreamBodyBuffer->cbBuffer > ustatus) ? ustatus : pStreamBodyBuffer->cbBuffer; CopyMemory(pStreamBodyBuffer->pvBuffer, &context->ReadBuffer[offset], length); ustatus -= length; offset += length; length = (pStreamTrailerBuffer->cbBuffer > ustatus) ? ustatus : pStreamTrailerBuffer->cbBuffer; CopyMemory(pStreamTrailerBuffer->pvBuffer, &context->ReadBuffer[offset], length); } return SEC_E_OK; } SECURITY_STATUS schannel_openssl_decrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) { int status; int length; BYTE* buffer; int ssl_error; PSecBuffer pBuffer; pBuffer = sspi_FindSecBuffer(pMessage, SECBUFFER_DATA); if (!pBuffer) return SEC_E_INVALID_TOKEN; status = BIO_write(context->bioRead, pBuffer->pvBuffer, pBuffer->cbBuffer); status = SSL_read(context->ssl, pBuffer->pvBuffer, pBuffer->cbBuffer); if (status < 0) { ssl_error = SSL_get_error(context->ssl, status); WLog_ERR(TAG, "SSL_read: %s", openssl_get_ssl_error_string(ssl_error)); } length = status; buffer = pBuffer->pvBuffer; pMessage->pBuffers[0].BufferType = SECBUFFER_STREAM_HEADER; pMessage->pBuffers[0].cbBuffer = 5; pMessage->pBuffers[1].BufferType = SECBUFFER_DATA; pMessage->pBuffers[1].pvBuffer = buffer; pMessage->pBuffers[1].cbBuffer = length; pMessage->pBuffers[2].BufferType = SECBUFFER_STREAM_TRAILER; pMessage->pBuffers[2].cbBuffer = 36; pMessage->pBuffers[3].BufferType = SECBUFFER_EMPTY; pMessage->pBuffers[3].cbBuffer = 0; return SEC_E_OK; } SCHANNEL_OPENSSL* schannel_openssl_new() { SCHANNEL_OPENSSL* context; context = (SCHANNEL_OPENSSL*) calloc(1, sizeof(SCHANNEL_OPENSSL)); if (context != NULL) { winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT); context->connected = FALSE; } return context; } void schannel_openssl_free(SCHANNEL_OPENSSL* context) { if (context) { free(context->ReadBuffer); free(context->WriteBuffer); free(context); } } #else int schannel_openssl_client_init(SCHANNEL_OPENSSL* context) { return 0; } int schannel_openssl_server_init(SCHANNEL_OPENSSL* context) { return 0; } SECURITY_STATUS schannel_openssl_client_process_tokens(SCHANNEL_OPENSSL* context, PSecBufferDesc pInput, PSecBufferDesc pOutput) { return SEC_E_OK; } SECURITY_STATUS schannel_openssl_server_process_tokens(SCHANNEL_OPENSSL* context, PSecBufferDesc pInput, PSecBufferDesc pOutput) { return SEC_E_OK; } SECURITY_STATUS schannel_openssl_encrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) { return SEC_E_OK; } SECURITY_STATUS schannel_openssl_decrypt_message(SCHANNEL_OPENSSL* context, PSecBufferDesc pMessage) { return SEC_E_OK; } SCHANNEL_OPENSSL* schannel_openssl_new(void) { return NULL; } void schannel_openssl_free(SCHANNEL_OPENSSL* context) { } #endif
995711.c
/* * srec2bin.c: Read Motorola SREC format, write binary data. * * By default reads from stdin and writes to stdout. The command-line * options `-i` and `-o` can be used to specify the input and output * file, respectively. Specifying an output file allows sparse writes. * * NOTE: Many SREC files produced by compilers/etc have data beginning * at an address greater than zero, potentially causing initial padding * in the output (up to gigabytes of unnecessary length). The command-line * option `-a` can be used to specify an offset, i.e., the value will be * subtracted from the SREC addresses (the result must not be negative). * * Alternatively, the command-line option `-A` sets the address offset * to the first address that would be written (i.e., first byte of * data written will be at address 0). * * Copyright (c) 2015 Kimmo Kulovesi, http://arkku.com * Provided with absolutely no warranty, use at your own risk only. * Distribute freely, mark modified copies as such. */ #include "kk_srec.h" #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #define AUTODETECT_ADDRESS (~(srec_address_t)0) static FILE *outfile; static unsigned long line_number = 1UL; static srec_address_t file_position = 0L; static srec_address_t address_offset = 0; static bool debug_enabled = 0; int main (int argc, char *argv[]) { struct srec_state srec; FILE *infile = stdin; srec_count_t count; char buf[256]; outfile = stdout; while (--argc) { char *arg = *(++argv); if (arg[0] == '-' && arg[1] && arg[2] == '\0') { switch (arg[1]) { case 'a': if (--argc == 0) { goto invalid_argument; } ++argv; errno = 0; address_offset = (srec_address_t) strtol(*argv, &arg, 0); if (errno || arg == *argv) { errno = errno ? errno : EINVAL; goto argument_error; } break; case 'A': address_offset = AUTODETECT_ADDRESS; break; case 'i': if (--argc == 0) { goto invalid_argument; } ++argv; if (!(infile = fopen(*argv, "r"))) { goto argument_error; } break; case 'o': if (--argc == 0) { goto invalid_argument; } ++argv; if (!(outfile = fopen(*argv, "wb"))) { goto argument_error; } break; case 'v': debug_enabled = 1; break; case 'h': case '?': arg = NULL; goto usage; default: goto invalid_argument; } continue; } invalid_argument: (void) fprintf(stderr, "Invalid argument: %s\n", arg); usage: (void) fprintf(stderr, "kk_srec " KK_SREC_VERSION " - Copyright (c) 2015 Kimmo Kulovesi\n"); (void) fprintf(stderr, "Usage: srec2bin ([-a <address_offset>]|[-A])" " [-o <out.bin>] [-i <in.srec>] [-v]\n"); return arg ? EXIT_FAILURE : EXIT_SUCCESS; argument_error: perror(*argv); return EXIT_FAILURE; } srec_begin_read(&srec); while (fgets(buf, sizeof(buf), infile)) { count = (srec_count_t) strlen(buf); srec_read_bytes(&srec, buf, count); line_number += (count && buf[count - 1] == '\n'); } srec_end_read(&srec); if (infile != stdin) { (void) fclose(infile); } return EXIT_SUCCESS; } void srec_data_read(struct srec_state *srec, srec_record_number_t record_type, srec_address_t address, uint8_t *data, srec_count_t length, srec_bool_t error) { if (srec->length != srec->byte_count) { if (srec->byte_count > SREC_LINE_MAX_BYTE_COUNT) { (void) fprintf(stderr, "Error: Byte count too high on line %lu\n", line_number); } else { (void) fprintf(stderr, "Error: Byte count mismatch on line %lu\n", line_number); } exit(EXIT_FAILURE); } if (error) { (void) fprintf(stderr, "Error: Checksum mismatch on line %lu\n", line_number); exit(EXIT_FAILURE); } if (SREC_IS_DATA(record_type)) { if (!outfile) { (void) fprintf(stderr, "Error: Excess data after termination\n"); exit(EXIT_FAILURE); } if (address < address_offset) { if (address_offset == AUTODETECT_ADDRESS) { // autodetect initial address address_offset = address; if (debug_enabled) { (void) fprintf(stderr, "Address offset: 0x%lx\n", (unsigned long) address_offset); } } else { (void) fprintf(stderr, "Address underflow on line %lu\n", line_number); exit(EXIT_FAILURE); } } address -= address_offset; if (address != file_position) { if (debug_enabled) { (void) fprintf(stderr, "Seeking from 0x%lx to 0x%lx on line %lu\n", (unsigned long) file_position, (unsigned long) address, line_number); } if (outfile == stdout || fseek(outfile, (long) address, SEEK_SET)) { if (file_position < address) { // "seek" forward in stdout by writing NUL bytes do { (void) fputc('\0', outfile); } while (++file_position < address); } else { perror("fseek"); exit(EXIT_FAILURE); } } file_position = address; } if (!fwrite(data, (size_t) length, 1, outfile)) { perror("fwrite"); exit(EXIT_FAILURE); } file_position += (srec_address_t) length; } else if (SREC_IS_TERMINATION(record_type)) { if (address || debug_enabled) { (void) fprintf(stderr, "Program start address: 0x%0*lx\n", SREC_ADDRESS_BYTE_COUNT(record_type) * 2, (unsigned long) address); } if (debug_enabled) { (void) fprintf(stderr, "%lu bytes written\n", (unsigned long) file_position); } if (outfile != stdout) { (void) fclose(outfile); } outfile = NULL; } else if (record_type == 0) { // Print the header record unless it contains control characters srec_bool_t is_printable = 1; srec_count_t i; for (i = 0; i < length && data[i]; ++i) { if (iscntrl(data[i])) { is_printable = 0; break; } } if (is_printable) { data[length] = '\0'; (void) fprintf(stderr, "Header on line %lu: %s\n", line_number, data); } } }
400369.c
#include "krim.h" #include "Token.h" #include "lexer.h" void compile(char *file_contents) { lexer_t *lexer = init_lexer(file_contents); token_t *tok = 0; while ((tok = lexer_next_token(lexer))->type != TOKEN_EOF) { printf("<type=`%s`, int_type=`%u`, value=`%s`>\n", token_to_string(tok), tok->type, tok->value); } }
328324.c
#include <string.h> #include <time.h> #include <sys/time.h> #include <sys/prctl.h> #include <pthread.h> #include "../src/nn_nuttx.h" #define SERVER_WORKERS_MAX 1 #define CLIENT_WORKERS_MAX 1 #define CLIENT_SEND_COUND_MAX 50 bool verbose = false; #define nn_log(fmt, args...) do { if(verbose) fprintf(stderr, fmt, ## args); } while(0) typedef struct { int cmd; int arg1; int arg2; } player_info_t; typedef struct media_player_ctx { void* player; char* name; struct media_player_ctx* next; }media_player_ctx_t; typedef struct { void* server; void* notifier; pthread_t tid; media_player_ctx_t* player_list; bool interrupted; int interval; } media_server_ctx_t; typedef struct { const char* name; pthread_t tid; void* server_proxy; void* cb_proxy; void* handle; bool interrupted; int interval; } player_t; typedef enum { CREATE = 0, SET_DATA_SOURCE, PREPARE, START, PAUSE, STOP, RELEASE, ISPLAYING } media_trans_type_t; static uint64_t milliseconds(void) { struct timeval tv; gettimeofday(&tv, NULL); return (((uint64_t)tv.tv_sec * 1000) + ((uint64_t)tv.tv_usec / 1000)); } static void media_server_player_notify_info(media_server_ctx_t* ctx, media_player_ctx_t* player) { player_info_t info = { .cmd = 1, .arg1 = 2, .arg2 = 3 }; nn_pub_topic_msg(ctx->notifier, player->name, strlen(player->name), &info, sizeof(info)); } static void* media_server_worker(void* arg) { int cnt = 0; media_server_ctx_t* ctx = (media_server_ctx_t*)arg; //pthread_detach(pthread_self()); //pthread_join() prctl(PR_SET_NAME, "pub_worker", NULL, NULL, NULL); if (ctx == NULL) { return NULL; } sleep(1); while (!ctx->interrupted) { media_player_ctx_t* player = ctx->player_list; while(player != NULL) { media_server_player_notify_info(ctx, player); player = player->next; } usleep(ctx->interval); cnt++; } nn_log("%s.cnt=%d\n", __func__, cnt); return NULL; } static void* media_server_player_create(media_server_ctx_t* ctx, const char* name) { media_player_ctx_t* player = calloc(1, sizeof(media_player_ctx_t)); media_player_ctx_t** head = &ctx->player_list; if (player == NULL) { return NULL; } player->player = calloc(1, sizeof(void*)); player->name = strdup(name); while(*head != NULL) { head = &((*head)->next); } *head = player; return player; } static int media_server_on_transaction(const void* cookie, const int code, nn_trans_data_t* data) { int ret = 0; switch (code) { case CREATE: if (data != NULL) { nn_log("media_server.create.name=%s\n", (char*)data->in); void* player = media_server_player_create((media_server_ctx_t*)cookie, data->in); if (player != NULL) { data->out = malloc(sizeof(void*)); memcpy(data->out, &player, sizeof(void*)); data->out_size = sizeof(void*); } } break; case SET_DATA_SOURCE: if (data != NULL) { nn_log("media_server.set_data_source.url=%s\n", (char*)data->in); } break; default: break; } return ret; } static int media_player_listener(const void* thiz, const void* topic, const size_t topic_len, const void* content, const size_t content_len) { player_t* player = (player_t*)thiz; player_info_t* info = (player_info_t*)content; if (strncmp(player->name, (char*)topic, sizeof(player->name) != 0)) { nn_log("%s.player=%s, topic=%s\n", player->name, (char*)topic); } else { nn_log("%s.%s.topic=%s, .cmd=%d, .arg1=%d, .arg2=%d\n", __func__, player->name, (char*)topic, info->cmd, info->arg1, info->arg2); } } static inline void* get_media_server_proxy(void) { return nn_client_connect("mediaserver"); } static inline void* get_media_server_cb_proxy(player_t* player) { return nn_sub_connect("mediapub", media_player_listener, player); } static void media_player_create(player_t* player) { void* handle = NULL; player->server_proxy = get_media_server_proxy(); player->cb_proxy = get_media_server_cb_proxy(player); nn_sub_register_topic(player->cb_proxy, player->name, strlen(player->name)); nn_log("%s.name=%s\n", __func__, player->name); nn_client_transaction(player->server_proxy, CREATE, player->name, strlen(player->name) + 1, &handle, sizeof(handle)); player->handle = handle; return; } static int media_player_set_data_source(player_t *player, const char* url) { int rc = nn_client_transaction(player->server_proxy, SET_DATA_SOURCE, url, strlen(url) + 1, NULL, 0); } static void* player_worker(void* arg) { int cnt = 0; player_t *player = (player_t*)arg; prctl(PR_SET_NAME, player->name, NULL, NULL, NULL); media_player_create(player); while(!player->interrupted) { uint64_t start = milliseconds(); int ret = media_player_set_data_source(player, "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/yyyyyyyyyyyyyyyyyyyyyyyyyyyy/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz/253.mp3"); if (ret != 0) { nn_log("%s.%s.latency=%llu\n", __func__, player->name, milliseconds() - start); } usleep(player->interval); cnt++; } nn_log("%s.%s.cnt=%d\n", __func__, player->name, cnt); } static int media_client_start(player_t client[], const int cnt) { int ret = 0; for(int i = 0; i < cnt; i++) { ret = pthread_create(&client[i].tid, NULL, player_worker, &client[i]); if (ret != 0) { nn_log("%s.player.%s.failed\n", __func__, client[i].name); break; } } return ret; } static void inline media_player_destroy(player_t *player) { player->interrupted = true; pthread_join(player->tid, NULL); nn_client_disconnect(player->server_proxy); nn_sub_unregister_topic(player->cb_proxy, player->name, strlen(player->name)); nn_sub_disconnect(player->cb_proxy); } static int media_client_stop(player_t client[], const int cnt) { nn_log("%s.enter\n", __func__); for (int i = 0; i < cnt; i++) { media_player_destroy(&client[i]); } nn_log("%s.exit\n", __func__); } int media_server_start(media_server_ctx_t* ctx) { ctx->server = nn_server_create("mediaserver"); if (ctx->server == NULL) { return -1; } ctx->notifier = nn_pub_create("mediapub"); if (ctx->notifier == NULL) { nn_server_release(ctx->server); ctx->server = NULL; return -2; } nn_server_set_transaction_cb(ctx->server, media_server_on_transaction, ctx); pthread_create(&ctx->tid, NULL, media_server_worker, ctx); } int media_server_stop(media_server_ctx_t *ctx) { nn_log("%s.enter\n", __func__); ctx->interrupted = true; pthread_join(ctx->tid, NULL); nn_server_release(ctx->server); nn_pub_release(ctx->notifier); nn_log("%s.exit\n", __func__); } static void inline usage(const char* progname) { printf("Usage: %s -t seconds -i interval_ms -r reqrep_mode -p subpub_mode -h help\n", progname); } int main(int argc, char* const argv[]) { int ch = 0; player_t player[3]; media_server_ctx_t media_server; bool reqrep = false; bool pubsub = false; int interval = 10000; //ms int duration = 30; //seconds while ((ch = getopt(argc, argv, "t:i:vrph")) != -1) { switch (ch) { case 'v': verbose = true; break; case 't': duration = atoi(optarg); nn_log("duration=%d\n", duration); break; case 'i': interval = atoi(optarg);; nn_log("interval=%d\n", interval); break; case 'r': reqrep = true; nn_log("reqrep=%d\n", reqrep); break; case 'p': pubsub = true; nn_log("pubsub=%d\n", pubsub); break; case 'h': case '?': default: usage(argv[0]); return 0; } } // player init memset(player, 0, sizeof(player)); player[2].name = "wakeup"; player[0].name = "tts"; player[1].name = "music"; player[0].interval = interval; player[1].interval = interval; player[2].interval = interval; if (!reqrep) { player[0].interrupted = true; player[1].interrupted = true; player[2].interrupted = true; } //server init memset(&media_server, 0, sizeof(media_server)); media_server.interval = interval; if (!pubsub) { media_server.interrupted = true; } if (!pubsub && !reqrep) { duration = 0; } media_server_start(&media_server); media_client_start(player, 3); while(duration > 0) { if (duration > 100) { sleep(100); } else { sleep(duration); } duration -= 100; } media_server_stop(&media_server); media_client_stop(player, 3); exit(EXIT_SUCCESS); }