blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
721
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 5
91
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 321
values | visit_date
timestamp[ns]date 2016-08-12 09:31:09
2023-09-06 10:45:07
| revision_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 2010-09-28 14:01:40
2023-09-06 06:22:19
| github_id
int64 426
681M
| star_events_count
int64 101
243k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[ns]date 2012-06-28 18:51:49
2023-09-14 21:59:16
⌀ | gha_created_at
timestamp[ns]date 2008-02-11 22:55:26
2023-08-10 11:14:58
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 26
values | language
stringclasses 2
values | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 6
10.2M
| extension
stringclasses 115
values | filename
stringlengths 3
113
| content
stringlengths 6
10.2M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e4b839cddf8c4b417a4453f85a80b3e1c12bfeca
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/external/iotjs/deps/jerry/tests/unit-core/test-poolman.c
|
478fc91c8418bc0f44188dcaea67e1124ea0d438
|
[
"LicenseRef-scancode-dco-1.1",
"Apache-2.0",
"MIT"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 2,056
|
c
|
test-poolman.c
|
/* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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.
*/
/**
* Unit test for pool manager.
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "jmem.h"
#define JMEM_ALLOCATOR_INTERNAL
#include "jmem-allocator-internal.h"
#include "test-common.h"
/* Iterations count. */
const uint32_t test_iters = 1024;
/* Subiterations count. */
#define TEST_MAX_SUB_ITERS 1024
#define TEST_CHUNK_SIZE 8
uint8_t *ptrs[TEST_MAX_SUB_ITERS];
uint8_t data[TEST_MAX_SUB_ITERS][TEST_CHUNK_SIZE];
int
main (void)
{
TEST_INIT ();
jmem_init ();
for (uint32_t i = 0; i < test_iters; i++)
{
const size_t subiters = ((size_t) rand () % TEST_MAX_SUB_ITERS) + 1;
for (size_t j = 0; j < subiters; j++)
{
ptrs[j] = (uint8_t *) jmem_pools_alloc (TEST_CHUNK_SIZE);
if (ptrs[j] != NULL)
{
for (size_t k = 0; k < TEST_CHUNK_SIZE; k++)
{
ptrs[j][k] = (uint8_t) (rand () % 256);
}
memcpy (data[j], ptrs[j], TEST_CHUNK_SIZE);
}
}
/* jmem_heap_print (false); */
for (size_t j = 0; j < subiters; j++)
{
if (rand () % 256 == 0)
{
jmem_pools_collect_empty ();
}
if (ptrs[j] != NULL)
{
TEST_ASSERT (!memcmp (data[j], ptrs[j], TEST_CHUNK_SIZE));
jmem_pools_free (ptrs[j], TEST_CHUNK_SIZE);
}
}
}
#ifdef JMEM_STATS
jmem_heap_stats_print ();
#endif /* JMEM_STATS */
jmem_finalize ();
return 0;
} /* main */
|
c4fa61c56ad1beaaa5e4df1d2acf29a516cc7ebb
|
0fa1152e1e434ce9fe9e2db95f43f25675bf7d27
|
/boards/nxp/fmurt1062-v1/src/board_config.h
|
091b40041895fec91a73b1ba045c735b60e02298
|
[
"BSD-3-Clause"
] |
permissive
|
PX4/PX4-Autopilot
|
4cc90dccc9285ca4db7f595ac5a7547df02ca92e
|
3d61ab84c42ff8623bd48ff0ba74f9cf26bb402b
|
refs/heads/main
| 2023-08-30T23:58:35.398450
| 2022-03-26T01:29:03
| 2023-08-30T15:40:01
| 5,298,790
| 3,146
| 3,798
|
BSD-3-Clause
| 2023-09-14T17:22:04
| 2012-08-04T21:19:36
|
C++
|
UTF-8
|
C
| false
| false
| 23,726
|
h
|
board_config.h
|
/****************************************************************************
*
* Copyright (c) 2018-2019 PX4 Development Team. 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 PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file board_config.h
*
* NXP fmukrt1062-v1 internal definitions
*/
#pragma once
/****************************************************************************************************
* Included Files
****************************************************************************************************/
#include <px4_platform_common/px4_config.h>
#include <nuttx/compiler.h>
#include <stdint.h>
#include "imxrt_gpio.h"
#include "imxrt_iomuxc.h"
#include "hardware/imxrt_pinmux.h"
#include <arch/board/board.h>
/****************************************************************************************************
* Definitions
****************************************************************************************************/
/* PX4IO connection configuration */
#if 0 // There is no PX4IO Support on first out
// This requires serial DMA driver
#define BOARD_USES_PX4IO_VERSION 2
#define PX4IO_SERIAL_DEVICE "/dev/ttyS6"
#define PX4IO_SERIAL_TX_GPIO GPIO_LPUART8_TX_2
#define PX4IO_SERIAL_RX_GPIO GPIO_LPUART8_RX_2
#define PX4IO_SERIAL_BASE IMXRT_LPUART8_BASE
#define PX4IO_SERIAL_VECTOR IMXRT_IRQ_LPUART8
#define PX4IO_SERIAL_TX_DMAMAP
#define PX4IO_SERIAL_RX_DMAMAP
#define PX4IO_SERIAL_RCC_REG
#define PX4IO_SERIAL_RCC_EN
#define PX4IO_SERIAL_CLOCK
#define PX4IO_SERIAL_BITRATE 1500000 /* 1.5Mbps -> max rate for IO */
#endif
/* Configuration ************************************************************************************/
/* FMURT1062 GPIOs ***********************************************************************************/
/* LEDs */
/* An RGB LED is connected through GPIO as shown below:
*/
#define LED_IOMUX (IOMUX_OPENDRAIN | IOMUX_PULL_NONE | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_SLOW)
#define GPIO_nLED_RED /* GPIO_B0_00 QTIMER1_TIMER0 GPIO2_IO0 */ (GPIO_PORT2 | GPIO_PIN0 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | LED_IOMUX)
#define GPIO_nLED_GREEN /* GPIO_B0_01 QTIMER1_TIMER1 GPIO2_IO1 */ (GPIO_PORT2 | GPIO_PIN1 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | LED_IOMUX)
#define GPIO_nLED_BLUE /* GPIO_B1_08 QTIMER1_TIMER3 GPIO2_IO24 */ (GPIO_PORT2 | GPIO_PIN24 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | LED_IOMUX)
#define BOARD_HAS_CONTROL_STATUS_LEDS 1
#define BOARD_OVERLOAD_LED LED_RED
#define BOARD_ARMED_STATE_LED LED_BLUE
/*
* Define the ability to shut off off the sensor signals
* by changing the signals to inputs
*/
#define _PIN_OFF(def) (((def) & (GPIO_PORT_MASK | GPIO_PIN_MASK)) | (GPIO_INPUT | IOMUX_PULL_DOWN_100K | IOMUX_CMOS_INPUT))
/* Define the Chip Selects, Data Ready and Control signals per SPI bus */
#define CS_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_UP_100K | IOMUX_DRIVE_33OHM | IOMUX_SPEED_LOW | IOMUX_SLEW_FAST)
#define OUT_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_UP_100K | IOMUX_DRIVE_50OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_FAST)
/* SPI1 off */
#define _GPIO_LPSPI1_SCK /* GPIO_EMC_27 GPIO4_IO27 */ (GPIO_PORT4 | GPIO_PIN27 | CS_IOMUX)
#define _GPIO_LPSPI1_MISO /* GPIO_EMC_29 GPIO4_IO29 */ (GPIO_PORT4 | GPIO_PIN29 | CS_IOMUX)
#define _GPIO_LPSPI1_MOSI /* GPIO_EMC_28 GPIO4_IO28 */ (GPIO_PORT4 | GPIO_PIN28 | CS_IOMUX)
#define GPIO_SPI1_SCK_OFF _PIN_OFF(_GPIO_LPSPI1_SCK)
#define GPIO_SPI1_MISO_OFF _PIN_OFF(_GPIO_LPSPI1_MISO)
#define GPIO_SPI1_MOSI_OFF _PIN_OFF(_GPIO_LPSPI1_MOSI)
#define _GPIO_LPSPI3_SCK /* GPIO_AD_B1_15 GPIO1_IO27 */ (GPIO_PORT1 | GPIO_PIN31 | CS_IOMUX)
#define _GPIO_LPSPI3_MISO /* GPIO_AD_B1_13 GPIO1_IO27 */ (GPIO_PORT1 | GPIO_PIN29 | CS_IOMUX)
#define _GPIO_LPSPI3_MOSI /* GPIO_AD_B1_14 GPIO1_IO27 */ (GPIO_PORT1 | GPIO_PIN30 | CS_IOMUX)
#define GPIO_SPI3_SCK_OFF _PIN_OFF(_GPIO_LPSPI3_SCK)
#define GPIO_SPI3_MISO_OFF _PIN_OFF(_GPIO_LPSPI3_MISO)
#define GPIO_SPI3_MOSI_OFF _PIN_OFF(_GPIO_LPSPI3_MOSI)
/* Define the SPI4 Data Ready and Control signals */
#define GPIO_SPI4_DRDY7_EXTERNAL1 /* GPIO_EMC_35 GPIO3_IO21*/ (GPIO_PORT3 | GPIO_PIN21 | GPIO_INPUT | DRDY_IOMUX)
#define GPIO_nSPI4_RESET_EXTERNAL1 /* GPIO_B1_00 GPIO2_IO16 */ (GPIO_PORT2 | GPIO_PIN16 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | OUT_IOMUX)
#define GPIO_SPI4_SYNC_EXTERNAL1 /* GPIO_EMC_05 GPIO4_IO5 */(GPIO_PORT4 | GPIO_PIN5 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | OUT_IOMUX)
#define GPIO_DRDY_OFF_SPI4_DRDY7_EXTERNAL1 _PIN_OFF(GPIO_SPI4_DRDY7_EXTERNAL1)
#define GPIO_nSPI4_RESET_EXTERNAL1_OFF _PIN_OFF(GPIO_nSPI4_RESET_EXTERNAL1)
#define GPIO_SPI4_SYNC_EXTERNAL1_OFF _PIN_OFF(GPIO_SPI4_SYNC_EXTERNAL1)
#define ADC_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_HIZ)
#define ADC1_CH(n) (n)
#define ADC1_GPIO(n, p) (GPIO_PORT1 | GPIO_PIN##p | ADC_IOMUX) //
/* Define GPIO pins used as ADC N.B. Channel numbers are for reference, */
#define PX4_ADC_GPIO \
/* BATTERY1_VOLTAGE GPIO_AD_B1_11 GPIO1 Pin 27 */ ADC1_GPIO(0, 27), \
/* BATTERY1_CURRENT GPIO_AD_B0_12 GPIO1 Pin 12 */ ADC1_GPIO(1, 12), \
/* BATTERY2_VOLTAGE GPIO_AD_B0_13 GPIO1 Pin 13 */ ADC1_GPIO(2, 13), \
/* BATTERY2_CURRENT GPIO_AD_B0_14 GPIO1 Pin 14 */ ADC1_GPIO(3, 14), \
/* SPARE_2_CHANNEL GPIO_AD_B0_15 GPIO1 Pin 15 */ ADC1_GPIO(4, 15), \
/* HW_VER_SENSE GPIO_AD_B1_04 GPIO1 Pin 20 */ ADC1_GPIO(9, 20), \
/* SCALED_V5 GPIO_AD_B1_05 GPIO1 Pin 21 */ ADC1_GPIO(10, 21), \
/* SCALED_VDD_3V3_SENSORS GPIO_AD_B1_06 GPIO1 Pin 22 */ ADC1_GPIO(11, 22), \
/* HW_REV_SENSE GPIO_AD_B1_08 GPIO1 Pin 24 */ ADC1_GPIO(13, 24), \
/* SPARE_1 GPIO_AD_B1_09 GPIO1 Pin 25 */ ADC1_GPIO(14, 25), \
/* RSSI_IN GPIO_AD_B1_10 GPIO1 Pin 26 */ ADC1_GPIO(15, 26)
/* Define Channel numbers must match above GPIO pin IN(n)*/
#define ADC_BATTERY1_VOLTAGE_CHANNEL /* GPIO_AD_B1_11 GPIO1 Pin 27 */ ADC1_CH(0)
#define ADC_BATTERY1_CURRENT_CHANNEL /* GPIO_AD_B0_12 GPIO1 Pin 12 */ ADC1_CH(1)
#define ADC_BATTERY2_VOLTAGE_CHANNEL /* GPIO_AD_B0_13 GPIO1 Pin 13 */ ADC1_CH(2)
#define ADC_BATTERY2_CURRENT_CHANNEL /* GPIO_AD_B0_14 GPIO1 Pin 14 */ ADC1_CH(3)
#define ADC1_SPARE_2_CHANNEL /* GPIO_AD_B0_15 GPIO1 Pin 15 */ ADC1_CH(4)
#define ADC_HW_VER_SENSE_CHANNEL /* GPIO_AD_B1_04 GPIO1 Pin 20 */ ADC1_CH(9)
#define ADC_SCALED_V5_CHANNEL /* GPIO_AD_B1_05 GPIO1 Pin 21 */ ADC1_CH(10)
#define ADC_SCALED_VDD_3V3_SENSORS_CHANNEL /* GPIO_AD_B1_06 GPIO1 Pin 22 */ ADC1_CH(11)
#define ADC_HW_REV_SENSE_CHANNEL /* GPIO_AD_B1_08 GPIO1 Pin 24 */ ADC1_CH(13)
#define ADC1_SPARE_1_CHANNEL /* GPIO_AD_B1_09 GPIO1 Pin 25 */ ADC1_CH(14)
#define ADC_RSSI_IN_CHANNEL /* GPIO_AD_B1_10 GPIO1 Pin 26 */ ADC1_CH(15)
#define ADC_CHANNELS \
((1 << ADC_BATTERY1_VOLTAGE_CHANNEL) | \
(1 << ADC_BATTERY1_CURRENT_CHANNEL) | \
(1 << ADC_BATTERY2_VOLTAGE_CHANNEL) | \
(1 << ADC_BATTERY2_CURRENT_CHANNEL) | \
(1 << ADC1_SPARE_2_CHANNEL) | \
(1 << ADC_RSSI_IN_CHANNEL) | \
(1 << ADC_SCALED_V5_CHANNEL) | \
(1 << ADC_SCALED_VDD_3V3_SENSORS_CHANNEL) | \
(1 << ADC_HW_VER_SENSE_CHANNEL) | \
(1 << ADC_HW_REV_SENSE_CHANNEL) | \
(1 << ADC1_SPARE_1_CHANNEL))
/* HW has to large of R termination on ADC todo:change when HW value is chosen */
#define BOARD_ADC_OPEN_CIRCUIT_V (5.6f)
/* HW Version and Revision drive signals Default to 1 to detect */
#define BOARD_HAS_HW_VERSIONING
#define HW_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MAX | IOMUX_SLEW_FAST)
#define GPIO_HW_VER_REV_DRIVE /* GPIO_AD_B0_01 GPIO1_IO01 */ (GPIO_PORT1 | GPIO_PIN1 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | HW_IOMUX)
#define GPIO_HW_REV_SENSE /* GPIO_AD_B1_08 GPIO1 Pin 24 */ ADC1_GPIO(13, 24)
#define GPIO_HW_VER_SENSE /* GPIO_AD_B1_04 GPIO1 Pin 20 */ ADC1_GPIO(9, 20)
#define HW_INFO_INIT_PREFIX "V5"
#define V500 HW_VER_REV(0x0,0x0) // FMUV5, Rev 0
#define V540 HW_VER_REV(0x4,0x0) // mini no can 2,3, Rev 0
/* CAN Silence
*
* Silent mode control \ ESC Mux select
*/
#define SILENT_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MAX | IOMUX_SLEW_FAST)
#define GPIO_CAN1_SILENT_S0 /* GPIO_AD_B0_10 GPIO1_IO10 */ (GPIO_PORT1 | GPIO_PIN10 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | SILENT_IOMUX)
#define GPIO_CAN2_SILENT_S1 /* GPIO_EMC_06 GPIO4_IO06 */ (GPIO_PORT4 | GPIO_PIN6 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | SILENT_IOMUX)
#define GPIO_CAN3_SILENT_S2 /* GPIO_EMC_09 GPIO4_IO09 */ (GPIO_PORT4 | GPIO_PIN9 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | SILENT_IOMUX)
/* HEATER
* PWM in future
*/
#define HEATER_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_50OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_FAST)
#define GPIO_HEATER_OUTPUT /* GPIO_B1_09 QTIMER2_TIMER3 GPIO2_IO25 */ (GPIO_QTIMER2_TIMER3_1 | HEATER_IOMUX)
#define HEATER_OUTPUT_EN(on_true) px4_arch_gpiowrite(GPIO_HEATER_OUTPUT, (on_true))
/* PWM Capture
*
* 2 PWM Capture inputs are supported
*/
#define DIRECT_PWM_CAPTURE_CHANNELS 2
#define CAP_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_50OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_FAST)
#define PIN_FLEXPWM2_PWMB0 /* P2:7 PWM2 B0 FMU_CAP1 */ (CAP_IOMUX | GPIO_FLEXPWM2_PWMB00_2)
#define PIN_FLEXPWM2_PWMB3 /* P3:3 PWM2 A1 FMU_CAP2 */ (CAP_IOMUX | GPIO_FLEXPWM2_PWMB03_3)
#define nARMED_INPUT_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_UP_22K | IOMUX_DRIVE_HIZ)
#define nARMED_OUTPUT_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_KEEP | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_FAST)
#define GPIO_nARMED_INIT /* GPIO_SD_B1_01 GPIO3_IO1 */ (GPIO_PORT3 | GPIO_PIN1 | GPIO_INPUT | nARMED_INPUT_IOMUX)
#define GPIO_nARMED /* GPIO_SD_B1_01 GPIO3_IO1 */ (GPIO_PORT3 | GPIO_PIN1 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | nARMED_OUTPUT_IOMUX)
#define BOARD_INDICATE_EXTERNAL_LOCKOUT_STATE(enabled) px4_arch_configgpio((enabled) ? GPIO_nARMED : GPIO_nARMED_INIT)
#define BOARD_GET_EXTERNAL_LOCKOUT_STATE() px4_arch_gpioread(GPIO_nARMED)
/* PWM
*/
#define DIRECT_PWM_OUTPUT_CHANNELS 8
#define BOARD_NUM_IO_TIMERS 8
// Input Capture not supported on MVP
#define BOARD_HAS_NO_CAPTURE
//#define BOARD_HAS_UI_LED_PWM 1 Not ported yet (Still Kinetis driver)
#define BOARD_HAS_LED_PWM 1
#define BOARD_LED_PWM_DRIVE_ACTIVE_LOW 1
/* UI LEDs are driven by timer 4 the pins have no alternates
*
* nUI_LED_RED GPIO_B0_10 GPIO2_IO10 QTIMER4_TIMER1
* nUI_LED_GREEN GPIO_B0_11 GPIO2_IO11 QTIMER4_TIMER2
* nUI_LED_BLUE GPIO_B1_11 GPIO2_IO27 QTIMER4_TIMER3
*/
/* Power supply control and monitoring GPIOs */
#define GENERAL_INPUT_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_UP_47K | IOMUX_DRIVE_HIZ)
#define GENERAL_OUTPUT_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_KEEP | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_FAST)
#define GPIO_nPOWER_IN_A /* GPIO_B0_12 GPIO2_IO12 */ (GPIO_PORT2 | GPIO_PIN12 | GPIO_INPUT | GENERAL_INPUT_IOMUX)
#define GPIO_nPOWER_IN_B /* GPIO_B0_13 GPIO2_IO13 */ (GPIO_PORT2 | GPIO_PIN13 | GPIO_INPUT | GENERAL_INPUT_IOMUX)
#define GPIO_nPOWER_IN_C /* GPIO_B0_14 GPIO2_IO14 */ (GPIO_PORT2 | GPIO_PIN14 | GPIO_INPUT | GENERAL_INPUT_IOMUX)
#define GPIO_nVDD_BRICK1_VALID GPIO_nPOWER_IN_A /* Brick 1 Is Chosen */
#define GPIO_nVDD_BRICK2_VALID GPIO_nPOWER_IN_B /* Brick 2 Is Chosen */
#define BOARD_NUMBER_BRICKS 2
#define GPIO_nVDD_USB_VALID GPIO_nPOWER_IN_C /* USB Is Chosen */
#define OC_INPUT_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_HIZ)
#define GPIO_nVDD_5V_PERIPH_EN /* GPIO_B1_03 GPIO2_IO19 */ (GPIO_PORT2 | GPIO_PIN19 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | GENERAL_OUTPUT_IOMUX)
#define GPIO_nVDD_5V_PERIPH_OC /* GPIO_B1_04 GPIO2_IO20 */ (GPIO_PORT2 | GPIO_PIN20 | GPIO_INPUT | OC_INPUT_IOMUX)
#define GPIO_nVDD_5V_HIPOWER_EN /* GPIO_B1_01 GPIO2_IO17 */ (GPIO_PORT2 | GPIO_PIN17 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | GENERAL_OUTPUT_IOMUX)
#define GPIO_nVDD_5V_HIPOWER_OC /* GPIO_B1_02 GPIO2_IO18 */ (GPIO_PORT2 | GPIO_PIN18 | GPIO_INPUT | OC_INPUT_IOMUX)
#define GPIO_VDD_3V3_SENSORS_EN /* GPIO_EMC_41 GPIO3_IO27 */ (GPIO_PORT3 | GPIO_PIN27 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | GENERAL_OUTPUT_IOMUX)
#define GPIO_VDD_3V3_SPEKTRUM_POWER_EN /* GPIO_AD_B0_00 GPIO1_IO00 */ (GPIO_PORT1 | GPIO_PIN0 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | GENERAL_OUTPUT_IOMUX)
#define GPIO_VDD_5V_RC_EN /* GPIO_AD_B0_08 GPIO1_IO08 */ (GPIO_PORT1 | GPIO_PIN8 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | GENERAL_OUTPUT_IOMUX)
#define GPIO_VDD_5V_WIFI_EN /* PMIC_STBY_REQ GPIO5_IO02 */ (GPIO_PORT5 | GPIO_PIN2 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | GENERAL_OUTPUT_IOMUX)
#define GPIO_VDD_3V3_SD_CARD_EN /* GPIO_EMC_13 GPIO4_IO13 */ (GPIO_PORT4 | GPIO_PIN13 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO |GENERAL_OUTPUT_IOMUX)
/* Define True logic Power Control in arch agnostic form */
#define VDD_5V_PERIPH_EN(on_true) px4_arch_gpiowrite(GPIO_nVDD_5V_PERIPH_EN, !(on_true))
#define VDD_5V_HIPOWER_EN(on_true) px4_arch_gpiowrite(GPIO_nVDD_5V_HIPOWER_EN, !(on_true))
#define VDD_3V3_SENSORS_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_3V3_SENSORS_EN, (on_true))
#define VDD_3V3_SPEKTRUM_POWER_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_3V3_SPEKTRUM_POWER_EN, (on_true))
#define READ_VDD_3V3_SPEKTRUM_POWER_EN() px4_arch_gpioread(GPIO_VDD_3V3_SPEKTRUM_POWER_EN)
#define VDD_5V_RC_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_5V_RC_EN, (on_true))
#define VDD_5V_WIFI_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_5V_WIFI_EN, (on_true))
#define VDD_3V3_SD_CARD_EN(on_true) px4_arch_gpiowrite(GPIO_VDD_3V3_SD_CARD_EN, (on_true))
/* Tone alarm output */
#define TONE_ALARM_TIMER 2 /* GPT 2 */
#define TONE_ALARM_CHANNEL 3 /* GPIO_AD_B1_07 GPT2_COMPARE3 */
#define GPIO_BUZZER_1 /* GPIO_AD_B1_07 GPIO1_IO23 */ (GPIO_PORT1 | GPIO_PIN23 | GPIO_OUTPUT | GPIO_OUTPUT_ZERO | GENERAL_OUTPUT_IOMUX)
#define GPIO_TONE_ALARM_IDLE GPIO_BUZZER_1
#define GPIO_TONE_ALARM (GPIO_GPT2_COMPARE3_2 | GENERAL_OUTPUT_IOMUX)
/* USB OTG FS
*
* VBUS_VALID is detected in USB_ANALOG_USB1_VBUS_DETECT_STAT
*/
/* High-resolution timer */
#define HRT_TIMER 1 /* use GPT1 for the HRT */
#define HRT_TIMER_CHANNEL 1 /* use capture/compare channel 1 */
#define HRT_PPM_CHANNEL /* GPIO_B1_06 GPT1_CAPTURE2 */ 2 /* use capture/compare channel 2 */
#define GPIO_PPM_IN /* GPIO_B1_06 GPT1_CAPTURE2 */ (GPIO_GPT1_CAPTURE2_2 | GENERAL_INPUT_IOMUX)
#define RC_SERIAL_PORT "/dev/ttyS5"
#define RC_SERIAL_SINGLEWIRE
/* PWM input driver. Use FMU AUX5 pins attached to GPIO_EMC_33 GPIO3_IO19 FLEXPWM3_PWMA2 */
#define PWMIN_TIMER /* FLEXPWM3_PWMA2 */ 3
#define PWMIN_TIMER_CHANNEL /* FLEXPWM3_PWMA2 */ 2
#define GPIO_PWM_IN /* GPIO_EMC_33 GPIO3_IO19 */ (GPIO_FLEXPWM3_PWMA02_1 | GENERAL_INPUT_IOMUX)
/* Shared pins Both FMU and PX4IO control/monitor
* FMU Initializes these pins to passive input until it is known
* if we have and PX4IO on board
*/
#define GPIO_RSSI_IN /* GPIO_AD_B1_10 GPIO1_IO26 */ (GPIO_PORT1 | GPIO_PIN26 | GPIO_INPUT | ADC_IOMUX)
#define GPIO_RSSI_IN_INIT /* GPIO_AD_B1_10 GPIO1_IO26 */ 0 /* Using 0 will Leave as ADC RSSI_IN */
/* Safety Switch is HW version dependent on having an PX4IO
* So we init to a benign state with the _INIT definition
* and provide the the non _INIT one for the driver to make a run time
* decision to use it.
*/
#define SAFETY_INIT_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_HIZ)
#define SAFETY_IOMUX (IOMUX_CMOS_OUTPUT | IOMUX_PULL_NONE | IOMUX_DRIVE_33OHM | IOMUX_SPEED_MEDIUM | IOMUX_SLEW_SLOW)
#define SAFETY_SW_IOMUX (IOMUX_CMOS_INPUT | IOMUX_PULL_UP_22K | IOMUX_DRIVE_HIZ)
#define GPIO_nSAFETY_SWITCH_LED_OUT_INIT /* GPIO_B0_15 GPIO2_IO15 */ (GPIO_PORT2 | GPIO_PIN15 | GPIO_INPUT | SAFETY_INIT_IOMUX)
#define GPIO_nSAFETY_SWITCH_LED_OUT /* GPIO_B0_15 GPIO2_IO15 */ (GPIO_PORT2 | GPIO_PIN15 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | SAFETY_IOMUX)
/* Enable the FMU to control it if there is no px4io fixme:This should be BOARD_SAFETY_LED(__ontrue) */
#define GPIO_LED_SAFETY GPIO_nSAFETY_SWITCH_LED_OUT
#define GPIO_SAFETY_SWITCH_IN /* GPIO_AD_B1_12 GPIO1_IO28 */ (GPIO_PORT1 | GPIO_PIN28 | GPIO_INPUT | SAFETY_SW_IOMUX)
/* Enable the FMU to use the switch it if there is no px4io fixme:This should be BOARD_SAFTY_BUTTON() */
#define GPIO_BTN_SAFETY GPIO_SAFETY_SWITCH_IN /* Enable the FMU to control it if there is no px4io */
/*
* FMUv5 has a separate RC_IN
*
* GPIO PPM_IN on GPIO_EMC_23 GPIO4 Pin 23 GPT1_CAPTURE2
* Inversion is possible in the UART and can drive GPIO PPM_IN as an output
*/
#define GPIO_PPM_IN_AS_OUT /* GPIO_B1_06 GPIO2_IO23 GPT1_CAPTURE2 GPT1_CAPTURE2 */ (GPIO_PORT2 | GPIO_PIN23 | GPIO_OUTPUT | GPIO_OUTPUT_ONE | GENERAL_OUTPUT_IOMUX)
#define SDIO_SLOTNO 0 /* Only one slot */
#define SDIO_MINOR 0
/* SD card bringup does not work if performed on the IDLE thread because it
* will cause waiting. Use either:
*
* CONFIG_BOARDCTL=y, OR
* CONFIG_BOARD_INITIALIZE=y && CONFIG_BOARD_INITTHREAD=y
*/
#if defined(CONFIG_BOARD_INITIALIZE) && !defined(CONFIG_BOARDCTL) && \
!defined(CONFIG_BOARD_INITTHREAD)
# warning SDIO initialization cannot be perfomed on the IDLE thread
#endif
/* By Providing BOARD_ADC_USB_CONNECTED (using the px4_arch abstraction)
* this board support the ADC system_power interface, and therefore
* provides the true logic GPIO BOARD_ADC_xxxx macros.
*/
#define BOARD_ADC_USB_VALID (!px4_arch_gpioread(GPIO_nVDD_USB_VALID))
#define BOARD_ADC_USB_CONNECTED (board_read_VBUS_state() == 0)
/* FMUv5 never powers odd the Servo rail */
#define BOARD_ADC_SERVO_VALID (1)
#define BOARD_ADC_BRICK1_VALID (!px4_arch_gpioread(GPIO_nVDD_BRICK1_VALID))
#define BOARD_ADC_BRICK2_VALID (!px4_arch_gpioread(GPIO_nVDD_BRICK2_VALID))
#define BOARD_ADC_PERIPH_5V_OC (!px4_arch_gpioread(GPIO_nVDD_5V_PERIPH_OC))
#define BOARD_ADC_HIPOWER_5V_OC (!px4_arch_gpioread(GPIO_nVDD_5V_HIPOWER_OC))
/* This board provides a DMA pool and APIs */
#define BOARD_DMA_ALLOC_POOL_SIZE 5120
/* This board provides the board_on_reset interface */
#define BOARD_HAS_ON_RESET 1
#define PX4_GPIO_INIT_LIST { \
GPIO_nARMED_INIT, \
PX4_ADC_GPIO, \
GPIO_HW_VER_REV_DRIVE, \
GPIO_FLEXCAN1_TX, \
GPIO_FLEXCAN1_RX, \
GPIO_FLEXCAN2_TX, \
GPIO_FLEXCAN2_RX, \
GPIO_FLEXCAN3_TX, \
GPIO_FLEXCAN3_RX, \
GPIO_CAN1_SILENT_S0, \
GPIO_CAN2_SILENT_S1, \
GPIO_CAN3_SILENT_S2, \
GPIO_HEATER_OUTPUT, \
GPIO_nPOWER_IN_A, \
GPIO_nPOWER_IN_B, \
GPIO_nPOWER_IN_C, \
GPIO_nVDD_5V_PERIPH_EN, \
GPIO_nVDD_5V_PERIPH_OC, \
GPIO_nVDD_5V_HIPOWER_EN, \
GPIO_nVDD_5V_HIPOWER_OC, \
GPIO_VDD_3V3_SENSORS_EN, \
GPIO_VDD_3V3_SD_CARD_EN, \
GPIO_VDD_3V3_SPEKTRUM_POWER_EN, \
GPIO_VDD_5V_RC_EN, \
GPIO_VDD_5V_WIFI_EN, \
GPIO_TONE_ALARM_IDLE, \
GPIO_RSSI_IN_INIT, \
GPIO_nSAFETY_SWITCH_LED_OUT_INIT, \
GPIO_nSPI4_RESET_EXTERNAL1, \
GPIO_SPI4_SYNC_EXTERNAL1, \
GPIO_SAFETY_SWITCH_IN \
}
#define BOARD_ENABLE_CONSOLE_BUFFER
__BEGIN_DECLS
/****************************************************************************************************
* Public Types
****************************************************************************************************/
/****************************************************************************************************
* Public data
****************************************************************************************************/
#ifndef __ASSEMBLY__
/****************************************************************************************************
* Public Functions
****************************************************************************************************/
/****************************************************************************
* Name: fmurt1062_usdhc_initialize
*
* Description:
* Initialize SDIO-based MMC/SD card support
*
****************************************************************************/
int fmurt1062_usdhc_initialize(void);
/****************************************************************************************************
* Name: imxrt_spidev_initialize
*
* Description:
* Called to configure SPI chip select GPIO pins for the PX4FMU board.
*
****************************************************************************************************/
extern void imxrt_spidev_initialize(void);
/************************************************************************************
* Name: imxrt_spi_bus_initialize
*
* Description:
* Called to configure SPI Buses.
*
************************************************************************************/
extern int imxrt1062_spi_bus_initialize(void);
/************************************************************************************
* Name: imxrt_usb_initialize
*
* Description:
* Called to configure USB.
*
************************************************************************************/
extern int imxrt_usb_initialize(void);
extern void imxrt_usbinitialize(void);
extern void board_peripheral_reset(int ms);
extern void fmurt1062_timer_initialize(void);
#include <px4_platform_common/board_common.h>
#endif /* __ASSEMBLY__ */
__END_DECLS
|
579e80abfd12b7f79587ee02dbd5adefeaf70e6b
|
d9e96244515264268d6078650fa707f34d94ee7a
|
/Working/Game/xleres/System/LoadGBuffer.h
|
8faf4b608b422a189756c99a61ac28754e8d7cbc
|
[
"MIT"
] |
permissive
|
xlgames-inc/XLE
|
45c89537c10561e216367a2e3bcd7d1c92b1b039
|
69cc4f2aa4faf12ed15bb4291c6992c83597899c
|
refs/heads/master
| 2022-06-29T17:16:11.491925
| 2022-05-04T00:29:28
| 2022-05-04T00:29:28
| 29,281,799
| 396
| 102
| null | 2016-01-04T13:35:59
| 2015-01-15T05:07:55
|
C++
|
UTF-8
|
C
| false
| false
| 1,489
|
h
|
LoadGBuffer.h
|
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
#if !defined(LOAD_GBUFFER_H)
#define LOAD_GBUFFER_H
#include "..\gbuffer.h"
#include "..\TextureAlgorithm.h"
Texture2D_MaybeMS<float4> GBuffer_Diffuse : register(t0);
Texture2D_MaybeMS<float4> GBuffer_Normals : register(t1);
#if HAS_PROPERTIES_BUFFER==1
Texture2D_MaybeMS<float4> GBuffer_Parameters : register(t2);
#endif
GBufferValues LoadGBuffer(float2 position, SystemInputs sys)
{
int2 pixelCoord = position.xy;
#if SHADER_NODE_EDITOR==1
// In the shader node editor, the gbuffer textures might not be
// the same dimensions as the output viewport. So we need to resample.
// Just do basic point resampling (otherwise normal filtering, etc,
// could get really complex)
uint2 textureDims;
GBuffer_Diffuse.GetDimensions(textureDims.x, textureDims.y);
pixelCoord = textureDims * pixelCoord / NodeEditor_GetOutputDimensions();
#endif
GBufferEncoded encoded;
encoded.diffuseBuffer = LoadFloat4(GBuffer_Diffuse, pixelCoord, GetSampleIndex(sys));
encoded.normalBuffer = LoadFloat4(GBuffer_Normals, pixelCoord, GetSampleIndex(sys));
#if HAS_PROPERTIES_BUFFER==1
encoded.propertiesBuffer = LoadFloat4(GBuffer_Parameters, pixelCoord, GetSampleIndex(sys));
#endif
return Decode(encoded);
}
#endif
|
568d762f30cebc1bf4caee065a8cca27a5fcae31
|
50dd46b8ece33f3cdd174284b15d1d51f89669d4
|
/third_party/edk2/Vlv2TbltDevicePkg/FvbRuntimeDxe/FvbService.c
|
89b9410424201b94c0dc04a4225cce667b52adef
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause",
"OpenSSL"
] |
permissive
|
google/google-ctf
|
f99da1ee07729bbccb869fff1cbaed6a80e43bcc
|
df02323eaf945d15e124801c74abaadca2749dc7
|
refs/heads/master
| 2023-08-31T14:30:27.548081
| 2023-08-29T13:04:20
| 2023-08-29T13:04:20
| 131,317,137
| 4,136
| 607
|
Apache-2.0
| 2023-08-30T22:17:02
| 2018-04-27T15:56:03
|
Go
|
UTF-8
|
C
| false
| false
| 34,810
|
c
|
FvbService.c
|
/** @file
Firmware Volume Block Driver for Lakeport Platform.
Firmware volume block driver for FWH or SPI device.
It depends on which Flash Device Library to be linked with this driver.
Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials are licensed and made available under
the terms and conditions of the BSD License that accompanies this distribution.
The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php.
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include "FvbService.h"
//
// Global variable for this FVB driver which contains
// the private data of all firmware volume block instances.
//
FWB_GLOBAL mFvbModuleGlobal;
//
// This platform driver knows there are 3 FVs on
// FD, which are FvRecovery, FvMain and FvNvStorage.
//
UINT32 mPlatformFvBaseAddress[] = {
FixedPcdGet32(PcdFlashNvStorageVariableBase),
};
FV_MEMMAP_DEVICE_PATH mFvMemmapDevicePathTemplate = {
{
{
HARDWARE_DEVICE_PATH,
HW_MEMMAP_DP,
{
(UINT8)(sizeof (MEMMAP_DEVICE_PATH)),
(UINT8)(sizeof (MEMMAP_DEVICE_PATH) >> 8)
}
},
EfiMemoryMappedIO,
(EFI_PHYSICAL_ADDRESS) 0,
(EFI_PHYSICAL_ADDRESS) 0,
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
END_DEVICE_PATH_LENGTH,
0
}
}
};
FV_PIWG_DEVICE_PATH mFvPIWGDevicePathTemplate = {
{
{
MEDIA_DEVICE_PATH,
MEDIA_PIWG_FW_VOL_DP,
{
(UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH)),
(UINT8)(sizeof (MEDIA_FW_VOL_DEVICE_PATH) >> 8)
}
},
{ 0 }
},
{
END_DEVICE_PATH_TYPE,
END_ENTIRE_DEVICE_PATH_SUBTYPE,
{
END_DEVICE_PATH_LENGTH,
0
}
}
};
//
// Template structure used when installing FVB protocol.
//
EFI_FW_VOL_BLOCK_DEVICE mFvbDeviceTemplate = {
FVB_DEVICE_SIGNATURE,
NULL,
0, // Instance
{
FvbProtocolGetAttributes,
FvbProtocolSetAttributes,
FvbProtocolGetPhysicalAddress,
FvbProtocolGetBlockSize,
FvbProtocolRead,
FvbProtocolWrite,
FvbProtocolEraseBlocks,
NULL
} // FwVolBlockInstance
};
/**
Get the pointer to EFI_FW_VOL_INSTANCE from the buffer pointed
by mFvbModuleGlobal.FvInstance based on a index.
Each EFI_FW_VOL_INSTANCE is with variable length as
we have a block map at the end of the EFI_FIRMWARE_VOLUME_HEADER.
@param[in] Instance The index of the EFI_FW_VOL_INSTANCE.
@return A pointer to EFI_FW_VOL_INSTANCE.
**/
EFI_FW_VOL_INSTANCE *
GetFvbInstance (
IN UINTN Instance
)
{
EFI_FW_VOL_INSTANCE *FwhRecord;
if ( Instance >= mFvbModuleGlobal.NumFv ) {
ASSERT_EFI_ERROR (EFI_INVALID_PARAMETER);
return NULL;
}
//
// Find the right instance of the FVB private data.
//
FwhRecord = mFvbModuleGlobal.FvInstance;
while ( Instance > 0 ) {
FwhRecord = (EFI_FW_VOL_INSTANCE *) ((UINTN)((UINT8 *)FwhRecord) +
FwhRecord->VolumeHeader.HeaderLength +
(sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));
Instance --;
}
return FwhRecord;
}
/**
Get the EFI_FVB_ATTRIBUTES_2 of a FV.
@param[in] The index of the EFI_FW_VOL_INSTANCE.
@return EFI_FVB_ATTRIBUTES_2 of the FV identified by Instance.
**/
STATIC
EFI_FVB_ATTRIBUTES_2
FvbGetVolumeAttributes (
IN UINTN Instance
)
{
EFI_FW_VOL_INSTANCE * FwInstance = NULL;
FwInstance = GetFvbInstance(Instance);
ASSERT (FwInstance != NULL);
if ( FwInstance != NULL ) {
return FwInstance->VolumeHeader.Attributes;
} else {
return 0;
}
}
/**
Retrieves the starting address of an LBA in an FV. It also
return a few other attribut of the FV.
@param[in] Instance The index of the EFI_FW_VOL_INSTANCE.
@param[in] Lba The logical block address.
@param[out] LbaAddress On output, contains the physical starting address
of the Lba.
@param[out] LbaLength On output, contains the length of the block.
@param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the
number of consecutive blocks starting with Lba is
returned. All blocks in this range have a size of
BlockSize.
@retval EFI_SUCCESS Successfully returns.
@retval EFI_INVALID_PARAMETER Instance not found.
**/
STATIC
EFI_STATUS
FvbGetLbaAddress (
IN UINTN Instance,
IN EFI_LBA Lba,
OUT UINTN *LbaAddress,
OUT UINTN *LbaLength,
OUT UINTN *NumOfBlocks
)
{
UINT32 NumBlocks = 0;
UINT32 BlockLength = 0;
UINTN Offset;
EFI_LBA StartLba;
EFI_LBA NextLba;
EFI_FW_VOL_INSTANCE *FwhInstance;
EFI_FV_BLOCK_MAP_ENTRY *BlockMap = NULL;
//
// Find the right instance of the FVB private data.
//
FwhInstance = GetFvbInstance (Instance);
StartLba = 0;
Offset = 0;
BlockMap = &(FwhInstance->VolumeHeader.BlockMap[0]);
ASSERT (BlockMap != NULL);
//
// Parse the blockmap of the FV to find which map entry the Lba belongs to.
//
while (TRUE) {
if ( BlockMap != NULL) {
NumBlocks = BlockMap->NumBlocks;
BlockLength = BlockMap->Length;
}
if ( NumBlocks == 0 || BlockLength == 0) {
return EFI_INVALID_PARAMETER;
}
NextLba = StartLba + NumBlocks;
//
// The map entry found.
//
if (Lba >= StartLba && Lba < NextLba) {
Offset = Offset + (UINTN)MultU64x32((Lba - StartLba), BlockLength);
if ( LbaAddress && FwhInstance ) {
*LbaAddress = FwhInstance->FvBase + Offset;
}
if (LbaLength ) {
*LbaLength = BlockLength;
}
if (NumOfBlocks ) {
*NumOfBlocks = (UINTN)(NextLba - Lba);
}
return EFI_SUCCESS;
}
StartLba = NextLba;
Offset = Offset + NumBlocks * BlockLength;
BlockMap++;
}
}
/**
Reads specified number of bytes into a buffer from the specified block.
@param[in] Instance The FV instance to be read from.
@param[in] Lba The logical block address to be read from.
@param[in] BlockOffset Offset into the block at which to begin reading.
@param[in] NumBytes Pointer that on input contains the total size of
the buffer. On output, it contains the total number
of bytes read.
@param[in] Buffer Pointer to a caller allocated buffer that will be
used to hold the data read.
@retval EFI_SUCCESS The firmware volume was read successfully and
contents are in Buffer.
@retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,
NumBytes contains the total number of bytes returned
in Buffer.
@retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state.
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be read.
@retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL.
**/
STATIC
EFI_STATUS
FvbReadBlock (
IN UINTN Instance,
IN EFI_LBA Lba,
IN UINTN BlockOffset,
IN OUT UINTN *NumBytes,
IN UINT8 *Buffer
)
{
EFI_FVB_ATTRIBUTES_2 Attributes;
UINTN LbaAddress;
UINTN LbaLength;
EFI_STATUS Status;
if ( (NumBytes == NULL) || (Buffer == NULL)) {
return (EFI_INVALID_PARAMETER);
}
if (*NumBytes == 0) {
return (EFI_INVALID_PARAMETER);
}
Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);
if (EFI_ERROR(Status)) {
return Status;
}
Attributes = FvbGetVolumeAttributes (Instance);
if ( (Attributes & EFI_FVB2_READ_STATUS) == 0) {
return (EFI_ACCESS_DENIED);
}
if (BlockOffset > LbaLength) {
return (EFI_INVALID_PARAMETER);
}
if (LbaLength < ( *NumBytes + BlockOffset ) ) {
*NumBytes = (UINT32) (LbaLength - BlockOffset);
Status = EFI_BAD_BUFFER_SIZE;
}
LibFvbFlashDeviceRead (LbaAddress + BlockOffset, NumBytes, Buffer);
return Status;
}
/**
Writes specified number of bytes from the input buffer to the block.
@param[in] Instance The FV instance to be written to.
@param[in] Lba The starting logical block index to write to.
@param[in] BlockOffset Offset into the block at which to begin writing.
@param[in] NumBytes Pointer that on input contains the total size of
the buffer. On output, it contains the total number
of bytes actually written.
@param[in] Buffer Pointer to a caller allocated buffer that contains
the source for the write.
@retval EFI_SUCCESS The firmware volume was written successfully.
@retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,
NumBytes contains the total number of bytes
actually writte.
@retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be written.
@retval EFI_INVALID_PARAMETER Instance not found, or NumBytes, Buffer are NULL.
**/
EFI_STATUS
FvbWriteBlock (
IN UINTN Instance,
IN EFI_LBA Lba,
IN UINTN BlockOffset,
IN OUT UINTN *NumBytes,
IN UINT8 *Buffer
)
{
EFI_FVB_ATTRIBUTES_2 Attributes;
UINTN LbaAddress;
UINTN LbaLength;
EFI_STATUS Status;
EFI_STATUS Status1;
if ( (NumBytes == NULL) || (Buffer == NULL)) {
return (EFI_INVALID_PARAMETER);
}
if (*NumBytes == 0) {
return (EFI_INVALID_PARAMETER);
}
Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);
if (EFI_ERROR(Status)) {
return Status;
}
//
// Check if the FV is write enabled.
//
Attributes = FvbGetVolumeAttributes (Instance);
if ( (Attributes & EFI_FVB2_WRITE_STATUS) == 0) {
return (EFI_ACCESS_DENIED);
}
//
// Perform boundary checks and adjust NumBytes.
//
if (BlockOffset > LbaLength) {
return (EFI_INVALID_PARAMETER);
}
if ( LbaLength < ( *NumBytes + BlockOffset ) ) {
DEBUG ((EFI_D_ERROR,
"FvWriteBlock: Reducing Numbytes from 0x%x to 0x%x\n",
*NumBytes,
(UINT32)(LbaLength-BlockOffset))
);
*NumBytes = (UINT32) (LbaLength - BlockOffset);
Status = EFI_BAD_BUFFER_SIZE;
}
LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);
Status1 = LibFvbFlashDeviceWrite (LbaAddress + BlockOffset, NumBytes, Buffer);
LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);
WriteBackInvalidateDataCacheRange ((VOID *) (LbaAddress + BlockOffset), *NumBytes);
if ( EFI_ERROR (Status1) ) {
return Status1;
}
return Status;
}
/**
Erases and initializes a firmware volume block.
@param[in] Instance The FV instance to be erased.
@param[in] Lba The logical block index to be erased.
@retval EFI_SUCCESS The erase request was successfully completed.
@retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be written. Firmware device may have been
partially erased.
@retval EFI_INVALID_PARAMETER Instance not found.
**/
EFI_STATUS
FvbEraseBlock (
IN UINTN Instance,
IN EFI_LBA Lba
)
{
EFI_FVB_ATTRIBUTES_2 Attributes;
UINTN LbaAddress;
UINTN LbaLength;
EFI_STATUS Status;
//
// Check if the FV is write enabled.
//
Attributes = FvbGetVolumeAttributes (Instance);
if( (Attributes & EFI_FVB2_WRITE_STATUS) == 0) {
return (EFI_ACCESS_DENIED);
}
//
// Get the starting address of the block for erase.
//
Status = FvbGetLbaAddress (Instance, Lba, &LbaAddress, &LbaLength, NULL);
if (EFI_ERROR(Status)) {
return Status;
}
LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, FALSE);
Status = LibFvbFlashDeviceBlockErase (LbaAddress, LbaLength);
LibFvbFlashDeviceBlockLock (LbaAddress, LbaLength, TRUE);
WriteBackInvalidateDataCacheRange ((VOID *) LbaAddress, LbaLength);
return Status;
}
/**
Modifies the current settings of the firmware volume according to the
input parameter, and returns the new setting of the volume.
@param[in] Instance The FV instance whose attributes is going to be
modified.
@param[in] Attributes On input, it is a pointer to EFI_FVB_ATTRIBUTES_2
containing the desired firmware volume settings.
On successful return, it contains the new settings
of the firmware volume.
@retval EFI_SUCCESS Successfully returns.
@retval EFI_ACCESS_DENIED The volume setting is locked and cannot be modified.
@retval EFI_INVALID_PARAMETER Instance not found, or The attributes requested are
in conflict with the capabilities as declared in the
firmware volume header.
**/
STATIC
EFI_STATUS
FvbSetVolumeAttributes (
IN UINTN Instance,
IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
)
{
EFI_FW_VOL_INSTANCE *FwhInstance = NULL;
EFI_FVB_ATTRIBUTES_2 OldAttributes = 0;
EFI_FVB_ATTRIBUTES_2 *AttribPtr = NULL;
EFI_FVB_ATTRIBUTES_2 UnchangedAttributes;
UINT32 Capabilities;
UINT32 OldStatus, NewStatus;
//
// Find the right instance of the FVB private data.
//
FwhInstance = GetFvbInstance (Instance);
AttribPtr = (EFI_FVB_ATTRIBUTES_2 *) & (FwhInstance->VolumeHeader.Attributes);
ASSERT (AttribPtr != NULL);
if ( AttribPtr != NULL) {
OldAttributes = *AttribPtr;
}
Capabilities = OldAttributes & EFI_FVB2_CAPABILITIES;
OldStatus = OldAttributes & EFI_FVB2_STATUS;
NewStatus = *Attributes & EFI_FVB2_STATUS;
UnchangedAttributes = EFI_FVB2_READ_DISABLED_CAP | \
EFI_FVB2_READ_ENABLED_CAP | \
EFI_FVB2_WRITE_DISABLED_CAP | \
EFI_FVB2_WRITE_ENABLED_CAP | \
EFI_FVB2_LOCK_CAP | \
EFI_FVB2_STICKY_WRITE | \
EFI_FVB2_MEMORY_MAPPED | \
EFI_FVB2_ERASE_POLARITY | \
EFI_FVB2_READ_LOCK_CAP | \
EFI_FVB2_WRITE_LOCK_CAP | \
EFI_FVB2_ALIGNMENT;
//
// Some attributes of FV is read only can *not* be set.
//
if ((OldAttributes & UnchangedAttributes) ^ (*Attributes & UnchangedAttributes)) {
return EFI_INVALID_PARAMETER;
}
//
// If firmware volume is locked, no status bit can be updated.
//
if ( OldAttributes & EFI_FVB2_LOCK_STATUS ) {
if ( OldStatus ^ NewStatus ) {
return EFI_ACCESS_DENIED;
}
}
//
// Test read disable.
//
if ((Capabilities & EFI_FVB2_READ_DISABLED_CAP) == 0) {
if ((NewStatus & EFI_FVB2_READ_STATUS) == 0) {
return EFI_INVALID_PARAMETER;
}
}
//
// Test read enable.
//
if ((Capabilities & EFI_FVB2_READ_ENABLED_CAP) == 0) {
if (NewStatus & EFI_FVB2_READ_STATUS) {
return EFI_INVALID_PARAMETER;
}
}
//
// Test write disable.
//
if ((Capabilities & EFI_FVB2_WRITE_DISABLED_CAP) == 0) {
if ((NewStatus & EFI_FVB2_WRITE_STATUS) == 0) {
return EFI_INVALID_PARAMETER;
}
}
//
// Test write enable.
//
if ((Capabilities & EFI_FVB2_WRITE_ENABLED_CAP) == 0) {
if (NewStatus & EFI_FVB2_WRITE_STATUS) {
return EFI_INVALID_PARAMETER;
}
}
//
// Test lock.
//
if ((Capabilities & EFI_FVB2_LOCK_CAP) == 0) {
if (NewStatus & EFI_FVB2_LOCK_STATUS) {
return EFI_INVALID_PARAMETER;
}
}
*AttribPtr = (*AttribPtr) & (0xFFFFFFFF & (~EFI_FVB2_STATUS));
*AttribPtr = (*AttribPtr) | NewStatus;
*Attributes = *AttribPtr;
return EFI_SUCCESS;
}
//
// FVB protocol APIs.
//
/**
Retrieves the physical address of the device.
@param[in] This A pointer to EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL.
@param[out] Address Output buffer containing the address.
retval EFI_SUCCESS The function always return successfully.
**/
EFI_STATUS
EFIAPI
FvbProtocolGetPhysicalAddress (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
OUT EFI_PHYSICAL_ADDRESS *Address
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
EFI_FW_VOL_INSTANCE *FvInstance;
FvbDevice = FVB_DEVICE_FROM_THIS (This);
FvInstance = GetFvbInstance(FvbDevice->Instance);
if (FvInstance != NULL) {
*Address = FvInstance->FvBase;
}
return EFI_SUCCESS;
}
/**
Retrieve the size of a logical block.
@param[in] This Calling context.
@param[in] Lba Indicates which block to return the size for.
@param[out] BlockSize A pointer to a caller allocated UINTN in which
the size of the block is returned.
@param[out] NumOfBlocks A pointer to a caller allocated UINTN in which the
number of consecutive blocks starting with Lba is
returned. All blocks in this range have a size of
BlockSize.
@retval EFI_SUCCESS The function always return successfully.
**/
EFI_STATUS
EFIAPI
FvbProtocolGetBlockSize (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
IN EFI_LBA Lba,
OUT UINTN *BlockSize,
OUT UINTN *NumOfBlocks
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
DEBUG((EFI_D_INFO,
"FvbProtocolGetBlockSize: Lba: 0x%lx BlockSize: 0x%x NumOfBlocks: 0x%x\n",
Lba,
BlockSize,
NumOfBlocks)
);
FvbDevice = FVB_DEVICE_FROM_THIS (This);
return FvbGetLbaAddress (
FvbDevice->Instance,
Lba,
NULL,
BlockSize,
NumOfBlocks
);
}
/**
Retrieves Volume attributes. No polarity translations are done.
@param[in] This Calling context.
@param[out] Attributes Output buffer which contains attributes.
@retval EFI_SUCCESS The function always return successfully.
**/
EFI_STATUS
EFIAPI
FvbProtocolGetAttributes (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
OUT EFI_FVB_ATTRIBUTES_2 *Attributes
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
FvbDevice = FVB_DEVICE_FROM_THIS (This);
*Attributes = FvbGetVolumeAttributes (FvbDevice->Instance);
DEBUG ((EFI_D_INFO,
"FvbProtocolGetAttributes: This: 0x%x Attributes: 0x%x\n",
This,
*Attributes)
);
return EFI_SUCCESS;
}
/**
Sets Volume attributes. No polarity translations are done.
@param[in] This Calling context.
@param[out] Attributes Output buffer which contains attributes.
@retval EFI_SUCCESS The function always return successfully.
**/
EFI_STATUS
EFIAPI
FvbProtocolSetAttributes (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
IN OUT EFI_FVB_ATTRIBUTES_2 *Attributes
)
{
EFI_STATUS Status;
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
DEBUG((EFI_D_INFO,
"FvbProtocolSetAttributes: Before SET - This: 0x%x Attributes: 0x%x\n",
This,
*Attributes)
);
FvbDevice = FVB_DEVICE_FROM_THIS (This);
Status = FvbSetVolumeAttributes (FvbDevice->Instance, Attributes);
DEBUG((EFI_D_INFO,
"FvbProtocolSetAttributes: After SET - This: 0x%x Attributes: 0x%x\n",
This,
*Attributes)
);
return Status;
}
/**
The EraseBlock() function erases one or more blocks as denoted by the
variable argument list. The entire parameter list of blocks must be verified
prior to erasing any blocks. If a block is requested that does not exist
within the associated firmware volume (it has a larger index than the last
block of the firmware volume), the EraseBlock() function must return
EFI_INVALID_PARAMETER without modifying the contents of the firmware volume.
@param[in] This Calling context.
@param[in] ... Starting LBA followed by Number of Lba to erase.
a -1 to terminate the list.
@retval EFI_SUCCESS The erase request was successfully completed.
@retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be written. Firmware device may have been
partially erased.
**/
EFI_STATUS
EFIAPI
FvbProtocolEraseBlocks (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
...
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
EFI_FW_VOL_INSTANCE *FwhInstance;
UINTN NumOfBlocks = 0;
VA_LIST args;
EFI_LBA StartingLba;
UINTN NumOfLba;
EFI_STATUS Status;
DEBUG((EFI_D_INFO, "FvbProtocolEraseBlocks: \n"));
FvbDevice = FVB_DEVICE_FROM_THIS (This);
FwhInstance = GetFvbInstance (FvbDevice->Instance);
if (FwhInstance != NULL) {
NumOfBlocks = FwhInstance->NumOfBlocks;
}
VA_START (args, This);
do {
StartingLba = VA_ARG (args, EFI_LBA);
if ( StartingLba == EFI_LBA_LIST_TERMINATOR ) {
break;
}
NumOfLba = VA_ARG (args, UINTN);
//
// Check input parameters.
//
if (NumOfLba == 0) {
VA_END (args);
return EFI_INVALID_PARAMETER;
}
if ( ( StartingLba + NumOfLba ) > NumOfBlocks ) {
return EFI_INVALID_PARAMETER;
}
} while ( 1 );
VA_END (args);
VA_START (args, This);
do {
StartingLba = VA_ARG (args, EFI_LBA);
if (StartingLba == EFI_LBA_LIST_TERMINATOR) {
break;
}
NumOfLba = VA_ARG (args, UINTN);
while ( NumOfLba > 0 ) {
Status = FvbEraseBlock (FvbDevice->Instance, StartingLba);
if ( EFI_ERROR(Status)) {
VA_END (args);
return Status;
}
StartingLba ++;
NumOfLba --;
}
} while ( 1 );
VA_END (args);
return EFI_SUCCESS;
}
/**
Writes data beginning at Lba:Offset from FV. The write terminates either
when *NumBytes of data have been written, or when a block boundary is
reached. *NumBytes is updated to reflect the actual number of bytes
written. The write opertion does not include erase. This routine will
attempt to write only the specified bytes. If the writes do not stick,
it will return an error.
@param[in] This Calling context.
@param[in] Lba Block in which to begin write.
@param[in] Offset Offset in the block at which to begin write.
@param[in,out] NumBytes On input, indicates the requested write size. On
output, indicates the actual number of bytes written
@param[in] Buffer Buffer containing source data for the write.
@retval EFI_SUCCESS The firmware volume was written successfully.
@retval EFI_BAD_BUFFER_SIZE Write attempted across a LBA boundary. On output,
NumBytes contains the total number of bytes
actually written.
@retval EFI_ACCESS_DENIED The firmware volume is in the WriteDisabled state.
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be written.
@retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL.
**/
EFI_STATUS
EFIAPI
FvbProtocolWrite (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
IN EFI_LBA Lba,
IN UINTN Offset,
IN OUT UINTN *NumBytes,
IN UINT8 *Buffer
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
FvbDevice = FVB_DEVICE_FROM_THIS (This);
DEBUG((EFI_D_INFO,
"FvbProtocolWrite: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x\n",
Lba,
Offset,
*NumBytes,
Buffer)
);
return FvbWriteBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);
}
/**
Reads data beginning at Lba:Offset from FV. The Read terminates either
when *NumBytes of data have been read, or when a block boundary is
reached. *NumBytes is updated to reflect the actual number of bytes
written. The write opertion does not include erase. This routine will
attempt to write only the specified bytes. If the writes do not stick,
it will return an error.
@param[in] This Calling context.
@param[in] Lba Block in which to begin write.
@param[in] Offset Offset in the block at which to begin write
@param[in,out] NumBytes On input, indicates the requested write size. On
output, indicates the actual number of bytes written.
@param[in] Buffer Buffer containing source data for the write.
Returns:
@retval EFI_SUCCESS The firmware volume was read successfully and
contents are in Buffer.
@retval EFI_BAD_BUFFER_SIZE Read attempted across a LBA boundary. On output,
NumBytes contains the total number of bytes returned
in Buffer.
@retval EFI_ACCESS_DENIED The firmware volume is in the ReadDisabled state
@retval EFI_DEVICE_ERROR The block device is not functioning correctly and
could not be read.
@retval EFI_INVALID_PARAMETER NumBytes or Buffer are NULL.
**/
EFI_STATUS
EFIAPI
FvbProtocolRead (
IN CONST EFI_FIRMWARE_VOLUME_BLOCK_PROTOCOL *This,
IN EFI_LBA Lba,
IN UINTN Offset,
IN OUT UINTN *NumBytes,
OUT UINT8 *Buffer
)
{
EFI_FW_VOL_BLOCK_DEVICE *FvbDevice;
EFI_STATUS Status;
FvbDevice = FVB_DEVICE_FROM_THIS (This);
Status = FvbReadBlock (FvbDevice->Instance, Lba, Offset, NumBytes, Buffer);
DEBUG((EFI_D_INFO,
"FvbProtocolRead: Lba: 0x%lx Offset: 0x%x NumBytes: 0x%x, Buffer: 0x%x\n",
Lba,
Offset,
*NumBytes,
Buffer)
);
return Status;
}
/**
Check the integrity of firmware volume header.
@param[in] FwVolHeader A pointer to a firmware volume header.
@retval TRUE The firmware volume is consistent.
@retval FALSE The firmware volume has corrupted.
**/
BOOLEAN
IsFvHeaderValid (
IN EFI_PHYSICAL_ADDRESS FvBase,
IN CONST EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader
)
{
if (FvBase == PcdGet32(PcdFlashNvStorageVariableBase)) {
if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiSystemNvDataFvGuid, sizeof(EFI_GUID)) != 0 ) {
return FALSE;
}
} else {
if (CompareMem (&FwVolHeader->FileSystemGuid, &gEfiFirmwareFileSystem2Guid, sizeof(EFI_GUID)) != 0 ) {
return FALSE;
}
}
if ( (FwVolHeader->Revision != EFI_FVH_REVISION) ||
(FwVolHeader->Signature != EFI_FVH_SIGNATURE) ||
(FwVolHeader->FvLength == ((UINTN) -1)) ||
((FwVolHeader->HeaderLength & 0x01 ) !=0) ) {
return FALSE;
}
if (CalculateCheckSum16 ((UINT16 *) FwVolHeader, FwVolHeader->HeaderLength) != 0) {
return FALSE;
}
return TRUE;
}
/**
The function does the necessary initialization work for
Firmware Volume Block Driver.
@retval EFI_SUCCESS This funtion always return EFI_SUCCESS.
It will ASSERT on errors.
**/
EFI_STATUS
FvbInitialize (
VOID
)
{
EFI_FW_VOL_INSTANCE *FwhInstance;
EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
EFI_FIRMWARE_VOLUME_HEADER *FvHeader;
EFI_FV_BLOCK_MAP_ENTRY *PtrBlockMapEntry;
EFI_PHYSICAL_ADDRESS BaseAddress;
EFI_STATUS Status;
UINTN BufferSize;
UINTN TmpHeaderLength;
UINTN Idx;
UINT32 MaxLbaSize;
//
// Calculate the total size for all firmware volume block instances.
//
BufferSize = 0;
for (Idx = 0; Idx < 1; Idx++) {
FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) mPlatformFvBaseAddress[Idx];
BufferSize += (FvHeader->HeaderLength +
sizeof (EFI_FW_VOL_INSTANCE) -
sizeof (EFI_FIRMWARE_VOLUME_HEADER)
);
}
mFvbModuleGlobal.FvInstance = (EFI_FW_VOL_INSTANCE *) AllocateRuntimeZeroPool (BufferSize);
ASSERT (NULL != mFvbModuleGlobal.FvInstance);
MaxLbaSize = 0;
FwhInstance = mFvbModuleGlobal.FvInstance;
mFvbModuleGlobal.NumFv = 0;
for (Idx = 0; Idx < 1; Idx++) {
BaseAddress = mPlatformFvBaseAddress[Idx];
FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *) (UINTN) BaseAddress;
if (!IsFvHeaderValid (BaseAddress, FwVolHeader)) {
//
// If not valid, get FvbInfo from the information carried in
// FVB driver.
//
DEBUG ((EFI_D_ERROR, "Fvb: FV header @ 0x%lx invalid\n", BaseAddress));
Status = GetFvbInfo (BaseAddress, &FwVolHeader);
ASSERT_EFI_ERROR(Status);
//
// Write back a healthy FV header.
//
DEBUG ((EFI_D_ERROR, "FwBlockService.c: Writing back healthy FV header\n"));
LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FwVolHeader->BlockMap->Length, FALSE);
Status = LibFvbFlashDeviceBlockErase ((UINTN)BaseAddress, FwVolHeader->BlockMap->Length);
TmpHeaderLength = (UINTN) FwVolHeader->HeaderLength;
Status = LibFvbFlashDeviceWrite (
(UINTN)BaseAddress,
&TmpHeaderLength,
(UINT8 *) FwVolHeader
);
LibFvbFlashDeviceBlockLock ((UINTN)BaseAddress, FwVolHeader->BlockMap->Length, TRUE);
WriteBackInvalidateDataCacheRange (
(VOID *) (UINTN) BaseAddress,
FwVolHeader->BlockMap->Length
);
}
CopyMem (&(FwhInstance->VolumeHeader), FwVolHeader, FwVolHeader->HeaderLength);
FwVolHeader = &(FwhInstance->VolumeHeader);
FwhInstance->FvBase = (UINTN)BaseAddress;
//
// Process the block map for each FV.
//
FwhInstance->NumOfBlocks = 0;
for (PtrBlockMapEntry = FwVolHeader->BlockMap; PtrBlockMapEntry->NumBlocks != 0; PtrBlockMapEntry++) {
//
// Get the maximum size of a block.
//
if (MaxLbaSize < PtrBlockMapEntry->Length) {
MaxLbaSize = PtrBlockMapEntry->Length;
}
FwhInstance->NumOfBlocks += PtrBlockMapEntry->NumBlocks;
}
//
// Add a FVB Protocol Instance.
//
mFvbModuleGlobal.NumFv++;
InstallFvbProtocol (FwhInstance, mFvbModuleGlobal.NumFv - 1);
//
// Move on to the next FwhInstance.
//
FwhInstance = (EFI_FW_VOL_INSTANCE *) ((UINTN)((UINT8 *)FwhInstance) +
FwVolHeader->HeaderLength +
(sizeof (EFI_FW_VOL_INSTANCE) - sizeof (EFI_FIRMWARE_VOLUME_HEADER)));
}
return EFI_SUCCESS;
}
|
3392c3ebdb5216879990a830a04467cca656abf8
|
2242d5c3a5883ae2c8335c88b09b4d5ce322111f
|
/ext/llrb_insn_opt_minus.c
|
080e44d189f504c76d45f8dd1392fe0896e408ae
|
[
"Ruby",
"BSD-2-Clause"
] |
permissive
|
k0kubun/llrb
|
4d760d9cabf3de181d41887b2bcac16a4305dfd4
|
eb07299a26a6d537260b761e513f01c8823b4a9f
|
refs/heads/master
| 2023-08-15T15:43:28.635111
| 2020-11-19T05:39:49
| 2020-11-19T05:39:49
| 88,408,003
| 332
| 4
| null | 2017-09-17T16:49:21
| 2017-04-16T11:09:12
|
C
|
UTF-8
|
C
| false
| false
| 980
|
c
|
llrb_insn_opt_minus.c
|
#include "cruby.h"
VALUE
llrb_insn_opt_minus(VALUE recv, VALUE obj)
{
if (FIXNUM_2_P(recv, obj) &&
BASIC_OP_UNREDEFINED_P(BOP_MINUS, INTEGER_REDEFINED_OP_FLAG)) {
long a, b, c;
a = FIX2LONG(recv);
b = FIX2LONG(obj);
c = a - b;
return LONG2NUM(c);
}
else if (FLONUM_2_P(recv, obj) &&
BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) {
return DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj));
}
//else if (!SPECIAL_CONST_P(recv) && !SPECIAL_CONST_P(obj)) {
// if (RBASIC_CLASS(recv) == rb_cFloat && RBASIC_CLASS(obj) == rb_cFloat &&
// BASIC_OP_UNREDEFINED_P(BOP_MINUS, FLOAT_REDEFINED_OP_FLAG)) {
// val = DBL2NUM(RFLOAT_VALUE(recv) - RFLOAT_VALUE(obj));
// }
// else {
// goto INSN_LABEL(normal_dispatch);
// }
//}
else {
/* other */
//INSN_LABEL(normal_dispatch):
//PUSH(recv);
//PUSH(obj);
//CALL_SIMPLE_METHOD(recv);
return rb_funcall(recv, '-', 1, obj);
}
}
|
111f71032df214d47e6c6c96c6332221e60d787c
|
78dc9f153549b281be709227bc9897931b06260d
|
/generation/WinSDK/RecompiledIdlHeaders/um/http.h
|
1d0fe2ea59b920f6299e0cd4ff855433abd04e55
|
[
"MIT"
] |
permissive
|
microsoft/win32metadata
|
dff35b4fe904d556162cee5133294c4498f1a79a
|
5bf233f04d45f7a697e112e9639722551103eb07
|
refs/heads/main
| 2023-09-01T19:51:22.972899
| 2023-08-30T21:39:44
| 2023-08-30T21:39:44
| 270,838,404
| 1,240
| 107
|
NOASSERTION
| 2023-09-14T18:49:44
| 2020-06-08T21:52:10
|
C++
|
UTF-8
|
C
| false
| false
| 90,313
|
h
|
http.h
|
/*++
Copyright (c) 1998-2002 Microsoft Corporation
Module Name:
Http.h
Abstract:
This header corresponds to the HTTP API specification
Revision History:
--*/
#ifndef __HTTP_H__
#define __HTTP_H__
#pragma once
#include <winapifamily.h>
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
#if _WIN32_WINNT >= 0x0501
//
// HTTPAPI is available on
//
// a) WinXP SP2 and higher
// b) Windows 2003 and higher
// c) Vista and higher.
//
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
//
// Flags for HttpInitialize() and HttpTerminate().
//
//
// HTTP_INITIALIZE_SERVER - Initializes the HTTP API layer and driver for
// applications using server APIs.
//
// HTTP_INITIALIZE_CONFIG - Initializes the HTTP API layer and driver for
// applications using HTTP configuration APIs.
//
// HTTP_DEMAND_CBT - Pre-Win7, it checks HTTP API layer and driver for
// Extended Protection capabilities.
// On Win7 and above, this flag has no use and is
// present only for app-compat reasons.
// It must be combined with HTTP_INITIALIZE_SERVER.
//
// Notes -
//
// 1. These flags can be used in combination.
//
// 2. HttpTerminate() must be called for each call to HttpInitialize() made
// with each flag set when invoking HttpInitialize. For example, one
// could make two calls to HttpInitialize() setting HTTP_INITIALIZE_SERVER
// the first time and HTTP_INITIALIZE_CONFIG the second time. One call
// to HttpTerminate() with both flags set suffices to clean up both
// calls to HttpInitialize().
//
#define HTTP_INITIALIZE_SERVER 0x00000001
#define HTTP_INITIALIZE_CONFIG 0x00000002
#define HTTP_DEMAND_CBT 0x00000004
#if _WIN32_WINNT >= 0x0600
//
// Following section defines the properties supported by the
// server side HTTP API.
//
typedef enum _HTTP_SERVER_PROPERTY
{
//
// Used for enabling server side authentication.
//
HttpServerAuthenticationProperty = 0,
//
// Used for enabling logging.
//
HttpServerLoggingProperty = 1,
//
// Used for setting QoS properties.
//
HttpServerQosProperty = 2,
//
// Used for configuring timeouts.
//
HttpServerTimeoutsProperty = 3,
//
// Used for limiting request queue lengths.
//
HttpServerQueueLengthProperty = 4,
//
// Used for manipulating the state.
//
HttpServerStateProperty = 5,
//
// Used for modifying the verbosity level of 503 type responses
// generated by server side API.
//
HttpServer503VerbosityProperty = 6,
//
// Used for manipulating Url Group to Request Queue association.
//
HttpServerBindingProperty = 7,
//
// Extended authentication property.
//
HttpServerExtendedAuthenticationProperty = 8,
//
// Listening endpoint property.
//
HttpServerListenEndpointProperty = 9,
//
// Authentication channel binding property
//
HttpServerChannelBindProperty = 10,
//
// IP Protection level policy for a Url Group.
//
HttpServerProtectionLevelProperty = 11,
//
// Used for manipulating Url Group to Delegate Request Queue association.
//
HttpServerDelegationProperty = 16,
} HTTP_SERVER_PROPERTY, *PHTTP_SERVER_PROPERTY;
#define HTTP_MAX_SERVER_QUEUE_LENGTH 0x7FFFFFFF
#define HTTP_MIN_SERVER_QUEUE_LENGTH 1
//
// Generic property flags. Each structure defining a property info typically
// contain an element of this type.
//
typedef struct _HTTP_PROPERTY_FLAGS
{
ULONG Present:1;
} HTTP_PROPERTY_FLAGS, *PHTTP_PROPERTY_FLAGS;
//
// Enabled state.
//
typedef enum _HTTP_ENABLED_STATE
{
HttpEnabledStateActive,
HttpEnabledStateInactive,
} HTTP_ENABLED_STATE, *PHTTP_ENABLED_STATE;
typedef struct _HTTP_STATE_INFO
{
HTTP_PROPERTY_FLAGS Flags;
HTTP_ENABLED_STATE State;
} HTTP_STATE_INFO, *PHTTP_STATE_INFO;
//
// Defines the verbosity level for a request queue which will be used
// when sending "503 - Service Unavailable" type error responses. Note that
// this setting only affects the error responses generated internally
// by HTTPAPI.
//
typedef enum _HTTP_503_RESPONSE_VERBOSITY
{
//
// Instead of sending a 503 response, the connection will be reset.
// This is the default behavior.
//
Http503ResponseVerbosityBasic,
//
// Will send a 503 w/ a generic reason phrase.
//
Http503ResponseVerbosityLimited,
//
// Will send a 503 w/ a detailed reason phrase.
//
Http503ResponseVerbosityFull
} HTTP_503_RESPONSE_VERBOSITY, *PHTTP_503_RESPONSE_VERBOSITY;
//
// Network QoS related.
//
typedef enum _HTTP_QOS_SETTING_TYPE
{
HttpQosSettingTypeBandwidth,
HttpQosSettingTypeConnectionLimit,
HttpQosSettingTypeFlowRate
} HTTP_QOS_SETTING_TYPE, *PHTTP_QOS_SETTING_TYPE;
typedef struct _HTTP_QOS_SETTING_INFO
{
HTTP_QOS_SETTING_TYPE QosType;
PVOID QosSetting;
} HTTP_QOS_SETTING_INFO, *PHTTP_QOS_SETTING_INFO;
typedef struct _HTTP_CONNECTION_LIMIT_INFO
{
HTTP_PROPERTY_FLAGS Flags;
ULONG MaxConnections;
} HTTP_CONNECTION_LIMIT_INFO, *PHTTP_CONNECTION_LIMIT_INFO;
typedef struct _HTTP_BANDWIDTH_LIMIT_INFO
{
HTTP_PROPERTY_FLAGS Flags;
ULONG MaxBandwidth;
} HTTP_BANDWIDTH_LIMIT_INFO, *PHTTP_BANDWIDTH_LIMIT_INFO;
typedef struct _HTTP_FLOWRATE_INFO
{
HTTP_PROPERTY_FLAGS Flags;
ULONG MaxBandwidth;
ULONG MaxPeakBandwidth;
ULONG BurstSize;
} HTTP_FLOWRATE_INFO, *PHTTP_FLOWRATE_INFO;
//
// Bandwidth throttling limit can not be set lower than the following
// number. The value is in bytes/sec.
//
#define HTTP_MIN_ALLOWED_BANDWIDTH_THROTTLING_RATE ((ULONG)1024)
//
// Distinguished value for bandwidth, connection limits and logging rollover
// size indicating "no limit".
//
#define HTTP_LIMIT_INFINITE ((ULONG)-1)
//
// Timeout information.
//
//
// For manipulating global timeout settings.
// These timers run when connection does not belong to any application.
// Value zero is not allowed for driver wide timeout settings.
//
typedef enum _HTTP_SERVICE_CONFIG_TIMEOUT_KEY
{
IdleConnectionTimeout = 0,
HeaderWaitTimeout
} HTTP_SERVICE_CONFIG_TIMEOUT_KEY, *PHTTP_SERVICE_CONFIG_TIMEOUT_KEY;
typedef USHORT HTTP_SERVICE_CONFIG_TIMEOUT_PARAM,
*PHTTP_SERVICE_CONFIG_TIMEOUT_PARAM;
//
// To set a timeout value use the set structure. To query/delete use the key
// directly. When you query a timeout value the output buffer must be exactly
// the sizeof param.
//
typedef struct _HTTP_SERVICE_CONFIG_TIMEOUT_SET
{
HTTP_SERVICE_CONFIG_TIMEOUT_KEY KeyDesc;
HTTP_SERVICE_CONFIG_TIMEOUT_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_TIMEOUT_SET, *PHTTP_SERVICE_CONFIG_TIMEOUT_SET;
//
// For manipulating application specific timeout settings.
// These timers run when there's a request being processed on a connection
// and HTTPAPI has already associated the request with an application.
// Setting a timeout value to zero will cause HTTPAPI to revert to default.
//
typedef struct _HTTP_TIMEOUT_LIMIT_INFO
{
HTTP_PROPERTY_FLAGS Flags;
//
// Timeouts configured in seconds.
//
USHORT EntityBody;
USHORT DrainEntityBody;
USHORT RequestQueue;
//
// Following two timeouts are only enforced after first request on
// connection is routed to the application. These will not manipulate
// the driver wide timeouts.
//
USHORT IdleConnection;
USHORT HeaderWait;
//
// Timeouts configured in bytes/second.
// This timer can be turned off by setting it to MAXULONG.
//
ULONG MinSendRate;
} HTTP_TIMEOUT_LIMIT_INFO, *PHTTP_TIMEOUT_LIMIT_INFO;
//
// Controls config settings
//
typedef enum _HTTP_SERVICE_CONFIG_SETTING_KEY
{
HttpNone = 0,
HttpTlsThrottle
} HTTP_SERVICE_CONFIG_SETTING_KEY, *PHTTP_SERVICE_CONFIG_SETTING_KEY;
typedef ULONG HTTP_SERVICE_CONFIG_SETTING_PARAM,
*PHTTP_SERVICE_CONFIG_SETTING_PARAM;
typedef struct _HTTP_SERVICE_CONFIG_SETTING_SET
{
HTTP_SERVICE_CONFIG_SETTING_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SETTING_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_SETTING_SET, *PHTTP_SERVICE_CONFIG_SETTING_SET;
//
// Controls whether IP-based URLs should listen on the specific IP or wildcard.
//
typedef struct _HTTP_LISTEN_ENDPOINT_INFO
{
HTTP_PROPERTY_FLAGS Flags;
BOOLEAN EnableSharing;
} HTTP_LISTEN_ENDPOINT_INFO, *PHTTP_LISTEN_ENDPOINT_INFO;
typedef struct _HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS
{
USHORT DomainNameLength;
PWSTR DomainName;
USHORT RealmLength;
PWSTR Realm;
} HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS,
*PHTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS;
typedef struct _HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS
{
USHORT RealmLength;
PWSTR Realm;
} HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS,
*PHTTP_SERVER_AUTHENTICATION_BASIC_PARAMS;
//
// Definitions used for setting server side authentication property.
//
#define HTTP_AUTH_ENABLE_BASIC (0x00000001)
#define HTTP_AUTH_ENABLE_DIGEST (0x00000002)
#define HTTP_AUTH_ENABLE_NTLM (0x00000004)
#define HTTP_AUTH_ENABLE_NEGOTIATE (0x00000008)
#define HTTP_AUTH_ENABLE_KERBEROS (0x00000010)
#define HTTP_AUTH_ENABLE_ALL \
(HTTP_AUTH_ENABLE_BASIC |\
HTTP_AUTH_ENABLE_DIGEST |\
HTTP_AUTH_ENABLE_NTLM |\
HTTP_AUTH_ENABLE_NEGOTIATE |\
HTTP_AUTH_ENABLE_KERBEROS)
C_ASSERT(HTTP_AUTH_ENABLE_NEGOTIATE > HTTP_AUTH_ENABLE_NTLM);
C_ASSERT(HTTP_AUTH_ENABLE_NTLM > HTTP_AUTH_ENABLE_DIGEST);
C_ASSERT(HTTP_AUTH_ENABLE_DIGEST > HTTP_AUTH_ENABLE_BASIC);
#define HTTP_AUTH_EX_FLAG_ENABLE_KERBEROS_CREDENTIAL_CACHING (0x01)
#define HTTP_AUTH_EX_FLAG_CAPTURE_CREDENTIAL (0x02)
typedef struct _HTTP_SERVER_AUTHENTICATION_INFO
{
HTTP_PROPERTY_FLAGS Flags;
ULONG AuthSchemes;
BOOLEAN ReceiveMutualAuth;
BOOLEAN ReceiveContextHandle;
BOOLEAN DisableNTLMCredentialCaching;
UCHAR ExFlags;
HTTP_SERVER_AUTHENTICATION_DIGEST_PARAMS DigestParams;
HTTP_SERVER_AUTHENTICATION_BASIC_PARAMS BasicParams;
} HTTP_SERVER_AUTHENTICATION_INFO, *PHTTP_SERVER_AUTHENTICATION_INFO;
#if _WIN32_WINNT >= _WIN32_WINNT_WIN7
//
// Definitions for setting authentication channel binding properties
//
typedef enum _HTTP_SERVICE_BINDING_TYPE
{
HttpServiceBindingTypeNone = 0,
HttpServiceBindingTypeW,
HttpServiceBindingTypeA
} HTTP_SERVICE_BINDING_TYPE;
typedef struct _HTTP_SERVICE_BINDING_BASE
{
HTTP_SERVICE_BINDING_TYPE Type;
} HTTP_SERVICE_BINDING_BASE, *PHTTP_SERVICE_BINDING_BASE;
typedef struct _HTTP_SERVICE_BINDING_A
{
HTTP_SERVICE_BINDING_BASE Base;
PCHAR Buffer;
ULONG BufferSize;
} HTTP_SERVICE_BINDING_A, *PHTTP_SERVICE_BINDING_A;
typedef struct _HTTP_SERVICE_BINDING_W
{
HTTP_SERVICE_BINDING_BASE Base;
PWCHAR Buffer;
ULONG BufferSize;
} HTTP_SERVICE_BINDING_W, *PHTTP_SERVICE_BINDING_W;
typedef enum _HTTP_AUTHENTICATION_HARDENING_LEVELS
{
HttpAuthenticationHardeningLegacy = 0,
HttpAuthenticationHardeningMedium,
HttpAuthenticationHardeningStrict
} HTTP_AUTHENTICATION_HARDENING_LEVELS;
//
// Channel binding token verification flags.
//
#define HTTP_CHANNEL_BIND_PROXY 0x1
#define HTTP_CHANNEL_BIND_PROXY_COHOSTING 0x20
//
// Service bind verification flags
//
#define HTTP_CHANNEL_BIND_NO_SERVICE_NAME_CHECK 0x2
#define HTTP_CHANNEL_BIND_DOTLESS_SERVICE 0x4
//
// Flags triggering channel bind parameters retrieval
//
#define HTTP_CHANNEL_BIND_SECURE_CHANNEL_TOKEN 0x8
#define HTTP_CHANNEL_BIND_CLIENT_SERVICE 0x10
//
// All valid flags (mask for internal checks)
//
typedef struct _HTTP_CHANNEL_BIND_INFO
{
HTTP_AUTHENTICATION_HARDENING_LEVELS Hardening;
ULONG Flags;
PHTTP_SERVICE_BINDING_BASE * ServiceNames;
ULONG NumberOfServiceNames;
} HTTP_CHANNEL_BIND_INFO, *PHTTP_CHANNEL_BIND_INFO;
typedef struct _HTTP_REQUEST_CHANNEL_BIND_STATUS
{
PHTTP_SERVICE_BINDING_BASE ServiceName;
PUCHAR ChannelToken;
ULONG ChannelTokenSize;
ULONG Flags;
} HTTP_REQUEST_CHANNEL_BIND_STATUS, *PHTTP_REQUEST_CHANNEL_BIND_STATUS;
#endif
typedef struct _HTTP_REQUEST_TOKEN_BINDING_INFO
{
PUCHAR TokenBinding;
ULONG TokenBindingSize;
PUCHAR EKM;
ULONG EKMSize;
UCHAR KeyType;
} HTTP_REQUEST_TOKEN_BINDING_INFO, *PHTTP_REQUEST_TOKEN_BINDING_INFO;
//
// Definitions used for setting logging property.
//
//
// The known log fields recognized/supported by HTTPAPI. Following fields
// are used for W3C logging. Subset of them are also used for error
// logging.
//
#define HTTP_LOG_FIELD_DATE 0x00000001
#define HTTP_LOG_FIELD_TIME 0x00000002
#define HTTP_LOG_FIELD_CLIENT_IP 0x00000004
#define HTTP_LOG_FIELD_USER_NAME 0x00000008
#define HTTP_LOG_FIELD_SITE_NAME 0x00000010
#define HTTP_LOG_FIELD_COMPUTER_NAME 0x00000020
#define HTTP_LOG_FIELD_SERVER_IP 0x00000040
#define HTTP_LOG_FIELD_METHOD 0x00000080
#define HTTP_LOG_FIELD_URI_STEM 0x00000100
#define HTTP_LOG_FIELD_URI_QUERY 0x00000200
#define HTTP_LOG_FIELD_STATUS 0x00000400
#define HTTP_LOG_FIELD_WIN32_STATUS 0x00000800
#define HTTP_LOG_FIELD_BYTES_SENT 0x00001000
#define HTTP_LOG_FIELD_BYTES_RECV 0x00002000
#define HTTP_LOG_FIELD_TIME_TAKEN 0x00004000
#define HTTP_LOG_FIELD_SERVER_PORT 0x00008000
#define HTTP_LOG_FIELD_USER_AGENT 0x00010000
#define HTTP_LOG_FIELD_COOKIE 0x00020000
#define HTTP_LOG_FIELD_REFERER 0x00040000
#define HTTP_LOG_FIELD_VERSION 0x00080000
#define HTTP_LOG_FIELD_HOST 0x00100000
#define HTTP_LOG_FIELD_SUB_STATUS 0x00200000
#define HTTP_LOG_FIELD_STREAM_ID 0x08000000
#define HTTP_LOG_FIELD_STREAM_ID_EX 0x10000000
#define HTTP_LOG_FIELD_TRANSPORT_TYPE 0x20000000
//
// Fields that are used only for error logging.
//
#define HTTP_LOG_FIELD_CLIENT_PORT 0x00400000
#define HTTP_LOG_FIELD_URI 0x00800000
#define HTTP_LOG_FIELD_SITE_ID 0x01000000
#define HTTP_LOG_FIELD_REASON 0x02000000
#define HTTP_LOG_FIELD_QUEUE_NAME 0x04000000
#define HTTP_LOG_FIELD_CORRELATION_ID 0x40000000
#define HTTP_LOG_FIELD_FAULT_CODE 0x80000000
//
// Defines the logging type.
//
typedef enum _HTTP_LOGGING_TYPE
{
HttpLoggingTypeW3C,
HttpLoggingTypeIIS,
HttpLoggingTypeNCSA,
HttpLoggingTypeRaw
} HTTP_LOGGING_TYPE, *PHTTP_LOGGING_TYPE;
//
// Defines the rollover type for log files.
//
typedef enum _HTTP_LOGGING_ROLLOVER_TYPE
{
HttpLoggingRolloverSize,
HttpLoggingRolloverDaily,
HttpLoggingRolloverWeekly,
HttpLoggingRolloverMonthly,
HttpLoggingRolloverHourly
} HTTP_LOGGING_ROLLOVER_TYPE, *PHTTP_LOGGING_ROLLOVER_TYPE;
//
// Log file rollover size can not be set lower than the following
// limit. The value is in bytes.
//
#define HTTP_MIN_ALLOWED_LOG_FILE_ROLLOVER_SIZE ((ULONG)(1 * 1024 * 1024))
//
// Logging option flags. When used in the logging configuration alters
// some default logging behaviour.
//
// HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER - This flag is used to change
// the log file rollover to happen by local time based. By default
// log file rollovers happen by GMT time.
//
// HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION - When set the unicode fields
// will be converted to UTF8 multibytes when writting to the log
// files. When this flag is not present, the local code page
// conversion happens.
//
// HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY -
// HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY - These two flags are used to
// to do selective logging. If neither of them are present both
// types of requests will be logged. Only one these flags can be
// set at a time. They are mutually exclusive.
//
#define HTTP_LOGGING_FLAG_LOCAL_TIME_ROLLOVER (0x00000001)
#define HTTP_LOGGING_FLAG_USE_UTF8_CONVERSION (0x00000002)
#define HTTP_LOGGING_FLAG_LOG_ERRORS_ONLY (0x00000004)
#define HTTP_LOGGING_FLAG_LOG_SUCCESS_ONLY (0x00000008)
//
// Configuration structure used for setting the logging property.
//
typedef struct _HTTP_LOGGING_INFO
{
//
// Specifies whether this property exists or not.
//
HTTP_PROPERTY_FLAGS Flags;
//
// Optional logging flags.
//
ULONG LoggingFlags;
//
// Optional informatonal software directive string for W3C type logging. Not
// used for other types of logging. If nothing is provided here HTTPAPI will
// log a default string. Any arbitrary string could be used here to identify
// the application. Length cannot be greater than MAX_PATH. Lenght is in
// bytes.
//
PCWSTR SoftwareName;
USHORT SoftwareNameLength;
//
// Log file directory must be a fully qualified path.
// Length must be in number of bytes.
//
USHORT DirectoryNameLength;
PCWSTR DirectoryName;
//
// Specifies the format for the log files.
//
HTTP_LOGGING_TYPE Format;
//
// Bitmask value indicates which fields to be logged
// if the log format is set to W3C. This must be the 'bitwise or'
// of the HTTP_LOG_FIELD_... values.
//
ULONG Fields;
//
// Following fields are reserved they must be NULL and zero..
//
PVOID pExtFields;
USHORT NumOfExtFields;
//
// Reserved must be zero.
//
USHORT MaxRecordSize;
//
// Defines the rollover type for the log files.
//
HTTP_LOGGING_ROLLOVER_TYPE RolloverType;
//
// Indicates the maximum size (in bytes) after which
// the log files should be rolled over. A value of -1
// (HTTP_LIMIT_INFINITE) indicates an unlimited size.
// This value is discarded if rollover type is not set to
// HttpLoggingRolloverSize.
//
ULONG RolloverSize;
//
// Specifies the security descriptor to be applied to
// the log files and the sub-directories. If null we will
// inherit the system default. This security descriptor must
// be self-relative.
//
PSECURITY_DESCRIPTOR pSecurityDescriptor;
} HTTP_LOGGING_INFO, *PHTTP_LOGGING_INFO;
//
// Binding information.
//
typedef struct _HTTP_BINDING_INFO
{
HTTP_PROPERTY_FLAGS Flags;
HANDLE RequestQueueHandle;
} HTTP_BINDING_INFO, *PHTTP_BINDING_INFO;
#endif
#if _WIN32_WINNT >= _WIN32_WINNT_WIN7
//
// Defines the protection level types for UrlGroups.
//
typedef enum _HTTP_PROTECTION_LEVEL_TYPE
{
//
// This option will allow edge (NAT) traversed traffic, i.e. Teredo
// for the UrlGroup, unless there is an admin rule that overwrites the
// application's intend.
//
HttpProtectionLevelUnrestricted,
//
// This setting will ensure that edge (NAT) traversed traffic
// will not be allowed.
//
HttpProtectionLevelEdgeRestricted,
//
// Below type is not supported by HTTP API.
//
HttpProtectionLevelRestricted
} HTTP_PROTECTION_LEVEL_TYPE, *PHTTP_PROTECTION_LEVEL_TYPE;
//
// Controls whether the associated UrlGroup Namespace should receive
// edge traversed traffic. By default this parameter is unspecified.
//
typedef struct _HTTP_PROTECTION_LEVEL_INFO
{
HTTP_PROPERTY_FLAGS Flags;
HTTP_PROTECTION_LEVEL_TYPE Level;
} HTTP_PROTECTION_LEVEL_INFO, *PHTTP_PROTECTION_LEVEL_INFO;
#endif
#if _WIN32_WINNT >= 0x0600
//
// Definitions for request queue manipulation.
//
// These flags are used with HttpCreateRequestQueue() API.
//
// HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING - To open an existing request
// queue. The request queue name must be supplied.
//
// HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER - Creates the request queue and
// marks that the caller process is not willing to do send/receive (HTTP I/O)on
// the handle directly.
//
#define HTTP_CREATE_REQUEST_QUEUE_FLAG_OPEN_EXISTING (0x00000001)
#define HTTP_CREATE_REQUEST_QUEUE_FLAG_CONTROLLER (0x00000002)
#define HTTP_CREATE_REQUEST_QUEUE_FLAG_DELEGATION (0x00000008)
#endif // _WIN32_WINNT >= 0x0600
//
// Flags for HttpReceiveHttpRequest().
//
// HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY - Specifies that the caller would like
// any available entity body to be copied along with the protocol headers.
//
// HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY - Specifies that the caller would like
// all of the entity bodies to be copied along with the protocol headers.
//
#define HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY 0x00000001
#define HTTP_RECEIVE_REQUEST_FLAG_FLUSH_BODY 0x00000002
#if _WIN32_WINNT >= 0x0600
//
// Flags for HttpReceiveRequestEntityBody().
//
// HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER - Specifies that the
// caller would like the buffer to get filled up with entity bodies unless
// there are no more entity bodies to be copied.
//
#define HTTP_RECEIVE_REQUEST_ENTITY_BODY_FLAG_FILL_BUFFER 0x00000001
#endif // _WIN32_WINNT >= 0x0600
//
// Flags for HttpSendHttpResponse() and HttpSendResponseEntityBody().
//
// HTTP_SEND_RESPONSE_FLAG_DISCONNECT - Specifies that the network connection
// should be disconnected immediately after sending the response, overriding
// the HTTP protocol's persistent connection features, such as
// "Connection: keep-alive".
//
// HTTP_SEND_RESPONSE_FLAG_MORE_DATA - Specifies that additional entity body
// data will be sent by the caller.
//
// HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA - Specifies that a caller wants the
// response to complete as soon as possible at the cost of buffering partial
// or the entire response.
//
// HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING - Specifies that a caller wants to
// enable the TCP nagling algorithm for this particular send.
//
// HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES - Specifies that for a range request
// a full response content is passed and a caller wants HTTP API to process
// ranges properly.
//
// HTTP_SEND_RESPONSE_FLAG_OPAQUE - Specifies that the request/response is not
// HTTP compliant and all subsequent bytes should be treated as entity-body.
//
// HTTP_SEND_RESPONSE_FLAG_GOAWAY - A flag that must always be specified with
// HTTP_SEND_RESPONSE_FLAG_DISCONNECT. For pure HTTP/1.x connections, that is
// connections that don't do HTTP/2 and HTTP/3, this behaves the same as
// HTTP_SEND_RESPONSE_FLAG_DISCONNECT. For HTTP/2 and HTTP/3, this results in
// sending a GOAWAY frame and will cause the client to move to a different
// connection.
//
#define HTTP_SEND_RESPONSE_FLAG_DISCONNECT 0x00000001
#define HTTP_SEND_RESPONSE_FLAG_MORE_DATA 0x00000002
#define HTTP_SEND_RESPONSE_FLAG_BUFFER_DATA 0x00000004
#define HTTP_SEND_RESPONSE_FLAG_ENABLE_NAGLING 0x00000008
#define HTTP_SEND_RESPONSE_FLAG_PROCESS_RANGES 0x00000020
#define HTTP_SEND_RESPONSE_FLAG_OPAQUE 0x00000040
#define HTTP_SEND_RESPONSE_FLAG_GOAWAY 0x00000100
//
// Flags for HttpFlushResponseCache().
//
// HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE - Flushes the specified URL and all
// hierarchally-related sub-URLs from the response or fragment cache.
//
#define HTTP_FLUSH_RESPONSE_FLAG_RECURSIVE 0x00000001
//
// Opaque identifiers for various HTTPAPI objects.
//
typedef ULONGLONG HTTP_OPAQUE_ID, *PHTTP_OPAQUE_ID;
typedef HTTP_OPAQUE_ID HTTP_REQUEST_ID, *PHTTP_REQUEST_ID;
typedef HTTP_OPAQUE_ID HTTP_CONNECTION_ID, *PHTTP_CONNECTION_ID;
typedef HTTP_OPAQUE_ID HTTP_RAW_CONNECTION_ID, *PHTTP_RAW_CONNECTION_ID;
#if _WIN32_WINNT >= 0x0600
typedef HTTP_OPAQUE_ID HTTP_URL_GROUP_ID, *PHTTP_URL_GROUP_ID;
typedef HTTP_OPAQUE_ID HTTP_SERVER_SESSION_ID, *PHTTP_SERVER_SESSION_ID;
// #if _WIN32_WINNT >= Somevalue
typedef HTTP_OPAQUE_ID HTTP_CLIENT_REQUEST_ID, *PHTTP_CLIENT_REQUEST_ID;
typedef HTTP_OPAQUE_ID HTTP_CLIENT_CONNECTION_ID, *PHTTP_CLIENT_CONNECTION_ID;
typedef HTTP_OPAQUE_ID HTTP_CLIENT_STREAM_ID, *PHTTP_CLIENT_STREAM_ID;
#endif // _WIN32_WINNT >= 0x0600
//
// Macros for opaque identifier manipulations.
//
#define HTTP_NULL_ID (0ui64)
#define HTTP_IS_NULL_ID(pid) (HTTP_NULL_ID == *(pid))
#define HTTP_SET_NULL_ID(pid) (*(pid) = HTTP_NULL_ID)
//
// This structure defines a file byte range.
//
// If the Length field is HTTP_BYTE_RANGE_TO_EOF then the remainder of the
// file (everything after StartingOffset) is sent.
//
#define HTTP_BYTE_RANGE_TO_EOF ((ULONGLONG)-1)
typedef struct _HTTP_BYTE_RANGE
{
ULARGE_INTEGER StartingOffset;
ULARGE_INTEGER Length;
} HTTP_BYTE_RANGE, *PHTTP_BYTE_RANGE;
//
// The type for HTTP protocol version numbers.
//
#ifdef HTTP_VERSION
#undef HTTP_VERSION
#endif
typedef struct _HTTP_VERSION
{
USHORT MajorVersion;
USHORT MinorVersion;
} HTTP_VERSION, *PHTTP_VERSION;
//
// Some useful macros for HTTP protocol version manipulation.
//
#define HTTP_VERSION_UNKNOWN { 0, 0 }
#define HTTP_VERSION_0_9 { 0, 9 }
#define HTTP_VERSION_1_0 { 1, 0 }
#define HTTP_VERSION_1_1 { 1, 1 }
#define HTTP_VERSION_2_0 { 2, 0 }
#define HTTP_VERSION_3_0 { 3, 0 }
#define HTTP_SET_VERSION(version, major, minor) \
do { \
(version).MajorVersion = (major); \
(version).MinorVersion = (minor); \
} while (0)
#define HTTP_EQUAL_VERSION(version, major, minor) \
((version).MajorVersion == (major) && \
(version).MinorVersion == (minor))
#define HTTP_GREATER_VERSION(version, major, minor) \
((version).MajorVersion > (major) || \
((version).MajorVersion == (major) && \
(version).MinorVersion > (minor)))
#define HTTP_LESS_VERSION(version, major, minor) \
((version).MajorVersion < (major) || \
((version).MajorVersion == (major) && \
(version).MinorVersion < (minor)))
#define HTTP_NOT_EQUAL_VERSION(version, major, minor) \
(!HTTP_EQUAL_VERSION(version, major, minor))
#define HTTP_GREATER_EQUAL_VERSION(version, major, minor) \
(!HTTP_LESS_VERSION(version, major, minor))
#define HTTP_LESS_EQUAL_VERSION(version, major, minor) \
(!HTTP_GREATER_VERSION(version, major, minor))
//
// The enum type for HTTP Scheme.
//
typedef enum _HTTP_URI_SCHEME
{
HttpSchemeHttp,
HttpSchemeHttps,
HttpSchemeMaximum
} HTTP_SCHEME, *PHTTP_URI_SCHEME;
//
// The enum type for HTTP verbs.
//
typedef enum _HTTP_VERB
{
HttpVerbUnparsed,
HttpVerbUnknown,
HttpVerbInvalid,
HttpVerbOPTIONS,
HttpVerbGET,
HttpVerbHEAD,
HttpVerbPOST,
HttpVerbPUT,
HttpVerbDELETE,
HttpVerbTRACE,
HttpVerbCONNECT,
HttpVerbTRACK, // used by Microsoft Cluster Server for a non-logged trace
HttpVerbMOVE,
HttpVerbCOPY,
HttpVerbPROPFIND,
HttpVerbPROPPATCH,
HttpVerbMKCOL,
HttpVerbLOCK,
HttpVerbUNLOCK,
HttpVerbSEARCH,
HttpVerbMaximum
} HTTP_VERB, *PHTTP_VERB;
//
// Symbols for all HTTP/1.1 headers and other tokens. Notice request +
// response values overlap. Make sure you know which type of header array
// you are indexing.
//
// These values are used as offsets into arrays and as token values in
// HTTP_KNOWN_HEADER arrays in HTTP_REQUEST_HEADERS and HTTP_RESPONSE_HEADERS.
//
// See RFC 2616, HTTP/1.1, for further explanation of most of these headers.
//
typedef enum _HTTP_HEADER_ID
{
HttpHeaderCacheControl = 0, // general-header [section 4.5]
HttpHeaderConnection = 1, // general-header [section 4.5]
HttpHeaderDate = 2, // general-header [section 4.5]
HttpHeaderKeepAlive = 3, // general-header [not in rfc]
HttpHeaderPragma = 4, // general-header [section 4.5]
HttpHeaderTrailer = 5, // general-header [section 4.5]
HttpHeaderTransferEncoding = 6, // general-header [section 4.5]
HttpHeaderUpgrade = 7, // general-header [section 4.5]
HttpHeaderVia = 8, // general-header [section 4.5]
HttpHeaderWarning = 9, // general-header [section 4.5]
HttpHeaderAllow = 10, // entity-header [section 7.1]
HttpHeaderContentLength = 11, // entity-header [section 7.1]
HttpHeaderContentType = 12, // entity-header [section 7.1]
HttpHeaderContentEncoding = 13, // entity-header [section 7.1]
HttpHeaderContentLanguage = 14, // entity-header [section 7.1]
HttpHeaderContentLocation = 15, // entity-header [section 7.1]
HttpHeaderContentMd5 = 16, // entity-header [section 7.1]
HttpHeaderContentRange = 17, // entity-header [section 7.1]
HttpHeaderExpires = 18, // entity-header [section 7.1]
HttpHeaderLastModified = 19, // entity-header [section 7.1]
// Request Headers
HttpHeaderAccept = 20, // request-header [section 5.3]
HttpHeaderAcceptCharset = 21, // request-header [section 5.3]
HttpHeaderAcceptEncoding = 22, // request-header [section 5.3]
HttpHeaderAcceptLanguage = 23, // request-header [section 5.3]
HttpHeaderAuthorization = 24, // request-header [section 5.3]
HttpHeaderCookie = 25, // request-header [not in rfc]
HttpHeaderExpect = 26, // request-header [section 5.3]
HttpHeaderFrom = 27, // request-header [section 5.3]
HttpHeaderHost = 28, // request-header [section 5.3]
HttpHeaderIfMatch = 29, // request-header [section 5.3]
HttpHeaderIfModifiedSince = 30, // request-header [section 5.3]
HttpHeaderIfNoneMatch = 31, // request-header [section 5.3]
HttpHeaderIfRange = 32, // request-header [section 5.3]
HttpHeaderIfUnmodifiedSince = 33, // request-header [section 5.3]
HttpHeaderMaxForwards = 34, // request-header [section 5.3]
HttpHeaderProxyAuthorization = 35, // request-header [section 5.3]
HttpHeaderReferer = 36, // request-header [section 5.3]
HttpHeaderRange = 37, // request-header [section 5.3]
HttpHeaderTe = 38, // request-header [section 5.3]
HttpHeaderTranslate = 39, // request-header [webDAV, not in rfc 2518]
HttpHeaderUserAgent = 40, // request-header [section 5.3]
HttpHeaderRequestMaximum = 41,
// Response Headers
HttpHeaderAcceptRanges = 20, // response-header [section 6.2]
HttpHeaderAge = 21, // response-header [section 6.2]
HttpHeaderEtag = 22, // response-header [section 6.2]
HttpHeaderLocation = 23, // response-header [section 6.2]
HttpHeaderProxyAuthenticate = 24, // response-header [section 6.2]
HttpHeaderRetryAfter = 25, // response-header [section 6.2]
HttpHeaderServer = 26, // response-header [section 6.2]
HttpHeaderSetCookie = 27, // response-header [not in rfc]
HttpHeaderVary = 28, // response-header [section 6.2]
HttpHeaderWwwAuthenticate = 29, // response-header [section 6.2]
HttpHeaderResponseMaximum = 30,
HttpHeaderMaximum = 41
} HTTP_HEADER_ID, *PHTTP_HEADER_ID;
//
// Structure defining format of a known HTTP header.
// Name is from HTTP_HEADER_ID.
//
typedef struct _HTTP_KNOWN_HEADER
{
USHORT RawValueLength; // in bytes not including the NUL
PCSTR pRawValue;
} HTTP_KNOWN_HEADER, *PHTTP_KNOWN_HEADER;
//
// Structure defining format of an unknown header.
//
typedef struct _HTTP_UNKNOWN_HEADER
{
USHORT NameLength; // in bytes not including the NUL
USHORT RawValueLength; // in bytes not including the NUL
PCSTR pName; // The header name (minus the ':' character)
PCSTR pRawValue; // The header value
} HTTP_UNKNOWN_HEADER, *PHTTP_UNKNOWN_HEADER;
#if _WIN32_WINNT >= 0x0600
//
// Log fields data structure is used for logging a request. This structure must
// be provided along with an HttpSendHttpResponse or HttpSendResponseEntityBody
// call that concludes the send.
//
// Base structure is for future versioning.
typedef enum _HTTP_LOG_DATA_TYPE
{
HttpLogDataTypeFields = 0
} HTTP_LOG_DATA_TYPE, *PHTTP_LOG_DATA_TYPE;
// should we DECLSPEC_ALIGN(4 or 8) == DECLSPEC_POINTERALIGN?
typedef struct _HTTP_LOG_DATA
{
HTTP_LOG_DATA_TYPE Type;
} HTTP_LOG_DATA, *PHTTP_LOG_DATA;
// Current log fields data structure for of type HttpLogDataTypeFields.
typedef struct _HTTP_LOG_FIELDS_DATA
{
HTTP_LOG_DATA Base;
USHORT UserNameLength;
USHORT UriStemLength;
USHORT ClientIpLength;
USHORT ServerNameLength;
USHORT ServiceNameLength;
USHORT ServerIpLength;
USHORT MethodLength;
USHORT UriQueryLength;
USHORT HostLength;
USHORT UserAgentLength;
USHORT CookieLength;
USHORT ReferrerLength;
PWCHAR UserName;
PWCHAR UriStem;
PCHAR ClientIp;
PCHAR ServerName;
PCHAR ServiceName;
PCHAR ServerIp;
PCHAR Method;
PCHAR UriQuery;
PCHAR Host;
PCHAR UserAgent;
PCHAR Cookie;
PCHAR Referrer;
USHORT ServerPort;
USHORT ProtocolStatus;
ULONG Win32Status;
HTTP_VERB MethodNum;
USHORT SubStatus;
} HTTP_LOG_FIELDS_DATA, *PHTTP_LOG_FIELDS_DATA;
#endif // _WIN32_WINNT >= 0x0600
//
// This enum defines a data source for a particular chunk of data.
//
typedef enum _HTTP_DATA_CHUNK_TYPE
{
HttpDataChunkFromMemory,
HttpDataChunkFromFileHandle,
HttpDataChunkFromFragmentCache,
HttpDataChunkFromFragmentCacheEx,
HttpDataChunkTrailers,
HttpDataChunkMaximum
} HTTP_DATA_CHUNK_TYPE, *PHTTP_DATA_CHUNK_TYPE;
//
// This structure describes an individual data chunk.
//
typedef struct _HTTP_DATA_CHUNK
{
//
// The type of this data chunk.
//
HTTP_DATA_CHUNK_TYPE DataChunkType;
//
// The data chunk structures, one per supported data chunk type.
//
union
{
//
// From-memory data chunk.
//
struct
{
PVOID pBuffer;
ULONG BufferLength;
} FromMemory;
//
// From-file handle data chunk.
//
struct
{
HTTP_BYTE_RANGE ByteRange;
HANDLE FileHandle;
} FromFileHandle;
//
// From-fragment cache data chunk.
//
struct
{
USHORT FragmentNameLength; // in bytes not including the NUL
PCWSTR pFragmentName;
} FromFragmentCache;
//
// From-fragment cache data chunk that specifies a byte range.
//
struct
{
HTTP_BYTE_RANGE ByteRange;
PCWSTR pFragmentName; // NULL-terminated string
} FromFragmentCacheEx;
//
// Trailer data chunk that specifies Trailer headers.
//
struct
{
USHORT TrailerCount;
PHTTP_UNKNOWN_HEADER pTrailers;
} Trailers;
};
} HTTP_DATA_CHUNK, *PHTTP_DATA_CHUNK;
//
// HTTP API doesn't support 16 bit applications.
// Neither WIN32 nor _WIN64 was defined.
//
C_ASSERT(TYPE_ALIGNMENT(HTTP_DATA_CHUNK) == sizeof(ULONGLONG));
//
// Structure defining format of request headers.
//
typedef struct _HTTP_REQUEST_HEADERS
{
//
// The array of unknown HTTP headers and the number of
// entries in the array.
//
USHORT UnknownHeaderCount;
PHTTP_UNKNOWN_HEADER pUnknownHeaders;
//
// Trailers - we don't use these currently, reserved for a future release
//
USHORT TrailerCount; // Reserved, must be 0
PHTTP_UNKNOWN_HEADER pTrailers; // Reserved, must be NULL
//
// Known headers.
//
HTTP_KNOWN_HEADER KnownHeaders[HttpHeaderRequestMaximum];
} HTTP_REQUEST_HEADERS, *PHTTP_REQUEST_HEADERS;
//
// Structure defining format of response headers.
//
typedef struct _HTTP_RESPONSE_HEADERS
{
//
// The array of unknown HTTP headers and the number of
// entries in the array.
//
USHORT UnknownHeaderCount;
PHTTP_UNKNOWN_HEADER pUnknownHeaders;
//
// Trailers - we don't use these currently, reserved for a future release
//
USHORT TrailerCount; // Reserved, must be 0
PHTTP_UNKNOWN_HEADER pTrailers; // Reserved, must be NULL
//
// Known headers.
//
HTTP_KNOWN_HEADER KnownHeaders[HttpHeaderResponseMaximum];
} HTTP_RESPONSE_HEADERS, *PHTTP_RESPONSE_HEADERS;
//
// Properties that can be passed down with IOCTL_HTTP_DELEGATE_REQUEST_EX
//
typedef enum _HTTP_DELEGATE_REQUEST_PROPERTY_ID
{
DelegateRequestReservedProperty,
DelegateRequestDelegateUrlProperty,
} HTTP_DELEGATE_REQUEST_PROPERTY_ID, *PHTTP_DELEGATE_REQUEST_PROPERTY_ID;
typedef struct _HTTP_DELEGATE_REQUEST_PROPERTY_INFO
{
HTTP_DELEGATE_REQUEST_PROPERTY_ID PropertyId;
ULONG PropertyInfoLength;
PVOID PropertyInfo;
} HTTP_DELEGATE_REQUEST_PROPERTY_INFO, *PHTTP_DELEGATE_REQUEST_PROPERTY_INFO;
//
// Properties that can be passed down with IOCTL_HTTP_CREATE_REQUEST_QUEUE_EX
//
typedef enum _HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID
{
CreateRequestQueueExternalIdProperty = 1,
CreateRequestQueueMax
} HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID, *PHTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID;
typedef struct _HTTP_CREATE_REQUEST_QUEUE_PROPERTY_INFO
{
HTTP_CREATE_REQUEST_QUEUE_PROPERTY_ID PropertyId;
ULONG PropertyInfoLength;
PVOID PropertyInfo;
} HTTP_CREATE_REQUEST_QUEUE_PROPERTY_INFO, *PHTTP_CREATE_REQUEST_QUEUE_PROPERTY_INFO;
//
// Structure defining format of transport address. Use pLocalAddress->sa_family
// to determine whether this is an IPv4 address (AF_INET) or IPv6 (AF_INET6).
//
// pRemoteAddress->sa_family will be the same as pLocalAddress->sa_family.
//
// SOCKADDRs are always in network order, not host order.
//
typedef struct _HTTP_TRANSPORT_ADDRESS
{
PSOCKADDR pRemoteAddress;
PSOCKADDR pLocalAddress;
} HTTP_TRANSPORT_ADDRESS, *PHTTP_TRANSPORT_ADDRESS;
//
// Structure defining format of cooked URL.
//
typedef struct _HTTP_COOKED_URL
{
//
// Pointers overlap and point into pFullUrl. NULL if not present.
//
USHORT FullUrlLength; // in bytes not including the NUL
USHORT HostLength; // in bytes (no NUL)
USHORT AbsPathLength; // in bytes (no NUL)
USHORT QueryStringLength; // in bytes (no NUL)
PCWSTR pFullUrl; // points to "http://hostname:port/abs/.../path?query"
PCWSTR pHost; // points to the first char in the hostname
PCWSTR pAbsPath; // Points to the 3rd '/' char
PCWSTR pQueryString; // Points to the 1st '?' char or NULL
} HTTP_COOKED_URL, *PHTTP_COOKED_URL;
//
// An opaque context for URL manipulation.
//
typedef ULONGLONG HTTP_URL_CONTEXT;
#if _WIN32_WINNT >= 0x0600
//
// Optional flags for URL manipulation functions.
//
// HTTP_URL_FLAG_REMOVE_ALL : When this flag is used
// when removing a Url from a url group, regardless of
// the passed URL, all of the Urls from the url group
// will be removed.
//
#define HTTP_URL_FLAG_REMOVE_ALL 0x00000001
//
// Request Authentication related.
//
typedef enum _HTTP_AUTH_STATUS
{
HttpAuthStatusSuccess,
HttpAuthStatusNotAuthenticated,
HttpAuthStatusFailure
} HTTP_AUTH_STATUS, *PHTTP_AUTH_STATUS;
typedef enum _HTTP_REQUEST_AUTH_TYPE
{
HttpRequestAuthTypeNone = 0,
HttpRequestAuthTypeBasic,
HttpRequestAuthTypeDigest,
HttpRequestAuthTypeNTLM,
HttpRequestAuthTypeNegotiate,
HttpRequestAuthTypeKerberos
} HTTP_REQUEST_AUTH_TYPE, *PHTTP_REQUEST_AUTH_TYPE;
#endif // _WIN32_WINNT >= 0x0600
//
// SSL Client certificate information.
//
typedef struct _HTTP_SSL_CLIENT_CERT_INFO
{
ULONG CertFlags;
ULONG CertEncodedSize;
PUCHAR pCertEncoded;
HANDLE Token;
BOOLEAN CertDeniedByMapper;
} HTTP_SSL_CLIENT_CERT_INFO, *PHTTP_SSL_CLIENT_CERT_INFO;
#if _WIN32_WINNT >= _WIN32_WINNT_WIN7
//
// Flag to retrieve secure channel binding with HttpReceiveClientCertificate
//
#define HTTP_RECEIVE_SECURE_CHANNEL_TOKEN 0x1
//
// Flag to retrieve full certificate chain with HttpReceiveClientCertificate
//
#define HTTP_RECEIVE_FULL_CHAIN 0x2
#endif
//
// Data computed during SSL handshake.
//
typedef struct _HTTP_SSL_INFO
{
USHORT ServerCertKeySize;
USHORT ConnectionKeySize;
ULONG ServerCertIssuerSize;
ULONG ServerCertSubjectSize;
PCSTR pServerCertIssuer;
PCSTR pServerCertSubject;
PHTTP_SSL_CLIENT_CERT_INFO pClientCertInfo;
ULONG SslClientCertNegotiated;
} HTTP_SSL_INFO, *PHTTP_SSL_INFO;
//
// HttpRequestInfoTypeSslProtocol payload. Contains basic information about the
// SSL/TLS protocol and cipher. See SecPkgContext_ConnectionInfo documentation
// for details. This information is meant for statistics. Do not use this for
// security enforcement because by the time you check this the client may
// already have transmitted the information being protected (e.g. HTTP request
// headers).
//
typedef struct _HTTP_SSL_PROTOCOL_INFO
{
ULONG Protocol;
ULONG CipherType;
ULONG CipherStrength;
ULONG HashType;
ULONG HashStrength;
ULONG KeyExchangeType;
ULONG KeyExchangeStrength;
} HTTP_SSL_PROTOCOL_INFO, *PHTTP_SSL_PROTOCOL_INFO;
//
// List of possible sizes for which information will be retured in HTTP_REQUEST_SIZING_INFO.
//
typedef enum _HTTP_REQUEST_SIZING_TYPE
{
HttpRequestSizingTypeTlsHandshakeLeg1ClientData, // Inbound/outbound data?
HttpRequestSizingTypeTlsHandshakeLeg1ServerData,
HttpRequestSizingTypeTlsHandshakeLeg2ClientData,
HttpRequestSizingTypeTlsHandshakeLeg2ServerData,
HttpRequestSizingTypeHeaders,
HttpRequestSizingTypeMax
} HTTP_REQUEST_SIZING_TYPE, *PHTTP_REQUEST_SIZING_TYPE;
//
// Flag values for HTTP_REQUEST_SIZING_INFO
//
#define HTTP_REQUEST_SIZING_INFO_FLAG_TCP_FAST_OPEN 0x00000001
#define HTTP_REQUEST_SIZING_INFO_FLAG_TLS_SESSION_RESUMPTION 0x00000002
#define HTTP_REQUEST_SIZING_INFO_FLAG_TLS_FALSE_START 0x00000004
#define HTTP_REQUEST_SIZING_INFO_FLAG_FIRST_REQUEST 0x00000008
//
// HttpRequestInfoTypeSizeInfo payload. Contains size information filled by
// each processsing stage.
//
typedef struct _HTTP_REQUEST_SIZING_INFO
{
ULONGLONG Flags;
ULONG RequestIndex;
ULONG RequestSizingCount;
ULONGLONG RequestSizing[HttpRequestSizingTypeMax];
} HTTP_REQUEST_SIZING_INFO, *PHTTP_REQUEST_SIZING_INFO;
//
// List of possible request timings for which information will be retured in
// HTTP_REQUEST_TIMING_INFO. Not all timings apply for every request.
//
typedef enum _HTTP_REQUEST_TIMING_TYPE
{
HttpRequestTimingTypeConnectionStart,
HttpRequestTimingTypeDataStart,
HttpRequestTimingTypeTlsCertificateLoadStart,
HttpRequestTimingTypeTlsCertificateLoadEnd,
HttpRequestTimingTypeTlsHandshakeLeg1Start,
HttpRequestTimingTypeTlsHandshakeLeg1End,
HttpRequestTimingTypeTlsHandshakeLeg2Start,
HttpRequestTimingTypeTlsHandshakeLeg2End,
HttpRequestTimingTypeTlsAttributesQueryStart,
HttpRequestTimingTypeTlsAttributesQueryEnd,
HttpRequestTimingTypeTlsClientCertQueryStart,
HttpRequestTimingTypeTlsClientCertQueryEnd,
HttpRequestTimingTypeHttp2StreamStart,
HttpRequestTimingTypeHttp2HeaderDecodeStart,
HttpRequestTimingTypeHttp2HeaderDecodeEnd,
HttpRequestTimingTypeRequestHeaderParseStart,
HttpRequestTimingTypeRequestHeaderParseEnd,
HttpRequestTimingTypeRequestRoutingStart,
HttpRequestTimingTypeRequestRoutingEnd,
HttpRequestTimingTypeRequestQueuedForInspection,
HttpRequestTimingTypeRequestDeliveredForInspection,
HttpRequestTimingTypeRequestReturnedAfterInspection,
HttpRequestTimingTypeRequestQueuedForDelegation,
HttpRequestTimingTypeRequestDeliveredForDelegation,
HttpRequestTimingTypeRequestReturnedAfterDelegation,
HttpRequestTimingTypeRequestQueuedForIO,
HttpRequestTimingTypeRequestDeliveredForIO,
HttpRequestTimingTypeHttp3StreamStart,
HttpRequestTimingTypeHttp3HeaderDecodeStart,
HttpRequestTimingTypeHttp3HeaderDecodeEnd,
HttpRequestTimingTypeMax
} HTTP_REQUEST_TIMING_TYPE, *PHTTP_REQUEST_TIMING_TYPE;
//
// HttpRequestInfoTypeTiming payload. Contains information about how much
// time was spent at each request processing stage.
//
typedef struct _HTTP_REQUEST_TIMING_INFO
{
ULONG RequestTimingCount;
ULONGLONG RequestTiming[HttpRequestTimingTypeMax];
} HTTP_REQUEST_TIMING_INFO, *PHTTP_REQUEST_TIMING_INFO;
#if _WIN32_WINNT >= 0x0600
//
// Generic request information type.
//
typedef enum _HTTP_REQUEST_INFO_TYPE
{
HttpRequestInfoTypeAuth,
HttpRequestInfoTypeChannelBind,
HttpRequestInfoTypeSslProtocol,
HttpRequestInfoTypeSslTokenBindingDraft,
HttpRequestInfoTypeSslTokenBinding,
HttpRequestInfoTypeRequestTiming,
HttpRequestInfoTypeTcpInfoV0,
HttpRequestInfoTypeRequestSizing,
HttpRequestInfoTypeQuicStats,
HttpRequestInfoTypeTcpInfoV1
} HTTP_REQUEST_INFO_TYPE, *PHTTP_REQUEST_INFO_TYPE;
typedef struct _HTTP_REQUEST_INFO
{
HTTP_REQUEST_INFO_TYPE InfoType;
ULONG InfoLength;
PVOID pInfo;
} HTTP_REQUEST_INFO, *PHTTP_REQUEST_INFO;
#ifndef __SECSTATUS_DEFINED__
typedef LONG SECURITY_STATUS;
#define __SECSTATUS_DEFINED__
#endif // __SECSTATUS_DEFINED__
//
// Authentication request info structure
//
#define HTTP_REQUEST_AUTH_FLAG_TOKEN_FOR_CACHED_CRED (0x00000001)
typedef struct _HTTP_REQUEST_AUTH_INFO
{
HTTP_AUTH_STATUS AuthStatus;
SECURITY_STATUS SecStatus;
ULONG Flags;
HTTP_REQUEST_AUTH_TYPE AuthType;
HANDLE AccessToken;
ULONG ContextAttributes;
//
// Optional serialized context.
//
ULONG PackedContextLength;
ULONG PackedContextType;
PVOID PackedContext;
//
// Optional mutual authentication data and its length in bytes.
//
ULONG MutualAuthDataLength;
PCHAR pMutualAuthData;
//
// For SSPI based schemes the package name is returned. Length does
// not include the terminating null and it is in bytes.
//
USHORT PackageNameLength;
PWSTR pPackageName;
} HTTP_REQUEST_AUTH_INFO, *PHTTP_REQUEST_AUTH_INFO;
#endif // _WIN32_WINNT >= 0x0600
//
// The structure of an HTTP request for downlevel OS
//
typedef struct _HTTP_REQUEST_V1
{
//
// Request flags (see HTTP_REQUEST_FLAG_* definitions below).
//
ULONG Flags;
//
// An opaque request identifier. These values are used by the driver
// to correlate outgoing responses with incoming requests.
//
HTTP_CONNECTION_ID ConnectionId;
HTTP_REQUEST_ID RequestId;
//
// The context associated with the URL prefix.
//
HTTP_URL_CONTEXT UrlContext;
//
// The HTTP version number.
//
HTTP_VERSION Version;
//
// The request verb.
//
HTTP_VERB Verb;
//
// The length of the verb string if the Verb field is HttpVerbUnknown.
//
USHORT UnknownVerbLength; // in bytes not including the NUL
//
// The length of the raw (uncooked) URL
//
USHORT RawUrlLength; // in bytes not including the NUL
//
// Pointer to the verb string if the Verb field is HttpVerbUnknown.
//
PCSTR pUnknownVerb;
//
// Pointer to the raw (uncooked) URL
//
PCSTR pRawUrl;
//
// The canonicalized Unicode URL
//
HTTP_COOKED_URL CookedUrl;
//
// Local and remote transport addresses for the connection.
//
HTTP_TRANSPORT_ADDRESS Address;
//
// The request headers.
//
HTTP_REQUEST_HEADERS Headers;
//
// The total number of bytes received from network for this request.
//
ULONGLONG BytesReceived;
//
// pEntityChunks is an array of EntityChunkCount HTTP_DATA_CHUNKs. The
// entity body is copied only if HTTP_RECEIVE_REQUEST_FLAG_COPY_BODY
// was passed to HttpReceiveHttpRequest().
//
USHORT EntityChunkCount;
PHTTP_DATA_CHUNK pEntityChunks;
//
// SSL connection information.
//
HTTP_RAW_CONNECTION_ID RawConnectionId;
PHTTP_SSL_INFO pSslInfo;
} HTTP_REQUEST_V1, *PHTTP_REQUEST_V1;
#if _WIN32_WINNT >= 0x0600
// Vista
//
// Version 2.0 members are defined here
// N.B. One must define V2 elements in two places :(
// This is due to the fact that C++ doesn't allow anonymous
// structure declarations and one must use structure
// inheritance instead.
//
#ifdef __cplusplus
typedef struct _HTTP_REQUEST_V2 : _HTTP_REQUEST_V1
{
//
// Version 1.0 members are inherited
// Version 2.0 members are declared below
//
//
// Additional Request Informations.
//
USHORT RequestInfoCount;
PHTTP_REQUEST_INFO pRequestInfo;
} HTTP_REQUEST_V2, *PHTTP_REQUEST_V2;
#else // __cplusplus
typedef struct _HTTP_REQUEST_V2
{
struct _HTTP_REQUEST_V1; // Anonymous structure
//
// Version 2.0 members are declared below
//
//
// Additional Request Informations.
//
USHORT RequestInfoCount;
PHTTP_REQUEST_INFO pRequestInfo;
} HTTP_REQUEST_V2, *PHTTP_REQUEST_V2;
#endif // __cplusplus
typedef HTTP_REQUEST_V2 HTTP_REQUEST;
#else // _WIN32_WINNT >= 0x0600
typedef HTTP_REQUEST_V1 HTTP_REQUEST;
#endif // _WIN32_WINNT >= 0x0600
typedef HTTP_REQUEST * PHTTP_REQUEST;
//
// Values for HTTP_REQUEST::Flags. Zero or more of these may be ORed together.
//
// HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS - there is more entity body
// to be read for this request. Otherwise, there is no entity body or
// all of the entity body was copied into pEntityChunks.
// HTTP_REQUEST_FLAG_IP_ROUTED - This flag indicates that the request has been
// routed based on host plus ip or ip binding.This is a hint for the application
// to include the local ip while flushing kernel cache entries build for this
// request if any.
// HTTP_REQUEST_FLAG_HTTP2 - Indicates the request was received over HTTP/2.
// HTTP_REQUEST_FLAG_HTTP3 - Indicates the request was received over HTTP/3.
//
#define HTTP_REQUEST_FLAG_MORE_ENTITY_BODY_EXISTS 0x00000001
#define HTTP_REQUEST_FLAG_IP_ROUTED 0x00000002
#define HTTP_REQUEST_FLAG_HTTP2 0x00000004
#define HTTP_REQUEST_FLAG_HTTP3 0x00000008
//
// This structure describes an HTTP response.
//
typedef struct _HTTP_RESPONSE_V1
{
//
// Response flags (see HTTP_RESPONSE_FLAG_* definitions below).
//
ULONG Flags;
//
// The raw HTTP protocol version number.
//
HTTP_VERSION Version;
//
// The HTTP status code (e.g., 200).
//
USHORT StatusCode;
//
// The HTTP reason (e.g., "OK"). This MUST not contain
// non-ASCII characters (i.e., all chars must be in range 0x20-0x7E).
//
USHORT ReasonLength; // in bytes not including the '\0'
PCSTR pReason;
//
// The response headers.
//
HTTP_RESPONSE_HEADERS Headers;
//
// pEntityChunks points to an array of EntityChunkCount HTTP_DATA_CHUNKs.
//
USHORT EntityChunkCount;
PHTTP_DATA_CHUNK pEntityChunks;
} HTTP_RESPONSE_V1, *PHTTP_RESPONSE_V1;
#if _WIN32_WINNT >= 0x0600
//
// Values for HTTP_RESPONSE::Flags.
//
// HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE - Set this flag if encodings
// other than identity form are available for this resource.This flag is ignored
// if application has not asked for response to be cached. It's used as a hint
// to the Http Server API for content negotiation used when serving from the
// the kernel response cache.
//
// HTTP_RESPONSE_FLAG_MORE_ENTITY_BODY_EXISTS - there is more entity body
// to be read for this response. Otherwise, there is no entity body or
// all of the entity body was copied into pEntityChunks.
//
#define HTTP_RESPONSE_FLAG_MULTIPLE_ENCODINGS_AVAILABLE 0x00000001
#define HTTP_RESPONSE_FLAG_MORE_ENTITY_BODY_EXISTS 0x00000002
typedef enum _HTTP_RESPONSE_INFO_TYPE
{
HttpResponseInfoTypeMultipleKnownHeaders,
HttpResponseInfoTypeAuthenticationProperty,
HttpResponseInfoTypeQoSProperty,
HttpResponseInfoTypeChannelBind
} HTTP_RESPONSE_INFO_TYPE, PHTTP_RESPONSE_INFO_TYPE;
typedef struct _HTTP_RESPONSE_INFO
{
HTTP_RESPONSE_INFO_TYPE Type;
ULONG Length;
PVOID pInfo;
} HTTP_RESPONSE_INFO, *PHTTP_RESPONSE_INFO;
#define HTTP_RESPONSE_INFO_FLAGS_PRESERVE_ORDER 0x00000001
//
// This structure allows the provision of providing multiple known headers.
//
typedef struct _HTTP_MULTIPLE_KNOWN_HEADERS
{
//
// Known header id.
//
HTTP_HEADER_ID HeaderId;
ULONG Flags;
//
// Number of headers of the same category.
//
USHORT KnownHeaderCount;
//
// Array of known header structures.
//
PHTTP_KNOWN_HEADER KnownHeaders;
} HTTP_MULTIPLE_KNOWN_HEADERS, *PHTTP_MULTIPLE_KNOWN_HEADERS;
//
// Version 2.0 members are defined here
// N.B. One must define V2 elements in two places :(
// This is due to the fact that C++ doesn't allow anonymous
// structure declarations and one must use structure
// inheritance instead.
//
#ifdef __cplusplus
typedef struct _HTTP_RESPONSE_V2 : _HTTP_RESPONSE_V1
{
//
// Version 1.0 members are inherited
// Version 2.0 members are declared below
//
USHORT ResponseInfoCount;
PHTTP_RESPONSE_INFO pResponseInfo;
} HTTP_RESPONSE_V2, *PHTTP_RESPONSE_V2;
#else // __cplusplus
typedef struct _HTTP_RESPONSE_V2
{
struct _HTTP_RESPONSE_V1;
//
// Version 2.0 members are declared below
//
USHORT ResponseInfoCount;
PHTTP_RESPONSE_INFO pResponseInfo;
} HTTP_RESPONSE_V2, *PHTTP_RESPONSE_V2;
#endif // __cplusplus
typedef HTTP_RESPONSE_V2 HTTP_RESPONSE;
#else // _WIN32_WINNT >= 0x0600
typedef HTTP_RESPONSE_V1 HTTP_RESPONSE;
#endif // _WIN32_WINNT >= 0x0600
typedef HTTP_RESPONSE *PHTTP_RESPONSE;
//
// Api Version. This is used to ensure compatibility between applications and
// httpapi.dll and http.sys.
//
// This must not be confused with the HTTP Protocol version.
//
typedef struct _HTTPAPI_VERSION
{
USHORT HttpApiMajorVersion;
USHORT HttpApiMinorVersion;
} HTTPAPI_VERSION, *PHTTPAPI_VERSION;
#if _WIN32_WINNT >= 0x0600
// Vista
#define HTTPAPI_VERSION_2 { 2, 0 }
#endif // _WIN32_WINNT >= 0x0600
#define HTTPAPI_VERSION_1 { 1, 0 }
#define HTTPAPI_EQUAL_VERSION(version, major, minor) \
((version).HttpApiMajorVersion == (major) && \
(version).HttpApiMinorVersion == (minor))
#define HTTPAPI_GREATER_VERSION(version, major, minor) \
((version).HttpApiMajorVersion > (major) || \
((version).HttpApiMajorVersion == (major) && \
(version).HttpApiMinorVersion > (minor)))
#define HTTPAPI_LESS_VERSION(version, major, minor) \
((version).HttpApiMajorVersion < (major) || \
((version).HttpApiMajorVersion == (major) && \
(version).HttpApiMinorVersion < (minor)))
#define HTTPAPI_VERSION_GREATER_OR_EQUAL( version, major, minor) \
(!HTTPAPI_LESS_VERSION(version, major, minor))
//
// Cache control.
//
//
// This enum defines the available cache policies.
//
typedef enum _HTTP_CACHE_POLICY_TYPE
{
HttpCachePolicyNocache,
HttpCachePolicyUserInvalidates,
HttpCachePolicyTimeToLive,
HttpCachePolicyMaximum
} HTTP_CACHE_POLICY_TYPE, *PHTTP_CACHE_POLICY_TYPE;
//
// Only cache unauthorized GETs + HEADs.
//
typedef struct _HTTP_CACHE_POLICY
{
HTTP_CACHE_POLICY_TYPE Policy;
ULONG SecondsToLive;
} HTTP_CACHE_POLICY, *PHTTP_CACHE_POLICY;
//
// Enum that is used with HttpSetServiceConfiguration(),
// HttpQueryServiceConfiguration(), and HttpDeleteServiceConfiguration() APIs.
//
typedef enum _HTTP_SERVICE_CONFIG_ID
{
HttpServiceConfigIPListenList, // Set, Query & Delete.
HttpServiceConfigSSLCertInfo, // Set, Update, Query & Delete.
HttpServiceConfigUrlAclInfo, // Set, Query & Delete.
HttpServiceConfigTimeout, // Set, Query & Delete.
HttpServiceConfigCache, // Set, Query & Delete.
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
HttpServiceConfigSslSniCertInfo, // Set, Update, Query & Delete.
HttpServiceConfigSslCcsCertInfo, // Set, Update, Query & Delete.
#endif
#if _WIN32_WINNT >= _WIN32_WINNT_WIN10
HttpServiceConfigSetting, // Set, Query & Delete.
#endif
HttpServiceConfigSslCertInfoEx,
HttpServiceConfigSslSniCertInfoEx,
HttpServiceConfigSslCcsCertInfoEx,
HttpServiceConfigSslScopedCcsCertInfo,
HttpServiceConfigSslScopedCcsCertInfoEx,
HttpServiceConfigMax
} HTTP_SERVICE_CONFIG_ID, *PHTTP_SERVICE_CONFIG_ID;
//
// Generic Query enum that can be used with HttpQueryServiceConfiguration()
//
typedef enum _HTTP_SERVICE_CONFIG_QUERY_TYPE
{
HttpServiceConfigQueryExact,
HttpServiceConfigQueryNext,
HttpServiceConfigQueryMax
} HTTP_SERVICE_CONFIG_QUERY_TYPE, *PHTTP_SERVICE_CONFIG_QUERY_TYPE;
//
// These data structures are used to define the key types of the various SSL
// bindings.
//
typedef struct _HTTP_SERVICE_CONFIG_SSL_KEY
{
PSOCKADDR pIpPort;
} HTTP_SERVICE_CONFIG_SSL_KEY, *PHTTP_SERVICE_CONFIG_SSL_KEY;
typedef struct _HTTP_SERVICE_CONFIG_SSL_KEY_EX
{
SOCKADDR_STORAGE IpPort;
} HTTP_SERVICE_CONFIG_SSL_KEY_EX, *PHTTP_SERVICE_CONFIG_SSL_KEY_EX;
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
typedef struct _HTTP_SERVICE_CONFIG_SSL_SNI_KEY
{
SOCKADDR_STORAGE IpPort;
PWSTR Host;
} HTTP_SERVICE_CONFIG_SSL_SNI_KEY, *PHTTP_SERVICE_CONFIG_SSL_SNI_KEY;
typedef struct _HTTP_SERVICE_CONFIG_SSL_CCS_KEY
{
SOCKADDR_STORAGE LocalAddress;
} HTTP_SERVICE_CONFIG_SSL_CCS_KEY, *PHTTP_SERVICE_CONFIG_SSL_CCS_KEY;
#endif
//
// This defines a record for the SSL config store.
//
typedef struct _HTTP_SERVICE_CONFIG_SSL_PARAM
{
ULONG SslHashLength; // Length of the SSL hash (in bytes)
PVOID pSslHash; // Pointer to the SSL hash
GUID AppId; // A unique identifier that can be used to
// identify the app that has set this parameter
PWSTR pSslCertStoreName; // Store name to read the server certificate
// from; defaults to "MY". Certificate must be
// stored in the LOCAL_MACHINE context.
//
// The following settings are used only for client certificates
//
//
// DefaultCertCheckMode is a bit flag with the following semantics
// 0x1 - Client certificate will not be verified for revocation
// 0x2 - Only cached certificate revocation will be used.
// 0x4 - Enable use of the DefaultRevocationFreshnessTime setting
// 0x10000 - No usage check.
DWORD DefaultCertCheckMode;
//
// DefaultRevocationFreshnessTime (seconds) - How often to check for
// an updated Certificate revocation list (CRL). If this value is 0
// then the new CRL is updated only if the previous one expires
//
DWORD DefaultRevocationFreshnessTime;
//
// DefaultRevocationUrlRetrievalTimeout (milliseconds) - Timeout on
// attempt to retrieve certificate revocation list from the remote URL.
//
DWORD DefaultRevocationUrlRetrievalTimeout;
//
// pDefaultSslCtlIdentifier - Restrict the certificate issuers that you
// want to trust. Can be a subset of the certificate issuers that are
// trusted by the machine.
//
PWSTR pDefaultSslCtlIdentifier;
//
// Store name under LOCAL_MACHINE where Ctl identified by
// pDefaultSslCtlIdentifier is stored.
//
PWSTR pDefaultSslCtlStoreName;
//
// Default Flags - see HTTP_SERVICE_CONFIG_SSL_FLAG* below.
//
DWORD DefaultFlags;
} HTTP_SERVICE_CONFIG_SSL_PARAM, *PHTTP_SERVICE_CONFIG_SSL_PARAM;
//
// The extended param type for the SSL extended params.
//
typedef enum _HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE
{
ExParamTypeHttp2Window,
ExParamTypeHttp2SettingsLimits,
ExParamTypeHttpPerformance,
ExParamTypeTlsRestrictions,
ExParamTypeErrorHeaders,
ExParamTypeTlsSessionTicketKeys,
ExParamTypeMax
} HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE, *PHTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE;
typedef struct _HTTP2_WINDOW_SIZE_PARAM
{
//
// The http/2 connection receive window size.
//
DWORD Http2ReceiveWindowSize;
} HTTP2_WINDOW_SIZE_PARAM, *PHTTP2_WINDOW_SIZE_PARAM;
typedef struct _HTTP2_SETTINGS_LIMITS_PARAM
{
//
// The maximum allowed settings per SETTINGS frame.
//
DWORD Http2MaxSettingsPerFrame;
//
// The maximum settings we will process in a minute.
//
DWORD Http2MaxSettingsPerMinute;
} HTTP2_SETTINGS_LIMITS_PARAM, *PHTTP2_SETTINGS_LIMITS_PARAM;
typedef enum _HTTP_PERFORMANCE_PARAM_TYPE
{
PerformanceParamSendBufferingFlags,
PerformanceParamAggressiveICW,
PerformanceParamMaxSendBufferSize,
PerformanceParamMaxConcurrentClientStreams,
PerformanceParamMaxReceiveBufferSize,
PerformanceParamDecryptOnSspiThread,
PerformanceParamMax,
} HTTP_PERFORMANCE_PARAM_TYPE, *PHTTP_PERFORMANCE_PARAM_TYPE;
typedef struct _HTTP_PERFORMANCE_PARAM
{
HTTP_PERFORMANCE_PARAM_TYPE Type;
ULONG BufferSize;
PVOID Buffer;
} HTTP_PERFORMANCE_PARAM, *PHTTP_PERFORMANCE_PARAM;
typedef struct _HTTP_TLS_RESTRICTIONS_PARAM
{
ULONG RestrictionCount;
PVOID TlsRestrictions;
} HTTP_TLS_RESTRICTIONS_PARAM, *PHTTP_TLS_RESTRICTIONS_PARAM;
typedef struct _HTTP_ERROR_HEADERS_PARAM
{
USHORT StatusCode;
USHORT HeaderCount;
PHTTP_UNKNOWN_HEADER Headers;
} HTTP_ERROR_HEADERS_PARAM, *PHTTP_ERROR_HEADERS_PARAM;
typedef struct _HTTP_TLS_SESSION_TICKET_KEYS_PARAM
{
ULONG SessionTicketKeyCount;
PVOID SessionTicketKeys;
} HTTP_TLS_SESSION_TICKET_KEYS_PARAM, *PHTTP_TLS_SESSION_TICKET_KEYS_PARAM;
//
// This defines the extended params for the ssl config record.
//
typedef struct _HTTP_SERVICE_CONFIG_SSL_PARAM_EX
{
//
// The id that decides which param property is passed below.
//
HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE ParamType;
//
// Flags for future use, if any.
//
ULONGLONG Flags;
//
// The property.
//
union
{
HTTP2_WINDOW_SIZE_PARAM Http2WindowSizeParam;
HTTP2_SETTINGS_LIMITS_PARAM Http2SettingsLimitsParam;
HTTP_PERFORMANCE_PARAM HttpPerformanceParam;
HTTP_TLS_RESTRICTIONS_PARAM HttpTlsRestrictionsParam;
HTTP_ERROR_HEADERS_PARAM HttpErrorHeadersParam;
HTTP_TLS_SESSION_TICKET_KEYS_PARAM HttpTlsSessionTicketKeysParam;
};
} HTTP_SERVICE_CONFIG_SSL_PARAM_EX, *PHTTP_SERVICE_CONFIG_SSL_PARAM_EX;
//
// The SSL config flags.
//
#define HTTP_SERVICE_CONFIG_SSL_FLAG_USE_DS_MAPPER 0x00000001
#define HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT 0x00000002
#if _WIN32_WINNT < 0x0600
#define HTTP_SERVICE_CONFIG_SSL_FLAG_NO_RAW_FILTER 0x00000004
#endif // _WIN32_WINNT < 0x0600
#define HTTP_SERVICE_CONFIG_SSL_FLAG_REJECT 0x00000008
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_HTTP2 0x00000010
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_QUIC 0x00000020
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_TLS13 0x00000040
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_OCSP_STAPLING 0x00000080
#define HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_TOKEN_BINDING 0x00000100
#define HTTP_SERVICE_CONFIG_SSL_FLAG_LOG_EXTENDED_EVENTS 0x00000200
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_LEGACY_TLS 0x00000400
#define HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_SESSION_TICKET 0x00000800
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_TLS12 0x00001000
#define HTTP_SERVICE_CONFIG_SSL_FLAG_ENABLE_CLIENT_CORRELATION 0x00002000
#define HTTP_SERVICE_CONFIG_SSL_FLAG_DISABLE_SESSION_ID 0x00004000
//
// These data structures are used by HttpSetServiceConfiguration() to add a new
// record to the SSL bindings list.
//
// ConfigId | Structure
// --------------------------------+---------------------------------
// HttpServiceConfigSSLCertInfo | HTTP_SERVICE_CONFIG_SSL_SET
// HttpServiceConfigSslSniCertInfo | HTTP_SERVICE_CONFIG_SSL_SNI_SET
// HttpServiceConfigSslCcsCertInfo | HTTP_SERVICE_CONFIG_SSL_CCS_SET
//
typedef struct _HTTP_SERVICE_CONFIG_SSL_SET
{
HTTP_SERVICE_CONFIG_SSL_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_SET, *PHTTP_SERVICE_CONFIG_SSL_SET;
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
typedef struct _HTTP_SERVICE_CONFIG_SSL_SNI_SET
{
HTTP_SERVICE_CONFIG_SSL_SNI_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_SNI_SET, *PHTTP_SERVICE_CONFIG_SSL_SNI_SET;
typedef struct _HTTP_SERVICE_CONFIG_SSL_CCS_SET
{
HTTP_SERVICE_CONFIG_SSL_CCS_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_CCS_SET, *PHTTP_SERVICE_CONFIG_SSL_CCS_SET;
typedef struct _HTTP_SERVICE_CONFIG_SSL_SET_EX
{
HTTP_SERVICE_CONFIG_SSL_KEY_EX KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM_EX ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_SET_EX, *PHTTP_SERVICE_CONFIG_SSL_SET_EX;
typedef struct _HTTP_SERVICE_CONFIG_SSL_SNI_SET_EX
{
HTTP_SERVICE_CONFIG_SSL_SNI_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM_EX ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_SNI_SET_EX, *PHTTP_SERVICE_CONFIG_SSL_SNI_SET_EX;
typedef struct _HTTP_SERVICE_CONFIG_SSL_CCS_SET_EX
{
HTTP_SERVICE_CONFIG_SSL_CCS_KEY KeyDesc;
HTTP_SERVICE_CONFIG_SSL_PARAM_EX ParamDesc;
} HTTP_SERVICE_CONFIG_SSL_CCS_SET_EX, *PHTTP_SERVICE_CONFIG_SSL_CCS_SET_EX;
#endif
//
// These data structures are used by HttpQueryServiceConfiguration() to query a
// particular record from the SSL store.
//
// ConfigId | Structure
// --------------------------------+---------------------------------
// HttpServiceConfigSSLCertInfo | HTTP_SERVICE_CONFIG_SSL_QUERY
// HttpServiceConfigSSLSniCertInfo | HTTP_SERVICE_CONFIG_SSL_SNI_QUERY
// HttpServiceConfigSslCcsCertInfo | HTTP_SERVICE_CONFIG_SSL_CCS_QUERY
//
// If QueryDesc is HttpServiceConfigQueryExact, then the one particular record
// is returned. If the QueryType is HttpServiceConfigQueryNext, then the next
// instance is returned. In such cases, the dwToken field represents the cursor.
// To retrieve the first item, dwToken has to be 0. For retrieving subsequent
// items, dwToken has to be incremented by 1, until ERROR_NO_MORE_ITEMS is
// returned.
//
typedef struct _HTTP_SERVICE_CONFIG_SSL_QUERY
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_KEY KeyDesc;
DWORD dwToken;
} HTTP_SERVICE_CONFIG_SSL_QUERY, *PHTTP_SERVICE_CONFIG_SSL_QUERY;
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
typedef struct _HTTP_SERVICE_CONFIG_SSL_SNI_QUERY
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_SNI_KEY KeyDesc;
DWORD dwToken;
} HTTP_SERVICE_CONFIG_SSL_SNI_QUERY, *PHTTP_SERVICE_CONFIG_SSL_SNI_QUERY;
typedef struct _HTTP_SERVICE_CONFIG_SSL_CCS_QUERY
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_CCS_KEY KeyDesc;
DWORD dwToken;
} HTTP_SERVICE_CONFIG_SSL_CCS_QUERY, *PHTTP_SERVICE_CONFIG_SSL_CCS_QUERY;
typedef struct _HTTP_SERVICE_CONFIG_SSL_QUERY_EX
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_KEY_EX KeyDesc;
DWORD dwToken;
HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE ParamType;
} HTTP_SERVICE_CONFIG_SSL_QUERY_EX, *PHTTP_SERVICE_CONFIG_SSL_QUERY_EX;
typedef struct _HTTP_SERVICE_CONFIG_SSL_SNI_QUERY_EX
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_SNI_KEY KeyDesc;
DWORD dwToken;
HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE ParamType;
} HTTP_SERVICE_CONFIG_SSL_SNI_QUERY_EX, *PHTTP_SERVICE_CONFIG_SSL_SNI_QUERY_EX;
typedef struct _HTTP_SERVICE_CONFIG_SSL_CCS_QUERY_EX
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_SSL_CCS_KEY KeyDesc;
DWORD dwToken;
HTTP_SSL_SERVICE_CONFIG_EX_PARAM_TYPE ParamType;
} HTTP_SERVICE_CONFIG_SSL_CCS_QUERY_EX, *PHTTP_SERVICE_CONFIG_SSL_CCS_QUERY_EX;
#endif
//
// Set/Delete IP Listen-Only List record
//
// Used as a parameter to both HttpSetServiceConfiguration() and
// HttpDeleteServiceConfiguration() functions.
//
typedef struct _HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM
{
USHORT AddrLength;
PSOCKADDR pAddress;
} HTTP_SERVICE_CONFIG_IP_LISTEN_PARAM, *PHTTP_SERVICE_CONFIG_IP_LISTEN_PARAM;
//
// Query IP Listen-Only List record.
//
// Parameter to HttpQueryServiceConfiguration() for the config ID
// HttpServiceConfigIPListenList. On successful return, AddrList
// contains an array of AddrCount elements. Caller must provide a
// large enough buffer to hold all elements in one call.
//
// Caller may determine the type of each returned element by examining
// AddrList[i].ss_family. If it's AF_INET, use ((PSOCKADDR_IN) &AddrList[i]);
// otherwise, for AF_INET6, use ((PSOCKADDR_IN6) &AddrList[i])
// to select the appropriate address type.
//
typedef struct _HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY
{
ULONG AddrCount;
SOCKADDR_STORAGE AddrList[ANYSIZE_ARRAY];
} HTTP_SERVICE_CONFIG_IP_LISTEN_QUERY, *PHTTP_SERVICE_CONFIG_IP_LISTEN_QUERY;
//
// URL ACL
//
//
typedef struct _HTTP_SERVICE_CONFIG_URLACL_KEY
{
PWSTR pUrlPrefix;
} HTTP_SERVICE_CONFIG_URLACL_KEY, *PHTTP_SERVICE_CONFIG_URLACL_KEY;
//
// This defines a record for the SSL config store.
//
typedef struct _HTTP_SERVICE_CONFIG_URLACL_PARAM
{
PWSTR pStringSecurityDescriptor;
} HTTP_SERVICE_CONFIG_URLACL_PARAM, *PHTTP_SERVICE_CONFIG_URLACL_PARAM;
//
// This data structure is used by HttpSetServiceConfiguration for the config ID
// HttpServiceConfigUrlAclInfo. It is used to add a new record to the URL ACL
// store.
//
typedef struct _HTTP_SERVICE_CONFIG_URLACL_SET
{
HTTP_SERVICE_CONFIG_URLACL_KEY KeyDesc;
HTTP_SERVICE_CONFIG_URLACL_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_URLACL_SET, *PHTTP_SERVICE_CONFIG_URLACL_SET;
//
// This data structure is used by HttpQueryServiceConfiguration() for the
// config ID HttpServiceConfigUrlAclInfo. It's used to query a particular
// record from the URL ACL store.
//
// If QueryType is HttpServiceConfigQueryExact, then one particular record of
// the type HTTP_SERVICE_CONFIG_URLACL_SET is returned. If the QueryType is
// HttpServiceConfigQueryNext, then the next instance of
// HTTP_SERVICE_CONFIG_URLACL_SET is returned. In such cases, the dwToken field
// represents the cursor. For the first item, dwToken has to be 0.
// For subsequent items, dwToken has to be incremented by 1,
// until ERROR_NO_MORE_ITEMS is returned.
//
typedef struct _HTTP_SERVICE_CONFIG_URLACL_QUERY
{
HTTP_SERVICE_CONFIG_QUERY_TYPE QueryDesc;
HTTP_SERVICE_CONFIG_URLACL_KEY KeyDesc;
DWORD dwToken;
} HTTP_SERVICE_CONFIG_URLACL_QUERY, *PHTTP_SERVICE_CONFIG_URLACL_QUERY;
//
// Cache Paramemers
//
//
// For manipulating global cache parameters.
// The parameters that can be changed or queued are per-uri cache size
// and cached range chunk size.
//
typedef enum _HTTP_SERVICE_CONFIG_CACHE_KEY
{
MaxCacheResponseSize = 0,
CacheRangeChunkSize
} HTTP_SERVICE_CONFIG_CACHE_KEY, *PHTTP_SERVICE_CONFIG_CACHE_KEY;
typedef ULONG HTTP_SERVICE_CONFIG_CACHE_PARAM,
*PHTTP_SERVICE_CONFIG_CACHE_PARAM;
//
// To set a cache parameter value use the set structure. To query use the key
// directly. When you query a parameter value the output buffer must be exactly
// the sizeof param.
//
typedef struct {
HTTP_SERVICE_CONFIG_CACHE_KEY KeyDesc;
HTTP_SERVICE_CONFIG_CACHE_PARAM ParamDesc;
} HTTP_SERVICE_CONFIG_CACHE_SET, *PHTTP_SERVICE_CONFIG_CACHE_SET;
//
// Input types for HttpQueryRequestProperty. Only types are public and not the API
// so that IIS need not have their own types for public usage.
//
typedef enum _HTTP_REQUEST_PROPERTY
{
HttpRequestPropertyIsb,
HttpRequestPropertyTcpInfoV0,
HttpRequestPropertyQuicStats,
HttpRequestPropertyTcpInfoV1,
HttpRequestPropertySni,
HttpRequestPropertyStreamError,
HttpRequestPropertyWskApiTimings,
HttpRequestPropertyQuicApiTimings
} HTTP_REQUEST_PROPERTY, *PHTTP_REQUEST_PROPERTY;
typedef struct _HTTP_QUERY_REQUEST_QUALIFIER_TCP
{
ULONGLONG Freshness;
} HTTP_QUERY_REQUEST_QUALIFIER_TCP, *PHTTP_QUERY_REQUEST_QUALIFIER_TCP;
typedef struct _HTTP_QUERY_REQUEST_QUALIFIER_QUIC
{
ULONGLONG Freshness;
} HTTP_QUERY_REQUEST_QUALIFIER_QUIC, *PHTTP_QUERY_REQUEST_QUALIFIER_QUIC;
#define HTTP_REQUEST_PROPERTY_SNI_HOST_MAX_LENGTH 255
//
// Flags inside HTTP_REQUEST_PROPERTY_SNI can have following values:
// - HTTP_REQUEST_PROPERTY_SNI_FLAG_SNI_USED: Indicates that SNI was used for succesful
// endpoint lookup during handshake. If client sent the SNI but Http.sys still decided to
// use IP endpoint binding then this flag will not be set.
// - HTTP_REQUEST_PROPERTY_SNI_FLAG_NO_SNI: Indicates that client did not send the SNI.
// If this flag is set, HTTP_REQUEST_PROPERTY_SNI_FLAG_SNI_USED can not be set.
//
#define HTTP_REQUEST_PROPERTY_SNI_FLAG_SNI_USED 0x00000001
#define HTTP_REQUEST_PROPERTY_SNI_FLAG_NO_SNI 0x00000002
typedef struct _HTTP_REQUEST_PROPERTY_SNI
{
WCHAR Hostname[HTTP_REQUEST_PROPERTY_SNI_HOST_MAX_LENGTH + 1];
ULONG Flags;
} HTTP_REQUEST_PROPERTY_SNI, *PHTTP_REQUEST_PROPERTY_SNI;
typedef struct _HTTP_REQUEST_PROPERTY_STREAM_ERROR
{
ULONG ErrorCode;
} HTTP_REQUEST_PROPERTY_STREAM_ERROR, *PHTTP_REQUEST_PROPERTY_STREAM_ERROR;
typedef struct _HTTP_WSK_API_TIMINGS
{
ULONGLONG ConnectCount;
ULONGLONG ConnectSum;
ULONGLONG DisconnectCount;
ULONGLONG DisconnectSum;
ULONGLONG SendCount;
ULONGLONG SendSum;
ULONGLONG ReceiveCount;
ULONGLONG ReceiveSum;
ULONGLONG ReleaseCount;
ULONGLONG ReleaseSum;
ULONGLONG ControlSocketCount;
ULONGLONG ControlSocketSum;
} HTTP_WSK_API_TIMINGS, *PHTTP_WSK_API_TIMINGS;
typedef struct _HTTP_QUIC_STREAM_API_TIMINGS
{
ULONGLONG OpenCount;
ULONGLONG OpenSum;
ULONGLONG CloseCount;
ULONGLONG CloseSum;
ULONGLONG StartCount;
ULONGLONG StartSum;
ULONGLONG ShutdownCount;
ULONGLONG ShutdownSum;
ULONGLONG SendCount;
ULONGLONG SendSum;
ULONGLONG ReceiveSetEnabledCount;
ULONGLONG ReceiveSetEnabledSum;
ULONGLONG GetParamCount;
ULONGLONG GetParamSum;
ULONGLONG SetParamCount;
ULONGLONG SetParamSum;
ULONGLONG SetCallbackHandlerCount;
ULONGLONG SetCallbackHandlerSum;
} HTTP_QUIC_STREAM_API_TIMINGS, *PHTTP_QUIC_STREAM_API_TIMINGS;
typedef struct _HTTP_QUIC_CONNECTION_API_TIMINGS
{
ULONGLONG OpenTime;
ULONGLONG CloseTime;
ULONGLONG StartTime;
ULONGLONG ShutdownTime;
ULONGLONG SecConfigCreateTime;
ULONGLONG SecConfigDeleteTime;
ULONGLONG GetParamCount;
ULONGLONG GetParamSum;
ULONGLONG SetParamCount;
ULONGLONG SetParamSum;
ULONGLONG SetCallbackHandlerCount;
ULONGLONG SetCallbackHandlerSum;
HTTP_QUIC_STREAM_API_TIMINGS ControlStreamTimings;
} HTTP_QUIC_CONNECTION_API_TIMINGS, *PHTTP_QUIC_CONNECTION_API_TIMINGS;
typedef struct _HTTP_QUIC_API_TIMINGS
{
HTTP_QUIC_CONNECTION_API_TIMINGS ConnectionTimings;
HTTP_QUIC_STREAM_API_TIMINGS StreamTimings;
} HTTP_QUIC_API_TIMINGS, *PHTTP_QUIC_API_TIMINGS;
typedef struct _HTTP_QUIC_STREAM_REQUEST_STATS
{
ULONGLONG StreamWaitStart;
ULONGLONG StreamWaitEnd;
ULONGLONG RequestHeadersCompressionStart;
ULONGLONG RequestHeadersCompressionEnd;
ULONGLONG ResponseHeadersDecompressionStart;
ULONGLONG ResponseHeadersDecompressionEnd;
ULONGLONG RequestHeadersCompressedSize;
ULONGLONG ResponseHeadersCompressedSize;
} HTTP_QUIC_STREAM_REQUEST_STATS, *PHTTP_QUIC_STREAM_REQUEST_STATS;
#define HTTP_QUIC_KEEPALIVE_TIMEOUT_DISABLED ((ULONG)-1)
typedef enum _HTTP_FEATURE_ID
{
HttpFeatureUnknown = 0,
HttpFeatureResponseTrailers = 1,
HttpFeatureApiTimings = 2,
HttpFeatureDelegateEx = 3,
HttpFeatureHttp3 = 4,
HttpFeatureLast = 5,
HttpFeaturemax = 0xFFFFFFFF,
} HTTP_FEATURE_ID, *PHTTP_FEATURE_ID;
//
// Define our API linkage.
//
#if !defined(HTTPAPI_LINKAGE)
#define HTTPAPI_LINKAGE DECLSPEC_IMPORT
#endif // !HTTPAPI_LINKAGE
//
// Initialize/Terminate APIs.
//
// NOTE: MUST be called once before all other APIs
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpInitialize(
IN HTTPAPI_VERSION Version,
IN ULONG Flags,
_Reserved_ IN OUT PVOID pReserved
);
// NOTE: MUST be called after final API call returns.
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpTerminate(
IN ULONG Flags,
_Reserved_ IN OUT PVOID pReserved
);
//
// HTTP Request Queue manipulation APIs.
//
// This API is maintained for backward competibility for the first
// version of the HTTPAPI and should not be used. Instead the new
// HttpCreateRequestQueue() API must be used.
//
// Use CloseHandle() to release the handles returned by
// HttpCreateHttpHandle() API.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCreateHttpHandle(
OUT PHANDLE RequestQueueHandle,
_Reserved_ ULONG Reserved
);
#if _WIN32_WINNT >= 0x0600
//
// Extended Request Queue manipulation APIs.
//
// Use HttpCloseRequestQueue() API to close the handles
// created by the HttpCreateRequestQueue API.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCreateRequestQueue(
IN HTTPAPI_VERSION Version,
IN PCWSTR Name OPTIONAL,
IN PSECURITY_ATTRIBUTES SecurityAttributes OPTIONAL,
IN ULONG Flags OPTIONAL,
OUT PHANDLE RequestQueueHandle
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCloseRequestQueue(
IN HANDLE RequestQueueHandle
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSetRequestQueueProperty(
_In_ HANDLE RequestQueueHandle,
_In_ HTTP_SERVER_PROPERTY Property,
_In_reads_bytes_(PropertyInformationLength) PVOID PropertyInformation,
_In_ ULONG PropertyInformationLength,
_Reserved_ ULONG Reserved1,
_Reserved_ PVOID Reserved2
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpQueryRequestQueueProperty(
_In_ HANDLE RequestQueueHandle,
_In_ HTTP_SERVER_PROPERTY Property,
_Out_writes_bytes_to_opt_(PropertyInformationLength, *ReturnLength) PVOID PropertyInformation,
_In_ ULONG PropertyInformationLength,
_Reserved_ ULONG Reserved1,
_Out_opt_ PULONG ReturnLength,
_Reserved_ PVOID Reserved2
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSetRequestProperty(
_In_ HANDLE RequestQueueHandle,
_In_ HTTP_OPAQUE_ID Id,
_In_ HTTP_REQUEST_PROPERTY PropertyId,
_In_reads_bytes_opt_(InputPropertySize) PVOID Input,
_In_ ULONG InputPropertySize,
_In_ LPOVERLAPPED Overlapped
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpShutdownRequestQueue(
IN HANDLE RequestQueueHandle
);
#endif // _WIN32_WINNT >= 0x0600
//
// SSL APIs.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpReceiveClientCertificate(
IN HANDLE RequestQueueHandle,
IN HTTP_CONNECTION_ID ConnectionId,
IN ULONG Flags,
_Out_writes_bytes_to_(SslClientCertInfoSize, *BytesReceived) PHTTP_SSL_CLIENT_CERT_INFO SslClientCertInfo,
IN ULONG SslClientCertInfoSize,
_Out_opt_ PULONG BytesReceived,
IN LPOVERLAPPED Overlapped OPTIONAL
);
#if _WIN32_WINNT >= 0x0600
//
// Server Session APIs.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCreateServerSession(
IN HTTPAPI_VERSION Version,
OUT PHTTP_SERVER_SESSION_ID ServerSessionId,
_Reserved_ IN ULONG Reserved
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCloseServerSession(
IN HTTP_SERVER_SESSION_ID ServerSessionId
);
HTTPAPI_LINKAGE
_Success_(return == NO_ERROR)
ULONG
WINAPI
HttpQueryServerSessionProperty(
IN HTTP_SERVER_SESSION_ID ServerSessionId,
IN HTTP_SERVER_PROPERTY Property,
_Out_writes_bytes_to_opt_(PropertyInformationLength, *ReturnLength) PVOID PropertyInformation,
IN ULONG PropertyInformationLength,
_Out_opt_ PULONG ReturnLength
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSetServerSessionProperty(
IN HTTP_SERVER_SESSION_ID ServerSessionId,
IN HTTP_SERVER_PROPERTY Property,
_In_reads_bytes_(PropertyInformationLength) PVOID PropertyInformation,
IN ULONG PropertyInformationLength
);
#endif // _WIN32_WINNT >= 0x0600
//
// Url Configuration APIs. Can only be used for V1 request queues.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpAddUrl(
IN HANDLE RequestQueueHandle,
IN PCWSTR FullyQualifiedUrl,
_Reserved_ PVOID Reserved
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpRemoveUrl(
IN HANDLE RequestQueueHandle,
IN PCWSTR FullyQualifiedUrl
);
#if _WIN32_WINNT >= 0x0600
//
// Url Group APIs.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCreateUrlGroup(
IN HTTP_SERVER_SESSION_ID ServerSessionId,
OUT PHTTP_URL_GROUP_ID pUrlGroupId,
_Reserved_ IN ULONG Reserved
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCloseUrlGroup(
IN HTTP_URL_GROUP_ID UrlGroupId
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpAddUrlToUrlGroup(
IN HTTP_URL_GROUP_ID UrlGroupId,
IN PCWSTR pFullyQualifiedUrl,
IN HTTP_URL_CONTEXT UrlContext OPTIONAL,
_Reserved_ IN ULONG Reserved
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpRemoveUrlFromUrlGroup(
IN HTTP_URL_GROUP_ID UrlGroupId,
IN PCWSTR pFullyQualifiedUrl,
IN ULONG Flags
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSetUrlGroupProperty(
IN HTTP_URL_GROUP_ID UrlGroupId,
IN HTTP_SERVER_PROPERTY Property,
_In_reads_bytes_(PropertyInformationLength) PVOID PropertyInformation,
IN ULONG PropertyInformationLength
);
HTTPAPI_LINKAGE
_Success_(return == NO_ERROR)
ULONG
WINAPI
HttpQueryUrlGroupProperty(
IN HTTP_URL_GROUP_ID UrlGroupId,
IN HTTP_SERVER_PROPERTY Property,
_Out_writes_bytes_to_opt_(PropertyInformationLength, *ReturnLength) PVOID PropertyInformation,
IN ULONG PropertyInformationLength,
_Out_opt_ PULONG ReturnLength
);
#endif // _WIN32_WINNT >= 0x0600
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpPrepareUrl(
_Reserved_ PVOID Reserved,
_Reserved_ ULONG Flags,
_In_ PCWSTR Url,
_Outptr_ PWSTR *PreparedUrl
);
#endif
//
// HTTP Server I/O APIs.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpReceiveHttpRequest(
IN HANDLE RequestQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
_Out_writes_bytes_to_(RequestBufferLength, *BytesReturned) PHTTP_REQUEST RequestBuffer,
IN ULONG RequestBufferLength,
_Out_opt_ PULONG BytesReturned,
IN LPOVERLAPPED Overlapped OPTIONAL
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpReceiveRequestEntityBody(
IN HANDLE RequestQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
_Out_writes_bytes_to_(EntityBufferLength, *BytesReturned) PVOID EntityBuffer,
IN ULONG EntityBufferLength,
_Out_opt_ PULONG BytesReturned,
IN LPOVERLAPPED Overlapped OPTIONAL
);
#if _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSendHttpResponse(
IN HANDLE RequestQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
IN PHTTP_RESPONSE HttpResponse,
IN PHTTP_CACHE_POLICY CachePolicy OPTIONAL,
OUT PULONG BytesSent OPTIONAL,
_Reserved_ PVOID Reserved1,
_Reserved_ ULONG Reserved2,
IN LPOVERLAPPED Overlapped OPTIONAL,
IN PHTTP_LOG_DATA LogData OPTIONAL
);
#else // _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSendHttpResponse(
IN HANDLE ReqQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
IN PHTTP_RESPONSE pHttpResponse,
IN PVOID pReserved1 OPTIONAL, // must be NULL
OUT PULONG pBytesSent OPTIONAL,
_Reserved_ PVOID pReserved2, // must be NULL
_Reserved_ ULONG Reserved3, // must be 0
IN LPOVERLAPPED pOverlapped OPTIONAL,
IN PVOID pReserved4 OPTIONAL // must be NULL
);
#endif // _WIN32_WINNT >= 0x0600
#if _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSendResponseEntityBody(
IN HANDLE RequestQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
IN USHORT EntityChunkCount OPTIONAL,
_In_reads_opt_(EntityChunkCount) PHTTP_DATA_CHUNK EntityChunks,
OUT PULONG BytesSent OPTIONAL,
_Reserved_ PVOID Reserved1 OPTIONAL,
_Reserved_ ULONG Reserved2 OPTIONAL,
IN LPOVERLAPPED Overlapped OPTIONAL,
IN PHTTP_LOG_DATA LogData OPTIONAL
);
#else // _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSendResponseEntityBody(
IN HANDLE ReqQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN ULONG Flags,
IN USHORT EntityChunkCount OPTIONAL,
_In_reads_opt_(EntityChunkCount)
IN PHTTP_DATA_CHUNK pEntityChunks OPTIONAL,
OUT PULONG pBytesSent OPTIONAL,
_Reserved_ PVOID pReserved1 OPTIONAL, // must be NULL
_Reserved_ ULONG Reserved2 OPTIONAL, // must be 0
IN LPOVERLAPPED pOverlapped OPTIONAL,
IN PVOID pReserved3 OPTIONAL // must be NULL
);
#endif // _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpDeclarePush(
_In_ HANDLE RequestQueueHandle,
_In_ HTTP_REQUEST_ID RequestId,
_In_ HTTP_VERB Verb,
_In_ PCWSTR Path,
_In_opt_ PCSTR Query,
_In_opt_ PHTTP_REQUEST_HEADERS Headers
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpWaitForDisconnect(
IN HANDLE RequestQueueHandle,
IN HTTP_CONNECTION_ID ConnectionId,
IN LPOVERLAPPED Overlapped OPTIONAL
);
#if _WIN32_WINNT >= 0x0600
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpWaitForDisconnectEx(
IN HANDLE RequestQueueHandle,
IN HTTP_CONNECTION_ID ConnectionId,
_Reserved_ IN ULONG Reserved OPTIONAL,
IN LPOVERLAPPED Overlapped OPTIONAL
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpCancelHttpRequest(
IN HANDLE RequestQueueHandle,
IN HTTP_REQUEST_ID RequestId,
IN LPOVERLAPPED Overlapped OPTIONAL
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpWaitForDemandStart(
IN HANDLE RequestQueueHandle,
IN LPOVERLAPPED Overlapped OPTIONAL
);
BOOL
WINAPI
HttpIsFeatureSupported(
_In_ HTTP_FEATURE_ID FeatureId
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpDelegateRequestEx(
_In_ HANDLE RequestQueueHandle,
_In_ HANDLE DelegateQueueHandle,
_In_ HTTP_REQUEST_ID RequestId,
_In_ HTTP_URL_GROUP_ID DelegateUrlGroupId,
_In_ ULONG PropertyInfoSetSize,
_In_ PHTTP_DELEGATE_REQUEST_PROPERTY_INFO PropertyInfoSet
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpFindUrlGroupId(
_In_ PCWSTR FullyQualifiedUrl,
_In_ HANDLE RequestQueueHandle,
_Out_ PHTTP_URL_GROUP_ID UrlGroupId
);
#endif // _WIN32_WINNT >= 0x0600
//
// Cache manipulation APIs.
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpFlushResponseCache(
IN HANDLE RequestQueueHandle,
IN PCWSTR UrlPrefix,
IN ULONG Flags,
IN LPOVERLAPPED Overlapped OPTIONAL
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpAddFragmentToCache(
IN HANDLE RequestQueueHandle,
IN PCWSTR UrlPrefix,
IN PHTTP_DATA_CHUNK DataChunk,
IN PHTTP_CACHE_POLICY CachePolicy,
IN LPOVERLAPPED Overlapped OPTIONAL
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpReadFragmentFromCache(
IN HANDLE RequestQueueHandle,
IN PCWSTR UrlPrefix,
IN PHTTP_BYTE_RANGE ByteRange OPTIONAL,
_Out_writes_bytes_to_(BufferLength, *BytesRead) PVOID Buffer,
IN ULONG BufferLength,
_Out_opt_ PULONG BytesRead,
IN LPOVERLAPPED Overlapped OPTIONAL
);
//
// Server configuration APIs
//
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpSetServiceConfiguration(
_Reserved_ HANDLE ServiceHandle,
_In_ HTTP_SERVICE_CONFIG_ID ConfigId,
_In_reads_bytes_(ConfigInformationLength) PVOID pConfigInformation,
_In_ ULONG ConfigInformationLength,
_Reserved_ LPOVERLAPPED pOverlapped
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpUpdateServiceConfiguration(
_Reserved_ HANDLE Handle,
_In_ HTTP_SERVICE_CONFIG_ID ConfigId,
_In_reads_bytes_(ConfigInfoLength) PVOID ConfigInfo,
_In_ ULONG ConfigInfoLength,
_Reserved_ LPOVERLAPPED Overlapped
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpDeleteServiceConfiguration(
_Reserved_ HANDLE ServiceHandle,
_In_ HTTP_SERVICE_CONFIG_ID ConfigId,
_In_reads_bytes_(ConfigInformationLength) PVOID pConfigInformation,
_In_ ULONG ConfigInformationLength,
_Reserved_ LPOVERLAPPED pOverlapped
);
HTTPAPI_LINKAGE
ULONG
WINAPI
HttpQueryServiceConfiguration(
_Reserved_ HANDLE ServiceHandle,
_In_ HTTP_SERVICE_CONFIG_ID ConfigId,
_In_reads_bytes_opt_(InputLength) PVOID pInput,
_In_ ULONG InputLength,
_Out_writes_bytes_to_opt_(OutputLength, *pReturnLength) PVOID pOutput,
_In_ ULONG OutputLength,
_Out_opt_ PULONG pReturnLength,
_Reserved_ LPOVERLAPPED pOverlapped
);
ULONG
WINAPI
HttpGetExtension(
__in HTTPAPI_VERSION Version,
__in ULONG Extension,
__out PVOID __bcount(BufferSize) Buffer,
__in ULONG BufferSize
);
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
#endif // _WIN32_WINNT >= 0x0501
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
#endif // __HTTP_H__
|
f82ced27a0ddc17a1b1eb29e747ae96b443f5e1c
|
bd14d23b3c6dd17110dd0cc691247b042466fdc9
|
/src/hse/hse/include/hse_header/hse_config/hse_b_config.h
|
20e93825d3335bcd68e84b9a8b86cefe2e886e25
|
[
"MIT"
] |
permissive
|
frankie-zeng/ECUBus
|
13e8938571a34563789a1d55d6a1c7f8864086a6
|
f196e56ef7c038a6360b454ad32d0b70e6a9fdca
|
refs/heads/master
| 2023-04-14T10:34:12.483817
| 2023-03-27T13:43:29
| 2023-03-27T13:43:29
| 239,531,393
| 135
| 52
|
MIT
| 2023-02-04T04:19:45
| 2020-02-10T14:28:25
|
C
|
UTF-8
|
C
| false
| false
| 17,228
|
h
|
hse_b_config.h
|
/**
* @file hse_b_config.h
*
* @brief HSE Basic features implementation.
* @details This file contains the HSE Basic implementation features.
*
* @addtogroup hse_b_config HSE Basic Features Implementation
* @ingroup class_common_types
* @{
*/
/*==================================================================================================
*
* (c) Copyright 2020 NXP.
*
* This software is owned or controlled by NXP and may only be used strictly in accordance with
* the applicable license terms. By expressly accepting such terms or by downloading, installing,
* activating and/or otherwise using the software, you are agreeing that you have read, and that
* you agree to comply with and are bound by, such license terms. If you do not agree to
* be bound by the applicable license terms, then you may not retain, install, activate or
* otherwise use the software.
==================================================================================================*/
/*==================================================================================================
==================================================================================================*/
#ifndef HSE_B_CONFIG_H
#define HSE_B_CONFIG_H
#ifdef __cplusplus
extern "C"{
#endif
/*==================================================================================================
* INCLUDE FILES
* 1) system and project includes
* 2) needed interfaces from external units
* 3) internal and external interfaces from this unit
==================================================================================================*/
/**
* @file hse_b_config.h
*/
/*==================================================================================================
* SOURCE FILE VERSION INFORMATION
==================================================================================================*/
/*==================================================================================================
* FILE VERSION CHECKS
==================================================================================================*/
/*==================================================================================================
* CONSTANTS
==================================================================================================*/
/*==================================================================================================
* DEFINES AND MACROS
==================================================================================================*/
/*-------------------------------------------------------*/
/**< \defdisable{#define,HSE_SPT_FLASHLESS_DEV}*/ /**< @brief The service is flashless (external flash). */
#define HSE_SPT_INTERNAL_FLASH_DEV /**< @brief Device has internal flash. */
/*-------------------------------------------------------*/
#define HSE_SPT_RANDOM /**< @brief Support for Random Number Generation. */
/*-------------------------------------------------------*/
#define HSE_SPT_SHE /**< @brief Support for SHE specification. NOTE: AES and CMAC features must be enabled. */
/*-------------------------------------------------------*/
#define HSE_SPT_AES /**< @brief Support for AES_(128, 192, 256)_(ECB, CBC, CFB, OFB, CTR) */
/**< \defdisable{#define,HSE_SPT_XTS_AES}*/ /**< @brief Support for XTS AES */
/**< \defdisable{#define,HSE_SPT_TDES}*/ /**< @brief Support for TDES_(128, 192)_(ECB, CBC, CFB, OFB) as defined in NIST SP 800-67 rev1. */
#define HSE_SPT_AEAD_GCM /**< @brief Support for AEAD AES GCM as defined in FIPS PUB 197, NIST SP 800-38D, RFC-5288 and RFC-4106. */
#define HSE_SPT_AEAD_CCM /**< @brief Support for AEAD AES CCM as defined in FIPS PUB 197, NIST SP 800-38C, RFC-6655 and RFC-4309. */
/**< \defdisable{#define,HSE_SPT_AUTHENC}*/ /**< @brief Support for Dual Purpose Crypto Service (Authenticated encryption) */
/*-------------------------------------------------------*/
#define HSE_SPT_HASH /**< @brief Hash support */
#ifdef HSE_SPT_HASH
/**< \defdisable{#define,HSE_SPT_MD5}*/ /**< @brief Support for MD5 as defined in IETF RFC-1321. */
#define HSE_SPT_SHA1 /**< @brief Support for SHA-1 as defined in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_224 /**< @brief Support for SHA2_224 in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_256 /**< @brief Support for SHA2_256 in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_384 /**< @brief Support for SHA2_384 in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_512 /**< @brief Support for SHA2_512 in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_512_224 /**< @brief Support for SHA2_512_224 in FIPS PUB 180-4. */
#define HSE_SPT_SHA2_512_256 /**< @brief Support for SHA2_512_256 in FIPS PUB 180-4. */
/**< \defdisable{#define,HSE_SPT_SHA3}*/ /**< @brief Support for SHA3_(224, 256, 384, 512) as defined in FIPS PUB 202. */
#define HSE_SPT_MIYAGUCHI_PRENEEL /**< @brief Miyaguchi-Preneel compression function (SHE spec support)*/
#endif /* ifdef HSE_SPT_HASH */
/*-------------------------------------------------------*/
#define HSE_SPT_MAC /**< @brief MAC support */
#ifdef HSE_SPT_MAC
#define HSE_SPT_FAST_CMAC /**< @brief Support for AES fast CMAC (optimized) */
#define HSE_SPT_CMAC /**< @brief Support for AES CMAC as defined in NIST SP 800-38B. */
#define HSE_SPT_HMAC /**< @brief Support for HMAC_SHA2_(224, 256) as defined in FIPS PUB 198-1 and SP 800-107. */
#define HSE_SPT_GMAC /**< @brief Support for AES GMAC as defined in NIST SP 800-38D. */
/**< \defdisable{#define,HSE_SPT_XCBC_MAC}*/ /**< @brief Support for AES XCBC_MAC_96 as defined in RFC-3566. */
#endif /* ifdef HSE_SPT_MAC */
/*-------------------------------------------------------*/
#define HSE_SPT_KEY_GEN /**< @brief Key Generate support */
#ifdef HSE_SPT_KEY_GEN
#define HSE_SPT_SYM_RND_KEY_GEN /**< @brief Support for symmetric random key generation. */
/**< \defdisable{#define,HSE_SPT_CLASSIC_DH_KEY_PAIR_GEN}*/ /**< @brief Support for Classic DH key-pair generation. */
#endif
/*-------------------------------------------------------*/
#define HSE_SPT_RSA /**< @brief RSA support */
#ifdef HSE_SPT_RSA
#define HSE_SPT_RSAES_NO_PADDING /**< @brief RSA modular exponentiation operations( RSAEP and RSADP). */
#define HSE_SPT_RSAES_OAEP /**< @brief Support for RSAES_OAEP as defined by RFC-8017. */
#define HSE_SPT_RSAES_PKCS1_V15 /**< @brief Support for RSAES_PKCS1_V15 as defined by PKCS#1 v2.2. */
#define HSE_SPT_RSASSA_PSS /**< @brief Support for RSASSA_PSS as defined by FIPS 186-4. */
#define HSE_SPT_RSASSA_PKCS1_V15 /**< @brief Support RSASSA_PKCS1_V15 as defined by PKCS#1 v2.2. */
#ifdef HSE_SPT_KEY_GEN
#define HSE_SPT_RSA_KEY_PAIR_GEN /**< @brief Support for RSA key-pair generation. */
#endif
#endif /* ifdef HSE_SPT_RSA */
/*-------------------------------------------------------*/
#define HSE_SPT_ECC /**< @brief Support for ECC */
#ifdef HSE_SPT_ECC
#define HSE_SPT_ECDH /**< @brief ECDH support */
#define HSE_SPT_ECDSA /**< @brief ECDSA support */
#define HSE_SPT_EDDSA /**< @brief Twisted Edwards EDDSA (e.g. ED25519) support */
#define HSE_SPT_MONTDH /**< @brief Montgomery DH (e.g X25519 curve) support */
#define HSE_SPT_ECC_USER_CURVES /**< @brief Support to set ECC curve (not supported by default)*/
#ifdef HSE_SPT_KEY_GEN
#define HSE_SPT_ECC_KEY_PAIR_GEN /**< @brief Support for ECC key-pair generation. */
#endif
#define HSE_SPT_EC_SEC_SECP256R1 /**< @brief Support Ecc p256v1 */
#define HSE_SPT_EC_SEC_SECP384R1 /**< @brief Support Ecc SECP p384r1 */
#define HSE_SPT_EC_SEC_SECP521R1 /**< @brief Support Ecc SECP p521r1 */
#define HSE_SPT_EC_BRAINPOOL_BRAINPOOLP256R1 /**< @brief Support Ecc BrainPool p256r1 */
#define HSE_SPT_EC_BRAINPOOL_BRAINPOOLP320R1 /**< @brief Support Ecc BrainPool p320r1 */
#define HSE_SPT_EC_BRAINPOOL_BRAINPOOLP384R1 /**< @brief Support Ecc BrainPool p384r1 */
#define HSE_SPT_EC_BRAINPOOL_BRAINPOOLP512R1 /**< @brief Support Ecc BrainPool p521r1 */
#define HSE_SPT_EC_25519_ED25519 /**< @brief Twisted Edwards ED25519 curve support (used with EDDSA )*/
#define HSE_SPT_EC_25519_CURVE25519 /**< @brief Montgomery X25519 curve support (used with MONTDH) */
#endif /*ifdef HSE_SPT_ECC */
/*-------------------------------------------------------*/
/**< \defdisable{#define,HSE_SPT_CLASSIC_DH} */ /**< @brief Support for generate key pair, DH share secret computation as defined in FIPS 186-4 */
/*-------------------------------------------------------*/
#define HSE_SPT_KEY_DERIVE /**< @brief KDF support */
#ifdef HSE_SPT_KEY_DERIVE
#define HSE_SPT_KDF_NXP_GENERIC /**< @brief NXP Generic KDF. */
#define HSE_SPT_KDF_SP800_56C_ONESTEP /**< @brief Support for KDF One-step as defined by SP800-56C rev1. */
#define HSE_SPT_KDF_SP800_56C_TWOSTEP /**< @brief Support for KDF Two-step as defined by SP800-56C rev1. */
#define HSE_SPT_KDF_SP800_108 /**< @brief Support for KDF(Counter, Feedback, Pipeline) as defined by SP800-108. */
#define HSE_SPT_KDF_ANS_X963 /**< @brief Support for KDF as defined by ANS X9.63. */
#define HSE_SPT_KDF_ISO18033_KDF1 /**< @brief Support for KDF1 as defined by ISO18033 */
#define HSE_SPT_KDF_ISO18033_KDF2 /**< @brief Support for KDF2 as defined by ISO18033 */
/**< \defdisable{#define,HSE_SPT_PBKDF2}*/ /**< @brief Support for PBKDF2 as defined as defined by PKCS#5 v2.1 and RFC-8018. */
/**< \defdisable{#define,HSE_SPT_KDF_TLS12_PRF}*/ /**< @brief KDF Support for TLS 1.2 as defined by RFC-5246. */
/**< \defdisable{#define,HSE_SPT_HKDF}*/ /**< @brief Support for HMAC-based Extract-and-Expand KDF as defined by RFC-5869. */
/**< \defdisable{#define,HSE_SPT_KDF_IKEV2}*/ /**< @brief KDF Support for IKEv2 as defined by RFC-4306. */
#endif /* ifdef HSE_SPT_KEY_DERIVE */
/*-------------------------------------------------------*/
#define HSE_SPT_NXP_ROM_KEYS /**< @brief Support NXP ROM keys. */
#ifdef HSE_SPT_NXP_ROM_KEYS
/**< \defdisable{#define,HSE_SPT_NXP_ROM_PUB_KEYS}*/ /**< @brief Support NXP ROM public keys. */
#endif
/*-------------------------------------------------------*/
#define HSE_SPT_MONOTONIC_COUNTERS /**< @brief Monotonic Counter support */
#ifdef HSE_SPT_MONOTONIC_COUNTERS
#define HSE_NUM_OF_MONOTONIC_COUNTERS (16U) /**< @brief The supported number of monotonic counters */
#endif
/*-------------------------------------------------------*/
#define HSE_SPT_BSB /**< @brief Basic Secure Booting(ASB) Support */
/**< \defdisable{#define,HSE_SPT_STREAM_CTX_IMPORT_EXPORT}*/ /**< @brief Support Import/Export of streaming context for symmetric operations */
#define HSE_SPT_MU_CONFIG /**< @brief Support MU configuration */
/**< \defdisable{#define,HSE_SPT_ACTIVE_TAMPER_CONFIG}*/ /**< @brief Support of active tamper */
#define HSE_SPT_SMR_CR /**< @brief Advance Secure Booting(ASB) Secure memory regions verification (SMR) & Core Reset(CR) Table Support */
#ifdef HSE_SPT_SMR_CR
#define HSE_NUM_OF_SMR_ENTRIES (8U) /**< @brief The supported number of SMR entries*/
#define HSE_NUM_OF_CORE_RESET_ENTRIES (2U) /**< @brief The supported number of CORE RESET entries*/
#endif
/**< \defdisable{#define,HSE_SPT_SELF_TEST}*/ /**< @brief Support self test */
#define HSE_SPT_OTA_FIRMWARE_UPDATE /**< @brief Support OTA Firmware Update */
#define HSE_SPT_SGT_OPTION /**< @brief Enable support for Scatter Gatter Table */
#ifdef HSE_SPT_SGT_OPTION
#define HSE_MAX_NUM_OF_SGT_ENTRIES (8U) /**< @brief Maximum number for SGT entries */
#endif
/*-------------------------------------------------------*/
#define HSE_NUM_OF_MU_INSTANCES (2U) /**< @brief The maxim number of MU interfaces */
#define HSE_NUM_OF_CHANNELS_PER_MU (4U) /**< @brief The maxim number of channels per MU interface */
#define HSE_STREAM_COUNT (2U) /**< @brief HSE stream count per interface */
#define HSE_NUM_OF_CMU_INSTANCES (1U) /**< @brief The maxim number of CMU interfaces */
#ifdef HSE_SPT_ACTIVE_TAMPER_CONFIG
#define HSE_TAMPER_NUMBER_MAX (1U) /**< @brief The maxim number of active tamper instances */
#endif
#ifdef HSE_SPT_ECC_USER_CURVES
#define HSE_NUM_OF_USER_ECC_CURVES (1U) /**< @brief The number of ECC curves the user can load into the HSE */
#endif
#define HSE_TOTAL_NUM_OF_KEY_GROUPS (32U) /**< @brief The total number of catalog configuration entries for both NVM and RAM catalogs.*/
#define HSE_MAX_NVM_STORE_SIZE (7776U) /**< @brief NVM key store size (in bytes) */
#define HSE_MAX_RAM_STORE_SIZE (4096U) /**< @brief RAM key store size (in bytes) */
#define HSE_AES_KEY_BITS_LENS {128U, 192U, 256U} /**< @brief AES key bit length (set to zero to disable a AES key size)*/
#ifdef HSE_SPT_TDES
#define HSE_TDES_KEY_BITS_LEN {64U, 128U, 192U} /**< @brief TDES key bit length */
#endif
#define HSE_MAX_SHARED_SECRET_BITS_LEN (2048U) /**< @brief Max shared secret bit length */
#ifdef HSE_SPT_HMAC
#define HSE_MIN_HMAC_KEY_BITS_LEN (128U) /**< @brief Min HMAC key bit length */
#define HSE_MAX_HMAC_KEY_BITS_LEN (1024U) /**< @brief Max HMAC key bit length */
#endif
#ifdef HSE_SPT_ECC
#define HSE_MIN_ECC_KEY_BITS_LEN (192U) /**< @brief Min ECC key bit length */
#define HSE_MAX_ECC_KEY_BITS_LEN (521U) /**< @brief Max ECC key bit length */
#endif
#ifdef HSE_SPT_RSA
#define HSE_MIN_RSA_KEY_BITS_LEN (1024U) /**< @brief Min RSA key bit length */
#define HSE_MAX_RSA_KEY_BITS_LEN (4096U) /**< @brief Max RSA key bit length */
#define HSE_MAX_RSA_PUB_EXP_SIZE (8U) /**< @brief Max RSA public exponent size (in bytes) */
#endif
#ifdef HSE_SPT_CLASSIC_DH
#define HSE_MIN_CLASSIC_DH_BITS_LEN (1024U) /**< @brief Min Classic DH key bit length */
#define HSE_MAX_CLASSIC_DH_BITS_LEN (4096U) /**< @brief Max Classic DH key bit length*/
#endif
#if defined(HSE_SPT_ECDSA) || defined(HSE_SPT_EDDSA) || defined(HSE_SPT_RSASSA_PSS) || defined(HSE_SPT_RSASSA_PKCS1_V15)
#define HSE_SPT_SIGN
#endif
#if defined(HSE_SPT_AEAD_GCM) || defined(HSE_SPT_AEAD_CCM)
#define HSE_SPT_AEAD
#endif
#if defined(HSE_SPT_ECDH) || defined(HSE_SPT_CLASSIC_DH) || defined(HSE_SPT_MONTDH)
#define HSE_SPT_COMPUTE_DH
#endif
#if (defined(HSE_SPT_SHA2_224) || defined(HSE_SPT_SHA2_256) || defined(HSE_SPT_SHA2_384) || \
defined(HSE_SPT_SHA2_512) || defined(HSE_SPT_SHA2_512_224) || defined(HSE_SPT_SHA2_512_256))
#define HSE_SPT_SHA2
#endif
/*==================================================================================================
* ENUMS
==================================================================================================*/
/*==================================================================================================
STRUCTURES AND OTHER TYPEDEFS
==================================================================================================*/
/*==================================================================================================
GLOBAL VARIABLE DECLARATIONS
==================================================================================================*/
/*==================================================================================================
FUNCTION PROTOTYPES
==================================================================================================*/
#ifdef __cplusplus
}
#endif
#endif /* HSE_B_CONFIG_H */
/**< @} */
|
799829d17d6da2c6d91e6f46fd562973bc631f7c
|
2c73a693c2b3c162eae2ab94f649d8c4494878ba
|
/components/repl/luat_repl.c
|
5f605351a07117c22b34da54d0aa692275b358ec
|
[
"MIT"
] |
permissive
|
openLuat/LuatOS
|
185e1e140aed908434168133571ddcafe98f4e12
|
4b29d5121ab4f7133630331e8502c526c7856897
|
refs/heads/master
| 2023-08-23T04:57:23.263539
| 2023-08-23T04:46:46
| 2023-08-23T04:46:46
| 230,403,844
| 378
| 93
|
MIT
| 2021-12-17T02:19:30
| 2019-12-27T08:29:19
|
C
|
UTF-8
|
C
| false
| false
| 6,125
|
c
|
luat_repl.c
|
#include "luat_base.h"
#include "luat_shell.h"
#include "luat_malloc.h"
#include "luat_rtos.h"
#include "luat_repl.h"
#include "luat_msgbus.h"
#define LUAT_LOG_TAG "repl"
#include "luat_log.h"
#ifdef LUAT_USE_REPL
static char* mulitline_buff;
static size_t mulitline_buff_size;
static size_t mulitline_buff_offset;
// static int mulitline_mode;
#define luat_repl_write luat_shell_write
// static const char* repl_tips = "";
static int repl_enable = 1;
int luat_repl_enable(int enable) {
int tmp = repl_enable;
if (enable >= 0) {
repl_enable = enable;
}
return tmp;
}
void luat_repl_init(void) {
luat_repl_write("LuatOS Ready\r\n>", strlen("LuatOS Ready\r\n>"));
}
static int report(lua_State* L) {
size_t len = 0;
const char *msg;
msg = lua_tolstring(L, -1, &len);
luat_repl_write(msg, len);
luat_repl_write("\r\n", 2);
lua_pop(L, 1); /* remove message */
return 0;
}
static int repl_handle(lua_State* L, void* ptr) {
char* buff = (char*)ptr;
rtos_msg_t* msg = (rtos_msg_t*)lua_topointer(L, -1);
size_t sz = msg->arg1;
// LLOGD("REPL-- %.*s --", sz, buff);
int ret = luaL_loadbuffer(L, buff, sz, "repl");
luat_heap_free(ptr);
if (ret != LUA_OK) {
// LLOGD("加载出错,语法问题? %d", ret);
report(L);
return 0;
}
// lua_pushcfunction(L, l_err);
// lua_pushvalue(L, -2);
ret = lua_pcall(L, 0, 0, 0);
if (ret < LUA_OK) {
// LLOGD("执行出错 %d", ret);
report(L);
return 0;
}
return 0;
}
static int find2run(void) {
// LLOGD("find2run %p %d %d", mulitline_buff, mulitline_buff_size, mulitline_buff_offset);
if (mulitline_buff == NULL)
return 1;
size_t i = 0;
for (; i < mulitline_buff_offset; i++)
{
if (mulitline_buff[i] == '\r' || mulitline_buff[i] == '\n') {
continue;
}
break;
}
// LLOGD("=================================");
if (i > 0) { // 有空白字符
if (i == mulitline_buff_offset) {
// 全是空白字符?
// 那就是啥都不需要
mulitline_buff_offset = 0;
mulitline_buff_size = 0;
luat_heap_free(mulitline_buff);
mulitline_buff = NULL;
return 1;
}
memmove(mulitline_buff, mulitline_buff + i, mulitline_buff_offset - i);
}
i = 0;
// LLOGD("待搜索字符串 | %.*s |", mulitline_buff_offset, mulitline_buff);
// LLOGD("是开头1吗? %d", memcmp("<<EOF\r", mulitline_buff, 6));
// LLOGD("是开头2吗? %d", memcmp("<<EOF\n", mulitline_buff, 6));
// 是不是多行呢
if (!memcmp("<<EOF\r", mulitline_buff, 6) || !memcmp("<<EOF\n", mulitline_buff, 6)) {
// LLOGD("找到了<<EOF");
// 找到开始了, 继续找结束
i += 6;
for (; i < mulitline_buff_offset - 4; i++)
{
if (!memcmp("EOF\r", mulitline_buff + i, 4) || !memcmp("EOF\n", mulitline_buff + i, 4)) {
// if (mulitline_buff[i-1] == '\r' || mulitline_buff[i-1] == '\n') {
// LLOGD("找到EOF结束符了");
// 是否再malloc一次呢? 貌似也没啥必要
memmove(mulitline_buff, mulitline_buff + 6, i - 6);
rtos_msg_t msg = {
.handler = repl_handle
};
msg.ptr = mulitline_buff;
msg.arg1 = i - 6;
mulitline_buff = NULL;
mulitline_buff_size = 0;
mulitline_buff_offset = 0;
luat_msgbus_put(&msg, 0);
return 0;
// }
}
}
// LLOGD("没有找到EOF结束");
return 1;
}
for (i = 1; i < mulitline_buff_offset; i++)
{
if (mulitline_buff[i] == '\r' || mulitline_buff[i] == '\n') {
char* buff = luat_heap_malloc(i);
if (buff == NULL) {
mulitline_buff_size = 0;
mulitline_buff_offset = 0;
luat_heap_free(mulitline_buff);
mulitline_buff = NULL;
luat_repl_write("REPL: out of memory\r\n", strlen("REPL: out of memory\r\n"));
return 1;
}
memcpy(buff, mulitline_buff, i);
rtos_msg_t msg = {
.handler = repl_handle
};
msg.ptr = buff;
msg.arg1 = i;
memmove(mulitline_buff, mulitline_buff + i, mulitline_buff_offset - i);
mulitline_buff_offset -= i;
luat_msgbus_put(&msg, 0);
return 0;
}
}
return 1;
}
void luat_shell_push(char* uart_buff, size_t rcount) {
// LLOGD("收到数据长度 %d", rcount);
if (rcount == 0 || !repl_enable)
return;
// rtos_msg_t msg = {
// .handler = repl_handle
// };
if (mulitline_buff == NULL) { // 全新的?
mulitline_buff_size = rcount > 1024 ? rcount : 1024;
mulitline_buff = luat_heap_malloc(mulitline_buff_size);
if (mulitline_buff == NULL) {
// mulitline_mode = 0;
mulitline_buff_offset = 0;
mulitline_buff_size = 0;
luat_repl_write("REPL: out of memory\r\n", strlen("REPL: out of memory\r\n"));
return;
}
}
if (mulitline_buff_offset + rcount > mulitline_buff_size) {
void* tmpptr = luat_heap_realloc(mulitline_buff, mulitline_buff_offset + rcount + 256);
if (tmpptr == NULL) {
luat_heap_free(mulitline_buff);
// mulitline_mode = 0;
mulitline_buff_offset = 0;
mulitline_buff_size = 0;
luat_repl_write("REPL: out of memory\r\n", strlen("REPL: out of memory\r\n"));
return;
}
}
memcpy(mulitline_buff + mulitline_buff_offset, uart_buff, rcount);
mulitline_buff_offset += rcount;
// 查找指令
while (find2run() == 0) {
// LLOGD("继续下一个查询循环");
}
return;
}
#endif
|
f541e9a02a13def516461d61e1f3c2faebaa1d05
|
08b91813241c91239b55cce7711ae307bec66eb5
|
/src/image/reader.c
|
3c7137d8d813208f46129ba8e386adc69fff8a27
|
[
"MIT",
"FSFUL"
] |
permissive
|
lc-soft/LCUI
|
8711344e37237763033a9eca5353f99ad0c262d6
|
051bb7a4d5c5cb7f6d71a0d6e54d4063b268db9c
|
refs/heads/develop
| 2023-07-30T07:41:49.610626
| 2022-04-10T06:32:11
| 2022-04-10T06:51:34
| 5,293,802
| 4,353
| 405
|
MIT
| 2023-04-30T08:55:37
| 2012-08-04T07:09:40
|
C
|
UTF-8
|
C
| false
| false
| 5,737
|
c
|
reader.c
|
/*
* reader.c -- Image read operations set
*
* Copyright (c) 2018, Liu chao <lc-soft@live.cn> All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of LCUI nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <LCUI_Build.h>
#include "config.h"
#include <LCUI/types.h>
#include <LCUI/graph.h>
#include <LCUI/image.h>
typedef struct LCUI_ImageInterfaceRec_ {
const char *suffix;
int (*init)(LCUI_ImageReader);
int (*read_header)(LCUI_ImageReader);
int (*read)(LCUI_ImageReader, LCUI_Graph *);
} LCUI_ImageInterfaceRec, *LCUI_ImageInterface;
static const LCUI_ImageInterfaceRec interfaces[] = {
#ifdef USE_LIBPNG
{ ".png", LCUI_InitPNGReader, LCUI_ReadPNGHeader, LCUI_ReadPNG },
#endif
#ifdef USE_LIBJPEG
{ ".jpeg .jpg", LCUI_InitJPEGReader, LCUI_ReadJPEGHeader,
LCUI_ReadJPEG },
#endif
{ ".bmp", LCUI_InitBMPReader, LCUI_ReadBMPHeader, LCUI_ReadBMP }
};
static int n_interfaces = sizeof(interfaces) / sizeof(LCUI_ImageInterfaceRec);
static size_t FileStream_OnRead(void *data, void *buffer, size_t size)
{
return fread(buffer, 1, size, data);
}
static void FileStream_OnSkip(void *data, long offset)
{
fseek(data, offset, SEEK_CUR);
}
static void FileStream_OnRewind(void *data)
{
rewind(data);
}
void LCUI_SetImageReaderForFile(LCUI_ImageReader reader, FILE *fp)
{
reader->stream_data = fp;
reader->fn_skip = FileStream_OnSkip;
reader->fn_read = FileStream_OnRead;
reader->fn_rewind = FileStream_OnRewind;
}
static int DetectImageType(const char *filename)
{
int i;
const char *suffix = NULL;
for (i = 0; filename[i]; ++i) {
if (filename[i] == '.') {
suffix = filename + i;
}
}
if (!suffix) {
return -1;
}
for (i = 0; i < n_interfaces; ++i) {
if (strstr(interfaces[i].suffix, suffix)) {
return i;
}
}
return -1;
}
static int LCUI_InitImageReaderByType(LCUI_ImageReader reader, int type)
{
int ret;
reader->fn_rewind(reader->stream_data);
ret = interfaces[type].init(reader);
if (ret != 0) {
return -2;
}
if (LCUI_SetImageReaderJump(reader)) {
return -2;
}
return interfaces[type].read_header(reader);
}
int LCUI_InitImageReader(LCUI_ImageReader reader)
{
int ret, i;
for (i = 0; i < n_interfaces; ++i) {
reader->fn_rewind(reader->stream_data);
ret = LCUI_InitImageReaderByType(reader, i);
if (ret == 0) {
return 0;
}
LCUI_DestroyImageReader(reader);
}
reader->fn_rewind(reader->stream_data);
reader->type = LCUI_UNKNOWN_READER;
return -ENOENT;
}
void LCUI_DestroyImageReader(LCUI_ImageReader reader)
{
if (reader->data) {
reader->destructor(reader->data);
}
reader->data = NULL;
reader->type = LCUI_UNKNOWN_READER;
reader->header.type = LCUI_UNKNOWN_IMAGE;
}
int LCUI_ReadImageHeader(LCUI_ImageReader reader)
{
int i = reader->type - 1;
if (reader->header.type != LCUI_UNKNOWN_IMAGE) {
return 0;
}
if (i < n_interfaces && i >= 0) {
return interfaces[i].read_header(reader);
}
return -2;
}
int LCUI_ReadImage(LCUI_ImageReader reader, LCUI_Graph *out)
{
int i = reader->type - 1;
if (i < n_interfaces && i >= 0) {
return interfaces[i].read(reader, out);
}
return -2;
}
int LCUI_ReadImageFile(const char *filepath, LCUI_Graph *out)
{
int ret;
FILE *fp;
LCUI_ImageReaderRec reader = { 0 };
fp = fopen(filepath, "rb");
if (!fp) {
return -ENOENT;
}
ret = DetectImageType(filepath);
LCUI_SetImageReaderForFile(&reader, fp);
if (ret >= 0) {
ret = LCUI_InitImageReaderByType(&reader, ret);
}
if (ret < 0) {
if (LCUI_InitImageReader(&reader) != 0) {
fclose(fp);
return -2;
}
}
if (LCUI_SetImageReaderJump(&reader)) {
ret = -2;
} else {
ret = LCUI_ReadImage(&reader, out);
}
LCUI_DestroyImageReader(&reader);
fclose(fp);
return ret;
}
int LCUI_GetImageSize(const char *filepath, int *width, int *height)
{
int ret;
FILE *fp;
LCUI_ImageReaderRec reader = { 0 };
fp = fopen(filepath, "rb");
if (!fp) {
return -ENOENT;
}
ret = DetectImageType(filepath);
LCUI_SetImageReaderForFile(&reader, fp);
if (ret >= 0) {
ret = LCUI_InitImageReaderByType(&reader, ret);
}
if (ret < 0) {
if (LCUI_InitImageReader(&reader) != 0) {
fclose(fp);
return -2;
}
}
*width = reader.header.width;
*height = reader.header.height;
LCUI_DestroyImageReader(&reader);
fclose(fp);
return 0;
}
|
0cf67787973bda4687ad21e786ac93eca2fc6b0a
|
95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5
|
/Engine/lib/curl/tests/libtest/lib1514.c
|
a2350030e091efcc3bc9d4ac6800304e787d1782
|
[
"curl",
"MIT",
"LicenseRef-scancode-unknown"
] |
permissive
|
TorqueGameEngines/Torque3D
|
4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8
|
a445a4364664e299196bd551d213844486080145
|
refs/heads/development
| 2023-09-03T12:40:40.658487
| 2023-08-24T14:44:43
| 2023-08-24T14:44:43
| 267,440,108
| 1,192
| 178
|
MIT
| 2023-09-13T14:28:16
| 2020-05-27T22:35:54
|
C++
|
UTF-8
|
C
| false
| false
| 2,489
|
c
|
lib1514.c
|
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, 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.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.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
/*
* Make sure libcurl does not send a `Content-Length: -1` header when HTTP POST
* size is unknown.
*/
#include "test.h"
#include "memdebug.h"
static char data[]="dummy";
struct WriteThis {
char *readptr;
size_t sizeleft;
};
static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp)
{
struct WriteThis *pooh = (struct WriteThis *)userp;
if(size*nmemb < 1)
return 0;
if(pooh->sizeleft) {
*ptr = pooh->readptr[0]; /* copy one single byte */
pooh->readptr++; /* advance pointer */
pooh->sizeleft--; /* less data left */
return 1; /* we return 1 byte at a time! */
}
return 0; /* no more data left to deliver */
}
int test(char *URL)
{
CURL *curl;
CURLcode result = CURLE_OK;
int res = 0;
struct WriteThis pooh = { data, sizeof(data)-1 };
global_init(CURL_GLOBAL_ALL);
easy_init(curl);
easy_setopt(curl, CURLOPT_URL, URL);
easy_setopt(curl, CURLOPT_POST, 1L);
/* Purposely omit to set CURLOPT_POSTFIELDSIZE */
easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
easy_setopt(curl, CURLOPT_READDATA, &pooh);
#ifdef LIB1539
/* speak HTTP 1.0 - no chunked! */
easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
#endif
result = curl_easy_perform(curl);
test_cleanup:
curl_easy_cleanup(curl);
curl_global_cleanup();
return (int)result;
}
|
9d25d83b4c404ebd22c10dce84c338364048c0b0
|
431a5c28b8dfcc7d6ca6f4f97bf370cd770547a7
|
/src/tmx/Asn_J2735/include/asn_j2735_r63/URL-Link.h
|
446d4d0e4d1a062953c90a4ff4e43e67139f9753
|
[
"Apache-2.0"
] |
permissive
|
usdot-fhwa-OPS/V2X-Hub
|
134061cfb55d8c83e871f7fd4bbfa5d8d3092eb0
|
aae33e6a16b8a30e1faee31a7ee863d191be06b8
|
refs/heads/develop
| 2023-08-26T10:10:59.989176
| 2023-08-24T14:58:21
| 2023-08-24T14:58:21
| 168,020,929
| 106
| 63
| null | 2023-09-11T20:24:45
| 2019-01-28T19:16:45
|
C
|
UTF-8
|
C
| false
| false
| 1,091
|
h
|
URL-Link.h
|
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "DSRC"
* found in "J2735_201603_ASN_CC.asn"
* `asn1c -gen-PER -fcompound-names -fincludes-quoted -fskeletons-copy`
*/
#ifndef _URL_Link_H_
#define _URL_Link_H_
#include "asn_application.h"
/* Including external dependencies */
#include "IA5String.h"
#ifdef __cplusplus
extern "C" {
#endif
/* URL-Link */
typedef IA5String_t URL_Link_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_URL_Link;
asn_struct_free_f URL_Link_free;
asn_struct_print_f URL_Link_print;
asn_constr_check_f URL_Link_constraint;
ber_type_decoder_f URL_Link_decode_ber;
der_type_encoder_f URL_Link_encode_der;
xer_type_decoder_f URL_Link_decode_xer;
xer_type_encoder_f URL_Link_encode_xer;
oer_type_decoder_f URL_Link_decode_oer;
oer_type_encoder_f URL_Link_encode_oer;
per_type_decoder_f URL_Link_decode_uper;
per_type_encoder_f URL_Link_encode_uper;
per_type_decoder_f URL_Link_decode_aper;
per_type_encoder_f URL_Link_encode_aper;
#ifdef __cplusplus
}
#endif
#endif /* _URL_Link_H_ */
#include "asn_internal.h"
|
c4faea64ac0ba20e82a9580a4c101d78db723601
|
7c857119fe1505b1d80d6e62969661c06dc1a2f4
|
/NetworkPkg/TcpDxe/TcpDriver.c
|
1817afa38665abe544aad61fc8a89aaab773854f
|
[
"BSD-2-Clause"
] |
permissive
|
CloverHackyColor/CloverBootloader
|
7042ca7dd6b513d22be591a295e49071ae1482ee
|
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
|
refs/heads/master
| 2023-08-30T22:14:34.590134
| 2023-08-27T19:14:02
| 2023-08-27T19:14:02
| 205,810,121
| 4,734
| 770
|
BSD-2-Clause
| 2023-09-03T12:41:33
| 2019-09-02T08:22:14
|
C
|
UTF-8
|
C
| false
| false
| 28,797
|
c
|
TcpDriver.c
|
/** @file
The driver binding and service binding protocol for the TCP driver.
Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include "TcpMain.h"
UINT16 mTcp4RandomPort;
UINT16 mTcp6RandomPort;
TCP_HEARTBEAT_TIMER mTcpTimer = {
NULL,
0
};
EFI_TCP4_PROTOCOL gTcp4ProtocolTemplate = {
Tcp4GetModeData,
Tcp4Configure,
Tcp4Routes,
Tcp4Connect,
Tcp4Accept,
Tcp4Transmit,
Tcp4Receive,
Tcp4Close,
Tcp4Cancel,
Tcp4Poll
};
EFI_TCP6_PROTOCOL gTcp6ProtocolTemplate = {
Tcp6GetModeData,
Tcp6Configure,
Tcp6Connect,
Tcp6Accept,
Tcp6Transmit,
Tcp6Receive,
Tcp6Close,
Tcp6Cancel,
Tcp6Poll
};
SOCK_INIT_DATA mTcpDefaultSockData = {
SockStream,
SO_CLOSED,
NULL,
TCP_BACKLOG,
TCP_SND_BUF_SIZE,
TCP_RCV_BUF_SIZE,
IP_VERSION_4,
NULL,
TcpCreateSocketCallback,
TcpDestroySocketCallback,
NULL,
NULL,
0,
TcpDispatcher,
NULL,
};
EFI_DRIVER_BINDING_PROTOCOL gTcp4DriverBinding = {
Tcp4DriverBindingSupported,
Tcp4DriverBindingStart,
Tcp4DriverBindingStop,
0xa,
NULL,
NULL
};
EFI_DRIVER_BINDING_PROTOCOL gTcp6DriverBinding = {
Tcp6DriverBindingSupported,
Tcp6DriverBindingStart,
Tcp6DriverBindingStop,
0xa,
NULL,
NULL
};
EFI_SERVICE_BINDING_PROTOCOL gTcpServiceBinding = {
TcpServiceBindingCreateChild,
TcpServiceBindingDestroyChild
};
/**
Create and start the heartbeat timer for the TCP driver.
@retval EFI_SUCCESS The timer was successfully created and started.
@retval other The timer was not created.
**/
EFI_STATUS
TcpCreateTimer (
VOID
)
{
EFI_STATUS Status;
Status = EFI_SUCCESS;
if (mTcpTimer.RefCnt == 0) {
Status = gBS->CreateEvent (
EVT_TIMER | EVT_NOTIFY_SIGNAL,
TPL_NOTIFY,
TcpTicking,
NULL,
&mTcpTimer.TimerEvent
);
if (!EFI_ERROR (Status)) {
Status = gBS->SetTimer (
mTcpTimer.TimerEvent,
TimerPeriodic,
(UINT64) (TICKS_PER_SECOND / TCP_TICK_HZ)
);
}
}
if (!EFI_ERROR (Status)) {
mTcpTimer.RefCnt++;
}
return Status;
}
/**
Stop and destroy the heartbeat timer for TCP driver.
**/
VOID
TcpDestroyTimer (
VOID
)
{
ASSERT (mTcpTimer.RefCnt > 0);
mTcpTimer.RefCnt--;
if (mTcpTimer.RefCnt > 0) {
return;
}
gBS->SetTimer (mTcpTimer.TimerEvent, TimerCancel, 0);
gBS->CloseEvent (mTcpTimer.TimerEvent);
mTcpTimer.TimerEvent = NULL;
}
/**
The entry point for Tcp driver, which is used to install Tcp driver on the ImageHandle.
@param[in] ImageHandle The firmware allocated handle for this driver image.
@param[in] SystemTable Pointer to the EFI system table.
@retval EFI_SUCCESS The driver loaded.
@retval other The driver did not load.
**/
EFI_STATUS
EFIAPI
TcpDriverEntryPoint (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
UINT32 Seed;
//
// Install the TCP Driver Binding Protocol
//
Status = EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&gTcp4DriverBinding,
ImageHandle,
&gTcpComponentName,
&gTcpComponentName2
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Install the TCP Driver Binding Protocol
//
Status = EfiLibInstallDriverBindingComponentName2 (
ImageHandle,
SystemTable,
&gTcp6DriverBinding,
NULL,
&gTcpComponentName,
&gTcpComponentName2
);
if (EFI_ERROR (Status)) {
EfiLibUninstallDriverBindingComponentName2 (
&gTcp4DriverBinding,
&gTcpComponentName,
&gTcpComponentName2
);
return Status;
}
//
// Initialize ISS and random port.
//
Seed = NetRandomInitSeed ();
mTcpGlobalIss = NET_RANDOM (Seed) % mTcpGlobalIss;
mTcp4RandomPort = (UINT16) (TCP_PORT_KNOWN + (NET_RANDOM (Seed) % TCP_PORT_KNOWN));
mTcp6RandomPort = mTcp4RandomPort;
return EFI_SUCCESS;
}
/**
Create a new TCP4 or TCP6 driver service binding protocol
@param[in] Controller Controller handle of device to bind driver to.
@param[in] Image The TCP driver's image handle.
@param[in] IpVersion IP_VERSION_4 or IP_VERSION_6.
@retval EFI_OUT_OF_RESOURCES Failed to allocate some resources.
@retval EFI_SUCCESS A new IP6 service binding private was created.
**/
EFI_STATUS
TcpCreateService (
IN EFI_HANDLE Controller,
IN EFI_HANDLE Image,
IN UINT8 IpVersion
)
{
EFI_STATUS Status;
EFI_GUID *IpServiceBindingGuid;
EFI_GUID *TcpServiceBindingGuid;
TCP_SERVICE_DATA *TcpServiceData;
IP_IO_OPEN_DATA OpenData;
if (IpVersion == IP_VERSION_4) {
IpServiceBindingGuid = &gEfiIp4ServiceBindingProtocolGuid;
TcpServiceBindingGuid = &gEfiTcp4ServiceBindingProtocolGuid;
} else {
IpServiceBindingGuid = &gEfiIp6ServiceBindingProtocolGuid;
TcpServiceBindingGuid = &gEfiTcp6ServiceBindingProtocolGuid;
}
Status = gBS->OpenProtocol (
Controller,
TcpServiceBindingGuid,
NULL,
Image,
Controller,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
if (!EFI_ERROR (Status)) {
return EFI_ALREADY_STARTED;
}
Status = gBS->OpenProtocol (
Controller,
IpServiceBindingGuid,
NULL,
Image,
Controller,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_UNSUPPORTED;
}
//
// Create the TCP service data.
//
TcpServiceData = AllocateZeroPool (sizeof (TCP_SERVICE_DATA));
if (TcpServiceData == NULL) {
return EFI_OUT_OF_RESOURCES;
}
TcpServiceData->Signature = TCP_DRIVER_SIGNATURE;
TcpServiceData->ControllerHandle = Controller;
TcpServiceData->DriverBindingHandle = Image;
TcpServiceData->IpVersion = IpVersion;
CopyMem (
&TcpServiceData->ServiceBinding,
&gTcpServiceBinding,
sizeof (EFI_SERVICE_BINDING_PROTOCOL)
);
TcpServiceData->IpIo = IpIoCreate (Image, Controller, IpVersion);
if (TcpServiceData->IpIo == NULL) {
Status = EFI_OUT_OF_RESOURCES;
goto ON_ERROR;
}
InitializeListHead (&TcpServiceData->SocketList);
ZeroMem (&OpenData, sizeof (IP_IO_OPEN_DATA));
if (IpVersion == IP_VERSION_4) {
CopyMem (
&OpenData.IpConfigData.Ip4CfgData,
&mIp4IoDefaultIpConfigData,
sizeof (EFI_IP4_CONFIG_DATA)
);
OpenData.IpConfigData.Ip4CfgData.DefaultProtocol = EFI_IP_PROTO_TCP;
} else {
CopyMem (
&OpenData.IpConfigData.Ip6CfgData,
&mIp6IoDefaultIpConfigData,
sizeof (EFI_IP6_CONFIG_DATA)
);
OpenData.IpConfigData.Ip6CfgData.DefaultProtocol = EFI_IP_PROTO_TCP;
}
OpenData.PktRcvdNotify = TcpRxCallback;
Status = IpIoOpen (TcpServiceData->IpIo, &OpenData);
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = TcpCreateTimer ();
if (EFI_ERROR (Status)) {
goto ON_ERROR;
}
Status = gBS->InstallMultipleProtocolInterfaces (
&Controller,
TcpServiceBindingGuid,
&TcpServiceData->ServiceBinding,
NULL
);
if (EFI_ERROR (Status)) {
TcpDestroyTimer ();
goto ON_ERROR;
}
return EFI_SUCCESS;
ON_ERROR:
if (TcpServiceData->IpIo != NULL) {
IpIoDestroy (TcpServiceData->IpIo);
TcpServiceData->IpIo = NULL;
}
FreePool (TcpServiceData);
return Status;
}
/**
Callback function which provided by user to remove one node in NetDestroyLinkList process.
@param[in] Entry The entry to be removed.
@param[in] Context Pointer to the callback context corresponds to the Context in NetDestroyLinkList.
@retval EFI_SUCCESS The entry has been removed successfully.
@retval Others Fail to remove the entry.
**/
EFI_STATUS
EFIAPI
TcpDestroyChildEntryInHandleBuffer (
IN LIST_ENTRY *Entry,
IN VOID *Context
)
{
SOCKET *Sock;
EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding;
UINTN NumberOfChildren;
EFI_HANDLE *ChildHandleBuffer;
if (Entry == NULL || Context == NULL) {
return EFI_INVALID_PARAMETER;
}
Sock = NET_LIST_USER_STRUCT_S (Entry, SOCKET, Link, SOCK_SIGNATURE);
ServiceBinding = ((TCP_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->ServiceBinding;
NumberOfChildren = ((TCP_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->NumberOfChildren;
ChildHandleBuffer = ((TCP_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT *) Context)->ChildHandleBuffer;
if (!NetIsInHandleBuffer (Sock->SockHandle, NumberOfChildren, ChildHandleBuffer)) {
return EFI_SUCCESS;
}
return ServiceBinding->DestroyChild (ServiceBinding, Sock->SockHandle);
}
/**
Destroy a TCP6 or TCP4 service binding instance. It will release all
the resources allocated by the instance.
@param[in] Controller Controller handle of device to bind driver to.
@param[in] ImageHandle The TCP driver's image handle.
@param[in] NumberOfChildren Number of Handles in ChildHandleBuffer. If number
of children is zero stop the entire bus driver.
@param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
if NumberOfChildren is 0.
@param[in] IpVersion IP_VERSION_4 or IP_VERSION_6
@retval EFI_SUCCESS The resources used by the instance were cleaned up.
@retval Others Failed to clean up some of the resources.
**/
EFI_STATUS
TcpDestroyService (
IN EFI_HANDLE Controller,
IN EFI_HANDLE ImageHandle,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer, OPTIONAL
IN UINT8 IpVersion
)
{
EFI_HANDLE NicHandle;
EFI_GUID *IpProtocolGuid;
EFI_GUID *ServiceBindingGuid;
EFI_SERVICE_BINDING_PROTOCOL *ServiceBinding;
TCP_SERVICE_DATA *TcpServiceData;
EFI_STATUS Status;
LIST_ENTRY *List;
TCP_DESTROY_CHILD_IN_HANDLE_BUF_CONTEXT Context;
ASSERT ((IpVersion == IP_VERSION_4) || (IpVersion == IP_VERSION_6));
if (IpVersion == IP_VERSION_4) {
IpProtocolGuid = &gEfiIp4ProtocolGuid;
ServiceBindingGuid = &gEfiTcp4ServiceBindingProtocolGuid;
} else {
IpProtocolGuid = &gEfiIp6ProtocolGuid;
ServiceBindingGuid = &gEfiTcp6ServiceBindingProtocolGuid;
}
NicHandle = NetLibGetNicHandle (Controller, IpProtocolGuid);
if (NicHandle == NULL) {
return EFI_SUCCESS;
}
Status = gBS->OpenProtocol (
NicHandle,
ServiceBindingGuid,
(VOID **) &ServiceBinding,
ImageHandle,
Controller,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
return EFI_DEVICE_ERROR;
}
TcpServiceData = TCP_SERVICE_FROM_THIS (ServiceBinding);
if (NumberOfChildren != 0) {
List = &TcpServiceData->SocketList;
Context.ServiceBinding = ServiceBinding;
Context.NumberOfChildren = NumberOfChildren;
Context.ChildHandleBuffer = ChildHandleBuffer;
Status = NetDestroyLinkList (
List,
TcpDestroyChildEntryInHandleBuffer,
&Context,
NULL
);
} else if (IsListEmpty (&TcpServiceData->SocketList)) {
//
// Uninstall TCP servicebinding protocol
//
gBS->UninstallMultipleProtocolInterfaces (
NicHandle,
ServiceBindingGuid,
ServiceBinding,
NULL
);
//
// Destroy the IpIO consumed by TCP driver
//
IpIoDestroy (TcpServiceData->IpIo);
TcpServiceData->IpIo = NULL;
//
// Destroy the heartbeat timer.
//
TcpDestroyTimer ();
//
// Release the TCP service data
//
FreePool (TcpServiceData);
Status = EFI_SUCCESS;
}
return Status;
}
/**
Test to see if this driver supports ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to test.
@param[in] RemainingDevicePath Optional parameter use to pick a specific
child device to start.
@retval EFI_SUCCESS This driver supports this device.
@retval EFI_ALREADY_STARTED This driver is already running on this device.
@retval other This driver does not support this device.
**/
EFI_STATUS
EFIAPI
Tcp4DriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
EFI_STATUS Status;
//
// Test for the Tcp4ServiceBinding Protocol
//
Status = gBS->OpenProtocol (
ControllerHandle,
&gEfiTcp4ServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
if (!EFI_ERROR (Status)) {
return EFI_ALREADY_STARTED;
}
//
// Test for the Ip4ServiceBinding Protocol
//
Status = gBS->OpenProtocol (
ControllerHandle,
&gEfiIp4ServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
return Status;
}
/**
Start this driver on ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to bind driver to.
@param[in] RemainingDevicePath Optional parameter use to pick a specific child
device to start.
@retval EFI_SUCCESS The driver is added to ControllerHandle.
@retval EFI_OUT_OF_RESOURCES There are not enough resources to start the
driver.
@retval other The driver cannot be added to ControllerHandle.
**/
EFI_STATUS
EFIAPI
Tcp4DriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
EFI_STATUS Status;
Status = TcpCreateService (ControllerHandle, This->DriverBindingHandle, IP_VERSION_4);
if ((Status == EFI_ALREADY_STARTED) || (Status == EFI_UNSUPPORTED)) {
Status = EFI_SUCCESS;
}
return Status;
}
/**
Stop this driver on ControllerHandle.
@param[in] This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
@param[in] ControllerHandle A handle to the device being stopped. The handle must
support a bus specific I/O protocol for the driver
to use to stop the device.
@param[in] NumberOfChildren The number of child device handles in ChildHandleBuffer.
@param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
if NumberOfChildren is 0.
@retval EFI_SUCCESS The device was stopped.
@retval EFI_DEVICE_ERROR The device could not be stopped due to a device error.
**/
EFI_STATUS
EFIAPI
Tcp4DriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
)
{
return TcpDestroyService (
ControllerHandle,
This->DriverBindingHandle,
NumberOfChildren,
ChildHandleBuffer,
IP_VERSION_4
);
}
/**
Test to see if this driver supports ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to test.
@param[in] RemainingDevicePath Optional parameter use to pick a specific
child device to start.
@retval EFI_SUCCESS This driver supports this device.
@retval EFI_ALREADY_STARTED This driver is already running on this device.
@retval other This driver does not support this device.
**/
EFI_STATUS
EFIAPI
Tcp6DriverBindingSupported (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
EFI_STATUS Status;
//
// Test for the Tcp6ServiceBinding Protocol
//
Status = gBS->OpenProtocol (
ControllerHandle,
&gEfiTcp6ServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
if (!EFI_ERROR (Status)) {
return EFI_ALREADY_STARTED;
}
//
// Test for the Ip6ServiceBinding Protocol
//
Status = gBS->OpenProtocol (
ControllerHandle,
&gEfiIp6ServiceBindingProtocolGuid,
NULL,
This->DriverBindingHandle,
ControllerHandle,
EFI_OPEN_PROTOCOL_TEST_PROTOCOL
);
return Status;
}
/**
Start this driver on ControllerHandle.
@param[in] This Protocol instance pointer.
@param[in] ControllerHandle Handle of device to bind driver to.
@param[in] RemainingDevicePath Optional parameter use to pick a specific child
device to start.
@retval EFI_SUCCESS The driver is added to ControllerHandle.
@retval EFI_OUT_OF_RESOURCES There are not enough resources to start the
driver.
@retval other The driver cannot be added to ControllerHandle.
**/
EFI_STATUS
EFIAPI
Tcp6DriverBindingStart (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN EFI_DEVICE_PATH_PROTOCOL *RemainingDevicePath OPTIONAL
)
{
EFI_STATUS Status;
Status = TcpCreateService (ControllerHandle, This->DriverBindingHandle, IP_VERSION_6);
if ((Status == EFI_ALREADY_STARTED) || (Status == EFI_UNSUPPORTED)) {
Status = EFI_SUCCESS;
}
return Status;
}
/**
Stop this driver on ControllerHandle.
@param[in] This A pointer to the EFI_DRIVER_BINDING_PROTOCOL instance.
@param[in] ControllerHandle A handle to the device being stopped. The handle must
support a bus specific I/O protocol for the driver
to use to stop the device.
@param[in] NumberOfChildren The number of child device handles in ChildHandleBuffer.
@param[in] ChildHandleBuffer An array of child handles to be freed. May be NULL
if NumberOfChildren is 0.
@retval EFI_SUCCESS The device was stopped.
@retval EFI_DEVICE_ERROR The device could not be stopped due to a device error.
**/
EFI_STATUS
EFIAPI
Tcp6DriverBindingStop (
IN EFI_DRIVER_BINDING_PROTOCOL *This,
IN EFI_HANDLE ControllerHandle,
IN UINTN NumberOfChildren,
IN EFI_HANDLE *ChildHandleBuffer OPTIONAL
)
{
return TcpDestroyService (
ControllerHandle,
This->DriverBindingHandle,
NumberOfChildren,
ChildHandleBuffer,
IP_VERSION_6
);
}
/**
The Callback funtion called after the TCP socket was created.
@param[in] This Pointer to the socket just created
@param[in] Context Context of the socket
@retval EFI_SUCCESS This protocol installed successfully.
@retval other An error occured.
**/
EFI_STATUS
TcpCreateSocketCallback (
IN SOCKET *This,
IN VOID *Context
)
{
EFI_STATUS Status;
TCP_SERVICE_DATA *TcpServiceData;
EFI_GUID *IpProtocolGuid;
VOID *Ip;
if (This->IpVersion == IP_VERSION_4) {
IpProtocolGuid = &gEfiIp4ProtocolGuid;
} else {
IpProtocolGuid = &gEfiIp6ProtocolGuid;
}
TcpServiceData = ((TCP_PROTO_DATA *) This->ProtoReserved)->TcpService;
//
// Open the default IP protocol of IP_IO BY_DRIVER.
//
Status = gBS->OpenProtocol (
TcpServiceData->IpIo->ChildHandle,
IpProtocolGuid,
&Ip,
TcpServiceData->DriverBindingHandle,
This->SockHandle,
EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER
);
if (EFI_ERROR (Status)) {
return Status;
}
//
// Open the device path on the handle where service binding resides on.
//
Status = gBS->OpenProtocol (
TcpServiceData->ControllerHandle,
&gEfiDevicePathProtocolGuid,
(VOID **) &This->ParentDevicePath,
TcpServiceData->DriverBindingHandle,
This->SockHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
gBS->CloseProtocol (
TcpServiceData->IpIo->ChildHandle,
IpProtocolGuid,
TcpServiceData->DriverBindingHandle,
This->SockHandle
);
} else {
//
// Insert this socket into the SocketList.
//
InsertTailList (&TcpServiceData->SocketList, &This->Link);
}
return Status;
}
/**
The callback function called before the TCP socket was to be destroyed.
@param[in] This The TCP socket to be destroyed.
@param[in] Context The context of the socket.
**/
VOID
TcpDestroySocketCallback (
IN SOCKET *This,
IN VOID *Context
)
{
TCP_SERVICE_DATA *TcpServiceData;
EFI_GUID *IpProtocolGuid;
if (This->IpVersion == IP_VERSION_4) {
IpProtocolGuid = &gEfiIp4ProtocolGuid;
} else {
IpProtocolGuid = &gEfiIp6ProtocolGuid;
}
TcpServiceData = ((TCP_PROTO_DATA *) This->ProtoReserved)->TcpService;
//
// Remove this node from the list.
//
RemoveEntryList (&This->Link);
//
// Close the IP protocol.
//
gBS->CloseProtocol (
TcpServiceData->IpIo->ChildHandle,
IpProtocolGuid,
TcpServiceData->DriverBindingHandle,
This->SockHandle
);
}
/**
Creates a child handle with a set of TCP services.
The CreateChild() function installs a protocol on ChildHandle.
If ChildHandle is a pointer to NULL, then a new handle is created and returned in ChildHandle.
If ChildHandle is not a pointer to NULL, then the protocol installs on the existing ChildHandle.
@param[in] This Pointer to the EFI_SERVICE_BINDING_PROTOCOL instance.
@param[in, out] ChildHandle Pointer to the handle of the child to create.
If it is NULL, then a new handle is created.
If it is a pointer to an existing UEFI handle,
then the protocol is added to the existing UEFI handle.
@retval EFI_SUCCES The protocol was added to ChildHandle.
@retval EFI_INVALID_PARAMETER ChildHandle is NULL.
@retval EFI_OUT_OF_RESOURCES There are not enough resources available to create
the child.
@retval other The child handle was not created.
**/
EFI_STATUS
EFIAPI
TcpServiceBindingCreateChild (
IN EFI_SERVICE_BINDING_PROTOCOL *This,
IN OUT EFI_HANDLE *ChildHandle
)
{
SOCKET *Sock;
TCP_SERVICE_DATA *TcpServiceData;
TCP_PROTO_DATA TcpProto;
EFI_STATUS Status;
EFI_TPL OldTpl;
if (NULL == This || NULL == ChildHandle) {
return EFI_INVALID_PARAMETER;
}
OldTpl = gBS->RaiseTPL (TPL_CALLBACK);
Status = EFI_SUCCESS;
TcpServiceData = TCP_SERVICE_FROM_THIS (This);
TcpProto.TcpService = TcpServiceData;
TcpProto.TcpPcb = NULL;
//
// Create a tcp instance with defualt Tcp default
// sock init data and TcpProto
//
mTcpDefaultSockData.ProtoData = &TcpProto;
mTcpDefaultSockData.DataSize = sizeof (TCP_PROTO_DATA);
mTcpDefaultSockData.DriverBinding = TcpServiceData->DriverBindingHandle;
mTcpDefaultSockData.IpVersion = TcpServiceData->IpVersion;
if (TcpServiceData->IpVersion == IP_VERSION_4) {
mTcpDefaultSockData.Protocol = &gTcp4ProtocolTemplate;
} else {
mTcpDefaultSockData.Protocol = &gTcp6ProtocolTemplate;
}
Sock = SockCreateChild (&mTcpDefaultSockData);
if (NULL == Sock) {
DEBUG (
(EFI_D_ERROR,
"TcpDriverBindingCreateChild: No resource to create a Tcp Child\n")
);
Status = EFI_OUT_OF_RESOURCES;
} else {
*ChildHandle = Sock->SockHandle;
}
mTcpDefaultSockData.ProtoData = NULL;
gBS->RestoreTPL (OldTpl);
return Status;
}
/**
Destroys a child handle with a set of TCP services.
The DestroyChild() function does the opposite of CreateChild(). It removes a protocol
that was installed by CreateChild() from ChildHandle. If the removed protocol is the
last protocol on ChildHandle, then ChildHandle is destroyed.
@param This Pointer to the EFI_SERVICE_BINDING_PROTOCOL instance.
@param ChildHandle Handle of the child to be destroyed.
@retval EFI_SUCCES The protocol was removed from ChildHandle.
@retval EFI_UNSUPPORTED ChildHandle does not support the protocol that is being removed.
@retval EFI_INVALID_PARAMETER Child handle is NULL.
@retval EFI_ACCESS_DENIED The protocol could not be removed from the ChildHandle
because its services are being used.
@retval other The child handle was not destroyed.
**/
EFI_STATUS
EFIAPI
TcpServiceBindingDestroyChild (
IN EFI_SERVICE_BINDING_PROTOCOL *This,
IN EFI_HANDLE ChildHandle
)
{
EFI_STATUS Status;
VOID *Tcp;
SOCKET *Sock;
if (NULL == This || NULL == ChildHandle) {
return EFI_INVALID_PARAMETER;
}
//
// retrieve the Tcp4 protocol from ChildHandle
//
Status = gBS->OpenProtocol (
ChildHandle,
&gEfiTcp4ProtocolGuid,
&Tcp,
gTcp4DriverBinding.DriverBindingHandle,
ChildHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
//
// No Tcp4, try the Tcp6 protocol
//
Status = gBS->OpenProtocol (
ChildHandle,
&gEfiTcp6ProtocolGuid,
&Tcp,
gTcp6DriverBinding.DriverBindingHandle,
ChildHandle,
EFI_OPEN_PROTOCOL_GET_PROTOCOL
);
if (EFI_ERROR (Status)) {
Status = EFI_UNSUPPORTED;
}
}
if (!EFI_ERROR (Status)) {
//
// destroy this sock and related Tcp protocol control
// block
//
Sock = SOCK_FROM_THIS (Tcp);
SockDestroyChild (Sock);
}
return Status;
}
|
11a1b3e2b793d798c540eee050b974c43f34fe71
|
c7a993dcd7efa07038a77ba7057b04b9450be550
|
/marching_cube/model/cffi/src/curvature_constraint.h
|
530b99b16e34779cc32b6a3c5df0b9266aea98fe
|
[
"MIT"
] |
permissive
|
yiyiliao/deep_marching_cubes
|
6d5f889a45367239c719892c426bfd8a7865a4db
|
e6efeb4da828403442b930709666f51a2476636c
|
refs/heads/master
| 2023-03-10T19:21:12.207458
| 2023-02-28T01:50:51
| 2023-02-28T01:50:51
| 137,336,879
| 256
| 36
| null | 2020-09-17T19:00:11
| 2018-06-14T09:29:27
|
Python
|
UTF-8
|
C
| false
| false
| 498
|
h
|
curvature_constraint.h
|
int curvature_constraint_forward(THFloatTensor *offset, THFloatTensor *topology, THFloatTensor *topology_empty, THFloatTensor *xTable, THFloatTensor *yTable, THFloatTensor *zTable, THFloatTensor *innerTable, THFloatTensor *loss );
int curvature_constraint_backward(THFloatTensor *grad_output, THFloatTensor *offset, THFloatTensor *topology, THFloatTensor *topology_empty, THFloatTensor *xTable, THFloatTensor *yTable, THFloatTensor *zTable, THFloatTensor *innerTable, THFloatTensor *grad_offset );
|
1e3ea26a98a3aec1a73edfabf1af4412d7278dd4
|
03b2c80dbc41e904b167d504666e27d798da5447
|
/src/eval_execute.h
|
7b9b5febcd6afccbce061d1b75d4d75543b7dc25
|
[
"Unlicense"
] |
permissive
|
nptcl/npt
|
7c1570b497cdce0b8971cb445fbc04cb500232d3
|
aa714a2370ac9fa5348c2fc96159b40b9de3de07
|
refs/heads/master
| 2023-03-20T09:13:54.669118
| 2022-07-02T11:17:44
| 2022-07-02T11:17:44
| 171,985,905
| 160
| 12
|
Unlicense
| 2023-03-11T01:36:37
| 2019-02-22T03:11:34
|
C
|
UTF-8
|
C
| false
| false
| 901
|
h
|
eval_execute.h
|
#ifndef __EVAL_EXECUTE_HEADER__
#define __EVAL_EXECUTE_HEADER__
#include "execute.h"
#include "typedef.h"
#define eval_execute_partial_ _n(eval_execute_partial_)
#define eval_result_partial_ _n(eval_result_partial_)
#define eval_result_partial_form_ _n(eval_result_partial_form_)
#define eval_result_compile_ _n(eval_result_compile_)
#define eval_result_macro_ _n(eval_result_macro_)
#define eval_toplevel_loop_ _n(eval_toplevel_loop_)
#define eval_stream_toplevel_ _n(eval_stream_toplevel_)
int eval_execute_partial_(Execute ptr, addr pos);
int eval_result_partial_(Execute ptr, addr pos, addr *ret);
int eval_result_partial_form_(Execute ptr, addr pos, addr *ret);
int eval_result_compile_(Execute ptr, addr pos, addr *ret);
int eval_result_macro_(Execute ptr, addr pos, addr *ret);
int eval_toplevel_loop_(Execute ptr, addr stream);
int eval_stream_toplevel_(Execute ptr, addr stream);
#endif
|
59bcc8d78f3a26f2bb7cc6ab8ddec8801f949b99
|
0744dcc5394cebf57ebcba343747af6871b67017
|
/os/kernel/pthread/pthread_condtimedwait.c
|
25fe0400e55a7e9137cd08ff42b5c1cae50f2d9d
|
[
"GPL-1.0-or-later",
"BSD-3-Clause",
"ISC",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
"Apache-2.0"
] |
permissive
|
Samsung/TizenRT
|
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
|
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
|
refs/heads/master
| 2023-08-31T08:59:33.327998
| 2023-08-08T06:09:20
| 2023-08-31T04:38:20
| 82,517,252
| 590
| 719
|
Apache-2.0
| 2023-09-14T06:54:49
| 2017-02-20T04:38:30
|
C
|
UTF-8
|
C
| false
| false
| 11,067
|
c
|
pthread_condtimedwait.c
|
/****************************************************************************
*
* Copyright 2016 Samsung Electronics 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.
*
****************************************************************************/
/****************************************************************************
* kernel/pthread/pthread_condtimedwait.c
*
* Copyright (C) 2007-2009, 2013-2014 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <tinyara/config.h>
#include <tinyara/compiler.h>
#include <stdint.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <assert.h>
#include <debug.h>
#include <tinyara/cancelpt.h>
#include <tinyara/wdog.h>
#include <tinyara/ttrace.h>
#include "sched/sched.h"
#include "pthread/pthread.h"
#include "clock/clock.h"
#include "signal/signal.h"
/****************************************************************************
* Definitions
****************************************************************************/
/****************************************************************************
* Private Type Declarations
****************************************************************************/
/****************************************************************************
* Global Variables
****************************************************************************/
/****************************************************************************
* Private Variables
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: pthread_condtimedout
*
* Description:
* This function is called if the timeout elapses before
* the condition is signaled.
*
* Parameters:
* argc - the number of arguments (should be 2)
* pid - the task ID of the task to wakeup
* signo - The signal to use to wake up the task
*
* Return Value:
* None
*
* Assumptions:
*
****************************************************************************/
static void pthread_condtimedout(int argc, uint32_t pid, uint32_t signo)
{
#ifdef HAVE_GROUP_MEMBERS
FAR struct tcb_s *tcb;
siginfo_t info;
/* The logic below if equivalent to sigqueue(), but uses sig_tcbdispatch()
* instead of sig_dispatch(). This avoids the group signal deliver logic
* and assures, instead, that the signal is delivered specifically to this
* thread that is known to be waiting on the signal.
*/
/* Get the waiting TCB. sched_gettcb() might return NULL if the task has
* exited for some reason.
*/
tcb = sched_gettcb((pid_t)pid);
if (tcb) {
/* Create the siginfo structure */
info.si_signo = signo;
info.si_code = SI_QUEUE;
info.si_value.sival_ptr = NULL;
#ifdef CONFIG_SCHED_HAVE_PARENT
info.si_pid = (pid_t)pid;
info.si_status = OK;
#endif
/* Process the receipt of the signal. The scheduler is not locked as
* is normally the case when this function is called because we are in
* a watchdog timer interrupt handler.
*/
(void)sig_tcbdispatch(tcb, &info);
}
#else /* HAVE_GROUP_MEMBERS */
/* Things are a little easier if there are not group members. We can just
* use sigqueue().
*/
#ifdef CONFIG_CAN_PASS_STRUCTS
union sigval value;
/* Send the specified signal to the specified task. */
value.sival_ptr = NULL;
(void)sigqueue((int)pid, (int)signo, value);
#else
(void)sigqueue((int)pid, (int)signo, NULL);
#endif
#endif /* HAVE_GROUP_MEMBERS */
}
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: pthread_cond_timedwait
*
* Description:
* A thread can perform a timed wait on a condition variable.
*
* Parameters:
* cond - the condition variable to wait on
* mutex - the mutex that protects the condition variable
* abstime - wait until this absolute time
*
* Return Value:
* OK (0) on success; A non-zero errno value is returned on failure.
*
* Assumptions:
* Timing is of resolution 1 msec, with +/-1 millisecond accuracy.
*
****************************************************************************/
int pthread_cond_timedwait(FAR pthread_cond_t *cond, FAR pthread_mutex_t *mutex, FAR const struct timespec *abstime)
{
FAR struct tcb_s *rtcb = this_task();
int ticks;
int mypid = (int)getpid();
irqstate_t int_state;
uint16_t oldstate;
int ret = OK;
int status;
trace_begin(TTRACE_TAG_TASK, "pthread_cond_timedwait");
svdbg("cond=0x%p mutex=0x%p abstime=0x%p\n", cond, mutex, abstime);
DEBUGASSERT(rtcb->waitdog == NULL);
/* pthread_cond_timedwait() is a cancellation point */
(void)enter_cancellation_point();
/* Make sure that non-NULL references were provided. */
if (!cond || !mutex) {
ret = EINVAL;
}
/* Make sure that the caller holds the mutex */
else if (mutex->pid != mypid) {
ret = EPERM;
}
/* If no wait time is provided, this function degenerates to
* the same behavior as pthread_cond_wait().
*/
else if (!abstime) {
ret = pthread_cond_wait(cond, mutex);
}
else {
/* Create a watchdog */
rtcb->waitdog = wd_create();
if (!rtcb->waitdog) {
ret = ENOMEM;
} else {
svdbg("Give up mutex...\n");
/* We must disable pre-emption and interrupts here so that
* the time stays valid until the wait begins. This adds
* complexity because we assure that interrupts and
* pre-emption are re-enabled correctly.
*/
sched_lock();
int_state = irqsave();
/* Convert the timespec to clock ticks. We must disable pre-emption
* here so that this time stays valid until the wait begins.
*/
ret = clock_abstime2ticks(CLOCK_REALTIME, abstime, &ticks);
if (ret) {
/* Restore interrupts (pre-emption will be enabled when
* we fall through the if/then/else)
*/
irqrestore(int_state);
} else {
/* Check the absolute time to wait. If it is now or in the past, then
* just return with the timedout condition.
*/
if (ticks <= 0) {
/* Restore interrupts and indicate that we have already timed out.
* (pre-emption will be enabled when we fall through the
* if/then/else
*/
irqrestore(int_state);
ret = ETIMEDOUT;
} else {
/* Give up the mutex */
mutex->pid = -1;
ret = pthread_mutex_give(mutex);
if (ret != 0) {
/* Restore interrupts (pre-emption will be enabled when
* we fall through the if/then/else)
*/
irqrestore(int_state);
} else {
/* Start the watchdog */
wd_start(rtcb->waitdog, ticks, (wdentry_t)pthread_condtimedout, 2, (uint32_t)mypid, (uint32_t)SIGCONDTIMEDOUT);
/* Take the condition semaphore. Do not restore interrupts
* until we return from the wait. This is necessary to
* make sure that the watchdog timer and the condition wait
* are started atomically.
*/
status = sem_wait((sem_t *)&cond->sem);
/* Did we get the condition semaphore. */
if (status != OK) {
/* NO.. Handle the special case where the semaphore wait was
* awakened by the receipt of a signal -- presumably the
* signal posted by pthread_condtimedout().
*/
if (get_errno() == EINTR) {
sdbg("Timedout!\n");
ret = ETIMEDOUT;
} else {
ret = EINVAL;
}
}
/* The interrupts stay disabled until after we sample the errno.
* This is because when debug is enabled and the console is used
* for debug output, then the errno can be altered by interrupt
* handling! (bad)
*/
irqrestore(int_state);
}
/* Reacquire the mutex (retaining the ret). */
svdbg("Re-locking...\n");
oldstate = pthread_disable_cancel();
status = pthread_mutex_take(mutex, false);
pthread_enable_cancel(oldstate);
if (status == OK) {
mutex->pid = mypid;
} else if (ret == 0) {
ret = status;
}
}
/* Re-enable pre-emption (It is expected that interrupts
* have already been re-enabled in the above logic)
*/
sched_unlock();
}
/* We no longer need the watchdog */
wd_delete(rtcb->waitdog);
rtcb->waitdog = NULL;
}
}
svdbg("Returning %d\n", ret);
leave_cancellation_point();
trace_end(TTRACE_TAG_TASK);
return ret;
}
|
a91b4c47e19006b45d00c2fb14f67e083414ef9a
|
792e930d13e9d5a838b64c86dcd55c75e6a1e3c5
|
/trilinear_c/src/trilinear_cuda.h
|
c4c3e6cb813dc79b242b36760245e206c427f527
|
[
"Apache-2.0"
] |
permissive
|
HuiZeng/Image-Adaptive-3DLUT
|
3147c117250c849a2bafb8b1f42d271cb9a8f0fb
|
b491f6df64a588864739a157db271e5c848e1805
|
refs/heads/master
| 2023-07-29T21:36:11.319991
| 2022-11-26T04:22:59
| 2022-11-26T04:22:59
| 278,017,089
| 667
| 119
| null | 2021-09-23T01:49:44
| 2020-07-08T07:11:16
|
Python
|
UTF-8
|
C
| false
| false
| 398
|
h
|
trilinear_cuda.h
|
int trilinear_forward_cuda(THCudaTensor * lut, THCudaTensor * image, THCudaTensor * output,
int lut_dim, int shift, float binsize, int width, int height, int batch);
int trilinear_backward_cuda(THCudaTensor * image, THCudaTensor * image_grad, THCudaTensor * lut_grad,
int lut_dim, int shift, float binsize, int width, int height, int batch);
|
b9b7e3e9e9cb404a6a3fb0be4ca9d480910a7891
|
ea9ac7578bc8a8fc83377f651b80e19920338fda
|
/src/gallium/auxiliary/target-helpers/drm_helper_public.h
|
32c0f4344eec537a4b734fed55c2eb84161a7778
|
[] |
no_license
|
yuq/mesa-lima
|
9d263945e23118c7aa997bb9fcb87ae6bf7ddf0d
|
2adeaa87e813644dcf70f903c0ac909d65ef2972
|
refs/heads/lima-18.1
| 2021-01-25T11:03:44.405200
| 2018-05-27T12:53:15
| 2018-05-27T12:53:15
| 93,909,976
| 186
| 21
| null | 2018-06-05T01:32:44
| 2017-06-10T02:07:43
|
C
|
UTF-8
|
C
| false
| false
| 2,289
|
h
|
drm_helper_public.h
|
#ifndef _DRM_HELPER_PUBLIC_H
#define _DRM_HELPER_PUBLIC_H
enum drm_conf;
struct drm_conf_ret;
struct pipe_screen;
struct pipe_screen_config;
struct pipe_screen *
pipe_i915_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_ilo_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_nouveau_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_r300_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_r600_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_radeonsi_create_screen(int fd, const struct pipe_screen_config *config);
const struct drm_conf_ret *
pipe_radeonsi_configuration_query(enum drm_conf conf);
struct pipe_screen *
pipe_vmwgfx_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_freedreno_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_virgl_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_vc4_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_vc5_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_pl111_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_exynos_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_meson_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_rockchip_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_sun4i_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_etna_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_imx_drm_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_tegra_create_screen(int fd, const struct pipe_screen_config *config);
struct pipe_screen *
pipe_lima_create_screen(int fd, const struct pipe_screen_config *config);
const struct drm_conf_ret *
pipe_default_configuration_query(enum drm_conf conf);
#endif /* _DRM_HELPER_PUBLIC_H */
|
4d5c462a2198153a46f96f1420b4e6f7d307d550
|
9467e2502183e843a67736800199e31674b1d8f6
|
/HybridCLRData/LocalIl2CppData-OSXEditor/il2cpp/external/mono/mono/metadata/verify.c
|
e509ed680c13c646aedb4b49a84abf321204d2f3
|
[
"Apache-2.0"
] |
permissive
|
yimengfan/BDFramework.Core
|
3a046fcd755a84ba55d648dd3ad52c37a1cc1a04
|
81380fce8e84367f912777717665b53f074ab617
|
refs/heads/master
| 2023-09-04T10:08:47.644992
| 2023-07-05T16:22:11
| 2023-07-05T16:22:11
| 85,928,537
| 2,421
| 497
|
Apache-2.0
| 2023-03-21T06:56:21
| 2017-03-23T09:03:48
|
C#
|
UTF-8
|
C
| false
| false
| 210,896
|
c
|
verify.c
|
/**
* \file
*
* Author:
* Mono Project (http://www.mono-project.com)
*
* Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
* Copyright 2004-2009 Novell, Inc (http://www.novell.com)
* Copyright 2011 Rodrigo Kumpera
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include <config.h>
#include <mono/metadata/object-internals.h>
#include <mono/metadata/dynamic-image-internals.h>
#include <mono/metadata/verify.h>
#include <mono/metadata/verify-internals.h>
#include <mono/metadata/opcodes.h>
#include <mono/metadata/tabledefs.h>
#include <mono/metadata/reflection.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-endian.h>
#include <mono/metadata/metadata.h>
#include <mono/metadata/metadata-internals.h>
#include <mono/metadata/class-internals.h>
#include <mono/metadata/security-manager.h>
#include <mono/metadata/security-core-clr.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/mono-basic-block.h>
#include <mono/metadata/attrdefs.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/monobitset.h>
#include <string.h>
#include <ctype.h>
static MiniVerifierMode verifier_mode = MONO_VERIFIER_MODE_OFF;
static gboolean verify_all = FALSE;
/*
* Set the desired level of checks for the verfier.
*
*/
void
mono_verifier_set_mode (MiniVerifierMode mode)
{
verifier_mode = mode;
}
void
mono_verifier_enable_verify_all ()
{
verify_all = TRUE;
}
#ifndef DISABLE_VERIFIER
/*
* Pull the list of opcodes
*/
#define OPDEF(a,b,c,d,e,f,g,h,i,j) \
a = i,
enum {
#include "mono/cil/opcode.def"
LAST = 0xff
};
#undef OPDEF
#ifdef MONO_VERIFIER_DEBUG
#define VERIFIER_DEBUG(code) do { code } while (0)
#else
#define VERIFIER_DEBUG(code)
#endif
//////////////////////////////////////////////////////////////////
#define IS_STRICT_MODE(ctx) (((ctx)->level & MONO_VERIFY_NON_STRICT) == 0)
#define IS_FAIL_FAST_MODE(ctx) (((ctx)->level & MONO_VERIFY_FAIL_FAST) == MONO_VERIFY_FAIL_FAST)
#define IS_SKIP_VISIBILITY(ctx) (((ctx)->level & MONO_VERIFY_SKIP_VISIBILITY) == MONO_VERIFY_SKIP_VISIBILITY)
#define IS_REPORT_ALL_ERRORS(ctx) (((ctx)->level & MONO_VERIFY_REPORT_ALL_ERRORS) == MONO_VERIFY_REPORT_ALL_ERRORS)
#define CLEAR_PREFIX(ctx, prefix) do { (ctx)->prefix_set &= ~(prefix); } while (0)
#define ADD_VERIFY_INFO(__ctx, __msg, __status, __exception) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = __status; \
vinfo->info.message = ( __msg ); \
vinfo->exception_type = (__exception); \
(__ctx)->list = g_slist_prepend ((__ctx)->list, vinfo); \
} while (0)
//TODO support MONO_VERIFY_REPORT_ALL_ERRORS
#define ADD_VERIFY_ERROR(__ctx, __msg) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, MONO_EXCEPTION_INVALID_PROGRAM); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE(__ctx, __msg) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, MONO_EXCEPTION_UNVERIFIABLE_IL); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define ADD_VERIFY_ERROR2(__ctx, __msg, __exception) \
do { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_ERROR, __exception); \
(__ctx)->valid = 0; \
} while (0)
#define CODE_NOT_VERIFIABLE2(__ctx, __msg, __exception) \
do { \
if ((__ctx)->verifiable || IS_REPORT_ALL_ERRORS (__ctx)) { \
ADD_VERIFY_INFO(__ctx, __msg, MONO_VERIFY_NOT_VERIFIABLE, __exception); \
(__ctx)->verifiable = 0; \
if (IS_FAIL_FAST_MODE (__ctx)) \
(__ctx)->valid = 0; \
} \
} while (0)
#define CHECK_ADD4_OVERFLOW_UN(a, b) ((guint32)(0xFFFFFFFFU) - (guint32)(b) < (guint32)(a))
#define CHECK_ADD8_OVERFLOW_UN(a, b) ((guint64)(0xFFFFFFFFFFFFFFFFUL) - (guint64)(b) < (guint64)(a))
#if SIZEOF_VOID_P == 4
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD4_OVERFLOW_UN(a, b)
#else
#define CHECK_ADDP_OVERFLOW_UN(a,b) CHECK_ADD8_OVERFLOW_UN(a, b)
#endif
#define ADDP_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADDP_OVERFLOW_UN (a, b))
#define ADD_IS_GREATER_OR_OVF(a, b, c) (((a) + (b) > (c)) || CHECK_ADD4_OVERFLOW_UN (a, b))
/*Flags to be used with ILCodeDesc::flags */
enum {
/*Instruction has not been processed.*/
IL_CODE_FLAG_NOT_PROCESSED = 0,
/*Instruction was decoded by mono_method_verify loop.*/
IL_CODE_FLAG_SEEN = 1,
/*Instruction was target of a branch or is at a protected block boundary.*/
IL_CODE_FLAG_WAS_TARGET = 2,
/*Used by stack_init to avoid double initialize each entry.*/
IL_CODE_FLAG_STACK_INITED = 4,
/*Used by merge_stacks to decide if it should just copy the eval stack.*/
IL_CODE_STACK_MERGED = 8,
/*This instruction is part of the delegate construction sequence, it cannot be target of a branch.*/
IL_CODE_DELEGATE_SEQUENCE = 0x10,
/*This is a delegate created from a ldftn to a non final virtual method*/
IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL = 0x20,
/*This is a call to a non final virtual method*/
IL_CODE_CALL_NONFINAL_VIRTUAL = 0x40,
};
typedef enum {
RESULT_VALID,
RESULT_UNVERIFIABLE,
RESULT_INVALID
} verify_result_t;
typedef struct {
MonoType *type;
int stype;
MonoMethod *method;
} ILStackDesc;
typedef struct {
ILStackDesc *stack;
guint16 size, max_size;
guint16 flags;
} ILCodeDesc;
typedef struct {
int max_args;
int max_stack;
int verifiable;
int valid;
int level;
int code_size;
ILCodeDesc *code;
ILCodeDesc eval;
MonoType **params;
GSList *list;
/*Allocated fnptr MonoType that should be freed by us.*/
GSList *funptrs;
/*Type dup'ed exception types from catch blocks.*/
GSList *exception_types;
int num_locals;
MonoType **locals;
char *locals_verification_state;
/*TODO get rid of target here, need_merge in mono_method_verify and hoist the merging code in the branching code*/
int target;
guint32 ip_offset;
MonoMethodSignature *signature;
MonoMethodHeader *header;
MonoGenericContext *generic_context;
MonoImage *image;
MonoMethod *method;
/*This flag helps solving a corner case of delegate verification in that you cannot have a "starg 0"
*on a method that creates a delegate for a non-final virtual method using ldftn*/
gboolean has_this_store;
/*This flag is used to control if the contructor of the parent class has been called.
*If the this pointer is pushed on the eval stack and it's a reference type constructor and
* super_ctor_called is false, the uninitialized flag is set on the pushed value.
*
* Poping an uninitialized this ptr from the eval stack is an unverifiable operation unless
* the safe variant is used. Only a few opcodes can use it : dup, pop, ldfld, stfld and call to a constructor.
*/
gboolean super_ctor_called;
guint32 prefix_set;
gboolean has_flags;
MonoType *constrained_type;
} VerifyContext;
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external);
static int
get_stack_type (MonoType *type);
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn);
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass);
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method);
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type);
static gboolean
verifier_class_is_assignable_from (MonoClass *target, MonoClass *candidate);
//////////////////////////////////////////////////////////////////
enum {
TYPE_INV = 0, /* leave at 0. */
TYPE_I4 = 1,
TYPE_I8 = 2,
TYPE_NATIVE_INT = 3,
TYPE_R8 = 4,
/* Used by operator tables to resolve pointer types (managed & unmanaged) and by unmanaged pointer types*/
TYPE_PTR = 5,
/* value types and classes */
TYPE_COMPLEX = 6,
/* Number of types, used to define the size of the tables*/
TYPE_MAX = 6,
/* Used by tables to signal that a result is not verifiable*/
NON_VERIFIABLE_RESULT = 0x80,
/*Mask used to extract just the type, excluding flags */
TYPE_MASK = 0x0F,
/* The stack type is a managed pointer, unmask the value to res */
POINTER_MASK = 0x100,
/*Stack type with the pointer mask*/
RAW_TYPE_MASK = 0x10F,
/* Controlled Mutability Manager Pointer */
CMMP_MASK = 0x200,
/* The stack type is a null literal*/
NULL_LITERAL_MASK = 0x400,
/**Used by ldarg.0 and family to let delegate verification happens.*/
THIS_POINTER_MASK = 0x800,
/**Signals that this is a boxed value type*/
BOXED_MASK = 0x1000,
/*This is an unitialized this ref*/
UNINIT_THIS_MASK = 0x2000,
/* This is a safe to return byref */
SAFE_BYREF_MASK = 0x4000,
};
static const char* const
type_names [TYPE_MAX + 1] = {
"Invalid",
"Int32",
"Int64",
"Native Int",
"Float64",
"Native Pointer",
"Complex"
};
enum {
PREFIX_UNALIGNED = 1,
PREFIX_VOLATILE = 2,
PREFIX_TAIL = 4,
PREFIX_CONSTRAINED = 8,
PREFIX_READONLY = 16
};
//////////////////////////////////////////////////////////////////
#ifdef ENABLE_VERIFIER_STATS
#define _MEM_ALLOC(amt) do { allocated_memory += (amt); working_set += (amt); } while (0)
#define _MEM_FREE(amt) do { working_set -= (amt); } while (0)
static int allocated_memory;
static int working_set;
static int max_allocated_memory;
static int max_working_set;
static int total_allocated_memory;
static void
finish_collect_stats (void)
{
max_allocated_memory = MAX (max_allocated_memory, allocated_memory);
max_working_set = MAX (max_working_set, working_set);
total_allocated_memory += allocated_memory;
allocated_memory = working_set = 0;
}
static void
init_verifier_stats (void)
{
static gboolean inited;
if (!inited) {
inited = TRUE;
mono_counters_register ("Maximum memory allocated during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_allocated_memory);
mono_counters_register ("Maximum memory used during verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &max_working_set);
mono_counters_register ("Total memory allocated for verification", MONO_COUNTER_METADATA | MONO_COUNTER_INT, &total_allocated_memory);
}
}
#else
#define _MEM_ALLOC(amt) do {} while (0)
#define _MEM_FREE(amt) do { } while (0)
#define finish_collect_stats()
#define init_verifier_stats()
#endif
//////////////////////////////////////////////////////////////////
/*Token validation macros and functions */
#define IS_MEMBER_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_MEMBERREF)
#define IS_METHOD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_METHOD)
#define IS_METHOD_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_METHODSPEC)
#define IS_FIELD_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_FIELD)
#define IS_TYPE_REF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEREF)
#define IS_TYPE_DEF(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPEDEF)
#define IS_TYPE_SPEC(token) (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC)
#define IS_METHOD_DEF_OR_REF_OR_SPEC(token) (IS_METHOD_DEF (token) || IS_MEMBER_REF (token) || IS_METHOD_SPEC (token))
#define IS_TYPE_DEF_OR_REF_OR_SPEC(token) (IS_TYPE_DEF (token) || IS_TYPE_REF (token) || IS_TYPE_SPEC (token))
#define IS_FIELD_DEF_OR_REF(token) (IS_FIELD_DEF (token) || IS_MEMBER_REF (token))
/*
* Verify if @token refers to a valid row on int's table.
*/
static gboolean
token_bounds_check (MonoImage *image, guint32 token)
{
if (image_is_dynamic (image))
return mono_dynamic_image_is_valid_token ((MonoDynamicImage*)image, token);
return image->tables [mono_metadata_token_table (token)].rows >= mono_metadata_token_index (token) && mono_metadata_token_index (token) > 0;
}
static MonoType *
mono_type_create_fnptr_from_mono_method (VerifyContext *ctx, MonoMethod *method)
{
MonoType *res = g_new0 (MonoType, 1);
_MEM_ALLOC (sizeof (MonoType));
//FIXME use mono_method_get_signature_full
res->data.method = mono_method_signature (method);
res->type = MONO_TYPE_FNPTR;
ctx->funptrs = g_slist_prepend (ctx->funptrs, res);
return res;
}
/*
* mono_type_is_enum_type:
*
* Returns: TRUE if @type is an enum type.
*/
static gboolean
mono_type_is_enum_type (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return TRUE;
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return TRUE;
return FALSE;
}
/*
* mono_type_is_value_type:
*
* Returns: TRUE if @type is named after @namespace.@name.
*
*/
static gboolean
mono_type_is_value_type (MonoType *type, const char *namespace_, const char *name)
{
return type->type == MONO_TYPE_VALUETYPE &&
!strcmp (namespace_, type->data.klass->name_space) &&
!strcmp (name, type->data.klass->name);
}
/*
* Returns TURE if @type is VAR or MVAR
*/
static gboolean
mono_type_is_generic_argument (MonoType *type)
{
return type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR;
}
/*
* mono_type_get_underlying_type_any:
*
* This functions is just like mono_type_get_underlying_type but it doesn't care if the type is byref.
*
* Returns the underlying type of @type regardless if it is byref or not.
*/
static MonoType*
mono_type_get_underlying_type_any (MonoType *type)
{
if (type->type == MONO_TYPE_VALUETYPE && type->data.klass->enumtype)
return mono_class_enum_basetype (type->data.klass);
if (type->type == MONO_TYPE_GENERICINST && type->data.generic_class->container_class->enumtype)
return mono_class_enum_basetype (type->data.generic_class->container_class);
return type;
}
static G_GNUC_UNUSED const char*
mono_type_get_stack_name (MonoType *type)
{
return type_names [get_stack_type (type) & TYPE_MASK];
}
#define CTOR_REQUIRED_FLAGS (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_RT_SPECIAL_NAME)
#define CTOR_INVALID_FLAGS (METHOD_ATTRIBUTE_STATIC)
static gboolean
mono_method_is_constructor (MonoMethod *method)
{
return ((method->flags & CTOR_REQUIRED_FLAGS) == CTOR_REQUIRED_FLAGS &&
!(method->flags & CTOR_INVALID_FLAGS) &&
!strcmp (".ctor", method->name));
}
static gboolean
mono_class_has_default_constructor (MonoClass *klass)
{
MonoMethod *method;
int i;
mono_class_setup_methods (klass);
if (mono_class_has_failure (klass))
return FALSE;
int mcount = mono_class_get_method_count (klass);
for (i = 0; i < mcount; ++i) {
method = klass->methods [i];
if (mono_method_is_constructor (method) &&
mono_method_signature (method) &&
mono_method_signature (method)->param_count == 0 &&
(method->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK) == METHOD_ATTRIBUTE_PUBLIC)
return TRUE;
}
return FALSE;
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
*/
static gboolean
mono_type_is_valid_type_in_context_full (MonoType *type, MonoGenericContext *context, gboolean check_gtd)
{
int i;
MonoGenericInst *inst;
switch (type->type) {
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
if (!context)
return FALSE;
inst = type->type == MONO_TYPE_VAR ? context->class_inst : context->method_inst;
if (!inst || mono_type_get_generic_param_num (type) >= inst->type_argc)
return FALSE;
break;
case MONO_TYPE_SZARRAY:
return mono_type_is_valid_type_in_context_full (&type->data.klass->byval_arg, context, check_gtd);
case MONO_TYPE_ARRAY:
return mono_type_is_valid_type_in_context_full (&type->data.array->eklass->byval_arg, context, check_gtd);
case MONO_TYPE_PTR:
return mono_type_is_valid_type_in_context_full (type->data.type, context, check_gtd);
case MONO_TYPE_GENERICINST:
inst = type->data.generic_class->context.class_inst;
if (!inst->is_open)
break;
for (i = 0; i < inst->type_argc; ++i)
if (!mono_type_is_valid_type_in_context_full (inst->type_argv [i], context, check_gtd))
return FALSE;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE: {
MonoClass *klass = type->data.klass;
/*
* It's possible to encode generic'sh types in such a way that they disguise themselves as class or valuetype.
* Fixing the type decoding is really tricky since under some cases this behavior is needed, for example, to
* have a 'class' type pointing to a 'genericinst' class.
*
* For the runtime these non canonical (weird) encodings work fine, the worst they can cause is some
* reflection oddities which are harmless - to security at least.
*/
if (klass->byval_arg.type != type->type)
return mono_type_is_valid_type_in_context_full (&klass->byval_arg, context, check_gtd);
if (check_gtd && mono_class_is_gtd (klass))
return FALSE;
break;
}
default:
break;
}
return TRUE;
}
static gboolean
mono_type_is_valid_type_in_context (MonoType *type, MonoGenericContext *context)
{
return mono_type_is_valid_type_in_context_full (type, context, FALSE);
}
/*This function returns NULL if the type is not instantiatable*/
static MonoType*
verifier_inflate_type (VerifyContext *ctx, MonoType *type, MonoGenericContext *context)
{
MonoError error;
MonoType *result;
result = mono_class_inflate_generic_type_checked (type, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return NULL;
}
return result;
}
/*A side note here. We don't need to check if arguments are broken since this
is only need to be done by the runtime before realizing the type.
*/
static gboolean
is_valid_generic_instantiation (MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
MonoError error;
int i;
if (ginst->type_argc != gc->type_argc)
return FALSE;
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass *paramClass;
MonoClass **constraints;
MonoType *param_type = ginst->type_argv [i];
/*it's not our job to validate type variables*/
if (mono_type_is_generic_argument (param_type))
continue;
paramClass = mono_class_from_mono_type (param_type);
/* A GTD can't be a generic argument.
*
* Due to how types are encoded we must check for the case of a genericinst MonoType and GTD MonoClass.
* This happens in cases such as: class Foo<T> { void X() { new Bar<T> (); } }
*
* Open instantiations can have GTDs as this happens when one type is instantiated with others params
* and the former has an expansion into the later. For example:
* class B<K> {}
* class A<T>: B<K> {}
* The type A <K> has a parent B<K>, that is inflated into the GTD B<>.
* Since A<K> is open, thus not instantiatable, this is valid.
*/
if (mono_class_is_gtd (paramClass) && param_type->type != MONO_TYPE_GENERICINST && !ginst->is_open)
return FALSE;
/*it's not safe to call mono_class_init from here*/
if (mono_class_is_ginst (paramClass) && !paramClass->inited) {
if (!mono_class_is_valid_generic_instantiation (NULL, paramClass))
return FALSE;
}
if (!param_info->constraints && !(param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK))
continue;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && (!paramClass->valuetype || mono_class_is_nullable (paramClass)))
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && paramClass->valuetype)
return FALSE;
if ((param_info->flags & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !paramClass->valuetype && !mono_class_has_default_constructor (paramClass))
return FALSE;
if (!param_info->constraints)
continue;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *inflated;
inflated = mono_class_inflate_generic_type_checked (&ctr->byval_arg, context, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return FALSE;
}
ctr = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
/*FIXME maybe we need the same this as verifier_class_is_assignable_from*/
if (!mono_class_is_assignable_from_slow (ctr, paramClass))
return FALSE;
}
}
return TRUE;
}
/**
* mono_generic_param_is_constraint_compatible:
*
* \returns TRUE if \p candidate is constraint compatible with \p target.
*
* This means that \p candidate constraints are a super set of \p target constaints
*/
static gboolean
mono_generic_param_is_constraint_compatible (VerifyContext *ctx, MonoGenericParam *target, MonoGenericParam *candidate, MonoClass *candidate_param_class, MonoGenericContext *context)
{
MonoGenericParamInfo *tinfo = mono_generic_param_info (target);
MonoGenericParamInfo *cinfo = mono_generic_param_info (candidate);
MonoClass **candidate_class;
gboolean class_constraint_satisfied = FALSE;
gboolean valuetype_constraint_satisfied = FALSE;
int tmask = tinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
int cmask = cinfo->flags & GENERIC_PARAMETER_ATTRIBUTE_SPECIAL_CONSTRAINTS_MASK;
if (cinfo->constraints) {
for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
MonoClass *cc;
MonoType *inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
if (!inflated)
return FALSE;
cc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
class_constraint_satisfied = TRUE;
else if (!mono_type_is_reference (&cc->byval_arg) && !MONO_CLASS_IS_INTERFACE (cc))
valuetype_constraint_satisfied = TRUE;
}
}
class_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) != 0;
valuetype_constraint_satisfied |= (cmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) != 0;
if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_REFERENCE_TYPE_CONSTRAINT) && !class_constraint_satisfied)
return FALSE;
if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_VALUE_TYPE_CONSTRAINT) && !valuetype_constraint_satisfied)
return FALSE;
if ((tmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) && !((cmask & GENERIC_PARAMETER_ATTRIBUTE_CONSTRUCTOR_CONSTRAINT) ||
valuetype_constraint_satisfied)) {
return FALSE;
}
if (tinfo->constraints) {
MonoClass **target_class;
for (target_class = tinfo->constraints; *target_class; ++target_class) {
MonoClass *tc;
MonoType *inflated = verifier_inflate_type (ctx, &(*target_class)->byval_arg, context);
if (!inflated)
return FALSE;
tc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
/*
* A constraint from @target might inflate into @candidate itself and in that case we don't need
* check it's constraints since it satisfy the constraint by itself.
*/
if (mono_metadata_type_equal (&tc->byval_arg, &candidate_param_class->byval_arg))
continue;
if (!cinfo->constraints)
return FALSE;
for (candidate_class = cinfo->constraints; *candidate_class; ++candidate_class) {
MonoClass *cc;
inflated = verifier_inflate_type (ctx, &(*candidate_class)->byval_arg, ctx->generic_context);
if (!inflated)
return FALSE;
cc = mono_class_from_mono_type (inflated);
mono_metadata_free_type (inflated);
if (verifier_class_is_assignable_from (tc, cc))
break;
/*
* This happens when we have the following:
*
* Bar<K> where K : IFace
* Foo<T, U> where T : U where U : IFace
* ...
* Bar<T> <- T here satisfy K constraint transitively through to U's constraint
*
*/
if (mono_type_is_generic_argument (&cc->byval_arg)) {
MonoGenericParam *other_candidate = verifier_get_generic_param_from_type (ctx, &cc->byval_arg);
if (mono_generic_param_is_constraint_compatible (ctx, target, other_candidate, cc, context)) {
break;
}
}
}
if (!*candidate_class)
return FALSE;
}
}
return TRUE;
}
static MonoGenericParam*
verifier_get_generic_param_from_type (VerifyContext *ctx, MonoType *type)
{
MonoGenericContainer *gc;
MonoMethod *method = ctx->method;
int num;
num = mono_type_get_generic_param_num (type);
if (type->type == MONO_TYPE_VAR) {
MonoClass *gtd = method->klass;
if (mono_class_is_ginst (gtd))
gtd = mono_class_get_generic_class (gtd)->container_class;
gc = mono_class_try_get_generic_container (gtd);
} else { //MVAR
MonoMethod *gmd = method;
if (method->is_inflated)
gmd = ((MonoMethodInflated*)method)->declaring;
gc = mono_method_get_generic_container (gmd);
}
if (!gc)
return NULL;
return mono_generic_container_get_param (gc, num);
}
/*
* Verify if @type is valid for the given @ctx verification context.
* this function checks for VAR and MVAR types that are invalid under the current verifier,
* This means that it either
*/
static gboolean
is_valid_type_in_context (VerifyContext *ctx, MonoType *type)
{
return mono_type_is_valid_type_in_context (type, ctx->generic_context);
}
static gboolean
is_valid_generic_instantiation_in_context (VerifyContext *ctx, MonoGenericInst *ginst, gboolean check_gtd)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
if (!mono_type_is_valid_type_in_context_full (type, ctx->generic_context, TRUE))
return FALSE;
}
return TRUE;
}
static gboolean
generic_arguments_respect_constraints (VerifyContext *ctx, MonoGenericContainer *gc, MonoGenericContext *context, MonoGenericInst *ginst)
{
int i;
for (i = 0; i < ginst->type_argc; ++i) {
MonoType *type = ginst->type_argv [i];
MonoGenericParam *target = mono_generic_container_get_param (gc, i);
MonoGenericParam *candidate;
MonoClass *candidate_class;
if (!mono_type_is_generic_argument (type))
continue;
if (!is_valid_type_in_context (ctx, type))
return FALSE;
candidate = verifier_get_generic_param_from_type (ctx, type);
candidate_class = mono_class_from_mono_type (type);
if (!mono_generic_param_is_constraint_compatible (ctx, target, candidate, candidate_class, context))
return FALSE;
}
return TRUE;
}
static gboolean
mono_method_repect_method_constraints (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
return !gc || generic_arguments_respect_constraints (ctx, gc, &gmethod->context, ginst);
}
static gboolean
mono_class_repect_method_constraints (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = mono_class_get_generic_class (klass);
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = mono_class_get_generic_container (gklass->container_class);
return !gc || generic_arguments_respect_constraints (ctx, gc, &gklass->context, ginst);
}
static gboolean
mono_method_is_valid_generic_instantiation (VerifyContext *ctx, MonoMethod *method)
{
MonoMethodInflated *gmethod = (MonoMethodInflated *)method;
MonoGenericInst *ginst = gmethod->context.method_inst;
MonoGenericContainer *gc = mono_method_get_generic_container (gmethod->declaring);
if (!gc) /*non-generic inflated method - it's part of a generic type */
return TRUE;
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst, TRUE))
return FALSE;
return is_valid_generic_instantiation (gc, &gmethod->context, ginst);
}
static gboolean
mono_class_is_valid_generic_instantiation (VerifyContext *ctx, MonoClass *klass)
{
MonoGenericClass *gklass = mono_class_get_generic_class (klass);
MonoGenericInst *ginst = gklass->context.class_inst;
MonoGenericContainer *gc = mono_class_get_generic_container (gklass->container_class);
if (ctx && !is_valid_generic_instantiation_in_context (ctx, ginst, TRUE))
return FALSE;
return is_valid_generic_instantiation (gc, &gklass->context, ginst);
}
static gboolean
mono_type_is_valid_in_context (VerifyContext *ctx, MonoType *type)
{
MonoClass *klass;
if (type == NULL) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid null type at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return FALSE;
}
if (!is_valid_type_in_context (ctx, type)) {
char *str = mono_type_full_name (type);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type (%s%s) (argument out of range or %s is not generic) at 0x%04x",
str [0] == '!' ? "" : type->type == MONO_TYPE_VAR ? "!" : "!!",
str,
type->type == MONO_TYPE_VAR ? "class" : "method",
ctx->ip_offset),
MONO_EXCEPTION_BAD_IMAGE);
g_free (str);
return FALSE;
}
klass = mono_class_from_mono_type (type);
mono_class_init (klass);
if (mono_class_has_failure (klass)) {
if (mono_class_is_ginst (klass) && !mono_class_is_valid_generic_instantiation (NULL, klass))
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
else
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (mono_class_is_ginst (klass) && mono_class_has_failure (mono_class_get_generic_class (klass)->container_class)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Could not load type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!mono_class_is_ginst (klass))
return TRUE;
if (!mono_class_is_valid_generic_instantiation (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
if (!mono_class_repect_method_constraints (ctx, klass)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic type instantiation of type %s.%s (generic args don't respect target's constraints) at 0x%04x", klass->name_space, klass->name, ctx->ip_offset), MONO_EXCEPTION_TYPE_LOAD);
return FALSE;
}
return TRUE;
}
static verify_result_t
mono_method_is_valid_in_context (VerifyContext *ctx, MonoMethod *method)
{
if (!mono_type_is_valid_in_context (ctx, &method->klass->byval_arg))
return RESULT_INVALID;
if (!method->is_inflated)
return RESULT_VALID;
if (!mono_method_is_valid_generic_instantiation (ctx, method)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset), MONO_EXCEPTION_UNVERIFIABLE_IL);
return RESULT_INVALID;
}
if (!mono_method_repect_method_constraints (ctx, method)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid generic method instantiation of method %s.%s::%s (generic args don't respect target's constraints) at 0x%04x", method->klass->name_space, method->klass->name, method->name, ctx->ip_offset));
return RESULT_UNVERIFIABLE;
}
return RESULT_VALID;
}
static MonoClassField*
verifier_load_field (VerifyContext *ctx, int token, MonoClass **out_klass, const char *opcode) {
MonoError error;
MonoClassField *field;
MonoClass *klass = NULL;
if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
field = (MonoClassField *)mono_method_get_wrapper_data (ctx->method, (guint32)token);
klass = field ? field->parent : NULL;
} else {
if (!IS_FIELD_DEF_OR_REF (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid field token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
field = mono_field_from_token_checked (ctx->image, token, &klass, ctx->generic_context, &error);
mono_error_cleanup (&error); /*FIXME don't swallow the error */
}
if (!field || !field->parent || !klass) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load field from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, &klass->byval_arg))
return NULL;
if (mono_field_get_flags (field) & FIELD_ATTRIBUTE_LITERAL) {
char *type_name = mono_type_get_full_name (field->parent);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot reference literal field %s::%s at 0x%04x", type_name, field->name, ctx->ip_offset));
g_free (type_name);
return NULL;
}
*out_klass = klass;
return field;
}
static MonoMethod*
verifier_load_method (VerifyContext *ctx, int token, const char *opcode) {
MonoMethod* method;
if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
method = (MonoMethod *)mono_method_get_wrapper_data (ctx->method, (guint32)token);
} else {
MonoError error;
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid method token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
method = mono_get_method_checked (ctx->image, token, NULL, ctx->generic_context, &error);
mono_error_cleanup (&error); /* FIXME don't swallow this error */
}
if (!method) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load method from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
if (mono_method_is_valid_in_context (ctx, method) == RESULT_INVALID)
return NULL;
return method;
}
static MonoType*
verifier_load_type (VerifyContext *ctx, int token, const char *opcode) {
MonoType* type;
if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
MonoClass *klass = (MonoClass *)mono_method_get_wrapper_data (ctx->method, (guint32)token);
type = klass ? &klass->byval_arg : NULL;
} else {
MonoError error;
if (!IS_TYPE_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid type token 0x%08x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
type = mono_type_get_checked (ctx->image, token, ctx->generic_context, &error);
mono_error_cleanup (&error); /*FIXME don't swallow the error */
}
if (!type) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Cannot load type from token 0x%08x for %s at 0x%04x", token, opcode, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return NULL;
}
if (!mono_type_is_valid_in_context (ctx, type))
return NULL;
return type;
}
/* stack_slot_get_type:
*
* Returns the stack type of @value. This value includes POINTER_MASK.
*
* Use this function to checks that account for a managed pointer.
*/
static gint32
stack_slot_get_type (ILStackDesc *value)
{
return value->stype & RAW_TYPE_MASK;
}
/* stack_slot_get_underlying_type:
*
* Returns the stack type of @value. This value does not include POINTER_MASK.
*
* Use this function is cases where the fact that the value could be a managed pointer is
* irrelevant. For example, field load doesn't care about this fact of type on stack.
*/
static gint32
stack_slot_get_underlying_type (ILStackDesc *value)
{
return value->stype & TYPE_MASK;
}
/* stack_slot_is_managed_pointer:
*
* Returns TRUE is @value is a managed pointer.
*/
static gboolean
stack_slot_is_managed_pointer (ILStackDesc *value)
{
return (value->stype & POINTER_MASK) == POINTER_MASK;
}
/* stack_slot_is_managed_mutability_pointer:
*
* Returns TRUE is @value is a managed mutability pointer.
*/
static G_GNUC_UNUSED gboolean
stack_slot_is_managed_mutability_pointer (ILStackDesc *value)
{
return (value->stype & CMMP_MASK) == CMMP_MASK;
}
/* stack_slot_is_null_literal:
*
* Returns TRUE is @value is the null literal.
*/
static gboolean
stack_slot_is_null_literal (ILStackDesc *value)
{
return (value->stype & NULL_LITERAL_MASK) == NULL_LITERAL_MASK;
}
/* stack_slot_is_this_pointer:
*
* Returns TRUE is @value is the this literal
*/
static gboolean
stack_slot_is_this_pointer (ILStackDesc *value)
{
return (value->stype & THIS_POINTER_MASK) == THIS_POINTER_MASK;
}
/* stack_slot_is_boxed_value:
*
* Returns TRUE is @value is a boxed value
*/
static gboolean
stack_slot_is_boxed_value (ILStackDesc *value)
{
return (value->stype & BOXED_MASK) == BOXED_MASK;
}
/* stack_slot_is_safe_byref:
*
* Returns TRUE is @value is a safe byref
*/
static gboolean
stack_slot_is_safe_byref (ILStackDesc *value)
{
return (value->stype & SAFE_BYREF_MASK) == SAFE_BYREF_MASK;
}
static const char *
stack_slot_get_name (ILStackDesc *value)
{
return type_names [value->stype & TYPE_MASK];
}
enum {
SAFE_BYREF_LOCAL = 1,
UNSAFE_BYREF_LOCAL = 2
};
static gboolean
local_is_safe_byref (VerifyContext *ctx, unsigned int arg)
{
return ctx->locals_verification_state [arg] == SAFE_BYREF_LOCAL;
}
static gboolean
local_is_unsafe_byref (VerifyContext *ctx, unsigned int arg)
{
return ctx->locals_verification_state [arg] == UNSAFE_BYREF_LOCAL;
}
#define APPEND_WITH_PREDICATE(PRED,NAME) do {\
if (PRED (value)) { \
if (!first) \
g_string_append (str, ", "); \
g_string_append (str, NAME); \
first = FALSE; \
} } while (0)
static char*
stack_slot_stack_type_full_name (ILStackDesc *value)
{
GString *str = g_string_new ("");
char *result;
gboolean has_pred = FALSE, first = TRUE;
if ((value->stype & TYPE_MASK) != value->stype) {
g_string_append(str, "[");
APPEND_WITH_PREDICATE (stack_slot_is_this_pointer, "this");
APPEND_WITH_PREDICATE (stack_slot_is_boxed_value, "boxed");
APPEND_WITH_PREDICATE (stack_slot_is_null_literal, "null");
APPEND_WITH_PREDICATE (stack_slot_is_managed_mutability_pointer, "cmmp");
APPEND_WITH_PREDICATE (stack_slot_is_managed_pointer, "mp");
APPEND_WITH_PREDICATE (stack_slot_is_safe_byref, "safe-byref");
has_pred = TRUE;
}
if (mono_type_is_generic_argument (value->type) && !stack_slot_is_boxed_value (value)) {
if (!has_pred)
g_string_append(str, "[");
if (!first)
g_string_append (str, ", ");
g_string_append (str, "unboxed");
has_pred = TRUE;
}
if (has_pred)
g_string_append(str, "] ");
g_string_append (str, stack_slot_get_name (value));
result = str->str;
g_string_free (str, FALSE);
return result;
}
static char*
stack_slot_full_name (ILStackDesc *value)
{
char *type_name = mono_type_full_name (value->type);
char *stack_name = stack_slot_stack_type_full_name (value);
char *res = g_strdup_printf ("%s (%s)", type_name, stack_name);
g_free (type_name);
g_free (stack_name);
return res;
}
//////////////////////////////////////////////////////////////////
/**
* mono_free_verify_list:
*/
void
mono_free_verify_list (GSList *list)
{
MonoVerifyInfoExtended *info;
GSList *tmp;
for (tmp = list; tmp; tmp = tmp->next) {
info = (MonoVerifyInfoExtended *)tmp->data;
g_free (info->info.message);
g_free (info);
}
g_slist_free (list);
}
#define ADD_ERROR(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = MONO_VERIFY_ERROR; \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_WARN(list,code,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->info.status = (code); \
vinfo->info.message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
} while (0)
#define ADD_INVALID(list,msg) \
do { \
MonoVerifyInfoExtended *vinfo = g_new (MonoVerifyInfoExtended, 1); \
vinfo->status = MONO_VERIFY_ERROR; \
vinfo->message = (msg); \
(list) = g_slist_prepend ((list), vinfo); \
/*G_BREAKPOINT ();*/ \
goto invalid_cil; \
} while (0)
#define CHECK_STACK_UNDERFLOW(num) \
do { \
if (cur_stack < (num)) \
ADD_INVALID (list, g_strdup_printf ("Stack underflow at 0x%04x (%d items instead of %d)", ip_offset, cur_stack, (num))); \
} while (0)
#define CHECK_STACK_OVERFLOW() \
do { \
if (cur_stack >= max_stack) \
ADD_INVALID (list, g_strdup_printf ("Maxstack exceeded at 0x%04x", ip_offset)); \
} while (0)
static int
in_any_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 1;
}
return 0;
}
/*
* in_any_exception_block:
*
* Returns TRUE is @offset is part of any exception clause (filter, handler, catch, finally or fault).
*/
static gboolean
in_any_exception_block (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return TRUE;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return TRUE;
}
return FALSE;
}
/*
* is_valid_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with br and brtrue/false.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
* The major difference from other similiar functions is that branching into a
* finally/fault block is invalid instead of just unverifiable.
*/
static int
is_valid_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching into a finally block is invalid*/
if ((clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY || clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) &&
!MONO_OFFSET_IN_HANDLER (clause, offset) &&
MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 1;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 1;
}
return 0;
}
/*
* is_valid_cmp_branch_instruction:
*
* Verify if it's valid to perform a branch from @offset to @target.
* This should be used with binary comparison branching instruction, like beq, bge and similars.
* It returns 0 if valid, 1 for unverifiable and 2 for invalid.
*
* The major differences from other similar functions are that most errors lead to invalid
* code and only branching out of finally, filter or fault clauses is unverifiable.
*/
static int
is_valid_cmp_branch_instruction (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
/*branching out of a handler or finally*/
if (clause->flags != MONO_EXCEPTION_CLAUSE_NONE &&
MONO_OFFSET_IN_HANDLER (clause, offset) &&
!MONO_OFFSET_IN_HANDLER (clause, target))
return 1;
if (clause->try_offset != target && (MONO_OFFSET_IN_CLAUSE (clause, offset) ^ MONO_OFFSET_IN_CLAUSE (clause, target)))
return 2;
if (MONO_OFFSET_IN_HANDLER (clause, offset) ^ MONO_OFFSET_IN_HANDLER (clause, target))
return 2;
if (MONO_OFFSET_IN_FILTER (clause, offset) ^ MONO_OFFSET_IN_FILTER (clause, target))
return 2;
}
return 0;
}
/*
* A leave can't escape a finally block
*/
static int
is_correct_leave (MonoMethodHeader *header, guint offset, guint target)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY && MONO_OFFSET_IN_HANDLER (clause, offset) && !MONO_OFFSET_IN_HANDLER (clause, target))
return 0;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return 0;
}
return 1;
}
/*
* A rethrow can't happen outside of a catch handler.
*/
static int
is_correct_rethrow (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset))
return 1;
}
return 0;
}
/*
* An endfinally can't happen outside of a finally/fault handler.
*/
static int
is_correct_endfinally (MonoMethodHeader *header, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < header->num_clauses; ++i) {
clause = &header->clauses [i];
if (MONO_OFFSET_IN_HANDLER (clause, offset) && (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT || clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY))
return 1;
}
return 0;
}
/*
* An endfilter can only happens inside a filter clause.
* In non-strict mode filter is allowed inside the handler clause too
*/
static MonoExceptionClause *
is_correct_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER)
continue;
if (MONO_OFFSET_IN_FILTER (clause, offset))
return clause;
if (!IS_STRICT_MODE (ctx) && MONO_OFFSET_IN_HANDLER (clause, offset))
return clause;
}
return NULL;
}
/*
* Non-strict endfilter can happens inside a try block or any handler block
*/
static int
is_unverifiable_endfilter (VerifyContext *ctx, guint offset)
{
int i;
MonoExceptionClause *clause;
for (i = 0; i < ctx->header->num_clauses; ++i) {
clause = &ctx->header->clauses [i];
if (MONO_OFFSET_IN_CLAUSE (clause, offset))
return 1;
}
return 0;
}
static gboolean
is_valid_bool_arg (ILStackDesc *arg)
{
if (stack_slot_is_managed_pointer (arg) || stack_slot_is_boxed_value (arg) || stack_slot_is_null_literal (arg))
return TRUE;
switch (stack_slot_get_underlying_type (arg)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_PTR:
return TRUE;
case TYPE_COMPLEX:
g_assert (arg->type);
switch (arg->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
return TRUE;
case MONO_TYPE_GENERICINST:
/*We need to check if the container class
* of the generic type is a valuetype, iow:
* is it a "class Foo<T>" or a "struct Foo<T>"?
*/
return !arg->type->data.generic_class->container_class->valuetype;
default:
return FALSE;
}
default:
return FALSE;
}
}
/*Type manipulation helper*/
/*Returns the byref version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byref (MonoType *type)
{
if (type->byref)
return type;
return &mono_class_from_mono_type (type)->this_arg;
}
/*Returns the byval version of the supplied MonoType*/
static MonoType*
mono_type_get_type_byval (MonoType *type)
{
if (!type->byref)
return type;
return &mono_class_from_mono_type (type)->byval_arg;
}
static MonoType*
mono_type_from_stack_slot (ILStackDesc *slot)
{
if (stack_slot_is_managed_pointer (slot))
return mono_type_get_type_byref (slot->type);
return slot->type;
}
/*Stack manipulation code*/
static void
ensure_stack_size (ILCodeDesc *stack, int required)
{
int new_size = 8;
ILStackDesc *tmp;
if (required < stack->max_size)
return;
/* We don't have to worry about the exponential growth since stack_copy prune unused space */
new_size = MAX (8, MAX (required, stack->max_size * 2));
g_assert (new_size >= stack->size);
g_assert (new_size >= required);
tmp = g_new0 (ILStackDesc, new_size);
_MEM_ALLOC (sizeof (ILStackDesc) * new_size);
if (stack->stack) {
if (stack->size)
memcpy (tmp, stack->stack, stack->size * sizeof (ILStackDesc));
g_free (stack->stack);
_MEM_FREE (sizeof (ILStackDesc) * stack->max_size);
}
stack->stack = tmp;
stack->max_size = new_size;
}
static void
stack_init (VerifyContext *ctx, ILCodeDesc *state)
{
if (state->flags & IL_CODE_FLAG_STACK_INITED)
return;
state->size = state->max_size = 0;
state->flags |= IL_CODE_FLAG_STACK_INITED;
}
static void
stack_copy (ILCodeDesc *to, ILCodeDesc *from)
{
ensure_stack_size (to, from->size);
to->size = from->size;
/*stack copy happens at merge points, which have small stacks*/
if (from->size)
memcpy (to->stack, from->stack, sizeof (ILStackDesc) * from->size);
}
static void
copy_stack_value (ILStackDesc *to, ILStackDesc *from)
{
to->stype = from->stype;
to->type = from->type;
to->method = from->method;
}
static int
check_underflow (VerifyContext *ctx, int size)
{
if (ctx->eval.size < size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack underflow, required %d, but have %d at 0x%04x", size, ctx->eval.size, ctx->ip_offset));
return 0;
}
return 1;
}
static int
check_overflow (VerifyContext *ctx)
{
if (ctx->eval.size >= ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have stack-depth %d at 0x%04x", ctx->eval.size + 1, ctx->ip_offset));
return 0;
}
return 1;
}
/*This reject out PTR, FNPTR and TYPEDBYREF*/
static gboolean
check_unmanaged_pointer (VerifyContext *ctx, ILStackDesc *value)
{
if (stack_slot_get_type (value) == TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
/*TODO verify if MONO_TYPE_TYPEDBYREF is not allowed here as well.*/
static gboolean
check_unverifiable_type (VerifyContext *ctx, MonoType *type)
{
if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unmanaged pointer is not a verifiable type at 0x%04x", ctx->ip_offset));
return 0;
}
return 1;
}
static ILStackDesc *
stack_push (VerifyContext *ctx)
{
g_assert (ctx->eval.size < ctx->max_stack);
g_assert (ctx->eval.size <= ctx->eval.max_size);
ensure_stack_size (&ctx->eval, ctx->eval.size + 1);
return & ctx->eval.stack [ctx->eval.size++];
}
static ILStackDesc *
stack_push_val (VerifyContext *ctx, int stype, MonoType *type)
{
ILStackDesc *top = stack_push (ctx);
top->stype = stype;
top->type = type;
return top;
}
static ILStackDesc *
stack_pop (VerifyContext *ctx)
{
ILStackDesc *ret;
g_assert (ctx->eval.size > 0);
ret = ctx->eval.stack + --ctx->eval.size;
if ((ret->stype & UNINIT_THIS_MASK) == UNINIT_THIS_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Found use of uninitialized 'this ptr' ref at 0x%04x", ctx->ip_offset));
return ret;
}
/* This function allows to safely pop an unititialized this ptr from
* the eval stack without marking the method as unverifiable.
*/
static ILStackDesc *
stack_pop_safe (VerifyContext *ctx)
{
g_assert (ctx->eval.size > 0);
return ctx->eval.stack + --ctx->eval.size;
}
/*Positive number distance from stack top. [0] is stack top, [1] is the one below*/
static ILStackDesc*
stack_peek (VerifyContext *ctx, int distance)
{
g_assert (ctx->eval.size - distance > 0);
return ctx->eval.stack + (ctx->eval.size - 1 - distance);
}
static ILStackDesc *
stack_push_stack_val (VerifyContext *ctx, ILStackDesc *value)
{
ILStackDesc *top = stack_push (ctx);
copy_stack_value (top, value);
return top;
}
/* Returns the MonoType associated with the token, or NULL if it is invalid.
*
* A boxable type can be either a reference or value type, but cannot be a byref type or an unmanaged pointer
* */
static MonoType*
get_boxable_mono_type (VerifyContext* ctx, int token, const char *opcode)
{
MonoType *type;
MonoClass *klass;
if (!(type = verifier_load_type (ctx, token, opcode)))
return NULL;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type for %s at 0x%04x", opcode, ctx->ip_offset));
return NULL;
}
if (type->type == MONO_TYPE_TYPEDBYREF)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid use of typedbyref for %s at 0x%04x", opcode, ctx->ip_offset));
if (!(klass = mono_class_from_mono_type (type)))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not retrieve type token for %s at 0x%04x", opcode, ctx->ip_offset));
if (mono_class_is_gtd (klass) && type->type != MONO_TYPE_GENERICINST)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the generic type definition in a boxable type position for %s at 0x%04x", opcode, ctx->ip_offset));
check_unverifiable_type (ctx, type);
return type;
}
/*operation result tables */
static const unsigned char bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char add_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_R8, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char int_bin_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char shift_op_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I8, TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char cmp_br_eq_op [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_I4, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_I4 | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_I4, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_I4},
};
static const unsigned char add_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char sub_ovf_un_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_PTR | NON_VERIFIABLE_RESULT, TYPE_INV, TYPE_NATIVE_INT | NON_VERIFIABLE_RESULT, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
static const unsigned char bin_ovf_table [TYPE_MAX][TYPE_MAX] = {
{TYPE_I4, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_I8, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_NATIVE_INT, TYPE_INV, TYPE_NATIVE_INT, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
{TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV, TYPE_INV},
};
#ifdef MONO_VERIFIER_DEBUG
/*debug helpers */
static void
dump_stack_value (ILStackDesc *value)
{
printf ("[(%x)(%x)", value->type->type, value->stype);
if (stack_slot_is_this_pointer (value))
printf ("[this] ");
if (stack_slot_is_boxed_value (value))
printf ("[boxed] ");
if (stack_slot_is_null_literal (value))
printf ("[null] ");
if (stack_slot_is_managed_mutability_pointer (value))
printf ("Controled Mutability MP: ");
if (stack_slot_is_managed_pointer (value))
printf ("Managed Pointer to: ");
if (stack_slot_is_safe_byref (value))
printf ("Safe ByRef to: ");
switch (stack_slot_get_underlying_type (value)) {
case TYPE_INV:
printf ("invalid type]");
return;
case TYPE_I4:
printf ("int32]");
return;
case TYPE_I8:
printf ("int64]");
return;
case TYPE_NATIVE_INT:
printf ("native int]");
return;
case TYPE_R8:
printf ("float64]");
return;
case TYPE_PTR:
printf ("unmanaged pointer]");
return;
case TYPE_COMPLEX:
switch (value->type->type) {
case MONO_TYPE_CLASS:
case MONO_TYPE_VALUETYPE:
printf ("complex] (%s)", value->type->data.klass->name);
return;
case MONO_TYPE_STRING:
printf ("complex] (string)");
return;
case MONO_TYPE_OBJECT:
printf ("complex] (object)");
return;
case MONO_TYPE_SZARRAY:
printf ("complex] (%s [])", value->type->data.klass->name);
return;
case MONO_TYPE_ARRAY:
printf ("complex] (%s [%d %d %d])",
value->type->data.array->eklass->name,
value->type->data.array->rank,
value->type->data.array->numsizes,
value->type->data.array->numlobounds);
return;
case MONO_TYPE_GENERICINST:
printf ("complex] (inst of %s )", value->type->data.generic_class->container_class->name);
return;
case MONO_TYPE_VAR:
printf ("complex] (type generic param !%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
case MONO_TYPE_MVAR:
printf ("complex] (method generic param !!%d - %s) ", value->type->data.generic_param->num, mono_generic_param_info (value->type->data.generic_param)->name);
return;
default: {
//should be a boxed value
char * name = mono_type_full_name (value->type);
printf ("complex] %s", name);
g_free (name);
return;
}
}
default:
printf ("unknown stack %x type]\n", value->stype);
g_assert_not_reached ();
}
}
static void
dump_stack_state (ILCodeDesc *state)
{
int i;
printf ("(%d) ", state->size);
for (i = 0; i < state->size; ++i)
dump_stack_value (state->stack + i);
printf ("\n");
}
#endif
/**
* is_array_type_compatible:
*
* Returns TRUE if candidate array type can be assigned to target.
*
* Both parameters MUST be of type MONO_TYPE_ARRAY (target->type == MONO_TYPE_ARRAY)
*/
static gboolean
is_array_type_compatible (MonoType *target, MonoType *candidate)
{
MonoArrayType *left = target->data.array;
MonoArrayType *right = candidate->data.array;
g_assert (target->type == MONO_TYPE_ARRAY);
g_assert (candidate->type == MONO_TYPE_ARRAY);
if (left->rank != right->rank)
return FALSE;
return verifier_class_is_assignable_from (left->eklass, right->eklass);
}
static int
get_stack_type (MonoType *type)
{
int mask = 0;
int type_kind = type->type;
if (type->byref)
mask = POINTER_MASK;
/*TODO handle CMMP_MASK */
handle_enum:
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
return TYPE_I4 | mask;
case MONO_TYPE_I:
case MONO_TYPE_U:
return TYPE_NATIVE_INT | mask;
/* FIXME: the spec says that you cannot have a pointer to method pointer, do we need to check this here? */
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
return TYPE_PTR | mask;
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
return TYPE_COMPLEX | mask;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return TYPE_I8 | mask;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
return TYPE_R8 | mask;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
type = mono_type_get_underlying_type_any (type);
if (!type)
return FALSE;
type_kind = type->type;
goto handle_enum;
} else {
return TYPE_COMPLEX | mask;
}
default:
return TYPE_INV;
}
}
/* convert MonoType to ILStackDesc format (stype) */
static gboolean
set_stack_value (VerifyContext *ctx, ILStackDesc *stack, MonoType *type, int take_addr)
{
int mask = 0;
int type_kind = type->type;
if (type->byref || take_addr)
mask = POINTER_MASK;
/* TODO handle CMMP_MASK */
handle_enum:
stack->type = type;
switch (type_kind) {
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
stack->stype = TYPE_I4 | mask;
break;
case MONO_TYPE_I:
case MONO_TYPE_U:
stack->stype = TYPE_NATIVE_INT | mask;
break;
/*FIXME: Do we need to check if it's a pointer to the method pointer? The spec says it' illegal to have that.*/
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
stack->stype = TYPE_PTR | mask;
break;
case MONO_TYPE_CLASS:
case MONO_TYPE_STRING:
case MONO_TYPE_OBJECT:
case MONO_TYPE_SZARRAY:
case MONO_TYPE_ARRAY:
case MONO_TYPE_VAR:
case MONO_TYPE_MVAR:
stack->stype = TYPE_COMPLEX | mask;
break;
case MONO_TYPE_I8:
case MONO_TYPE_U8:
stack->stype = TYPE_I8 | mask;
break;
case MONO_TYPE_R4:
case MONO_TYPE_R8:
stack->stype = TYPE_R8 | mask;
break;
case MONO_TYPE_GENERICINST:
case MONO_TYPE_VALUETYPE:
if (mono_type_is_enum_type (type)) {
MonoType *utype = mono_type_get_underlying_type_any (type);
if (!utype) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve underlying type of %x at %d", type->type, ctx->ip_offset));
return FALSE;
}
type = utype;
type_kind = type->type;
goto handle_enum;
} else {
stack->stype = TYPE_COMPLEX | mask;
break;
}
default:
VERIFIER_DEBUG ( printf ("unknown type 0x%02x in eval stack type\n", type->type); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Illegal value set on stack 0x%02x at %d", type->type, ctx->ip_offset));
return FALSE;
}
return TRUE;
}
/*
* init_stack_with_value_at_exception_boundary:
*
* Initialize the stack and push a given type.
* The instruction is marked as been on the exception boundary.
*/
static void
init_stack_with_value_at_exception_boundary (VerifyContext *ctx, ILCodeDesc *code, MonoClass *klass)
{
MonoError error;
MonoType *type = mono_class_inflate_generic_type_checked (&klass->byval_arg, ctx->generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_get_full_name (klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid class %s used for exception", name));
g_free (name);
mono_error_cleanup (&error);
return;
}
if (!ctx->max_stack) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack overflow at 0x%04x", ctx->ip_offset));
return;
}
stack_init (ctx, code);
ensure_stack_size (code, 1);
set_stack_value (ctx, code->stack, type, FALSE);
ctx->exception_types = g_slist_prepend (ctx->exception_types, type);
code->size = 1;
code->flags |= IL_CODE_FLAG_WAS_TARGET;
if (mono_type_is_generic_argument (type))
code->stack->stype |= BOXED_MASK;
}
/* Class lazy loading functions */
static GENERATE_GET_CLASS_WITH_CACHE (ienumerable, "System.Collections.Generic", "IEnumerable`1")
static GENERATE_GET_CLASS_WITH_CACHE (icollection, "System.Collections.Generic", "ICollection`1")
static GENERATE_GET_CLASS_WITH_CACHE (ireadonly_list, "System.Collections.Generic", "IReadOnlyList`1")
static GENERATE_GET_CLASS_WITH_CACHE (ireadonly_collection, "System.Collections.Generic", "IReadOnlyCollection`1")
static MonoClass*
get_ienumerable_class (void)
{
return mono_class_get_ienumerable_class ();
}
static MonoClass*
get_icollection_class (void)
{
return mono_class_get_icollection_class ();
}
static MonoClass*
get_ireadonlylist_class (void)
{
return mono_class_get_ireadonly_list_class ();
}
static MonoClass*
get_ireadonlycollection_class (void)
{
return mono_class_get_ireadonly_collection_class ();
}
static MonoClass*
inflate_class_one_arg (MonoClass *gtype, MonoClass *arg0)
{
MonoType *args [1];
args [0] = &arg0->byval_arg;
return mono_class_bind_generic_parameters (gtype, 1, args, FALSE);
}
static gboolean
verifier_inflate_and_check_compat (MonoClass *target, MonoClass *gtd, MonoClass *arg)
{
MonoClass *tmp;
if (!(tmp = inflate_class_one_arg (gtd, arg)))
return FALSE;
if (mono_class_is_variant_compatible (target, tmp, TRUE))
return TRUE;
return FALSE;
}
static gboolean
verifier_class_is_assignable_from (MonoClass *target, MonoClass *candidate)
{
MonoClass *iface_gtd;
if (target == candidate)
return TRUE;
if (mono_class_has_variant_generic_params (target)) {
if (MONO_CLASS_IS_INTERFACE (target)) {
if (MONO_CLASS_IS_INTERFACE (candidate) && mono_class_is_variant_compatible (target, candidate, TRUE))
return TRUE;
if (candidate->rank == 1) {
if (verifier_inflate_and_check_compat (target, mono_defaults.generic_ilist_class, candidate->element_class))
return TRUE;
if (verifier_inflate_and_check_compat (target, get_icollection_class (), candidate->element_class))
return TRUE;
if (verifier_inflate_and_check_compat (target, get_ienumerable_class (), candidate->element_class))
return TRUE;
if (verifier_inflate_and_check_compat (target, get_ireadonlylist_class (), candidate->element_class))
return TRUE;
if (verifier_inflate_and_check_compat (target, get_ireadonlycollection_class (), candidate->element_class))
return TRUE;
} else {
MonoError error;
int i;
while (candidate && candidate != mono_defaults.object_class) {
mono_class_setup_interfaces (candidate, &error);
if (!mono_error_ok (&error)) {
mono_error_cleanup (&error);
return FALSE;
}
/*klass is a generic variant interface, We need to extract from oklass a list of ifaces which are viable candidates.*/
for (i = 0; i < candidate->interface_offsets_count; ++i) {
MonoClass *iface = candidate->interfaces_packed [i];
if (mono_class_is_variant_compatible (target, iface, TRUE))
return TRUE;
}
for (i = 0; i < candidate->interface_count; ++i) {
MonoClass *iface = candidate->interfaces [i];
if (mono_class_is_variant_compatible (target, iface, TRUE))
return TRUE;
}
candidate = candidate->parent;
}
}
} else if (target->delegate) {
if (mono_class_is_variant_compatible (target, candidate, TRUE))
return TRUE;
}
return FALSE;
}
if (mono_class_is_assignable_from (target, candidate))
return TRUE;
if (!MONO_CLASS_IS_INTERFACE (target) || !mono_class_is_ginst (target) || candidate->rank != 1)
return FALSE;
iface_gtd = mono_class_get_generic_class (target)->container_class;
if (iface_gtd != mono_defaults.generic_ilist_class && iface_gtd != get_icollection_class () && iface_gtd != get_ienumerable_class ())
return FALSE;
target = mono_class_from_mono_type (mono_class_get_generic_class (target)->context.class_inst->type_argv [0]);
candidate = candidate->element_class;
return TRUE;
}
/*Verify if type 'candidate' can be stored in type 'target'.
*
* If strict, check for the underlying type and not the verification stack types
*/
static gboolean
verify_type_compatibility_full (VerifyContext *ctx, MonoType *target, MonoType *candidate, gboolean strict)
{
#define IS_ONE_OF3(T, A, B, C) (T == A || T == B || T == C)
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
MonoType *original_candidate = candidate;
VERIFIER_DEBUG ( printf ("checking type compatibility %s x %s strict %d\n", mono_type_full_name (target), mono_type_full_name (candidate), strict); );
/*only one is byref */
if (candidate->byref ^ target->byref) {
/* converting from native int to byref*/
if (get_stack_type (candidate) == TYPE_NATIVE_INT && target->byref) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("using byref native int at 0x%04x", ctx->ip_offset));
return TRUE;
}
return FALSE;
}
strict |= target->byref;
/*From now on we don't care about byref anymore, so it's ok to discard it here*/
candidate = mono_type_get_underlying_type_any (candidate);
handle_enum:
switch (target->type) {
case MONO_TYPE_VOID:
return candidate->type == MONO_TYPE_VOID;
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I1, MONO_TYPE_U1, MONO_TYPE_BOOLEAN);
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
if (strict)
return IS_ONE_OF3 (candidate->type, MONO_TYPE_I2, MONO_TYPE_U2, MONO_TYPE_CHAR);
case MONO_TYPE_I4:
case MONO_TYPE_U4: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_I8:
case MONO_TYPE_U8:
return IS_ONE_OF2 (candidate->type, MONO_TYPE_I8, MONO_TYPE_U8);
case MONO_TYPE_R4:
case MONO_TYPE_R8:
if (strict)
return candidate->type == target->type;
return IS_ONE_OF2 (candidate->type, MONO_TYPE_R4, MONO_TYPE_R8);
case MONO_TYPE_I:
case MONO_TYPE_U: {
gboolean is_native_int = IS_ONE_OF2 (candidate->type, MONO_TYPE_I, MONO_TYPE_U);
gboolean is_int4 = IS_ONE_OF2 (candidate->type, MONO_TYPE_I4, MONO_TYPE_U4);
if (strict)
return is_native_int || is_int4;
return is_native_int || get_stack_type (candidate) == TYPE_I4;
}
case MONO_TYPE_PTR:
if (candidate->type != MONO_TYPE_PTR)
return FALSE;
/* check the underlying type */
return verify_type_compatibility_full (ctx, target->data.type, candidate->data.type, TRUE);
case MONO_TYPE_FNPTR: {
MonoMethodSignature *left, *right;
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
left = mono_type_get_signature (target);
right = mono_type_get_signature (candidate);
return mono_metadata_signature_equal (left, right) && left->call_convention == right->call_convention;
}
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (mono_class_is_nullable (target_klass)) {
if (!mono_class_is_nullable (candidate_klass))
return FALSE;
return target_klass == candidate_klass;
}
return verifier_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_STRING:
return candidate->type == MONO_TYPE_STRING;
case MONO_TYPE_CLASS:
/*
* VAR / MVAR compatibility must be checked by verify_stack_type_compatibility
* to take boxing status into account.
*/
if (mono_type_is_generic_argument (original_candidate))
return FALSE;
if (candidate->type == MONO_TYPE_VALUETYPE)
return FALSE;
/* If candidate is an enum it should return true for System.Enum and supertypes.
* That's why here we use the original type and not the underlying type.
*/
return verifier_class_is_assignable_from (target->data.klass, mono_class_from_mono_type (original_candidate));
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_SZARRAY: {
MonoClass *left;
MonoClass *right;
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
left = mono_class_from_mono_type (target);
right = mono_class_from_mono_type (candidate);
return verifier_class_is_assignable_from (left, right);
}
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_TYPEDBYREF:
return candidate->type == MONO_TYPE_TYPEDBYREF;
case MONO_TYPE_VALUETYPE: {
MonoClass *target_klass;
MonoClass *candidate_klass;
if (candidate->type == MONO_TYPE_CLASS)
return FALSE;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
if (target_klass == candidate_klass)
return TRUE;
if (mono_type_is_enum_type (target)) {
target = mono_type_get_underlying_type_any (target);
if (!target)
return FALSE;
goto handle_enum;
}
return FALSE;
}
case MONO_TYPE_VAR:
if (candidate->type != MONO_TYPE_VAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
case MONO_TYPE_MVAR:
if (candidate->type != MONO_TYPE_MVAR)
return FALSE;
return mono_type_get_generic_param_num (candidate) == mono_type_get_generic_param_num (target);
default:
VERIFIER_DEBUG ( printf ("unknown store type %d\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
return 1;
#undef IS_ONE_OF3
#undef IS_ONE_OF2
}
static gboolean
verify_type_compatibility (VerifyContext *ctx, MonoType *target, MonoType *candidate)
{
return verify_type_compatibility_full (ctx, target, candidate, FALSE);
}
/*
* Returns the generic param bound to the context been verified.
*
*/
static MonoGenericParam*
get_generic_param (VerifyContext *ctx, MonoType *param)
{
guint16 param_num = mono_type_get_generic_param_num (param);
if (param->type == MONO_TYPE_VAR) {
if (!ctx->generic_context->class_inst || ctx->generic_context->class_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic type argument %d", param_num));
return NULL;
}
return ctx->generic_context->class_inst->type_argv [param_num]->data.generic_param;
}
/*param must be a MVAR */
if (!ctx->generic_context->method_inst || ctx->generic_context->method_inst->type_argc <= param_num) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid generic method argument %d", param_num));
return NULL;
}
return ctx->generic_context->method_inst->type_argv [param_num]->data.generic_param;
}
static gboolean
recursive_boxed_constraint_type_check (VerifyContext *ctx, MonoType *type, MonoClass *constraint_class, int recursion_level)
{
MonoType *constraint_type = &constraint_class->byval_arg;
if (recursion_level <= 0)
return FALSE;
if (verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (constraint_type), FALSE))
return TRUE;
if (mono_type_is_generic_argument (constraint_type)) {
MonoGenericParam *param = get_generic_param (ctx, constraint_type);
MonoClass **klass;
if (!param)
return FALSE;
for (klass = mono_generic_param_info (param)->constraints; klass && *klass; ++klass) {
if (recursive_boxed_constraint_type_check (ctx, type, *klass, recursion_level - 1))
return TRUE;
}
}
return FALSE;
}
/**
* is_compatible_boxed_valuetype:
*
* Returns: TRUE if @candidate / @stack is a valid boxed valuetype.
*
* @type The source type. It it tested to be of the proper type.
* @candidate type of the boxed valuetype.
* @stack stack slot of the boxed valuetype, separate from @candidade since one could be changed before calling this function
* @strict if TRUE candidate must be boxed compatible to the target type
*
*/
static gboolean
is_compatible_boxed_valuetype (VerifyContext *ctx, MonoType *type, MonoType *candidate, ILStackDesc *stack, gboolean strict)
{
if (!stack_slot_is_boxed_value (stack))
return FALSE;
if (type->byref || candidate->byref)
return FALSE;
if (mono_type_is_generic_argument (candidate)) {
MonoGenericParam *param = get_generic_param (ctx, candidate);
MonoClass **klass;
if (!param)
return FALSE;
for (klass = mono_generic_param_info (param)->constraints; klass && *klass; ++klass) {
/*256 should be enough since there can't be more than 255 generic arguments.*/
if (recursive_boxed_constraint_type_check (ctx, type, *klass, 256))
return TRUE;
}
}
if (mono_type_is_generic_argument (type))
return FALSE;
if (!strict)
return TRUE;
return MONO_TYPE_IS_REFERENCE (type) && verifier_class_is_assignable_from (mono_class_from_mono_type (type), mono_class_from_mono_type (candidate));
}
static int
verify_stack_type_compatibility_full (VerifyContext *ctx, MonoType *type, ILStackDesc *stack, gboolean drop_byref, gboolean valuetype_must_be_boxed)
{
MonoType *candidate = mono_type_from_stack_slot (stack);
if (MONO_TYPE_IS_REFERENCE (type) && !type->byref && stack_slot_is_null_literal (stack))
return TRUE;
if (is_compatible_boxed_valuetype (ctx, type, candidate, stack, TRUE))
return TRUE;
if (valuetype_must_be_boxed && !stack_slot_is_boxed_value (stack) && !MONO_TYPE_IS_REFERENCE (candidate))
return FALSE;
if (!valuetype_must_be_boxed && stack_slot_is_boxed_value (stack))
return FALSE;
if (drop_byref)
return verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (candidate), FALSE);
/* Handle how Roslyn emit fixed statements by encoding it as byref */
if (type->byref && candidate->byref && (type->type == MONO_TYPE_I) && !mono_type_is_reference (candidate)) {
if (!IS_STRICT_MODE (ctx))
return TRUE;
}
return verify_type_compatibility_full (ctx, type, candidate, FALSE);
}
static int
verify_stack_type_compatibility (VerifyContext *ctx, MonoType *type, ILStackDesc *stack)
{
return verify_stack_type_compatibility_full (ctx, type, stack, FALSE, FALSE);
}
static gboolean
mono_delegate_type_equal (MonoType *target, MonoType *candidate)
{
if (candidate->byref ^ target->byref)
return FALSE;
switch (target->type) {
case MONO_TYPE_VOID:
case MONO_TYPE_I1:
case MONO_TYPE_U1:
case MONO_TYPE_BOOLEAN:
case MONO_TYPE_I2:
case MONO_TYPE_U2:
case MONO_TYPE_CHAR:
case MONO_TYPE_I4:
case MONO_TYPE_U4:
case MONO_TYPE_I8:
case MONO_TYPE_U8:
case MONO_TYPE_R4:
case MONO_TYPE_R8:
case MONO_TYPE_I:
case MONO_TYPE_U:
case MONO_TYPE_STRING:
case MONO_TYPE_TYPEDBYREF:
return candidate->type == target->type;
case MONO_TYPE_PTR:
if (candidate->type != MONO_TYPE_PTR)
return FALSE;
return mono_delegate_type_equal (target->data.type, candidate->data.type);
case MONO_TYPE_FNPTR:
if (candidate->type != MONO_TYPE_FNPTR)
return FALSE;
return mono_delegate_signature_equal (mono_type_get_signature (target), mono_type_get_signature (candidate), FALSE);
case MONO_TYPE_GENERICINST: {
MonoClass *target_klass;
MonoClass *candidate_klass;
target_klass = mono_class_from_mono_type (target);
candidate_klass = mono_class_from_mono_type (candidate);
/*FIXME handle nullables and enum*/
return verifier_class_is_assignable_from (target_klass, candidate_klass);
}
case MONO_TYPE_OBJECT:
return MONO_TYPE_IS_REFERENCE (candidate);
case MONO_TYPE_CLASS:
return verifier_class_is_assignable_from(target->data.klass, mono_class_from_mono_type (candidate));
case MONO_TYPE_SZARRAY:
if (candidate->type != MONO_TYPE_SZARRAY)
return FALSE;
return verifier_class_is_assignable_from (mono_class_from_mono_type (target)->element_class, mono_class_from_mono_type (candidate)->element_class);
case MONO_TYPE_ARRAY:
if (candidate->type != MONO_TYPE_ARRAY)
return FALSE;
return is_array_type_compatible (target, candidate);
case MONO_TYPE_VALUETYPE:
/*FIXME handle nullables and enum*/
return mono_class_from_mono_type (candidate) == mono_class_from_mono_type (target);
case MONO_TYPE_VAR:
return candidate->type == MONO_TYPE_VAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
case MONO_TYPE_MVAR:
return candidate->type == MONO_TYPE_MVAR && mono_type_get_generic_param_num (target) == mono_type_get_generic_param_num (candidate);
return FALSE;
default:
VERIFIER_DEBUG ( printf ("Unknown type %d. Implement me!\n", target->type); );
g_assert_not_reached ();
return FALSE;
}
}
static gboolean
mono_delegate_param_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (method, delegate);
}
static gboolean
mono_delegate_ret_equal (MonoType *delegate, MonoType *method)
{
if (mono_metadata_type_equal_full (delegate, method, TRUE))
return TRUE;
return mono_delegate_type_equal (delegate, method);
}
/*
* mono_delegate_signature_equal:
*
* Compare two signatures in the way expected by delegates.
*
* This function only exists due to the fact that it should ignore the 'has_this' part of the signature.
*
* FIXME can this function be eliminated and proper metadata functionality be used?
*/
static gboolean
mono_delegate_signature_equal (MonoMethodSignature *delegate_sig, MonoMethodSignature *method_sig, gboolean is_static_ldftn)
{
int i;
int method_offset = is_static_ldftn ? 1 : 0;
if (delegate_sig->param_count + method_offset != method_sig->param_count)
return FALSE;
if (delegate_sig->call_convention != method_sig->call_convention)
return FALSE;
for (i = 0; i < delegate_sig->param_count; i++) {
MonoType *p1 = delegate_sig->params [i];
MonoType *p2 = method_sig->params [i + method_offset];
if (!mono_delegate_param_equal (p1, p2))
return FALSE;
}
if (!mono_delegate_ret_equal (delegate_sig->ret, method_sig->ret))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_is_signature_compatible (MonoMethodSignature *target, MonoMethodSignature *candidate)
{
return mono_delegate_signature_equal (target, candidate, FALSE);
}
/*
* verify_ldftn_delegate:
*
* Verify properties of ldftn based delegates.
*/
static void
verify_ldftn_delegate (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
MonoMethod *method = funptr->method;
/*ldftn non-final virtuals only allowed if method is not static,
* the object is a this arg (comes from a ldarg.0), and there is no starg.0.
* This rules doesn't apply if the object on stack is a boxed valuetype.
*/
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !mono_class_is_sealed (method->klass) && !stack_slot_is_boxed_value (value)) {
/*A stdarg 0 must not happen, we fail here only in fail fast mode to avoid double error reports*/
if (IS_FAIL_FAST_MODE (ctx) && ctx->has_this_store)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", ctx->ip_offset));
/*current method must not be static*/
if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid ldftn with virtual function at 0x%04x", ctx->ip_offset));
/*value is the this pointer, loaded using ldarg.0 */
if (!stack_slot_is_this_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object argument, it is not the this pointer, to ldftn with virtual method at 0x%04x", ctx->ip_offset));
ctx->code [ctx->ip_offset].flags |= IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL;
}
}
/*
* verify_delegate_compatibility:
*
* Verify delegate creation sequence.
*
*/
static void
verify_delegate_compatibility (VerifyContext *ctx, MonoClass *delegate, ILStackDesc *value, ILStackDesc *funptr)
{
#define IS_VALID_OPCODE(offset, opcode) (ip [ip_offset - offset] == opcode && (ctx->code [ip_offset - offset].flags & IL_CODE_FLAG_SEEN))
#define IS_LOAD_FUN_PTR(kind) (IS_VALID_OPCODE (6, CEE_PREFIX1) && ip [ip_offset - 5] == kind)
MonoMethod *invoke, *method;
const guint8 *ip = ctx->header->code;
guint32 ip_offset = ctx->ip_offset;
gboolean is_static_ldftn = FALSE, is_first_arg_bound = FALSE;
if (stack_slot_get_type (funptr) != TYPE_PTR || !funptr->method) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid function pointer parameter for delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
invoke = mono_get_delegate_invoke (delegate);
method = funptr->method;
if (!method || !mono_method_signature (method)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid method on stack to create delegate %s construction at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
if (!invoke || !mono_method_signature (invoke)) {
char *name = mono_type_get_full_name (delegate);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Delegate type %s with bad Invoke method at 0x%04x", name, ctx->ip_offset));
g_free (name);
return;
}
is_static_ldftn = (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) && method->flags & METHOD_ATTRIBUTE_STATIC;
if (is_static_ldftn)
is_first_arg_bound = mono_method_signature (invoke)->param_count + 1 == mono_method_signature (method)->param_count;
if (!mono_delegate_signature_equal (mono_method_signature (invoke), mono_method_signature (method), is_first_arg_bound)) {
char *fun_sig = mono_signature_get_desc (mono_method_signature (method), FALSE);
char *invoke_sig = mono_signature_get_desc (mono_method_signature (invoke), FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Function pointer signature '%s' doesn't match delegate's signature '%s' at 0x%04x", fun_sig, invoke_sig, ctx->ip_offset));
g_free (fun_sig);
g_free (invoke_sig);
}
/*
* Delegate code sequences:
* [-6] ldftn token
* newobj ...
*
*
* [-7] dup
* [-6] ldvirtftn token
* newobj ...
*
* ldftn sequence:*/
if (ip_offset > 5 && IS_LOAD_FUN_PTR (CEE_LDFTN)) {
verify_ldftn_delegate (ctx, delegate, value, funptr);
} else if (ip_offset > 6 && IS_VALID_OPCODE (7, CEE_DUP) && IS_LOAD_FUN_PTR (CEE_LDVIRTFTN)) {
ctx->code [ip_offset - 6].flags |= IL_CODE_DELEGATE_SEQUENCE;
}else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid code sequence for delegate creation at 0x%04x", ctx->ip_offset));
}
ctx->code [ip_offset].flags |= IL_CODE_DELEGATE_SEQUENCE;
//general tests
if (is_first_arg_bound) {
if (mono_method_signature (method)->param_count == 0 || !verify_stack_type_compatibility_full (ctx, mono_method_signature (method)->params [0], value, FALSE, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_STATIC) {
if (!stack_slot_is_null_literal (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Non-null this args used with static function for delegate creation at 0x%04x", ctx->ip_offset));
} else {
if (!verify_stack_type_compatibility_full (ctx, &method->klass->byval_arg, value, FALSE, TRUE) && !stack_slot_is_null_literal (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("This object not compatible with function pointer for delegate creation at 0x%04x", ctx->ip_offset));
}
}
if (stack_slot_get_type (value) != TYPE_COMPLEX)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid first parameter for delegate creation at 0x%04x", ctx->ip_offset));
#undef IS_VALID_OPCODE
#undef IS_LOAD_FUN_PTR
}
static gboolean
is_this_arg_of_struct_instance_method (unsigned int arg, VerifyContext *ctx)
{
if (arg != 0)
return FALSE;
if (ctx->method->flags & METHOD_ATTRIBUTE_STATIC)
return FALSE;
if (!ctx->method->klass->valuetype)
return FALSE;
return TRUE;
}
/* implement the opcode checks*/
static void
push_arg (VerifyContext *ctx, unsigned int arg, int take_addr)
{
ILStackDesc *top;
if (arg >= ctx->max_args) {
if (take_addr)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
else {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d", arg + 1));
if (check_overflow (ctx)) //FIXME: what sane value could we ever push?
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->params [arg]);
if (ctx->params [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
top = stack_push (ctx);
if (!set_stack_value (ctx, top, ctx->params [arg], take_addr))
return;
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC)) {
if (take_addr)
ctx->has_this_store = TRUE;
else
top->stype |= THIS_POINTER_MASK;
if (mono_method_is_constructor (ctx->method) && !ctx->super_ctor_called && !ctx->method->klass->valuetype)
top->stype |= UNINIT_THIS_MASK;
}
if (!take_addr && ctx->params [arg]->byref && !is_this_arg_of_struct_instance_method (arg, ctx))
top->stype |= SAFE_BYREF_MASK;
}
}
static void
push_local (VerifyContext *ctx, guint32 arg, int take_addr)
{
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local %d", arg + 1));
} else if (check_overflow (ctx)) {
/*We must let the value be pushed, otherwise we would get an underflow error*/
check_unverifiable_type (ctx, ctx->locals [arg]);
if (ctx->locals [arg]->byref && take_addr)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ByRef of ByRef at 0x%04x", ctx->ip_offset));
ILStackDesc *value = stack_push (ctx);
set_stack_value (ctx, value, ctx->locals [arg], take_addr);
if (local_is_safe_byref (ctx, arg))
value->stype |= SAFE_BYREF_MASK;
}
}
static void
store_arg (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->max_args) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method doesn't have argument %d at 0x%04x", arg + 1, ctx->ip_offset));
if (check_underflow (ctx, 1))
stack_pop (ctx);
return;
}
if (check_underflow (ctx, 1)) {
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, ctx->params [arg], value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in argument store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
}
if (arg == 0 && !(ctx->method->flags & METHOD_ATTRIBUTE_STATIC))
ctx->has_this_store = 1;
}
static void
store_local (VerifyContext *ctx, guint32 arg)
{
ILStackDesc *value;
if (arg >= ctx->num_locals) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method doesn't have local var %d at 0x%04x", arg + 1, ctx->ip_offset));
return;
}
/*TODO verify definite assigment */
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (ctx->locals [arg]->byref) {
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly managed reference when storing on a local variable at 0x%04x", ctx->ip_offset));
if (local_is_safe_byref (ctx, arg) && !stack_slot_is_safe_byref (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot store an unsafe ret byref to a local that was previously stored a save ret byref value at 0x%04x", ctx->ip_offset));
if (stack_slot_is_safe_byref (value) && !local_is_unsafe_byref (ctx, arg))
ctx->locals_verification_state [arg] |= SAFE_BYREF_LOCAL;
if (!stack_slot_is_safe_byref (value))
ctx->locals_verification_state [arg] |= UNSAFE_BYREF_LOCAL;
}
if (!verify_stack_type_compatibility (ctx, ctx->locals [arg], value)) {
char *expected = mono_type_full_name (ctx->locals [arg]);
char *found = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type '%s' on stack cannot be stored to local %d with type '%s' at 0x%04x",
found,
arg,
expected,
ctx->ip_offset));
g_free (expected);
g_free (found);
}
}
/*FIXME add and sub needs special care here*/
static void
do_binop (VerifyContext *ctx, unsigned int opcode, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b, *top;
int idxa, idxb, complexMerge = 0;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a)) {
idxa = TYPE_PTR;
complexMerge = 1;
}
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b)) {
idxb = TYPE_PTR;
complexMerge = 2;
}
--idxa;
--idxb;
res = table [idxa][idxb];
VERIFIER_DEBUG ( printf ("binop res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
top = stack_push (ctx);
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction applyed to ill formed stack (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
copy_stack_value (top, a);
return;
}
if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Binary instruction is not verifiable (%s x %s)", stack_slot_get_name (a), stack_slot_get_name (b)));
res = res & ~NON_VERIFIABLE_RESULT;
}
if (complexMerge && res == TYPE_PTR) {
if (complexMerge == 1)
copy_stack_value (top, a);
else if (complexMerge == 2)
copy_stack_value (top, b);
/*
* There is no need to merge the type of two pointers.
* The only valid operation is subtraction, that returns a native
* int as result and can be used with any 2 pointer kinds.
* This is valid acording to Patition III 1.1.4
*/
} else
top->stype = res;
}
static void
do_boolean_branch_op (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
ILStackDesc *top;
VERIFIER_DEBUG ( printf ("boolean branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Boolean branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (!is_valid_bool_arg (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Argument type %s not valid for brtrue/brfalse at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
check_unmanaged_pointer (ctx, top);
}
static gboolean
stack_slot_is_complex_type_not_reference_type (ILStackDesc *slot)
{
return stack_slot_get_type (slot) == TYPE_COMPLEX && !MONO_TYPE_IS_REFERENCE (slot->type) && !stack_slot_is_boxed_value (slot);
}
static gboolean
stack_slot_is_reference_value (ILStackDesc *slot)
{
return stack_slot_get_type (slot) == TYPE_COMPLEX && (MONO_TYPE_IS_REFERENCE (slot->type) || stack_slot_is_boxed_value (slot));
}
static void
do_branch_op (VerifyContext *ctx, signed int delta, const unsigned char table [TYPE_MAX][TYPE_MAX])
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
int target = ctx->ip_offset + delta;
VERIFIER_DEBUG ( printf ("branch offset %d delta %d target %d\n", ctx->ip_offset, delta, target); );
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_cmp_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1: /*FIXME use constants and not magic numbers.*/
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
return;
}
ctx->target = target;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
VERIFIER_DEBUG ( printf ("branch res %d\n", res); );
VERIFIER_DEBUG ( printf ("idxa %d idxb %d\n", idxa, idxb); );
if (res == TYPE_INV) {
CODE_NOT_VERIFIABLE (ctx,
g_strdup_printf ("Compare and Branch instruction applyed to ill formed stack (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare and Branch instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
}
static void
do_cmp_op (VerifyContext *ctx, const unsigned char table [TYPE_MAX][TYPE_MAX], guint32 opcode)
{
ILStackDesc *a, *b;
int idxa, idxb;
unsigned char res;
if (!check_underflow (ctx, 2))
return;
b = stack_pop (ctx);
a = stack_pop (ctx);
if (opcode == CEE_CGT_UN) {
if ((stack_slot_is_reference_value (a) && stack_slot_is_null_literal (b)) ||
(stack_slot_is_reference_value (b) && stack_slot_is_null_literal (a))) {
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
return;
}
}
idxa = stack_slot_get_underlying_type (a);
if (stack_slot_is_managed_pointer (a))
idxa = TYPE_PTR;
idxb = stack_slot_get_underlying_type (b);
if (stack_slot_is_managed_pointer (b))
idxb = TYPE_PTR;
if (stack_slot_is_complex_type_not_reference_type (a) || stack_slot_is_complex_type_not_reference_type (b)) {
res = TYPE_INV;
} else {
--idxa;
--idxb;
res = table [idxa][idxb];
}
if(res == TYPE_INV) {
char *left_type = stack_slot_full_name (a);
char *right_type = stack_slot_full_name (b);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf("Compare instruction applyed to ill formed stack (%s x %s) at 0x%04x", left_type, right_type, ctx->ip_offset));
g_free (left_type);
g_free (right_type);
} else if (res & NON_VERIFIABLE_RESULT) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Compare instruction is not verifiable (%s x %s) at 0x%04x", stack_slot_get_name (a), stack_slot_get_name (b), ctx->ip_offset));
res = res & ~NON_VERIFIABLE_RESULT;
}
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
}
static void
do_ret (VerifyContext *ctx)
{
MonoType *ret = ctx->signature->ret;
VERIFIER_DEBUG ( printf ("checking ret\n"); );
if (ret->type != MONO_TYPE_VOID) {
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop(ctx);
if (!verify_stack_type_compatibility (ctx, ctx->signature->ret, top)) {
char *ret_type = mono_type_full_name (ctx->signature->ret);
char *stack_type = stack_slot_full_name (top);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible return value on stack with method signature, expected '%s' but got '%s' at 0x%04x", ret_type, stack_type, ctx->ip_offset));
g_free (stack_type);
g_free (ret_type);
return;
}
if (ret->byref && !stack_slot_is_safe_byref (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref and return value is not a safe-to-return-byref at 0x%04x", ctx->ip_offset));
if (ret->type == MONO_TYPE_TYPEDBYREF || mono_type_is_value_type (ret, "System", "ArgIterator") || mono_type_is_value_type (ret, "System", "RuntimeArgumentHandle"))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Method returns byref, TypedReference, ArgIterator or RuntimeArgumentHandle at 0x%04x", ctx->ip_offset));
}
if (ctx->eval.size > 0) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack not empty (%d) after ret at 0x%04x", ctx->eval.size, ctx->ip_offset));
}
if (in_any_block (ctx->header, ctx->ip_offset))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("ret cannot escape exception blocks at 0x%04x", ctx->ip_offset));
}
/*
* FIXME we need to fix the case of a non-virtual instance method defined in the parent but call using a token pointing to a subclass.
* This is illegal but mono_get_method_full decoded it.
* TODO handle calling .ctor outside one or calling the .ctor for other class but super
*/
static void
do_invoke_method (VerifyContext *ctx, int method_token, gboolean virtual_)
{
MonoError error;
int param_count, i;
MonoMethodSignature *sig;
ILStackDesc *value;
MonoMethod *method;
gboolean virt_check_this = FALSE;
gboolean constrained = ctx->prefix_set & PREFIX_CONSTRAINED;
if (!(method = verifier_load_method (ctx, method_token, virtual_ ? "callvirt" : "call")))
return;
if (virtual_) {
CLEAR_PREFIX (ctx, PREFIX_CONSTRAINED);
if (method->klass->valuetype) // && !constrained ???
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with valuetype method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_STATIC))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use callvirtual with static method at 0x%04x", ctx->ip_offset));
} else {
if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use call with an abstract method at 0x%04x", ctx->ip_offset));
if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !(method->flags & METHOD_ATTRIBUTE_FINAL) && !mono_class_is_sealed (method->klass)) {
virt_check_this = TRUE;
ctx->code [ctx->ip_offset].flags |= IL_CODE_CALL_NONFINAL_VIRTUAL;
}
}
if (!(sig = mono_method_get_signature_checked (method, ctx->image, method_token, ctx->generic_context, &error))) {
mono_error_cleanup (&error);
sig = mono_method_get_signature_checked (method, ctx->image, method_token, NULL, &error);
}
if (!sig) {
char *name = mono_type_get_full_name (method->klass);
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not resolve signature of %s:%s at 0x%04x due to: %s", name, method->name, ctx->ip_offset, mono_error_get_message (&error)));
mono_error_cleanup (&error);
g_free (name);
return;
}
param_count = sig->param_count + sig->hasthis;
if (!check_underflow (ctx, param_count))
return;
gboolean is_safe_byref_call = TRUE;
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params[i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter with function signature: Calling method with signature (%s) but for argument %d there is a (%s) on stack at 0x%04x", sig_name, i, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of %s at 0x%04x", virtual_ ? "callvirt" : "call", ctx->ip_offset));
if ((ctx->prefix_set & PREFIX_TAIL) && stack_slot_is_managed_pointer (value)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot pass a byref argument to a tail %s at 0x%04x", virtual_ ? "callvirt" : "call", ctx->ip_offset));
return;
}
if (stack_slot_is_managed_pointer (value) && !stack_slot_is_safe_byref (value))
is_safe_byref_call = FALSE;
}
if (sig->hasthis) {
MonoType *type = &method->klass->byval_arg;
ILStackDesc copy;
if (mono_method_is_constructor (method) && !method->klass->valuetype) {
if (IS_STRICT_MODE (ctx) && !mono_method_is_constructor (ctx->method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor outside one at 0x%04x", ctx->ip_offset));
if (IS_STRICT_MODE (ctx) && method->klass != ctx->method->klass->parent && method->klass != ctx->method->klass)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a constructor of a type different from this or super at 0x%04x", ctx->ip_offset));
ctx->super_ctor_called = TRUE;
value = stack_pop_safe (ctx);
if (IS_STRICT_MODE (ctx) && (value->stype & THIS_POINTER_MASK) != THIS_POINTER_MASK)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid 'this ptr' argument for constructor at 0x%04x", ctx->ip_offset));
if (!(value->stype & UNINIT_THIS_MASK))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Calling the base constructor on an initialized this pointer at 0x%04x", ctx->ip_offset));
} else {
value = stack_pop (ctx);
}
copy_stack_value (©, value);
//TODO we should extract this to a 'drop_byref_argument' and use everywhere
//Other parts of the code suffer from the same issue of
copy.type = mono_type_get_type_byval (copy.type);
copy.stype &= ~POINTER_MASK;
if (virt_check_this && !stack_slot_is_this_pointer (value) && !(method->klass->valuetype || stack_slot_is_boxed_value (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use the call opcode with a non-final virtual method on an object different than the 'this' pointer at 0x%04x", ctx->ip_offset));
if (constrained && virtual_) {
if (!stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object is not a managed pointer for a constrained call at 0x%04x", ctx->ip_offset));
if (!mono_metadata_type_equal_full (mono_type_get_type_byval (value->type), mono_type_get_underlying_type (ctx->constrained_type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Object not compatible with constrained type at 0x%04x", ctx->ip_offset));
copy.stype |= BOXED_MASK;
copy.type = ctx->constrained_type;
} else {
if (stack_slot_is_managed_pointer (value) && !mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a reference type using a managed pointer to the this arg at 0x%04x", ctx->ip_offset));
if (!virtual_ && mono_class_from_mono_type (value->type)->valuetype && !method->klass->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot call a valuetype baseclass at 0x%04x", ctx->ip_offset));
if (virtual_ && mono_class_from_mono_type (value->type)->valuetype && !stack_slot_is_boxed_value (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a valuetype with callvirt at 0x%04x", ctx->ip_offset));
if (method->klass->valuetype && (stack_slot_is_boxed_value (value) || !stack_slot_is_managed_pointer (value)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a boxed or literal valuetype to call a valuetype method at 0x%04x", ctx->ip_offset));
}
if (!verify_stack_type_compatibility (ctx, type, ©)) {
char *expected = mono_type_full_name (type);
char *effective = stack_slot_full_name (©);
char *method_name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible this argument on stack with method signature expected '%s' but got '%s' for a call to '%s' at 0x%04x",
expected, effective, method_name, ctx->ip_offset));
g_free (method_name);
g_free (effective);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, mono_class_from_mono_type (value->type))) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
} else if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *name = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Method %s is not accessible at 0x%04x", name, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (name);
}
if (sig->ret->type != MONO_TYPE_VOID) {
if (!mono_type_is_valid_in_context (ctx, sig->ret))
return;
if (check_overflow (ctx)) {
value = stack_push (ctx);
set_stack_value (ctx, value, sig->ret, FALSE);
if ((ctx->prefix_set & PREFIX_READONLY) && method->klass->rank && !strcmp (method->name, "Address")) {
ctx->prefix_set &= ~PREFIX_READONLY;
value->stype |= CMMP_MASK;
}
if (sig->ret->byref && is_safe_byref_call)
value->stype |= SAFE_BYREF_MASK;
}
}
if ((ctx->prefix_set & PREFIX_TAIL)) {
if (!mono_delegate_ret_equal (mono_method_signature (ctx->method)->ret, sig->ret))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call with incompatible return type at 0x%04x", ctx->ip_offset));
if (ctx->header->code [ctx->ip_offset + 5] != CEE_RET)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Tail call not followed by ret at 0x%04x", ctx->ip_offset));
}
}
static void
do_push_static_field (VerifyContext *ctx, int token, gboolean take_addr)
{
MonoClassField *field;
MonoClass *klass;
if (!check_overflow (ctx))
return;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!(field = verifier_load_field (ctx, token, &klass, take_addr ? "ldsflda" : "ldsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot load non static field at 0x%04x", ctx->ip_offset));
return;
}
/*taking the address of initonly field only works from the static constructor */
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && (ctx->method->flags & (METHOD_ATTRIBUTE_SPECIAL_NAME | METHOD_ATTRIBUTE_STATIC)) && !strcmp (".cctor", ctx->method->name)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
ILStackDesc *value = stack_push (ctx);
set_stack_value (ctx, value, field->type, take_addr);
if (take_addr)
value->stype |= SAFE_BYREF_MASK;
}
static void
do_store_static_field (VerifyContext *ctx, int token) {
MonoClassField *field;
MonoClass *klass;
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!(field = verifier_load_field (ctx, token, &klass, "stsfld")))
return;
if (!(field->type->attrs & FIELD_ATTRIBUTE_STATIC)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Cannot store non static field at 0x%04x", ctx->ip_offset));
return;
}
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type in store static field at 0x%04x", ctx->ip_offset));
return;
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
if (!verify_stack_type_compatibility (ctx, field->type, value)) {
char *stack_name = stack_slot_full_name (value);
char *field_name = mono_type_full_name (field->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type in static field store expected '%s' but found '%s' at 0x%04x",
field_name, stack_name, ctx->ip_offset));
g_free (field_name);
g_free (stack_name);
}
}
static gboolean
check_is_valid_type_for_field_ops (VerifyContext *ctx, int token, ILStackDesc *obj, MonoClassField **ret_field, const char *opcode)
{
MonoClassField *field;
MonoClass *klass;
gboolean is_pointer;
/*must be a reference type, a managed pointer, an unamanaged pointer, or a valuetype*/
if (!(field = verifier_load_field (ctx, token, &klass, opcode)))
return FALSE;
*ret_field = field;
//the value on stack is going to be used as a pointer
is_pointer = stack_slot_get_type (obj) == TYPE_PTR || (stack_slot_get_type (obj) == TYPE_NATIVE_INT && !get_stack_type (&field->parent->byval_arg));
if (field->type->type == MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Typedbyref field is an unverfiable type at 0x%04x", ctx->ip_offset));
return FALSE;
}
g_assert (obj->type);
/*The value on the stack must be a subclass of the defining type of the field*/
/* we need to check if we can load the field from the stack value*/
if (is_pointer) {
if (stack_slot_get_underlying_type (obj) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Native int is not a verifiable type to reference a field at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
} else {
if (!field->parent->valuetype && stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a managed pointer to a reference type and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
/*a value type can be loaded from a value or a managed pointer, but not a boxed object*/
if (field->parent->valuetype && stack_slot_is_boxed_value (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type at stack is a boxed valuetype and is not compatible to reference the field at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_null_literal (obj) && !verify_stack_type_compatibility_full (ctx, &field->parent->byval_arg, obj, TRUE, FALSE)) {
char *found = stack_slot_full_name (obj);
char *expected = mono_type_full_name (&field->parent->byval_arg);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected type '%s' but found '%s' referencing the 'this' argument at 0x%04x", expected, found, ctx->ip_offset));
g_free (found);
g_free (expected);
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_field_full (ctx->method, field, mono_class_from_mono_type (obj->type)))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Type at stack is not accessible at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_FIELD_ACCESS);
}
check_unmanaged_pointer (ctx, obj);
return TRUE;
}
static void
do_push_field (VerifyContext *ctx, int token, gboolean take_addr)
{
ILStackDesc *obj;
MonoClassField *field;
gboolean is_safe_byref = FALSE;
if (!take_addr)
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, take_addr ? "ldflda" : "ldfld"))
return;
if (take_addr && field->parent->valuetype && !stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a temporary value-type at 0x%04x", ctx->ip_offset));
if (take_addr && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY) &&
!(field->parent == ctx->method->klass && mono_method_is_constructor (ctx->method)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot take the address of a init-only field at 0x%04x", ctx->ip_offset));
//must do it here cuz stack_push will return the same slot as obj above
is_safe_byref = take_addr && (stack_slot_is_reference_value (obj) || stack_slot_is_safe_byref (obj));
ILStackDesc *value = stack_push (ctx);
set_stack_value (ctx, value, field->type, take_addr);
if (is_safe_byref)
value->stype |= SAFE_BYREF_MASK;
}
static void
do_store_field (VerifyContext *ctx, int token)
{
ILStackDesc *value, *obj;
MonoClassField *field;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
value = stack_pop (ctx);
obj = stack_pop_safe (ctx);
if (!check_is_valid_type_for_field_ops (ctx, token, obj, &field, "stfld"))
return;
if (!verify_stack_type_compatibility (ctx, field->type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible type %s in field store at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
/*TODO proper handle for Nullable<T>*/
static void
do_box_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "box");
MonoClass *klass;
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*box is a nop for reference types*/
if (stack_slot_get_underlying_type (value) == TYPE_COMPLEX && MONO_TYPE_IS_REFERENCE (value->type) && MONO_TYPE_IS_REFERENCE (type)) {
stack_push_stack_val (ctx, value)->stype |= BOXED_MASK;
return;
}
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for boxing operation at 0x%04x", ctx->ip_offset));
klass = mono_class_from_mono_type (type);
if (mono_class_is_nullable (klass))
type = &mono_class_get_nullable_param (klass)->byval_arg;
stack_push_val (ctx, TYPE_COMPLEX | BOXED_MASK, type);
}
static void
do_unbox_value (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
if (!mono_class_from_mono_type (type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid reference type for unbox at 0x%04x", ctx->ip_offset));
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, value = stack_push (ctx), mono_type_get_type_byref (type), FALSE);
value->stype |= CMMP_MASK;
}
static void
do_unbox_any (VerifyContext *ctx, int klass_token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "unbox.any");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
/*Value should be: a boxed valuetype or a reference type*/
if (!(stack_slot_get_type (value) == TYPE_COMPLEX &&
(stack_slot_is_boxed_value (value) || !mono_class_from_mono_type (value->type)->valuetype)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type %s at stack for unbox.any operation at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_unary_math_op (VerifyContext *ctx, int op)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
break;
case TYPE_R8:
if (op == CEE_NEG)
break;
case TYPE_COMPLEX: /*only enums are ok*/
if (mono_type_is_enum_type (value->type))
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for unary not at 0x%04x", ctx->ip_offset));
}
stack_push_stack_val (ctx, value);
}
static void
do_conversion (VerifyContext *ctx, int kind)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
switch (stack_slot_get_type (value)) {
case TYPE_I4:
case TYPE_I8:
case TYPE_NATIVE_INT:
case TYPE_R8:
break;
default:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type (%s) at stack for conversion operation. Numeric type expected at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
}
switch (kind) {
case TYPE_I4:
stack_push_val (ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
break;
case TYPE_I8:
stack_push_val (ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
break;
case TYPE_R8:
stack_push_val (ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
break;
case TYPE_NATIVE_INT:
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
break;
default:
g_error ("unknown type %02x in conversion", kind);
}
}
static void
do_load_token (VerifyContext *ctx, int token)
{
MonoError error;
gpointer handle;
MonoClass *handle_class;
if (!check_overflow (ctx))
return;
if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
handle = mono_method_get_wrapper_data (ctx->method, token);
handle_class = (MonoClass *)mono_method_get_wrapper_data (ctx->method, token + 1);
if (handle_class == mono_defaults.typehandle_class)
handle = &((MonoClass*)handle)->byval_arg;
} else {
switch (token & 0xff000000) {
case MONO_TOKEN_TYPE_DEF:
case MONO_TOKEN_TYPE_REF:
case MONO_TOKEN_TYPE_SPEC:
case MONO_TOKEN_FIELD_DEF:
case MONO_TOKEN_METHOD_DEF:
case MONO_TOKEN_METHOD_SPEC:
case MONO_TOKEN_MEMBER_REF:
if (!token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Table index out of range 0x%x for token %x for ldtoken at 0x%04x", mono_metadata_token_index (token), token, ctx->ip_offset));
return;
}
break;
default:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid table 0x%x for token 0x%x for ldtoken at 0x%04x", mono_metadata_token_table (token), token, ctx->ip_offset));
return;
}
handle = mono_ldtoken_checked (ctx->image, token, &handle_class, ctx->generic_context, &error);
}
if (!handle) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid token 0x%x for ldtoken at 0x%04x due to %s", token, ctx->ip_offset, mono_error_get_message (&error)));
mono_error_cleanup (&error);
return;
}
if (handle_class == mono_defaults.typehandle_class) {
mono_type_is_valid_in_context (ctx, (MonoType*)handle);
} else if (handle_class == mono_defaults.methodhandle_class) {
mono_method_is_valid_in_context (ctx, (MonoMethod*)handle);
} else if (handle_class == mono_defaults.fieldhandle_class) {
mono_type_is_valid_in_context (ctx, &((MonoClassField*)handle)->parent->byval_arg);
} else {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid ldtoken type %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
}
stack_push_val (ctx, TYPE_COMPLEX, mono_class_get_type (handle_class));
}
static void
do_ldobj_value (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "ldobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)
&& stack_slot_get_type (value) != TYPE_NATIVE_INT
&& !(stack_slot_get_type (value) == TYPE_PTR && value->type->type != MONO_TYPE_FNPTR)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid argument %s to ldobj at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
return;
}
if (stack_slot_get_type (value) == TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Using native pointer to ldobj at 0x%04x", ctx->ip_offset));
/*We have a byval on the stack, but the comparison must be strict. */
if (!verify_type_compatibility_full (ctx, type, mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldojb operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, FALSE);
}
static void
do_stobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "stobj");
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stobj at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of stobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (src) && !MONO_TYPE_IS_REFERENCE (src->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, type, src)) {
char *type_name = mono_type_full_name (type);
char *src_name = stack_slot_full_name (src);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token '%s' and source '%s' of stobj don't match ' at 0x%04x", type_name, src_name, ctx->ip_offset));
g_free (type_name);
g_free (src_name);
}
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of stobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_cpobj (VerifyContext *ctx, int token)
{
ILStackDesc *dest, *src;
MonoType *type = get_boxable_mono_type (ctx, token, "cpobj");
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
src = stack_pop (ctx);
dest = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (src))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid source of cpobj operation at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid destination of cpobj operation at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (dest))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with cpobj at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, type, mono_type_get_type_byval (src->type)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Token and source types of cpobj don't match at 0x%04x", ctx->ip_offset));
if (!verify_type_compatibility (ctx, mono_type_get_type_byval (dest->type), type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Destination and token types of cpobj don't match at 0x%04x", ctx->ip_offset));
}
static void
do_initobj (VerifyContext *ctx, int token)
{
ILStackDesc *obj;
MonoType *stack, *type = get_boxable_mono_type (ctx, token, "initobj");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
obj = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid object address for initobj at 0x%04x", ctx->ip_offset));
if (stack_slot_is_managed_mutability_pointer (obj))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with initobj at 0x%04x", ctx->ip_offset));
stack = mono_type_get_type_byval (obj->type);
if (MONO_TYPE_IS_REFERENCE (stack)) {
if (!verify_type_compatibility (ctx, stack, type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
else if (IS_STRICT_MODE (ctx) && !mono_metadata_type_equal (type, stack))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type token of initobj not compatible with value on stack at 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility (ctx, stack, type)) {
char *expected_name = mono_type_full_name (type);
char *stack_name = mono_type_full_name (stack);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Initobj %s not compatible with value on stack %s at 0x%04x", expected_name, stack_name, ctx->ip_offset));
g_free (expected_name);
g_free (stack_name);
}
}
static void
do_newobj (VerifyContext *ctx, int token)
{
ILStackDesc *value;
int i;
MonoMethodSignature *sig;
MonoMethod *method;
gboolean is_delegate = FALSE;
if (!(method = verifier_load_method (ctx, token, "newobj")))
return;
if (!mono_method_is_constructor (method)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Method from token 0x%08x not a constructor at 0x%04x", token, ctx->ip_offset));
return;
}
if (mono_class_get_flags (method->klass) & (TYPE_ATTRIBUTE_ABSTRACT | TYPE_ATTRIBUTE_INTERFACE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Trying to instantiate an abstract or interface type at 0x%04x", ctx->ip_offset));
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL)) {
char *from = mono_method_full_name (ctx->method, TRUE);
char *to = mono_method_full_name (method, TRUE);
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Constructor %s not visible from %s at 0x%04x", to, from, ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
g_free (from);
g_free (to);
}
//FIXME use mono_method_get_signature_full
sig = mono_method_signature (method);
if (!sig) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature to newobj at 0x%04x", ctx->ip_offset));
return;
}
if (!sig->hasthis) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid constructor signature missing hasthis at 0x%04x", ctx->ip_offset));
return;
}
if (!check_underflow (ctx, sig->param_count))
return;
is_delegate = method->klass->parent == mono_defaults.multicastdelegate_class;
if (is_delegate) {
ILStackDesc *funptr;
//first arg is object, second arg is fun ptr
if (sig->param_count != 2) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid delegate constructor at 0x%04x", ctx->ip_offset));
return;
}
funptr = stack_pop (ctx);
value = stack_pop (ctx);
verify_delegate_compatibility (ctx, method->klass, value, funptr);
} else {
for (i = sig->param_count - 1; i >= 0; --i) {
VERIFIER_DEBUG ( printf ("verifying constructor argument %d\n", i); );
value = stack_pop (ctx);
if (!verify_stack_type_compatibility (ctx, sig->params [i], value)) {
char *stack_name = stack_slot_full_name (value);
char *sig_name = mono_type_full_name (sig->params [i]);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Incompatible parameter value with constructor signature: %s X %s at 0x%04x", sig_name, stack_name, ctx->ip_offset));
g_free (stack_name);
g_free (sig_name);
}
if (stack_slot_is_managed_mutability_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer as argument of newobj at 0x%04x", ctx->ip_offset));
}
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &method->klass->byval_arg, FALSE);
}
static void
do_cast (VerifyContext *ctx, int token, const char *opcode) {
ILStackDesc *value;
MonoType *type;
gboolean is_boxed;
gboolean do_box;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, opcode)))
return;
if (type->byref) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid %s type at 0x%04x", opcode, ctx->ip_offset));
return;
}
value = stack_pop (ctx);
is_boxed = stack_slot_is_boxed_value (value);
if (stack_slot_is_managed_pointer (value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
else if (!MONO_TYPE_IS_REFERENCE (value->type) && !is_boxed) {
char *name = stack_slot_full_name (value);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a reference type on stack for %s but found %s at 0x%04x", opcode, name, ctx->ip_offset));
g_free (name);
}
switch (value->type->type) {
case MONO_TYPE_FNPTR:
case MONO_TYPE_PTR:
case MONO_TYPE_TYPEDBYREF:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value for %s at 0x%04x", opcode, ctx->ip_offset));
default:
break;
}
do_box = is_boxed || mono_type_is_generic_argument(type) || mono_class_from_mono_type (type)->valuetype;
stack_push_val (ctx, TYPE_COMPLEX | (do_box ? BOXED_MASK : 0), type);
}
static MonoType *
mono_type_from_opcode (int opcode) {
switch (opcode) {
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_STIND_I1:
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_STELEM_I1:
return &mono_defaults.sbyte_class->byval_arg;
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_STIND_I2:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_STELEM_I2:
return &mono_defaults.int16_class->byval_arg;
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_STIND_I4:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_STELEM_I4:
return &mono_defaults.int32_class->byval_arg;
case CEE_LDIND_I8:
case CEE_STIND_I8:
case CEE_LDELEM_I8:
case CEE_STELEM_I8:
return &mono_defaults.int64_class->byval_arg;
case CEE_LDIND_R4:
case CEE_STIND_R4:
case CEE_LDELEM_R4:
case CEE_STELEM_R4:
return &mono_defaults.single_class->byval_arg;
case CEE_LDIND_R8:
case CEE_STIND_R8:
case CEE_LDELEM_R8:
case CEE_STELEM_R8:
return &mono_defaults.double_class->byval_arg;
case CEE_LDIND_I:
case CEE_STIND_I:
case CEE_LDELEM_I:
case CEE_STELEM_I:
return &mono_defaults.int_class->byval_arg;
case CEE_LDIND_REF:
case CEE_STIND_REF:
case CEE_LDELEM_REF:
case CEE_STELEM_REF:
return &mono_defaults.object_class->byval_arg;
default:
g_error ("unknown opcode %02x in mono_type_from_opcode ", opcode);
return NULL;
}
}
static void
do_load_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *value;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (!stack_slot_is_managed_pointer (value)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Load indirect not using a manager pointer at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
return;
}
if (opcode == CEE_LDIND_REF) {
if (stack_slot_get_underlying_type (value) != TYPE_COMPLEX || mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind_ref expected object byref operation at 0x%04x", ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_get_type_byval (value->type), FALSE);
} else {
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (value->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type at stack for ldind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_type_from_opcode (opcode), FALSE);
}
}
static void
do_store_indirect (VerifyContext *ctx, int opcode)
{
ILStackDesc *addr, *val;
CLEAR_PREFIX (ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (ctx, 2))
return;
val = stack_pop (ctx);
addr = stack_pop (ctx);
check_unmanaged_pointer (ctx, addr);
if (!stack_slot_is_managed_pointer (addr) && stack_slot_get_type (addr) != TYPE_PTR) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid non-pointer argument to stind at 0x%04x", ctx->ip_offset));
return;
}
if (stack_slot_is_managed_mutability_pointer (addr)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with stind at 0x%04x", ctx->ip_offset));
return;
}
if (!verify_type_compatibility_full (ctx, mono_type_from_opcode (opcode), mono_type_get_type_byval (addr->type), TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid addr type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, mono_type_from_opcode (opcode), val))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value type at stack for stind 0x%x operation at 0x%04x", opcode, ctx->ip_offset));
}
static void
do_newarr (VerifyContext *ctx, int token)
{
ILStackDesc *value;
MonoType *type = get_boxable_mono_type (ctx, token, "newarr");
if (!type)
return;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Array size type on stack (%s) is not a verifiable type at 0x%04x", stack_slot_get_name (value), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), mono_class_get_type (mono_array_class_get (mono_class_from_mono_type (type), 1)), FALSE);
}
/*FIXME handle arrays that are not 0-indexed*/
static void
do_ldlen (VerifyContext *ctx)
{
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_COMPLEX || value->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type for ldlen at 0x%04x", ctx->ip_offset));
stack_push_val (ctx, TYPE_NATIVE_INT, &mono_defaults.int_class->byval_arg);
}
/*FIXME handle arrays that are not 0-indexed*/
/*FIXME handle readonly prefix and CMMP*/
static void
do_ldelema (VerifyContext *ctx, int klass_token)
{
ILStackDesc *index, *array, *res;
MonoType *type = get_boxable_mono_type (ctx, klass_token, "ldelema");
gboolean valid;
if (!type)
return;
if (!check_underflow (ctx, 2))
return;
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelema is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelema at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (get_stack_type (type) == TYPE_I4 || get_stack_type (type) == TYPE_NATIVE_INT) {
valid = verify_type_compatibility_full (ctx, type, &array->type->data.klass->byval_arg, TRUE);
} else {
valid = mono_metadata_type_equal (type, &array->type->data.klass->byval_arg);
}
if (!valid)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelema at 0x%04x", ctx->ip_offset));
}
}
res = stack_push (ctx);
set_stack_value (ctx, res, type, TRUE);
if (ctx->prefix_set & PREFIX_READONLY) {
ctx->prefix_set &= ~PREFIX_READONLY;
res->stype |= CMMP_MASK;
}
res->stype |= SAFE_BYREF_MASK;
}
/*
* FIXME handle arrays that are not 0-indexed
* FIXME handle readonly prefix and CMMP
*/
static void
do_ldelem (VerifyContext *ctx, int opcode, int token)
{
#define IS_ONE_OF2(T, A, B) (T == A || T == B)
ILStackDesc *index, *array;
MonoType *type;
if (!check_underflow (ctx, 2))
return;
if (opcode == CEE_LDELEM) {
if (!(type = verifier_load_type (ctx, token, "ldelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for ldelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for ldelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
else {
if (opcode == CEE_LDELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for ldelem.ref 0x%04x", ctx->ip_offset));
type = &array->type->data.klass->byval_arg;
} else {
MonoType *candidate = &array->type->data.klass->byval_arg;
if (IS_STRICT_MODE (ctx)) {
MonoType *underlying_type = mono_type_get_underlying_type_any (type);
MonoType *underlying_candidate = mono_type_get_underlying_type_any (candidate);
if ((IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I, MONO_TYPE_U)) ||
(IS_ONE_OF2 (underlying_candidate->type, MONO_TYPE_I4, MONO_TYPE_U4) && IS_ONE_OF2 (underlying_type->type, MONO_TYPE_I, MONO_TYPE_U)))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
if (!verify_type_compatibility_full (ctx, type, candidate, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for ldelem.X at 0x%04x", ctx->ip_offset));
}
}
}
set_stack_value (ctx, stack_push (ctx), type, FALSE);
#undef IS_ONE_OF2
}
/*
* FIXME handle arrays that are not 0-indexed
*/
static void
do_stelem (VerifyContext *ctx, int opcode, int token)
{
ILStackDesc *index, *array, *value;
MonoType *type;
if (!check_underflow (ctx, 3))
return;
if (opcode == CEE_STELEM) {
if (!(type = verifier_load_type (ctx, token, "stelem.any"))) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Type (0x%08x) not found at 0x%04x", token, ctx->ip_offset));
return;
}
} else {
type = mono_type_from_opcode (opcode);
}
value = stack_pop (ctx);
index = stack_pop (ctx);
array = stack_pop (ctx);
if (stack_slot_get_type (index) != TYPE_I4 && stack_slot_get_type (index) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Index type(%s) for stdelem.X is not an int or a native int at 0x%04x", stack_slot_get_name (index), ctx->ip_offset));
if (!stack_slot_is_null_literal (array)) {
if (stack_slot_get_type (array) != TYPE_COMPLEX || array->type->type != MONO_TYPE_SZARRAY) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type(%s) for stelem.X at 0x%04x", stack_slot_get_name (array), ctx->ip_offset));
} else {
if (opcode == CEE_STELEM_REF) {
if (array->type->data.klass->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (!verify_type_compatibility_full (ctx, &array->type->data.klass->byval_arg, type, TRUE)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid array type on stack for stdelem.X at 0x%04x", ctx->ip_offset));
}
}
}
if (opcode == CEE_STELEM_REF) {
if (!stack_slot_is_boxed_value (value) && mono_class_from_mono_type (value->type)->valuetype)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value is not a reference type for stelem.ref 0x%04x", ctx->ip_offset));
} else if (opcode != CEE_STELEM_REF) {
if (!verify_stack_type_compatibility (ctx, type, value))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid value on stack for stdelem.X at 0x%04x", ctx->ip_offset));
if (stack_slot_is_boxed_value (value) && !MONO_TYPE_IS_REFERENCE (value->type) && !MONO_TYPE_IS_REFERENCE (type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use stobj with a boxed source value that is not a reference type at 0x%04x", ctx->ip_offset));
}
}
static void
do_throw (VerifyContext *ctx)
{
ILStackDesc *exception;
if (!check_underflow (ctx, 1))
return;
exception = stack_pop (ctx);
if (!stack_slot_is_null_literal (exception) && !(stack_slot_get_type (exception) == TYPE_COMPLEX && !mono_class_from_mono_type (exception->type)->valuetype))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type at 0x%04x", ctx->ip_offset));
if (mono_type_is_generic_argument (exception->type) && !stack_slot_is_boxed_value (exception)) {
char *name = mono_type_full_name (exception->type);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid type on stack for throw, expected reference type but found unboxed %s at 0x%04x ", name, ctx->ip_offset));
g_free (name);
}
/*The stack is left empty after a throw*/
ctx->eval.size = 0;
}
static void
do_endfilter (VerifyContext *ctx)
{
MonoExceptionClause *clause;
if (IS_STRICT_MODE (ctx)) {
if (ctx->eval.size != 1)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack size must have one item for endfilter at 0x%04x", ctx->ip_offset));
if (ctx->eval.size >= 1 && stack_slot_get_type (stack_pop (ctx)) != TYPE_I4)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Stack item type is not an int32 for endfilter at 0x%04x", ctx->ip_offset));
}
if ((clause = is_correct_endfilter (ctx, ctx->ip_offset))) {
if (IS_STRICT_MODE (ctx)) {
if (ctx->ip_offset != clause->handler_offset - 2)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
} else {
if ((ctx->ip_offset != clause->handler_offset - 2) && !MONO_OFFSET_IN_HANDLER (clause, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter is not the last instruction of the filter clause at 0x%04x", ctx->ip_offset));
}
} else {
if (IS_STRICT_MODE (ctx) && !is_unverifiable_endfilter (ctx, ctx->ip_offset))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
else
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("endfilter outside filter clause at 0x%04x", ctx->ip_offset));
}
ctx->eval.size = 0;
}
static void
do_leave (VerifyContext *ctx, int delta)
{
int target = ((gint32)ctx->ip_offset) + delta;
if (target >= ctx->code_size || target < 0)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target out of code at 0x%04x", ctx->ip_offset));
if (!is_correct_leave (ctx->header, ctx->ip_offset, target))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Leave not allowed in finally block at 0x%04x", ctx->ip_offset));
ctx->eval.size = 0;
ctx->target = target;
}
/*
* do_static_branch:
*
* Verify br and br.s opcodes.
*/
static void
do_static_branch (VerifyContext *ctx, int delta)
{
int target = ctx->ip_offset + delta;
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("branch target out of code at 0x%04x", ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Branch target escapes out of exception block at 0x%04x", ctx->ip_offset));
break;
}
ctx->target = target;
}
static void
do_switch (VerifyContext *ctx, int count, const unsigned char *data)
{
int i, base = ctx->ip_offset + 5 + count * 4;
ILStackDesc *value;
if (!check_underflow (ctx, 1))
return;
value = stack_pop (ctx);
if (stack_slot_get_type (value) != TYPE_I4 && stack_slot_get_type (value) != TYPE_NATIVE_INT)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to switch at 0x%04x", ctx->ip_offset));
for (i = 0; i < count; ++i) {
int target = base + read32 (data + i * 4);
if (target < 0 || target >= ctx->code_size) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x out of code at 0x%04x", i, ctx->ip_offset));
return;
}
switch (is_valid_branch_instruction (ctx->header, ctx->ip_offset, target)) {
case 1:
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
break;
case 2:
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Switch target %x escapes out of exception block at 0x%04x", i, ctx->ip_offset));
return;
}
merge_stacks (ctx, &ctx->eval, &ctx->code [target], FALSE, TRUE);
}
}
static void
do_load_function_ptr (VerifyContext *ctx, guint32 token, gboolean virtual_)
{
ILStackDesc *top;
MonoMethod *method;
if (virtual_ && !check_underflow (ctx, 1))
return;
if (!virtual_ && !check_overflow (ctx))
return;
if (ctx->method->wrapper_type != MONO_WRAPPER_NONE) {
method = (MonoMethod *)mono_method_get_wrapper_data (ctx->method, (guint32)token);
if (!method) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
} else {
if (!IS_METHOD_DEF_OR_REF_OR_SPEC (token) || !token_bounds_check (ctx->image, token)) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid token %x for ldftn at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!(method = verifier_load_method (ctx, token, virtual_ ? "ldvirtfrn" : "ldftn")))
return;
}
if (mono_method_is_constructor (method))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldftn with a constructor at 0x%04x", ctx->ip_offset));
if (virtual_) {
ILStackDesc *top = stack_pop (ctx);
if (stack_slot_get_type (top) != TYPE_COMPLEX || top->type->type == MONO_TYPE_VALUETYPE)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Invalid argument to ldvirtftn at 0x%04x", ctx->ip_offset));
if (method->flags & METHOD_ATTRIBUTE_STATIC)
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use ldvirtftn with a constructor at 0x%04x", ctx->ip_offset));
if (!verify_stack_type_compatibility (ctx, &method->klass->byval_arg, top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Unexpected object for ldvirtftn at 0x%04x", ctx->ip_offset));
}
if (!IS_SKIP_VISIBILITY (ctx) && !mono_method_can_access_method_full (ctx->method, method, NULL))
CODE_NOT_VERIFIABLE2 (ctx, g_strdup_printf ("Loaded method is not visible for ldftn/ldvirtftn at 0x%04x", ctx->ip_offset), MONO_EXCEPTION_METHOD_ACCESS);
top = stack_push_val(ctx, TYPE_PTR, mono_type_create_fnptr_from_mono_method (ctx, method));
top->method = method;
}
static void
do_sizeof (VerifyContext *ctx, int token)
{
MonoType *type;
if (!(type = verifier_load_type (ctx, token, "sizeof")))
return;
if (type->byref && type->type != MONO_TYPE_TYPEDBYREF) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of byref type at 0x%04x", ctx->ip_offset));
return;
}
if (type->type == MONO_TYPE_VOID) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Invalid use of void type at 0x%04x", ctx->ip_offset));
return;
}
if (check_overflow (ctx))
set_stack_value (ctx, stack_push (ctx), &mono_defaults.uint32_class->byval_arg, FALSE);
}
/* Stack top can be of any type, the runtime doesn't care and treat everything as an int. */
static void
do_localloc (VerifyContext *ctx)
{
if (ctx->eval.size != 1) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
if (in_any_exception_block (ctx->header, ctx->ip_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Stack must have only size item in localloc at 0x%04x", ctx->ip_offset));
return;
}
/*TODO verify top type*/
/* top = */ stack_pop (ctx);
set_stack_value (ctx, stack_push (ctx), &mono_defaults.int_class->byval_arg, FALSE);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Instruction localloc in never verifiable at 0x%04x", ctx->ip_offset));
}
static void
do_ldstr (VerifyContext *ctx, guint32 token)
{
GSList *error = NULL;
if (ctx->method->wrapper_type == MONO_WRAPPER_NONE && !image_is_dynamic (ctx->image)) {
if (mono_metadata_token_code (token) != MONO_TOKEN_STRING) {
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string token %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
if (!mono_verifier_verify_string_signature (ctx->image, mono_metadata_token_index (token), &error)) {
if (error)
ctx->list = g_slist_concat (ctx->list, error);
ADD_VERIFY_ERROR2 (ctx, g_strdup_printf ("Invalid string index %x at 0x%04x", token, ctx->ip_offset), MONO_EXCEPTION_BAD_IMAGE);
return;
}
}
if (check_overflow (ctx))
stack_push_val (ctx, TYPE_COMPLEX, &mono_defaults.string_class->byval_arg);
}
static void
do_refanyval (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanyval, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), type, TRUE);
}
static void
do_refanytype (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (top->stype != TYPE_PTR || top->type->type != MONO_TYPE_TYPEDBYREF)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected a typedref as argument for refanytype, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typehandle_class->byval_arg, FALSE);
}
static void
do_mkrefany (VerifyContext *ctx, int token)
{
ILStackDesc *top;
MonoType *type;
if (!check_underflow (ctx, 1))
return;
if (!(type = get_boxable_mono_type (ctx, token, "refanyval")))
return;
top = stack_pop (ctx);
if (stack_slot_is_managed_mutability_pointer (top))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot use a readonly pointer with mkrefany at 0x%04x", ctx->ip_offset));
if (!stack_slot_is_managed_pointer (top)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Expected a managed pointer for mkrefany, but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
}else {
MonoType *stack_type = mono_type_get_type_byval (top->type);
if (MONO_TYPE_IS_REFERENCE (type) && !mono_metadata_type_equal (type, stack_type))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
if (!MONO_TYPE_IS_REFERENCE (type) && !verify_type_compatibility_full (ctx, type, stack_type, TRUE))
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Type not compatible for mkrefany at 0x%04x", ctx->ip_offset));
}
set_stack_value (ctx, stack_push (ctx), &mono_defaults.typed_reference_class->byval_arg, FALSE);
}
static void
do_ckfinite (VerifyContext *ctx)
{
ILStackDesc *top;
if (!check_underflow (ctx, 1))
return;
top = stack_pop (ctx);
if (stack_slot_get_underlying_type (top) != TYPE_R8)
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Expected float32 or float64 on stack for ckfinit but found %s at 0x%04x", stack_slot_get_name (top), ctx->ip_offset));
stack_push_stack_val (ctx, top);
}
/*
* merge_stacks:
* Merge the stacks and perform compat checks. The merge check if types of @from are mergeable with type of @to
*
* @from holds new values for a given control path
* @to holds the current values of a given control path
*
* TODO we can eliminate the from argument as all callers pass &ctx->eval
*/
static void
merge_stacks (VerifyContext *ctx, ILCodeDesc *from, ILCodeDesc *to, gboolean start, gboolean external)
{
MonoError error;
int i, j;
stack_init (ctx, to);
if (start) {
if (to->flags == IL_CODE_FLAG_NOT_PROCESSED)
from->size = 0;
else
stack_copy (&ctx->eval, to);
goto end_verify;
} else if (!(to->flags & IL_CODE_STACK_MERGED)) {
stack_copy (to, &ctx->eval);
goto end_verify;
}
VERIFIER_DEBUG ( printf ("performing stack merge %d x %d\n", from->size, to->size); );
if (from->size != to->size) {
VERIFIER_DEBUG ( printf ("different stack sizes %d x %d at 0x%04x\n", from->size, to->size, ctx->ip_offset); );
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Could not merge stacks, different sizes (%d x %d) at 0x%04x", from->size, to->size, ctx->ip_offset));
goto end_verify;
}
//FIXME we need to preserve CMMP attributes
//FIXME we must take null literals into consideration.
for (i = 0; i < from->size; ++i) {
ILStackDesc *new_slot = from->stack + i;
ILStackDesc *old_slot = to->stack + i;
MonoType *new_type = mono_type_from_stack_slot (new_slot);
MonoType *old_type = mono_type_from_stack_slot (old_slot);
MonoClass *old_class = mono_class_from_mono_type (old_type);
MonoClass *new_class = mono_class_from_mono_type (new_type);
MonoClass *match_class = NULL;
// check for safe byref before the next steps override new_slot
if (stack_slot_is_safe_byref (old_slot) ^ stack_slot_is_safe_byref (new_slot)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stack at depth %d byref types are safe byref incompatible at %0x04x ", i, ctx->ip_offset));
goto end_verify;
}
// S := T then U = S (new value is compatible with current value, keep current)
if (verify_stack_type_compatibility (ctx, old_type, new_slot)) {
copy_stack_value (new_slot, old_slot);
continue;
}
// T := S then U = T (old value is compatible with current value, use new)
if (verify_stack_type_compatibility (ctx, new_type, old_slot)) {
copy_stack_value (old_slot, new_slot);
continue;
}
/*Both slots are the same boxed valuetype. Simply copy it.*/
if (stack_slot_is_boxed_value (old_slot) &&
stack_slot_is_boxed_value (new_slot) &&
mono_metadata_type_equal (old_type, new_type)) {
copy_stack_value (new_slot, old_slot);
continue;
}
if (mono_type_is_generic_argument (old_type) || mono_type_is_generic_argument (new_type)) {
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
goto end_verify;
}
//both are reference types, use closest common super type
if (!mono_class_from_mono_type (old_type)->valuetype
&& !mono_class_from_mono_type (new_type)->valuetype
&& !stack_slot_is_managed_pointer (old_slot)
&& !stack_slot_is_managed_pointer (new_slot)) {
mono_class_setup_supertypes (old_class);
mono_class_setup_supertypes (new_class);
for (j = MIN (old_class->idepth, new_class->idepth) - 1; j > 0; --j) {
if (mono_metadata_type_equal (&old_class->supertypes [j]->byval_arg, &new_class->supertypes [j]->byval_arg)) {
match_class = old_class->supertypes [j];
goto match_found;
}
}
mono_class_setup_interfaces (old_class, &error);
if (!mono_error_ok (&error)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
mono_error_cleanup (&error);
goto end_verify;
}
mono_class_setup_interfaces (new_class, &error);
if (!mono_error_ok (&error)) {
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Cannot merge stacks due to a TypeLoadException %s at 0x%04x", mono_error_get_message (&error), ctx->ip_offset));
mono_error_cleanup (&error);
goto end_verify;
}
/* if old class is an interface that new class implements */
if (mono_class_is_interface (old_class)) {
if (verifier_class_is_assignable_from (old_class, new_class)) {
match_class = old_class;
goto match_found;
}
for (j = 0; j < old_class->interface_count; ++j) {
if (verifier_class_is_assignable_from (old_class->interfaces [j], new_class)) {
match_class = old_class->interfaces [j];
goto match_found;
}
}
}
if (mono_class_is_interface (new_class)) {
if (verifier_class_is_assignable_from (new_class, old_class)) {
match_class = new_class;
goto match_found;
}
for (j = 0; j < new_class->interface_count; ++j) {
if (verifier_class_is_assignable_from (new_class->interfaces [j], old_class)) {
match_class = new_class->interfaces [j];
goto match_found;
}
}
}
//No decent super type found, use object
match_class = mono_defaults.object_class;
goto match_found;
} else if (is_compatible_boxed_valuetype (ctx,old_type, new_type, new_slot, FALSE) || is_compatible_boxed_valuetype (ctx, new_type, old_type, old_slot, FALSE)) {
match_class = mono_defaults.object_class;
goto match_found;
}
{
char *old_name = stack_slot_full_name (old_slot);
char *new_name = stack_slot_full_name (new_slot);
CODE_NOT_VERIFIABLE (ctx, g_strdup_printf ("Could not merge stack at depth %d, types not compatible: %s X %s at 0x%04x", i, old_name, new_name, ctx->ip_offset));
g_free (old_name);
g_free (new_name);
}
set_stack_value (ctx, old_slot, &new_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
goto end_verify;
match_found:
g_assert (match_class);
set_stack_value (ctx, old_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
set_stack_value (ctx, new_slot, &match_class->byval_arg, stack_slot_is_managed_pointer (old_slot));
continue;
}
end_verify:
if (external)
to->flags |= IL_CODE_FLAG_WAS_TARGET;
to->flags |= IL_CODE_STACK_MERGED;
}
#define HANDLER_START(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER ? (clause)->data.filter_offset : clause->handler_offset)
#define IS_CATCH_OR_FILTER(clause) ((clause)->flags == MONO_EXCEPTION_CLAUSE_FILTER || (clause)->flags == MONO_EXCEPTION_CLAUSE_NONE)
/**
* is_clause_in_range :
*
* Returns TRUE if either the protected block or the handler of @clause is in the @start - @end range.
*/
static gboolean
is_clause_in_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset >= start && clause->try_offset < end)
return TRUE;
if (HANDLER_START (clause) >= start && HANDLER_START (clause) < end)
return TRUE;
return FALSE;
}
/**
* is_clause_inside_range :
*
* Returns TRUE if @clause lies completely inside the @start - @end range.
*/
static gboolean
is_clause_inside_range (MonoExceptionClause *clause, guint32 start, guint32 end)
{
if (clause->try_offset < start || (clause->try_offset + clause->try_len) > end)
return FALSE;
if (HANDLER_START (clause) < start || (clause->handler_offset + clause->handler_len) > end)
return FALSE;
return TRUE;
}
/**
* is_clause_nested :
*
* Returns TRUE if @nested is nested in @clause.
*/
static gboolean
is_clause_nested (MonoExceptionClause *clause, MonoExceptionClause *nested)
{
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (nested, clause->data.filter_offset, clause->handler_offset))
return TRUE;
return is_clause_inside_range (nested, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_inside_range (nested, clause->handler_offset, clause->handler_offset + clause->handler_len);
}
/* Test the relationship between 2 exception clauses. Follow P.1 12.4.2.7 of ECMA
* the each pair of exception must have the following properties:
* - one is fully nested on another (the outer must not be a filter clause) (the nested one must come earlier)
* - completely disjoin (none of the 3 regions of each entry overlap with the other 3)
* - mutual protection (protected block is EXACT the same, handlers are disjoin and all handler are catch or all handler are filter)
*/
static void
verify_clause_relationship (VerifyContext *ctx, MonoExceptionClause *clause, MonoExceptionClause *to_test)
{
/*clause is nested*/
if (to_test->flags == MONO_EXCEPTION_CLAUSE_FILTER && is_clause_inside_range (clause, to_test->data.filter_offset, to_test->handler_offset)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clause inside filter"));
return;
}
/*wrong nesting order.*/
if (is_clause_nested (clause, to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Nested exception clause appears after enclosing clause"));
return;
}
/*mutual protection*/
if (clause->try_offset == to_test->try_offset && clause->try_len == to_test->try_len) {
/*handlers are not disjoint*/
if (is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception handlers overlap"));
return;
}
/* handlers are not catch or filter */
if (!IS_CATCH_OR_FILTER (clause) || !IS_CATCH_OR_FILTER (to_test)) {
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses with shared protected block are neither catch or filter"));
return;
}
/*OK*/
return;
}
/*not completelly disjoint*/
if ((is_clause_in_range (to_test, clause->try_offset, clause->try_offset + clause->try_len) ||
is_clause_in_range (to_test, HANDLER_START (clause), clause->handler_offset + clause->handler_len)) && !is_clause_nested (to_test, clause))
ADD_VERIFY_ERROR (ctx, g_strdup_printf ("Exception clauses overlap"));
}
#define code_bounds_check(size) \
if (ADDP_IS_GREATER_OR_OVF (ip, size, end)) {\
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Code overrun starting with 0x%x at 0x%04x", *ip, ctx.ip_offset)); \
break; \
} \
static gboolean
mono_opcode_is_prefix (int op)
{
switch (op) {
case MONO_CEE_UNALIGNED_:
case MONO_CEE_VOLATILE_:
case MONO_CEE_TAIL_:
case MONO_CEE_CONSTRAINED_:
case MONO_CEE_READONLY_:
return TRUE;
}
return FALSE;
}
/*
* FIXME: need to distinguish between valid and verifiable.
* Need to keep track of types on the stack.
*/
/**
* mono_method_verify:
* Verify types for opcodes.
*/
GSList*
mono_method_verify (MonoMethod *method, int level)
{
MonoError error;
const unsigned char *ip, *code_start;
const unsigned char *end;
MonoSimpleBasicBlock *bb = NULL, *original_bb = NULL;
int i, n, need_merge = 0, start = 0;
guint ip_offset = 0, prefix = 0;
MonoGenericContext *generic_context = NULL;
MonoImage *image;
VerifyContext ctx;
GSList *tmp;
VERIFIER_DEBUG ( printf ("Verify IL for method %s %s %s\n", method->klass->name_space, method->klass->name, method->name); );
init_verifier_stats ();
if (method->iflags & (METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL | METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
(method->flags & (METHOD_ATTRIBUTE_PINVOKE_IMPL | METHOD_ATTRIBUTE_ABSTRACT))) {
return NULL;
}
memset (&ctx, 0, sizeof (VerifyContext));
//FIXME use mono_method_get_signature_full
ctx.signature = mono_method_signature (method);
if (!ctx.signature) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method signature"));
finish_collect_stats ();
return ctx.list;
}
if (!method->is_generic && !mono_class_is_gtd (method->klass) && ctx.signature->has_type_parameters) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Method and signature don't match in terms of genericity"));
finish_collect_stats ();
return ctx.list;
}
ctx.header = mono_method_get_header_checked (method, &error);
if (!ctx.header) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Could not decode method header due to %s", mono_error_get_message (&error)));
mono_error_cleanup (&error);
finish_collect_stats ();
return ctx.list;
}
ctx.method = method;
code_start = ip = ctx.header->code;
end = ip + ctx.header->code_size;
ctx.image = image = method->klass->image;
ctx.max_args = ctx.signature->param_count + ctx.signature->hasthis;
ctx.max_stack = ctx.header->max_stack;
ctx.verifiable = ctx.valid = 1;
ctx.level = level;
ctx.code = g_new (ILCodeDesc, ctx.header->code_size);
ctx.code_size = ctx.header->code_size;
_MEM_ALLOC (sizeof (ILCodeDesc) * ctx.header->code_size);
memset(ctx.code, 0, sizeof (ILCodeDesc) * ctx.header->code_size);
ctx.num_locals = ctx.header->num_locals;
ctx.locals = (MonoType **)g_memdup (ctx.header->locals, sizeof (MonoType*) * ctx.header->num_locals);
_MEM_ALLOC (sizeof (MonoType*) * ctx.header->num_locals);
ctx.locals_verification_state = g_new0 (char, ctx.num_locals);
if (ctx.num_locals > 0 && !ctx.header->init_locals)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Method with locals variable but without init locals set"));
ctx.params = g_new (MonoType*, ctx.max_args);
_MEM_ALLOC (sizeof (MonoType*) * ctx.max_args);
if (ctx.signature->hasthis)
ctx.params [0] = method->klass->valuetype ? &method->klass->this_arg : &method->klass->byval_arg;
memcpy (ctx.params + ctx.signature->hasthis, ctx.signature->params, sizeof (MonoType *) * ctx.signature->param_count);
if (ctx.signature->is_inflated)
ctx.generic_context = generic_context = mono_method_get_context (method);
if (!generic_context && (mono_class_is_gtd (method->klass) || method->is_generic)) {
if (method->is_generic)
ctx.generic_context = generic_context = &(mono_method_get_generic_container (method)->context);
else
ctx.generic_context = generic_context = &mono_class_get_generic_container (method->klass)->context;
}
for (i = 0; i < ctx.num_locals; ++i) {
MonoType *uninflated = ctx.locals [i];
ctx.locals [i] = mono_class_inflate_generic_type_checked (ctx.locals [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.locals [i] ? ctx.locals [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.num_locals = i;
ctx.max_args = 0;
goto cleanup;
}
}
for (i = 0; i < ctx.max_args; ++i) {
MonoType *uninflated = ctx.params [i];
ctx.params [i] = mono_class_inflate_generic_type_checked (ctx.params [i], ctx.generic_context, &error);
if (!mono_error_ok (&error)) {
char *name = mono_type_full_name (ctx.params [i] ? ctx.params [i] : uninflated);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %d of type %s", i, name));
g_free (name);
mono_error_cleanup (&error);
/* we must not free (in cleanup) what was not yet allocated (but only copied) */
ctx.max_args = i;
goto cleanup;
}
}
stack_init (&ctx, &ctx.eval);
for (i = 0; i < ctx.num_locals; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.locals [i]))
break;
if (get_stack_type (ctx.locals [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.locals [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid local %i of type %s", i, name));
g_free (name);
break;
}
}
for (i = 0; i < ctx.max_args; ++i) {
if (!mono_type_is_valid_in_context (&ctx, ctx.params [i]))
break;
if (get_stack_type (ctx.params [i]) == TYPE_INV) {
char *name = mono_type_full_name (ctx.params [i]);
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid parameter %i of type %s", i, name));
g_free (name);
break;
}
}
if (!ctx.valid)
goto cleanup;
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
VERIFIER_DEBUG (printf ("clause try %x len %x filter at %x handler at %x len %x\n", clause->try_offset, clause->try_len, clause->data.filter_offset, clause->handler_offset, clause->handler_len); );
if (clause->try_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause out of bounds at 0x%04x", clause->try_offset));
if (clause->try_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->handler_offset > ctx.code_size || ADD_IS_GREATER_OR_OVF (clause->handler_offset, clause->handler_len, ctx.code_size))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause out of bounds at 0x%04x", clause->try_offset));
if (clause->handler_len <= 0)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("handler clause len <= 0 at 0x%04x", clause->try_offset));
if (clause->try_offset < clause->handler_offset && ADD_IS_GREATER_OR_OVF (clause->try_offset, clause->try_len, HANDLER_START (clause)))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("try block (at 0x%04x) includes handler block (at 0x%04x)", clause->try_offset, clause->handler_offset));
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
if (clause->data.filter_offset > ctx.code_size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause out of bounds at 0x%04x", clause->try_offset));
if (clause->data.filter_offset >= clause->handler_offset)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("filter clause must come before the handler clause at 0x%04x", clause->data.filter_offset));
}
for (n = i + 1; n < ctx.header->num_clauses && ctx.valid; ++n)
verify_clause_relationship (&ctx, clause, ctx.header->clauses + n);
if (!ctx.valid)
break;
ctx.code [clause->try_offset].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->try_offset + clause->try_len < ctx.code_size)
ctx.code [clause->try_offset + clause->try_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->handler_offset + clause->handler_len < ctx.code_size)
ctx.code [clause->handler_offset + clause->handler_len].flags |= IL_CODE_FLAG_WAS_TARGET;
if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) {
if (!clause->data.catch_class) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Catch clause %d with invalid type", i));
break;
}
if (!mono_type_is_valid_in_context (&ctx, &clause->data.catch_class->byval_arg))
break;
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, clause->data.catch_class);
}
else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->data.filter_offset, mono_defaults.exception_class);
init_stack_with_value_at_exception_boundary (&ctx, ctx.code + clause->handler_offset, mono_defaults.exception_class);
}
}
if (!ctx.valid)
goto cleanup;
original_bb = bb = mono_basic_block_split (method, &error, ctx.header);
if (!mono_error_ok (&error)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid branch target: %s", mono_error_get_message (&error)));
mono_error_cleanup (&error);
goto cleanup;
}
g_assert (bb);
while (ip < end && ctx.valid) {
int op_size;
ip_offset = (guint) (ip - code_start);
{
const unsigned char *ip_copy = ip;
int op;
if (ip_offset > bb->end) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block at [0x%04x] targets middle instruction at 0x%04x", bb->end, ip_offset));
goto cleanup;
}
if (ip_offset == bb->end)
bb = bb->next;
op_size = mono_opcode_value_and_size (&ip_copy, end, &op);
if (op_size == -1) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ip_offset));
goto cleanup;
}
if (ADD_IS_GREATER_OR_OVF (ip_offset, op_size, bb->end)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets middle of instruction at 0x%04x", ip_offset));
goto cleanup;
}
/*Last Instruction*/
if (ip_offset + op_size == bb->end && mono_opcode_is_prefix (op)) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or EH block targets between prefix '%s' and instruction at 0x%04x", mono_opcode_name (op), ip_offset));
goto cleanup;
}
}
ctx.ip_offset = ip_offset = (guint) (ip - code_start);
/*We need to check against fallthrou in and out of protected blocks.
* For fallout we check the once a protected block ends, if the start flag is not set.
* Likewise for fallthru in, we check if ip is the start of a protected block and start is not set
* TODO convert these checks to be done using flags and not this loop
*/
for (i = 0; i < ctx.header->num_clauses && ctx.valid; ++i) {
MonoExceptionClause *clause = ctx.header->clauses + i;
if ((clause->try_offset + clause->try_len == ip_offset) && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru off try block at 0x%04x", ip_offset));
start = 1;
}
if ((clause->handler_offset + clause->handler_len == ip_offset) && start == 0) {
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallout of handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER && clause->handler_offset == ip_offset && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("fallout of filter block at 0x%04x", ip_offset));
start = 1;
}
if (clause->handler_offset == ip_offset && start == 0) {
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("fallthru handler block at 0x%04x", ip_offset));
start = 1;
}
if (clause->try_offset == ip_offset && ctx.eval.size > 0 && start == 0) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Try to enter try block with a non-empty stack at 0x%04x", ip_offset));
start = 1;
}
}
/*This must be done after fallthru detection otherwise it won't happen.*/
if (bb->dead) {
/*FIXME remove this once we move all bad branch checking code to use BB only*/
ctx.code [ip_offset].flags |= IL_CODE_FLAG_SEEN;
ip += op_size;
continue;
}
if (!ctx.valid)
break;
if (need_merge) {
VERIFIER_DEBUG ( printf ("extra merge needed! 0x%04x \n", ctx.target); );
merge_stacks (&ctx, &ctx.eval, &ctx.code [ctx.target], FALSE, TRUE);
need_merge = 0;
}
merge_stacks (&ctx, &ctx.eval, &ctx.code[ip_offset], start, FALSE);
start = 0;
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
#ifdef MONO_VERIFIER_DEBUG
{
char *discode;
discode = mono_disasm_code_one (NULL, method, ip, NULL);
discode [strlen (discode) - 1] = 0; /* no \n */
g_print ("[%d] %-29s (%d)\n", ip_offset, discode, ctx.eval.size);
g_free (discode);
}
dump_stack_state (&ctx.code [ip_offset]);
dump_stack_state (&ctx.eval);
#endif
switch (*ip) {
case CEE_NOP:
case CEE_BREAK:
++ip;
break;
case CEE_LDARG_0:
case CEE_LDARG_1:
case CEE_LDARG_2:
case CEE_LDARG_3:
push_arg (&ctx, *ip - CEE_LDARG_0, FALSE);
++ip;
break;
case CEE_LDARG_S:
case CEE_LDARGA_S:
code_bounds_check (2);
push_arg (&ctx, ip [1], *ip == CEE_LDARGA_S);
ip += 2;
break;
case CEE_ADD_OVF_UN:
do_binop (&ctx, *ip, add_ovf_un_table);
++ip;
break;
case CEE_SUB_OVF_UN:
do_binop (&ctx, *ip, sub_ovf_un_table);
++ip;
break;
case CEE_ADD_OVF:
case CEE_SUB_OVF:
case CEE_MUL_OVF:
case CEE_MUL_OVF_UN:
do_binop (&ctx, *ip, bin_ovf_table);
++ip;
break;
case CEE_ADD:
do_binop (&ctx, *ip, add_table);
++ip;
break;
case CEE_SUB:
do_binop (&ctx, *ip, sub_table);
++ip;
break;
case CEE_MUL:
case CEE_DIV:
case CEE_REM:
do_binop (&ctx, *ip, bin_op_table);
++ip;
break;
case CEE_AND:
case CEE_DIV_UN:
case CEE_OR:
case CEE_REM_UN:
case CEE_XOR:
do_binop (&ctx, *ip, int_bin_op_table);
++ip;
break;
case CEE_SHL:
case CEE_SHR:
case CEE_SHR_UN:
do_binop (&ctx, *ip, shift_op_table);
++ip;
break;
case CEE_POP:
if (!check_underflow (&ctx, 1))
break;
stack_pop_safe (&ctx);
++ip;
break;
case CEE_RET:
do_ret (&ctx);
++ip;
start = 1;
break;
case CEE_LDLOC_0:
case CEE_LDLOC_1:
case CEE_LDLOC_2:
case CEE_LDLOC_3:
/*TODO support definite assignment verification? */
push_local (&ctx, *ip - CEE_LDLOC_0, FALSE);
++ip;
break;
case CEE_STLOC_0:
case CEE_STLOC_1:
case CEE_STLOC_2:
case CEE_STLOC_3:
store_local (&ctx, *ip - CEE_STLOC_0);
++ip;
break;
case CEE_STLOC_S:
code_bounds_check (2);
store_local (&ctx, ip [1]);
ip += 2;
break;
case CEE_STARG_S:
code_bounds_check (2);
store_arg (&ctx, ip [1]);
ip += 2;
break;
case CEE_LDC_I4_M1:
case CEE_LDC_I4_0:
case CEE_LDC_I4_1:
case CEE_LDC_I4_2:
case CEE_LDC_I4_3:
case CEE_LDC_I4_4:
case CEE_LDC_I4_5:
case CEE_LDC_I4_6:
case CEE_LDC_I4_7:
case CEE_LDC_I4_8:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
++ip;
break;
case CEE_LDC_I4_S:
code_bounds_check (2);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 2;
break;
case CEE_LDC_I4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I4, &mono_defaults.int32_class->byval_arg);
ip += 5;
break;
case CEE_LDC_I8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx,TYPE_I8, &mono_defaults.int64_class->byval_arg);
ip += 9;
break;
case CEE_LDC_R4:
code_bounds_check (5);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 5;
break;
case CEE_LDC_R8:
code_bounds_check (9);
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_R8, &mono_defaults.double_class->byval_arg);
ip += 9;
break;
case CEE_LDNULL:
if (check_overflow (&ctx))
stack_push_val (&ctx, TYPE_COMPLEX | NULL_LITERAL_MASK, &mono_defaults.object_class->byval_arg);
++ip;
break;
case CEE_BEQ_S:
case CEE_BNE_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_eq_op);
ip += 2;
need_merge = 1;
break;
case CEE_BGE_S:
case CEE_BGT_S:
case CEE_BLE_S:
case CEE_BLT_S:
case CEE_BGE_UN_S:
case CEE_BGT_UN_S:
case CEE_BLE_UN_S:
case CEE_BLT_UN_S:
code_bounds_check (2);
do_branch_op (&ctx, (signed char)ip [1] + 2, cmp_br_op);
ip += 2;
need_merge = 1;
break;
case CEE_BEQ:
case CEE_BNE_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_eq_op);
ip += 5;
need_merge = 1;
break;
case CEE_BGE:
case CEE_BGT:
case CEE_BLE:
case CEE_BLT:
case CEE_BGE_UN:
case CEE_BGT_UN:
case CEE_BLE_UN:
case CEE_BLT_UN:
code_bounds_check (5);
do_branch_op (&ctx, (gint32)read32 (ip + 1) + 5, cmp_br_op);
ip += 5;
need_merge = 1;
break;
case CEE_LDLOC_S:
case CEE_LDLOCA_S:
code_bounds_check (2);
push_local (&ctx, ip[1], *ip == CEE_LDLOCA_S);
ip += 2;
break;
case CEE_UNUSED99:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_DUP: {
ILStackDesc *top;
if (!check_underflow (&ctx, 1))
break;
if (!check_overflow (&ctx))
break;
top = stack_push (&ctx);
copy_stack_value (top, stack_peek (&ctx, 1));
++ip;
break;
}
case CEE_JMP:
code_bounds_check (5);
if (ctx.eval.size)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Eval stack must be empty in jmp at 0x%04x", ip_offset));
/* token = read32 (ip + 1); */
if (in_any_block (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("jmp cannot escape exception blocks at 0x%04x", ip_offset));
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction jmp is not verifiable at 0x%04x", ctx.ip_offset));
/*
* FIXME: check signature, retval, arguments etc.
*/
ip += 5;
break;
case CEE_CALL:
case CEE_CALLVIRT:
code_bounds_check (5);
do_invoke_method (&ctx, read32 (ip + 1), *ip == CEE_CALLVIRT);
ip += 5;
break;
case CEE_CALLI:
code_bounds_check (5);
/* token = read32 (ip + 1); */
/*
* FIXME: check signature, retval, arguments etc.
* FIXME: check requirements for tail call
*/
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Intruction calli is not verifiable at 0x%04x", ctx.ip_offset));
ip += 5;
break;
case CEE_BR_S:
code_bounds_check (2);
do_static_branch (&ctx, (signed char)ip [1] + 2);
need_merge = 1;
ip += 2;
start = 1;
break;
case CEE_BRFALSE_S:
case CEE_BRTRUE_S:
code_bounds_check (2);
do_boolean_branch_op (&ctx, (signed char)ip [1] + 2);
ip += 2;
need_merge = 1;
break;
case CEE_BR:
code_bounds_check (5);
do_static_branch (&ctx, (gint32)read32 (ip + 1) + 5);
need_merge = 1;
ip += 5;
start = 1;
break;
case CEE_BRFALSE:
case CEE_BRTRUE:
code_bounds_check (5);
do_boolean_branch_op (&ctx, (gint32)read32 (ip + 1) + 5);
ip += 5;
need_merge = 1;
break;
case CEE_SWITCH: {
guint32 entries;
code_bounds_check (5);
entries = read32 (ip + 1);
if (entries > 0xFFFFFFFFU / sizeof (guint32))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Too many switch entries %x at 0x%04x", entries, ctx.ip_offset));
ip += 5;
code_bounds_check (sizeof (guint32) * entries);
do_switch (&ctx, entries, ip);
ip += sizeof (guint32) * entries;
break;
}
case CEE_LDIND_I1:
case CEE_LDIND_U1:
case CEE_LDIND_I2:
case CEE_LDIND_U2:
case CEE_LDIND_I4:
case CEE_LDIND_U4:
case CEE_LDIND_I8:
case CEE_LDIND_I:
case CEE_LDIND_R4:
case CEE_LDIND_R8:
case CEE_LDIND_REF:
do_load_indirect (&ctx, *ip);
++ip;
break;
case CEE_STIND_REF:
case CEE_STIND_I1:
case CEE_STIND_I2:
case CEE_STIND_I4:
case CEE_STIND_I8:
case CEE_STIND_R4:
case CEE_STIND_R8:
case CEE_STIND_I:
do_store_indirect (&ctx, *ip);
++ip;
break;
case CEE_NOT:
case CEE_NEG:
do_unary_math_op (&ctx, *ip);
++ip;
break;
case CEE_CONV_I1:
case CEE_CONV_I2:
case CEE_CONV_I4:
case CEE_CONV_U1:
case CEE_CONV_U2:
case CEE_CONV_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_I8:
case CEE_CONV_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_R4:
case CEE_CONV_R8:
case CEE_CONV_R_UN:
do_conversion (&ctx, TYPE_R8);
++ip;
break;
case CEE_CONV_I:
case CEE_CONV_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_CPOBJ:
code_bounds_check (5);
do_cpobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDOBJ:
code_bounds_check (5);
do_ldobj_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDSTR:
code_bounds_check (5);
do_ldstr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWOBJ:
code_bounds_check (5);
do_newobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CASTCLASS:
case CEE_ISINST:
code_bounds_check (5);
do_cast (&ctx, read32 (ip + 1), *ip == CEE_CASTCLASS ? "castclass" : "isinst");
ip += 5;
break;
case CEE_UNUSED58:
case CEE_UNUSED1:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_UNBOX:
code_bounds_check (5);
do_unbox_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_THROW:
do_throw (&ctx);
start = 1;
++ip;
break;
case CEE_LDFLD:
case CEE_LDFLDA:
code_bounds_check (5);
do_push_field (&ctx, read32 (ip + 1), *ip == CEE_LDFLDA);
ip += 5;
break;
case CEE_LDSFLD:
case CEE_LDSFLDA:
code_bounds_check (5);
do_push_static_field (&ctx, read32 (ip + 1), *ip == CEE_LDSFLDA);
ip += 5;
break;
case CEE_STFLD:
code_bounds_check (5);
do_store_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STSFLD:
code_bounds_check (5);
do_store_static_field (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_STOBJ:
code_bounds_check (5);
do_stobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1_UN:
case CEE_CONV_OVF_I2_UN:
case CEE_CONV_OVF_I4_UN:
case CEE_CONV_OVF_U1_UN:
case CEE_CONV_OVF_U2_UN:
case CEE_CONV_OVF_U4_UN:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8_UN:
case CEE_CONV_OVF_U8_UN:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I_UN:
case CEE_CONV_OVF_U_UN:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_BOX:
code_bounds_check (5);
do_box_value (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_NEWARR:
code_bounds_check (5);
do_newarr (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDLEN:
do_ldlen (&ctx);
++ip;
break;
case CEE_LDELEMA:
code_bounds_check (5);
do_ldelema (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDELEM_I1:
case CEE_LDELEM_U1:
case CEE_LDELEM_I2:
case CEE_LDELEM_U2:
case CEE_LDELEM_I4:
case CEE_LDELEM_U4:
case CEE_LDELEM_I8:
case CEE_LDELEM_I:
case CEE_LDELEM_R4:
case CEE_LDELEM_R8:
case CEE_LDELEM_REF:
do_ldelem (&ctx, *ip, 0);
++ip;
break;
case CEE_STELEM_I:
case CEE_STELEM_I1:
case CEE_STELEM_I2:
case CEE_STELEM_I4:
case CEE_STELEM_I8:
case CEE_STELEM_R4:
case CEE_STELEM_R8:
case CEE_STELEM_REF:
do_stelem (&ctx, *ip, 0);
++ip;
break;
case CEE_LDELEM:
code_bounds_check (5);
do_ldelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_STELEM:
code_bounds_check (5);
do_stelem (&ctx, *ip, read32 (ip + 1));
ip += 5;
break;
case CEE_UNBOX_ANY:
code_bounds_check (5);
do_unbox_any (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONV_OVF_I1:
case CEE_CONV_OVF_U1:
case CEE_CONV_OVF_I2:
case CEE_CONV_OVF_U2:
case CEE_CONV_OVF_I4:
case CEE_CONV_OVF_U4:
do_conversion (&ctx, TYPE_I4);
++ip;
break;
case CEE_CONV_OVF_I8:
case CEE_CONV_OVF_U8:
do_conversion (&ctx, TYPE_I8);
++ip;
break;
case CEE_CONV_OVF_I:
case CEE_CONV_OVF_U:
do_conversion (&ctx, TYPE_NATIVE_INT);
++ip;
break;
case CEE_REFANYVAL:
code_bounds_check (5);
do_refanyval (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CKFINITE:
do_ckfinite (&ctx);
++ip;
break;
case CEE_MKREFANY:
code_bounds_check (5);
do_mkrefany (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_LDTOKEN:
code_bounds_check (5);
do_load_token (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_ENDFINALLY:
if (!is_correct_endfinally (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("endfinally must be used inside a finally/fault handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_LEAVE:
code_bounds_check (5);
do_leave (&ctx, read32 (ip + 1) + 5);
ip += 5;
start = 1;
need_merge = 1;
break;
case CEE_LEAVE_S:
code_bounds_check (2);
do_leave (&ctx, (signed char)ip [1] + 2);
ip += 2;
start = 1;
need_merge = 1;
break;
case CEE_PREFIX1:
code_bounds_check (2);
++ip;
switch (*ip) {
case CEE_STLOC:
code_bounds_check (3);
store_local (&ctx, read16 (ip + 1));
ip += 3;
break;
case CEE_CEQ:
do_cmp_op (&ctx, cmp_br_eq_op, *ip);
++ip;
break;
case CEE_CGT:
case CEE_CGT_UN:
case CEE_CLT:
case CEE_CLT_UN:
do_cmp_op (&ctx, cmp_br_op, *ip);
++ip;
break;
case CEE_STARG:
code_bounds_check (3);
store_arg (&ctx, read16 (ip + 1) );
ip += 3;
break;
case CEE_ARGLIST:
if (!check_overflow (&ctx))
break;
if (ctx.signature->call_convention != MONO_CALL_VARARG)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Cannot use arglist on method without VARGARG calling convention at 0x%04x", ctx.ip_offset));
set_stack_value (&ctx, stack_push (&ctx), &mono_defaults.argumenthandle_class->byval_arg, FALSE);
++ip;
break;
case CEE_LDFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), FALSE);
ip += 5;
break;
case CEE_LDVIRTFTN:
code_bounds_check (5);
do_load_function_ptr (&ctx, read32 (ip + 1), TRUE);
ip += 5;
break;
case CEE_LDARG:
case CEE_LDARGA:
code_bounds_check (3);
push_arg (&ctx, read16 (ip + 1), *ip == CEE_LDARGA);
ip += 3;
break;
case CEE_LDLOC:
case CEE_LDLOCA:
code_bounds_check (3);
push_local (&ctx, read16 (ip + 1), *ip == CEE_LDLOCA);
ip += 3;
break;
case CEE_LOCALLOC:
do_localloc (&ctx);
++ip;
break;
case CEE_UNUSED56:
case CEE_UNUSED57:
case CEE_UNUSED70:
case CEE_UNUSED:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Use of the `unused' opcode"));
++ip;
break;
case CEE_ENDFILTER:
do_endfilter (&ctx);
start = 1;
++ip;
break;
case CEE_UNALIGNED_:
code_bounds_check (2);
prefix |= PREFIX_UNALIGNED;
ip += 2;
break;
case CEE_VOLATILE_:
prefix |= PREFIX_VOLATILE;
++ip;
break;
case CEE_TAIL_:
prefix |= PREFIX_TAIL;
++ip;
if (ip < end && (*ip != CEE_CALL && *ip != CEE_CALLI && *ip != CEE_CALLVIRT))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("tail prefix must be used only with call opcodes at 0x%04x", ip_offset));
break;
case CEE_INITOBJ:
code_bounds_check (5);
do_initobj (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_CONSTRAINED_:
code_bounds_check (5);
ctx.constrained_type = get_boxable_mono_type (&ctx, read32 (ip + 1), "constrained.");
prefix |= PREFIX_CONSTRAINED;
ip += 5;
break;
case CEE_READONLY_:
prefix |= PREFIX_READONLY;
ip++;
break;
case CEE_CPBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction cpblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_INITBLK:
CLEAR_PREFIX (&ctx, PREFIX_UNALIGNED | PREFIX_VOLATILE);
if (!check_underflow (&ctx, 3))
break;
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Instruction initblk is not verifiable at 0x%04x", ctx.ip_offset));
ip++;
break;
case CEE_NO_:
ip += 2;
break;
case CEE_RETHROW:
if (!is_correct_rethrow (ctx.header, ip_offset))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("rethrow must be used inside a catch handler at 0x%04x", ctx.ip_offset));
ctx.eval.size = 0;
start = 1;
++ip;
break;
case CEE_SIZEOF:
code_bounds_check (5);
do_sizeof (&ctx, read32 (ip + 1));
ip += 5;
break;
case CEE_REFANYTYPE:
do_refanytype (&ctx);
++ip;
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction FE %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
break;
default:
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction %x at 0x%04x", *ip, ctx.ip_offset));
++ip;
}
/*TODO we can fast detect a forward branch or exception block targeting code after prefix, we should fail fast*/
if (prefix) {
if (!ctx.prefix_set) //first prefix
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
ctx.prefix_set |= prefix;
ctx.has_flags = TRUE;
prefix = 0;
} else {
if (!ctx.has_flags)
ctx.code [ctx.ip_offset].flags |= IL_CODE_FLAG_SEEN;
if (ctx.prefix_set & PREFIX_CONSTRAINED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after constrained prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_READONLY)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after readonly prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_VOLATILE)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after volatile prefix at 0x%04x", ctx.ip_offset));
if (ctx.prefix_set & PREFIX_UNALIGNED)
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Invalid instruction after unaligned prefix at 0x%04x", ctx.ip_offset));
ctx.prefix_set = prefix = 0;
ctx.has_flags = FALSE;
}
}
/*
* if ip != end we overflowed: mark as error.
*/
if ((ip != end || !start) && ctx.verifiable && !ctx.list) {
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Run ahead of method code at 0x%04x", ip_offset));
}
/*We should guard against the last decoded opcode, otherwise we might add errors that doesn't make sense.*/
for (i = 0; i < ctx.code_size && i < ip_offset; ++i) {
if (ctx.code [i].flags & IL_CODE_FLAG_WAS_TARGET) {
if (!(ctx.code [i].flags & IL_CODE_FLAG_SEEN))
ADD_VERIFY_ERROR (&ctx, g_strdup_printf ("Branch or exception block target middle of instruction at 0x%04x", i));
if (ctx.code [i].flags & IL_CODE_DELEGATE_SEQUENCE)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Branch to delegate code sequence at 0x%04x", i));
}
if ((ctx.code [i].flags & IL_CODE_LDFTN_DELEGATE_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid ldftn with virtual function in method with stdarg 0 at 0x%04x", i));
if ((ctx.code [i].flags & IL_CODE_CALL_NONFINAL_VIRTUAL) && ctx.has_this_store)
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Invalid call to a non-final virtual function in method with stdarg.0 or ldarga.0 at 0x%04x", i));
}
if (mono_method_is_constructor (ctx.method) && !ctx.super_ctor_called && !ctx.method->klass->valuetype && ctx.method->klass != mono_defaults.object_class) {
char *method_name = mono_method_full_name (ctx.method, TRUE);
char *type = mono_type_get_full_name (ctx.method->klass);
if (ctx.method->klass->parent && mono_class_has_failure (ctx.method->klass->parent))
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor due to a TypeLoadException on base type.", method_name, type));
else
CODE_NOT_VERIFIABLE (&ctx, g_strdup_printf ("Constructor %s for type %s not calling base type ctor.", method_name, type));
g_free (method_name);
g_free (type);
}
cleanup:
if (ctx.code) {
for (i = 0; i < ctx.header->code_size; ++i) {
if (ctx.code [i].stack)
g_free (ctx.code [i].stack);
}
}
for (tmp = ctx.funptrs; tmp; tmp = tmp->next)
g_free (tmp->data);
g_slist_free (ctx.funptrs);
for (tmp = ctx.exception_types; tmp; tmp = tmp->next)
mono_metadata_free_type ((MonoType *)tmp->data);
g_slist_free (ctx.exception_types);
for (i = 0; i < ctx.num_locals; ++i) {
if (ctx.locals [i])
mono_metadata_free_type (ctx.locals [i]);
}
for (i = 0; i < ctx.max_args; ++i) {
if (ctx.params [i])
mono_metadata_free_type (ctx.params [i]);
}
if (ctx.eval.stack)
g_free (ctx.eval.stack);
if (ctx.code)
g_free (ctx.code);
g_free (ctx.locals);
g_free (ctx.locals_verification_state);
g_free (ctx.params);
mono_basic_block_free (original_bb);
mono_metadata_free_mh (ctx.header);
finish_collect_stats ();
return ctx.list;
}
char*
mono_verify_corlib ()
{
/* This is a public API function so cannot be removed */
return NULL;
}
/**
* mono_verifier_is_enabled_for_method:
* \param method the method to probe
* \returns TRUE if \p method needs to be verified.
*/
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
return mono_verifier_is_enabled_for_class (method->klass) && (method->wrapper_type == MONO_WRAPPER_NONE || method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD);
}
/**
* mono_verifier_is_enabled_for_class:
* \param klass The \c MonoClass to probe
* \returns TRUE if \p klass need to be verified.
*/
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
return verify_all || (verifier_mode > MONO_VERIFIER_MODE_OFF && !(klass->image->assembly && klass->image->assembly->in_gac) && klass->image != mono_defaults.corlib);
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
return verify_all || verifier_mode > MONO_VERIFIER_MODE_OFF;
}
/*
* Dynamic methods are not considered full trust since if the user is trusted and need to
* generate unsafe code, make the method skip verification - this is a known good way to do it.
*/
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
return mono_verifier_is_class_full_trust (method->klass) && !method_is_dynamic (method);
}
/*
* Returns if @klass is under full trust or not.
*
* TODO This code doesn't take CAS into account.
*
* Under verify_all all user code must be verifiable if no security option was set
*
*/
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* under CoreCLR code is trusted if it is part of the "platform" otherwise all code inside the GAC is trusted */
gboolean trusted_location = !mono_security_core_clr_enabled () ?
(klass->image->assembly && klass->image->assembly->in_gac) : mono_security_core_clr_is_platform_image (klass->image);
if (verify_all && verifier_mode == MONO_VERIFIER_MODE_OFF)
return trusted_location || klass->image == mono_defaults.corlib;
return verifier_mode < MONO_VERIFIER_MODE_VERIFIABLE || trusted_location || klass->image == mono_defaults.corlib;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility, gboolean is_fulltrust)
{
return mono_method_verify (method,
(verifier_mode != MONO_VERIFIER_MODE_STRICT ? MONO_VERIFY_NON_STRICT: 0)
| (!is_fulltrust && !mono_verifier_is_method_full_trust (method) ? MONO_VERIFY_FAIL_FAST : 0)
| (skip_visibility ? MONO_VERIFY_SKIP_VISIBILITY : 0));
}
static int
get_field_end (MonoClassField *field)
{
int align;
int size = mono_type_size (field->type, &align);
if (size == 0)
size = 4; /*FIXME Is this a safe bet?*/
return size + field->offset;
}
static gboolean
verify_class_for_overlapping_reference_fields (MonoClass *klass)
{
int i = 0, j;
gpointer iter = NULL;
MonoClassField *field;
gboolean is_fulltrust = mono_verifier_is_class_full_trust (klass);
/*We can't skip types with !has_references since this is calculated after we have run.*/
if (!mono_class_is_explicit_layout (klass))
return TRUE;
/*We must check for stuff overlapping reference fields.
The outer loop uses mono_class_get_fields to ensure that MonoClass:fields get inited.
*/
while ((field = mono_class_get_fields (klass, &iter))) {
int fieldEnd = get_field_end (field);
gboolean is_valuetype = !MONO_TYPE_IS_REFERENCE (field->type);
++i;
if (mono_field_is_deleted (field) || (field->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
int fcount = mono_class_get_field_count (klass);
for (j = i; j < fcount; ++j) {
MonoClassField *other = &klass->fields [j];
int otherEnd = get_field_end (other);
if (mono_field_is_deleted (other) || (is_valuetype && !MONO_TYPE_IS_REFERENCE (other->type)) || (other->type->attrs & FIELD_ATTRIBUTE_STATIC))
continue;
if (!is_valuetype && MONO_TYPE_IS_REFERENCE (other->type) && field->offset == other->offset && is_fulltrust)
continue;
if ((otherEnd > field->offset && otherEnd <= fieldEnd) || (other->offset >= field->offset && other->offset < fieldEnd))
return FALSE;
}
}
return TRUE;
}
static guint
field_hash (gconstpointer key)
{
const MonoClassField *field = (const MonoClassField *)key;
return g_str_hash (field->name) ^ mono_metadata_type_hash (field->type); /**/
}
static gboolean
field_equals (gconstpointer _a, gconstpointer _b)
{
const MonoClassField *a = (const MonoClassField *)_a;
const MonoClassField *b = (const MonoClassField *)_b;
return !strcmp (a->name, b->name) && mono_metadata_type_equal (a->type, b->type);
}
static gboolean
verify_class_fields (MonoClass *klass)
{
gpointer iter = NULL;
MonoClassField *field;
MonoGenericContext *context = mono_class_get_context (klass);
GHashTable *unique_fields = g_hash_table_new_full (&field_hash, &field_equals, NULL, NULL);
if (mono_class_is_gtd (klass))
context = &mono_class_get_generic_container (klass)->context;
while ((field = mono_class_get_fields (klass, &iter)) != NULL) {
if (!mono_type_is_valid_type_in_context (field->type, context)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
if (g_hash_table_lookup (unique_fields, field)) {
g_hash_table_destroy (unique_fields);
return FALSE;
}
g_hash_table_insert (unique_fields, field, field);
}
g_hash_table_destroy (unique_fields);
return TRUE;
}
static gboolean
verify_interfaces (MonoClass *klass)
{
int i;
for (i = 0; i < klass->interface_count; ++i) {
MonoClass *iface = klass->interfaces [i];
if (!mono_class_get_flags (iface))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout_with_target (MonoClass *klass, MonoClass *target_class)
{
int type;
gpointer iter = NULL;
MonoClassField *field;
MonoClass *field_class;
if (!klass->valuetype)
return TRUE;
type = klass->byval_arg.type;
/*primitive type fields are not properly decoded*/
if ((type >= MONO_TYPE_BOOLEAN && type <= MONO_TYPE_R8) || (type >= MONO_TYPE_I && type <= MONO_TYPE_U))
return TRUE;
while ((field = mono_class_get_fields (klass, &iter)) != NULL) {
if (!field->type)
return FALSE;
if (field->type->attrs & (FIELD_ATTRIBUTE_STATIC | FIELD_ATTRIBUTE_HAS_FIELD_RVA))
continue;
field_class = mono_class_get_generic_type_definition (mono_class_from_mono_type (field->type));
if (field_class == target_class || klass == field_class || !verify_valuetype_layout_with_target (field_class, target_class))
return FALSE;
}
return TRUE;
}
static gboolean
verify_valuetype_layout (MonoClass *klass)
{
gboolean res;
res = verify_valuetype_layout_with_target (klass, klass);
return res;
}
static gboolean
recursive_mark_constraint_args (MonoBitSet *used_args, MonoGenericContainer *gc, MonoType *type)
{
int idx;
MonoClass **constraints;
MonoGenericParamInfo *param_info;
g_assert (mono_type_is_generic_argument (type));
idx = mono_type_get_generic_param_num (type);
if (mono_bitset_test_fast (used_args, idx))
return FALSE;
mono_bitset_set_fast (used_args, idx);
param_info = mono_generic_container_get_param_info (gc, idx);
if (!param_info->constraints)
return TRUE;
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
return FALSE;
}
return TRUE;
}
static gboolean
verify_generic_parameters (MonoClass *klass)
{
int i;
MonoGenericContainer *gc = mono_class_get_generic_container (klass);
MonoBitSet *used_args = mono_bitset_new (gc->type_argc, 0);
for (i = 0; i < gc->type_argc; ++i) {
MonoGenericParamInfo *param_info = mono_generic_container_get_param_info (gc, i);
MonoClass **constraints;
if (!param_info->constraints)
continue;
mono_bitset_clear_all (used_args);
mono_bitset_set_fast (used_args, i);
for (constraints = param_info->constraints; *constraints; ++constraints) {
MonoClass *ctr = *constraints;
MonoType *constraint_type = &ctr->byval_arg;
if (!mono_class_can_access_class (klass, ctr))
goto fail;
if (!mono_type_is_valid_type_in_context (constraint_type, &gc->context))
goto fail;
if (mono_type_is_generic_argument (constraint_type) && !recursive_mark_constraint_args (used_args, gc, constraint_type))
goto fail;
if (mono_class_is_ginst (ctr) && !mono_class_is_valid_generic_instantiation (NULL, ctr))
goto fail;
}
}
mono_bitset_free (used_args);
return TRUE;
fail:
mono_bitset_free (used_args);
return FALSE;
}
/*
* Check if the class is verifiable.
*
* Right now there are no conditions that make a class a valid but not verifiable. Both overlapping reference
* field and invalid generic instantiation are fatal errors.
*
* This method must be safe to be called from mono_class_init and all code must be carefull about that.
*
*/
gboolean
mono_verifier_verify_class (MonoClass *klass)
{
/*Neither <Module>, object or ifaces have parent.*/
if (!klass->parent &&
klass != mono_defaults.object_class &&
!MONO_CLASS_IS_INTERFACE (klass) &&
(!image_is_dynamic (klass->image) && klass->type_token != 0x2000001)) /*<Module> is the first type in the assembly*/
return FALSE;
if (klass->parent) {
if (MONO_CLASS_IS_INTERFACE (klass->parent))
return FALSE;
if (!mono_class_is_ginst (klass) && mono_class_is_gtd (klass->parent))
return FALSE;
if (mono_class_is_ginst (klass->parent) && !mono_class_is_ginst (klass)) {
MonoGenericContext *context = mono_class_get_context (klass);
if (mono_class_is_gtd (klass))
context = &mono_class_get_generic_container (klass)->context;
if (!mono_type_is_valid_type_in_context (&klass->parent->byval_arg, context))
return FALSE;
}
}
if (mono_class_is_gtd (klass) && (mono_class_is_explicit_layout (klass)))
return FALSE;
if (mono_class_is_gtd (klass) && !verify_generic_parameters (klass))
return FALSE;
if (!verify_class_for_overlapping_reference_fields (klass))
return FALSE;
if (mono_class_is_ginst (klass) && !mono_class_is_valid_generic_instantiation (NULL, klass))
return FALSE;
if (!mono_class_is_ginst (klass) && !verify_class_fields (klass))
return FALSE;
if (klass->valuetype && !verify_valuetype_layout (klass))
return FALSE;
if (!verify_interfaces (klass))
return FALSE;
return TRUE;
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *klass)
{
return mono_class_is_valid_generic_instantiation (NULL, klass);
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
if (!method->is_inflated)
return TRUE;
return mono_method_is_valid_generic_instantiation (NULL, method);
}
#else
gboolean
mono_verifier_verify_class (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return TRUE;
}
GSList*
mono_method_verify_with_current_settings (MonoMethod *method, gboolean skip_visibility, gboolean is_fulltrust)
{
/* The verifier was disabled at compile time */
return NULL;
}
gboolean
mono_verifier_is_class_full_trust (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_method_full_trust (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return TRUE;
}
gboolean
mono_verifier_is_enabled_for_image (MonoImage *image)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_class (MonoClass *klass)
{
/* The verifier was disabled at compile time */
return FALSE;
}
gboolean
mono_verifier_is_enabled_for_method (MonoMethod *method)
{
/* The verifier was disabled at compile time */
return FALSE;
}
GSList*
mono_method_verify (MonoMethod *method, int level)
{
/* The verifier was disabled at compile time */
return NULL;
}
void
mono_free_verify_list (GSList *list)
{
/* The verifier was disabled at compile time */
/* will always be null if verifier is disabled */
}
gboolean
mono_verifier_class_is_valid_generic_instantiation (MonoClass *klass)
{
return TRUE;
}
gboolean
mono_verifier_is_method_valid_generic_instantiation (MonoMethod *method)
{
return TRUE;
}
#endif
|
091e6dee6b0a547108d1d50ed48f620553c6f521
|
2d5743a0cc3b0ca82856d12e5576949868630031
|
/libcperciva/datastruct/elasticqueue.c
|
ac4c3e6e49dbf3f02ace156b91e94b6a4ee84775
|
[
"BSD-2-Clause"
] |
permissive
|
Tarsnap/kivaloo
|
20dfd70438375c7b8f8ea00a928b87c9299ae8be
|
1b4fffe65e8bdc789cb47a6191b4df33613a98e0
|
refs/heads/master
| 2023-09-03T01:26:01.625376
| 2023-08-26T18:52:14
| 2023-08-26T18:52:14
| 36,057,493
| 207
| 22
|
NOASSERTION
| 2023-08-29T18:49:29
| 2015-05-22T07:05:37
|
C
|
UTF-8
|
C
| false
| false
| 3,463
|
c
|
elasticqueue.c
|
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "elasticarray.h"
#include "elasticqueue.h"
struct elasticqueue {
struct elasticarray * EA;
size_t offset;
size_t len;
size_t reclen;
};
/**
* elasticqueue_init(reclen):
* Create and return an empty elastic queue of ${reclen}-byte records.
* The value ${reclen} must be positive.
*/
struct elasticqueue *
elasticqueue_init(size_t reclen)
{
struct elasticqueue * EQ;
/* Sanity check. */
assert(reclen > 0);
/* Allocate structure. */
if ((EQ = malloc(sizeof(struct elasticqueue))) == NULL)
goto err0;
EQ->reclen = reclen;
/* Create (empty) elastic array. */
if ((EQ->EA = elasticarray_init(0, EQ->reclen)) == NULL)
goto err1;
/* The queue is empty so far. */
EQ->offset = EQ->len = 0;
/* Success! */
return (EQ);
err1:
free(EQ);
err0:
/* Failure! */
return (NULL);
}
/**
* elasticqueue_add(EQ, rec):
* Add ${rec} to the end of the elastic queue ${EQ}.
*/
int
elasticqueue_add(struct elasticqueue * EQ, const void * rec)
{
/* Add the record to the end of the elastic array. */
if (elasticarray_append(EQ->EA, rec, 1, EQ->reclen))
goto err0;
/* The queue just gained a record. */
EQ->len += 1;
/* Success! */
return (0);
err0:
/* Failure! */
return (-1);
}
/**
* elasticqueue_delete(EQ):
* Delete the record at the front of the elastic queue ${EQ}. If the queue
* is empty, this function will have no effect.
*
* As an exception to the normal rule, an elastic queue may use more memory
* than the standard bound immediately following an elasticqueue_delete() call;
* but only if realloc(3) failed to shrink a memory allocation.
*/
void
elasticqueue_delete(struct elasticqueue * EQ)
{
size_t i;
void * oldpos;
void * newpos;
/* Return immediately if the queue is empty. */
if (EQ->len == 0)
return;
/* Adjust pointers to remove the record from the logical queue. */
EQ->offset += 1;
EQ->len -= 1;
/* Should we move everything to the front of the array? */
if (EQ->offset > EQ->len) {
/* Move records. */
for (i = 0; i < EQ->len; i++) {
newpos = elasticarray_get(EQ->EA, i, EQ->reclen);
oldpos = elasticarray_get(EQ->EA, i + EQ->offset,
EQ->reclen);
memcpy(newpos, oldpos, EQ->reclen);
}
/* Remove the unused space at the end. */
elasticarray_shrink(EQ->EA, EQ->offset, EQ->reclen);
/* And remember that everything is now at the front. */
EQ->offset = 0;
}
}
/**
* elasticqueue_getlen(EQ):
* Return the length of the elastic queue ${EQ}.
*/
size_t
elasticqueue_getlen(const struct elasticqueue * EQ)
{
return (EQ->len);
}
/**
* elasticqueue_get(EQ, pos):
* Return a pointer to the element in position ${pos} of the elastic queue
* ${EQ}, where 0 is the head of the queue and elasticqueue_getlen(${EQ}) - 1
* is the tail. For values of ${pos} beyond the end of the queue, NULL will
* be returned.
*/
void *
elasticqueue_get(struct elasticqueue * EQ, size_t pos)
{
/* Return NULL for out-of-bounds requests. */
if (pos >= EQ->len)
return (NULL);
/* Return a pointer to the record. */
return (elasticarray_get(EQ->EA, pos + EQ->offset, EQ->reclen));
}
/**
* elasticqueue_free(EQ):
* Free the elastic queue ${EQ}.
*/
void
elasticqueue_free(struct elasticqueue * EQ)
{
/* Behave consistently with free(NULL). */
if (EQ == NULL)
return;
/* Free the underlying elastic array. */
elasticarray_free(EQ->EA);
/* Free the elastic queue structure. */
free(EQ);
}
|
8bddee27969c6f081fd6ae9684ef1f543903b128
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/tool/decode/x86opinfo.c
|
4e91453faab2491689c4b993d04d3269556934de
|
[
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 7,030
|
c
|
x86opinfo.c
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ 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. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/errno.h"
#include "libc/intrin/bits.h"
#include "libc/macros.internal.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/stdio.h"
#include "libc/str/str.h"
#include "libc/str/tab.internal.h"
#include "libc/sysv/consts/ex.h"
#include "libc/sysv/consts/exit.h"
#include "third_party/getopt/getopt.internal.h"
#include "third_party/xed/x86.h"
#include "tool/decode/lib/idname.h"
#include "tool/decode/lib/xederrors.h"
const struct IdName kXedModeNames[] = {
{XED_MACHINE_MODE_LONG_64, "long"},
{XED_MACHINE_MODE_LONG_COMPAT_32, "long32"},
{XED_MACHINE_MODE_LONG_COMPAT_16, "long16"},
{XED_MACHINE_MODE_LEGACY_32, "legacy"},
{XED_MACHINE_MODE_LEGACY_16, "legacy16"},
{XED_MACHINE_MODE_REAL, "real"},
{XED_MACHINE_MODE_UNREAL, "unreal"},
};
int g_mode;
struct XedDecodedInst g_xedd;
wontreturn void ShowUsage(int rc, FILE *f) {
size_t i;
fputs("Usage: ", f);
fputs(program_invocation_name, f);
fputs(" [-rl] [-m MODE] HEX\n MODE ∊ {", f);
fputs(kXedModeNames[0].name, f);
for (i = 1; i < ARRAYLEN(kXedModeNames); ++i) {
fputc(',', f);
fputs(kXedModeNames[i].name, f);
}
fputs("}\n", f);
exit(rc);
}
void SetMachineMode(const char *s) {
size_t i;
for (i = 0; i < ARRAYLEN(kXedModeNames); ++i) {
if (strcasecmp(s, kXedModeNames[i].name) == 0) {
g_mode = kXedModeNames[i].id;
return;
}
}
fputs("error: bad mode\n", stderr);
ShowUsage(EXIT_FAILURE, stderr);
}
void GetOpts(int argc, char *argv[]) {
int opt;
g_mode = XED_MACHINE_MODE_LONG_64;
while ((opt = getopt(argc, argv, "?hrlm:")) != -1) {
switch (opt) {
case 'r':
g_mode = XED_MACHINE_MODE_REAL;
break;
case 'l':
g_mode = XED_MACHINE_MODE_LEGACY_32;
break;
case 'm':
SetMachineMode(optarg);
break;
case '?':
case 'h':
ShowUsage(EXIT_SUCCESS, stdout);
default:
ShowUsage(EX_USAGE, stderr);
}
}
}
void CheckHex(const char *s) {
size_t i, n;
if ((n = strlen(s)) % 2 == 1) {
ShowUsage(EX_DATAERR, stderr);
}
for (i = 0; i < n; ++i) {
if (!isxdigit(s[i + 0])) {
ShowUsage(EX_DATAERR, stderr);
}
}
}
void ShowField(const char *name, uint64_t value) {
if (value) {
printf("/\t%-20s = %#lx\n", name, value);
}
}
void ShowField2(const char *name, uint64_t value, bool cond) {
if (value || cond) {
printf("/\t%-20s = %#lx\n", name, value);
}
}
void ShowOffset(const char *name, uint64_t off) {
printf("/\t%-20s = %#lx\n", name, off);
}
int main(int argc, char *argv[]) {
int err;
size_t i, j, k;
uint8_t buf[XED_MAX_INSTRUCTION_BYTES];
GetOpts(argc, argv);
for (k = 0, i = optind; i < argc; ++i) {
CheckHex(argv[i]);
for (j = 0; argv[i][j]; j += 2) {
if (++k > XED_MAX_INSTRUCTION_BYTES) {
ShowUsage(EX_DATAERR, stderr);
}
buf[k - 1] = kHexToInt[argv[i][j + 0] & 255] << 4 |
kHexToInt[argv[i][j + 1] & 255];
}
}
xed_decoded_inst_zero_set_mode(&g_xedd, g_mode);
if ((err = xed_instruction_length_decode(&g_xedd, buf, k)) !=
XED_ERROR_NONE) {
fputs("XED_ERROR_", stderr);
fputs(findnamebyid(kXedErrorIdNames, err), stderr);
fputc('\n', stderr);
exit(EXIT_FAILURE);
}
#define SHOWOP(F) ShowField(#F, g_xedd.op.F)
#define SHOWOP2(F, C) ShowField2(#F, g_xedd.op.F, C)
printf("/\t%-20s = %d\n", "length", g_xedd.length);
SHOWOP(error);
SHOWOP(lock);
SHOWOP(osz);
SHOWOP(asz);
SHOWOP(rep);
SHOWOP(rex);
SHOWOP(rexb);
SHOWOP(rexr);
SHOWOP(rexrr);
SHOWOP(rexw);
SHOWOP(rexx);
SHOWOP(map);
SHOWOP(opcode);
if (g_xedd.op.has_modrm) {
printf("\n");
printf("/\t%-20s = 0b%02hhb (%d)\n", "mod", g_xedd.op.mod, g_xedd.op.mod);
printf("/\t%-20s = 0b%03hhb (%d)\n", "reg", g_xedd.op.reg, g_xedd.op.reg);
printf("/\t%-20s = 0b%03hhb (%d)\n", "rm", g_xedd.op.rm, g_xedd.op.rm);
printf("\n");
}
if (g_xedd.op.has_sib) {
printf("/\t%-20s = 0b%02hhb (%d)\n", "scale", xed_sib_scale(g_xedd.op.sib),
xed_sib_scale(g_xedd.op.sib));
printf("/\t%-20s = 0b%03hhb (%d)\n", "index", xed_sib_index(g_xedd.op.sib),
xed_sib_index(g_xedd.op.sib));
printf("/\t%-20s = 0b%03hhb (%d)\n", "base", xed_sib_base(g_xedd.op.sib),
xed_sib_base(g_xedd.op.sib));
printf("\n");
}
SHOWOP2(disp, !!g_xedd.op.pos_disp);
SHOWOP2(uimm0, !!g_xedd.op.pos_imm);
SHOWOP2(uimm1, !!g_xedd.op.pos_imm1);
SHOWOP(mode);
SHOWOP(amd3dnow);
SHOWOP(bcrc);
SHOWOP(disp_width);
SHOWOP(hint);
SHOWOP(ild_f2);
SHOWOP(ild_f3);
SHOWOP(imm1_bytes);
SHOWOP(imm_width);
SHOWOP(imm_signed);
SHOWOP(llrc);
SHOWOP(mask);
SHOWOP(max_bytes);
SHOWOP(mode_first_prefix);
SHOWOP(nprefixes);
SHOWOP(nrexes);
SHOWOP(nseg_prefixes);
SHOWOP(out_of_bytes);
SHOWOP(pos_disp);
SHOWOP(pos_imm);
SHOWOP(pos_imm1);
SHOWOP(pos_modrm);
SHOWOP(pos_opcode);
SHOWOP(pos_sib);
SHOWOP(realmode);
SHOWOP(seg_ovd);
SHOWOP(srm);
SHOWOP(ubit);
SHOWOP(vex_prefix);
SHOWOP(vexdest210);
SHOWOP(vexdest3);
SHOWOP(vexdest4);
SHOWOP(vexvalid);
SHOWOP(vl);
SHOWOP(zeroing);
return 0;
}
|
73f1c1f1b25b97c521d6ed289666d17d256076c4
|
9de0cec678bc4a3bec2b4adabef9f39ff5b4afac
|
/PWG/HMTF/TriggerStudies/analysis.C
|
f3e77281169decde51934371c328608d6cb2ee88
|
[] |
permissive
|
alisw/AliPhysics
|
91bf1bd01ab2af656a25ff10b25e618a63667d3e
|
5df28b2b415e78e81273b0d9bf5c1b99feda3348
|
refs/heads/master
| 2023-08-31T20:41:44.927176
| 2023-08-31T14:51:12
| 2023-08-31T14:51:12
| 61,661,378
| 129
| 1,150
|
BSD-3-Clause
| 2023-09-14T18:48:45
| 2016-06-21T19:31:29
|
C++
|
UTF-8
|
C
| false
| false
| 25,804
|
c
|
analysis.C
|
#include "TPad.h"
#include "TFile.h"
#include "TStyle.h"
#include "TList.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TH1D.h"
#include "TH2D.h"
#include "TH3D.h"
#include "TObjString.h"
#include "TBits.h"
#include "TLine.h"
#include "TChain.h"
#ifndef __CINT__
#include "AliTriggerBCMask.h"
#include "AliAnalysisTriggerScalers.h"
#endif
#include "TMath.h"
//enum triggerAliases {kINT=0,kSH1,kSH2,kVHM,kVHMNOPF,kVHMSPD1,kSH2NOPF,kSH2SPD1,kSH1NOPF,NTRIGGERS};
enum triggerAliases {kINT=0,kSH1,kSH2,kVHM,NTRIGGERS};
Bool_t IsOutOfBunchPileup(TBits* fIR1, TBits* fIR2, Int_t fRunNumber, UShort_t fBC);
void analysis(){
gStyle->SetOptStat(0);
gStyle->SetLabelFont(42,"XYZ");
gStyle->SetLabelSize(0.05,"XYZ");
gStyle->SetHistLineWidth(2);
gStyle->SetTitleFont(42,"XYZ");
gStyle->SetTitleSize(0.05,"XYZ");
gStyle->SetHistLineColor(kBlue);
TFile* fMean = new TFile("mean.root");
TH1D* hMeanOfV0M = (TH1D*) fMean->Get("hMeanOfflineV0M");
TH1D* hMeanOnV0M = (TH1D*) fMean->Get("hMeanOnlineV0M");
TH1D* hMeanOfTKL = (TH1D*) fMean->Get("hMeanTKL");
TH1D* hMeanOfCL1 = (TH1D*) fMean->Get("hMeanCL1");
TH1D* hMeanOnFOR = (TH1D*) fMean->Get("hMeanOnlineFO");
TH1D* hMeanOfFOR = (TH1D*) fMean->Get("hMeanOfflineFO");
TChain* fTree = new TChain("events");
fTree->Add("/alice/cernbox/hm/lhc15f/AnalysisResults.*.root");
fTree->Add("/alice/cernbox/hm/lhc15h/AnalysisResults.*.root");
fTree->Add("/alice/cernbox/hm/lhc15i/AnalysisResults.*.root");
fTree->Add("/alice/cernbox/hm/lhc15j/AnalysisResults.*.root");
fTree->Add("/alice/cernbox/hm/lhc15l/AnalysisResults.*.root");
// fTree->Add("/alice/cernbox/hm/lhc15l/AnalysisResults.239319.root");
// fTree->Add("/alice/cernbox/hm/lhc15l/AnalysisResults.241393.root");
// fTree->Add("/alice/cernbox/hm/lhc15l/AnalysisResults.239319.root");
// fTree->Add("/alice/cernbox/hm/lhc15l/AnalysisResults.*.root");
TObjString* fClassesFired = new TObjString();
Bool_t fIsIncomplete;
Int_t fRunNumber;
UShort_t fBC;
Float_t fV0ATime;
Float_t fV0CTime;
Bool_t fBBFlag[64];
Bool_t fBGFlag[64];
Bool_t fIsFriend=0;
ULong64_t fBBFlagPF[21];
ULong64_t fBGFlagPF[21];
Float_t fMTotV0A;
Float_t fMTotV0C;
Float_t fMRingV0A[4];
Float_t fMRingV0C[4];
UShort_t fTriggerChargeA;
UShort_t fTriggerChargeC;
TBits* fIR1 = new TBits();
TBits* fIR2 = new TBits();
TBits* fIRT0A = new TBits();
TBits* fIRT0C = new TBits();
TBits* fIRTVX = new TBits();
UInt_t fNofTracklets;
Int_t fNofITSClusters[6];
TBits* fFOmap = new TBits();
TBits* fFiredChipMap = new TBits();
UInt_t fInputsL0;
UInt_t fVertexContributors;
UInt_t fPileupContributors;
Bool_t fIsPileupSPD;
Int_t fV0ADecision;
Int_t fV0CDecision;
Float_t fT0A[5];
Float_t fT0C[5];
Float_t fTVX[5];
fTree->SetBranchAddress("fIsIncomplete",&fIsIncomplete);
fTree->SetBranchAddress("fRunNumber",&fRunNumber);
fTree->SetBranchAddress("fBC",&fBC);
fTree->SetBranchAddress("fClassesFired",&fClassesFired);
fTree->SetBranchAddress("fInputsL0",&fInputsL0);
fTree->SetBranchAddress("fVertexContributors",&fVertexContributors);
fTree->SetBranchAddress("fPileupContributors",&fPileupContributors);
fTree->SetBranchAddress("fIsPileupSPD",&fIsPileupSPD);
fTree->SetBranchAddress("fV0ATime",&fV0ATime);
fTree->SetBranchAddress("fV0CTime",&fV0CTime);
fTree->SetBranchAddress("fBBFlag",&fBBFlag);
fTree->SetBranchAddress("fBGFlag",&fBGFlag);
fTree->SetBranchAddress("fIsFriend",&fIsFriend);
fTree->SetBranchAddress("fBBFlagPF",&fBBFlagPF);
fTree->SetBranchAddress("fBGFlagPF",&fBGFlagPF);
fTree->SetBranchAddress("fMTotV0A",&fMTotV0A);
fTree->SetBranchAddress("fMTotV0C",&fMTotV0C);
fTree->SetBranchAddress("fMRingV0A",&fMRingV0A);
fTree->SetBranchAddress("fMRingV0C",&fMRingV0C);
fTree->SetBranchAddress("fTriggerChargeA",&fTriggerChargeA);
fTree->SetBranchAddress("fTriggerChargeC",&fTriggerChargeC);
fTree->SetBranchAddress("fIR1",&fIR1);
fTree->SetBranchAddress("fIR2",&fIR2);
fTree->SetBranchAddress("fNofTracklets",&fNofTracklets);
fTree->SetBranchAddress("fNofITSClusters",&fNofITSClusters);
fTree->SetBranchAddress("fFOmap",&fFOmap);
fTree->SetBranchAddress("fFiredChipMap",&fFiredChipMap);
fTree->SetBranchAddress("fV0ADecision",&fV0ADecision);
fTree->SetBranchAddress("fV0CDecision",&fV0CDecision);
fTree->SetBranchAddress("fT0A",&fT0A);
fTree->SetBranchAddress("fT0C",&fT0C);
fTree->SetBranchAddress("fTVX",&fTVX);
TH3D* hEventCounter = new TH3D("hEventCounter","",1,0,1,1,0,1,1,0,1);
TH3D* hPileupBcRun = new TH3D("hPileupBcRun",";pileup;bc;",40,-20,20,4,0,4,1,0,1);
TH3D* hClsVsTklall = new TH3D("hClsVsTklall",";;tracklets;clusters",NTRIGGERS,0,NTRIGGERS,400,0,400,400,0,4000);
TH3D* hClsVsTklbgd = new TH3D("hClsVsTklbgd",";;tracklets;clusters",NTRIGGERS,0,NTRIGGERS,400,0,400,400,0,4000);
TH3D* hClsVsTklsig = new TH3D("hClsVsTklsig",";;tracklets;clusters",NTRIGGERS,0,NTRIGGERS,400,0,400,400,0,4000);
TH3D* hClsVsTklsel = new TH3D("hClsVsTklsel",";;tracklets;clusters",NTRIGGERS,0,NTRIGGERS,400,0,400,400,0,4000);
TH3D* hBBAall = new TH3D("hBBAall",";BBA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBBCall = new TH3D("hBBCall",";BBC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGAall = new TH3D("hBGAall",";BGA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGCall = new TH3D("hBGCall",";BGC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBBAbgd = new TH3D("hBBAbgd",";BBA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBBCbgd = new TH3D("hBBCbgd",";BBC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGAbgd = new TH3D("hBGAbgd",";BGA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGCbgd = new TH3D("hBGCbgd",";BGC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBBAsig = new TH3D("hBBAsig",";BBA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBBCsig = new TH3D("hBBCsig",";BBC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGAsig = new TH3D("hBGAsig",";BGA flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hBGCsig = new TH3D("hBGCsig",";BGC flags;",NTRIGGERS,0,NTRIGGERS,33,0,33,1,0,1);
TH3D* hV0ATime = new TH3D("hV0ATime" ,";;V0A time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hV0CTime = new TH3D("hV0CTime ",";;V0C time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hV0ATimeBB = new TH3D("hV0ATimeBB",";;V0A time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hV0CTimeBB = new TH3D("hV0CTimeBB",";;V0C time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hV0ATimeBG = new TH3D("hV0ATimeBG",";;V0A time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hV0CTimeBG = new TH3D("hV0CTimeBG",";;V0C time, ns;",NTRIGGERS,0,NTRIGGERS,180,-45,45,1,0,1);
TH3D* hOnV0M = new TH3D("hOnV0M","",NTRIGGERS,0,NTRIGGERS, 220,0,11000,1,0,1);
TH3D* hOfV0M = new TH3D("hOfV0M","",NTRIGGERS,0,NTRIGGERS, 200,0, 2000,1,0,1);
TH3D* hOfTKL = new TH3D("hOfTKL","",NTRIGGERS,0,NTRIGGERS, 200,0, 200,1,0,1);
TH3D* hOfCL1 = new TH3D("hOfCL1","",NTRIGGERS,0,NTRIGGERS, 200,0, 400,1,0,1);
TH3D* hOnFOR = new TH3D("hOnFOR","",NTRIGGERS,0,NTRIGGERS, 200,0, 200,1,0,1);
TH3D* hOfFOR = new TH3D("hOfFOR","",NTRIGGERS,0,NTRIGGERS, 300,0, 300,1,0,1);
TH3D* hOnV0Mnorm = new TH3D("hOnV0Mnorm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOfV0Mnorm = new TH3D("hOfV0Mnorm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOfTKLnorm = new TH3D("hOfTKLnorm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOfCL1norm = new TH3D("hOfCL1norm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOnFORnorm = new TH3D("hOnFORnorm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOfFORnorm = new TH3D("hOfFORnorm","",NTRIGGERS,0,NTRIGGERS, 150,0, 15,1,0,1);
TH3D* hOnFORvsOfFOR_all = new TH3D("hOnFORvsOfFOR_all" ,"",200,0,200,300,0,300,1,0,1);
TH3D* hOnFORvsOfFOR_sel_mod0 = new TH3D("hOnFORvsOfFOR_sel_mod0","",200,0,200,300,0,300,1,0,1);
TH3D* hOnFORvsOfFOR_sel_mod1 = new TH3D("hOnFORvsOfFOR_sel_mod1","",200,0,200,300,0,300,1,0,1);
TH3D* hOnFORvsOfFOR_sel_mod2 = new TH3D("hOnFORvsOfFOR_sel_mod2","",200,0,200,300,0,300,1,0,1);
TH3D* hOnFORvsOfFOR_sel_mod3 = new TH3D("hOnFORvsOfFOR_sel_mod3","",200,0,200,300,0,300,1,0,1);
TH3D* hOnV0MvsOfV0M_all = new TH3D("hOnV0MvsOfV0M_all" ,"",200,0,2000,220,0,11000,1,0,1);
TH3D* hOnV0MvsOfV0M_sel_mod0 = new TH3D("hOnV0MvsOfV0M_sel_mod0 ","",200,0,2000,220,0,11000,1,0,1);
TH3D* hOnV0MvsOfV0M_sel_mod1 = new TH3D("hOnV0MvsOfV0M_sel_mod1 ","",200,0,2000,220,0,11000,1,0,1);
TH3D* hOnV0MvsOfV0M_sel_mod2 = new TH3D("hOnV0MvsOfV0M_sel_mod2 ","",200,0,2000,220,0,11000,1,0,1);
TH3D* hOnV0MvsOfV0M_sel_mod3 = new TH3D("hOnV0MvsOfV0M_sel_mod3 ","",200,0,2000,220,0,11000,1,0,1);
TH2D* hV0C012vsV0C3 = new TH2D("hV0C012vsV0C3","",800,0,800,300,0,300);
TH1D* h0TVXall = new TH1D("h0TVXall","",1,0,1);
TH1D* h0TVXbad = new TH1D("h0TVXbad","",1,0,1);
TH1D* h0VIRall = new TH1D("h0VIRall","",1,0,1);
TH1D* h0VIRbad = new TH1D("h0VIRbad","",1,0,1);
TH1D* h0TVXbcs = new TH1D("h0TVXbcs","",3564,0,3564);
printf("Entries: %i\n",fTree->GetEntries());
Int_t nSPD1 = 0;
Int_t nWrong = 0;
Bool_t tr[NTRIGGERS];
for (Int_t ev=0;ev<fTree->GetEntries();ev++){
// for (Int_t ev=0;ev<100000;ev++){
fTree->GetEntry(ev);
if (ev%100000==0) printf("Event=%10i Run=%i\n",ev, fRunNumber);
const char* srun = Form("%i",fRunNumber);
if (fClassesFired->String().Contains("C0TVX-B")){
if (fIsIncomplete || fInputsL0==0) continue;
if (!(fInputsL0 & 1<<2)) printf("0TVX input not fired");
h0TVXall->Fill(srun,1);
h0TVXbad->Fill(srun,0);
if (!fIR2->TestBitNumber(90)) {
h0TVXbad->Fill(srun,1);
h0TVXbcs->Fill(fBC);
printf("0TVX:");
for (Int_t i=-90;i<=90;i++) printf("%i",fIR2->TestBitNumber(90+i));
printf("\n");
}
}
if (fClassesFired->String().Contains("CINT7-B")){
if (fIsIncomplete || fInputsL0==0) continue;
if (!(fInputsL0 & 1<<3)) continue;
h0VIRall->Fill(srun,1);
h0VIRbad->Fill(srun,0);
if (!fIR1->TestBitNumber(90)) {
printf("0VIR:");
h0VIRbad->Fill(srun,1);
for (Int_t i=-90;i<=90;i++) printf("%i",fIR1->TestBitNumber(90+i));
printf("\n");
}
}
// continue;
Bool_t mb = fClassesFired->String().Contains("CINT7-B");
Bool_t sh1 = fClassesFired->String().Contains("CVHMSH1-B");
Bool_t sh2 = fClassesFired->String().Contains("CVHMSH2-B");
Bool_t vhm = fClassesFired->String().Contains("CVHMV0M-B");
Bool_t vhmnopf = fClassesFired->String().Contains("CVHMV0M-B-NOPF");
Bool_t vhmspd1 = fClassesFired->String().Contains("CVHMV0M-B-SPD1");
Bool_t sh2nopf = fClassesFired->String().Contains("CVHMSH2-B-NOPF");
Bool_t sh2spd1 = fClassesFired->String().Contains("CVHMSH2-B-SPD1");
Bool_t sh1nopf = fClassesFired->String().Contains("CVHMSH1-B-NOPF");
tr[kINT] = mb;
tr[kSH1] = sh1;
tr[kSH2] = sh2;
tr[kVHM] = vhm;
if (mb) hEventCounter->Fill("all","CINT7-B-NOPF" ,srun,1.);
if (vhmnopf) hEventCounter->Fill("all","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("all","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("all","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("all","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("all","CVHMSH1-B-NOPF",srun,1.);
if (fIsIncomplete || fInputsL0==0) continue;
Bool_t VBA = fInputsL0 & 1<< 0;
Bool_t VBC = fInputsL0 & 1<< 1;
Bool_t V0M = fInputsL0 & 1<< 9;
Bool_t VHM = fInputsL0 & 1<<10;
Bool_t SH2 = fInputsL0 & 1<<13;
if (mb && (!VBA || !VBC)) { printf("run=%i fInputsL0=%i mb mismatch: VBA=%i VBC=%i\n",fRunNumber,fInputsL0,VBA,VBC); continue; }
if (sh2 && (!VHM || !SH2)) { printf("run=%i fInputsL0=%i sh2 mismatch: VHM=%i SH2=%i\n",fRunNumber,fInputsL0,VHM,SH2); continue; }
if (vhm && (!VHM || !V0M)) { printf("run=%i fInputsL0=%i vhm mismatch: VHM=%i V0M=%i\n",fRunNumber,fInputsL0,VHM,V0M); continue; }
if (mb) hEventCounter->Fill("complete","CINT7-B-NOPF" ,srun,1.);
if (vhmnopf) hEventCounter->Fill("complete","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("complete","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("complete","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("complete","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("complete","CVHMSH1-B-NOPF",srun,1.);
Double_t meanOfV0M = hMeanOfV0M->GetBinContent(hMeanOfV0M->GetXaxis()->FindBin(srun));
Double_t meanOnV0M = hMeanOnV0M->GetBinContent(hMeanOnV0M->GetXaxis()->FindBin(srun));
Double_t meanOfFOR = hMeanOfFOR->GetBinContent(hMeanOfFOR->GetXaxis()->FindBin(srun));
Double_t meanOnFOR = hMeanOnFOR->GetBinContent(hMeanOnFOR->GetXaxis()->FindBin(srun));
Double_t meanOfTKL = hMeanOfTKL->GetBinContent(hMeanOfTKL->GetXaxis()->FindBin(srun));
Double_t meanOfCL1 = hMeanOfCL1->GetBinContent(hMeanOfCL1->GetXaxis()->FindBin(srun));
Int_t nBBA=0; for (Int_t b=0;b<32;b++) nBBA+=fBBFlag[b+32];
Int_t nBBC=0; for (Int_t b=0;b<32;b++) nBBC+=fBBFlag[b];
Int_t nBGA=0; for (Int_t b=0;b<32;b++) nBGA+=fBGFlag[b+32];
Int_t nBGC=0; for (Int_t b=0;b<32;b++) nBGC+=fBGFlag[b];
Bool_t bgdV0 = (fV0ADecision!=1 || fV0CDecision!=1);
Bool_t goodV0 = fV0ADecision==1 && fV0CDecision==1;
Int_t nClusters = fNofITSClusters[0]+fNofITSClusters[1];
Int_t nTracklets = fNofTracklets;
Double_t V0C012 = fMRingV0C[0]+fMRingV0C[1]+fMRingV0C[2];
Double_t V0C3 = fMRingV0C[3];
Double_t onFOR = fFOmap->CountBits(400);
Double_t ofFOR = fFiredChipMap->CountBits(400);
Double_t ofCL1 = fNofITSClusters[1];
Double_t ofTKL = fNofTracklets;
Double_t onV0M = fTriggerChargeA+fTriggerChargeC;
Double_t ofV0M = fMTotV0A+fMTotV0C;
Bool_t bgdSPD = (nClusters<85 ? 0 : nClusters>85.+(2000.-85.)/(150.-7.)*(nTracklets-7.));
Bool_t goodSPD = nClusters < 65+4*nTracklets;
Bool_t isV0Casym = (V0C012 < 160.) || (V0C3 > 12.*TMath::Power(0.01*(V0C012-160.), 1.7));
Bool_t isOutOfBunchPileup = IsOutOfBunchPileup(fIR1, fIR2, fRunNumber, fBC);
Bool_t isEventSelected = goodV0 && !isOutOfBunchPileup && !fIsPileupSPD && goodSPD && isV0Casym;
Bool_t isOutlierFOR = onFOR<200./300.*(ofFOR-50);
Bool_t isOutlierV0M = onV0M<5000./800.*(ofV0M-200);
if (goodV0){
if (mb) hEventCounter->Fill("good_V0","CINT7-B-NOPF",srun,1.);
if (vhmnopf) hEventCounter->Fill("good_V0","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("good_V0","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("good_V0","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("good_V0","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("good_V0","CVHMSH1-B-NOPF",srun,1.);
if (goodSPD) {
if (mb) hEventCounter->Fill("good_SPD","CINT7-B-NOPF",srun,1.);
if (vhmnopf) hEventCounter->Fill("good_SPD","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("good_SPD","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("good_SPD","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("good_SPD","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("good_SPD","CVHMSH1-B-NOPF",srun,1.);
if (!fIsPileupSPD) {
if (mb) hEventCounter->Fill("no_same_bunch_pileup","CINT7-B-NOPF",srun,1.);
if (vhmnopf) hEventCounter->Fill("no_same_bunch_pileup","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("no_same_bunch_pileup","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("no_same_bunch_pileup","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("no_same_bunch_pileup","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("no_same_bunch_pileup","CVHMSH1-B-NOPF",srun,1.);
if (!isOutOfBunchPileup) {
if (mb) hEventCounter->Fill("no_out_of_bunch_pileup","CINT7-B-NOPF",srun,1.);
if (vhmnopf) hEventCounter->Fill("no_out_of_bunch_pileup","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("no_out_of_bunch_pileup","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("no_out_of_bunch_pileup","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("no_out_of_bunch_pileup","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("no_out_of_bunch_pileup","CVHMSH1-B-NOPF",srun,1.);
if (isV0Casym) {
if (mb) hEventCounter->Fill("selected","CINT7-B-NOPF",srun,1.);
if (vhmnopf) hEventCounter->Fill("selected","CVHMV0M-B-NOPF",srun,1.);
if (vhmspd1) hEventCounter->Fill("selected","CVHMV0M-B-SPD1",srun,1.);
if (sh2nopf) hEventCounter->Fill("selected","CVHMSH2-B-NOPF",srun,1.);
if (sh2spd1) hEventCounter->Fill("selected","CVHMSH2-B-SPD1",srun,1.);
if (sh1nopf) hEventCounter->Fill("selected","CVHMSH1-B-NOPF",srun,1.);
}
}
}
}
}
if (goodV0 && !isOutOfBunchPileup && !fIsPileupSPD && goodSPD) hV0C012vsV0C3->Fill(V0C012,V0C3);
hPileupBcRun->Fill(0.,0.,srun,0.);
if (mb & isOutlierFOR) for (Int_t i=-19;i<=20;i++) if (fIR2->TestBitNumber(90+i)) hPileupBcRun->Fill(i-1,fBC%4,srun,1);
//// if (sh2) for (Int_t i=-19;i<=20;i++) if (fIR1->TestBitNumber(90+i)) hPileupBcRun->Fill(i-1,fBC%4,srun,1);
Double_t onV0Mnorm = onV0M/meanOnV0M;
Double_t ofV0Mnorm = ofV0M/meanOfV0M;
Double_t onFORnorm = onFOR/meanOnFOR;
Double_t ofFORnorm = ofFOR/meanOfFOR;
Double_t ofTKLnorm = ofTKL/meanOfTKL;
Double_t ofCL1norm = ofCL1/meanOfCL1;
if (ofFORnorm>=15) ofFOR=14.9;
if (onFORnorm>=15) onFOR=14.9;
if (ofTKLnorm>=15) ofTKL=14.9;
if (ofCL1norm>=15) ofCL1=14.9;
if (onV0Mnorm>=15) onV0M=14.9;
if (ofV0Mnorm>=15) ofV0M=14.9;
if (ofFOR>=300) ofFOR=299.9;
if (onFOR>=200) onFOR=199.9;
if (ofTKL>=200) ofTKL=199.9;
if (ofCL1>=400) ofCL1=399.9;
if (onV0M>=11000) onV0M=10999.9;
if (ofV0M>=2000) ofV0M=1999.9;
if (nTracklets>=400) nTracklets=399;
if (nClusters>=4000) nClusters=3999;
for (Int_t t=0;t<NTRIGGERS;t++){
// for (Int_t t=0;t<1;t++){
if (!tr[t]) continue;
hClsVsTklall->Fill(t,nTracklets,nClusters,1);
hBBAall->Fill(t,nBBA,srun,1);
hBBCall->Fill(t,nBBC,srun,1);
hBGAall->Fill(t,nBGA,srun,1);
hBGCall->Fill(t,nBGC,srun,1);
if (fV0ATime>=-45 && fV0ATime<=45) hV0ATime->Fill(t,fV0ATime,srun,1);
if (fV0CTime>=-45 && fV0CTime<=45) hV0CTime->Fill(t,fV0CTime,srun,1);
if (fV0ADecision==1) hV0ATimeBB->Fill(t,fV0ATime,srun,1);
if (fV0CDecision==1) hV0CTimeBB->Fill(t,fV0CTime,srun,1);
if (fV0ADecision==2) hV0ATimeBG->Fill(t,fV0ATime,srun,1);
if (fV0CDecision==2) hV0CTimeBG->Fill(t,fV0CTime,srun,1);
if (goodV0 && !isOutOfBunchPileup) hClsVsTklsel->Fill(t,nTracklets,nClusters,1);
if (bgdSPD) {
hClsVsTklbgd->Fill(t,nTracklets,nClusters,1);
hBBAbgd->Fill(t,nBBA,srun,1);
hBBCbgd->Fill(t,nBBC,srun,1);
hBGAbgd->Fill(t,nBGA,srun,1);
hBGCbgd->Fill(t,nBGC,srun,1);
}
if (t==0) {
hOnFORvsOfFOR_all->Fill(ofFOR,onFOR,srun,1);
hOnV0MvsOfV0M_all->Fill(ofV0M,onV0M,srun,1);
}
if (!isEventSelected) continue;
hClsVsTklsig->Fill(t,nTracklets,nClusters,1);
hBBAsig->Fill(t,nBBA,srun,1);
hBBCsig->Fill(t,nBBC,srun,1);
hBGAsig->Fill(t,nBGA,srun,1);
hBGCsig->Fill(t,nBGC,srun,1);
hOnV0M->Fill(t,onV0M,srun,1);
hOfV0M->Fill(t,ofV0M,srun,1);
hOfTKL->Fill(t,ofTKL,srun,1);
hOfCL1->Fill(t,ofCL1,srun,1);
hOnFOR->Fill(t,onFOR,srun,1);
hOfFOR->Fill(t,ofFOR,srun,1);
hOnV0Mnorm->Fill(t,onV0Mnorm,srun,1);
hOfV0Mnorm->Fill(t,ofV0Mnorm,srun,1);
hOfTKLnorm->Fill(t,ofTKLnorm,srun,1);
hOfCL1norm->Fill(t,ofCL1norm,srun,1);
hOnFORnorm->Fill(t,onFORnorm,srun,1);
hOfFORnorm->Fill(t,ofFORnorm,srun,1);
if (t==0) {
if (fBC%4==0) hOnFORvsOfFOR_sel_mod0->Fill(ofFOR,onFOR,srun,1);
if (fBC%4==1) hOnFORvsOfFOR_sel_mod1->Fill(ofFOR,onFOR,srun,1);
if (fBC%4==2) hOnFORvsOfFOR_sel_mod2->Fill(ofFOR,onFOR,srun,1);
if (fBC%4==3) hOnFORvsOfFOR_sel_mod3->Fill(ofFOR,onFOR,srun,1);
if (fBC%4==0) hOnV0MvsOfV0M_sel_mod0->Fill(ofV0M,onV0M,srun,1);
if (fBC%4==1) hOnV0MvsOfV0M_sel_mod1->Fill(ofV0M,onV0M,srun,1);
if (fBC%4==2) hOnV0MvsOfV0M_sel_mod2->Fill(ofV0M,onV0M,srun,1);
if (fBC%4==3) hOnV0MvsOfV0M_sel_mod3->Fill(ofV0M,onV0M,srun,1);
}
}
}
TFile* fout = new TFile("results.root","recreate");
// hEventCounter->Write();
// hClsVsTklAll->Write();
// hClsVsTkl->Write();
// hOnVsOffSPD1->Write();
// hOnVsOffSPD2->Write();
// hOnVsOffSPD1vsRun->Write();
// hOnVsOffSPD2vsRun->Write();
// hOnVsOffV0M1->Write();
// hOnVsOffV0M2->Write();
// hPileup->Write();
// hBBA_SMB_all->Write();
// hBBC_SMB_all->Write();
// hBGA_SMB_all->Write();
// hBGC_SMB_all->Write();
// hBBA_SMB_sig->Write();
// hBBC_SMB_sig->Write();
// hBGA_SMB_sig->Write();
// hBGC_SMB_sig->Write();
// hBBA_SMB_bgd->Write();
// hBBC_SMB_bgd->Write();
// hBGA_SMB_bgd->Write();
// hBGC_SMB_bgd->Write();
// hBBA_VMB_all->Write();
// hBBC_VMB_all->Write();
// hBGA_VMB_all->Write();
// hBGC_VMB_all->Write();
// hBBA_VMB_sig->Write();
// hBBC_VMB_sig->Write();
// hBGA_VMB_sig->Write();
// hBGC_VMB_sig->Write();
// hBBA_VMB_bgd->Write();
// hBBC_VMB_bgd->Write();
// hBGA_VMB_bgd->Write();
// hBGC_VMB_bgd->Write();
// hBBA_SHM_all->Write();
// hBBC_SHM_all->Write();
// hBGA_SHM_all->Write();
// hBGC_SHM_all->Write();
// hBBA_VHM_all->Write();
// hBBC_VHM_all->Write();
// hBGA_VHM_all->Write();
// hBGC_VHM_all->Write();
// hBBA_SHM_bgd->Write();
// hBBC_SHM_bgd->Write();
// hBGA_SHM_bgd->Write();
// hBGC_SHM_bgd->Write();
// hBBA_VHM_bgd->Write();
// hBBC_VHM_bgd->Write();
// hBGA_VHM_bgd->Write();
// hBGC_VHM_bgd->Write();
// hBBA_SHM_sig->Write();
// hBBC_SHM_sig->Write();
// hBGA_SHM_sig->Write();
// hBGC_SHM_sig->Write();
// hBBA_VHM_sig->Write();
// hBBC_VHM_sig->Write();
// hBGA_VHM_sig->Write();
// hBGC_VHM_sig->Write();
// hOnlineV0M->Write();
// hOnlineSPD->Write();
// hOnlineVHM->Write();
// hOnlineSHM->Write();
// hOfflineV0M->Write();
// hOfflineVHM->Write();
// hOfflineV0Mcut->Write();
// hOfflineVHMcut->Write();
// hOfflineSPD->Write();
// hOfflineSHM->Write();
// hV0ATime->Write();
// hV0CTime->Write();
// hV0ATimeNoOutOfBunch->Write();
// hV0CTimeNoOutOfBunch->Write();
// hV0ATimeBB->Write();
hEventCounter->Write();
hPileupBcRun->Write();
hClsVsTklall->Write();
hClsVsTklbgd->Write();
hClsVsTklsig->Write();
hClsVsTklsel->Write();
hBBAall->Write();
hBBCall->Write();
hBGAall->Write();
hBGCall->Write();
hBBAbgd->Write();
hBBCbgd->Write();
hBGAbgd->Write();
hBGCbgd->Write();
hBBAsig->Write();
hBBCsig->Write();
hBGAsig->Write();
hBGCsig->Write();
hV0ATime->Write();
hV0CTime->Write();
hV0ATimeBB->Write();
hV0CTimeBB->Write();
hV0ATimeBG->Write();
hV0CTimeBG->Write();
hOnV0M->Write();
hOfV0M->Write();
hOfTKL->Write();
hOfCL1->Write();
hOnFOR->Write();
hOfFOR->Write();
hOnV0Mnorm->Write();
hOfV0Mnorm->Write();
hOfTKLnorm->Write();
hOfCL1norm->Write();
hOnFORnorm->Write();
hOfFORnorm->Write();
hOnFORvsOfFOR_all->Write();
hOnFORvsOfFOR_sel_mod0->Write();
hOnFORvsOfFOR_sel_mod1->Write();
hOnFORvsOfFOR_sel_mod2->Write();
hOnFORvsOfFOR_sel_mod3->Write();
hOnV0MvsOfV0M_all->Write();
hOnV0MvsOfV0M_sel_mod0 ->Write();
hOnV0MvsOfV0M_sel_mod1->Write();
hOnV0MvsOfV0M_sel_mod2->Write();
hOnV0MvsOfV0M_sel_mod3->Write();
hV0C012vsV0C3->Write();
h0TVXbcs->Write();
h0TVXall->Write();
h0TVXbad->Write();
h0VIRall->Write();
h0VIRbad->Write();
fout->Close();
}
Bool_t IsOutOfBunchPileup(TBits* fIR1, TBits* fIR2, Int_t fRunNumber, UShort_t fBC) {
Bool_t isOutOfBunchPileup = 0;
if ((fRunNumber>=225000 && fRunNumber<=225719) ||
(fRunNumber>=226062 && fRunNumber<=226500) ||
(fRunNumber>=233912 && fRunNumber<=234050)
) isOutOfBunchPileup=0; // isolated bunches
else {
Int_t pf1 = -4-fBC%4; // standard D-1;D0;D+1
Int_t pf2 = +7-fBC%4; // standard D-1;D0;D+1
if (fRunNumber<=238621) { pf1+=4; pf2+=4; } // D0;D+1;D+2: shifted settings in LHC15f-j
if (fRunNumber==240404) { pf1+=4; pf2+=4; } // test in LHC15k with D0;D+1;D+2
if (fRunNumber==240411) { pf1+=0; pf2-=4; } // test in LHC15k with D-1;D0
if (fRunNumber==240427) { pf1-=4; pf2-=4; } // test in LHC15k with D-2;D-1;D0
// temporary staff to be adjusted with friend info
Int_t pf2maxForT0 = pf2;
Int_t ir1skip = 0;
if (fRunNumber<=228948) { pf2maxForT0=8; } // temporary: 0UBA|0UBC IR2 with afterpulses starting from +9
if (fRunNumber<=238187) { ir1skip=2; } // temporary: for 0VIR(>=2) or VBA&VBC or VBA|VBC
for (Int_t i=pf1;i<=pf2;i++) {
if (i==0) continue;
if (i<=pf2maxForT0) isOutOfBunchPileup|=fIR2->TestBitNumber(90+i); // T0-based clean-up
if (i>0 && i<=ir1skip) continue; // skip next 2 for old IR definitions
isOutOfBunchPileup|=fIR1->TestBitNumber(90+i); // V0-based clean-up
}
}
return isOutOfBunchPileup;
}
|
c7029d066d3b670d1cb4a0a4837651c140d31364
|
ecce427678ecff2a93a47f3b1b664202c7d27617
|
/levels/bitdw/areas/1/narrow_path_platform/model.inc.c
|
64029a16da976555722a691a65bb0bdfb51c250b
|
[] |
no_license
|
sm64pc/sm64ex
|
ecf37f31b3f7426c4874254660d856030d789714
|
54cd27ccee45a2403b45f07a00d6043c51149969
|
refs/heads/nightly
| 2023-08-11T12:14:34.424168
| 2023-07-01T11:45:50
| 2023-07-01T11:45:50
| 262,091,731
| 795
| 238
| null | 2023-07-01T11:45:51
| 2020-05-07T15:43:27
|
C
|
UTF-8
|
C
| false
| false
| 9,111
|
c
|
model.inc.c
|
// 0x0700A718 - 0x0700A818
static const Vtx bitdw_seg7_vertex_0700A718[] = {
{{{ 102, 102, 102}, 0, { 18, 836}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -420, 162, -49}, 0, { 82, -532}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ 102, 102, 307}, 0, { 990, 990}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -565, 162, 95}, 0, { 990, -766}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -995, 314, -334}, 0, { 990, -574}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -565, 162, 95}, 0, { 990, 990}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -420, 162, -49}, 0, { 0, 990}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -850, 314, -479}, 0, { 0, -574}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ 102, 102, 102}, 0, { 0, 62}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ 717, 102, 307}, 0, { 990, 990}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ 717, 102, 102}, 0, { 0, 990}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ 102, 102, 307}, 0, { 990, 0}, {0x8e, 0xac, 0x52, 0xff}}},
{{{ -565, 60, 95}, 0, { 1012, -744}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ -420, 60, -49}, 0, { 104, -510}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 102, 0, 102}, 0, { 40, 858}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 102, 0, 307}, 0, { 1012, 1010}, {0x3a, 0x47, 0x2d, 0xff}}},
};
// 0x0700A818 - 0x0700A918
static const Vtx bitdw_seg7_vertex_0700A818[] = {
{{{ -565, 60, 95}, 0, { 990, 1050}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ -1065, 236, -404}, 0, { 990, -512}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ -920, 236, -549}, 0, { 0, -512}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ -420, 60, -49}, 0, { 0, 1050}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 717, 0, 102}, 0, { 0, 990}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 717, 0, 307}, 0, { 990, 990}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 102, 0, 307}, 0, { 990, -542}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 102, 0, 102}, 0, { 0, -544}, {0x3a, 0x47, 0x2d, 0xff}}},
{{{ 717, 0, 102}, 0, { -1308, 606}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 102, 102, 102}, 0, { -158, 734}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 717, 102, 102}, 0, { -1308, 352}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 102, 0, 102}, 0, { -158, 990}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 102, 102, 307}, 0, { 0, 734}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 717, 0, 307}, 0, { -1308, 606}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 717, 102, 307}, 0, { -1308, 352}, {0x4d, 0x6f, 0x2d, 0xff}}},
{{{ 102, 0, 307}, 0, { 0, 990}, {0x4d, 0x6f, 0x2d, 0xff}}},
};
// 0x0700A918 - 0x0700AA18
static const Vtx bitdw_seg7_vertex_0700A918[] = {
{{{ -420, 60, -49}, 0, { 1352, 1244}, {0x47, 0x61, 0x15, 0xff}}},
{{{ -420, 162, -49}, 0, { 1352, 990}, {0x47, 0x61, 0x15, 0xff}}},
{{{ 102, 102, 102}, 0, { 2658, 1136}, {0x47, 0x61, 0x15, 0xff}}},
{{{ 102, 0, 102}, 0, { 2658, 1392}, {0x47, 0x61, 0x15, 0xff}}},
{{{ -565, 162, 95}, 0, { 1636, 720}, {0x47, 0x61, 0x15, 0xff}}},
{{{ -565, 60, 95}, 0, { 1636, 890}, {0x47, 0x61, 0x15, 0xff}}},
{{{ 102, 0, 307}, 0, { 0, 990}, {0x47, 0x61, 0x15, 0xff}}},
{{{ 102, 102, 307}, 0, { 0, 820}, {0x47, 0x61, 0x15, 0xff}}},
{{{ -420, 162, -49}, 0, { 1352, 990}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -420, 60, -49}, 0, { 1352, 1244}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -850, 314, -479}, 0, { 278, 610}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -920, 236, -549}, 0, { 102, 804}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -995, 314, -334}, 0, { -82, 610}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -565, 60, 95}, 0, { 990, 1244}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -565, 162, 95}, 0, { 990, 990}, {0x44, 0x5f, 0x25, 0xff}}},
{{{ -1065, 236, -404}, 0, { -256, 804}, {0x44, 0x5f, 0x25, 0xff}}},
};
// 0x0700AA18 - 0x0700AAF8
static const Vtx bitdw_seg7_vertex_0700AA18[] = {
{{{ 1126, 0, 0}, 0, { -90, 1042}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 1189, -168, 94}, 0, { -18, 1254}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 717, 0, 102}, 0, { 562, 512}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 717, 0, 307}, 0, { 888, 758}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 1189, -168, 315}, 0, { 336, 1520}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 1126, 0, 410}, 0, { 562, 1532}, {0x4e, 0x69, 0x7e, 0xff}}},
{{{ 717, 102, 307}, 0, { 820, 1498}, {0x74, 0xb2, 0xbd, 0xff}}},
{{{ 1126, 102, 410}, 0, { 0, 990}, {0x74, 0xb2, 0xbd, 0xff}}},
{{{ 1126, 102, 0}, 0, { 650, 308}, {0x74, 0xb2, 0xbd, 0xff}}},
{{{ 717, 102, 102}, 0, { 1160, 1158}, {0x74, 0xb2, 0xbd, 0xff}}},
{{{ 717, 0, 102}, 0, { 562, 512}, {0x27, 0x35, 0x3e, 0xff}}},
{{{ 1189, -168, 315}, 0, { 336, 1520}, {0x27, 0x35, 0x3e, 0xff}}},
{{{ 717, 0, 307}, 0, { 888, 758}, {0x27, 0x35, 0x3e, 0xff}}},
{{{ 1189, -168, 94}, 0, { -18, 1254}, {0x27, 0x35, 0x3e, 0xff}}},
};
// 0x0700AAF8 - 0x0700AB78
static const Vtx bitdw_seg7_vertex_0700AAF8[] = {
{{{ 717, 0, 307}, 0, { 0, 480}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 1126, 102, 410}, 0, { 1246, 1244}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 717, 102, 307}, 0, { 224, 224}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 1126, 0, 410}, 0, { 990, 1498}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 1126, 0, 0}, 0, { 990, 1498}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 717, 102, 102}, 0, { 224, 224}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 1126, 102, 0}, 0, { 1246, 1244}, {0x2d, 0x5e, 0x7c, 0xff}}},
{{{ 717, 0, 102}, 0, { 0, 480}, {0x2d, 0x5e, 0x7c, 0xff}}},
};
// 0x0700AB78 - 0x0700AC70
static const Gfx bitdw_seg7_dl_0700AB78[] = {
gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, sky_09000800),
gsDPLoadSync(),
gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)),
gsSPVertex(bitdw_seg7_vertex_0700A718, 16, 0),
gsSP2Triangles( 0, 1, 2, 0x0, 1, 3, 2, 0x0),
gsSP2Triangles( 4, 5, 6, 0x0, 7, 4, 6, 0x0),
gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0),
gsSP2Triangles(12, 13, 14, 0x0, 15, 12, 14, 0x0),
gsSPVertex(bitdw_seg7_vertex_0700A818, 16, 0),
gsSP2Triangles( 0, 1, 2, 0x0, 3, 0, 2, 0x0),
gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0),
gsSP2Triangles( 8, 9, 10, 0x0, 8, 11, 9, 0x0),
gsSP2Triangles(12, 13, 14, 0x0, 12, 15, 13, 0x0),
gsSPVertex(bitdw_seg7_vertex_0700A918, 16, 0),
gsSP2Triangles( 0, 1, 2, 0x0, 0, 2, 3, 0x0),
gsSP2Triangles( 4, 5, 6, 0x0, 4, 6, 7, 0x0),
gsSP2Triangles( 8, 9, 10, 0x0, 9, 11, 10, 0x0),
gsSP2Triangles(12, 13, 14, 0x0, 12, 15, 13, 0x0),
gsSPEndDisplayList(),
};
// 0x0700AC70 - 0x0700ACC8
static const Gfx bitdw_seg7_dl_0700AC70[] = {
gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, sky_09001800),
gsDPLoadSync(),
gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)),
gsSPVertex(bitdw_seg7_vertex_0700AA18, 14, 0),
gsSP2Triangles( 0, 1, 2, 0x0, 3, 4, 5, 0x0),
gsSP2Triangles( 6, 7, 8, 0x0, 6, 8, 9, 0x0),
gsSP2Triangles(10, 11, 12, 0x0, 10, 13, 11, 0x0),
gsSPEndDisplayList(),
};
// 0x0700ACC8 - 0x0700AD10
static const Gfx bitdw_seg7_dl_0700ACC8[] = {
gsDPSetTextureImage(G_IM_FMT_RGBA, G_IM_SIZ_16b, 1, sky_09007000),
gsDPLoadSync(),
gsDPLoadBlock(G_TX_LOADTILE, 0, 0, 32 * 32 - 1, CALC_DXT(32, G_IM_SIZ_16b_BYTES)),
gsSPVertex(bitdw_seg7_vertex_0700AAF8, 8, 0),
gsSP2Triangles( 0, 1, 2, 0x0, 0, 3, 1, 0x0),
gsSP2Triangles( 4, 5, 6, 0x0, 4, 7, 5, 0x0),
gsSPEndDisplayList(),
};
// 0x0700AD10 - 0x0700AD90
const Gfx bitdw_seg7_dl_0700AD10[] = {
gsDPPipeSync(),
gsDPSetCombineMode(G_CC_MODULATERGB, G_CC_MODULATERGB),
gsSPClearGeometryMode(G_LIGHTING),
gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 0, 0, G_TX_LOADTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, G_TX_NOMASK, G_TX_NOLOD),
gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_ON),
gsDPTileSync(),
gsDPSetTile(G_IM_FMT_RGBA, G_IM_SIZ_16b, 8, 0, G_TX_RENDERTILE, 0, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD, G_TX_WRAP | G_TX_NOMIRROR, 5, G_TX_NOLOD),
gsDPSetTileSize(0, 0, 0, (32 - 1) << G_TEXTURE_IMAGE_FRAC, (32 - 1) << G_TEXTURE_IMAGE_FRAC),
gsSPDisplayList(bitdw_seg7_dl_0700AB78),
gsSPDisplayList(bitdw_seg7_dl_0700AC70),
gsSPDisplayList(bitdw_seg7_dl_0700ACC8),
gsSPTexture(0xFFFF, 0xFFFF, 0, G_TX_RENDERTILE, G_OFF),
gsDPPipeSync(),
gsDPSetCombineMode(G_CC_SHADE, G_CC_SHADE),
gsSPSetGeometryMode(G_LIGHTING),
gsSPEndDisplayList(),
};
|
600ba0157867b819e5d2d7b28ec325440f7463e2
|
72bdf3d5a4f063734d2fa78ef0121abb1687e17a
|
/reg-lib/cpu/_reg_femTrans.h
|
8293de697de7d77b71d3074c3a979575f6aff27d
|
[] |
permissive
|
KCL-BMEIS/niftyreg
|
95bf0e25d5b12c29cb41f2c1943d6ae5e4a18ada
|
6db8b16c17884a9b8859c980c4f1c408f62bd9ca
|
refs/heads/master
| 2023-08-31T16:20:25.493600
| 2022-11-18T07:48:12
| 2022-11-18T07:48:12
| 134,296,286
| 103
| 41
|
BSD-3-Clause
| 2022-07-28T14:24:51
| 2018-05-21T16:34:44
|
C
|
UTF-8
|
C
| false
| false
| 3,207
|
h
|
_reg_femTrans.h
|
/**
* @file _reg_femTransformation_gpu.h
* @author Marc Modat
* @date 02/11/2011
* @brief Functions built to interface between NiftyReg and NiftySim
* It basically allows to populate a dense deformation
*
* Created by Marc Modat on 02/11/2011.
* Copyright (c) 2011-2018, University College London
* Copyright (c) 2018, NiftyReg Developers.
* All rights reserved.
* See the LICENSE.txt file in the nifty_reg root folder
*
*/
#ifndef _REG_FEMTRANS_H
#define _REG_FEMTRANS_H
#include "nifti1_io.h"
#include <fstream>
#include "_reg_maths.h"
/** @brief Initialise multiples arrays to populate a dense deformation
* field from a FEM parametrisation
* @param elementNodes Arrays that contains the nodes use to define each element.
* @param nodePositions Arrays that contains the position in mm of
* every node
* @param deformationFieldImage Deformation field image, at this stage it
* is only used to define the space of the transformation
* @param closestNodes This array will contain for every voxel the closest
* nodes to be used for interpolation
* @param femInterpolationWeight This arrayt will contain for every voxel
* the weight associated with the closest node.
*/
void reg_fem_InitialiseTransformation(int *elementNodes,
unsigned int elementNumber,
float *nodePositions,
nifti_image *deformationFieldImage,
unsigned int *closestNodes,
float *femInterpolationWeight
);
/** @brief A dense deformation field is filled using interpolation
* from a coarse mesh
* @param nodePositions Array that contains the position of every node
* @param deformationFieldImage Deformation field image that will be
* filled
* @param closestNodes Array that contains for every voxel the closest
* nodes from the mesh
* @param femInterpolationWeight Array that contains for every voxel,
* the weight associated with the closest nodes.
*/
void reg_fem_getDeformationField(float *nodePositions,
nifti_image *deformationFieldImage,
unsigned int *closestNodes,
float *femInterpolationWeight
);
/** @brief Convert a dense gradient image into a mesh based gradient image
* @param voxelBasedGradient Image that contains the gradient image
* @param closestNodes Array that contains the closest nodes associated
* with every voxel
* @param femInterpolationWeight Array that contains for every voxel the
* weight associated with the closest nodes
* @param nodeNumber Scalar that contains the total number of node in the mesh
* @param femBasedGradient Array that contains the gradient values at
* every node.
*/
void reg_fem_voxelToNodeGradient(nifti_image *voxelBasedGradient,
unsigned int *closestNodes,
float *femInterpolationWeight,
unsigned int nodeNumber,
float *femBasedGradient);
#endif
|
b149790aba8915cacc47b8a1df26dee0018d9105
|
4e32ea5b4a215f427af04630e01b1312ffd31a55
|
/test/programs/simple/enum-large-llu.c
|
12d6008b11dd12c597302e730f4aea0cb141b33d
|
[
"Apache-2.0",
"GPL-1.0-or-later"
] |
permissive
|
sosy-lab/cpachecker
|
1add74cb774316dd6e1aea3fb1f352c8141466b7
|
1822761867d106301bda0bc99ed3cc0a25c529aa
|
refs/heads/trunk
| 2023-08-31T14:47:22.284597
| 2023-08-31T14:20:58
| 2023-08-31T14:20:58
| 20,107,238
| 186
| 90
|
Apache-2.0
| 2021-07-27T14:24:30
| 2014-05-23T16:57:37
|
SWIG
|
UTF-8
|
C
| false
| false
| 1,204
|
c
|
enum-large-llu.c
|
// This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
// testing upper and lower bounds of unsigned long long
enum e1 {
// lower bound of llu
E1,
E2,
// upper bound of lld
E3 = 9223372036854775807,
// excceeding upper bound of lld
E4,
// lower bound of lld
E5 = -9223372036854775808,
// upper bound of llu
E6 = 18446744073709551615,
// calculating with upper bound of llu and upper bound of lld
E7 = E6 - E3,
// moving within space of llu
E8 = E6 - 1
};
int main() {
if (E1 != 0) {
goto ERROR;
}
if (E2 != 1) {
goto ERROR;
}
if (E3 != 9223372036854775807) {
goto ERROR;
}
if (E4 != 9223372036854775808) {
goto ERROR;
}
if (E5 != -9223372036854775808) {
goto ERROR;
}
if (E6 != 18446744073709551615){
goto ERROR;
}
if (E7 != 9223372036854775808){
goto ERROR;
}
if (E8 != 18446744073709551614){
goto ERROR;
}
return 0;
ERROR:
return 1;
}
|
92bd734273e14ca1ef5933f7d61caa459ecae05b
|
56df6683865fd9319b389afd6dd4a922299da593
|
/source/serials/metacall_serial/include/metacall_serial/metacall_serial_impl.h
|
489c4b31a9e99e7b5ca560ceba1d3984bc4c1e71
|
[
"Python-2.0",
"GPL-2.0-or-later",
"MPL-1.1",
"NCSA",
"LicenseRef-scancode-proprietary-license",
"GPL-1.0-or-later",
"BSD-3-Clause",
"MPL-2.0",
"Ruby",
"BSD-2-Clause",
"MIT",
"Apache-2.0"
] |
permissive
|
metacall/core
|
4f36fe0b13924853aab6d0f053285b649398cc1d
|
419ffb573b17501c91662f0f161032bb19ea1ab3
|
refs/heads/develop
| 2023-08-23T10:19:30.898387
| 2023-08-10T18:39:08
| 2023-08-10T18:39:08
| 163,221,062
| 1,391
| 167
|
Apache-2.0
| 2023-09-13T23:49:43
| 2018-12-26T22:02:57
|
C
|
UTF-8
|
C
| false
| false
| 2,387
|
h
|
metacall_serial_impl.h
|
/*
* Serial Library by Parra Studios
* Copyright (C) 2016 - 2022 Vicente Eduardo Ferrer Garcia <vic798@gmail.com>
*
* A cross-platform library for managing multiple serialization and deserialization formats.
*
*/
#ifndef METACALL_SERIAL_IMPL_H
#define METACALL_SERIAL_IMPL_H 1
/* -- Headers -- */
#include <metacall_serial/metacall_serial_api.h>
#include <serial/serial_interface.h>
#ifdef __cplusplus
extern "C" {
#endif
/* -- Methods -- */
/**
* @brief
* Retrieve extension supported by MetaCall Native Format implementation
*
* @return
* Returns constant string representing serial extension
*
*/
METACALL_SERIAL_API const char *metacall_serial_impl_extension(void);
/**
* @brief
* Initialize MetaCall Native Format document implementation
*
* @return
* Returns pointer to serial document implementation on success, null pointer otherwise
*
*/
METACALL_SERIAL_API serial_handle metacall_serial_impl_initialize(memory_allocator allocator);
/**
* @brief
* Serialize with MetaCall Native Format document implementation @impl
*
* @param[in] handle
* Pointer to the serial document implementation
*
* @param[in] v
* Reference to the value is going to be serialized
*
* @param[out] size
* Size in bytes of the return buffer
*
* @return
* String with the value serialized on correct serialization, null otherwise
*
*/
METACALL_SERIAL_API char *metacall_serial_impl_serialize(serial_handle handle, value v, size_t *size);
/**
* @brief
* Deserialize with MetaCall Native Format document implementation @handle
*
* @param[in] handle
* Pointer to the serial document implementation
*
* @param[in] buffer
* Reference to the string is going to be deserialized
*
* @param[in] size
* Size in bytes of the string @buffer
*
* @return
* Pointer to value deserialized on correct serialization, null otherwise
*
*/
METACALL_SERIAL_API value metacall_serial_impl_deserialize(serial_handle handle, const char *buffer, size_t size);
/**
* @brief
* Destroy MetaCall Native Format document implementation
*
* @return
* Returns zero on correct destruction, distinct from zero otherwise
*
*/
METACALL_SERIAL_API int metacall_serial_impl_destroy(serial_handle handle);
#ifdef __cplusplus
}
#endif
#endif /* METACALL_SERIAL_IMPL_H */
|
173e3058ca9b47dbf7244e170d5da4770f523bea
|
971b2cea2d1c3001aadc8ca1a48110b7db1ed5f2
|
/deps/abc/src/aig/gia/giaSwitch.c
|
4722ef0f59fdbc8aa2ebd7bd9917227d3bd51adc
|
[
"MIT-Modern-Variant",
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
emsec/hal
|
70ad2921739967d914dd458984bd7d6d497d3b0a
|
e4fae37bec9168a61100eacfda37a1f291b4d0be
|
refs/heads/master
| 2023-09-02T20:27:32.909426
| 2023-09-01T13:03:24
| 2023-09-01T13:03:24
| 169,076,171
| 510
| 72
|
MIT
| 2023-09-01T13:03:26
| 2019-02-04T12:37:20
|
C++
|
UTF-8
|
C
| false
| false
| 26,114
|
c
|
giaSwitch.c
|
/**CFile****************************************************************
FileName [giaSwitch.c]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Scalable AIG package.]
Synopsis [Computing switching activity.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: giaSwitch.c,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#include "giaAig.h"
#include "base/main/main.h"
ABC_NAMESPACE_IMPL_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
// switching estimation parameters
typedef struct Gia_ParSwi_t_ Gia_ParSwi_t;
struct Gia_ParSwi_t_
{
// user-controlled parameters
int nWords; // the number of machine words
int nIters; // the number of timeframes
int nPref; // the number of first timeframes to skip
int nRandPiFactor; // PI trans prob (-1=3/8; 0=1/2; 1=1/4; 2=1/8, etc)
int fProbOne; // collect probability of one
int fProbTrans; // collect probatility of Swiing
int fVerbose; // enables verbose output
};
typedef struct Gia_ManSwi_t_ Gia_ManSwi_t;
struct Gia_ManSwi_t_
{
Gia_Man_t * pAig;
Gia_ParSwi_t * pPars;
int nWords;
// simulation information
unsigned * pDataSim; // simulation data
unsigned * pDataSimCis; // simulation data for CIs
unsigned * pDataSimCos; // simulation data for COs
int * pData1; // switching data
};
static inline unsigned * Gia_SwiData( Gia_ManSwi_t * p, int i ) { return p->pDataSim + i * p->nWords; }
static inline unsigned * Gia_SwiDataCi( Gia_ManSwi_t * p, int i ) { return p->pDataSimCis + i * p->nWords; }
static inline unsigned * Gia_SwiDataCo( Gia_ManSwi_t * p, int i ) { return p->pDataSimCos + i * p->nWords; }
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis [This procedure sets default parameters.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Gia_ManSetDefaultParamsSwi( Gia_ParSwi_t * p )
{
memset( p, 0, sizeof(Gia_ParSwi_t) );
p->nWords = 10; // the number of machine words of simulatation data
p->nIters = 48; // the number of all timeframes to simulate
p->nPref = 16; // the number of first timeframes to skip when computing switching
p->nRandPiFactor = 0; // primary input transition probability (-1=3/8; 0=1/2; 1=1/4; 2=1/8, etc)
p->fProbOne = 0; // compute probability of signal being one (if 0, compute probability of switching)
p->fProbTrans = 1; // compute signal transition probability (if 0, compute transition probability using probability of being one)
p->fVerbose = 0; // enables verbose output
}
/**Function*************************************************************
Synopsis [Creates fast simulation manager.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Gia_ManSwi_t * Gia_ManSwiCreate( Gia_Man_t * pAig, Gia_ParSwi_t * pPars )
{
Gia_ManSwi_t * p;
p = ABC_ALLOC( Gia_ManSwi_t, 1 );
memset( p, 0, sizeof(Gia_ManSwi_t) );
p->pAig = Gia_ManFront( pAig );
p->pPars = pPars;
p->nWords = pPars->nWords;
p->pDataSim = ABC_ALLOC( unsigned, p->nWords * p->pAig->nFront );
p->pDataSimCis = ABC_ALLOC( unsigned, p->nWords * Gia_ManCiNum(p->pAig) );
p->pDataSimCos = ABC_ALLOC( unsigned, p->nWords * Gia_ManCoNum(p->pAig) );
p->pData1 = ABC_CALLOC( int, Gia_ManObjNum(pAig) );
return p;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
void Gia_ManSwiDelete( Gia_ManSwi_t * p )
{
Gia_ManStop( p->pAig );
ABC_FREE( p->pData1 );
ABC_FREE( p->pDataSim );
ABC_FREE( p->pDataSimCis );
ABC_FREE( p->pDataSimCos );
ABC_FREE( p );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoRandom( Gia_ManSwi_t * p, unsigned * pInfo, int nProbNum )
{
unsigned Mask = 0;
int w, i;
if ( nProbNum == -1 )
{ // 3/8 = 1/4 + 1/8
Mask = (Gia_ManRandom( 0 ) & Gia_ManRandom( 0 )) |
(Gia_ManRandom( 0 ) & Gia_ManRandom( 0 ) & Gia_ManRandom( 0 ));
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] ^= Mask;
}
else if ( nProbNum > 0 )
{
Mask = Gia_ManRandom( 0 );
for ( i = 0; i < nProbNum; i++ )
Mask &= Gia_ManRandom( 0 );
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] ^= Mask;
}
else if ( nProbNum == 0 )
{
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = Gia_ManRandom( 0 );
}
else
assert( 0 );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoRandomShift( Gia_ManSwi_t * p, unsigned * pInfo, int nProbNum )
{
unsigned Mask = 0;
int w, i;
if ( nProbNum == -1 )
{ // 3/8 = 1/4 + 1/8
Mask = (Gia_ManRandom( 0 ) & Gia_ManRandom( 0 )) |
(Gia_ManRandom( 0 ) & Gia_ManRandom( 0 ) & Gia_ManRandom( 0 ));
}
else if ( nProbNum >= 0 )
{
Mask = Gia_ManRandom( 0 );
for ( i = 0; i < nProbNum; i++ )
Mask &= Gia_ManRandom( 0 );
}
else
assert( 0 );
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = (pInfo[w] << 16) | ((pInfo[w] ^ Mask) & 0xffff);
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoZero( Gia_ManSwi_t * p, unsigned * pInfo )
{
int w;
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = 0;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoOne( Gia_ManSwi_t * p, unsigned * pInfo )
{
int w;
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = ~0;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoCopy( Gia_ManSwi_t * p, unsigned * pInfo, unsigned * pInfo0 )
{
int w;
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = pInfo0[w];
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoCopyShift( Gia_ManSwi_t * p, unsigned * pInfo, unsigned * pInfo0 )
{
int w;
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = (pInfo[w] << 16) | (pInfo0[w] & 0xffff);
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimulateCi( Gia_ManSwi_t * p, Gia_Obj_t * pObj, int iCi )
{
unsigned * pInfo = Gia_SwiData( p, Gia_ObjValue(pObj) );
unsigned * pInfo0 = Gia_SwiDataCi( p, iCi );
int w;
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = pInfo0[w];
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimulateCo( Gia_ManSwi_t * p, int iCo, Gia_Obj_t * pObj )
{
unsigned * pInfo = Gia_SwiDataCo( p, iCo );
unsigned * pInfo0 = Gia_SwiData( p, Gia_ObjDiff0(pObj) );
int w;
if ( Gia_ObjFaninC0(pObj) )
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = ~pInfo0[w];
else
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = pInfo0[w];
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimulateNode( Gia_ManSwi_t * p, Gia_Obj_t * pObj )
{
unsigned * pInfo = Gia_SwiData( p, Gia_ObjValue(pObj) );
unsigned * pInfo0 = Gia_SwiData( p, Gia_ObjDiff0(pObj) );
unsigned * pInfo1 = Gia_SwiData( p, Gia_ObjDiff1(pObj) );
int w;
if ( Gia_ObjFaninC0(pObj) )
{
if ( Gia_ObjFaninC1(pObj) )
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = ~(pInfo0[w] | pInfo1[w]);
else
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = ~pInfo0[w] & pInfo1[w];
}
else
{
if ( Gia_ObjFaninC1(pObj) )
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = pInfo0[w] & ~pInfo1[w];
else
for ( w = p->nWords-1; w >= 0; w-- )
pInfo[w] = pInfo0[w] & pInfo1[w];
}
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoInit( Gia_ManSwi_t * p )
{
int i = 0;
for ( ; i < Gia_ManPiNum(p->pAig); i++ )
Gia_ManSwiSimInfoRandom( p, Gia_SwiDataCi(p, i), 0 );
for ( ; i < Gia_ManCiNum(p->pAig); i++ )
Gia_ManSwiSimInfoZero( p, Gia_SwiDataCi(p, i) );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoTransfer( Gia_ManSwi_t * p, int nProbNum )
{
int i = 0, nShift = Gia_ManPoNum(p->pAig)-Gia_ManPiNum(p->pAig);
for ( ; i < Gia_ManPiNum(p->pAig); i++ )
Gia_ManSwiSimInfoRandom( p, Gia_SwiDataCi(p, i), nProbNum );
for ( ; i < Gia_ManCiNum(p->pAig); i++ )
Gia_ManSwiSimInfoCopy( p, Gia_SwiDataCi(p, i), Gia_SwiDataCo(p, nShift+i) );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimInfoTransferShift( Gia_ManSwi_t * p, int nProbNum )
{
int i = 0, nShift = Gia_ManPoNum(p->pAig)-Gia_ManPiNum(p->pAig);
for ( ; i < Gia_ManPiNum(p->pAig); i++ )
Gia_ManSwiSimInfoRandomShift( p, Gia_SwiDataCi(p, i), nProbNum );
for ( ; i < Gia_ManCiNum(p->pAig); i++ )
Gia_ManSwiSimInfoCopyShift( p, Gia_SwiDataCi(p, i), Gia_SwiDataCo(p, nShift+i) );
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline int Gia_ManSwiSimInfoCountOnes( Gia_ManSwi_t * p, int iPlace )
{
unsigned * pInfo;
int w, Counter = 0;
pInfo = Gia_SwiData( p, iPlace );
for ( w = p->nWords-1; w >= 0; w-- )
Counter += Gia_WordCountOnes( pInfo[w] );
return Counter;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline int Gia_ManSwiSimInfoCountTrans( Gia_ManSwi_t * p, int iPlace )
{
unsigned * pInfo;
int w, Counter = 0;
pInfo = Gia_SwiData( p, iPlace );
for ( w = p->nWords-1; w >= 0; w-- )
Counter += 2*Gia_WordCountOnes( (pInfo[w] ^ (pInfo[w] >> 16)) & 0xffff );
return Counter;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Gia_ManSwiSimulateRound( Gia_ManSwi_t * p, int fCount )
{
Gia_Obj_t * pObj;
int i;//, iCis = 0, iCos = 0;
assert( p->pAig->nFront > 0 );
assert( Gia_ManConst0(p->pAig)->Value == 0 );
Gia_ManSwiSimInfoZero( p, Gia_SwiData(p, 0) );
Gia_ManForEachObj1( p->pAig, pObj, i )
{
if ( Gia_ObjIsAndOrConst0(pObj) )
{
assert( Gia_ObjValue(pObj) < p->pAig->nFront );
Gia_ManSwiSimulateNode( p, pObj );
}
else if ( Gia_ObjIsCo(pObj) )
{
assert( Gia_ObjValue(pObj) == GIA_NONE );
// Gia_ManSwiSimulateCo( p, iCos++, pObj );
Gia_ManSwiSimulateCo( p, Gia_ObjCioId(pObj), pObj );
}
else // if ( Gia_ObjIsCi(pObj) )
{
assert( Gia_ObjValue(pObj) < p->pAig->nFront );
// Gia_ManSwiSimulateCi( p, pObj, iCis++ );
Gia_ManSwiSimulateCi( p, pObj, Gia_ObjCioId(pObj) );
}
if ( fCount && !Gia_ObjIsCo(pObj) )
{
if ( p->pPars->fProbTrans )
p->pData1[i] += Gia_ManSwiSimInfoCountTrans( p, Gia_ObjValue(pObj) );
else
p->pData1[i] += Gia_ManSwiSimInfoCountOnes( p, Gia_ObjValue(pObj) );
}
}
// assert( Gia_ManCiNum(p->pAig) == iCis );
// assert( Gia_ManCoNum(p->pAig) == iCos );
}
/**Function*************************************************************
Synopsis [Computes switching activity of one node.]
Description [Uses the formula: Switching = 2 * nOnes * nZeros / (nTotal ^ 2) ]
SideEffects []
SeeAlso []
***********************************************************************/
float Gia_ManSwiComputeSwitching( int nOnes, int nSimWords )
{
int nTotal = 32 * nSimWords;
return (float)2.0 * nOnes / nTotal * (nTotal - nOnes) / nTotal;
}
/**Function*************************************************************
Synopsis [Computes switching activity of one node.]
Description [Uses the formula: Switching = 2 * nOnes * nZeros / (nTotal ^ 2) ]
SideEffects []
SeeAlso []
***********************************************************************/
float Gia_ManSwiComputeProbOne( int nOnes, int nSimWords )
{
int nTotal = 32 * nSimWords;
return (float)nOnes / nTotal;
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Gia_ManSwiSimulate( Gia_Man_t * pAig, Gia_ParSwi_t * pPars )
{
Gia_ManSwi_t * p;
Gia_Obj_t * pObj;
Vec_Int_t * vSwitching;
float * pSwitching;
int i;
abctime clk, clkTotal = Abc_Clock();
if ( pPars->fProbOne && pPars->fProbTrans )
printf( "Conflict of options: Can either compute probability of 1, or probability of switching by observing transitions.\n" );
// create manager
clk = Abc_Clock();
p = Gia_ManSwiCreate( pAig, pPars );
if ( pPars->fVerbose )
{
printf( "Obj = %8d (%8d). F = %6d. ",
pAig->nObjs, Gia_ManCiNum(pAig) + Gia_ManAndNum(pAig), p->pAig->nFront );
printf( "AIG = %7.2f MB. F-mem = %7.2f MB. Other = %7.2f MB. ",
12.0*Gia_ManObjNum(p->pAig)/(1<<20),
4.0*p->nWords*p->pAig->nFront/(1<<20),
4.0*p->nWords*(Gia_ManCiNum(p->pAig) + Gia_ManCoNum(p->pAig))/(1<<20) );
ABC_PRT( "Time", Abc_Clock() - clk );
}
// perform simulation
Gia_ManRandom( 1 );
Gia_ManSwiSimInfoInit( p );
for ( i = 0; i < pPars->nIters; i++ )
{
Gia_ManSwiSimulateRound( p, i >= pPars->nPref );
if ( i == pPars->nIters - 1 )
break;
if ( pPars->fProbTrans )
Gia_ManSwiSimInfoTransferShift( p, pPars->nRandPiFactor );
else
Gia_ManSwiSimInfoTransfer( p, pPars->nRandPiFactor );
}
if ( pPars->fVerbose )
{
printf( "Simulated %d frames with %d words. ", pPars->nIters, pPars->nWords );
ABC_PRT( "Simulation time", Abc_Clock() - clkTotal );
}
// derive the result
vSwitching = Vec_IntStart( Gia_ManObjNum(pAig) );
pSwitching = (float *)vSwitching->pArray;
if ( pPars->fProbOne )
{
Gia_ManForEachObj( pAig, pObj, i )
pSwitching[i] = Gia_ManSwiComputeProbOne( p->pData1[i], pPars->nWords*(pPars->nIters-pPars->nPref) );
Gia_ManForEachCo( pAig, pObj, i )
{
if ( Gia_ObjFaninC0(pObj) )
pSwitching[Gia_ObjId(pAig,pObj)] = (float)1.0-pSwitching[Gia_ObjId(pAig,Gia_ObjFanin0(pObj))];
else
pSwitching[Gia_ObjId(pAig,pObj)] = pSwitching[Gia_ObjId(pAig,Gia_ObjFanin0(pObj))];
}
}
else if ( pPars->fProbTrans )
{
Gia_ManForEachObj( pAig, pObj, i )
pSwitching[i] = Gia_ManSwiComputeProbOne( p->pData1[i], pPars->nWords*(pPars->nIters-pPars->nPref) );
}
else
{
Gia_ManForEachObj( pAig, pObj, i )
pSwitching[i] = Gia_ManSwiComputeSwitching( p->pData1[i], pPars->nWords*(pPars->nIters-pPars->nPref) );
}
/*
printf( "PI: " );
Gia_ManForEachPi( pAig, pObj, i )
printf( "%d=%d (%f) ", i, p->pData1[Gia_ObjId(pAig,pObj)], pSwitching[Gia_ObjId(pAig,pObj)] );
printf( "\n" );
printf( "LO: " );
Gia_ManForEachRo( pAig, pObj, i )
printf( "%d=%d (%f) ", i, p->pData1[Gia_ObjId(pAig,pObj)], pSwitching[Gia_ObjId(pAig,pObj)] );
printf( "\n" );
printf( "PO: " );
Gia_ManForEachPo( pAig, pObj, i )
printf( "%d=%d (%f) ", i, p->pData1[Gia_ObjId(pAig,pObj)], pSwitching[Gia_ObjId(pAig,pObj)] );
printf( "\n" );
printf( "LI: " );
Gia_ManForEachRi( pAig, pObj, i )
printf( "%d=%d (%f) ", i, p->pData1[Gia_ObjId(pAig,pObj)], pSwitching[Gia_ObjId(pAig,pObj)] );
printf( "\n" );
*/
Gia_ManSwiDelete( p );
return vSwitching;
}
/**Function*************************************************************
Synopsis [Computes probability of switching (or of being 1).]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Int_t * Gia_ManComputeSwitchProbs( Gia_Man_t * pGia, int nFrames, int nPref, int fProbOne )
{
Gia_ParSwi_t Pars, * pPars = &Pars;
// set the default parameters
Gia_ManSetDefaultParamsSwi( pPars );
// override some of the defaults
pPars->nIters = nFrames; // set number of total timeframes
if ( Abc_FrameReadFlag("seqsimframes") )
pPars->nIters = atoi( Abc_FrameReadFlag("seqsimframes") );
pPars->nPref = nPref; // set number of first timeframes to skip
// decide what should be computed
if ( fProbOne )
{
// if the user asked to compute propability of 1, we do not need transition information
pPars->fProbOne = 1; // enable computing probabiblity of being one
pPars->fProbTrans = 0; // disable computing transition probability
}
else
{
// if the user asked for transition propabability, we do not need to compute probability of 1
pPars->fProbOne = 0; // disable computing probabiblity of being one
pPars->fProbTrans = 1; // enable computing transition probability
}
// perform the computation of switching activity
return Gia_ManSwiSimulate( pGia, pPars );
}
Vec_Int_t * Saig_ManComputeSwitchProbs( Aig_Man_t * pAig, int nFrames, int nPref, int fProbOne )
{
Vec_Int_t * vSwitching, * vResult;
Gia_Man_t * p;
Aig_Obj_t * pObj;
int i;
// translate AIG into the intermediate form (takes care of choices if present!)
p = Gia_ManFromAigSwitch( pAig );
// perform the computation of switching activity
vSwitching = Gia_ManComputeSwitchProbs( p, nFrames, nPref, fProbOne );
// transfer the computed result to the original AIG
vResult = Vec_IntStart( Aig_ManObjNumMax(pAig) );
Aig_ManForEachObj( pAig, pObj, i )
{
// if ( Aig_ObjIsCo(pObj) )
// printf( "%d=%f\n", i, Abc_Int2Float( Vec_IntEntry(vSwitching, Abc_Lit2Var(pObj->iData)) ) );
Vec_IntWriteEntry( vResult, i, Vec_IntEntry(vSwitching, Abc_Lit2Var(pObj->iData)) );
}
// delete intermediate results
Vec_IntFree( vSwitching );
Gia_ManStop( p );
return vResult;
}
/**Function*************************************************************
Synopsis [Computes probability of switching (or of being 1).]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
float Gia_ManEvaluateSwitching( Gia_Man_t * p )
{
Gia_Obj_t * pObj;
float SwitchTotal = 0.0;
int i;
assert( p->pSwitching );
ABC_FREE( p->pRefs );
Gia_ManCreateRefs( p );
Gia_ManForEachObj( p, pObj, i )
SwitchTotal += (float)Gia_ObjRefNum(p, pObj) * p->pSwitching[i] / 255;
return SwitchTotal;
}
/**Function*************************************************************
Synopsis [Computes probability of switching (or of being 1).]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
/*
float Gia_ManComputeSwitching( Gia_Man_t * p, int nFrames, int nPref, int fProbOne )
{
Gia_Man_t * pDfs;
Gia_Obj_t * pObj, * pObjDfs;
Vec_Int_t * vSwitching;
float * pSwitching, Switch, SwitchTotal = 0.0;
int i;
// derives the DFS ordered AIG
if ( Gia_ManHasMapping(p) )
Gia_ManSetRefsMapped(p);
else
Gia_ManCreateRefs( p );
// pDfs = Gia_ManDupOrderDfs( p );
pDfs = Gia_ManDup( p );
assert( Gia_ManObjNum(pDfs) == Gia_ManObjNum(p) );
// perform the computation of switching activity
vSwitching = Gia_ManComputeSwitchProbs( pDfs, nFrames, nPref, fProbOne );
// transfer the computed result to the original AIG
ABC_FREE( p->pSwitching );
p->pSwitching = ABC_CALLOC( unsigned char, Gia_ManObjNum(p) );
pSwitching = (float *)vSwitching->pArray;
Gia_ManForEachObj( p, pObj, i )
{
pObjDfs = Gia_ObjFromLit( pDfs, pObj->Value );
Switch = pSwitching[ Gia_ObjId(pDfs, pObjDfs) ];
p->pSwitching[i] = (char)((Switch >= 1.0) ? 255 : (int)((0.002 + Switch) * 255)); // 0.00196 = (1/255)/2
if ( Gia_ObjIsCi(pObj) || (Gia_ObjIsAnd(pObj) && (!Gia_ManHasMapping(p) || Gia_ObjIsLut(p, i))) )
{
SwitchTotal += (float)Gia_ObjRefNum(p, pObj) * p->pSwitching[i] / 255;
// printf( "%d = %.2f\n", i, (float)Gia_ObjRefNum(p, pObj) * p->pSwitching[i] / 255 );
}
}
Vec_IntFree( vSwitching );
Gia_ManStop( pDfs );
return SwitchTotal;
}
*/
float Gia_ManComputeSwitching( Gia_Man_t * p, int nFrames, int nPref, int fProbOne )
{
Vec_Int_t * vSwitching = Gia_ManComputeSwitchProbs( p, nFrames, nPref, fProbOne );
float * pSwi = (float *)Vec_IntArray(vSwitching), SwiTotal = 0;
Gia_Obj_t * pObj;
int i, k, iFan;
if ( Gia_ManHasMapping(p) )
{
Gia_ManForEachLut( p, i )
Gia_LutForEachFanin( p, i, iFan, k )
SwiTotal += pSwi[iFan];
}
else
{
Gia_ManForEachAnd( p, pObj, i )
SwiTotal += pSwi[Gia_ObjFaninId0(pObj, i)] + pSwi[Gia_ObjFaninId1(pObj, i)];
}
if ( 0 )
{
Gia_ManForEachObj( p, pObj, i )
{
printf( "Switch %6.2f ", pSwi[i] );
Gia_ObjPrint( p, pObj );
}
}
Vec_IntFree( vSwitching );
return SwiTotal;
}
/**Function*************************************************************
Synopsis [Determine probability of being 1 at the outputs.]
Description []
SideEffects []
SeeAlso []
***********************************************************************/
Vec_Flt_t * Gia_ManPrintOutputProb( Gia_Man_t * p )
{
Vec_Flt_t * vSimData;
Gia_Man_t * pDfs = Gia_ManDup( p );
assert( Gia_ManObjNum(pDfs) == Gia_ManObjNum(p) );
vSimData = (Vec_Flt_t *)Gia_ManComputeSwitchProbs( pDfs, (Gia_ManRegNum(p) ? 16 : 1), 0, 1 );
Gia_ManStop( pDfs );
return vSimData;
}
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
ABC_NAMESPACE_IMPL_END
|
9338c6e8fb76eb64422bdee054d5f81e4c92b976
|
95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5
|
/Engine/lib/curl/lib/psl.c
|
60c98a4ca45ec50ee4767d70792b62e5e053d9f4
|
[
"MIT",
"LicenseRef-scancode-unknown",
"curl"
] |
permissive
|
TorqueGameEngines/Torque3D
|
4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8
|
a445a4364664e299196bd551d213844486080145
|
refs/heads/development
| 2023-09-03T12:40:40.658487
| 2023-08-24T14:44:43
| 2023-08-24T14:44:43
| 267,440,108
| 1,192
| 178
|
MIT
| 2023-09-13T14:28:16
| 2020-05-27T22:35:54
|
C++
|
UTF-8
|
C
| false
| false
| 3,312
|
c
|
psl.c
|
/***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, 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.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.
*
* SPDX-License-Identifier: curl
*
***************************************************************************/
#include "curl_setup.h"
#include <curl/curl.h>
#ifdef USE_LIBPSL
#include "psl.h"
#include "share.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
void Curl_psl_destroy(struct PslCache *pslcache)
{
if(pslcache->psl) {
if(pslcache->dynamic)
psl_free((psl_ctx_t *) pslcache->psl);
pslcache->psl = NULL;
pslcache->dynamic = FALSE;
}
}
static time_t now_seconds(void)
{
struct curltime now = Curl_now();
return now.tv_sec;
}
const psl_ctx_t *Curl_psl_use(struct Curl_easy *easy)
{
struct PslCache *pslcache = easy->psl;
const psl_ctx_t *psl;
time_t now;
if(!pslcache)
return NULL;
Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED);
now = now_seconds();
if(!pslcache->psl || pslcache->expires <= now) {
/* Let a chance to other threads to do the job: avoids deadlock. */
Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
/* Update cache: this needs an exclusive lock. */
Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SINGLE);
/* Recheck in case another thread did the job. */
now = now_seconds();
if(!pslcache->psl || pslcache->expires <= now) {
bool dynamic = FALSE;
time_t expires = TIME_T_MAX;
#if defined(PSL_VERSION_NUMBER) && PSL_VERSION_NUMBER >= 0x001000
psl = psl_latest(NULL);
dynamic = psl != NULL;
/* Take care of possible time computation overflow. */
expires = now < TIME_T_MAX - PSL_TTL? now + PSL_TTL: TIME_T_MAX;
/* Only get the built-in PSL if we do not already have the "latest". */
if(!psl && !pslcache->dynamic)
#endif
psl = psl_builtin();
if(psl) {
Curl_psl_destroy(pslcache);
pslcache->psl = psl;
pslcache->dynamic = dynamic;
pslcache->expires = expires;
}
}
Curl_share_unlock(easy, CURL_LOCK_DATA_PSL); /* Release exclusive lock. */
Curl_share_lock(easy, CURL_LOCK_DATA_PSL, CURL_LOCK_ACCESS_SHARED);
}
psl = pslcache->psl;
if(!psl)
Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
return psl;
}
void Curl_psl_release(struct Curl_easy *easy)
{
Curl_share_unlock(easy, CURL_LOCK_DATA_PSL);
}
#endif /* USE_LIBPSL */
|
aadbf146c1af99fdb07886eee5ca9bbd857ea183
|
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
|
/sysutils/logrotate/patches/patch-config.c
|
67a45fba540a4f79dcbf120738455dcc70c16332
|
[] |
no_license
|
NetBSD/pkgsrc
|
a0732c023519650ef821ab89c23ab6ab59e25bdb
|
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
|
refs/heads/trunk
| 2023-09-01T07:40:12.138283
| 2023-09-01T05:25:19
| 2023-09-01T05:25:19
| 88,439,572
| 321
| 138
| null | 2023-07-12T22:34:14
| 2017-04-16T20:04:15
| null |
UTF-8
|
C
| false
| false
| 447
|
c
|
patch-config.c
|
$NetBSD: patch-config.c,v 1.7 2020/10/08 07:50:51 wiz Exp $
Fix NetBSD compilation.
--- config.c.orig 2020-07-10 08:22:39.000000000 +0000
+++ config.c
@@ -19,7 +19,13 @@
#include <wctype.h>
#include <fnmatch.h>
#include <sys/mman.h>
-#include <libgen.h>
+#ifndef _LIBGEN_H_
+# include <libgen.h>
+#endif
+
+#ifndef secure_getenv
+#define secure_getenv getenv
+#endif
#if !defined(PATH_MAX) && defined(__FreeBSD__)
#include <sys/param.h>
|
851f57c507351f9f4a93c4b5c5e9c41b8aec2d80
|
ca2125d3a3a4aa7167326a09ff3adae4a03c90fe
|
/Graphics/Archiver/interface/ArchiverFactoryLoader.h
|
0351536e7ee936ba1e8a94769d2fd4a88ded6c8d
|
[
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-nvidia-2002",
"BSD-2-Clause"
] |
permissive
|
DiligentGraphics/DiligentCore
|
9e124fee53bda1b280b3aa8c11ef1d3dc577d630
|
2ebd6cd1b3221a50d7f11f77ac51023a2b33697f
|
refs/heads/master
| 2023-08-28T14:13:18.861391
| 2023-08-24T00:52:40
| 2023-08-24T00:52:40
| 44,292,712
| 545
| 180
|
Apache-2.0
| 2023-09-11T14:44:45
| 2015-10-15T03:56:34
|
C++
|
UTF-8
|
C
| false
| false
| 2,373
|
h
|
ArchiverFactoryLoader.h
|
/*
* Copyright 2019-2022 Diligent Graphics LLC
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#pragma once
#include "ArchiverFactory.h"
#if PLATFORM_ANDROID || PLATFORM_LINUX || PLATFORM_MACOS || PLATFORM_IOS || PLATFORM_TVOS || (PLATFORM_WIN32 && !defined(_MSC_VER))
// https://gcc.gnu.org/wiki/Visibility
# define API_QUALIFIER __attribute__((visibility("default")))
#elif PLATFORM_WIN32 || PLATFORM_UNIVERSAL_WINDOWS
# define API_QUALIFIER
#else
# error Unsupported platform
#endif
#if ENGINE_DLL && PLATFORM_WIN32 && defined(_MSC_VER)
# include "../../GraphicsEngine/interface/LoadEngineDll.h"
# define EXPLICITLY_LOAD_ARCHIVER_FACTORY_DLL 1
#endif
DILIGENT_BEGIN_NAMESPACE(Diligent)
#if EXPLICITLY_LOAD_ARCHIVER_FACTORY_DLL
typedef struct IArchiverFactory* (*GetArchiverFactoryType)();
inline GetArchiverFactoryType DILIGENT_GLOBAL_FUNCTION(LoadArchiverFactory)()
{
return (GetArchiverFactoryType)LoadEngineDll("Archiver", "GetArchiverFactory");
}
#else
API_QUALIFIER
struct IArchiverFactory* DILIGENT_GLOBAL_FUNCTION(GetArchiverFactory)();
#endif
DILIGENT_END_NAMESPACE // namespace Diligent
|
2d3d9a3ca06bd84e1d6845aad14f524ad8c9886d
|
83e7dc1281874779c46dfadcc15b2bb66d8e599c
|
/examples/widgets/checkbox/lv_example_checkbox_1.c
|
cfce553f6c57f67a9d2724e61dbc85eb9cdd909e
|
[
"MIT"
] |
permissive
|
lvgl/lvgl
|
7d51d6774d6ac71df7101fc7ded56fea4b70be01
|
5c984b4a5364b6455966eb3a860153806c51626f
|
refs/heads/master
| 2023-08-30T22:39:20.283922
| 2023-08-30T19:55:29
| 2023-08-30T19:55:29
| 60,667,730
| 9,296
| 2,218
|
MIT
| 2023-09-14T17:59:34
| 2016-06-08T04:14:34
|
C
|
UTF-8
|
C
| false
| false
| 1,537
|
c
|
lv_example_checkbox_1.c
|
#include "../../lv_examples.h"
#if LV_USE_CHECKBOX && LV_BUILD_EXAMPLES
static void event_handler(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t * obj = lv_event_get_target(e);
if(code == LV_EVENT_VALUE_CHANGED) {
LV_UNUSED(obj);
const char * txt = lv_checkbox_get_text(obj);
const char * state = lv_obj_get_state(obj) & LV_STATE_CHECKED ? "Checked" : "Unchecked";
LV_UNUSED(txt);
LV_UNUSED(state);
LV_LOG_USER("%s: %s", txt, state);
}
}
void lv_example_checkbox_1(void)
{
lv_obj_set_flex_flow(lv_scr_act(), LV_FLEX_FLOW_COLUMN);
lv_obj_set_flex_align(lv_scr_act(), LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER);
lv_obj_t * cb;
cb = lv_checkbox_create(lv_scr_act());
lv_checkbox_set_text(cb, "Apple");
lv_obj_add_event(cb, event_handler, LV_EVENT_ALL, NULL);
cb = lv_checkbox_create(lv_scr_act());
lv_checkbox_set_text(cb, "Banana");
lv_obj_add_state(cb, LV_STATE_CHECKED);
lv_obj_add_event(cb, event_handler, LV_EVENT_ALL, NULL);
cb = lv_checkbox_create(lv_scr_act());
lv_checkbox_set_text(cb, "Lemon");
lv_obj_add_state(cb, LV_STATE_DISABLED);
lv_obj_add_event(cb, event_handler, LV_EVENT_ALL, NULL);
cb = lv_checkbox_create(lv_scr_act());
lv_obj_add_state(cb, LV_STATE_CHECKED | LV_STATE_DISABLED);
lv_checkbox_set_text(cb, "Melon\nand a new line");
lv_obj_add_event(cb, event_handler, LV_EVENT_ALL, NULL);
lv_obj_update_layout(cb);
}
#endif
|
4ea8f9a719c7de5211d65e2c78351423a2b39673
|
270937d32c2bc8e33622d96c045b43b8a23bc086
|
/ion/gfx/glfunctiontypes.h
|
6c1d4d99ad907576b56ec20776c05ebde715c4b2
|
[
"Apache-2.0"
] |
permissive
|
google/ion
|
32491fc26a0a2a5fd602e4008296ccba5017d689
|
514ce797458d02e7cd3a1b2d0b5c7ff8ccb5f5d1
|
refs/heads/master
| 2023-09-04T18:10:40.343013
| 2022-06-09T07:56:18
| 2022-06-09T07:56:18
| 50,387,855
| 1,651
| 132
|
Apache-2.0
| 2018-05-12T02:16:47
| 2016-01-25T23:13:46
|
C++
|
UTF-8
|
C
| false
| false
| 1,551
|
h
|
glfunctiontypes.h
|
/**
Copyright 2017 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ION_GFX_GLFUNCTIONTYPES_H_
#define ION_GFX_GLFUNCTIONTYPES_H_
#include "ion/portgfx/glheaders.h"
// These types are necessary to distinguish between types with overlapping
// values, e.g., GL_ZERO, GL_NONE, and GL_POINTS are the same number. Having
// specially named types allows TracingHelper determine which value to print.
typedef GLenum GLblendenum;
typedef GLenum GLstencilenum;
typedef GLint GLintenum;
typedef GLint GLtextureenum;
typedef GLbitfield GLmapaccess;
// These special types let TracingHelper know the type of pointer being passed.
typedef GLfloat GLfloat1;
typedef GLfloat GLfloat2;
typedef GLfloat GLfloat3;
typedef GLfloat GLfloat4;
typedef GLfloat GLmatrix2;
typedef GLfloat GLmatrix3;
typedef GLfloat GLmatrix4;
typedef GLint GLint1;
typedef GLint GLint2;
typedef GLint GLint3;
typedef GLint GLint4;
typedef GLuint GLuint1;
typedef GLuint GLuint2;
typedef GLuint GLuint3;
typedef GLuint GLuint4;
#endif // ION_GFX_GLFUNCTIONTYPES_H_
|
e4643aa7acfb00f9a5494b3bdffd5b150a6b55c4
|
fbef550c1f0206aac0582a58f7e3db945f442a9a
|
/extensions/doc/html.h
|
4c8810d471c92b7edb592398a6b9bcaa99508f92
|
[
"MIT"
] |
permissive
|
Hammerspoon/hammerspoon
|
0f03b4dd2ef3b44ea4c0a1cd0b94fcb513b5f2b7
|
0ccc9d07641a660140d1d2f05b76f682b501a0e8
|
refs/heads/master
| 2023-08-19T01:26:41.898873
| 2023-06-20T22:52:50
| 2023-06-20T22:52:50
| 24,956,772
| 11,379
| 676
|
MIT
| 2023-06-09T02:51:33
| 2014-10-08T19:24:44
|
Objective-C
|
UTF-8
|
C
| false
| false
| 1,981
|
h
|
html.h
|
/*
* Copyright (c) 2011, Vicent Marti
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND 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.
*/
#ifndef UPSKIRT_HTML_H
#define UPSKIRT_HTML_H
#include "markdown.h"
#include "buffer.h"
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
#endif
struct html_renderopt {
struct {
int header_count;
int current_level;
int level_offset;
} toc_data;
unsigned int flags;
/* extra callbacks */
void (*link_attributes)(struct buf *ob, const struct buf *url, void *self);
};
typedef enum {
HTML_SKIP_HTML = (1 << 0),
HTML_SKIP_STYLE = (1 << 1),
HTML_SKIP_IMAGES = (1 << 2),
HTML_SKIP_LINKS = (1 << 3),
HTML_EXPAND_TABS = (1 << 4),
HTML_SAFELINK = (1 << 5),
HTML_TOC = (1 << 6),
HTML_HARD_WRAP = (1 << 7),
HTML_USE_XHTML = (1 << 8),
HTML_ESCAPE = (1 << 9),
} html_render_mode;
typedef enum {
HTML_TAG_NONE = 0,
HTML_TAG_OPEN,
HTML_TAG_CLOSE,
} html_tag;
int
sdhtml_is_tag(const uint8_t *tag_data, size_t tag_size, const char *tagname);
extern void
sdhtml_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options_ptr, unsigned int render_flags);
extern void
sdhtml_toc_renderer(struct sd_callbacks *callbacks, struct html_renderopt *options_ptr);
extern void
sdhtml_smartypants(struct buf *ob, const uint8_t *text, size_t size);
#ifdef __cplusplus
}
#endif
#endif
|
46b583a73558d3f6e1e8312d1775dd418a7f8f1a
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/grpc/src/src/core/ext/upb-generated/envoy/extensions/filters/http/fault/v3/fault.upb.h
|
4a106be1ded73e9b4d4f5c70ae69ceeff3452471
|
[
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later",
"BSD-3-Clause",
"MPL-2.0"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C
| false
| false
| 31,444
|
h
|
fault.upb.h
|
/* This file was generated by upbc (the upb compiler) from the input
* file:
*
* envoy/extensions/filters/http/fault/v3/fault.proto
*
* Do not edit -- your changes will be discarded when the file is
* regenerated. */
#ifndef ENVOY_EXTENSIONS_FILTERS_HTTP_FAULT_V3_FAULT_PROTO_UPB_H_
#define ENVOY_EXTENSIONS_FILTERS_HTTP_FAULT_V3_FAULT_PROTO_UPB_H_
#include "upb/msg_internal.h"
#include "upb/decode.h"
#include "upb/decode_fast.h"
#include "upb/encode.h"
#include "upb/port_def.inc"
#ifdef __cplusplus
extern "C" {
#endif
struct envoy_extensions_filters_http_fault_v3_FaultAbort;
struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort;
struct envoy_extensions_filters_http_fault_v3_HTTPFault;
typedef struct envoy_extensions_filters_http_fault_v3_FaultAbort envoy_extensions_filters_http_fault_v3_FaultAbort;
typedef struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort;
typedef struct envoy_extensions_filters_http_fault_v3_HTTPFault envoy_extensions_filters_http_fault_v3_HTTPFault;
extern const upb_MiniTable envoy_extensions_filters_http_fault_v3_FaultAbort_msginit;
extern const upb_MiniTable envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit;
extern const upb_MiniTable envoy_extensions_filters_http_fault_v3_HTTPFault_msginit;
struct envoy_config_route_v3_HeaderMatcher;
struct envoy_extensions_filters_common_fault_v3_FaultDelay;
struct envoy_extensions_filters_common_fault_v3_FaultRateLimit;
struct envoy_type_v3_FractionalPercent;
struct google_protobuf_UInt32Value;
extern const upb_MiniTable envoy_config_route_v3_HeaderMatcher_msginit;
extern const upb_MiniTable envoy_extensions_filters_common_fault_v3_FaultDelay_msginit;
extern const upb_MiniTable envoy_extensions_filters_common_fault_v3_FaultRateLimit_msginit;
extern const upb_MiniTable envoy_type_v3_FractionalPercent_msginit;
extern const upb_MiniTable google_protobuf_UInt32Value_msginit;
/* envoy.extensions.filters.http.fault.v3.FaultAbort */
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_new(upb_Arena* arena) {
return (envoy_extensions_filters_http_fault_v3_FaultAbort*)_upb_Message_New(&envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, arena);
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_parse(const char* buf, size_t size, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_FaultAbort* ret = envoy_extensions_filters_http_fault_v3_FaultAbort_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_parse_ex(const char* buf, size_t size,
const upb_ExtensionRegistry* extreg,
int options, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_FaultAbort* ret = envoy_extensions_filters_http_fault_v3_FaultAbort_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, extreg, options, arena) !=
kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_FaultAbort_serialize(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg, upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, 0, arena, &ptr, len);
return ptr;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_FaultAbort_serialize_ex(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg, int options,
upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, options, arena, &ptr, len);
return ptr;
}
typedef enum {
envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_http_status = 2,
envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_grpc_status = 5,
envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_header_abort = 4,
envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_NOT_SET = 0
} envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_oneofcases;
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_oneofcases envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_case(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return (envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_oneofcases)*UPB_PTR_AT(msg, UPB_SIZE(4, 4), int32_t);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_FaultAbort_has_http_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return _upb_getoneofcase(msg, UPB_SIZE(4, 4)) == 2;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_clear_http_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
UPB_WRITE_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), 0, UPB_SIZE(4, 4), envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_NOT_SET);
}
UPB_INLINE uint32_t envoy_extensions_filters_http_fault_v3_FaultAbort_http_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return UPB_READ_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), UPB_SIZE(4, 4), 2, _upb_UInt32_FromU(0u));
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_FaultAbort_has_percentage(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return _upb_hasbit(msg, 1);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_clear_percentage(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 8), const upb_Message*) = NULL;
}
UPB_INLINE const struct envoy_type_v3_FractionalPercent* envoy_extensions_filters_http_fault_v3_FaultAbort_percentage(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(12, 8), const struct envoy_type_v3_FractionalPercent*);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_FaultAbort_has_header_abort(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return _upb_getoneofcase(msg, UPB_SIZE(4, 4)) == 4;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_clear_header_abort(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
UPB_WRITE_ONEOF(msg, envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*, UPB_SIZE(8, 16), 0, UPB_SIZE(4, 4), envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_NOT_SET);
}
UPB_INLINE const envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_header_abort(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return UPB_READ_ONEOF(msg, const envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*, UPB_SIZE(8, 16), UPB_SIZE(4, 4), 4, NULL);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_FaultAbort_has_grpc_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return _upb_getoneofcase(msg, UPB_SIZE(4, 4)) == 5;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_clear_grpc_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
UPB_WRITE_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), 0, UPB_SIZE(4, 4), envoy_extensions_filters_http_fault_v3_FaultAbort_error_type_NOT_SET);
}
UPB_INLINE uint32_t envoy_extensions_filters_http_fault_v3_FaultAbort_grpc_status(const envoy_extensions_filters_http_fault_v3_FaultAbort* msg) {
return UPB_READ_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), UPB_SIZE(4, 4), 5, _upb_UInt32_FromU(0u));
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_set_http_status(envoy_extensions_filters_http_fault_v3_FaultAbort *msg, uint32_t value) {
UPB_WRITE_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), value, UPB_SIZE(4, 4), 2);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_set_percentage(envoy_extensions_filters_http_fault_v3_FaultAbort *msg, struct envoy_type_v3_FractionalPercent* value) {
_upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(12, 8), struct envoy_type_v3_FractionalPercent*) = value;
}
UPB_INLINE struct envoy_type_v3_FractionalPercent* envoy_extensions_filters_http_fault_v3_FaultAbort_mutable_percentage(envoy_extensions_filters_http_fault_v3_FaultAbort* msg, upb_Arena* arena) {
struct envoy_type_v3_FractionalPercent* sub = (struct envoy_type_v3_FractionalPercent*)envoy_extensions_filters_http_fault_v3_FaultAbort_percentage(msg);
if (sub == NULL) {
sub = (struct envoy_type_v3_FractionalPercent*)_upb_Message_New(&envoy_type_v3_FractionalPercent_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_FaultAbort_set_percentage(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_set_header_abort(envoy_extensions_filters_http_fault_v3_FaultAbort *msg, envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* value) {
UPB_WRITE_ONEOF(msg, envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*, UPB_SIZE(8, 16), value, UPB_SIZE(4, 4), 4);
}
UPB_INLINE struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_mutable_header_abort(envoy_extensions_filters_http_fault_v3_FaultAbort* msg, upb_Arena* arena) {
struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* sub = (struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*)envoy_extensions_filters_http_fault_v3_FaultAbort_header_abort(msg);
if (sub == NULL) {
sub = (struct envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*)_upb_Message_New(&envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_FaultAbort_set_header_abort(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_FaultAbort_set_grpc_status(envoy_extensions_filters_http_fault_v3_FaultAbort *msg, uint32_t value) {
UPB_WRITE_ONEOF(msg, uint32_t, UPB_SIZE(8, 16), value, UPB_SIZE(4, 4), 5);
}
/* envoy.extensions.filters.http.fault.v3.FaultAbort.HeaderAbort */
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_new(upb_Arena* arena) {
return (envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort*)_upb_Message_New(&envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, arena);
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_parse(const char* buf, size_t size, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* ret = envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_parse_ex(const char* buf, size_t size,
const upb_ExtensionRegistry* extreg,
int options, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* ret = envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, extreg, options, arena) !=
kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_serialize(const envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* msg, upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, 0, arena, &ptr, len);
return ptr;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_serialize_ex(const envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort* msg, int options,
upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_FaultAbort_HeaderAbort_msginit, options, arena, &ptr, len);
return ptr;
}
/* envoy.extensions.filters.http.fault.v3.HTTPFault */
UPB_INLINE envoy_extensions_filters_http_fault_v3_HTTPFault* envoy_extensions_filters_http_fault_v3_HTTPFault_new(upb_Arena* arena) {
return (envoy_extensions_filters_http_fault_v3_HTTPFault*)_upb_Message_New(&envoy_extensions_filters_http_fault_v3_HTTPFault_msginit, arena);
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_HTTPFault* envoy_extensions_filters_http_fault_v3_HTTPFault_parse(const char* buf, size_t size, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_HTTPFault* ret = envoy_extensions_filters_http_fault_v3_HTTPFault_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_HTTPFault_msginit, NULL, 0, arena) != kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE envoy_extensions_filters_http_fault_v3_HTTPFault* envoy_extensions_filters_http_fault_v3_HTTPFault_parse_ex(const char* buf, size_t size,
const upb_ExtensionRegistry* extreg,
int options, upb_Arena* arena) {
envoy_extensions_filters_http_fault_v3_HTTPFault* ret = envoy_extensions_filters_http_fault_v3_HTTPFault_new(arena);
if (!ret) return NULL;
if (upb_Decode(buf, size, ret, &envoy_extensions_filters_http_fault_v3_HTTPFault_msginit, extreg, options, arena) !=
kUpb_DecodeStatus_Ok) {
return NULL;
}
return ret;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_HTTPFault_serialize(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_HTTPFault_msginit, 0, arena, &ptr, len);
return ptr;
}
UPB_INLINE char* envoy_extensions_filters_http_fault_v3_HTTPFault_serialize_ex(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg, int options,
upb_Arena* arena, size_t* len) {
char* ptr;
(void)upb_Encode(msg, &envoy_extensions_filters_http_fault_v3_HTTPFault_msginit, options, arena, &ptr, len);
return ptr;
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_has_delay(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return _upb_hasbit(msg, 1);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_delay(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), const upb_Message*) = NULL;
}
UPB_INLINE const struct envoy_extensions_filters_common_fault_v3_FaultDelay* envoy_extensions_filters_http_fault_v3_HTTPFault_delay(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(4, 8), const struct envoy_extensions_filters_common_fault_v3_FaultDelay*);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_has_abort(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return _upb_hasbit(msg, 2);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_abort(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), const upb_Message*) = NULL;
}
UPB_INLINE const envoy_extensions_filters_http_fault_v3_FaultAbort* envoy_extensions_filters_http_fault_v3_HTTPFault_abort(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(8, 16), const envoy_extensions_filters_http_fault_v3_FaultAbort*);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_upstream_cluster(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_upstream_cluster(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_StringView);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_has_headers(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return _upb_has_submsg_nohasbit(msg, UPB_SIZE(20, 40));
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_headers(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
_upb_array_detach(msg, UPB_SIZE(20, 40));
}
UPB_INLINE const struct envoy_config_route_v3_HeaderMatcher* const* envoy_extensions_filters_http_fault_v3_HTTPFault_headers(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t* len) {
return (const struct envoy_config_route_v3_HeaderMatcher* const*)_upb_array_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_downstream_nodes(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
_upb_array_detach(msg, UPB_SIZE(24, 48));
}
UPB_INLINE upb_StringView const* envoy_extensions_filters_http_fault_v3_HTTPFault_downstream_nodes(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t* len) {
return (upb_StringView const*)_upb_array_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_has_max_active_faults(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return _upb_hasbit(msg, 3);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_max_active_faults(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(28, 56), const upb_Message*) = NULL;
}
UPB_INLINE const struct google_protobuf_UInt32Value* envoy_extensions_filters_http_fault_v3_HTTPFault_max_active_faults(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(28, 56), const struct google_protobuf_UInt32Value*);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_has_response_rate_limit(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return _upb_hasbit(msg, 4);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_response_rate_limit(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(32, 64), const upb_Message*) = NULL;
}
UPB_INLINE const struct envoy_extensions_filters_common_fault_v3_FaultRateLimit* envoy_extensions_filters_http_fault_v3_HTTPFault_response_rate_limit(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(32, 64), const struct envoy_extensions_filters_common_fault_v3_FaultRateLimit*);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_delay_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(36, 72), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_delay_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(36, 72), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_abort_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(44, 88), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_abort_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(44, 88), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_delay_duration_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(52, 104), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_delay_duration_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(52, 104), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_abort_http_status_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(60, 120), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_abort_http_status_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(60, 120), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_max_active_faults_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(68, 136), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_max_active_faults_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(68, 136), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_response_rate_limit_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(76, 152), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_response_rate_limit_percent_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(76, 152), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_abort_grpc_status_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(84, 168), upb_StringView) = upb_StringView_FromDataAndSize(NULL, 0);
}
UPB_INLINE upb_StringView envoy_extensions_filters_http_fault_v3_HTTPFault_abort_grpc_status_runtime(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(84, 168), upb_StringView);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_clear_disable_downstream_cluster_stats(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = 0;
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_disable_downstream_cluster_stats(const envoy_extensions_filters_http_fault_v3_HTTPFault* msg) {
return *UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_delay(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, struct envoy_extensions_filters_common_fault_v3_FaultDelay* value) {
_upb_sethas(msg, 1);
*UPB_PTR_AT(msg, UPB_SIZE(4, 8), struct envoy_extensions_filters_common_fault_v3_FaultDelay*) = value;
}
UPB_INLINE struct envoy_extensions_filters_common_fault_v3_FaultDelay* envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_delay(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena) {
struct envoy_extensions_filters_common_fault_v3_FaultDelay* sub = (struct envoy_extensions_filters_common_fault_v3_FaultDelay*)envoy_extensions_filters_http_fault_v3_HTTPFault_delay(msg);
if (sub == NULL) {
sub = (struct envoy_extensions_filters_common_fault_v3_FaultDelay*)_upb_Message_New(&envoy_extensions_filters_common_fault_v3_FaultDelay_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_HTTPFault_set_delay(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_abort(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, envoy_extensions_filters_http_fault_v3_FaultAbort* value) {
_upb_sethas(msg, 2);
*UPB_PTR_AT(msg, UPB_SIZE(8, 16), envoy_extensions_filters_http_fault_v3_FaultAbort*) = value;
}
UPB_INLINE struct envoy_extensions_filters_http_fault_v3_FaultAbort* envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_abort(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena) {
struct envoy_extensions_filters_http_fault_v3_FaultAbort* sub = (struct envoy_extensions_filters_http_fault_v3_FaultAbort*)envoy_extensions_filters_http_fault_v3_HTTPFault_abort(msg);
if (sub == NULL) {
sub = (struct envoy_extensions_filters_http_fault_v3_FaultAbort*)_upb_Message_New(&envoy_extensions_filters_http_fault_v3_FaultAbort_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_HTTPFault_set_abort(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_upstream_cluster(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(12, 24), upb_StringView) = value;
}
UPB_INLINE struct envoy_config_route_v3_HeaderMatcher** envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_headers(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t* len) {
return (struct envoy_config_route_v3_HeaderMatcher**)_upb_array_mutable_accessor(msg, UPB_SIZE(20, 40), len);
}
UPB_INLINE struct envoy_config_route_v3_HeaderMatcher** envoy_extensions_filters_http_fault_v3_HTTPFault_resize_headers(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t len, upb_Arena* arena) {
return (struct envoy_config_route_v3_HeaderMatcher**)_upb_Array_Resize_accessor2(msg, UPB_SIZE(20, 40), len, UPB_SIZE(2, 3), arena);
}
UPB_INLINE struct envoy_config_route_v3_HeaderMatcher* envoy_extensions_filters_http_fault_v3_HTTPFault_add_headers(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena) {
struct envoy_config_route_v3_HeaderMatcher* sub = (struct envoy_config_route_v3_HeaderMatcher*)_upb_Message_New(&envoy_config_route_v3_HeaderMatcher_msginit, arena);
bool ok = _upb_Array_Append_accessor2(msg, UPB_SIZE(20, 40), UPB_SIZE(2, 3), &sub, arena);
if (!ok) return NULL;
return sub;
}
UPB_INLINE upb_StringView* envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_downstream_nodes(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t* len) {
return (upb_StringView*)_upb_array_mutable_accessor(msg, UPB_SIZE(24, 48), len);
}
UPB_INLINE upb_StringView* envoy_extensions_filters_http_fault_v3_HTTPFault_resize_downstream_nodes(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, size_t len, upb_Arena* arena) {
return (upb_StringView*)_upb_Array_Resize_accessor2(msg, UPB_SIZE(24, 48), len, UPB_SIZE(3, 4), arena);
}
UPB_INLINE bool envoy_extensions_filters_http_fault_v3_HTTPFault_add_downstream_nodes(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_StringView val, upb_Arena* arena) {
return _upb_Array_Append_accessor2(msg, UPB_SIZE(24, 48), UPB_SIZE(3, 4), &val, arena);
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_max_active_faults(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, struct google_protobuf_UInt32Value* value) {
_upb_sethas(msg, 3);
*UPB_PTR_AT(msg, UPB_SIZE(28, 56), struct google_protobuf_UInt32Value*) = value;
}
UPB_INLINE struct google_protobuf_UInt32Value* envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_max_active_faults(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena) {
struct google_protobuf_UInt32Value* sub = (struct google_protobuf_UInt32Value*)envoy_extensions_filters_http_fault_v3_HTTPFault_max_active_faults(msg);
if (sub == NULL) {
sub = (struct google_protobuf_UInt32Value*)_upb_Message_New(&google_protobuf_UInt32Value_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_HTTPFault_set_max_active_faults(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_response_rate_limit(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, struct envoy_extensions_filters_common_fault_v3_FaultRateLimit* value) {
_upb_sethas(msg, 4);
*UPB_PTR_AT(msg, UPB_SIZE(32, 64), struct envoy_extensions_filters_common_fault_v3_FaultRateLimit*) = value;
}
UPB_INLINE struct envoy_extensions_filters_common_fault_v3_FaultRateLimit* envoy_extensions_filters_http_fault_v3_HTTPFault_mutable_response_rate_limit(envoy_extensions_filters_http_fault_v3_HTTPFault* msg, upb_Arena* arena) {
struct envoy_extensions_filters_common_fault_v3_FaultRateLimit* sub = (struct envoy_extensions_filters_common_fault_v3_FaultRateLimit*)envoy_extensions_filters_http_fault_v3_HTTPFault_response_rate_limit(msg);
if (sub == NULL) {
sub = (struct envoy_extensions_filters_common_fault_v3_FaultRateLimit*)_upb_Message_New(&envoy_extensions_filters_common_fault_v3_FaultRateLimit_msginit, arena);
if (!sub) return NULL;
envoy_extensions_filters_http_fault_v3_HTTPFault_set_response_rate_limit(msg, sub);
}
return sub;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_delay_percent_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(36, 72), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_abort_percent_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(44, 88), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_delay_duration_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(52, 104), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_abort_http_status_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(60, 120), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_max_active_faults_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(68, 136), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_response_rate_limit_percent_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(76, 152), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_abort_grpc_status_runtime(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, upb_StringView value) {
*UPB_PTR_AT(msg, UPB_SIZE(84, 168), upb_StringView) = value;
}
UPB_INLINE void envoy_extensions_filters_http_fault_v3_HTTPFault_set_disable_downstream_cluster_stats(envoy_extensions_filters_http_fault_v3_HTTPFault *msg, bool value) {
*UPB_PTR_AT(msg, UPB_SIZE(1, 1), bool) = value;
}
extern const upb_MiniTable_File envoy_extensions_filters_http_fault_v3_fault_proto_upb_file_layout;
#ifdef __cplusplus
} /* extern "C" */
#endif
#include "upb/port_undef.inc"
#endif /* ENVOY_EXTENSIONS_FILTERS_HTTP_FAULT_V3_FAULT_PROTO_UPB_H_ */
|
c8ee60c2ad4cd2884204807351b61e3cedb1d83f
|
581bdcc078d282e388f1b655d4cfc4e08152d117
|
/plugins/ExtendedTools/pooldialogbig.c
|
04bcc2ce1bef4b7d4bcc3ea1c61a835c26692e28
|
[
"MIT",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Zlib",
"LGPL-2.1-or-later",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain"
] |
permissive
|
winsiderss/systeminformer
|
774928be871f0055263ac5e62ae0a598b098486b
|
5a6b442acd45d681f699a133d476a3211d072871
|
refs/heads/master
| 2023-08-28T15:43:41.074679
| 2023-08-27T20:59:20
| 2023-08-27T20:59:20
| 50,824,485
| 2,137
| 292
|
MIT
| 2023-09-10T22:35:12
| 2016-02-01T08:10:21
|
C
|
UTF-8
|
C
| false
| false
| 8,545
|
c
|
pooldialogbig.c
|
/*
* Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved.
*
* This file is part of System Informer.
*
* Authors:
*
* dmex 2016-2023
*
*/
#include "exttools.h"
#include "poolmon.h"
NTSTATUS EtEnumBigPoolTable(
_Out_ PVOID* Buffer
)
{
NTSTATUS status;
PVOID buffer;
ULONG bufferSize;
ULONG attempts;
bufferSize = 0x100;
buffer = PhAllocate(bufferSize);
status = NtQuerySystemInformation(
SystemBigPoolInformation,
buffer,
bufferSize,
&bufferSize
);
attempts = 0;
while (status == STATUS_INFO_LENGTH_MISMATCH && attempts < 8)
{
PhFree(buffer);
buffer = PhAllocate(bufferSize);
status = NtQuerySystemInformation(
SystemBigPoolInformation,
buffer,
bufferSize,
&bufferSize
);
attempts++;
}
if (NT_SUCCESS(status))
*Buffer = buffer;
else
PhFree(buffer);
return status;
}
VOID EtUpdateBigPoolTable(
_Inout_ PBIGPOOLTAG_CONTEXT Context
)
{
PSYSTEM_BIGPOOL_INFORMATION bigPoolTable;
ULONG i;
if (!NT_SUCCESS(EtEnumBigPoolTable(&bigPoolTable)))
return;
for (i = 0; i < bigPoolTable->Count; i++)
{
INT itemIndex;
SYSTEM_BIGPOOL_ENTRY poolTagInfo;
WCHAR virtualAddressString[PH_PTR_STR_LEN_1] = L"";
poolTagInfo = bigPoolTable->AllocatedInfo[i];
if (poolTagInfo.TagUlong != Context->TagUlong)
continue;
PhPrintPointer(virtualAddressString, poolTagInfo.VirtualAddress);
itemIndex = PhAddListViewItem(
Context->ListViewHandle,
MAXINT,
virtualAddressString,
NULL
);
PhSetListViewSubItem(
Context->ListViewHandle,
itemIndex,
1,
PhaFormatSize(poolTagInfo.SizeInBytes, ULONG_MAX)->Buffer
);
if (poolTagInfo.NonPaged)
{
PhSetListViewSubItem(
Context->ListViewHandle,
itemIndex,
2,
L"Yes"
);
}
else
{
PhSetListViewSubItem(
Context->ListViewHandle,
itemIndex,
2,
L"No"
);
}
}
PhFree(bigPoolTable);
}
INT_PTR CALLBACK EtBigPoolMonDlgProc(
_In_ HWND hwndDlg,
_In_ UINT uMsg,
_In_ WPARAM wParam,
_In_ LPARAM lParam
)
{
PBIGPOOLTAG_CONTEXT context;
if (uMsg == WM_INITDIALOG)
{
context = PhAllocateZero(sizeof(BIGPOOLTAG_CONTEXT));
context->TagUlong = ((PPOOL_ITEM)lParam)->TagUlong;
PhZeroExtendToUtf16Buffer(context->Tag, sizeof(context->Tag), context->TagString);
PhSetWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT, context);
}
else
{
context = PhGetWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT);
}
if (!context)
return FALSE;
switch (uMsg)
{
case WM_INITDIALOG:
{
context->WindowHandle = hwndDlg;
context->ListViewHandle = GetDlgItem(hwndDlg, IDC_BIGPOOLLIST);
PhSetApplicationWindowIcon(hwndDlg);
PhSetWindowText(hwndDlg, PhaFormatString(L"Large Allocations (%s)", context->TagString)->Buffer);
PhSetListViewStyle(context->ListViewHandle, FALSE, TRUE);
PhSetControlTheme(context->ListViewHandle, L"explorer");
PhAddListViewColumn(context->ListViewHandle, 0, 0, 0, LVCFMT_LEFT, 150, L"Address");
PhAddListViewColumn(context->ListViewHandle, 1, 1, 1, LVCFMT_LEFT, 100, L"Size");
PhAddListViewColumn(context->ListViewHandle, 2, 2, 2, LVCFMT_LEFT, 100, L"NonPaged");
PhSetExtendedListView(context->ListViewHandle);
PhInitializeLayoutManager(&context->LayoutManager, hwndDlg);
PhAddLayoutItem(&context->LayoutManager, context->ListViewHandle, NULL, PH_ANCHOR_ALL);
PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDC_REFRESH), NULL, PH_ANCHOR_BOTTOM | PH_ANCHOR_LEFT);
PhAddLayoutItem(&context->LayoutManager, GetDlgItem(hwndDlg, IDCANCEL), NULL, PH_ANCHOR_BOTTOM | PH_ANCHOR_RIGHT);
if (PhGetIntegerPairSetting(SETTING_NAME_BIGPOOL_WINDOW_POSITION).X != 0)
PhLoadWindowPlacementFromSetting(SETTING_NAME_BIGPOOL_WINDOW_POSITION, SETTING_NAME_BIGPOOL_WINDOW_SIZE, hwndDlg);
else
PhCenterWindow(hwndDlg, NULL);
PhInitializeWindowTheme(hwndDlg, !!PhGetIntegerSetting(L"EnableThemeSupport"));
EtUpdateBigPoolTable(context);
}
break;
case WM_SIZE:
PhLayoutManagerLayout(&context->LayoutManager);
break;
case WM_DESTROY:
{
PhRemoveWindowContext(hwndDlg, PH_WINDOW_CONTEXT_DEFAULT);
PhSaveWindowPlacementToSetting(SETTING_NAME_BIGPOOL_WINDOW_POSITION, SETTING_NAME_BIGPOOL_WINDOW_SIZE, hwndDlg);
PhDeleteLayoutManager(&context->LayoutManager);
PhFree(context);
}
break;
case WM_COMMAND:
{
switch (GET_WM_COMMAND_ID(wParam, lParam))
{
case IDCANCEL:
EndDialog(hwndDlg, IDOK);
break;
case IDC_REFRESH:
{
ExtendedListView_SetRedraw(context->ListViewHandle, FALSE);
ListView_DeleteAllItems(context->ListViewHandle);
EtUpdateBigPoolTable(context);
ExtendedListView_SetRedraw(context->ListViewHandle, TRUE);
}
break;
}
}
break;
case WM_NOTIFY:
{
LPNMHDR hdr = (LPNMHDR)lParam;
PhHandleListViewNotifyForCopy(lParam, context->ListViewHandle);
switch (hdr->code)
{
case NM_RCLICK:
{
if (hdr->hwndFrom == context->ListViewHandle)
{
POINT point;
PPH_EMENU menu;
ULONG numberOfItems;
PVOID* listviewItems;
PPH_EMENU_ITEM selectedItem;
PhGetSelectedListViewItemParams(context->ListViewHandle, &listviewItems, &numberOfItems);
if (numberOfItems == 0)
break;
menu = PhCreateEMenu();
PhInsertEMenuItem(menu, PhCreateEMenuItem(0, USHRT_MAX, L"&Copy", NULL, NULL), ULONG_MAX);
PhInsertCopyListViewEMenuItem(menu, USHRT_MAX, context->ListViewHandle);
GetCursorPos(&point);
selectedItem = PhShowEMenu(
menu,
context->ListViewHandle,
PH_EMENU_SHOW_LEFTRIGHT,
PH_ALIGN_LEFT | PH_ALIGN_TOP,
point.x,
point.y
);
if (selectedItem && selectedItem->Id != ULONG_MAX)
{
if (PhHandleCopyListViewEMenuItem(selectedItem))
break;
switch (selectedItem->Id)
{
case USHRT_MAX:
{
PhCopyListView(context->ListViewHandle);
}
break;
}
}
PhDestroyEMenu(menu);
}
}
break;
}
}
break;
case WM_CTLCOLORBTN:
return HANDLE_WM_CTLCOLORBTN(hwndDlg, wParam, lParam, PhWindowThemeControlColor);
case WM_CTLCOLORDLG:
return HANDLE_WM_CTLCOLORDLG(hwndDlg, wParam, lParam, PhWindowThemeControlColor);
case WM_CTLCOLORSTATIC:
return HANDLE_WM_CTLCOLORSTATIC(hwndDlg, wParam, lParam, PhWindowThemeControlColor);
}
return FALSE;
}
VOID EtShowBigPoolDialog(
_In_ PPOOL_ITEM PoolItem
)
{
PhDialogBox(
PluginInstance->DllBase,
MAKEINTRESOURCE(IDD_BIGPOOL),
NULL,
EtBigPoolMonDlgProc,
PoolItem
);
}
|
0b4320cbf3752cc562fec4ffdc015fb826a9009f
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/arm/src/s32k3xx/hardware/s32k3xx_fxosc.h
|
ef189d606377e0373f7073b77d04dfce7f94b5eb
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 5,057
|
h
|
s32k3xx_fxosc.h
|
/****************************************************************************
* arch/arm/src/s32k3xx/hardware/s32k3xx_fxosc.h
*
* 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.
*
****************************************************************************/
/* Copyright 2022 NXP */
#ifndef __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_FXOSC_H
#define __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_FXOSC_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <hardware/s32k3xx_memorymap.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* FXOSC Register Offsets ***************************************************/
#define S32K3XX_FXOSC_CTRL_OFFSET (0x00) /* FXOSC Control Register (CTRL) */
#define S32K3XX_FXOSC_STAT_OFFSET (0x04) /* Oscillator Status Register (STAT) */
/* FXOSC Register Addresses *************************************************/
#define S32K3XX_FXOSC_CTRL (S32K3XX_FXOSC_BASE + S32K3XX_FXOSC_CTRL_OFFSET)
#define S32K3XX_FXOSC_STAT (S32K3XX_FXOSC_BASE + S32K3XX_FXOSC_STAT_OFFSET)
/* FXOSC Register Bitfield Definitions **************************************/
/* FXOSC Control Register (CTRL) */
#define FXOSC_CTRL_OSCON (1 << 0) /* Bit 0: Enables FXOSC (OSCON) */
# define FXOSC_CTRL_OSCOFF (0 << 0) /* Disables FXOSC */
/* Bits 1-3: Reserved */
#define FXOSC_CTRL_GM_SEL_SHIFT (4) /* Bits 4-7: Crystal overdrive protection, transconductance selection (GM_SEL) */
#define FXOSC_CTRL_GM_SEL_MASK (0x0f << FXOSC_CTRL_GM_SEL_SHIFT)
# define FXOSC_CTRL_GM_SEL_0X (0x00 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0x */
# define FXOSC_CTRL_GM_SEL_0_1004X (0x01 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.1004x */
# define FXOSC_CTRL_GM_SEL_0_2009X (0x02 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.2009x */
# define FXOSC_CTRL_GM_SEL_0_3013X (0x03 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.3013x */
# define FXOSC_CTRL_GM_SEL_0_2343X (0x04 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.2343x */
# define FXOSC_CTRL_GM_SEL_0_3348X (0x05 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.3348x */
# define FXOSC_CTRL_GM_SEL_0_4345X (0x06 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.4345x */
# define FXOSC_CTRL_GM_SEL_0_5349X (0x07 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.5349x */
# define FXOSC_CTRL_GM_SEL_0_4679X (0x08 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.4679x */
# define FXOSC_CTRL_GM_SEL_0_5684X (0x09 << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.5684x */
# define FXOSC_CTRL_GM_SEL_0_6681X (0x0a << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.6681x */
# define FXOSC_CTRL_GM_SEL_0_7678X (0x0b << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.7678x */
# define FXOSC_CTRL_GM_SEL_0_7016X (0x0c << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.7016x */
# define FXOSC_CTRL_GM_SEL_0_8013X (0x0d << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.8013x */
# define FXOSC_CTRL_GM_SEL_0_9003X (0x0e << FXOSC_CTRL_GM_SEL_SHIFT) /* 0.9003x */
# define FXOSC_CTRL_GM_SEL_1X (0x0f << FXOSC_CTRL_GM_SEL_SHIFT) /* 1x */
/* Bits 8-15: Reserved */
#define FXOSC_CTRL_EOCV_SHIFT (16) /* Bits 16-23: End of count value (EOCV) */
#define FXOSC_CTRL_EOCV_MASK (0xff << FXOSC_CTRL_EOCV_SHIFT)
#define FXOSC_CTRL_EOCV(n) (((n) << FXOSC_CTRL_EOCV_SHIFT) & FXOSC_CTRL_EOCV_MASK)
#define FXOSC_CTRL_COMP_EN (1 << 24) /* Bit 24: Comparator enable (COMP_EN) */
# define FXOSC_CTRL_COMP_DIS (0 << 24) /* Comparator disable */
/* Bits 25-30: Reserved */
#define FXOSC_CTRL_OSC_BYP (1 << 31) /* Bit 31: Oscillator bypass (OSC_BYP) */
/* Oscillator Status Register (STAT) */
/* Bits 0-30: Reserved */
#define FXOSC_STAT_OSC_STAT (1 << 31) /* Bit 31: Crystal oscilator status (OSC_STAT) */
# define FXOSC_STAT_OSC_STAT_OFF (0 << 31) /* Crystal oscillator is off or not stable */
# define FXOSC_STAT_OSC_STAT_ON (1 << 31) /* Crystal oscillator is on and providing a stable clock */
#endif /* __ARCH_ARM_SRC_S32K3XX_HARDWARE_S32K3XX_FXOSC_H */
|
c3b1c850f1ebc3c44be8ba571e8245a3b03bde2f
|
2fe9ec7915276be05ecf8710a63c6e1b5e79730a
|
/projects/mcpha/server/pha-server.c
|
63a10f9174af87a96201cac542502e93d746fca5
|
[
"MIT"
] |
permissive
|
pavel-demin/red-pitaya-notes
|
bd3829ea730d80d34e3dd62a86bbb811ce207190
|
effa44a5c3cc1b4198c6bd32479b2fd791d3358d
|
refs/heads/master
| 2023-08-31T05:03:49.738847
| 2023-08-30T23:28:08
| 2023-08-30T23:28:08
| 28,404,370
| 308
| 206
|
MIT
| 2023-06-25T15:54:24
| 2014-12-23T15:15:00
|
C
|
UTF-8
|
C
| false
| false
| 5,047
|
c
|
pha-server.c
|
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <pthread.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define TCP_PORT 1002
int sock_thread = -1;
volatile void *sts, *cfg;
volatile uint32_t *pha;
void *read_handler(void *arg);
int main(int argc, char *argv[])
{
int fd, sock_server, sock_client;
struct sched_param param;
pthread_attr_t attr;
pthread_t thread;
volatile uint8_t *rst;
struct sockaddr_in addr;
int yes = 1;
uint64_t command, data;
uint8_t code, chan;
if((fd = open("/dev/mem", O_RDWR)) < 0)
{
perror("open");
return EXIT_FAILURE;
}
cfg = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x40000000);
sts = mmap(NULL, sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x41000000);
pha = mmap(NULL, 8*sysconf(_SC_PAGESIZE), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0x42000000);
rst = cfg + 3;
/* set sample rate */
*(uint16_t *)(cfg + 6) = 125;
/* reset timers and phas */
*rst &= ~3;
*rst |= 3;
if((sock_server = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
return EXIT_FAILURE;
}
setsockopt(sock_server, SOL_SOCKET, SO_REUSEADDR, (void *)&yes , sizeof(yes));
/* setup listening address */
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(TCP_PORT);
if(bind(sock_server, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
return EXIT_FAILURE;
}
listen(sock_server, 1024);
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
param.sched_priority = 99;
pthread_attr_setschedparam(&attr, ¶m);
while(1)
{
if((sock_client = accept(sock_server, NULL, NULL)) < 0)
{
perror("accept");
return EXIT_FAILURE;
}
while(1)
{
if(recv(sock_client, &command, 8, MSG_WAITALL) <= 0) break;
code = (uint8_t)(command >> 60) & 0xf;
chan = (uint8_t)(command >> 56) & 0xf;
data = (uint64_t)(command & 0xffffffffffffffULL);
if(code == 0)
{
/* reset pha */
*rst &= ~1;
*rst |= 1;
}
else if(code == 1)
{
/* reset timer */
*rst &= ~2;
*rst |= 2;
}
else if(code == 2)
{
/* set sample rate */
*(uint16_t *)(cfg + 6) = data;
}
else if(code == 3)
{
/* set negator mode (0 for disabled, 1 for enabled) */
if(chan == 0)
{
if(data == 0)
{
*rst &= ~16;
}
else if(data == 1)
{
*rst |= 16;
}
}
else if(chan == 1)
{
if(data == 0)
{
*rst &= ~32;
}
else if(data == 1)
{
*rst |= 32;
}
}
}
else if(code == 4)
{
/* set pha delay */
if(chan == 0)
{
*(uint16_t *)(cfg + 50) = data;
}
else if(chan == 1)
{
*(uint16_t *)(cfg + 66) = data;
}
}
else if(code == 5)
{
/* set pha min threshold */
if(chan == 0)
{
*(uint16_t *)(cfg + 52) = data;
}
else if(chan == 1)
{
*(uint16_t *)(cfg + 68) = data;
}
}
else if(code == 6)
{
/* set pha max threshold */
if(chan == 0)
{
*(uint16_t *)(cfg + 54) = data;
}
else if(chan == 1)
{
*(uint16_t *)(cfg + 70) = data;
}
}
else if(code == 7)
{
/* set timer */
if(chan == 0)
{
*(uint64_t *)(cfg + 40) = data;
}
else if(chan == 1)
{
*(uint64_t *)(cfg + 56) = data;
}
}
else if(code == 8)
{
/* start */
sock_thread = sock_client;
if(pthread_create(&thread, &attr, read_handler, NULL) < 0)
{
perror("pthread_create");
return EXIT_FAILURE;
}
pthread_detach(thread);
/* reset fifo */
*rst &= ~64;
*rst |= 64;
/* start timer */
*rst |= 8;
}
}
/* stop timer */
*rst &= ~8;
sock_thread = -1;
close(sock_client);
}
close(sock_server);
return EXIT_SUCCESS;
}
void *read_handler(void *arg)
{
int i, size;
uint32_t buffer[4096];
while(1)
{
if(sock_thread < 0) break;
size = *(uint16_t *)(sts + 40);
if(size < 4)
{
usleep(1000);
continue;
}
if(size > 4096) size = 4096;
for(i = 0; i < size; ++i)
{
buffer[i] = *pha;
}
if(send(sock_thread, buffer, 4 * size, MSG_NOSIGNAL) < 0) break;
}
return NULL;
}
|
34ef5e728622630da491b6ebcd120627c9976d25
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/world/area_dgb/dgb_vtx.h
|
d7683562afb029f8b4d9e61b23b3c8a4d1f3c16b
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 7,316
|
h
|
dgb_vtx.h
|
#ifndef DGB_VTX_H
#define DGB_VTX_H
#include "common.h"
extern Vtx vtx_C20F40[];
extern Vtx vtx_C21100[];
extern Vtx vtx_C21130[];
extern Vtx vtx_C211E0[];
extern Vtx vtx_C211F0[];
extern Vtx vtx_C21240[];
extern Vtx vtx_C21360[];
extern Vtx vtx_C213C0[];
extern Vtx vtx_C215A0[];
extern Vtx vtx_C21700[];
extern Vtx vtx_C21770[];
extern Vtx vtx_C21810[];
extern Vtx vtx_C21930[];
extern Vtx vtx_C21AE0[];
extern Vtx vtx_C21B20[];
extern Vtx vtx_C21BD0[];
extern Vtx vtx_C21C90[];
extern Vtx vtx_C21D30[];
extern Vtx vtx_C21DD0[];
extern Vtx vtx_C21E00[];
extern Vtx vtx_C21F30[];
extern Vtx vtx_C22050[];
extern Vtx vtx_C22190[];
extern Vtx vtx_C222D0[];
extern Vtx vtx_C22330[];
extern Vtx vtx_C224A0[];
extern Vtx vtx_C224E0[];
extern Vtx vtx_C22510[];
extern Vtx vtx_C22620[];
extern Vtx vtx_C22780[];
extern Vtx vtx_C22810[];
extern Vtx vtx_C22870[];
extern Vtx vtx_C228F0[];
extern Vtx vtx_C22950[];
extern Vtx vtx_C229F0[];
extern Vtx vtx_C22B00[];
extern Vtx vtx_C22C00[];
extern Vtx vtx_C22E00[];
extern Vtx vtx_C22EC0[];
extern Vtx vtx_C230A0[];
extern Vtx vtx_C23240[];
extern Vtx vtx_C23260[];
extern Vtx vtx_C232A0[];
extern Vtx vtx_C23330[];
extern Vtx vtx_C233D0[];
extern Vtx vtx_C23480[];
extern Vtx vtx_C234B0[];
extern Vtx vtx_C235C0[];
extern Vtx vtx_C236E0[];
extern Vtx vtx_C23810[];
extern Vtx vtx_C238B0[];
extern Vtx vtx_C239D0[];
extern Vtx vtx_C23A70[];
extern Vtx vtx_C23B70[];
extern Vtx vtx_C23BA0[];
extern Vtx vtx_C23C70[];
extern Vtx vtx_C23C90[];
extern Vtx vtx_C23CE0[];
extern Vtx vtx_C23D20[];
extern Vtx vtx_C23D60[];
extern Vtx vtx_C23DD0[];
extern Vtx vtx_C23E00[];
extern Vtx vtx_C23E20[];
extern Vtx vtx_C23E50[];
extern Vtx vtx_C23F10[];
extern Vtx vtx_C23FD0[];
extern Vtx vtx_C240D0[];
extern Vtx vtx_C241D0[];
extern Vtx vtx_C24350[];
extern Vtx vtx_C24510[];
extern Vtx vtx_C24540[];
extern Vtx vtx_C24600[];
extern Vtx vtx_C24690[];
extern Vtx vtx_C24720[];
extern Vtx vtx_C24730[];
extern Vtx vtx_C24840[];
extern Vtx vtx_C24960[];
extern Vtx vtx_C24980[];
extern Vtx vtx_C24AD0[];
extern Vtx vtx_C24AF0[];
extern Vtx vtx_C24CD0[];
extern Vtx vtx_C24EB0[];
extern Vtx vtx_C24F30[];
extern Vtx vtx_C24FB0[];
extern Vtx vtx_C25050[];
extern Vtx vtx_C25250[];
extern Vtx vtx_C25310[];
extern Vtx vtx_C25350[];
extern Vtx vtx_C25500[];
extern Vtx vtx_C25600[];
extern Vtx vtx_C256D0[];
extern Vtx vtx_C25710[];
extern Vtx vtx_C257D0[];
extern Vtx vtx_C257F0[];
extern Vtx vtx_C25900[];
extern Vtx vtx_C25950[];
extern Vtx vtx_C25A30[];
extern Vtx vtx_C25AB0[];
extern Vtx vtx_C25B30[];
extern Vtx vtx_C25BD0[];
extern Vtx vtx_C25C00[];
extern Vtx vtx_C25C20[];
extern Vtx vtx_C25C80[];
extern Vtx vtx_C25CF0[];
extern Vtx vtx_C25D30[];
extern Vtx vtx_C25DA0[];
extern Vtx vtx_C25DD0[];
extern Vtx vtx_C25EA0[];
extern Vtx vtx_C25F00[];
extern Vtx vtx_C25F90[];
extern Vtx vtx_C26040[];
extern Vtx vtx_C26090[];
extern Vtx vtx_C26130[];
extern Vtx vtx_C26250[];
extern Vtx vtx_C26290[];
extern Vtx vtx_C262D0[];
extern Vtx vtx_C26310[];
extern Vtx vtx_C26350[];
extern Vtx vtx_C26390[];
extern Vtx vtx_C263D0[];
extern Vtx vtx_C26410[];
extern Vtx vtx_C26450[];
extern Vtx vtx_C26490[];
extern Vtx vtx_C264D0[];
extern Vtx vtx_C26510[];
extern Vtx vtx_C26550[];
extern Vtx vtx_C26590[];
extern Vtx vtx_C265D0[];
extern Vtx vtx_C26610[];
extern Vtx vtx_C26650[];
extern Vtx vtx_C26690[];
extern Vtx vtx_C266D0[];
extern Vtx vtx_C26710[];
extern Vtx vtx_C26750[];
extern Vtx vtx_C26890[];
extern Vtx vtx_C26A60[];
extern Vtx vtx_C26AE0[];
extern Vtx vtx_C26CC0[];
extern Vtx vtx_C26EB0[];
extern Vtx vtx_C26F40[];
extern Vtx vtx_C26FB0[];
extern Vtx vtx_C27110[];
extern Vtx vtx_C27180[];
extern Vtx vtx_C27220[];
extern Vtx vtx_C27300[];
extern Vtx vtx_C273A0[];
extern Vtx vtx_C27460[];
extern Vtx vtx_C27580[];
extern Vtx vtx_C27740[];
extern Vtx vtx_C27770[];
extern Vtx vtx_C27880[];
extern Vtx vtx_C27A40[];
extern Vtx vtx_C27A70[];
extern Vtx vtx_C27B80[];
extern Vtx vtx_C27D60[];
extern Vtx vtx_C27F20[];
extern Vtx vtx_C27FC0[];
extern Vtx vtx_C27FE0[];
extern Vtx vtx_C28080[];
extern Vtx vtx_C28110[];
extern Vtx vtx_C28190[];
extern Vtx vtx_C281B0[];
extern Vtx vtx_C281E0[];
extern Vtx vtx_C282D0[];
extern Vtx vtx_C282F0[];
extern Vtx vtx_C28310[];
extern Vtx vtx_C28420[];
extern Vtx vtx_C284F0[];
extern Vtx vtx_C28550[];
extern Vtx vtx_C28690[];
extern Vtx vtx_C28720[];
extern Vtx vtx_C287A0[];
extern Vtx vtx_C28890[];
extern Vtx vtx_C28970[];
extern Vtx vtx_C28A70[];
extern Vtx vtx_C28BB0[];
extern Vtx vtx_C28D90[];
extern Vtx vtx_C28F70[];
extern Vtx vtx_C29150[];
extern Vtx vtx_C29330[];
extern Vtx vtx_C29470[];
extern Vtx vtx_C294A0[];
extern Vtx vtx_C294F0[];
extern Vtx vtx_C29540[];
extern Vtx vtx_C29570[];
extern Vtx vtx_C295B0[];
extern Vtx vtx_C29630[];
extern Vtx vtx_C29650[];
extern Vtx vtx_C296C0[];
extern Vtx vtx_C29750[];
extern Vtx vtx_C297F0[];
extern Vtx vtx_C298E0[];
extern Vtx vtx_C29A40[];
extern Vtx vtx_C29AB0[];
extern Vtx vtx_C29BB0[];
extern Vtx vtx_C29CD0[];
extern Vtx vtx_C29E00[];
extern Vtx vtx_C29F50[];
extern Vtx vtx_C2A080[];
extern Vtx vtx_C2A180[];
extern Vtx vtx_C2A2C0[];
extern Vtx vtx_C2A3C0[];
extern Vtx vtx_C2A540[];
extern Vtx vtx_C2A700[];
extern Vtx vtx_C2A740[];
extern Vtx vtx_C2A790[];
extern Vtx vtx_C2A8D0[];
extern Vtx vtx_C2AAB0[];
extern Vtx vtx_C2AC90[];
extern Vtx vtx_C2AD20[];
extern Vtx vtx_C2AD70[];
extern Vtx vtx_C2AE50[];
extern Vtx vtx_C2AE70[];
extern Vtx vtx_C2AEB0[];
extern Vtx vtx_C2AF60[];
extern Vtx vtx_C2AF80[];
extern Vtx vtx_C2B010[];
extern Vtx vtx_C2B050[];
extern Vtx vtx_C2B220[];
extern Vtx vtx_C2B250[];
extern Vtx vtx_C2B2D0[];
extern Vtx vtx_C2B340[];
extern Vtx vtx_C2B3C0[];
extern Vtx vtx_C2B3E0[];
extern Vtx vtx_C2B410[];
extern Vtx vtx_C2B560[];
extern Vtx vtx_C2B6D0[];
extern Vtx vtx_C2B800[];
extern Vtx vtx_C2B850[];
extern Vtx vtx_C2B8E0[];
extern Vtx vtx_C2B9B0[];
extern Vtx vtx_C2BA50[];
extern Vtx vtx_C2BB50[];
extern Vtx vtx_C2BD50[];
extern Vtx vtx_C2BE50[];
extern Vtx vtx_C2BF50[];
extern Vtx vtx_C2BF60[];
extern Vtx vtx_C2BFD0[];
extern Vtx vtx_C2C080[];
extern Vtx vtx_C2C0B0[];
extern Vtx vtx_C2C0F0[];
extern Vtx vtx_C2C130[];
extern Vtx vtx_C2C1C0[];
extern Vtx vtx_C2C300[];
extern Vtx vtx_C2C4E0[];
extern Vtx vtx_C2C6C0[];
extern Vtx vtx_C2C8A0[];
extern Vtx vtx_C2CA20[];
extern Vtx vtx_C2CBA0[];
extern Vtx vtx_C2CD20[];
extern Vtx vtx_C2CEA0[];
extern Vtx vtx_C2CED0[];
extern Vtx vtx_C2CF00[];
extern Vtx vtx_C2CFC0[];
extern Vtx vtx_C2D140[];
extern Vtx vtx_C2D170[];
extern Vtx vtx_C2D1A0[];
extern Vtx vtx_C2D260[];
extern Vtx vtx_C2D3E0[];
extern Vtx vtx_C2D410[];
extern Vtx vtx_C2D440[];
extern Vtx vtx_C2D500[];
extern Vtx vtx_C2D560[];
extern Vtx vtx_C2D5C0[];
extern Vtx vtx_C2D620[];
extern Vtx vtx_C2D660[];
extern Vtx vtx_C2D6A0[];
extern Vtx vtx_C2D6E0[];
extern Vtx vtx_C2D830[];
extern Vtx vtx_C2D8F0[];
extern Vtx vtx_C2DA20[];
extern Vtx vtx_C2DBE0[];
extern Vtx vtx_C2DCB0[];
extern Vtx vtx_C2DD50[];
extern Vtx vtx_C2DD90[];
extern Vtx vtx_C2DEA0[];
extern Vtx vtx_C2DFC0[];
extern Vtx vtx_C2E020[];
extern Vtx vtx_C2E1E0[];
extern Vtx vtx_C2E2B0[];
extern Vtx vtx_C2E360[];
extern Vtx vtx_C2E390[];
extern Vtx vtx_C2E4A0[];
extern Vtx vtx_C2E5D0[];
extern Vtx vtx_C2E620[];
extern Vtx vtx_C2E7B0[];
extern Vtx vtx_C2E800[];
extern Vtx vtx_C2E8C0[];
extern Vtx vtx_C2E980[];
extern Vtx vtx_C2EA60[];
#endif
|
47011d6506e29412e20144019eee19d23bc7939d
|
1b90be9561c10508eea59cb36c1f1665d0ef947f
|
/lib/sundials_6.1.1/src/sundials/sundials_linearsolver.c
|
7a2a62e89826ae34a40db00c69d5b3dd814b6292
|
[
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0"
] |
permissive
|
stan-dev/math
|
473e7c1eaf11f84eaf2032c2455e12ba65feef39
|
bdf281f4e7f8034f47974d14dea7f09e600ac02a
|
refs/heads/develop
| 2023-08-31T09:02:59.224115
| 2023-08-29T15:17:01
| 2023-08-29T15:17:01
| 38,388,440
| 732
| 240
|
BSD-3-Clause
| 2023-09-14T19:44:20
| 2015-07-01T18:40:54
|
C++
|
UTF-8
|
C
| false
| false
| 6,933
|
c
|
sundials_linearsolver.c
|
/* -----------------------------------------------------------------
* Programmer(s): Daniel Reynolds @ SMU
* David J. Gardner, Carol S. Woodward, and
* Slaven Peles @ LLNL
* -----------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2022, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
* -----------------------------------------------------------------
* This is the implementation file for a generic SUNLINEARSOLVER
* package. It contains the implementation of the SUNLinearSolver
* operations listed in sundials_linearsolver.h
* -----------------------------------------------------------------*/
#include <stdlib.h>
#include <sundials/sundials_linearsolver.h>
#include "sundials_context_impl.h"
#if defined(SUNDIALS_BUILD_WITH_PROFILING)
static SUNProfiler getSUNProfiler(SUNLinearSolver S)
{
return(S->sunctx->profiler);
}
#endif
/* -----------------------------------------------------------------
* Create a new empty SUNLinearSolver object
* ----------------------------------------------------------------- */
SUNLinearSolver SUNLinSolNewEmpty(SUNContext sunctx)
{
SUNLinearSolver LS;
SUNLinearSolver_Ops ops;
/* a context is required */
if (sunctx == NULL) return(NULL);
/* create linear solver object */
LS = NULL;
LS = (SUNLinearSolver) malloc(sizeof *LS);
if (LS == NULL) return(NULL);
/* create linear solver ops structure */
ops = NULL;
ops = (SUNLinearSolver_Ops) malloc(sizeof *ops);
if (ops == NULL) { free(LS); return(NULL); }
/* initialize operations to NULL */
ops->gettype = NULL;
ops->getid = NULL;
ops->setatimes = NULL;
ops->setpreconditioner = NULL;
ops->setscalingvectors = NULL;
ops->setzeroguess = NULL;
ops->initialize = NULL;
ops->setup = NULL;
ops->solve = NULL;
ops->numiters = NULL;
ops->resnorm = NULL;
ops->resid = NULL;
ops->lastflag = NULL;
ops->space = NULL;
ops->free = NULL;
/* attach ops and initialize content and context to NULL */
LS->ops = ops;
LS->content = NULL;
LS->sunctx = sunctx;
return(LS);
}
/* -----------------------------------------------------------------
* Free a generic SUNLinearSolver (assumes content is already empty)
* ----------------------------------------------------------------- */
void SUNLinSolFreeEmpty(SUNLinearSolver S)
{
if (S == NULL) return;
/* free non-NULL ops structure */
if (S->ops) free(S->ops);
S->ops = NULL;
/* free overall N_Vector object and return */
free(S);
return;
}
/* -----------------------------------------------------------------
* Functions in the 'ops' structure
* -----------------------------------------------------------------*/
SUNLinearSolver_Type SUNLinSolGetType(SUNLinearSolver S)
{
return(S->ops->gettype(S));
}
SUNLinearSolver_ID SUNLinSolGetID(SUNLinearSolver S)
{
if (S->ops->getid)
return(S->ops->getid(S));
else
return(SUNLINEARSOLVER_CUSTOM);
}
int SUNLinSolSetATimes(SUNLinearSolver S, void* A_data,
SUNATimesFn ATimes)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->setatimes)
ier = S->ops->setatimes(S, A_data, ATimes);
else
ier = SUNLS_SUCCESS;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolSetPreconditioner(SUNLinearSolver S, void* P_data,
SUNPSetupFn Pset, SUNPSolveFn Psol)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->setpreconditioner)
ier = S->ops->setpreconditioner(S, P_data, Pset, Psol);
else
ier = SUNLS_SUCCESS;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolSetScalingVectors(SUNLinearSolver S,
N_Vector s1, N_Vector s2)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->setscalingvectors)
ier = S->ops->setscalingvectors(S, s1, s2);
else
ier = SUNLS_SUCCESS;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolSetZeroGuess(SUNLinearSolver S, booleantype onoff)
{
if (S->ops->setzeroguess)
return ((int) S->ops->setzeroguess(S, onoff));
else
return SUNLS_SUCCESS;
}
int SUNLinSolInitialize(SUNLinearSolver S)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->initialize)
ier = S->ops->initialize(S);
else
ier = SUNLS_SUCCESS;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolSetup(SUNLinearSolver S, SUNMatrix A)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->setup)
ier = S->ops->setup(S, A);
else
ier = SUNLS_SUCCESS;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolSolve(SUNLinearSolver S, SUNMatrix A, N_Vector x,
N_Vector b, realtype tol)
{
int ier;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
ier = S->ops->solve(S, A, x, b, tol);
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(ier);
}
int SUNLinSolNumIters(SUNLinearSolver S)
{
int ier;
if (S->ops->numiters)
ier = S->ops->numiters(S);
else
ier = 0;
return(ier);
}
realtype SUNLinSolResNorm(SUNLinearSolver S)
{
double result;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->resnorm)
result = S->ops->resnorm(S);
else
result = RCONST(0.0);
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(result);
}
N_Vector SUNLinSolResid(SUNLinearSolver S)
{
N_Vector resid;
SUNDIALS_MARK_FUNCTION_BEGIN(getSUNProfiler(S));
if (S->ops->resid)
resid = S->ops->resid(S);
else
resid = NULL;
SUNDIALS_MARK_FUNCTION_END(getSUNProfiler(S));
return(resid);
}
sunindextype SUNLinSolLastFlag(SUNLinearSolver S)
{
if (S->ops->lastflag)
return ((sunindextype) S->ops->lastflag(S));
else
return SUNLS_SUCCESS;
}
int SUNLinSolSpace(SUNLinearSolver S, long int *lenrwLS,
long int *leniwLS)
{
if (S->ops->space)
return ((int) S->ops->space(S, lenrwLS, leniwLS));
else {
*lenrwLS = 0;
*leniwLS = 0;
return SUNLS_SUCCESS;
}
}
int SUNLinSolFree(SUNLinearSolver S)
{
if (S == NULL) return SUNLS_SUCCESS;
/* if the free operation exists use it */
if (S->ops)
if (S->ops->free) return(S->ops->free(S));
/* if we reach this point, either ops == NULL or free == NULL,
try to cleanup by freeing the content, ops, and solver */
if (S->content) { free(S->content); S->content = NULL; }
if (S->ops) { free(S->ops); S->ops = NULL; }
free(S); S = NULL;
return(SUNLS_SUCCESS);
}
|
711767ab99a827e466d330e609c219454c87a9b8
|
8838eb997879add5759b6dfb23f9a646464e53ca
|
/platform/stm32/f4/stm32f4ve/stm32f4ve.h
|
53a9e00df868b3e65ebd4d9bece14c2c698fbba6
|
[
"BSD-2-Clause"
] |
permissive
|
embox/embox
|
d6aacec876978522f01cdc4b8de37a668c6f4c80
|
98e3c06e33f3fdac10a29c069c20775568e0a6d1
|
refs/heads/master
| 2023-09-04T03:02:20.165042
| 2023-09-02T14:55:31
| 2023-09-02T14:55:31
| 33,078,138
| 1,087
| 325
|
BSD-2-Clause
| 2023-09-14T16:58:34
| 2015-03-29T15:27:48
|
C
|
UTF-8
|
C
| false
| false
| 378
|
h
|
stm32f4ve.h
|
#ifndef __STM32F4VE_H
#define __STM32F4VE_H
#ifdef __cplusplus
extern "C" {
#endif
#include "stm32f4xx_hal.h"
/**
* @brief Define for STM32F4_DISCOVERY board
#if !defined (USE_STM32F4_DISCO)
#define USE_STM32F4_DISCO
#endif
*/
uint32_t BSP_GetVersion(void);
#ifdef __cplusplus
}
#endif
#endif /* __STM32F4VE_H */
|
b94b9e74c0a97592503fa15910c38331eba2ba69
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/mips/alchemy/dev/aupci.c
|
c96416f62279d6fbc56d1bf08f049c6d7bb183f1
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 11,863
|
c
|
aupci.c
|
/* $NetBSD: aupci.c,v 1.22 2022/09/29 07:00:46 skrll Exp $ */
/*-
* Copyright (c) 2006 Itronix Inc.
* All rights reserved.
*
* Written by Garrett D'Amore for Itronix Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of Itronix Inc. may not be used to endorse
* or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY ITRONIX INC. ``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 ITRONIX INC. 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 "opt_pci.h"
#include "pci.h"
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: aupci.c,v 1.22 2022/09/29 07:00:46 skrll Exp $");
#include <sys/types.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/systm.h>
#include <sys/errno.h>
#include <sys/device.h>
#include <sys/bus.h>
#include <uvm/uvm_extern.h>
#include <mips/locore.h>
#include <mips/pte.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <dev/pci/pciconf.h>
#ifdef PCI_NETBSD_CONFIGURE
#include <mips/cache.h>
#endif
#include <mips/alchemy/include/au_himem_space.h>
#include <mips/alchemy/include/aubusvar.h>
#include <mips/alchemy/include/aureg.h>
#include <mips/alchemy/include/auvar.h>
#include <mips/alchemy/dev/aupcireg.h>
#include <mips/alchemy/dev/aupcivar.h>
struct aupci_softc {
device_t sc_dev;
struct mips_pci_chipset sc_pc;
struct mips_bus_space sc_mem_space;
struct mips_bus_space sc_io_space;
struct mips_bus_space sc_cfg_space;
bus_space_tag_t sc_memt;
bus_space_tag_t sc_iot;
bus_space_tag_t sc_cfgt;
bus_space_tag_t sc_bust;
bus_space_handle_t sc_bush;
paddr_t sc_cfgbase;
paddr_t sc_membase;
paddr_t sc_iobase;
/* XXX: dma tag */
};
int aupcimatch(device_t, struct cfdata *, void *);
void aupciattach(device_t, device_t, void *);
#if NPCI > 0
static void aupci_attach_hook(device_t, device_t, struct pcibus_attach_args *);
static int aupci_bus_maxdevs(void *, int);
static pcitag_t aupci_make_tag(void *, int, int, int);
static void aupci_decompose_tag(void *, pcitag_t, int *, int *, int *);
static pcireg_t aupci_conf_read(void *, pcitag_t, int);
static void aupci_conf_write(void *, pcitag_t, int, pcireg_t);
static const char *aupci_intr_string(void *, pci_intr_handle_t, char *, size_t);
static void aupci_conf_interrupt(void *, int, int, int, int, int *);
static void *aupci_intr_establish(void *, pci_intr_handle_t, int,
int (*)(void *), void *);
static void aupci_intr_disestablish(void *, void *);
#define PCI_CFG_READ 0
#define PCI_CFG_WRITE 1
#define PCI_IO_START AUPCI_IO_START
#define PCI_IO_END AUPCI_IO_END
#define PCI_IO_SIZE ((PCI_IO_END - PCI_IO_START) + 1)
#define PCI_MEM_END 0xffffffff
#define PCI_MEM_SIZE(m) ((PCI_MEM_END - (m)) + 1)
#endif /* NPCI > 0 */
CFATTACH_DECL_NEW(aupci, sizeof(struct aupci_softc),
aupcimatch, aupciattach, NULL, NULL);
int aupci_found = 0;
/*
* Physical PCI addresses are 36-bits long, so we need to have
* adequate storage space for them.
*/
#if NPCI > 0
#if !defined(_MIPS_PADDR_T_64BIT) && !defined(_LP64)
#error "aupci requires 64 bit paddr_t!"
#endif
#endif
int
aupcimatch(device_t parent, struct cfdata *match, void *aux)
{
struct aubus_attach_args *aa = (struct aubus_attach_args *)aux;
if (strcmp(aa->aa_name, "aupci") != 0)
return 0;
if (aupci_found)
return 0;
return 1;
}
void
aupciattach(device_t parent, device_t self, void *aux)
{
struct aupci_softc *sc = device_private(self);
struct aubus_attach_args *aa = (struct aubus_attach_args *)aux;
uint32_t cfg;
#if NPCI > 0
uint32_t mbar, mask;
bus_addr_t mstart;
struct pcibus_attach_args pba;
#endif
aupci_found = 1;
sc->sc_dev = self;
sc->sc_bust = aa->aa_st;
if (bus_space_map(sc->sc_bust, aa->aa_addrs[0], 512, 0,
&sc->sc_bush) != 0) {
aprint_error(": unable to map PCI registers\n");
return;
}
#if NPCI > 0
/*
* These physical addresses are locked in on the CPUs we have
* seen. Perhaps these should be passed in via locators, thru
* the configuration file.
*/
sc->sc_cfgbase = PCI_CONFIG_BASE;
sc->sc_membase = PCI_MEM_BASE;
sc->sc_iobase = PCI_IO_BASE;
#endif
/*
* Configure byte swapping, as YAMON doesn't do it. YAMON does take
* care of most of the rest of the details (clocking, etc.), however.
*/
#if _BYTE_ORDER == _BIG_ENDIAN
/*
* N.B.: This still doesn't do the DMA thing properly. I have
* not yet figured out how to get DMA access to work properly
* without having bytes swapped while the processor is in
* big-endian mode. I'm not even sure that the Alchemy part
* can do it without swapping the bytes (which would be a
* bummer, since then only parts which had hardware detection
* and swapping support would work without special hacks in
* their drivers.)
*/
cfg = AUPCI_CONFIG_CH | AUPCI_CONFIG_R1H |
AUPCI_CONFIG_R2H | AUPCI_CONFIG_AEN |
AUPCI_CONFIG_SM | AUPCI_CONFIG_ST | AUPCI_CONFIG_SIC_DATA;
#else
cfg = AUPCI_CONFIG_CH | AUPCI_CONFIG_R1H |
AUPCI_CONFIG_R2H | AUPCI_CONFIG_AEN;
#endif
bus_space_write_4(sc->sc_bust, sc->sc_bush, AUPCI_CONFIG, cfg);
cfg = bus_space_read_4(sc->sc_bust, sc->sc_bush, AUPCI_COMMAND_STATUS);
aprint_normal(": Alchemy Host-PCI Bridge, %sMHz\n",
(cfg & PCI_STATUS_66MHZ_SUPPORT) ? "66" : "33");
aprint_naive("\n");
#if NPCI > 0
/*
* PCI configuration space. Address in this bus are
* orthogonal to other spaces. We need to make the entire
* 32-bit address space available.
*/
sc->sc_cfgt = &sc->sc_cfg_space;
au_himem_space_init(sc->sc_cfgt, "pcicfg", sc->sc_cfgbase,
0x00000000, 0xffffffff, AU_HIMEM_SPACE_IO);
/*
* Virtual PCI memory. Configured so that we don't overlap
* with PCI memory space.
*/
mask = bus_space_read_4(sc->sc_bust, sc->sc_bush, AUPCI_MWMASK);
mask >>= AUPCI_MWMASK_SHIFT;
mask <<= AUPCI_MWMASK_SHIFT;
mbar = bus_space_read_4(sc->sc_bust, sc->sc_bush, AUPCI_MBAR);
mstart = (mbar & mask) + (~mask + 1);
sc->sc_memt = &sc->sc_mem_space;
au_himem_space_init(sc->sc_memt, "pcimem", sc->sc_membase,
mstart, 0xffffffff, AU_HIMEM_SPACE_LITTLE_ENDIAN);
/*
* IO space. Address in this bus are orthogonal to other spaces.
* 16 MB should be plenty. We don't start from zero to avoid
* potential device bugs.
*/
sc->sc_iot = &sc->sc_io_space;
au_himem_space_init(sc->sc_iot, "pciio",
sc->sc_iobase, AUPCI_IO_START, AUPCI_IO_END,
AU_HIMEM_SPACE_LITTLE_ENDIAN | AU_HIMEM_SPACE_IO);
sc->sc_pc.pc_conf_v = sc;
sc->sc_pc.pc_attach_hook = aupci_attach_hook;
sc->sc_pc.pc_bus_maxdevs = aupci_bus_maxdevs;
sc->sc_pc.pc_make_tag = aupci_make_tag;
sc->sc_pc.pc_decompose_tag = aupci_decompose_tag;
sc->sc_pc.pc_conf_read = aupci_conf_read;
sc->sc_pc.pc_conf_write = aupci_conf_write;
sc->sc_pc.pc_intr_v = sc;
sc->sc_pc.pc_intr_map = aupci_intr_map;
sc->sc_pc.pc_intr_string = aupci_intr_string;
sc->sc_pc.pc_intr_establish = aupci_intr_establish;
sc->sc_pc.pc_intr_disestablish = aupci_intr_disestablish;
sc->sc_pc.pc_conf_interrupt = aupci_conf_interrupt;
#ifdef PCI_NETBSD_CONFIGURE
struct pciconf_resources *pcires = pciconf_resource_init();
pciconf_resource_add(pcires, PCICONF_RESOURCE_IO,
PCI_IO_START, PCI_IO_SIZE);
pciconf_resource_add(pcires, PCICONF_RESOURCE_MEM,
mstart, PCI_MEM_SIZE(mstart));
pci_configure_bus(&sc->sc_pc, pcires, 0,
mips_cache_info.mci_dcache_align);
pciconf_resource_fini(pcires);
#endif
pba.pba_iot = sc->sc_iot;
pba.pba_memt = sc->sc_memt;
/* XXX: review dma tag logic */
pba.pba_dmat = aa->aa_dt;
pba.pba_dmat64 = NULL;
pba.pba_pc = &sc->sc_pc;
pba.pba_flags = PCI_FLAGS_IO_OKAY | PCI_FLAGS_MEM_OKAY;
pba.pba_bus = 0;
pba.pba_bridgetag = NULL;
config_found(self, &pba, pcibusprint, CFARGS_NONE);
#endif /* NPCI > 0 */
}
#if NPCI > 0
void
aupci_attach_hook(device_t parent, device_t self,
struct pcibus_attach_args *pba)
{
}
int
aupci_bus_maxdevs(void *v, int busno)
{
return 32;
}
pcitag_t
aupci_make_tag(void *v, int bus, int device, int function)
{
pcitag_t tag;
if (bus >= 256 || device >= 32 || function >= 8)
panic("aupci_make_tag: bad request");
tag = (bus << 16) | (device << 11) | (function << 8);
return tag;
}
void
aupci_decompose_tag(void *v, pcitag_t tag, int *b, int *d, int *f)
{
if (b != NULL)
*b = (tag >> 16) & 0xff;
if (d != NULL)
*d = (tag >> 11) & 0x1f;
if (f != NULL)
*f = (tag >> 8) & 0x07;
}
static inline bool
aupci_conf_access(void *v, int dir, pcitag_t tag, int reg, pcireg_t *datap)
{
struct aupci_softc *sc = (struct aupci_softc *)v;
uint32_t status;
int s;
bus_addr_t addr;
int b, d, f;
bus_space_handle_t h;
if ((unsigned int)reg >= PCI_CONF_SIZE)
return false;
aupci_decompose_tag(v, tag, &b, &d, &f);
if (b) {
/* configuration type 1 */
addr = 0x80000000 | tag;
} else if (d > 19) {
/* device num too big for bus 0 */
return false;
} else {
addr = (0x800 << d) | (f << 8);
}
/* probing illegal target is OK, return an error indication */
if (addr == 0)
return false;
if (bus_space_map(sc->sc_cfgt, addr, 256, 0, &h) != 0)
return false;
s = splhigh();
if (dir == PCI_CFG_WRITE)
bus_space_write_4(sc->sc_cfgt, h, reg, *datap);
else
*datap = bus_space_read_4(sc->sc_cfgt, h, reg);
DELAY(2);
/* check for and clear master abort condition */
status = bus_space_read_4(sc->sc_bust, sc->sc_bush, AUPCI_CONFIG);
bus_space_write_4(sc->sc_bust, sc->sc_bush, AUPCI_CONFIG,
status & ~(AUPCI_CONFIG_EF));
splx(s);
bus_space_unmap(sc->sc_cfgt, h, 256);
/* if we got a PCI master abort, fail it */
if (status & AUPCI_CONFIG_EF)
return false;
return true;
}
pcireg_t
aupci_conf_read(void *v, pcitag_t tag, int reg)
{
pcireg_t data;
if (aupci_conf_access(v, PCI_CFG_READ, tag, reg, &data) == false)
return 0xffffffff;
return (data);
}
void
aupci_conf_write(void *v, pcitag_t tag, int reg, pcireg_t data)
{
aupci_conf_access(v, PCI_CFG_WRITE, tag, reg, &data);
}
const char *
aupci_intr_string(void *v, pci_intr_handle_t ih, char *buf, size_t len)
{
snprintf(buf, len, "irq %u", (unsigned)ih);
return buf;
}
void *
aupci_intr_establish(void *v, pci_intr_handle_t ih, int ipl,
int (*handler)(void *), void *arg)
{
return (au_intr_establish(ih, 0, ipl, IST_LEVEL_LOW, handler, arg));
}
void
aupci_intr_disestablish(void *v, void *cookie)
{
au_intr_disestablish(cookie);
}
void
aupci_conf_interrupt(void *v, int bus, int dev, int ipin, int swiz, int *iline)
{
/*
* We let the machdep_pci_intr_map take care of IRQ routing.
* On some platforms the BIOS may have handled this properly,
* on others it might not have. For now we avoid clobbering
* the settings establishsed by the BIOS, so that they will be
* there if the platform logic is confident that it can rely
* on them.
*/
}
#endif
|
598129ec1ad9b488999b236f0eb5a3f81f522a9d
|
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
|
/net/wmnet/files/patch-main.c
|
4634d148a59138d8bca6960a515777f18c01cf6c
|
[
"BSD-2-Clause"
] |
permissive
|
freebsd/freebsd-ports
|
86f2e89d43913412c4f6b2be3e255bc0945eac12
|
605a2983f245ac63f5420e023e7dce56898ad801
|
refs/heads/main
| 2023-08-30T21:46:28.720924
| 2023-08-30T19:33:44
| 2023-08-30T19:33:44
| 1,803,961
| 916
| 918
|
NOASSERTION
| 2023-09-08T04:06:26
| 2011-05-26T11:15:35
| null |
UTF-8
|
C
| false
| false
| 6,595
|
c
|
patch-main.c
|
--- main.c.orig Sat Jun 5 15:28:39 2004
+++ main.c Sat Jun 5 15:28:46 2004
@@ -32,11 +32,11 @@
#define LED_SZE_Y (4)
#define LED_ON_NET_X (87)
-#define LED_ON_NET_Y (66)
+#define LED_ON_NET_Y (92)
#define LED_OFF_NET_X (93)
-#define LED_OFF_NET_Y (66)
+#define LED_OFF_NET_Y (92)
#define LED_ERR_NET_X (81)
-#define LED_ERR_NET_Y (66)
+#define LED_ERR_NET_Y (92)
#define LED_PWR_X (53)
#define LED_PWR_Y (7)
@@ -52,6 +52,7 @@
static unsigned findInterface(char const*);
static void printversion(void);
static char const *rateToStr(unsigned long);
+static double getRate(unsigned long, char *);
static void SetErrLED(int);
static void SetOffLED(int);
static void SetOnLED(int);
@@ -68,7 +69,7 @@
------------------------------------------------------------------------------*/
static void DrawActiveIFS(char const* name)
{
- copyXPMArea(5, 84, 30, 10, 5, 5);
+ copyXPMArea(5, 110, 30, 10, 5, 5);
if (name) {
int ii, kk = 5;
@@ -77,9 +78,9 @@
int const ch = toupper(name[ii]);
if (ch >= 'A' && ch <= 'Z')
- copyXPMArea((ch - 'A') * 6, 74, 6, 9, kk, 5);
+ copyXPMArea((ch - 'A') * 6, 100, 6, 9, kk, 5);
else
- copyXPMArea((ch - '0') * 6, 64, 6, 9, kk, 5);
+ copyXPMArea((ch - '0') * 6, 90, 6, 9, kk, 5);
kk += 6;
}
}
@@ -91,25 +92,22 @@
static void DrawStats(unsigned ifCurr, int height, int x_left, int y_bottom)
{
unsigned baseLine = y_bottom - height / 2;
- unsigned maxVal = 0, ii;
+ unsigned maxVal = 0, ii, currVal = 0;
char const* ptr = 0;
/* Find the maximum value. We'll scale the graph to this value. */
+ unsigned long rcv, xmt;
for (ii = 0; ii < G_WIDTH; ++ii) {
- unsigned long rcv, xmt;
ifGetData(ifCurr, ii, &xmt, &rcv);
xmt /= delay;
rcv /= delay;
-
- if (rcv > maxVal)
- maxVal = rcv;
- if (xmt > maxVal)
- maxVal = xmt;
+ currVal = xmt > rcv ? xmt : rcv ;
+ if (currVal > maxVal)
+ maxVal = currVal;
}
- ptr = rateToStr(maxVal);
/* Now draw the data points. */
@@ -127,27 +125,58 @@
}
for (jj = 0; jj < height; ++jj)
if (y_bottom - jj <= start && y_bottom - jj >= stop)
- copyXPMArea(100 + 1, 68, 1, 1, ii + x_left, y_bottom - jj);
+ copyXPMArea(99 + 1, 106, 1, 1, ii + x_left, y_bottom - jj);
else
- copyXPMArea(100, 68, 1, 1, ii + x_left, y_bottom - jj);
+ copyXPMArea(99, 106, 1, 1, ii + x_left, y_bottom - jj);
/* Draw the base line. */
- copyXPMArea(100 + 3, 68, 1, 1, ii + x_left, baseLine);
+ copyXPMArea(100, 106, 1, 1, ii + x_left, baseLine);
}
- /* Now draw the data rate... */
+ /* Now draw the download data rate... */
+
+ /* Clear area */
+ copyXPMArea( 6, 111, 54 , 9 , 6, 63);
+
+ ptr = rateToStr(rcv);
+ copyXPMArea(('D' - 'A') * 6, 100, 6, 9, 6,
+ 62);
+ copyXPMArea(64, 90, 4, 9, 12,
+ 62);
+ for (ii = 20; *ptr; ++ptr)
+ if (isdigit(*ptr)) {
+ copyXPMArea((*ptr - '0') * 6, 90, 6, 9, 1 + ii, 62 );
+ ii += 6;
+ } else if ('.' == *ptr) {
+ copyXPMArea(60, 90, 4, 9, 1 + ii, 62);
+ ii += 4;
+ } else {
+ copyXPMArea((toupper(*ptr) - 'A') * 6, 100, 6, 9, 1 + ii,
+ 62);
+ ii += 6;
+ }
+
+ /* Now draw the upload data rate... */
+
+ /* Clear area */
+ copyXPMArea( 6, 111, 54 , 9 , 6, 76);
- for (ii = 5; *ptr; ++ptr)
+ ptr = rateToStr(xmt);
+ copyXPMArea(('U' - 'A') * 6, 100, 6, 9, 6,
+ 75);
+ copyXPMArea(64, 90, 4, 9, 12,
+ 75);
+ for (ii = 20; *ptr; ++ptr)
if (isdigit(*ptr)) {
- copyXPMArea((*ptr - '0') * 6, 64, 6, 9, 1 + ii, y_bottom - 10);
+ copyXPMArea((*ptr - '0') * 6, 90, 6, 9, 1 + ii, 75 );
ii += 6;
} else if ('.' == *ptr) {
- copyXPMArea(60, 64, 4, 9, 1 + ii, y_bottom - 10);
+ copyXPMArea(60, 90, 4, 9, 1 + ii, 75);
ii += 4;
} else {
- copyXPMArea((toupper(*ptr) - 'A') * 6, 74, 6, 9, 1 + ii,
- y_bottom - 10);
+ copyXPMArea((toupper(*ptr) - 'A') * 6, 100, 6, 9, 1 + ii,
+ 75);
ii += 6;
}
@@ -205,41 +234,39 @@
------------------------------------------------------------------------------*/
static char const* rateToStr(unsigned long rate)
{
- static char buffer[7];
- char scaleFactor, *ptr = buffer;
+ static char buffer[14];
+ char scaleFactor='\0', *ptr = buffer;
- /* Based upon its magnitude, determine how much 'rate' needs to be
- scaled and also indicate its unit of scale. */
-
- if (rate > 1000000) {
- rate /= 100000;
- scaleFactor = 'M';
- } else if (rate > 1000) {
- rate /= 100;
- scaleFactor = 'K';
- } else {
- rate *= 10;
- scaleFactor = '\0';
- }
+ double drate = getRate(rate,&scaleFactor);
- /* Transform the value into a left - justified string. */
-
- if (rate >= 1000)
- *ptr++ = rate / 1000 + '0';
- if (rate >= 100)
- *ptr++ = (rate / 100) % 10 + '0';
- if (rate >= 10)
- *ptr++ = (rate / 10) % 10 + '0';
- if (scaleFactor) {
- *ptr++ = '.';
- *ptr++ = rate % 10 + '0';
- }
+ /* Transform the rate value into a left - justified string. */
+ ptr+=sprintf(ptr,"%.1f",drate);
*ptr++ = scaleFactor;
*ptr = '\0';
return buffer;
}
/*------------------------------------------------------------------------------
+ getRate
+------------------------------------------------------------------------------*/
+static double getRate(unsigned long rate, char *scaleFactor)
+{
+ double drate = rate;
+
+ /* Based upon its magnitude, determine how much 'rate' needs to be
+ scaled and also indicate its unit of scale. */
+
+ if (rate > 1048576) {
+ drate /= 1048576;
+ *scaleFactor = 'M';
+ } else if (rate > 1024) {
+ drate /= 1024;
+ *scaleFactor = 'K';
+ }
+ return drate;
+}
+
+/*------------------------------------------------------------------------------
SetErrLED
------------------------------------------------------------------------------*/
static void SetErrLED(int led)
@@ -314,10 +341,11 @@
{
static char const txt[] =
"\nwmnet, v1p2 - A network interface monitor for WindowMaker.\n\n"
- "\t-h this help screen\n"
- "\t-i name start with interface 'name'\n"
- "\t-u delay seconds between samples (defaults to 1)\n"
- "\t-v print the version number\n";
+ "\t-h this help screen\n"
+ "\t-i name start with interface 'name'\n"
+ "\t-u delay seconds between samples (defaults to 1)\n"
+ "\t-geom <geometry> geometry to use\n"
+ "\t-v print the version number\n";
fputs(txt, stderr);
}
@@ -425,6 +453,13 @@
case 'v':
printversion();
return 0;
+
+ case 'g':
+ if (ii + 1 == argc) {
+ printf("wmnet: must specify geometry\n");
+ return 0;
+ }
+ break;
default:
usage();
|
3d52ba88836c106f2b7f3e055932aa408a79e689
|
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
|
/sys/arch/evbarm/tsarm/isa/isa_machdep.c
|
c0cd7aa01baa9ade3639bc67fd4919642c7c43f2
|
[] |
no_license
|
NetBSD/src
|
1a9cbc22ed778be638b37869ed4fb5c8dd616166
|
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
|
refs/heads/trunk
| 2023-08-31T13:24:58.105962
| 2023-08-27T15:50:47
| 2023-08-27T15:50:47
| 88,439,547
| 656
| 348
| null | 2023-07-20T20:07:24
| 2017-04-16T20:03:43
| null |
UTF-8
|
C
| false
| false
| 6,122
|
c
|
isa_machdep.c
|
/* $NetBSD: isa_machdep.c,v 1.13 2014/03/08 18:08:16 skrll Exp $ */
/*-
* Copyright (c) 1996-1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jesse Off
*
* This code is derived from software contributed to The NetBSD Foundation
* by Mark Brinicombe, Charles M. Hannum and by Jason R. Thorpe of the
* Numerical Aerospace Simulation Facility, NASA Ames Research Center.
*
* 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 NETBSD FOUNDATION, INC. 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.
*/
/*-
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* 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 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.
*
* @(#)isa.c 7.2 (Berkeley) 5/13/91
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: isa_machdep.c,v 1.13 2014/03/08 18:08:16 skrll Exp $");
#include "opt_irqstats.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/syslog.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/bus.h>
#include <machine/intr.h>
#include <machine/pio.h>
#include <machine/bootconfig.h>
#include <machine/isa_machdep.h>
#include <dev/isa/isareg.h>
#include <dev/isa/isavar.h>
#include <arm/ep93xx/ep93xxvar.h>
#include <uvm/uvm_extern.h>
/* prototypes */
void isa_tsarm_init(u_int, u_int);
struct arm32_isa_chipset isa_chipset_tag;
static unsigned int ep93xxirq[3] = { 20, 33, 40 };
/* only have 3 irqs connected to real lines on TS-7xxx */
static unsigned int isairq[3] = { 5, 6, 7 };
static unsigned int isairq_nhandlers[3] = { 0, 0, 0 };
int
isa_intr_alloc(isa_chipset_tag_t ic, int mask, int type, int *irq)
{
int i, bestirq, count;
if (type == IST_NONE)
panic("intr_alloc: bogus type");
bestirq = -1;
count = -1;
/* some interrupts should never be dynamically allocated */
mask &= 0x00e0;
for (i = 0; i < __arraycount(isairq); i++) {
if ((mask & (1<<isairq[i])) == 0)
continue;
if (isairq_nhandlers[i] < count || count == -1) {
bestirq = isairq[i];
count = isairq_nhandlers[i];
}
}
if (bestirq == -1)
return (1);
*irq = bestirq;
return (0);
}
const struct evcnt *
isa_intr_evcnt(isa_chipset_tag_t ic, int irq)
{
return NULL;
}
/*
* Set up an interrupt handler to start being called.
*/
void *
isa_intr_establish(isa_chipset_tag_t ic, int irq, int type, int level, int (*ih_fun)(void *), void *ih_arg)
{
int epirq = -1, i;
/* Find real EP93XX irq number */
for(i = 0; i < __arraycount(isairq); i++) {
if (irq == isairq[i]) epirq = ep93xxirq[i];
}
if (epirq == -1)
return NULL;
else
return (ep93xx_intr_establish(epirq, level, ih_fun, ih_arg));
}
/*
* Deregister an interrupt handler.
*/
void
isa_intr_disestablish(isa_chipset_tag_t ic, void *arg)
{
ep93xx_intr_disestablish(arg);
}
void
isa_tsarm_init(u_int iobase16, u_int membase16)
{
isa_io_init(iobase16, membase16);
}
/*
* isa_intr_init()
*
* TODO: Set up ISA IRQ 5 on GPIO pin
*/
void
isa_intr_init(void)
{
}
void
isa_attach_hook(device_t parent, device_t self, struct isabus_attach_args *iba)
{
/*
* Since we can only have one ISA bus, we just use a single
* statically allocated ISA chipset structure. Pass it up
* now.
*/
iba->iba_ic = &isa_chipset_tag;
printf(": PC/104 expansion bus");
}
void
isa_detach_hook(isa_chipset_tag_t ic, device_t self)
{
}
|
498a7dd19288e7235ab9a03f04fd81dcedf16a4d
|
d38ed5f31d74a79a054ed55dd9123a8d615283b9
|
/third_party/libgit2/tests/refs/list.c
|
3e8c82c94b6feb752313bfb56d7028ef9d45d8ad
|
[
"Apache-2.0",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"GCC-exception-2.0",
"LGPL-2.0-or-later",
"Zlib",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"ISC",
"MIT"
] |
permissive
|
chigraph/chigraph
|
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
|
6981bdd6763db54edfe284c1f7d223193584c69a
|
refs/heads/master
| 2022-12-21T13:46:57.273039
| 2022-12-17T18:41:19
| 2022-12-17T18:41:19
| 60,776,831
| 364
| 65
|
Apache-2.0
| 2019-12-13T14:46:43
| 2016-06-09T13:27:37
|
C++
|
UTF-8
|
C
| false
| false
| 1,219
|
c
|
list.c
|
#include "clar_libgit2.h"
#include "repository.h"
#include "git2/reflog.h"
#include "reflog.h"
static git_repository *g_repo;
void test_refs_list__initialize(void)
{
g_repo = cl_git_sandbox_init("testrepo");
}
void test_refs_list__cleanup(void)
{
cl_git_sandbox_cleanup();
}
void test_refs_list__all(void)
{
/* try to list all the references in our test repo */
git_strarray ref_list;
cl_git_pass(git_reference_list(&ref_list, g_repo));
/*{
unsigned short i;
for (i = 0; i < ref_list.count; ++i)
printf("# %s\n", ref_list.strings[i]);
}*/
/* We have exactly 12 refs in total if we include the packed ones:
* there is a reference that exists both in the packfile and as
* loose, but we only list it once */
cl_assert_equal_i((int)ref_list.count, 18);
git_strarray_free(&ref_list);
}
void test_refs_list__do_not_retrieve_references_which_name_end_with_a_lock_extension(void)
{
git_strarray ref_list;
/* Create a fake locked reference */
cl_git_mkfile(
"./testrepo/.git/refs/heads/hanwen.lock",
"144344043ba4d4a405da03de3844aa829ae8be0e\n");
cl_git_pass(git_reference_list(&ref_list, g_repo));
cl_assert_equal_i((int)ref_list.count, 18);
git_strarray_free(&ref_list);
}
|
73da7c9784c9c2eb6dd007b3adb0acb3eb3992c1
|
995c73cc45a35afe22229aac5e707c2406ef44a7
|
/original/sig.c
|
bd555f5937b6d34e043d488ae369f1fe63b19338
|
[
"Unlicense"
] |
permissive
|
diogocabral/sherlock
|
2646991f310f0c0f0f85260537bedb76290aaddf
|
2299e4b123e986ce8d54121631e49b006e52af74
|
refs/heads/master
| 2022-05-28T12:20:15.326333
| 2022-05-13T02:19:02
| 2022-05-13T02:19:02
| 58,764,117
| 129
| 41
|
Unlicense
| 2022-05-13T02:19:03
| 2016-05-13T18:38:51
|
C
|
UTF-8
|
C
| false
| false
| 2,929
|
c
|
sig.c
|
/*
* sig.c - written by Rob Pike, modified by Loki
*
* This program doesn't quite do what the specification says.
* It adds a '-o outfile' option which allows the user to
* specify which file should receive the output (rather than
* always going to stdout). The default is still stdout.
* It also doesn't use stdin as input. This was done so that
* the usage message would appear if the user just types 'sig'.
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
enum{
WORDSIZE = 128
};
int Ntoken = 3;
int Zerobits = 4;
unsigned long zeromask;
int ntoken = 0;
char ** token;
FILE * outfile;
void signature(FILE*);
void usage(void)
{
fprintf(stderr, "usage: sig");
fprintf(stderr, " [-z zerobits]");
fprintf(stderr, " [-n chainlength]");
fprintf(stderr, " [-o outfile]");
fprintf(stderr, " file ...\n");
fprintf(stderr, "defaults:");
fprintf(stderr, " zerobits=3");
fprintf(stderr, " chainlength=4");
fprintf(stderr, " outfile=the screen");
fprintf(stderr, "\n");
exit(2);
}
int main(int argc, char *argv[])
{
FILE *f;
int i, start, nfiles;
char *s, *outname;
outfile = stdout;
outname = NULL;
for (start=1; start < argc; start++) {
if (argv[start][0] != '-')
break;
switch (argv[start][1]) {
case 'z':
s = argv[++start];
if (s == NULL)
usage();
Zerobits = atoi(s);
if (Zerobits < 0 || Zerobits > 31)
usage();
break;
case 'n':
s = argv[++start];
if (s == NULL)
usage();
Ntoken = atoi(s);
if (Ntoken <= 0)
usage();
break;
case 'o':
s = argv[++start];
if (s == NULL)
usage();
outname = s;
break;
default:
usage();
}
}
nfiles = argc - start;
if (nfiles < 1)
usage();
if (outname != NULL)
outfile = fopen(outname, "w");
zeromask = (1<<Zerobits)-1;
for (i=start; i < argc; i++) {
f = fopen(argv[i], "r");
if (f == NULL) {
fprintf(stderr, "sig: can't open %s:", argv[i]);
perror(NULL);
continue;
}
signature(f);
fclose(f);
}
return 0;
}
unsigned long hash(char *tok[])
{
unsigned long h;
unsigned char *s;
int i;
h = 0;
for (i=0; i < Ntoken; i++)
for (s=(unsigned char*)tok[i]; *s; s++)
h = h*31 + *s;
return h;
}
void dotoken(char *s)
{
unsigned long h;
int i;
for (i=Ntoken; --i > 0; )
strcpy(token[i], token[i-1]);
strcpy(token[0], s);
ntoken++;
if (ntoken < Ntoken)
return;
h = hash(token);
if ((h & zeromask) == 0)
fprintf(outfile, "%0lx\n", h>>Zerobits);
}
void tokenize(char *s)
{
char *t, *e;
e = s+strlen(s);
while (s < e) {
while (*s=='\t' || *s=='\n' || *s==' ')
s++;
t = s;
while (*s!= '\0' && *s!='\t' && *s!='\n' && *s!=' ')
s++;
*s = '\0';
if (s > t)
dotoken(t);
s++;
}
}
void signature(FILE *f)
{
char buf[1024];
int i;
token = malloc(Ntoken * sizeof(char*));
for(i=0; i < Ntoken; i++)
token[i] = malloc(WORDSIZE+1);
while (fgets(buf, sizeof buf, f) != NULL)
tokenize(buf);
}
|
1c0660878fd3e791d143a1396aadcb6035a1146e
|
af8fe84a9a43f5d7309cca301a791e9a1da6edf2
|
/external/asf4-drivers/hal/include/hpl_mci_sync.h
|
29c0ac157922c0d9b6f7c5ae119125ecf64c6fc8
|
[
"Apache-2.0"
] |
permissive
|
digitalbitbox/bitbox02-firmware
|
c2581b02088009385d7c40066ad940a469eca761
|
12cfa59f05c200a72fa204961e3a5f8b3d3c0ba0
|
refs/heads/master
| 2023-08-31T22:14:19.307352
| 2023-08-31T09:29:16
| 2023-08-31T09:29:16
| 190,549,724
| 219
| 87
|
Apache-2.0
| 2023-09-14T07:10:09
| 2019-06-06T09:00:23
|
C
|
UTF-8
|
C
| false
| false
| 8,415
|
h
|
hpl_mci_sync.h
|
/**
* \file
*
* \brief SAM MCI HPL
*
* Copyright (C) 2016 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef _HPL_MCI_H_INCLUDED
#define _HPL_MCI_H_INCLUDED
#include <compiler.h>
#include <utils.h>
#ifdef __cplusplus
extern "C" {
#endif
//! \name Flags used to define MCI parser for SD/MMC command
//! @{
//! Have response
#define MCI_RESP_PRESENT (1lu << 8)
//! 136 bit response
#define MCI_RESP_136 (1lu << 11)
//! Expect valid crc
#define MCI_RESP_CRC (1lu << 12)
//! Card may send busy
#define MCI_RESP_BUSY (1lu << 13)
//! Open drain for a braodcast command
#define MCI_CMD_OPENDRAIN (1lu << 14)
//! To signal a data write operation
#define MCI_CMD_WRITE (1lu << 15)
//! To signal a SDIO tranfer in multi byte mode
#define MCI_CMD_SDIO_BYTE (1lu << 16)
//! To signal a SDIO tranfer in block mode
#define MCI_CMD_SDIO_BLOCK (1lu << 17)
//! To signal a data transfer in stream mode
#define MCI_CMD_STREAM (1lu << 18)
//! To signal a data transfer in single block mode
#define MCI_CMD_SINGLE_BLOCK (1lu << 19)
//! To signal a data transfer in multi block mode
#define MCI_CMD_MULTI_BLOCK (1lu << 20)
//! @}
/**
* \brief mci sync device structure
*/
struct _mci_sync_device {
void * hw;
uint64_t mci_sync_trans_pos;
uint16_t mci_sync_block_size;
uint16_t mci_sync_nb_block;
};
/**
* \brief Initialize MCI low level driver.
*
* \return Operation status.
* \retval 0 Success.
* \retval <0 Error code.
*/
int32_t _mci_sync_init(struct _mci_sync_device *const mci_dev, void *const hw);
/**
* \brief Deinitialize MCI low level driver.
*
* \return Operation status.
* \retval 0 Success.
* \retval <0 Error code.
*/
int32_t _mci_sync_deinit(struct _mci_sync_device *const mci_dev);
/**
* \brief Select a device and initialize it
*
* \param[in] slot Selected slot
* \param[in] clock Maximum clock to use (Hz)
* \param[in] bus_width Bus width to use (1, 4 or 8)
* \param[in] high_speed true, to enable high speed mode
* \return Operation status.
* \retval 0 Success.
* \retval <0 Error code.
*/
int32_t _mci_sync_select_device(struct _mci_sync_device *const mci_dev, uint8_t slot, uint32_t clock, uint8_t bus_width,
bool high_speed);
/**
* \brief Get the maximum bus width of a device
* by a selected slot
*
* \param[in] slot Selected slot
* \return bus width.
*/
uint8_t _mci_sync_get_bus_width(struct _mci_sync_device *const mci_dev, uint8_t slot);
/**
* \brief Get the high speed capability of the device.
*
* \return true, if the high speed is supported.
*/
bool _mci_sync_is_high_speed_capable(struct _mci_sync_device *const mci_dev);
/**
* \brief Send 74 clock cycles on the line.
* Note: It is required after card plug and before card install.
*/
void _mci_sync_send_clock(struct _mci_sync_device *const mci_dev);
/**
* \brief Disable the bus clock.
*/
void _mci_sync_pause_clock(struct _mci_sync_device *const mci_dev);
/**
* \brief Resume the bus clock.
*/
void _mci_sync_resume_clock(struct _mci_sync_device *const mci_dev);
/**
* \brief Send a command on the selected slot
*
* \param[in] cmd Command definition
* \param[in] arg Argument of the command
* \return true if success, otherwise false
*/
bool _mci_sync_send_cmd(struct _mci_sync_device *const mci_dev, uint32_t cmd, uint32_t arg);
/**
* \brief Get 32 bits response of the last command.
*
* \return 32 bits response.
*/
uint32_t _mci_sync_get_response(struct _mci_sync_device *const mci_dev);
/**
* \brief Get 128 bits response of the last command.
*
* \param[in] response Pointer on the array to fill
* with the 128 bits response.
*/
void _mci_sync_get_response_128(struct _mci_sync_device *const mci_dev, uint8_t *response);
/**
* \brief Send an ADTC command on the selected slot
* An ADTC (Addressed Data Transfer Commands)
* command is used for read/write access..
*
* \param[in] cmd Command definition.
* \param[in] arg Argument of the command.
* \param[in] block_size Block size used for the transfer.
* \param[in] nb_block Total number of block for this transfer
* \param[in] access_block if true, the x_read_blocks() and x_write_blocks()
* functions must be used after this function.
* If false, the mci_read_word() and mci_write_word()
* functions must be used after this function.
*
* \return true if success, otherwise false
*/
bool _mci_sync_adtc_start(struct _mci_sync_device *const mci_dev, uint32_t cmd, uint32_t arg, uint16_t block_size,
uint16_t nb_block, bool access_block);
/**
* \brief Send a command to stop an ADTC command on the selected slot.
*
* \param[in] cmd Command definition
* \param[in] arg Argument of the command
*
* \return true if success, otherwise false
*/
bool _mci_sync_adtc_stop(struct _mci_sync_device *const mci_dev, uint32_t cmd, uint32_t arg);
/**
* \brief Read a word on the line.
*
* \param[in] value Pointer on a word to fill.
*
* \return true if success, otherwise false
*/
bool _mci_sync_read_word(struct _mci_sync_device *const mci_dev, uint32_t *value);
/**
* \brief Write a word on the line
*
* \param[in] value Word to send
*
* \return true if success, otherwise false
*/
bool _mci_sync_write_word(struct _mci_sync_device *const mci_dev, uint32_t value);
/**
* \brief Start a read blocks transfer on the line
* Note: The driver will use the DMA available to speed up the transfer.
*
* \param[in] dst Pointer on the buffer to fill
* \param[in] nb_block Number of block to transfer
*
* \return true if started, otherwise false
*/
bool _mci_sync_start_read_blocks(struct _mci_sync_device *const mci_dev, void *dst, uint16_t nb_block);
/**
* \brief Start a write blocks transfer on the line
* Note: The driver will use the DMA available to speed up the transfer.
*
* \param[in] src Pointer on the buffer to send
* \param[in] nb_block Number of block to transfer
*
* \return true if started, otherwise false
*/
bool _mci_sync_start_write_blocks(struct _mci_sync_device *const mci_dev, const void *src, uint16_t nb_block);
/**
* \brief Wait the end of transfer initiated by mci_start_read_blocks()
*
* \return true if success, otherwise false
*/
bool _mci_sync_wait_end_of_read_blocks(struct _mci_sync_device *const mci_dev);
/**
* \brief Wait the end of transfer initiated by mci_start_write_blocks()
*
* \return true if success, otherwise false
*/
bool _mci_sync_wait_end_of_write_blocks(struct _mci_sync_device *const mci_dev);
#ifdef __cplusplus
}
#endif
#endif /* _HPL_MCI_H_INCLUDED */
|
14fc8be03920f6d93a1df353c4baf8d39202bbe7
|
f3eed0234b4d0ad2bbb2abd700cf1e2c7a0e8a1d
|
/AKWF-c/AKWF_vgamebasic/AKWF_vgsin_0016.h
|
27793cbd41662d0e355cce3d7cf4a4a1ba44ef78
|
[
"CC0-1.0"
] |
permissive
|
KristofferKarlAxelEkstrand/AKWF-FREE
|
b2defa1a2d389d309be6dd2e9f968923daf80d1b
|
cf8171df36e9fec25416b5f568b72a6e2cb69194
|
refs/heads/master
| 2023-07-23T18:22:36.939705
| 2023-07-10T17:14:40
| 2023-07-10T17:14:40
| 145,817,187
| 359
| 59
|
CC0-1.0
| 2023-07-10T17:14:41
| 2018-08-23T07:26:56
| null |
UTF-8
|
C
| false
| false
| 4,684
|
h
|
AKWF_vgsin_0016.h
|
/* Adventure Kid Waveforms (AKWF) converted for use with Teensy Audio Library
*
* Adventure Kid Waveforms(AKWF) Open waveforms library
* https://www.adventurekid.se/akrt/waveforms/adventure-kid-waveforms/
*
* This code is in the public domain, CC0 1.0 Universal (CC0 1.0)
* https://creativecommons.org/publicdomain/zero/1.0/
*
* Converted by Brad Roy, https://github.com/prosper00
*/
/* AKWF_vgsin_0016 256 samples
+-----------------------------------------------------------------------------------------------------------------+
| ****** ***** |
| **** **** |
| **** *** |
| *** **** |
| *** *** |
| *** **** |
| ** *** |
|* *** *|
| *** ***|
| **** **** |
| *** *** |
| **** ** |
| **** ***** |
| **** **** |
| ****** ****** |
+-----------------------------------------------------------------------------------------------------------------+
*/
const uint16_t AKWF_vgsin_0016 [] = {
33228, 34155, 34257, 34585, 35508, 36061, 37467, 38576, 38796, 39548, 40201, 41092, 41753, 42542, 44058, 44787,
44720, 45425, 46176, 46909, 48499, 49123, 49126, 49780, 50617, 51083, 52428, 53067, 53070, 53671, 54018, 54955,
55520, 56238, 57183, 57396, 57605, 58174, 58594, 59284, 59865, 59974, 60278, 60765, 61304, 61437, 61804, 62610,
62985, 62870, 62952, 63264, 63447, 63935, 64289, 64183, 64262, 64593, 64714, 64596, 64909, 65138, 65083, 65110,
65088, 65112, 65083, 65123, 65062, 64706, 64619, 64730, 64384, 64216, 64185, 63849, 63627, 63365, 63088, 62887,
62503, 62051, 61906, 61577, 61368, 61088, 60424, 60200, 59561, 58877, 58794, 58400, 57856, 57431, 56482, 55783,
55774, 55258, 54441, 53776, 53410, 52807, 51515, 50878, 50947, 50138, 49475, 48575, 47383, 46996, 46530, 45777,
45052, 44171, 43610, 42836, 41483, 41339, 39898, 39177, 39441, 37893, 36775, 36325, 35860, 34969, 34403, 33169,
31857, 31604, 30939, 30252, 29411, 28664, 28011, 26521, 25608, 25332, 24598, 23864, 23123, 21884, 21270, 20950,
20193, 19510, 18621, 17966, 17365, 16038, 15499, 15521, 14698, 14029, 13133, 11901, 11676, 11479, 10964, 10526,
9598, 9060, 8273, 7387, 7278, 6968, 6426, 5983, 5268, 4755, 4671, 4284, 4142, 3772, 3167, 2897,
2423, 2124, 1923, 1616, 1405, 1112, 863, 877, 552, 371, 510, 250, 0, 0, 8, 0,
12, 0, 15, 2, 368, 460, 423, 451, 404, 753, 914, 1352, 1789, 1731, 1734, 2066,
2217, 2760, 3548, 3648, 4024, 4163, 4557, 5163, 5386, 6104, 6697, 6766, 7223, 7743, 8191, 9235,
9725, 10198, 10759, 11241, 11695, 12945, 14076, 13814, 14316, 15183, 15760, 16116, 17145, 18671, 18951, 19091,
19870, 20591, 21481, 23171, 23631, 23477, 24249, 24996, 26190, 26891, 28173, 29423, 29393, 29822, 30615, 31378,
};
|
b8b083c10daed9485aab3f6433417e295a930767
|
632f6f14abb1dbdf86aca1506b8012392bef2a41
|
/source/daplink/info.h
|
2250f84a785860d10f93f052c2c35b89388471be
|
[
"Apache-2.0"
] |
permissive
|
ARMmbed/DAPLink
|
a34f7ce41d6bfc38d49283766a03280f52322f2a
|
19f797fa6396b726250c57eb9be80245a5f877dd
|
refs/heads/main
| 2023-08-23T20:37:22.744671
| 2023-06-29T19:36:00
| 2023-08-16T16:39:58
| 24,571,059
| 1,865
| 883
|
Apache-2.0
| 2023-08-16T16:39:59
| 2014-09-28T21:38:24
|
C
|
UTF-8
|
C
| false
| false
| 2,701
|
h
|
info.h
|
/**
* @file info.h
* @brief methods to get information about the board
*
* DAPLink Interface Firmware
* Copyright (c) 2009-2016, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INFO_H
#define INFO_H
#include <stdbool.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void info_init(void);
void info_set_uuid_target(uint32_t *uuid_data);
void info_crc_compute(void);
// Get the 48 digit unique ID as a null terminated string.
// This is the string used as the USB serial number.
// This string is made up of the following:
// <board ID><family ID><host ID><hic ID>
const char *info_get_unique_id(void);
// Get the 4 digit board ID as a null terminated string
const char *info_get_board_id(void);
// Get the 32 digit ID of the processor running daplink as a null terminated string
const char *info_get_host_id(void);
// Get the 32 digit ID of the target processor as a null terminated string
const char *info_get_target_id(void);
// Get the 8 digit hic ID as a null terminated string
const char *info_get_hic_id(void);
// Get the 4 digit version ID as a null terminated string
const char *info_get_version(void);
// Get the 12 digit mac as a null terminated string
const char *info_get_mac(void);
// Get the string descriptor for for the unique_id
// This is in the format of a USB string descriptor
// offset 0, size 1, bLength
// offset 1, size 1, bDescriptorType always 3
// offset 2, size n, bString - unicode encoded unique id
const char *info_get_unique_id_string_descriptor(void);
// Check if various regions are present
bool info_get_bootloader_present(void);
bool info_get_interface_present(void);
bool info_get_config_admin_present(void);
bool info_get_config_user_present(void);
// Get the CRCs of various regions.
// The CRC returned is only valid if
// the given region is present.
uint32_t info_get_crc_bootloader(void);
uint32_t info_get_crc_interface(void);
uint32_t info_get_crc_config_user(void);
// Get version info as an integer
uint32_t info_get_bootloader_version(void);
uint32_t info_get_interface_version(void);
#ifdef __cplusplus
}
#endif
#endif
|
b3065ca7764afce8cdd357f20b4726ea016c05fe
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/m68k-linux-any/asm/bootinfo-atari.h
|
854bda646746765db40dc1c1664dbed0faa59364
|
[
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 999
|
h
|
bootinfo-atari.h
|
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
/*
** asm/bootinfo-atari.h -- Atari-specific boot information definitions
*/
#ifndef _ASM_M68K_BOOTINFO_ATARI_H
#define _ASM_M68K_BOOTINFO_ATARI_H
/*
* Atari-specific tags
*/
#define BI_ATARI_MCH_COOKIE 0x8000 /* _MCH cookie from TOS (__be32) */
#define BI_ATARI_MCH_TYPE 0x8001 /* special machine type (__be32) */
/*
* mch_cookie values (upper word of BI_ATARI_MCH_COOKIE)
*/
#define ATARI_MCH_ST 0
#define ATARI_MCH_STE 1
#define ATARI_MCH_TT 2
#define ATARI_MCH_FALCON 3
/*
* Atari machine types (BI_ATARI_MCH_TYPE)
*/
#define ATARI_MACH_NORMAL 0 /* no special machine type */
#define ATARI_MACH_MEDUSA 1 /* Medusa 040 */
#define ATARI_MACH_HADES 2 /* Hades 040 or 060 */
#define ATARI_MACH_AB40 3 /* Afterburner040 on Falcon */
/*
* Latest Atari bootinfo version
*/
#define ATARI_BOOTI_VERSION MK_BI_VERSION(2, 1)
#endif /* _ASM_M68K_BOOTINFO_ATARI_H */
|
2af5fd1b8bf8dad224d396456f011866f6e31119
|
98ee5bc94e754d9b1802d66d7b5c5fcf184a6c90
|
/lib/include/kasumi_internal.h
|
d9d26068ca358423808c107ce17c1f25e34de76d
|
[
"BSD-3-Clause"
] |
permissive
|
intel/intel-ipsec-mb
|
f180701ca3dbdc26f310c5706cb3e8577defa2df
|
9e17d6cad1f99e64f3534053a3ff096c46646058
|
refs/heads/main
| 2023-08-30T13:20:47.709185
| 2023-08-28T13:17:46
| 2023-08-29T13:14:00
| 73,856,328
| 255
| 89
|
BSD-3-Clause
| 2023-08-30T08:42:45
| 2016-11-15T21:22:17
|
C
|
UTF-8
|
C
| false
| false
| 76,974
|
h
|
kasumi_internal.h
|
/*******************************************************************************
Copyright (c) 2009-2023, Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
/*---------------------------------------------------------
* Kasumi_internal.h
*---------------------------------------------------------*/
#ifndef _KASUMI_INTERNAL_H_
#define _KASUMI_INTERNAL_H_
#include <sys/types.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include "intel-ipsec-mb.h"
#include "wireless_common.h"
#include "include/clear_regs_mem.h"
#include "include/constant_lookup.h"
#include "memcpy.h"
#include "error.h"
#include "kasumi_interface.h"
/*---------------------------------------------------------------------
* Kasumi Inner S-Boxes
*---------------------------------------------------------------------*/
/* Table version based on a small table, no cache trash */
static const uint16_t sso_kasumi_S7e[] = {
0x6c00, 0x6601, 0x7802, 0x7603, 0x2404, 0x4e05, 0xb006, 0xce07,
0x5c08, 0x1e09, 0x6a0a, 0xac0b, 0x1c0c, 0x3e0d, 0xea0e, 0x5c0f,
0x4e10, 0xc011, 0x6a12, 0xc213, 0x0214, 0xac15, 0xae16, 0x3617,
0x6e18, 0xa019, 0x681a, 0x001b, 0x0a1c, 0xe41d, 0xc41e, 0x9c1f,
0x2a20, 0x5021, 0xb622, 0xd823, 0x2024, 0x3225, 0x3826, 0x2e27,
0x9a28, 0xac29, 0x042a, 0xa62b, 0x882c, 0xd62d, 0xd22e, 0x082f,
0x4830, 0x9631, 0xf432, 0x1c33, 0x4634, 0xb035, 0x7636, 0xa637,
0xea38, 0x7039, 0x543a, 0x783b, 0xdc3c, 0x6e3d, 0xae3e, 0xba3f,
0x6a40, 0x6a41, 0x1c42, 0x9043, 0x3a44, 0x5e45, 0x8c46, 0x7447,
0x7c48, 0x5449, 0x384a, 0x1c4b, 0xa44c, 0xe84d, 0x604e, 0x304f,
0x4050, 0xc451, 0x8652, 0xac53, 0x1654, 0xb655, 0x1856, 0x0657,
0x0658, 0xa259, 0xf25a, 0x785b, 0xf85c, 0x785d, 0x845e, 0x3a5f,
0x0c60, 0xfc61, 0xf062, 0x9c63, 0x5e64, 0xc265, 0x6666, 0x7667,
0x9a68, 0x4669, 0x746a, 0xb46b, 0x506c, 0xe06d, 0x3a6e, 0x866f,
0x6070, 0x3471, 0x3c72, 0xd673, 0x3474, 0x4c75, 0xa476, 0x7277,
0xa478, 0xd479, 0xea7a, 0xa47b, 0x487c, 0x147d, 0x8a7e, 0xf87f,
0x6c00, 0x6601, 0x7802, 0x7603, 0x2404, 0x4e05, 0xb006, 0xce07,
0x5c08, 0x1e09, 0x6a0a, 0xac0b, 0x1c0c, 0x3e0d, 0xea0e, 0x5c0f,
0x4e10, 0xc011, 0x6a12, 0xc213, 0x0214, 0xac15, 0xae16, 0x3617,
0x6e18, 0xa019, 0x681a, 0x001b, 0x0a1c, 0xe41d, 0xc41e, 0x9c1f,
0x2a20, 0x5021, 0xb622, 0xd823, 0x2024, 0x3225, 0x3826, 0x2e27,
0x9a28, 0xac29, 0x042a, 0xa62b, 0x882c, 0xd62d, 0xd22e, 0x082f,
0x4830, 0x9631, 0xf432, 0x1c33, 0x4634, 0xb035, 0x7636, 0xa637,
0xea38, 0x7039, 0x543a, 0x783b, 0xdc3c, 0x6e3d, 0xae3e, 0xba3f,
0x6a40, 0x6a41, 0x1c42, 0x9043, 0x3a44, 0x5e45, 0x8c46, 0x7447,
0x7c48, 0x5449, 0x384a, 0x1c4b, 0xa44c, 0xe84d, 0x604e, 0x304f,
0x4050, 0xc451, 0x8652, 0xac53, 0x1654, 0xb655, 0x1856, 0x0657,
0x0658, 0xa259, 0xf25a, 0x785b, 0xf85c, 0x785d, 0x845e, 0x3a5f,
0x0c60, 0xfc61, 0xf062, 0x9c63, 0x5e64, 0xc265, 0x6666, 0x7667,
0x9a68, 0x4669, 0x746a, 0xb46b, 0x506c, 0xe06d, 0x3a6e, 0x866f,
0x6070, 0x3471, 0x3c72, 0xd673, 0x3474, 0x4c75, 0xa476, 0x7277,
0xa478, 0xd479, 0xea7a, 0xa47b, 0x487c, 0x147d, 0x8a7e, 0xf87f
};
static const uint16_t sso_kasumi_S9e[] = {
0x4ea7, 0xdeef, 0x42a1, 0xf77b, 0x0f87, 0x9d4e, 0x1209, 0xa552,
0x4c26, 0xc4e2, 0x6030, 0xcd66, 0x89c4, 0x0381, 0xb45a, 0x1b8d,
0x6eb7, 0xfafd, 0x2693, 0x974b, 0x3f9f, 0xa954, 0x6633, 0xd56a,
0x6532, 0xe9f4, 0x0d06, 0xa452, 0xb0d8, 0x3e9f, 0xc964, 0x62b1,
0x5eaf, 0xe2f1, 0xd3e9, 0x4a25, 0x9cce, 0x2211, 0x0000, 0x9b4d,
0x582c, 0xfcfe, 0xf57a, 0x743a, 0x1e8f, 0xb8dc, 0xa251, 0x2190,
0xbe5f, 0x0603, 0x773b, 0xeaf5, 0x6c36, 0xd6eb, 0xb4da, 0x2b95,
0xb1d8, 0x1108, 0x58ac, 0xddee, 0xe773, 0x4522, 0x1f8f, 0x984c,
0x4aa5, 0x8ac5, 0x178b, 0xf279, 0x0301, 0xc1e0, 0x4fa7, 0xa8d4,
0xe0f0, 0x381c, 0x9dce, 0x60b0, 0x2d96, 0xf7fb, 0x4120, 0xbedf,
0xebf5, 0x2f97, 0xf2f9, 0x1309, 0xb259, 0x74ba, 0xbadd, 0x59ac,
0x48a4, 0x944a, 0x71b8, 0x88c4, 0x95ca, 0x4ba5, 0xbd5e, 0x46a3,
0xd0e8, 0x3c9e, 0x0c86, 0xc562, 0x1a0d, 0xf4fa, 0xd7eb, 0x1c8e,
0x7ebf, 0x8a45, 0x82c1, 0x53a9, 0x3098, 0xc6e3, 0xdd6e, 0x0e87,
0xb158, 0x592c, 0x2914, 0xe4f2, 0x6bb5, 0x8140, 0xe271, 0x2d16,
0x160b, 0xe6f3, 0xae57, 0x7b3d, 0x4824, 0xba5d, 0xe1f0, 0x361b,
0xcfe7, 0x7dbe, 0xc5e2, 0x5229, 0x8844, 0x389c, 0x93c9, 0x0683,
0x8d46, 0x2793, 0xa753, 0x2814, 0x4e27, 0xe673, 0x75ba, 0xf87c,
0xb7db, 0x0180, 0xf9fc, 0x6a35, 0xe070, 0x54aa, 0xbfdf, 0x2e97,
0xfc7e, 0x52a9, 0x9249, 0x190c, 0x2f17, 0x8341, 0x50a8, 0xd96c,
0xd76b, 0x4924, 0x5c2e, 0xe7f3, 0x1389, 0x8f47, 0x8944, 0x3018,
0x91c8, 0x170b, 0x3a9d, 0x99cc, 0xd1e8, 0x55aa, 0x6b35, 0xcae5,
0x6fb7, 0xf5fa, 0xa0d0, 0x1f0f, 0xbb5d, 0x2391, 0x65b2, 0xd8ec,
0x2010, 0xa2d1, 0xcf67, 0x6834, 0x7038, 0xf078, 0x8ec7, 0x2b15,
0xa3d1, 0x41a0, 0xf8fc, 0x3f1f, 0xecf6, 0x0c06, 0xa653, 0x6331,
0x49a4, 0xb359, 0x3299, 0xedf6, 0x8241, 0x7a3d, 0xe8f4, 0x351a,
0x5aad, 0xbcde, 0x45a2, 0x8643, 0x0582, 0xe170, 0x0b05, 0xca65,
0xb9dc, 0x4723, 0x86c3, 0x5dae, 0x6231, 0x9e4f, 0x4ca6, 0x954a,
0x3118, 0xff7f, 0xeb75, 0x0080, 0xfd7e, 0x3198, 0x369b, 0xdfef,
0xdf6f, 0x0984, 0x2512, 0xd66b, 0x97cb, 0x43a1, 0x7c3e, 0x8dc6,
0x0884, 0xc2e1, 0x96cb, 0x793c, 0xd4ea, 0x1c0e, 0x5b2d, 0xb65b,
0xeff7, 0x3d1e, 0x51a8, 0xa6d3, 0xb75b, 0x6733, 0x188c, 0xed76,
0x4623, 0xce67, 0xfa7d, 0x57ab, 0x2613, 0xacd6, 0x8bc5, 0x2492,
0xe5f2, 0x753a, 0x79bc, 0xcce6, 0x0100, 0x9349, 0x8cc6, 0x3b1d,
0x6432, 0xe874, 0x9c4e, 0x359a, 0x140a, 0x9acd, 0xfdfe, 0x56ab,
0xcee7, 0x5a2d, 0x168b, 0xa7d3, 0x3a1d, 0xac56, 0xf3f9, 0x4020,
0x9048, 0x341a, 0xad56, 0x2c96, 0x7339, 0xd5ea, 0x5faf, 0xdcee,
0x379b, 0x8b45, 0x2a95, 0xb3d9, 0x5028, 0xee77, 0x5cae, 0xc763,
0x72b9, 0xd2e9, 0x0b85, 0x8e47, 0x81c0, 0x2311, 0xe974, 0x6e37,
0xdc6e, 0x64b2, 0x8542, 0x180c, 0xabd5, 0x1188, 0xe371, 0x7cbe,
0x0201, 0xda6d, 0xef77, 0x1289, 0x6ab5, 0xb058, 0x964b, 0x6934,
0x0904, 0xc9e4, 0xc462, 0x2110, 0xe572, 0x2713, 0x399c, 0xde6f,
0xa150, 0x7d3e, 0x0804, 0xf1f8, 0xd9ec, 0x0703, 0x6130, 0x9a4d,
0xa351, 0x67b3, 0x2a15, 0xcb65, 0x5f2f, 0x994c, 0xc7e3, 0x2412,
0x5e2f, 0xaa55, 0x3219, 0xe3f1, 0xb5da, 0x4321, 0xc864, 0x1b0d,
0x5128, 0xbdde, 0x1d0e, 0xd46a, 0x3e1f, 0xd068, 0x63b1, 0xa854,
0x3d9e, 0xcde6, 0x158a, 0xc060, 0xc663, 0x349a, 0xffff, 0x2894,
0x3b9d, 0xd369, 0x3399, 0xfeff, 0x44a2, 0xaed7, 0x5d2e, 0x92c9,
0x150a, 0xbf5f, 0xaf57, 0x2090, 0x73b9, 0xdb6d, 0xd86c, 0x552a,
0xf6fb, 0x4422, 0x6cb6, 0xfbfd, 0x148a, 0xa4d2, 0x9f4f, 0x0a85,
0x6f37, 0xc160, 0x9148, 0x1a8d, 0x198c, 0xb55a, 0xf67b, 0x7f3f,
0x85c2, 0x3319, 0x5bad, 0xc8e4, 0x77bb, 0xc3e1, 0xb85c, 0x2994,
0xcbe5, 0x4da6, 0xf0f8, 0x5329, 0x2e17, 0xaad5, 0x0482, 0xa5d2,
0x2c16, 0xb2d9, 0x371b, 0x8c46, 0x4d26, 0xd168, 0x47a3, 0xfe7f,
0x7138, 0xf379, 0x0e07, 0xa9d4, 0x84c2, 0x0402, 0xea75, 0x4f27,
0x9fcf, 0x0502, 0xc0e0, 0x7fbf, 0xeef7, 0x76bb, 0xa050, 0x1d8e,
0x391c, 0xc361, 0xd269, 0x0d86, 0x572b, 0xafd7, 0xadd6, 0x70b8,
0x7239, 0x90c8, 0xb95c, 0x7e3f, 0x98cc, 0x78bc, 0x4221, 0x87c3,
0xc261, 0x3c1e, 0x6d36, 0xb6db, 0xbc5e, 0x40a0, 0x0281, 0xdbed,
0x8040, 0x66b3, 0x0f07, 0xcc66, 0x7abd, 0x9ecf, 0xe472, 0x2592,
0x6db6, 0xbbdd, 0x0783, 0xf47a, 0x80c0, 0x542a, 0xfb7d, 0x0a05,
0x2291, 0xec76, 0x68b4, 0x83c1, 0x4b25, 0x8743, 0x1088, 0xf97c,
0x562b, 0x8442, 0x783c, 0x8fc7, 0xab55, 0x7bbd, 0x94ca, 0x61b0,
0x1008, 0xdaed, 0x1e0f, 0xf178, 0x69b4, 0xa1d0, 0x763b, 0x9bcd
};
/* KASUMI cipher definitions */
#define NUM_KASUMI_ROUNDS (8) /* 8 rounds in the kasumi spec */
#define QWORDSIZEINBITS (64)
#define QWORDSIZEINBYTES (8)
#define LAST_PADDING_BIT (1)
/*--------- 16 bit rotate left ------------------------------------------*/
#define ROL16(a,b) (uint16_t)((a<<b)|(a>>(16-b)))
/*----- a 64-bit structure to help with kasumi endian issues -----*/
typedef union _ku64 {
uint64_t b64[1];
uint32_t b32[2];
uint16_t b16[4];
uint8_t b8[8];
} kasumi_union_t;
typedef union SafeBuffer {
uint64_t b64;
uint32_t b32[2];
uint8_t b8[IMB_KASUMI_BLOCK_SIZE];
} SafeBuf;
/*---------------------------------------------------------------------
* Inline 16-bit left rotation
*---------------------------------------------------------------------*/
#define ROL16(a,b) (uint16_t)((a<<b)|(a>>(16-b)))
#define FIp1(data, key1, key2, key3) \
do { \
uint16_t datal, datah; \
\
(data) ^= (key1); \
datal = LOOKUP16_SSE(sso_kasumi_S7e, (uint8_t)(data), 256); \
datah = LOOKUP16_SSE(sso_kasumi_S9e, (data) >> 7, 512); \
(data) = datal ^ datah; \
(data) ^= (key2); \
datal = LOOKUP16_SSE(sso_kasumi_S7e, (data) >> 9, 256); \
datah = LOOKUP16_SSE(sso_kasumi_S9e, (data) & 0x1FF, 512); \
(data) = datal ^ datah; \
(data) ^= (key3); \
} while (0)
#define FIp2(data1, data2, key1, key2, key3, key4) \
do { \
FIp1(data1, key1, key2, key3); \
FIp1(data2, key1, key2, key4); \
} while (0)
#define FLpi(key1, key2, res_h, res_l) \
do { \
uint16_t l, r; \
r = (res_l) & (key1); \
r = (res_h) ^ ROL16(r, 1); \
l = r | (key2); \
(res_h) = (res_l) ^ ROL16(l, 1); \
(res_l) = r; \
} while (0)
#define FLp1(index, h, l) \
do { \
uint16_t ka = *(index + 0); \
uint16_t kb = *(index + 1); \
FLpi(ka, kb, h, l); \
} while (0)
#define FLp2(index, h1, l1, h2, l2) \
do { \
uint16_t ka = *(index + 0); \
uint16_t kb = *(index + 1); \
FLpi(ka, kb, h1, l1); \
FLpi(ka, kb, h2, l2); \
} while (0)
#define FLp3(index, h1, l1, h2, l2, h3, l3) \
do { \
uint16_t ka = *(index + 0); \
uint16_t kb = *(index + 1); \
FLpi(ka, kb, h1, l1); \
FLpi(ka, kb, h2, l2); \
FLpi(ka, kb, h3, l3); \
} while (0)
#define FLp4(index, h1, l1, h2, l2, h3, l3, h4, l4) \
do { \
FLp2(index, h1, l1, h2, l2); \
FLp2(index, h3, l3, h4, l4); \
} while (0)
#define FOp1(index, h, l) \
do { \
FIp1(h, *(index + 2), *(index + 3), l); \
FIp1(l, *(index + 4), *(index + 5), h); \
FIp1(h, *(index + 6), *(index + 7), l); \
} while (0)
#define FOp2(index, h1, l1, h2, l2) \
do { \
uint16_t ka = *(index + 2); \
uint16_t kb = *(index + 3); \
FIp2(h1, h2, ka, kb, l1, l2); \
ka = *(index + 4); \
kb = *(index + 5); \
FIp2(l1, l2, ka, kb, h1, h2); \
ka = *(index + 6); \
kb = *(index + 7); \
FIp2(h1, h2, ka, kb, l1, l2); \
} while (0)
#define FOp3(index, h1, l1, h2, l2, h3, l3) \
do { \
uint16_t ka = *(index + 2); \
uint16_t kb = *(index + 3); \
FIp2(h1, h2, ka, kb, l1, l2); \
FIp1(h3, ka, kb, l3); \
ka = *(index + 4); \
kb = *(index + 5); \
FIp2(l1, l2, ka, kb, h1, h2); \
FIp1(l3, ka, kb, h3); \
ka = *(index + 6); \
kb = *(index + 7); \
FIp2(h1, h2, ka, kb, l1, l2); \
FIp1(h3, ka, kb, l3); \
} while (0)
#define FOp4(index, h1, l1, h2, l2, h3, l3, h4, l4) \
do { \
uint16_t ka = *(index + 2); \
uint16_t kb = *(index + 3); \
FIp2(h1, h2, ka, kb, l1, l2); \
FIp2(h3, h4, ka, kb, l3, l4); \
ka = *(index + 4); \
kb = *(index + 5); \
FIp2(l1, l2, ka, kb, h1, h2); \
FIp2(l3, l4, ka, kb, h3, h4); \
ka = *(index + 6); \
kb = *(index + 7); \
FIp2(h1, h2, ka, kb, l1, l2); \
FIp2(h3, h4, ka, kb, l3, l4); \
} while (0)
/**
*******************************************************************************
* @description
* This function performs the Kasumi operation on the given block using the key
* that is already scheduled in the context
*
* @param[in] pContext Context where the scheduled keys are stored
* @param[in/out] pData Block to be enc/dec
*
******************************************************************************/
static void kasumi_1_block(const uint16_t *context, uint16_t *data)
{
const uint16_t *end = context + KASUMI_KEY_SCHEDULE_SIZE;
/* 4 iterations odd/even */
do {
uint16_t temp_l = data[3], temp_h = data[2];
FLp1(context, temp_h, temp_l);
FOp1(context, temp_h, temp_l);
context += 8;
data[1] ^= temp_l;
data[0] ^= temp_h;
temp_h = data[1];
temp_l = data[0];
FOp1(context, temp_h, temp_l);
FLp1(context, temp_h, temp_l);
context += 8;
data[3] ^= temp_h;
data[2] ^= temp_l;
} while (context < end);
}
/**
******************************************************************************
* @description
* This function performs the Kasumi operation on the given blocks using the key
* that is already scheduled in the context
*
* @param[in] pContext Context where the scheduled keys are stored
* @param[in/out] pData1 First block to be enc/dec
* @param[in/out] pData2 Second block to be enc/dec
*
******************************************************************************/
static void
kasumi_2_blocks(const uint16_t *context, uint16_t *data1, uint16_t *data2)
{
const uint16_t *end = context + KASUMI_KEY_SCHEDULE_SIZE;
/* 4 iterations odd/even , with fine grain interleave */
do {
/* even */
uint16_t temp1_l = data1[3], temp1_h = data1[2];
uint16_t temp2_l = data2[3], temp2_h = data2[2];
FLp2(context, temp1_h, temp1_l, temp2_h, temp2_l);
FOp2(context, temp1_h, temp1_l, temp2_h, temp2_l);
context += 8;
data1[1] ^= temp1_l;
data1[0] ^= temp1_h;
data2[1] ^= temp2_l;
data2[0] ^= temp2_h;
/* odd */
temp1_h = data1[1];
temp1_l = data1[0];
temp2_h = data2[1];
temp2_l = data2[0];
FOp2(context, temp1_h, temp1_l, temp2_h, temp2_l);
FLp2(context, temp1_h, temp1_l, temp2_h, temp2_l);
context += 8;
data1[3] ^= temp1_h;
data1[2] ^= temp1_l;
data2[3] ^= temp2_h;
data2[2] ^= temp2_l;
} while (context < end);
}
/**
*******************************************************************************
* @description
* This function performs the Kasumi operation on the given blocks using the key
* that is already scheduled in the context
*
* @param[in] pContext Context where the scheduled keys are stored
* @param[in/out] pData1 First block to be enc/dec
* @param[in/out] pData2 Second block to be enc/dec
* @param[in/out] pData3 Third block to be enc/dec
*
******************************************************************************/
static void
kasumi_3_blocks(const uint16_t *context, uint16_t *data1,
uint16_t *data2, uint16_t *data3)
{
/* Case when the conmpiler is able to interleave efficiently */
const uint16_t *end = context + KASUMI_KEY_SCHEDULE_SIZE;
/* 4 iterations odd/even , with fine grain interleave */
do {
uint16_t temp1_l = data1[3], temp1_h = data1[2];
uint16_t temp2_l = data2[3], temp2_h = data2[2];
uint16_t temp3_l = data3[3], temp3_h = data3[2];
FLp3(context, temp1_h, temp1_l, temp2_h, temp2_l, temp3_h,
temp3_l);
FOp3(context, temp1_h, temp1_l, temp2_h, temp2_l, temp3_h,
temp3_l);
context += 8;
data1[1] ^= temp1_l;
data1[0] ^= temp1_h;
data2[1] ^= temp2_l;
data2[0] ^= temp2_h;
data3[1] ^= temp3_l;
data3[0] ^= temp3_h;
temp1_h = data1[1];
temp1_l = data1[0];
temp2_h = data2[1];
temp2_l = data2[0];
temp3_h = data3[1];
temp3_l = data3[0];
FOp3(context, temp1_h, temp1_l, temp2_h, temp2_l, temp3_h,
temp3_l);
FLp3(context, temp1_h, temp1_l, temp2_h, temp2_l, temp3_h,
temp3_l);
context += 8;
data1[3] ^= temp1_h;
data1[2] ^= temp1_l;
data2[3] ^= temp2_h;
data2[2] ^= temp2_l;
data3[3] ^= temp3_h;
data3[2] ^= temp3_l;
} while (context < end);
}
/**
*******************************************************************************
* @description
* This function performs the Kasumi operation on the given blocks using the key
* that is already scheduled in the context
*
* @param[in] pContext Context where the scheduled keys are stored
* @param[in] ppData Pointer to an array of addresses of blocks
*
******************************************************************************/
static void
kasumi_4_blocks(const uint16_t *context, uint16_t **ppData)
{
/* Case when the conmpiler is unable to interleave efficiently */
kasumi_2_blocks (context, ppData[0], ppData[1]);
kasumi_2_blocks (context, ppData[2], ppData[3]);
}
/**
******************************************************************************
* @description
* This function performs the Kasumi operation on the given blocks using the key
* that is already scheduled in the context
*
* @param[in] pContext Context where the scheduled keys are stored
* @param[in] ppData Pointer to an array of addresses of blocks
*
******************************************************************************/
static void
kasumi_8_blocks(const uint16_t *context, uint16_t **ppData)
{
kasumi_4_blocks (context, &ppData[0]);
kasumi_4_blocks (context, &ppData[4]);
}
/******************************************************************************
* @description
* Multiple wrappers for the Kasumi rounds on up to 16 blocks of 64 bits at a
*time.
*
* Depending on the variable packet lengths, different wrappers get called.
* It has been measured that 1 packet is faster than 2, 2 packets is faster
*than 3
* 3 packets is faster than 4, and so on ...
* It has also been measured that 6 = 4+2 packets is faster than 8
* It has also been measured that 7 packets are processed faster as 8 packets,
*
* If the assumptions are not verified, it is easy to implmement
* the right function and reference it in wrapperArray.
*
*******************************************************************************/
static void
kasumi_f8_1_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_1_block(context, data[0]);
}
static void
kasumi_f8_2_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_2_blocks(context, data[0], data[1]);
}
static void
kasumi_f8_3_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_3_blocks(context, data[0], data[1], data[2]);
}
static void
kasumi_f8_5_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_4_blocks(context, &data[0]);
kasumi_1_block(context, data[4]);
}
static void
kasumi_f8_6_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
/* It is also assumed 6 = 4+2 packets is faster than 8 */
kasumi_4_blocks(context, &data[0]);
kasumi_2_blocks(context, data[4], data[5]);
}
static void
kasumi_f8_7_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_4_blocks(context, &data[0]);
kasumi_3_blocks(context, data[4], data[5], data[6]);
}
static void
kasumi_f8_9_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_1_block(context, data[8]);
}
static void
kasumi_f8_10_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_2_blocks(context, data[8], data[9]);
}
static void
kasumi_f8_11_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_3_blocks(context, data[8], data[9], data[10]);
}
static void
kasumi_f8_12_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_4_blocks(context, &data[8]);
}
static void
kasumi_f8_13_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_4_blocks(context, &data[8]);
kasumi_1_block(context, data[12]);
}
static void
kasumi_f8_14_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_4_blocks(context, &data[8]);
kasumi_2_blocks(context, data[12], data[13]);
}
static void
kasumi_f8_15_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_4_blocks(context, &data[8]);
kasumi_3_blocks(context, data[12], data[13], data[14]);
}
static void
kasumi_f8_16_buffer_wrapper(const uint16_t *context, uint16_t **data)
{
kasumi_8_blocks(context, &data[0]);
kasumi_8_blocks(context, &data[8]);
}
typedef void (*kasumi_wrapper_t)(const uint16_t *, uint16_t **);
static kasumi_wrapper_t kasumiWrapperArray[] = {
NULL,
kasumi_f8_1_buffer_wrapper,
kasumi_f8_2_buffer_wrapper,
kasumi_f8_3_buffer_wrapper,
kasumi_4_blocks,
kasumi_f8_5_buffer_wrapper,
kasumi_f8_6_buffer_wrapper,
kasumi_f8_7_buffer_wrapper,
kasumi_8_blocks,
kasumi_f8_9_buffer_wrapper,
kasumi_f8_10_buffer_wrapper,
kasumi_f8_11_buffer_wrapper,
kasumi_f8_12_buffer_wrapper,
kasumi_f8_13_buffer_wrapper,
kasumi_f8_14_buffer_wrapper,
kasumi_f8_15_buffer_wrapper,
kasumi_f8_16_buffer_wrapper};
/*---------------------------------------------------------------------
* kasumi_key_schedule_sk()
* Build the key schedule. Most "key" operations use 16-bit
*
* Context is a flat array of 64 uint16. The context is built in the same order
* it will be used.
*---------------------------------------------------------------------*/
static inline void
kasumi_key_schedule_sk(uint16_t *context, const void *pKey)
{
/* Kasumi constants*/
static const uint16_t C[] = {0x0123, 0x4567, 0x89AB, 0xCDEF,
0xFEDC, 0xBA98, 0x7654, 0x3210};
uint16_t k[8], kprime[8], n;
const uint8_t *pk = (const uint8_t *) pKey;
/* Build K[] and K'[] keys */
for (n = 0; n < 8; n++, pk += 2) {
k[n] = (pk[0] << 8) + pk[1];
kprime[n] = k[n] ^ C[n];
}
/*
* Finally construct the various sub keys [Kli1, KlO ...) in the right
* order for easy usage at run-time
*/
for (n = 0; n < 8; n++) {
context[0] = ROL16(k[n], 1);
context[1] = kprime[(n + 2) & 0x7];
context[2] = ROL16(k[(n + 1) & 0x7], 5);
context[3] = kprime[(n + 4) & 0x7];
context[4] = ROL16(k[(n + 5) & 0x7], 8);
context[5] = kprime[(n + 3) & 0x7];
context[6] = ROL16(k[(n + 6) & 0x7], 13);
context[7] = kprime[(n + 7) & 0x7];
context += 8;
}
#ifdef SAFE_DATA
clear_mem(k, sizeof(k));
clear_mem(kprime, sizeof(kprime));
#endif
}
/*---------------------------------------------------------------------
* kasumi_compute_sched()
* Generic ksaumi key sched init function.
*
*---------------------------------------------------------------------*/
static inline int
kasumi_compute_sched(const uint8_t modifier,
const void *const pKey, void *pCtx)
{
#ifdef SAFE_PARAM
/* Check for NULL pointers */
imb_set_errno(NULL, 0);
if (pKey == NULL) {
imb_set_errno(NULL, IMB_ERR_NULL_KEY);
return -1;
}
if (pCtx == NULL) {
imb_set_errno(NULL, IMB_ERR_NULL_EXP_KEY);
return -1;
}
#endif
uint32_t i = 0;
const uint8_t *const key = (const uint8_t * const)pKey;
uint8_t ModKey[IMB_KASUMI_KEY_SIZE] = {0}; /* Modified key */
kasumi_key_sched_t *pLocalCtx = (kasumi_key_sched_t *)pCtx;
/* Construct the modified key*/
for (i = 0; i < IMB_KASUMI_KEY_SIZE; i++)
ModKey[i] = (uint8_t)key[i] ^ modifier;
kasumi_key_schedule_sk(pLocalCtx->sk16, pKey);
kasumi_key_schedule_sk(pLocalCtx->msk16, ModKey);
#ifdef SAFE_DATA
clear_mem(ModKey, sizeof(ModKey));
CLEAR_SCRATCH_GPS();
CLEAR_SCRATCH_SIMD_REGS();
#endif
return 0;
}
/*---------------------------------------------------------------------
* kasumi_key_sched_size()
* Get the size of a kasumi key sched context.
*
*---------------------------------------------------------------------*/
static inline size_t
kasumi_key_sched_size(void)
{
/*
* There are two keys that need to be scheduled: the original one and
* the modified one (xored with the relevant modifier)
*/
return sizeof(kasumi_key_sched_t);
}
/*---------------------------------------------------------------------
* kasumi_init_f8_key_sched()
* Compute the kasumi f8 key schedule.
*
*---------------------------------------------------------------------*/
static inline int
kasumi_init_f8_key_sched(const void *const pKey,
kasumi_key_sched_t *pCtx)
{
return kasumi_compute_sched(0x55, pKey, pCtx);
}
/*---------------------------------------------------------------------
* kasumi_init_f9_key_sched()
* Compute the kasumi f9 key schedule.
*
*---------------------------------------------------------------------*/
static inline int
kasumi_init_f9_key_sched(const void *const pKey,
kasumi_key_sched_t *pCtx)
{
return kasumi_compute_sched(0xAA, pKey, pCtx);
}
static inline void
kasumi_f8_1_buffer(const kasumi_key_sched_t *pCtx, const uint64_t IV,
const void *pIn, void *pOut,
const uint32_t length)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
uint32_t blkcnt;
kasumi_union_t a, b; /* the modifier */
const uint8_t *pBufferIn = (const uint8_t *) pIn;
uint8_t *pBufferOut = (uint8_t *) pOut;
uint32_t lengthInBytes = length;
/* IV Endianness */
a.b64[0] = BSWAP64(IV);
/* First encryption to create modifier */
kasumi_1_block(pCtx->msk16, a.b16 );
/* Final initialisation steps */
blkcnt = 0;
b.b64[0] = a.b64[0];
/* Now run the block cipher */
while (lengthInBytes) {
/* KASUMI it to produce the next block of keystream */
kasumi_1_block(pCtx->sk16, b.b16 );
if (lengthInBytes > IMB_KASUMI_BLOCK_SIZE) {
pBufferIn = xor_keystrm_rev(pBufferOut, pBufferIn,
b.b64[0]);
pBufferOut += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
/* done another 64 bits */
lengthInBytes -= IMB_KASUMI_BLOCK_SIZE;
/* apply the modifier and update the block count */
b.b64[0] ^= a.b64[0];
b.b16[0] ^= (uint16_t)++blkcnt;
} else if (lengthInBytes < IMB_KASUMI_BLOCK_SIZE) {
SafeBuf safeInBuf = {0};
/* end of the loop, handle the last bytes */
memcpy_keystrm(safeInBuf.b8, pBufferIn,
lengthInBytes);
xor_keystrm_rev(b.b8, safeInBuf.b8, b.b64[0]);
memcpy_keystrm(pBufferOut, b.b8, lengthInBytes);
lengthInBytes = 0;
#ifdef SAFE_DATA
clear_mem(&safeInBuf, sizeof(safeInBuf));
#endif
} else {
/* lengthInBytes == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut, pBufferIn, b.b64[0]);
lengthInBytes = 0;
}
}
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a, sizeof(a));
clear_mem(&b, sizeof(b));
#endif
}
static inline void
preserve_bits(kasumi_union_t *c,
const uint8_t *pcBufferOut, const uint8_t *pcBufferIn,
SafeBuf *safeOutBuf, SafeBuf *safeInBuf,
const uint8_t bit_len, const uint8_t byte_len)
{
const uint64_t mask = UINT64_MAX << (IMB_KASUMI_BLOCK_SIZE * 8 -
bit_len);
/* Clear the last bits of the keystream and the input
* (input only in out-of-place case) */
c->b64[0] &= mask;
if (pcBufferIn != pcBufferOut) {
const uint64_t swapMask = BSWAP64(mask);
safeInBuf->b64 &= swapMask;
/*
* Merge the last bits from the output, to be preserved,
* in the keystream, to be XOR'd with the input
* (which last bits are 0, maintaining the output bits)
*/
memcpy_keystrm(safeOutBuf->b8, pcBufferOut, byte_len);
c->b64[0] |= BSWAP64(safeOutBuf->b64 & ~swapMask);
}
}
static inline void
kasumi_f8_1_buffer_bit(const kasumi_key_sched_t *pCtx, const uint64_t IV,
const void *pIn, void *pOut,
const uint32_t lengthInBits,
const uint32_t offsetInBits)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
const uint8_t *pBufferIn = (const uint8_t *) pIn;
uint8_t *pBufferOut = (uint8_t *) pOut;
uint32_t cipherLengthInBits = lengthInBits;
uint32_t blkcnt;
uint64_t shiftrem = 0;
kasumi_union_t a, b, c; /* the modifier */
const uint8_t *pcBufferIn = pBufferIn + (offsetInBits / 8);
uint8_t *pcBufferOut = pBufferOut + (offsetInBits / 8);
/* Offset into the first byte (0 - 7 bits) */
uint32_t remainOffset = offsetInBits % 8;
SafeBuf safeOutBuf = {0};
SafeBuf safeInBuf = {0};
/* IV Endianness */
a.b64[0] = BSWAP64(IV);
/* First encryption to create modifier */
kasumi_1_block(pCtx->msk16, a.b16);
/* Final initialisation steps */
blkcnt = 0;
b.b64[0] = a.b64[0];
/* Now run the block cipher */
/* Start with potential partial block (due to offset and length) */
kasumi_1_block(pCtx->sk16, b.b16);
c.b64[0] = b.b64[0] >> remainOffset;
/* Only one block to encrypt */
if (cipherLengthInBits < (64 - remainOffset)) {
const uint32_t byteLength = (cipherLengthInBits + 7) / 8;
memcpy_keystrm(safeInBuf.b8, pcBufferIn, byteLength);
/*
* If operation is Out-of-place and there is offset
* to be applied, "remainOffset" bits from the output buffer
* need to be preserved (only applicable to first byte,
* since remainOffset is up to 7 bits)
*/
if ((pIn != pOut) && remainOffset) {
const uint8_t mask8 =
(const uint8_t)(1 << (8 - remainOffset)) - 1;
safeInBuf.b8[0] = (safeInBuf.b8[0] & mask8) |
(pcBufferOut[0] & ~mask8);
}
/* If last byte is a partial byte, the last bits of the output
* need to be preserved */
const uint8_t bitlen_with_off = remainOffset +
cipherLengthInBits;
if ((bitlen_with_off & 0x7) != 0) {
preserve_bits(&c, pcBufferOut, pcBufferIn, &safeOutBuf,
&safeInBuf, bitlen_with_off, byteLength);
}
xor_keystrm_rev(safeOutBuf.b8, safeInBuf.b8, c.b64[0]);
memcpy_keystrm(pcBufferOut, safeOutBuf.b8, byteLength);
return;
}
/*
* If operation is Out-of-place and there is offset
* to be applied, "remainOffset" bits from the output buffer
* need to be preserved (only applicable to first byte,
* since remainOffset is up to 7 bits)
*/
if ((pIn != pOut) && remainOffset) {
const uint8_t mask8 =
(const uint8_t)(1 << (8 - remainOffset)) - 1;
memcpy_keystrm(safeInBuf.b8, pcBufferIn, 8);
safeInBuf.b8[0] = (safeInBuf.b8[0] & mask8) |
(pcBufferOut[0] & ~mask8);
xor_keystrm_rev(pcBufferOut, safeInBuf.b8, c.b64[0]);
pcBufferIn += IMB_KASUMI_BLOCK_SIZE;
} else {
/* At least 64 bits to produce (including offset) */
pcBufferIn = xor_keystrm_rev(pcBufferOut, pcBufferIn, c.b64[0]);
}
if (remainOffset != 0)
shiftrem = b.b64[0] << (64 - remainOffset);
cipherLengthInBits -= IMB_KASUMI_BLOCK_SIZE * 8 - remainOffset;
pcBufferOut += IMB_KASUMI_BLOCK_SIZE;
/* apply the modifier and update the block count */
b.b64[0] ^= a.b64[0];
b.b16[0] ^= (uint16_t)++blkcnt;
while (cipherLengthInBits) {
/* KASUMI it to produce the next block of keystream */
kasumi_1_block(pCtx->sk16, b.b16);
c.b64[0] = (b.b64[0] >> remainOffset) | shiftrem;
if (remainOffset != 0)
shiftrem = b.b64[0] << (64 - remainOffset);
if (cipherLengthInBits >= IMB_KASUMI_BLOCK_SIZE * 8) {
pcBufferIn = xor_keystrm_rev(pcBufferOut,
pcBufferIn, c.b64[0]);
cipherLengthInBits -= IMB_KASUMI_BLOCK_SIZE * 8;
pcBufferOut += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
/* apply the modifier and update the block count */
b.b64[0] ^= a.b64[0];
b.b16[0] ^= (uint16_t)++blkcnt;
} else {
/* end of the loop, handle the last bytes */
const uint32_t byteLength =
(cipherLengthInBits + 7) / 8;
memcpy_keystrm(safeInBuf.b8, pcBufferIn,
byteLength);
/* If last byte is a partial byte, the last bits
* of the output need to be preserved */
if ((cipherLengthInBits & 0x7) != 0)
preserve_bits(&c, pcBufferOut, pcBufferIn,
&safeOutBuf, &safeInBuf,
cipherLengthInBits, byteLength);
xor_keystrm_rev(safeOutBuf.b8, safeInBuf.b8, c.b64[0]);
memcpy_keystrm(pcBufferOut, safeOutBuf.b8, byteLength);
cipherLengthInBits = 0;
}
}
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a, sizeof(a));
clear_mem(&b, sizeof(b));
clear_mem(&c, sizeof(c));
clear_mem(&safeInBuf, sizeof(safeInBuf));
clear_mem(&safeOutBuf, sizeof(safeOutBuf));
#endif
}
static inline void
kasumi_f8_2_buffer(const kasumi_key_sched_t *pCtx,
const uint64_t IV1, const uint64_t IV2,
const void *pIn1, void *pOut1,
const uint32_t length1,
const void *pIn2, void *pOut2,
const uint32_t length2)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
const uint8_t *pBufferIn1 = (const uint8_t *) pIn1;
uint8_t *pBufferOut1 = (uint8_t *) pOut1;
uint32_t lengthInBytes1 = length1;
const uint8_t *pBufferIn2 = (const uint8_t *) pIn2;
uint8_t *pBufferOut2 = (uint8_t *) pOut2;
uint32_t lengthInBytes2 = length2;
uint32_t blkcnt, length;
kasumi_union_t a1, b1; /* the modifier */
kasumi_union_t a2, b2; /* the modifier */
SafeBuf safeInBuf = {0};
kasumi_union_t temp;
/* IV Endianness */
a1.b64[0] = BSWAP64(IV1);
a2.b64[0] = BSWAP64(IV2);
kasumi_2_blocks(pCtx->msk16, a1.b16, a2.b16);
/* Final initialisation steps */
blkcnt = 0;
b1.b64[0] = a1.b64[0];
b2.b64[0] = a2.b64[0];
/* check which packet is longer and save "common" shortest length */
if (lengthInBytes1 > lengthInBytes2)
length = lengthInBytes2;
else
length = lengthInBytes1;
/* Round down to to a whole number of qwords. (QWORDLENGTHINBYTES-1 */
length &= ~7;
lengthInBytes1 -= length;
lengthInBytes2 -= length;
/* Now run the block cipher for common packet length, a whole number of
* blocks */
while (length) {
/* KASUMI it to produce the next block of keystream for both
* packets */
kasumi_2_blocks(pCtx->sk16, b1.b16, b2.b16);
/* xor and write keystream */
pBufferIn1 =
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
pBufferOut1 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn2 =
xor_keystrm_rev(pBufferOut2, pBufferIn2, b2.b64[0]);
pBufferOut2 += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
length -= IMB_KASUMI_BLOCK_SIZE; /* done another 64 bits */
/* apply the modifier and update the block count */
b1.b64[0] ^= a1.b64[0];
b1.b16[0] ^= (uint16_t)++blkcnt;
b2.b64[0] ^= a2.b64[0];
b2.b16[0] ^= (uint16_t)blkcnt;
}
/*
* Process common part at end of first packet and second packet.
* One of the packets has a length less than 8 bytes.
*/
if (lengthInBytes1 > 0 && lengthInBytes2 > 0) {
/* final round for 1 of the packets */
kasumi_2_blocks(pCtx->sk16, b1.b16, b2.b16);
if (lengthInBytes1 > IMB_KASUMI_BLOCK_SIZE) {
pBufferIn1 = xor_keystrm_rev(pBufferOut1,
pBufferIn1, b1.b64[0]);
pBufferOut1 += IMB_KASUMI_BLOCK_SIZE;
b1.b64[0] ^= a1.b64[0];
b1.b16[0] ^= (uint16_t)++blkcnt;
lengthInBytes1 -= IMB_KASUMI_BLOCK_SIZE;
} else if (lengthInBytes1 < IMB_KASUMI_BLOCK_SIZE) {
memcpy_keystrm(safeInBuf.b8, pBufferIn1,
lengthInBytes1);
xor_keystrm_rev(temp.b8, safeInBuf.b8, b1.b64[0]);
memcpy_keystrm(pBufferOut1, temp.b8,
lengthInBytes1);
lengthInBytes1 = 0;
} else {
/* lengthInBytes1 == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
lengthInBytes1 = 0;
}
if (lengthInBytes2 > IMB_KASUMI_BLOCK_SIZE) {
pBufferIn2 = xor_keystrm_rev(pBufferOut2,
pBufferIn2, b2.b64[0]);
pBufferOut2 += IMB_KASUMI_BLOCK_SIZE;
b2.b64[0] ^= a2.b64[0];
b2.b16[0] ^= (uint16_t)++blkcnt;
lengthInBytes2 -= IMB_KASUMI_BLOCK_SIZE;
} else if (lengthInBytes2 < IMB_KASUMI_BLOCK_SIZE) {
memcpy_keystrm(safeInBuf.b8, pBufferIn2,
lengthInBytes2);
xor_keystrm_rev(temp.b8, safeInBuf.b8, b2.b64[0]);
memcpy_keystrm(pBufferOut2, temp.b8,
lengthInBytes2);
lengthInBytes2 = 0;
} else {
/* lengthInBytes2 == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut2, pBufferIn2, b2.b64[0]);
lengthInBytes2 = 0;
}
}
if (lengthInBytes1 < lengthInBytes2) {
/* packet 2 is not completed since lengthInBytes2 > 0
* packet 1 has less than 8 bytes.
*/
if (lengthInBytes1) {
kasumi_1_block(pCtx->sk16, b1.b16);
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
}
/* move pointers to right variables for packet 1 */
lengthInBytes1 = lengthInBytes2;
b1.b64[0] = b2.b64[0];
a1.b64[0] = a2.b64[0];
pBufferIn1 = pBufferIn2;
pBufferOut1 = pBufferOut2;
} else { /* lengthInBytes1 >= lengthInBytes2 */
if (!lengthInBytes1)
/* both packets are completed */
return;
/* process the remaining of packet 2 */
if (lengthInBytes2) {
kasumi_1_block(pCtx->sk16, b2.b16);
xor_keystrm_rev(pBufferOut2, pBufferIn2, b2.b64[0]);
}
/* packet 1 is not completed */
}
/* process the length difference from ipkt1 and pkt2 */
while (lengthInBytes1) {
/* KASUMI it to produce the next block of keystream */
kasumi_1_block(pCtx->sk16, b1.b16);
if (lengthInBytes1 > IMB_KASUMI_BLOCK_SIZE) {
pBufferIn1 = xor_keystrm_rev(pBufferOut1,
pBufferIn1, b1.b64[0]);
pBufferOut1 += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
lengthInBytes1 -= IMB_KASUMI_BLOCK_SIZE;
/* apply the modifier and update the block count */
b1.b64[0] ^= a1.b64[0];
b1.b16[0] ^= (uint16_t)++blkcnt;
} else if (lengthInBytes1 < IMB_KASUMI_BLOCK_SIZE) {
/* end of the loop, handle the last bytes */
memcpy_keystrm(safeInBuf.b8, pBufferIn1,
lengthInBytes1);
xor_keystrm_rev(temp.b8, safeInBuf.b8, b1.b64[0]);
memcpy_keystrm(pBufferOut1, temp.b8,
lengthInBytes1);
lengthInBytes1 = 0;
} else {
/* lengthInBytes1 == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
lengthInBytes1 = 0;
}
}
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a1, sizeof(a1));
clear_mem(&b1, sizeof(b1));
clear_mem(&a2, sizeof(a2));
clear_mem(&b2, sizeof(b2));
clear_mem(&temp, sizeof(temp));
clear_mem(&safeInBuf, sizeof(safeInBuf));
#endif
}
static inline void
kasumi_f8_3_buffer(const kasumi_key_sched_t *pCtx,
const uint64_t IV1, const uint64_t IV2, const uint64_t IV3,
const void *pIn1, void *pOut1,
const void *pIn2, void *pOut2,
const void *pIn3, void *pOut3,
const uint32_t length)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
const uint8_t *pBufferIn1 = (const uint8_t *) pIn1;
uint8_t *pBufferOut1 = (uint8_t *) pOut1;
const uint8_t *pBufferIn2 = (const uint8_t *) pIn2;
uint8_t *pBufferOut2 = (uint8_t *) pOut2;
const uint8_t *pBufferIn3 = (const uint8_t *) pIn3;
uint8_t *pBufferOut3 = (uint8_t *) pOut3;
uint32_t lengthInBytes = length;
uint32_t blkcnt;
kasumi_union_t a1, b1; /* the modifier */
kasumi_union_t a2, b2; /* the modifier */
kasumi_union_t a3, b3; /* the modifier */
/* IV Endianness */
a1.b64[0] = BSWAP64(IV1);
a2.b64[0] = BSWAP64(IV2);
a3.b64[0] = BSWAP64(IV3);
kasumi_3_blocks(pCtx->msk16, a1.b16, a2.b16, a3.b16);
/* Final initialisation steps */
blkcnt = 0;
b1.b64[0] = a1.b64[0];
b2.b64[0] = a2.b64[0];
b3.b64[0] = a3.b64[0];
/* Now run the block cipher for common packet lengthInBytes, a whole
* number of blocks */
while (lengthInBytes) {
/* KASUMI it to produce the next block of keystream for all the
* packets */
kasumi_3_blocks(pCtx->sk16, b1.b16, b2.b16, b3.b16);
if (lengthInBytes > IMB_KASUMI_BLOCK_SIZE) {
/* xor and write keystream */
pBufferIn1 = xor_keystrm_rev(pBufferOut1,
pBufferIn1, b1.b64[0]);
pBufferOut1 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn2 = xor_keystrm_rev(pBufferOut2,
pBufferIn2, b2.b64[0]);
pBufferOut2 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn3 = xor_keystrm_rev(pBufferOut3,
pBufferIn3, b3.b64[0]);
pBufferOut3 += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
lengthInBytes -= IMB_KASUMI_BLOCK_SIZE;
/* apply the modifier and update the block count */
b1.b64[0] ^= a1.b64[0];
b1.b16[0] ^= (uint16_t)++blkcnt;
b2.b64[0] ^= a2.b64[0];
b2.b16[0] ^= (uint16_t)blkcnt;
b3.b64[0] ^= a3.b64[0];
b3.b16[0] ^= (uint16_t)blkcnt;
} else if (lengthInBytes < IMB_KASUMI_BLOCK_SIZE) {
SafeBuf safeInBuf = {0};
/* end of the loop, handle the last bytes */
memcpy_keystrm(safeInBuf.b8, pBufferIn1,
lengthInBytes);
xor_keystrm_rev(b1.b8, safeInBuf.b8, b1.b64[0]);
memcpy_keystrm(pBufferOut1, b1.b8, lengthInBytes);
memcpy_keystrm(safeInBuf.b8, pBufferIn2,
lengthInBytes);
xor_keystrm_rev(b2.b8, safeInBuf.b8, b2.b64[0]);
memcpy_keystrm(pBufferOut2, b2.b8, lengthInBytes);
memcpy_keystrm(safeInBuf.b8, pBufferIn3,
lengthInBytes);
xor_keystrm_rev(b3.b8, safeInBuf.b8, b3.b64[0]);
memcpy_keystrm(pBufferOut3, b3.b8, lengthInBytes);
lengthInBytes = 0;
#ifdef SAFE_DATA
clear_mem(&safeInBuf, sizeof(safeInBuf));
#endif
} else {
/* lengthInBytes == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
xor_keystrm_rev(pBufferOut2, pBufferIn2, b2.b64[0]);
xor_keystrm_rev(pBufferOut3, pBufferIn3, b3.b64[0]);
lengthInBytes = 0;
}
}
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a1, sizeof(a1));
clear_mem(&b1, sizeof(b1));
clear_mem(&a2, sizeof(a2));
clear_mem(&b2, sizeof(b2));
clear_mem(&a3, sizeof(a3));
clear_mem(&b3, sizeof(b3));
#endif
}
/*---------------------------------------------------------
* @description
* Kasumi F8 4 packet:
* Four packets enc/dec with the same key schedule.
* The 4 Ivs are independent and are passed as an array of values
* The packets are separate, the datalength is common
*---------------------------------------------------------*/
static inline void
kasumi_f8_4_buffer(const kasumi_key_sched_t *pCtx, const uint64_t IV1,
const uint64_t IV2, const uint64_t IV3, const uint64_t IV4,
const void *pIn1, void *pOut1,
const void *pIn2, void *pOut2,
const void *pIn3, void *pOut3,
const void *pIn4, void *pOut4,
const uint32_t length)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
const uint8_t *pBufferIn1 = (const uint8_t *) pIn1;
uint8_t *pBufferOut1 = (uint8_t *) pOut1;
const uint8_t *pBufferIn2 = (const uint8_t *) pIn2;
uint8_t *pBufferOut2 = (uint8_t *) pOut2;
const uint8_t *pBufferIn3 = (const uint8_t *) pIn3;
uint8_t *pBufferOut3 = (uint8_t *) pOut3;
const uint8_t *pBufferIn4 = (const uint8_t *) pIn4;
uint8_t *pBufferOut4 = (uint8_t *) pOut4;
uint32_t lengthInBytes = length;
uint32_t blkcnt;
kasumi_union_t a1, b1; /* the modifier */
kasumi_union_t a2, b2; /* the modifier */
kasumi_union_t a3, b3; /* the modifier */
kasumi_union_t a4, b4; /* the modifier */
uint16_t *pTemp[4] = {b1.b16, b2.b16, b3.b16, b4.b16};
/* IV Endianness */
b1.b64[0] = BSWAP64(IV1);
b2.b64[0] = BSWAP64(IV2);
b3.b64[0] = BSWAP64(IV3);
b4.b64[0] = BSWAP64(IV4);
kasumi_4_blocks(pCtx->msk16, pTemp);
/* Final initialisation steps */
blkcnt = 0;
a1.b64[0] = b1.b64[0];
a2.b64[0] = b2.b64[0];
a3.b64[0] = b3.b64[0];
a4.b64[0] = b4.b64[0];
/* Now run the block cipher for common packet lengthInBytes, a whole
* number of blocks */
while (lengthInBytes) {
/* KASUMI it to produce the next block of keystream for all the
* packets */
kasumi_4_blocks(pCtx->sk16, pTemp);
if (lengthInBytes > IMB_KASUMI_BLOCK_SIZE) {
/* xor and write keystream */
pBufferIn1 = xor_keystrm_rev(pBufferOut1,
pBufferIn1, b1.b64[0]);
pBufferOut1 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn2 = xor_keystrm_rev(pBufferOut2,
pBufferIn2, b2.b64[0]);
pBufferOut2 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn3 = xor_keystrm_rev(pBufferOut3,
pBufferIn3, b3.b64[0]);
pBufferOut3 += IMB_KASUMI_BLOCK_SIZE;
pBufferIn4 = xor_keystrm_rev(pBufferOut4,
pBufferIn4, b4.b64[0]);
pBufferOut4 += IMB_KASUMI_BLOCK_SIZE;
/* loop variant */
lengthInBytes -= IMB_KASUMI_BLOCK_SIZE;
/* apply the modifier and update the block count */
b1.b64[0] ^= a1.b64[0];
b1.b16[0] ^= (uint16_t)++blkcnt;
b2.b64[0] ^= a2.b64[0];
b2.b16[0] ^= (uint16_t)blkcnt;
b3.b64[0] ^= a3.b64[0];
b3.b16[0] ^= (uint16_t)blkcnt;
b4.b64[0] ^= a4.b64[0];
b4.b16[0] ^= (uint16_t)blkcnt;
} else if (lengthInBytes < IMB_KASUMI_BLOCK_SIZE) {
SafeBuf safeInBuf = {0};
/* end of the loop, handle the last bytes */
memcpy_keystrm(safeInBuf.b8, pBufferIn1,
lengthInBytes);
xor_keystrm_rev(b1.b8, safeInBuf.b8, b1.b64[0]);
memcpy_keystrm(pBufferOut1, b1.b8, lengthInBytes);
memcpy_keystrm(safeInBuf.b8, pBufferIn2,
lengthInBytes);
xor_keystrm_rev(b2.b8, safeInBuf.b8, b2.b64[0]);
memcpy_keystrm(pBufferOut2, b2.b8, lengthInBytes);
memcpy_keystrm(safeInBuf.b8, pBufferIn3,
lengthInBytes);
xor_keystrm_rev(b3.b8, safeInBuf.b8, b3.b64[0]);
memcpy_keystrm(pBufferOut3, b3.b8, lengthInBytes);
memcpy_keystrm(safeInBuf.b8, pBufferIn4,
lengthInBytes);
xor_keystrm_rev(b4.b8, safeInBuf.b8, b4.b64[0]);
memcpy_keystrm(pBufferOut4, b4.b8, lengthInBytes);
lengthInBytes = 0;
#ifdef SAFE_DATA
clear_mem(&safeInBuf, sizeof(safeInBuf));
#endif
} else {
/* lengthInBytes == IMB_KASUMI_BLOCK_SIZE */
xor_keystrm_rev(pBufferOut1, pBufferIn1, b1.b64[0]);
xor_keystrm_rev(pBufferOut2, pBufferIn2, b2.b64[0]);
xor_keystrm_rev(pBufferOut3, pBufferIn3, b3.b64[0]);
xor_keystrm_rev(pBufferOut4, pBufferIn4, b4.b64[0]);
lengthInBytes = 0;
}
}
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a1, sizeof(a1));
clear_mem(&b1, sizeof(b1));
clear_mem(&a2, sizeof(a2));
clear_mem(&b2, sizeof(b2));
clear_mem(&a3, sizeof(a3));
clear_mem(&b3, sizeof(b3));
clear_mem(&a4, sizeof(a4));
clear_mem(&b4, sizeof(b4));
#endif
}
/*---------------------------------------------------------
* @description
* Kasumi F8 2 packet:
* Two packets enc/dec with the same key schedule.
* The 2 Ivs are independent and are passed as an array of values.
* The packets are separate, the datalength is common
*---------------------------------------------------------*/
/******************************************************************************
* @description
* Kasumi F8 n packet:
* Performs F8 enc/dec on [n] packets. The operation is performed in-place.
* The input IV's are passed in Big Endian format.
* The KeySchedule is in Little Endian format.
*******************************************************************************/
static inline void
kasumi_f8_n_buffer(const kasumi_key_sched_t *pKeySchedule, const uint64_t IV[],
const void * const pIn[], void *pOut[],
const uint32_t lengths[], const uint32_t bufCount)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
if (bufCount > 16) {
pOut[0] = NULL;
printf("dataCount too high (%u)\n", (unsigned) bufCount);
return;
}
uint32_t dataCount = bufCount;
kasumi_union_t A[NUM_PACKETS_16], temp[NUM_PACKETS_16], tempSort;
uint16_t *data[NUM_PACKETS_16];
uint32_t dataLen[NUM_PACKETS_16];
uint8_t *pDataOut[NUM_PACKETS_16] = {NULL};
const uint8_t *pDataIn[NUM_PACKETS_16] = {NULL};
const uint8_t *srctempbuff;
uint8_t *dsttempbuff;
uint32_t blkcnt = 0;
uint32_t len = 0;
uint32_t packet_idx, inner_idx, same_size_blocks;
int sortNeeded = 0;
SafeBuf safeInBuf = {0};
memcpy((void *)dataLen, lengths, dataCount * sizeof(uint32_t));
memcpy((void *)pDataIn, pIn, dataCount * sizeof(void *));
memcpy((void *)pDataOut, pOut, dataCount * sizeof(void *));
/* save the IV to A for each packet */
packet_idx = dataCount;
while (packet_idx--) {
/*copy IV in reverse endian order as input IV is BE */
temp[packet_idx].b64[0] = BSWAP64(IV[packet_idx]);
/* set LE IV pointers */
data[packet_idx] = temp[packet_idx].b16;
/* check if all packets are sorted by decreasing length */
if (packet_idx > 0 &&
dataLen[packet_idx - 1] < dataLen[packet_idx])
/* this packet array is not correctly sorted */
sortNeeded = 1;
}
/* do 1st kasumi block on A with modified key, this overwrites A */
kasumiWrapperArray[dataCount](pKeySchedule->msk16, data);
if (sortNeeded) {
/* sort packets in decreasing buffer size from [0] to [n]th
packet,
** where buffer[0] will contain longest buffer and
buffer[n] will
contain the shortest buffer.
4 arrays are swapped :
- pointers to input buffers
- pointers to output buffers
- pointers to input IV's
- input buffer lengths
*/
packet_idx = dataCount;
while (packet_idx--) {
inner_idx = packet_idx;
while (inner_idx--) {
if (dataLen[packet_idx] > dataLen[inner_idx]) {
/* swap buffers to arrange in descending
* order from [0]. */
srctempbuff = pDataIn[packet_idx];
dsttempbuff = pDataOut[packet_idx];
tempSort = temp[packet_idx];
const int tempLen = dataLen[packet_idx];
pDataIn[packet_idx] =
pDataIn[inner_idx];
pDataOut[packet_idx] =
pDataOut[inner_idx];
temp[packet_idx] = temp[inner_idx];
dataLen[packet_idx] =
dataLen[inner_idx];
pDataIn[inner_idx] = srctempbuff;
pDataOut[inner_idx] = dsttempbuff;
temp[inner_idx] = tempSort;
dataLen[inner_idx] = tempLen;
}
} /* for inner packet idx (inner bubble-sort) */
} /* for outer packet idx (outer bubble-sort) */
} /* if sortNeeded */
packet_idx = dataCount;
while (packet_idx--)
/* copy the schedule */
A[packet_idx].b64[0] = temp[packet_idx].b64[0];
while (dataCount > 0) {
/* max num of blocks left depends on roundUp(smallest packet),
* The shortest stream to process is always stored at location
* [dataCount - 1]
*/
same_size_blocks =
((dataLen[dataCount - 1] + IMB_KASUMI_BLOCK_SIZE - 1) /
IMB_KASUMI_BLOCK_SIZE) -
blkcnt;
/* process streams of complete blocks */
while (same_size_blocks-- > 1) {
/* do kasumi block encryption */
kasumiWrapperArray[dataCount](pKeySchedule->sk16,
data);
packet_idx = dataCount;
while (packet_idx--)
xor_keystrm_rev(pDataOut[packet_idx] + len,
pDataIn[packet_idx] + len,
temp[packet_idx].b64[0]);
/* length already done since the start of the packets */
len += IMB_KASUMI_BLOCK_SIZE;
/* block idx is incremented and rewritten in the
* keystream */
blkcnt += 1;
packet_idx = dataCount;
while (packet_idx--) {
temp[packet_idx].b64[0] ^= A[packet_idx].b64[0];
temp[packet_idx].b16[0] ^= (uint16_t)blkcnt;
} /* for packet_idx */
} /* while same_size_blocks (iteration on multiple blocks) */
/* keystream for last block of all packets */
kasumiWrapperArray[dataCount](pKeySchedule->sk16, data);
/* process incomplete blocks without overwriting past the buffer
* end */
while ((dataCount > 0) &&
(dataLen[dataCount - 1] < (len+IMB_KASUMI_BLOCK_SIZE))) {
dataCount--;
/* incomplete block is copied into a temp buffer */
memcpy_keystrm(safeInBuf.b8, pDataIn[dataCount] + len,
dataLen[dataCount] - len);
xor_keystrm_rev(temp[dataCount].b8,
safeInBuf.b8,
temp[dataCount].b64[0]);
memcpy_keystrm(pDataOut[dataCount] + len,
temp[dataCount].b8,
dataLen[dataCount] - len);
} /* while dataCount */
/* process last blocks: it can be the last complete block of the
packets or, if
KASUMI_SAFE_BUFFER is defined, the last block (complete or not)
of the packets*/
while ((dataCount > 0) &&
(dataLen[dataCount-1] <= (len+IMB_KASUMI_BLOCK_SIZE))) {
dataCount--;
xor_keystrm_rev(pDataOut[dataCount] + len,
pDataIn[dataCount] + len,
temp[dataCount].b64[0]);
} /* while dataCount */
/* block idx is incremented and rewritten in the keystream */
blkcnt += 1;
/* for the following packets, this block is not the last one:
dataCount is not decremented */
packet_idx = dataCount;
while (packet_idx--) {
xor_keystrm_rev(pDataOut[packet_idx] + len,
pDataIn[packet_idx] + len,
temp[packet_idx].b64[0]);
temp[packet_idx].b64[0] ^= A[packet_idx].b64[0];
temp[packet_idx].b16[0] ^= (uint16_t)blkcnt;
} /* while packet_idx */
/* length already done since the start of the packets */
len += IMB_KASUMI_BLOCK_SIZE;
/* the remaining packets, if any, have now at least one valid
block, which might be complete or not */
} /* while (dataCount) */
#ifdef SAFE_DATA
uint32_t i;
/* Clear sensitive data in stack */
for (i = 0; i < bufCount; i++) {
clear_mem(&A[i], sizeof(A[i]));
clear_mem(&temp[i], sizeof(temp[i]));
}
clear_mem(&tempSort, sizeof(tempSort));
clear_mem(&safeInBuf, sizeof(safeInBuf));
#endif
}
static inline void
kasumi_f9_1_buffer(const kasumi_key_sched_t *pCtx, const void *dataIn,
const uint32_t length, void *pDigest)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
kasumi_union_t a, b, mask;
const uint64_t *pIn = (const uint64_t *)dataIn;
uint32_t lengthInBytes = length;
/* Init */
a.b64[0] = 0;
b.b64[0] = 0;
mask.b64[0] = -1;
/* Now run kasumi for all 8 byte blocks */
while (lengthInBytes >= 8) {
a.b64[0] ^= BSWAP64(*(pIn++));
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* loop variant */
lengthInBytes -= 8; /* done another 64 bits */
/* update */
b.b64[0] ^= a.b64[0];
}
if (lengthInBytes) {
SafeBuf safeBuf = {0};
/* Not a whole 8 byte block remaining */
mask.b64[0] = ~(mask.b64[0] >> (BYTESIZE * lengthInBytes));
safe_memcpy(&safeBuf.b64, pIn, lengthInBytes);
mask.b64[0] &= BSWAP64(safeBuf.b64);
a.b64[0] ^= mask.b64[0];
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] ^= a.b64[0];
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&safeBuf, sizeof(safeBuf));
#endif
}
/* Kasumi b */
kasumi_1_block(pCtx->msk16, b.b16);
/* swap result */
*(uint32_t *)pDigest = bswap4(b.b32[1]);
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a, sizeof(a));
clear_mem(&b, sizeof(b));
clear_mem(&mask, sizeof(mask));
#endif
}
/*---------------------------------------------------------
* @description
* Kasumi F9 1 packet with user config:
* Single packet digest with user defined IV, and precomputed key schedule.
*
* IV = swap32(count) << 32 | swap32(fresh)
*
*---------------------------------------------------------*/
static inline void
kasumi_f9_1_buffer_user(const kasumi_key_sched_t *pCtx, const uint64_t IV,
const void *pDataIn, const uint32_t length,
void *pDigest, const uint32_t direction)
{
#ifdef SAFE_DATA
CLEAR_SCRATCH_SIMD_REGS();
#endif /* SAFE_DATA */
kasumi_union_t a, b, mask, message, temp;
uint32_t lengthInBits = length;
const uint64_t *pIn = (const uint64_t *)pDataIn;
kasumi_union_t safebuff;
a.b64[0] = 0;
b.b64[0] = 0;
/* Use the count and fresh for first round */
a.b64[0] = BSWAP64(IV);
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] = a.b64[0];
/* Now run kasumi for all 8 byte blocks */
while (lengthInBits >= QWORDSIZEINBITS) {
a.b64[0] ^= BSWAP64(*(pIn++));
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* loop variant */
lengthInBits -= 64; /* done another 64 bits */
/* update */
b.b64[0] ^= a.b64[0];
}
/* Is there any non 8 byte blocks remaining ? */
if (lengthInBits == 0) {
/* last block is : direct + 1 + 62 0's */
a.b64[0] ^= ((uint64_t)direction + direction + LAST_PADDING_BIT)
<< (QWORDSIZEINBITS - 2);
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] ^= a.b64[0];
} else if (lengthInBits <= (QWORDSIZEINBITS - 2)) {
/* last block is : message + direction + LAST_PADDING_BITS(1) +
* less than 62 0's */
mask.b64[0] = -1;
temp.b64[0] = 0;
message.b64[0] = 0;
mask.b64[0] = ~(mask.b64[0] >> lengthInBits);
/*round up and copy last lengthInBits */
safe_memcpy(&safebuff.b64[0], pIn, (lengthInBits + 7) / 8);
message.b64[0] = BSWAP64(safebuff.b64[0]);
temp.b64[0] = mask.b64[0] & message.b64[0];
temp.b64[0] |=
((uint64_t)direction + direction + LAST_PADDING_BIT)
<< ((QWORDSIZEINBITS - 2) - lengthInBits);
a.b64[0] ^= temp.b64[0];
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] ^= a.b64[0];
} else if (lengthInBits == (QWORDSIZEINBITS - 1)) {
/* next block is : message + direct */
/* last block is : 1 + 63 0's */
a.b64[0] ^= direction | (~1 & BSWAP64(*(pIn++)));
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] ^= a.b64[0];
a.b8[QWORDSIZEINBYTES - 1] ^= (LAST_PADDING_BIT)
<< (QWORDSIZEINBYTES - 1);
/* KASUMI it */
kasumi_1_block(pCtx->sk16, a.b16);
/* update */
b.b64[0] ^= a.b64[0];
}
/* Kasumi b */
kasumi_1_block(pCtx->msk16, b.b16);
/* swap result */
*(uint32_t *)pDigest = bswap4(b.b32[1]);
#ifdef SAFE_DATA
/* Clear sensitive data in stack */
clear_mem(&a, sizeof(a));
clear_mem(&b, sizeof(b));
clear_mem(&mask, sizeof(mask));
clear_mem(&message, sizeof(message));
clear_mem(&temp, sizeof(temp));
clear_mem(&safebuff, sizeof(safebuff));
#endif
}
#endif /*_KASUMI_INTERNAL_H_*/
|
eb7d4ea1268dbead040fd73b5c35acf183dbd496
|
1efb2283837c9b70bc6449cec877799e4efa3268
|
/test/mpi/ft/isendalive.c
|
2b750939bc6a644832e240f2632e4777953d3efe
|
[
"mpich2"
] |
permissive
|
pmodels/mpich
|
d2392e8e30536cad3e500c16aa1e71211101d83f
|
2d265f9f5f93ebdd07ad547423bc6212868262a4
|
refs/heads/main
| 2023-09-04T05:50:15.041823
| 2023-09-01T23:07:33
| 2023-09-01T23:07:33
| 70,918,679
| 506
| 313
|
NOASSERTION
| 2023-09-14T14:38:36
| 2016-10-14T14:39:42
|
C
|
UTF-8
|
C
| false
| false
| 1,480
|
c
|
isendalive.c
|
/*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include "mpitest.h"
/*
* This test attempts communication between 2 running processes
* after another process has failed. The communication should complete
* successfully.
*/
int main(int argc, char **argv)
{
int rank, size, err = 0;
char buf[10];
MPI_Request request;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
if (size < 3) {
fprintf(stderr, "Must run with at least 3 processes\n");
MPI_Abort(MPI_COMM_WORLD, 1);
}
if (rank == 1) {
exit(EXIT_FAILURE);
}
if (rank == 0) {
err = MPI_Isend("No Errors", 10, MPI_CHAR, 2, 0, MPI_COMM_WORLD, &request);
err += MPI_Wait(&request, MPI_STATUS_IGNORE);
if (err) {
fprintf(stderr, "An error occurred during the send operation\n");
}
}
if (rank == 2) {
err = MPI_Irecv(buf, 10, MPI_CHAR, 0, 0, MPI_COMM_WORLD, &request);
err += MPI_Wait(&request, MPI_STATUS_IGNORE);
if (err) {
fprintf(stderr, "An error occurred during the recv operation\n");
} else {
printf(" %s\n", buf);
fflush(stdout);
}
}
MPI_Finalize();
return MTestReturnValue(err);
}
|
7720ca09f6be6132342c03cbc61ae8f9a6aacedd
|
59864cbd213b5da6f50d6255b0a021564b3d5bd4
|
/challenges/Recipe_Database/src/get_instructions.c
|
aa4f519d92be591a08df1959fb63b17484e31352
|
[
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown",
"BSD-2-Clause"
] |
permissive
|
trailofbits/cb-multios
|
8af96a4fbc3b34644367faa135347f88e0e0d0a3
|
810d7b24b1f62f56ef49b148fe155b0d0629cad2
|
refs/heads/master
| 2023-09-05T03:56:20.229403
| 2022-12-27T15:47:54
| 2022-12-27T15:47:54
| 41,688,943
| 522
| 133
|
MIT
| 2023-06-29T02:47:13
| 2015-08-31T17:04:31
|
C
|
UTF-8
|
C
| false
| false
| 3,524
|
c
|
get_instructions.c
|
/*
Author: Steve Wood <swood@cromulence.co>
Copyright (c) 2014 Cromulence LLC
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 "libcgc.h"
#include "cgc_stdlib.h"
#include "cgc_service.h"
void cgc_get_instructions(Recipe_Type *recipe) {
cgc_size_t size;
char buffer[1024];
char *temp_step;
char **step_list;
int step_count = 0;
cgc_printf("Enter the step by step instructions. A blank line to end.\n\n");
cgc_printf("Step 1: ");
size=cgc_getline(buffer, sizeof(buffer));
if (size <=1)
return;
else {
// the dynamic array is null terminated so allocate memory for the null too
#ifdef PATCHED
recipe->Instructions = cgc_malloc(sizeof(char *) * 4);
#else
recipe->Instructions = cgc_malloc(sizeof(char *) * 2);
#endif
if (recipe->Instructions == 0) {
cgc_printf("unable to malloc memory\n");
cgc__terminate(-1);
}
#ifdef PATCHED
cgc_memset(recipe->Instructions, 0, sizeof(char *)*4);
#else
cgc_memset(recipe->Instructions, 0, sizeof(char *)*2);
#endif
#ifdef PATCHED
temp_step=cgc_malloc(cgc_strlen(buffer)+1);
#else
temp_step=cgc_malloc(cgc_strlen(buffer));
#endif
if (temp_step == 0) {
cgc_printf("unable to malloc memory\n");
cgc__terminate(-1);
}
#ifdef PATCHED
cgc_memset( temp_step, 0, cgc_strlen(buffer) + 1 );
#endif
cgc_strcpy(temp_step, buffer);
recipe->Instructions[0] = temp_step;
step_count++;
}
cgc_printf("Step 2: ");
size=cgc_getline(buffer, sizeof(buffer));
while(size > 1) {
#ifdef PATCHED
step_list = cgc_malloc(sizeof(char *)*(step_count+4));
#else
step_list = cgc_malloc(sizeof(char *)*(step_count+2));
#endif
if (step_list == 0) {
cgc_printf("unable to malloc\n");
cgc__terminate(-1);
}
#ifdef PATCHED
cgc_memset(step_list, 0, sizeof(char *)*(step_count+4));
#else
cgc_memset(step_list, 0, sizeof(char *)*(step_count+2));
#endif
cgc_memcpy(step_list, recipe->Instructions, sizeof(char *)*(step_count+1));
#ifdef PATCHED
temp_step=cgc_malloc(cgc_strlen(buffer)+1);
#else
temp_step=cgc_malloc(cgc_strlen(buffer));
#endif
if (temp_step == 0) {
cgc_printf("unable to malloc memory\n");
cgc__terminate(-1);
}
#ifdef PATCHED
cgc_memset( temp_step, 0, cgc_strlen(buffer)+ 1);
#endif
cgc_strcpy(temp_step, buffer);
step_list[step_count] = temp_step;
cgc_free(recipe->Instructions);
recipe->Instructions = step_list;
++step_count;
cgc_printf("Step @d: ", step_count+1);
size=cgc_getline(buffer, sizeof(buffer));
} // while
} // get_instructions()
|
b9333ad997b847f1ecad8c2199ab2b6bba17589c
|
1885ce333f6980ab6aad764b3f8caf42094d9f7d
|
/test/e2e/test_master/skia/src/images/SkImageEncoderFns.h
|
741ff727eb31e7e19e5b3f45888100c0932f5ec8
|
[
"MIT"
] |
permissive
|
satya-das/cppparser
|
1dbccdeed4287c36c61edc30190c82de447e415b
|
f9a4cfac1a3af7286332056d7c661d86b6c35eb3
|
refs/heads/master
| 2023-07-06T00:55:23.382303
| 2022-10-03T19:40:05
| 2022-10-03T19:40:05
| 16,642,636
| 194
| 26
|
MIT
| 2023-06-26T13:44:32
| 2014-02-08T12:20:01
|
C++
|
UTF-8
|
C
| false
| false
| 6,077
|
h
|
SkImageEncoderFns.h
|
/*
* Copyright 2012 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkImageEncoderFns_DEFINED
# define SkImageEncoderFns_DEFINED
# include "include/core/SkColor.h"
# include "include/core/SkICC.h"
# include "include/core/SkTypes.h"
# include "include/private/SkColorData.h"
# include "include/third_party/skcms/skcms.h"
typedef void (*transform_scanline_proc) (char* dst, const char* src, int width, int bpp);
static void transform_scanline_memcpy(char* dst, const char* src, int width, int bpp)
{
memcpy(dst, src, width * bpp);
}
static void transform_scanline_A8_to_GrayAlpha(char* dst, const char* src, int width, int)
{
for (int i = 0; i < width; i++)
{
*dst++ = 0;
*dst++ = *src++;
}
}
static void skcms(char* dst, const char* src, int n, skcms_PixelFormat srcFmt, skcms_AlphaFormat srcAlpha, skcms_PixelFormat dstFmt, skcms_AlphaFormat dstAlpha)
{
SkAssertResult(skcms_Transform(src, srcFmt, srcAlpha, nullptr, dst, dstFmt, dstAlpha, nullptr, n));
}
static void transform_scanline_gray(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_G_8, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_565(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_BGR_565, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_RGBX(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_BGRX(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_BGRA_8888, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_444(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_ABGR_4444, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_rgbA(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_bgrA(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_BGRA_8888, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_to_premul_legacy(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_PremulAsEncoded);
}
static void transform_scanline_BGRA(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_BGRA_8888, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_4444(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_ABGR_4444, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_101010x(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_1010102, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGB_161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_1010102(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_1010102, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_1010102_premul(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_1010102, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F16(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_hhhh, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F16_premul(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_hhhh, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F16_to_8888(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_hhhh, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F16_premul_to_8888(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_hhhh, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F16_to_premul_8888(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_hhhh, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_8888, skcms_AlphaFormat_PremulAsEncoded);
}
static void transform_scanline_F32(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_ffff, skcms_AlphaFormat_Unpremul, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static void transform_scanline_F32_premul(char* dst, const char* src, int width, int)
{
skcms(dst, src, width, skcms_PixelFormat_RGBA_ffff, skcms_AlphaFormat_PremulAsEncoded, skcms_PixelFormat_RGBA_16161616BE, skcms_AlphaFormat_Unpremul);
}
static sk_sp<SkData> icc_from_color_space(const SkImageInfo& info)
{
SkColorSpace* cs = info.colorSpace();
if (!cs)
{
return nullptr;
}
skcms_TransferFunction fn;
skcms_Matrix3x3 toXYZD50;
if (cs->isNumericalTransferFn(&fn) && cs->toXYZD50(&toXYZD50))
{
return SkWriteICCProfile(fn, toXYZD50);
}
return nullptr;
}
#endif
|
fed774862f5d9d318d081a24feca99ed65b986d7
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/media/pci/mantis/mantis_vp1041.c
|
07aa887a4b4a9ed46b9daf136e37c36ee9bbff9c
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 11,247
|
c
|
mantis_vp1041.c
|
/*
Mantis VP-1041 driver
Copyright (C) Manu Abraham (abraham.manu@gmail.com)
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.
*/
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include "dmxdev.h"
#include "dvbdev.h"
#include "dvb_demux.h"
#include "dvb_frontend.h"
#include "dvb_net.h"
#include "mantis_common.h"
#include "mantis_ioc.h"
#include "mantis_dvb.h"
#include "mantis_vp1041.h"
#include "stb0899_reg.h"
#include "stb0899_drv.h"
#include "stb0899_cfg.h"
#include "stb6100_cfg.h"
#include "stb6100.h"
#include "lnbp21.h"
#define MANTIS_MODEL_NAME "VP-1041"
#define MANTIS_DEV_TYPE "DSS/DVB-S/DVB-S2"
static const struct stb0899_s1_reg vp1041_stb0899_s1_init_1[] = {
/* 0x0000000b, *//* SYSREG */
{ STB0899_DEV_ID , 0x30 },
{ STB0899_DISCNTRL1 , 0x32 },
{ STB0899_DISCNTRL2 , 0x80 },
{ STB0899_DISRX_ST0 , 0x04 },
{ STB0899_DISRX_ST1 , 0x00 },
{ STB0899_DISPARITY , 0x00 },
{ STB0899_DISSTATUS , 0x20 },
{ STB0899_DISF22 , 0x99 },
{ STB0899_DISF22RX , 0xa8 },
/* SYSREG ? */
{ STB0899_ACRPRESC , 0x11 },
{ STB0899_ACRDIV1 , 0x0a },
{ STB0899_ACRDIV2 , 0x05 },
{ STB0899_DACR1 , 0x00 },
{ STB0899_DACR2 , 0x00 },
{ STB0899_OUTCFG , 0x00 },
{ STB0899_MODECFG , 0x00 },
{ STB0899_IRQSTATUS_3 , 0xfe },
{ STB0899_IRQSTATUS_2 , 0x03 },
{ STB0899_IRQSTATUS_1 , 0x7c },
{ STB0899_IRQSTATUS_0 , 0xf4 },
{ STB0899_IRQMSK_3 , 0xf3 },
{ STB0899_IRQMSK_2 , 0xfc },
{ STB0899_IRQMSK_1 , 0xff },
{ STB0899_IRQMSK_0 , 0xff },
{ STB0899_IRQCFG , 0x00 },
{ STB0899_I2CCFG , 0x88 },
{ STB0899_I2CRPT , 0x58 },
{ STB0899_IOPVALUE5 , 0x00 },
{ STB0899_IOPVALUE4 , 0x33 },
{ STB0899_IOPVALUE3 , 0x6d },
{ STB0899_IOPVALUE2 , 0x90 },
{ STB0899_IOPVALUE1 , 0x60 },
{ STB0899_IOPVALUE0 , 0x00 },
{ STB0899_GPIO00CFG , 0x82 },
{ STB0899_GPIO01CFG , 0x82 },
{ STB0899_GPIO02CFG , 0x82 },
{ STB0899_GPIO03CFG , 0x82 },
{ STB0899_GPIO04CFG , 0x82 },
{ STB0899_GPIO05CFG , 0x82 },
{ STB0899_GPIO06CFG , 0x82 },
{ STB0899_GPIO07CFG , 0x82 },
{ STB0899_GPIO08CFG , 0x82 },
{ STB0899_GPIO09CFG , 0x82 },
{ STB0899_GPIO10CFG , 0x82 },
{ STB0899_GPIO11CFG , 0x82 },
{ STB0899_GPIO12CFG , 0x82 },
{ STB0899_GPIO13CFG , 0x82 },
{ STB0899_GPIO14CFG , 0x82 },
{ STB0899_GPIO15CFG , 0x82 },
{ STB0899_GPIO16CFG , 0x82 },
{ STB0899_GPIO17CFG , 0x82 },
{ STB0899_GPIO18CFG , 0x82 },
{ STB0899_GPIO19CFG , 0x82 },
{ STB0899_GPIO20CFG , 0x82 },
{ STB0899_SDATCFG , 0xb8 },
{ STB0899_SCLTCFG , 0xba },
{ STB0899_AGCRFCFG , 0x1c }, /* 0x11 */
{ STB0899_GPIO22 , 0x82 }, /* AGCBB2CFG */
{ STB0899_GPIO21 , 0x91 }, /* AGCBB1CFG */
{ STB0899_DIRCLKCFG , 0x82 },
{ STB0899_CLKOUT27CFG , 0x7e },
{ STB0899_STDBYCFG , 0x82 },
{ STB0899_CS0CFG , 0x82 },
{ STB0899_CS1CFG , 0x82 },
{ STB0899_DISEQCOCFG , 0x20 },
{ STB0899_GPIO32CFG , 0x82 },
{ STB0899_GPIO33CFG , 0x82 },
{ STB0899_GPIO34CFG , 0x82 },
{ STB0899_GPIO35CFG , 0x82 },
{ STB0899_GPIO36CFG , 0x82 },
{ STB0899_GPIO37CFG , 0x82 },
{ STB0899_GPIO38CFG , 0x82 },
{ STB0899_GPIO39CFG , 0x82 },
{ STB0899_NCOARSE , 0x17 }, /* 0x15 = 27 Mhz Clock, F/3 = 198MHz, F/6 = 99MHz */
{ STB0899_SYNTCTRL , 0x02 }, /* 0x00 = CLK from CLKI, 0x02 = CLK from XTALI */
{ STB0899_FILTCTRL , 0x00 },
{ STB0899_SYSCTRL , 0x01 },
{ STB0899_STOPCLK1 , 0x20 },
{ STB0899_STOPCLK2 , 0x00 },
{ STB0899_INTBUFSTATUS , 0x00 },
{ STB0899_INTBUFCTRL , 0x0a },
{ 0xffff , 0xff },
};
static const struct stb0899_s1_reg vp1041_stb0899_s1_init_3[] = {
{ STB0899_DEMOD , 0x00 },
{ STB0899_RCOMPC , 0xc9 },
{ STB0899_AGC1CN , 0x01 },
{ STB0899_AGC1REF , 0x10 },
{ STB0899_RTC , 0x23 },
{ STB0899_TMGCFG , 0x4e },
{ STB0899_AGC2REF , 0x34 },
{ STB0899_TLSR , 0x84 },
{ STB0899_CFD , 0xf7 },
{ STB0899_ACLC , 0x87 },
{ STB0899_BCLC , 0x94 },
{ STB0899_EQON , 0x41 },
{ STB0899_LDT , 0xf1 },
{ STB0899_LDT2 , 0xe3 },
{ STB0899_EQUALREF , 0xb4 },
{ STB0899_TMGRAMP , 0x10 },
{ STB0899_TMGTHD , 0x30 },
{ STB0899_IDCCOMP , 0xfd },
{ STB0899_QDCCOMP , 0xff },
{ STB0899_POWERI , 0x0c },
{ STB0899_POWERQ , 0x0f },
{ STB0899_RCOMP , 0x6c },
{ STB0899_AGCIQIN , 0x80 },
{ STB0899_AGC2I1 , 0x06 },
{ STB0899_AGC2I2 , 0x00 },
{ STB0899_TLIR , 0x30 },
{ STB0899_RTF , 0x7f },
{ STB0899_DSTATUS , 0x00 },
{ STB0899_LDI , 0xbc },
{ STB0899_CFRM , 0xea },
{ STB0899_CFRL , 0x31 },
{ STB0899_NIRM , 0x2b },
{ STB0899_NIRL , 0x80 },
{ STB0899_ISYMB , 0x1d },
{ STB0899_QSYMB , 0xa6 },
{ STB0899_SFRH , 0x2f },
{ STB0899_SFRM , 0x68 },
{ STB0899_SFRL , 0x40 },
{ STB0899_SFRUPH , 0x2f },
{ STB0899_SFRUPM , 0x68 },
{ STB0899_SFRUPL , 0x40 },
{ STB0899_EQUAI1 , 0x02 },
{ STB0899_EQUAQ1 , 0xff },
{ STB0899_EQUAI2 , 0x04 },
{ STB0899_EQUAQ2 , 0x05 },
{ STB0899_EQUAI3 , 0x02 },
{ STB0899_EQUAQ3 , 0xfd },
{ STB0899_EQUAI4 , 0x03 },
{ STB0899_EQUAQ4 , 0x07 },
{ STB0899_EQUAI5 , 0x08 },
{ STB0899_EQUAQ5 , 0xf5 },
{ STB0899_DSTATUS2 , 0x00 },
{ STB0899_VSTATUS , 0x00 },
{ STB0899_VERROR , 0x86 },
{ STB0899_IQSWAP , 0x2a },
{ STB0899_ECNT1M , 0x00 },
{ STB0899_ECNT1L , 0x00 },
{ STB0899_ECNT2M , 0x00 },
{ STB0899_ECNT2L , 0x00 },
{ STB0899_ECNT3M , 0x0a },
{ STB0899_ECNT3L , 0xad },
{ STB0899_FECAUTO1 , 0x06 },
{ STB0899_FECM , 0x01 },
{ STB0899_VTH12 , 0xb0 },
{ STB0899_VTH23 , 0x7a },
{ STB0899_VTH34 , 0x58 },
{ STB0899_VTH56 , 0x38 },
{ STB0899_VTH67 , 0x34 },
{ STB0899_VTH78 , 0x24 },
{ STB0899_PRVIT , 0xff },
{ STB0899_VITSYNC , 0x19 },
{ STB0899_RSULC , 0xb1 }, /* DVB = 0xb1, DSS = 0xa1 */
{ STB0899_TSULC , 0x42 },
{ STB0899_RSLLC , 0x41 },
{ STB0899_TSLPL , 0x12 },
{ STB0899_TSCFGH , 0x0c },
{ STB0899_TSCFGM , 0x00 },
{ STB0899_TSCFGL , 0x00 },
{ STB0899_TSOUT , 0x69 }, /* 0x0d for CAM */
{ STB0899_RSSYNCDEL , 0x00 },
{ STB0899_TSINHDELH , 0x02 },
{ STB0899_TSINHDELM , 0x00 },
{ STB0899_TSINHDELL , 0x00 },
{ STB0899_TSLLSTKM , 0x1b },
{ STB0899_TSLLSTKL , 0xb3 },
{ STB0899_TSULSTKM , 0x00 },
{ STB0899_TSULSTKL , 0x00 },
{ STB0899_PCKLENUL , 0xbc },
{ STB0899_PCKLENLL , 0xcc },
{ STB0899_RSPCKLEN , 0xbd },
{ STB0899_TSSTATUS , 0x90 },
{ STB0899_ERRCTRL1 , 0xb6 },
{ STB0899_ERRCTRL2 , 0x95 },
{ STB0899_ERRCTRL3 , 0x8d },
{ STB0899_DMONMSK1 , 0x27 },
{ STB0899_DMONMSK0 , 0x03 },
{ STB0899_DEMAPVIT , 0x5c },
{ STB0899_PLPARM , 0x19 },
{ STB0899_PDELCTRL , 0x48 },
{ STB0899_PDELCTRL2 , 0x00 },
{ STB0899_BBHCTRL1 , 0x00 },
{ STB0899_BBHCTRL2 , 0x00 },
{ STB0899_HYSTTHRESH , 0x77 },
{ STB0899_MATCSTM , 0x00 },
{ STB0899_MATCSTL , 0x00 },
{ STB0899_UPLCSTM , 0x00 },
{ STB0899_UPLCSTL , 0x00 },
{ STB0899_DFLCSTM , 0x00 },
{ STB0899_DFLCSTL , 0x00 },
{ STB0899_SYNCCST , 0x00 },
{ STB0899_SYNCDCSTM , 0x00 },
{ STB0899_SYNCDCSTL , 0x00 },
{ STB0899_ISI_ENTRY , 0x00 },
{ STB0899_ISI_BIT_EN , 0x00 },
{ STB0899_MATSTRM , 0xf0 },
{ STB0899_MATSTRL , 0x02 },
{ STB0899_UPLSTRM , 0x45 },
{ STB0899_UPLSTRL , 0x60 },
{ STB0899_DFLSTRM , 0xe3 },
{ STB0899_DFLSTRL , 0x00 },
{ STB0899_SYNCSTR , 0x47 },
{ STB0899_SYNCDSTRM , 0x05 },
{ STB0899_SYNCDSTRL , 0x18 },
{ STB0899_CFGPDELSTATUS1 , 0x19 },
{ STB0899_CFGPDELSTATUS2 , 0x2b },
{ STB0899_BBFERRORM , 0x00 },
{ STB0899_BBFERRORL , 0x01 },
{ STB0899_UPKTERRORM , 0x00 },
{ STB0899_UPKTERRORL , 0x00 },
{ 0xffff , 0xff },
};
struct stb0899_config vp1041_stb0899_config = {
.init_dev = vp1041_stb0899_s1_init_1,
.init_s2_demod = stb0899_s2_init_2,
.init_s1_demod = vp1041_stb0899_s1_init_3,
.init_s2_fec = stb0899_s2_init_4,
.init_tst = stb0899_s1_init_5,
.demod_address = 0x68, /* 0xd0 >> 1 */
.xtal_freq = 27000000,
.inversion = IQ_SWAP_ON, /* 1 */
.lo_clk = 76500000,
.hi_clk = 99000000,
.esno_ave = STB0899_DVBS2_ESNO_AVE,
.esno_quant = STB0899_DVBS2_ESNO_QUANT,
.avframes_coarse = STB0899_DVBS2_AVFRAMES_COARSE,
.avframes_fine = STB0899_DVBS2_AVFRAMES_FINE,
.miss_threshold = STB0899_DVBS2_MISS_THRESHOLD,
.uwp_threshold_acq = STB0899_DVBS2_UWP_THRESHOLD_ACQ,
.uwp_threshold_track = STB0899_DVBS2_UWP_THRESHOLD_TRACK,
.uwp_threshold_sof = STB0899_DVBS2_UWP_THRESHOLD_SOF,
.sof_search_timeout = STB0899_DVBS2_SOF_SEARCH_TIMEOUT,
.btr_nco_bits = STB0899_DVBS2_BTR_NCO_BITS,
.btr_gain_shift_offset = STB0899_DVBS2_BTR_GAIN_SHIFT_OFFSET,
.crl_nco_bits = STB0899_DVBS2_CRL_NCO_BITS,
.ldpc_max_iter = STB0899_DVBS2_LDPC_MAX_ITER,
.tuner_get_frequency = stb6100_get_frequency,
.tuner_set_frequency = stb6100_set_frequency,
.tuner_set_bandwidth = stb6100_set_bandwidth,
.tuner_get_bandwidth = stb6100_get_bandwidth,
.tuner_set_rfsiggain = NULL,
};
struct stb6100_config vp1041_stb6100_config = {
.tuner_address = 0x60,
.refclock = 27000000,
};
static int vp1041_frontend_init(struct mantis_pci *mantis, struct dvb_frontend *fe)
{
struct i2c_adapter *adapter = &mantis->adapter;
int err = 0;
err = mantis_frontend_power(mantis, POWER_ON);
if (err == 0) {
mantis_frontend_soft_reset(mantis);
msleep(250);
mantis->fe = dvb_attach(stb0899_attach, &vp1041_stb0899_config, adapter);
if (mantis->fe) {
dprintk(MANTIS_ERROR, 1,
"found STB0899 DVB-S/DVB-S2 frontend @0x%02x",
vp1041_stb0899_config.demod_address);
if (dvb_attach(stb6100_attach, mantis->fe, &vp1041_stb6100_config, adapter)) {
if (!dvb_attach(lnbp21_attach, mantis->fe, adapter, 0, 0))
dprintk(MANTIS_ERROR, 1, "No LNBP21 found!");
}
} else {
return -EREMOTEIO;
}
} else {
dprintk(MANTIS_ERROR, 1, "Frontend on <%s> POWER ON failed! <%d>",
adapter->name,
err);
return -EIO;
}
dprintk(MANTIS_ERROR, 1, "Done!");
return 0;
}
struct mantis_hwconfig vp1041_config = {
.model_name = MANTIS_MODEL_NAME,
.dev_type = MANTIS_DEV_TYPE,
.ts_size = MANTIS_TS_188,
.baud_rate = MANTIS_BAUD_9600,
.parity = MANTIS_PARITY_NONE,
.bytes = 0,
.frontend_init = vp1041_frontend_init,
.power = GPIF_A12,
.reset = GPIF_A13,
};
|
78046264fb0f7e6c9878303e5d7bdb4be1b02b8e
|
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
|
/ngmath/src/lib/gridpack/dsgrid/dsgrid3d.c
|
f0b844028fc32da953b9b63285457c0b548e425b
|
[
"Apache-2.0"
] |
permissive
|
NCAR/ncl
|
243c30eaefce642d53373aa583b73df72eb59f22
|
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
|
refs/heads/develop
| 2023-03-17T07:53:18.883458
| 2022-05-11T16:01:03
| 2022-05-11T16:01:03
| 67,087,395
| 254
| 68
|
NOASSERTION
| 2022-10-08T07:20:06
| 2016-09-01T01:34:28
|
C
|
UTF-8
|
C
| false
| false
| 11,707
|
c
|
dsgrid3d.c
|
/************************************************************************
* *
* Copyright (C) 2000 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
* The use of this Software is governed by a License Agreement. *
* *
************************************************************************/
#include <ncarg/ngmath.h>
#include "dstypes.h"
#include "dsproto.h"
#include "dsuhead.h"
#define PIH 1.5707963
/*
* Interpolate randomly-spaced 3D input data to a regularly spaced grid.
*/
double *c_dsgrid3d(int n, double x[], double y[], double z[], double u[],
int nx, int ny, int nz, double xo[], double yo[],
double zo[], int *ier)
/*
* Arguments
* ---------
* n - The number of input data points.
* x - An array of X coordinate values of the input data points.
* y - An array of Y coordinate values of the input data points.
* z - An array of Z coordinate values of the input data points.
* u - The functional value at coordinate (x,y,z).
* nx - The dimension of the array xo containing the X coordinate
* values for the output grid.
* ny - The dimension of the array yo containing the Y coordinate
* values for the output grid.
* nz - The dimension of the array zo containing the z coordinate
* values for the output grid.
* xo - The array containing the X coordinate values for the output
* grid (must be monotone increasing, but need not be equally
* spaced.
* yo - The array containing the Y coordinate values for the output
* grid (must be monotone increasing, but need not be equally
* spaced.
* zo - The array containing the Z coordinate values for the output
* grid (must be monotone increasing, but need not be equally
* spaced.
* *ier - An error return value ( = 0 is no error).
*
* Return value
* ------------
* A pointer to the first element of a linear array that is
* laid out as a 3D array (i.e. the last subscript varies fastest)
* of dimension: nx by ny by nz.
*/
{
int i, j, k;
static double perror = 1.;
double xc, yc, zc, *retval;
DSpointd3 q;
/*
* Get memory and do initialization.
*/
*ier = 0;
dsgetmem(n, nx, ny, nz, ier);
if (*ier != 0) return(&perror);
dsinit(n, nx, ny, nz, x, y, z, xo, yo, zo, ier);
if (*ier != 0) return(&perror);
/*
* Loop over the output grid
*/
for (i = 0; i < nx; i++) {
xc = xo[i];
for (j = 0; j < ny; j++) {
yc = yo[j];
for (k = 0; k < nz; k++) {
zc = zo[k];
/*
* Compute the distances from (xc, yc, zc) to all the input points.
*/
q.x = xc * ds_scale;
q.y = yc * ds_scale;
q.z = zc * ds_scale;
dsdist(n, ds_input_points, q, ds_distances);
/*
* Calculate the interpolated value.
*/
if (ds_shadowing) {
ds_output[nz*ny*i + nz*j + k] =
svalue(n, u, q.x, q.y, q.z);
}
else {
ds_output[nz*ny*i + nz*j + k] =
ivalue(n, u, q.x, q.y, q.z);
}
}
}
}
retval = &ds_output[0];
dsfreemem();
ds_first_call = 0;
return(retval);
}
/*
* Get required memory.
*/
void dsgetmem(int n, int nx, int ny, int nz, int *ier)
{
ds_input_points = (DSpointd3 *) calloc(n, sizeof(DSpointd3));
if (ds_input_points == NULL) {
DSErrorHnd(6, "dsgetmem", stderr, "\n");
*ier = ds_error_status;
return;
}
ds_distances = (double *) calloc(n, sizeof(double));
if (ds_distances == NULL) {
DSErrorHnd(9, "dsgetmem", stderr, "\n");
*ier = ds_error_status;
return;
}
ds_weights = (double *) calloc(n, sizeof(double));
if (ds_weights == NULL) {
DSErrorHnd(10, "dsgetmem", stderr, "\n");
*ier = ds_error_status;
return;
}
ds_permutation_vector = (int *) calloc(n, sizeof(int));
if (ds_permutation_vector == NULL) {
DSErrorHnd(11, "dsgetmem", stderr, "\n");
*ier = ds_error_status;
return;
}
ds_output = (double *) calloc(nx*ny*nz, sizeof(double));
if (ds_output == NULL) {
DSErrorHnd(12, "dsgetmem", stderr, "\n");
*ier = ds_error_status;
return;
}
}
/*
* Free memory.
*/
void dsfreemem()
{
free(ds_input_points);
free(ds_distances);
free(ds_weights);
free(ds_permutation_vector);
}
/*
* Initialization.
*/
void dsinit(int n, int nx, int ny, int nz, double x[], double y[], double z[],
double xo[], double yo[], double zo[], int *ier)
{
int i;
double xmn, ymn, zmn, xmx, ymx, zmx, tlm;
if (ds_set_maxpts == 0) ds_maxpoints = n;
if (n < 3) {
DSErrorHnd(2, "dsinit", stderr, "\n");
*ier = ds_error_status;
return;
}
if ((nx <= 0) || (ny <=0) || (nz <= 0)) {
DSErrorHnd(3, "dsinit", stderr, "\n");
*ier = ds_error_status;
return;
}
xmn = xo[0];
ymn = yo[0];
zmn = zo[0];
xmx = xo[0];
ymx = yo[0];
zmx = zo[0];
for (i = 0; i < nx; i++) {
xmn = MIN(xo[i], xmn);
xmx = MAX(xo[i], xmx);
}
for (i = 0; i < ny; i++) {
ymn = MIN(yo[i], ymn);
ymx = MAX(yo[i], ymx);
}
for (i = 0; i < nz; i++) {
zmn = MIN(zo[i], zmn);
zmx = MAX(zo[i], zmx);
}
for (i = 0; i < n; i++) {
xmn = MIN(x[i], xmn);
xmx = MAX(x[i], xmx);
ymn = MIN(y[i], ymn);
ymx = MAX(y[i], ymx);
zmn = MIN(z[i], zmn);
zmx = MAX(z[i], zmx);
}
/*
* Find the maximum span of the three coordinates.
*/
tlm = MAX(MAX((xmx - xmn), ymx - ymn), zmx - zmn);
/*
* Set the maximum distance for point inclusion to include all
* points, if this has not been specifically set by the user.
*/
if (ds_set_max_dist == 0) ds_max_dist =
2.*((xmx - xmn) + (ymx - ymn) + (zmx - zmn));
/*
* Scale and store the input values.
*/
ds_scale = 1./tlm;
for (i = 0; i < n; i++) {
ds_input_points[i].x = x[i] * ds_scale;
ds_input_points[i].y = y[i] * ds_scale;
ds_input_points[i].z = z[i] * ds_scale;
}
ds_epsilon_test = 1.E-5;
for (i = 0; i < nx*ny*nz; i++) {
ds_output[i] = ds_missing_value;
}
}
/*
* Calculate interpolated value when the shadowing option is
* turned off.
*/
double ivalue(int num_points, double *values,
double xc, double yc, double zc)
{
int iw, it;
double normalization_factor, interpolated_value, weight_sum;
for (iw = 0; iw < num_points; iw++) {
if ( (ds_distances[iw] < ds_epsilon_test) && (ds_distances[iw] >= 0.) ) {
for (it = 0; it < num_points; it++) {
ds_weights[it] = 0.;
}
ds_weights[iw] = 1.;
goto label_1;
}
}
dweights(num_points);
for (weight_sum = 0., iw = 0; iw < num_points; iw++) {
weight_sum += ds_weights[iw];
}
if (weight_sum == 0.) {
DSErrorHnd(14, "ivalue", stderr, "\n");
return(ds_missing_value);
}
normalization_factor = 1./weight_sum;
for (iw = 0; iw < num_points; iw++) {
ds_weights[iw] *= normalization_factor;
}
label_1:
for (interpolated_value = 0., iw = 0; iw < num_points; iw++) {
interpolated_value += values[iw] * ds_weights[iw];
}
return(interpolated_value);
}
/*
* Calculate interpolated value when shadowing option is on.
*/
double svalue(int num_points, double *values,
double xc, double yc, double zc)
{
int iw, ia, it, lp;
double normalization_factor, interpolated_value, weight_sum;
for (iw = 0; iw < num_points; iw++) {
if ( (ds_distances[iw] < ds_epsilon_test) && (ds_distances[iw] >= 0.) ) {
for (it = 0; it < num_points; it++) {
ds_weights[it] = 0.;
}
ds_weights[iw] = 1.;
goto label_1;
}
}
for (it = 0; it < num_points; it++) {
ds_permutation_vector[it] = it;
}
dssortd(num_points, ds_distances, ds_permutation_vector);
sweights(num_points, xc, yc, zc);
for (weight_sum = 0., iw = 0; iw < num_points; iw++) {
weight_sum += ds_weights[iw];
}
if (weight_sum == 0.) {
DSErrorHnd(14, "svalue", stderr, "\n");
return(ds_missing_value);
}
normalization_factor = 1./weight_sum;
for (iw = 0; iw < num_points; iw++) {
ds_weights[iw] *= normalization_factor;
}
label_1:
for (interpolated_value = 0., iw = 0; iw < num_points; iw++) {
lp = ds_permutation_vector[iw];
interpolated_value += values[iw] * ds_weights[iw];
}
return(interpolated_value);
}
/*
* 3D interpolation in point mode.
*/
void c_dspnt3d(int n, double xi[], double yi[], double zi[], double ui[],
int m, double xo[], double yo[], double zo[], double uo[],
int *ier)
{
int i;
double xt[1], yt[1], zt[1];
for (i = 0; i < m; i++) {
xt[0] = xo[i];
yt[0] = yo[i];
zt[0] = zo[i];
uo[i] = *c_dsgrid3d(n, xi, yi, zi, ui, 1, 1, 1, xt, yt, zt, ier);
}
}
/*
* Claculate weights when shadowing is on.
*/
void sweights(int n, double xc, double yc, double zc)
{
int lpw, lpa, iw, ia;
double minimum_angle, angle, shadow_scale;
DSpointd3 p1, p2, p3;
lpw = ds_permutation_vector[0];
if (ds_distances[lpw] > 0.) {
ds_weights[lpw] = 1./dist_pow(ds_distances[0]);
}
else {
ds_weights[lpw] = 0.;
}
for (iw = 1; iw < n; iw++) {
minimum_angle = PIH;
lpw = ds_permutation_vector[n-iw];
p1.x = ds_input_points[lpw].x;
p1.y = ds_input_points[lpw].y;
p1.z = ds_input_points[lpw].z;
p2.x = xc;
p2.y = yc;
p2.z = zc;
for (ia = 0; ia < n - iw; ia++) {
lpa = ds_permutation_vector[ia];
p3.x = ds_input_points[lpa].x;
p3.y = ds_input_points[lpa].y;
p3.z = ds_input_points[lpa].z;
angle = dsangd(p1,p2,p3);
if (angle < minimum_angle) minimum_angle = angle;
}
shadow_scale = tan(0.5*minimum_angle);
if (ds_distances[n-iw] > 0.) {
ds_weights[lpw] = shadow_scale / dist_pow(ds_distances[n-iw]);
}
else {
ds_weights[lpw] = 0.;
}
}
}
void dweights(int n)
{
int it;
for (it = 0; it < n; it++) {
if (ds_distances[it] > 0.) {
ds_weights[it] = 1./ dist_pow(ds_distances[it]);
}
else {
ds_weights[it] = 0.;
}
}
}
/*
* Calculate powers of the distances.
*/
double dist_pow(double dist)
{
double dtmp;
if (ds_exponent == 3.0) {
dtmp = dist*dist*dist;
}
else if (ds_exponent == 1.0) {
dtmp = dist;
}
else if (ds_exponent == 0.5) {
dtmp = sqrt(dist);
}
else if (ds_exponent == 2.0) {
dtmp = dist*dist;
}
else if (ds_exponent == 4.0) {
dtmp = dist*dist;
dtmp = dtmp*dtmp;
}
else if (ds_exponent == 5.0) {
dtmp = dist*dist*dist*dist*dist;
}
else if (ds_exponent == 6.0) {
dtmp = dist*dist*dist;
dtmp = dtmp*dtmp;
}
else if (ds_exponent == 7.0) {
dtmp = dist*dist*dist*dist*dist*dist*dist;
}
else if (ds_exponent == 8.0) {
dtmp = dist*dist;
dtmp = dtmp*dtmp;
dtmp = dtmp*dtmp;
}
else if (ds_exponent == 9.0) {
dtmp = dist*dist*dist;
dtmp = dtmp*dtmp*dtmp;
}
else if (ds_exponent == 10.0) {
dtmp = dist*dist*dist*dist*dist;
dtmp = dtmp*dtmp;
}
else {
dtmp = pow(dist, ds_exponent);
}
if (dtmp < (double) 1.E-30) {
return ( (double) 1.E-30);
}
else {
return (dtmp);
}
}
|
010ac8733d9478b77c0a3030fef829498f1e7247
|
e73547787354afd9b717ea57fe8dd0695d161821
|
/src/effects/gfx/flashing_box_shockwave.c
|
771042ff63620e80ccfeedd6d682d81a347a8cde
|
[] |
no_license
|
pmret/papermario
|
8b514b19653cef8d6145e47499b3636b8c474a37
|
9774b26d93f1045dd2a67e502b6efc9599fb6c31
|
refs/heads/main
| 2023-08-31T07:09:48.951514
| 2023-08-21T18:07:08
| 2023-08-21T18:07:08
| 287,151,133
| 904
| 139
| null | 2023-09-14T02:44:23
| 2020-08-13T01:22:57
|
C
|
UTF-8
|
C
| false
| false
| 719
|
c
|
flashing_box_shockwave.c
|
#include "effects/gfx/D_09000000_3930A0.png.inc.c"
#include "effects/gfx/D_09000200_3932A0.png.inc.c"
#include "effects/gfx/D_09000600_3936A0.gfx.inc.c"
#include "effects/gfx/D_090006A8_393748.vtx.inc.c"
#include "effects/gfx/D_090007E8_393888.vtx.inc.c"
#include "effects/gfx/D_090008E8_393988.gfx.inc.c"
#include "effects/gfx/D_09000950_3939F0.gfx.inc.c"
#include "effects/gfx/D_090009F8_393A98.vtx.inc.c"
#include "effects/gfx/D_09000B18_393BB8.vtx.inc.c"
#include "effects/gfx/D_09000BB8_393C58.vtx.inc.c"
#include "effects/gfx/D_09000CF8_393D98.vtx.inc.c"
#include "effects/gfx/D_09000E18_393EB8.vtx.inc.c"
#include "effects/gfx/D_09000EB8_393F58.vtx.inc.c"
#include "effects/gfx/D_09000FF8_394098.gfx.inc.c"
|
3d0fc4c91fb3aba24ebb13868bde41b180e57840
|
c6759b857e55991fea3ef0b465dbcee53fa38714
|
/rtos/freeRTOS/vendors/gwt/vega/pmsis/include/pmsis/targets/periph/cluster/cluster_ctrl_unit/cluster_ctrl_unit_macros.h
|
16099a96d9906e75620d6324f79b38bab2fbec4a
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
GreenWaves-Technologies/gap_sdk
|
1b343bba97b7a5ce62a24162bd72eef5cc67e269
|
3fea306d52ee33f923f2423c5a75d9eb1c07e904
|
refs/heads/master
| 2023-09-01T14:38:34.270427
| 2023-08-10T09:04:44
| 2023-08-10T09:04:44
| 133,324,605
| 145
| 96
|
Apache-2.0
| 2023-08-27T19:03:52
| 2018-05-14T07:50:29
|
C
|
UTF-8
|
C
| false
| false
| 14,449
|
h
|
cluster_ctrl_unit_macros.h
|
/* THIS FILE HAS BEEN GENERATED, DO NOT MODIFY IT.
*/
/*
* Copyright (C) 2020 GreenWaves Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __ARCHI_CLUSTER_CTRL_UNIT_MACROS__
#define __ARCHI_CLUSTER_CTRL_UNIT_MACROS__
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
#endif
//
// REGISTERS FIELDS MACROS
//
#if !defined(LANGUAGE_ASSEMBLY) && !defined(__ASSEMBLER__)
#define CLUSTER_CTRL_UNIT_EOC_EOC_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_EOC_EOC_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_EOC_EOC_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_EOC_EOC(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE0_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE0_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE0_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE0(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE1_GET(value) (GAP_BEXTRACTU((value),1,1))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE1_GETS(value) (GAP_BEXTRACT((value),1,1))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE1_SET(value,field) (GAP_BINSERT((value),(field),1,1))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE1(val) ((val) << 1)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE2_GET(value) (GAP_BEXTRACTU((value),1,2))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE2_GETS(value) (GAP_BEXTRACT((value),1,2))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE2_SET(value,field) (GAP_BINSERT((value),(field),1,2))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE2(val) ((val) << 2)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE3_GET(value) (GAP_BEXTRACTU((value),1,3))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE3_GETS(value) (GAP_BEXTRACT((value),1,3))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE3_SET(value,field) (GAP_BINSERT((value),(field),1,3))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE3(val) ((val) << 3)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE4_GET(value) (GAP_BEXTRACTU((value),1,4))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE4_GETS(value) (GAP_BEXTRACT((value),1,4))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE4_SET(value,field) (GAP_BINSERT((value),(field),1,4))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE4(val) ((val) << 4)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE5_GET(value) (GAP_BEXTRACTU((value),1,5))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE5_GETS(value) (GAP_BEXTRACT((value),1,5))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE5_SET(value,field) (GAP_BINSERT((value),(field),1,5))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE5(val) ((val) << 5)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE6_GET(value) (GAP_BEXTRACTU((value),1,6))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE6_GETS(value) (GAP_BEXTRACT((value),1,6))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE6_SET(value,field) (GAP_BINSERT((value),(field),1,6))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE6(val) ((val) << 6)
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE7_GET(value) (GAP_BEXTRACTU((value),1,7))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE7_GETS(value) (GAP_BEXTRACT((value),1,7))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE7_SET(value,field) (GAP_BINSERT((value),(field),1,7))
#define CLUSTER_CTRL_UNIT_FETCH_EN_CORE7(val) ((val) << 7)
#define CLUSTER_CTRL_UNIT_CLOCK_GATE_EN_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_CLOCK_GATE_EN_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_CLOCK_GATE_EN_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_CLOCK_GATE_EN(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE0_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE0_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE0_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE0(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE1_GET(value) (GAP_BEXTRACTU((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE1_GETS(value) (GAP_BEXTRACT((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE1_SET(value,field) (GAP_BINSERT((value),(field),1,1))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE1(val) ((val) << 1)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE2_GET(value) (GAP_BEXTRACTU((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE2_GETS(value) (GAP_BEXTRACT((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE2_SET(value,field) (GAP_BINSERT((value),(field),1,2))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE2(val) ((val) << 2)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE3_GET(value) (GAP_BEXTRACTU((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE3_GETS(value) (GAP_BEXTRACT((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE3_SET(value,field) (GAP_BINSERT((value),(field),1,3))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE3(val) ((val) << 3)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE4_GET(value) (GAP_BEXTRACTU((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE4_GETS(value) (GAP_BEXTRACT((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE4_SET(value,field) (GAP_BINSERT((value),(field),1,4))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE4(val) ((val) << 4)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE5_GET(value) (GAP_BEXTRACTU((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE5_GETS(value) (GAP_BEXTRACT((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE5_SET(value,field) (GAP_BINSERT((value),(field),1,5))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE5(val) ((val) << 5)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE6_GET(value) (GAP_BEXTRACTU((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE6_GETS(value) (GAP_BEXTRACT((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE6_SET(value,field) (GAP_BINSERT((value),(field),1,6))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE6(val) ((val) << 6)
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE7_GET(value) (GAP_BEXTRACTU((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE7_GETS(value) (GAP_BEXTRACT((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE7_SET(value,field) (GAP_BINSERT((value),(field),1,7))
#define CLUSTER_CTRL_UNIT_DBG_RESUME_CORE7(val) ((val) << 7)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE0_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE0_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE0_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE0(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE1_GET(value) (GAP_BEXTRACTU((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE1_GETS(value) (GAP_BEXTRACT((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE1_SET(value,field) (GAP_BINSERT((value),(field),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE1(val) ((val) << 1)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE2_GET(value) (GAP_BEXTRACTU((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE2_GETS(value) (GAP_BEXTRACT((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE2_SET(value,field) (GAP_BINSERT((value),(field),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE2(val) ((val) << 2)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE3_GET(value) (GAP_BEXTRACTU((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE3_GETS(value) (GAP_BEXTRACT((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE3_SET(value,field) (GAP_BINSERT((value),(field),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE3(val) ((val) << 3)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE4_GET(value) (GAP_BEXTRACTU((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE4_GETS(value) (GAP_BEXTRACT((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE4_SET(value,field) (GAP_BINSERT((value),(field),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE4(val) ((val) << 4)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE5_GET(value) (GAP_BEXTRACTU((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE5_GETS(value) (GAP_BEXTRACT((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE5_SET(value,field) (GAP_BINSERT((value),(field),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE5(val) ((val) << 5)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE6_GET(value) (GAP_BEXTRACTU((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE6_GETS(value) (GAP_BEXTRACT((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE6_SET(value,field) (GAP_BINSERT((value),(field),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE6(val) ((val) << 6)
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE7_GET(value) (GAP_BEXTRACTU((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE7_GETS(value) (GAP_BEXTRACT((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE7_SET(value,field) (GAP_BINSERT((value),(field),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_STATUS_CORE7(val) ((val) << 7)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE0_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE0_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE0_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE0(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE1_GET(value) (GAP_BEXTRACTU((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE1_GETS(value) (GAP_BEXTRACT((value),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE1_SET(value,field) (GAP_BINSERT((value),(field),1,1))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE1(val) ((val) << 1)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE2_GET(value) (GAP_BEXTRACTU((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE2_GETS(value) (GAP_BEXTRACT((value),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE2_SET(value,field) (GAP_BINSERT((value),(field),1,2))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE2(val) ((val) << 2)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE3_GET(value) (GAP_BEXTRACTU((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE3_GETS(value) (GAP_BEXTRACT((value),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE3_SET(value,field) (GAP_BINSERT((value),(field),1,3))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE3(val) ((val) << 3)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE4_GET(value) (GAP_BEXTRACTU((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE4_GETS(value) (GAP_BEXTRACT((value),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE4_SET(value,field) (GAP_BINSERT((value),(field),1,4))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE4(val) ((val) << 4)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE5_GET(value) (GAP_BEXTRACTU((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE5_GETS(value) (GAP_BEXTRACT((value),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE5_SET(value,field) (GAP_BINSERT((value),(field),1,5))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE5(val) ((val) << 5)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE6_GET(value) (GAP_BEXTRACTU((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE6_GETS(value) (GAP_BEXTRACT((value),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE6_SET(value,field) (GAP_BINSERT((value),(field),1,6))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE6(val) ((val) << 6)
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE7_GET(value) (GAP_BEXTRACTU((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE7_GETS(value) (GAP_BEXTRACT((value),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE7_SET(value,field) (GAP_BINSERT((value),(field),1,7))
#define CLUSTER_CTRL_UNIT_DBG_HALT_MASK_CORE7(val) ((val) << 7)
#define CLUSTER_CTRL_UNIT_BOOT_ADDR0_BA_GET(value) (GAP_BEXTRACTU((value),32,0))
#define CLUSTER_CTRL_UNIT_BOOT_ADDR0_BA_GETS(value) (GAP_BEXTRACT((value),32,0))
#define CLUSTER_CTRL_UNIT_BOOT_ADDR0_BA_SET(value,field) (GAP_BINSERT((value),(field),32,0))
#define CLUSTER_CTRL_UNIT_BOOT_ADDR0_BA(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_POL_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_POL_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_POL_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_POL(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_POL_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_POL_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_POL_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_POL(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_REP_POL_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_REP_POL_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_REP_POL_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH0_REP_POL(val) ((val) << 0)
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_REP_POL_GET(value) (GAP_BEXTRACTU((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_REP_POL_GETS(value) (GAP_BEXTRACT((value),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_REP_POL_SET(value,field) (GAP_BINSERT((value),(field),1,0))
#define CLUSTER_CTRL_UNIT_TCDM_ARB_POLICY_CH1_REP_POL(val) ((val) << 0)
#endif
#endif
|
4d117c9bc85dbcfa0d9af6a25c87aadcd147c9d5
|
9ceacf33fd96913cac7ef15492c126d96cae6911
|
/usr.bin/last/last.c
|
68399226ce6b920a777507c1bd71865a9f1ced94
|
[] |
no_license
|
openbsd/src
|
ab97ef834fd2d5a7f6729814665e9782b586c130
|
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
|
refs/heads/master
| 2023-09-02T18:54:56.624627
| 2023-09-02T15:16:12
| 2023-09-02T15:16:12
| 66,966,208
| 3,394
| 1,235
| null | 2023-08-08T02:42:25
| 2016-08-30T18:18:25
|
C
|
UTF-8
|
C
| false
| false
| 14,816
|
c
|
last.c
|
/* $OpenBSD: last.c,v 1.54 2021/10/24 21:24:16 deraadt Exp $ */
/* $NetBSD: last.c,v 1.6 1994/12/24 16:49:02 cgd Exp $ */
/*
* Copyright (c) 1987, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/stat.h>
#include <ctype.h>
#include <err.h>
#include <fcntl.h>
#include <libgen.h>
#include <paths.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>
#include <utmp.h>
#define NO 0 /* false/no */
#define YES 1 /* true/yes */
#define ATOI2(ar) ((ar)[0] - '0') * 10 + ((ar)[1] - '0'); (ar) += 2;
static struct utmp buf[1024]; /* utmp read buffer */
struct arg {
char *name; /* argument */
#define HOST_TYPE -2
#define TTY_TYPE -3
#define USER_TYPE -4
int type; /* type of arg */
struct arg *next; /* linked list pointer */
} *arglist;
struct ttytab {
time_t logout; /* log out time */
char tty[UT_LINESIZE + 1]; /* terminal name */
struct ttytab*next; /* linked list pointer */
} *ttylist;
static time_t currentout; /* current logout value */
static long maxrec = -1; /* records to display */
static char *file = _PATH_WTMP; /* wtmp file */
static int fulltime = 0; /* Display seconds? */
static time_t snaptime = 0; /* report only at this time */
static int calculate = 0;
static int seconds = 0;
void addarg(int, char *);
struct ttytab *addtty(char *);
void hostconv(char *);
void onintr(int);
char *ttyconv(char *);
time_t dateconv(char *);
int want(struct utmp *, int);
void wtmp(void);
void checkargs(void);
void print_entry(const struct utmp *);
void usage(void);
#define NAME_WIDTH 9
#define HOST_WIDTH 24
#define SECSPERDAY (24 * 60 * 60)
int
main(int argc, char *argv[])
{
const char *errstr;
int ch, lastch = '\0', newarg = 1, prevoptind = 1;
while ((ch = getopt(argc, argv, "0123456789cf:h:n:st:d:T")) != -1) {
switch (ch) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
/*
* kludge: last was originally designed to take
* a number after a dash.
*/
if (newarg || !isdigit(lastch))
maxrec = 0;
else if (maxrec > INT_MAX / 10)
usage();
maxrec = (maxrec * 10) + (ch - '0');
break;
case 'c':
calculate = 1;
break;
case 'f':
file = optarg;
break;
case 'h':
hostconv(optarg);
addarg(HOST_TYPE, optarg);
break;
case 'n':
maxrec = strtonum(optarg, 0, LONG_MAX, &errstr);
if (errstr != NULL)
errx(1, "number of lines is %s: %s", errstr,
optarg);
if (maxrec == 0)
exit(0);
break;
case 's':
seconds = 1;
break;
case 't':
addarg(TTY_TYPE, ttyconv(optarg));
break;
case 'd':
snaptime = dateconv(optarg);
break;
case 'T':
fulltime = 1;
break;
default:
usage();
}
lastch = ch;
newarg = optind != prevoptind;
prevoptind = optind;
}
if (maxrec == 0)
exit(0);
if (unveil(file, "r") == -1)
err(1, "unveil %s", file);
if (pledge("stdio rpath", NULL) == -1)
err(1, "pledge");
if (argc) {
setvbuf(stdout, NULL, _IOLBF, 0);
for (argv += optind; *argv; ++argv) {
#define COMPATIBILITY
#ifdef COMPATIBILITY
/* code to allow "last p5" to work */
addarg(TTY_TYPE, ttyconv(*argv));
#endif
addarg(USER_TYPE, *argv);
}
}
checkargs();
wtmp();
exit(0);
}
/*
* if snaptime is set, print warning if usernames, or -t or -h
* flags are also provided
*/
void
checkargs(void)
{
int ttyflag = 0;
struct arg *step;
if (!snaptime || !arglist)
return;
for (step = arglist; step; step = step->next)
switch (step->type) {
case HOST_TYPE:
(void)fprintf(stderr,
"Warning: Ignoring hostname flag\n");
break;
case TTY_TYPE:
if (!ttyflag) { /* don't print this twice */
(void)fprintf(stderr,
"Warning: Ignoring tty flag\n");
ttyflag = 1;
}
break;
case USER_TYPE:
(void)fprintf(stderr,
"Warning: Ignoring username[s]\n");
break;
default:
break;
/* PRINT NOTHING */
}
}
void
print_entry(const struct utmp *bp)
{
printf("%-*.*s %-*.*s %-*.*s ",
NAME_WIDTH, UT_NAMESIZE, bp->ut_name,
UT_LINESIZE, UT_LINESIZE, bp->ut_line,
HOST_WIDTH, UT_HOSTSIZE, bp->ut_host);
if (seconds)
printf("%lld", (long long)bp->ut_time);
else {
struct tm *tm;
tm = localtime(&bp->ut_time);
if (tm == NULL) {
/* bogus entry? format as epoch time... */
printf("%lld", (long long)bp->ut_time);
} else {
char tim[40];
strftime(tim, sizeof tim,
fulltime ? "%a %b %d %H:%M:%S" : "%a %b %d %H:%M",
tm);
printf("%s", tim);
}
}
}
/*
* read through the wtmp file
*/
void
wtmp(void)
{
time_t delta, total = 0;
int timesize, wfd, snapfound = 0;
char *ct, *crmsg = "invalid";
struct utmp *bp;
struct stat stb;
ssize_t bytes;
off_t bl;
struct ttytab *T;
if ((wfd = open(file, O_RDONLY)) == -1 || fstat(wfd, &stb) == -1)
err(1, "%s", file);
bl = (stb.st_size + sizeof(buf) - 1) / sizeof(buf);
if (fulltime)
timesize = 8; /* HH:MM:SS */
else
timesize = 5; /* HH:MM */
(void)time(&buf[0].ut_time);
(void)signal(SIGINT, onintr);
(void)signal(SIGQUIT, onintr);
while (--bl >= 0) {
if (lseek(wfd, bl * sizeof(buf), SEEK_SET) == -1 ||
(bytes = read(wfd, buf, sizeof(buf))) == -1)
err(1, "%s", file);
for (bp = &buf[bytes / sizeof(buf[0]) - 1]; bp >= buf; --bp) {
/*
* if the terminal line is '~', the machine stopped.
* see utmp(5) for more info.
*/
if (bp->ut_line[0] == '~' && !bp->ut_line[1]) {
/* everybody just logged out */
for (T = ttylist; T; T = T->next)
T->logout = -bp->ut_time;
currentout = -bp->ut_time;
crmsg = strncmp(bp->ut_name, "shutdown",
UT_NAMESIZE) ? "crash" : "shutdown";
/*
* if we're in snapshot mode, we want to
* exit if this shutdown/reboot appears
* while we we are tracking the active
* range
*/
if (snaptime && snapfound) {
close(wfd);
return;
}
/*
* don't print shutdown/reboot entries
* unless flagged for
*/
if (want(bp, NO)) {
print_entry(bp);
printf("\n");
if (maxrec != -1 && !--maxrec) {
close(wfd);
return;
}
}
continue;
}
/*
* if the line is '{' or '|', date got set; see
* utmp(5) for more info.
*/
if ((bp->ut_line[0] == '{' || bp->ut_line[0] == '|') &&
!bp->ut_line[1]) {
if (want(bp, NO)) {
print_entry(bp);
printf("\n");
if (maxrec && !--maxrec) {
close(wfd);
return;
}
}
continue;
}
/* find associated tty */
for (T = ttylist;; T = T->next) {
if (!T) {
/* add new one */
T = addtty(bp->ut_line);
break;
}
if (!strncmp(T->tty, bp->ut_line, UT_LINESIZE))
break;
}
/*
* print record if not in snapshot mode and wanted
* or in snapshot mode and in snapshot range
*/
if (bp->ut_name[0] &&
((want(bp, YES)) || (bp->ut_time < snaptime &&
(T->logout > snaptime || !T->logout ||
T->logout < 0)))) {
snapfound = 1;
print_entry(bp);
printf(" ");
if (!T->logout)
puts(" still logged in");
else {
if (T->logout < 0) {
T->logout = -T->logout;
printf("- %s", crmsg);
} else {
if (seconds)
printf("- %lld",
(long long)T->logout);
else
printf("- %*.*s",
timesize, timesize,
ctime(&T->logout)+11);
}
delta = T->logout - bp->ut_time;
if (seconds)
printf(" (%lld)\n",
(long long)delta);
else {
if (delta < SECSPERDAY)
printf(" (%*.*s)\n",
timesize, timesize,
asctime(gmtime(&delta))+11);
else
printf(" (%lld+%*.*s)\n",
(long long)delta / SECSPERDAY,
timesize, timesize,
asctime(gmtime(&delta))+11);
}
if (calculate)
total += delta;
}
if (maxrec != -1 && !--maxrec) {
close(wfd);
return;
}
}
T->logout = bp->ut_time;
}
}
close(wfd);
if (calculate) {
if ((total / SECSPERDAY) > 0) {
int days = (total / SECSPERDAY);
total -= (days * SECSPERDAY);
printf("\nTotal time: %d days, %*.*s\n",
days, timesize, timesize,
asctime(gmtime(&total))+11);
} else
printf("\nTotal time: %*.*s\n",
timesize, timesize,
asctime(gmtime(&total))+11);
}
ct = ctime(&buf[0].ut_time);
printf("\n%s begins %10.10s %*.*s %4.4s\n", basename(file), ct,
timesize, timesize, ct + 11, ct + 20);
}
/*
* see if want this entry
*/
int
want(struct utmp *bp, int check)
{
struct arg *step;
if (check) {
/*
* some entries, such as ftp and uucp, will
* include process name plus id; exclude entries
* that start with 'console' and 'tty' from
* having the process id stripped.
*/
if ((strncmp(bp->ut_line, "console", strlen("console")) != 0) &&
(strncmp(bp->ut_line, "tty", strlen("tty")) != 0)) {
char *s;
for (s = bp->ut_line;
*s != '\0' && !isdigit((unsigned char)*s); s++)
;
*s = '\0';
}
}
if (snaptime) /* if snaptime is set, return NO */
return (NO);
if (!arglist)
return (YES);
for (step = arglist; step; step = step->next)
switch (step->type) {
case HOST_TYPE:
if (!strncasecmp(step->name, bp->ut_host, UT_HOSTSIZE))
return (YES);
break;
case TTY_TYPE:
if (!strncmp(step->name, bp->ut_line, UT_LINESIZE))
return (YES);
break;
case USER_TYPE:
if (!strncmp(step->name, bp->ut_name, UT_NAMESIZE))
return (YES);
break;
}
return (NO);
}
/*
* add an entry to a linked list of arguments
*/
void
addarg(int type, char *arg)
{
struct arg *cur;
if (!(cur = malloc((u_int)sizeof(struct arg))))
err(1, "malloc failure");
cur->next = arglist;
cur->type = type;
cur->name = arg;
arglist = cur;
}
/*
* add an entry to a linked list of ttys
*/
struct ttytab *
addtty(char *ttyname)
{
struct ttytab *cur;
if (!(cur = malloc((u_int)sizeof(struct ttytab))))
err(1, "malloc failure");
cur->next = ttylist;
cur->logout = currentout;
memmove(cur->tty, ttyname, UT_LINESIZE);
return (ttylist = cur);
}
/*
* convert the hostname to search pattern; if the supplied host name
* has a domain attached that is the same as the current domain, rip
* off the domain suffix since that's what login(1) does.
*/
void
hostconv(char *arg)
{
static char *hostdot, name[HOST_NAME_MAX+1];
static int first = 1;
char *argdot;
if (!(argdot = strchr(arg, '.')))
return;
if (first) {
first = 0;
if (gethostname(name, sizeof(name)))
err(1, "gethostname");
hostdot = strchr(name, '.');
}
if (hostdot && !strcasecmp(hostdot, argdot))
*argdot = '\0';
}
/*
* convert tty to correct name.
*/
char *
ttyconv(char *arg)
{
size_t len = 8;
char *mval;
/*
* kludge -- we assume that all tty's end with
* a two character suffix.
*/
if (strlen(arg) == 2) {
/* either 6 for "ttyxx" or 8 for "console" */
if (!(mval = malloc(len)))
err(1, "malloc failure");
if (!strcmp(arg, "co"))
(void)strlcpy(mval, "console", len);
else
snprintf(mval, len, "tty%s", arg);
return (mval);
}
if (!strncmp(arg, _PATH_DEV, sizeof(_PATH_DEV) - 1))
return (arg + 5);
return (arg);
}
/*
* Convert the snapshot time in command line given in the format
* [[[CC]YY]MMDD]hhmm[.SS]] to a time_t.
* Derived from atime_arg1() in usr.bin/touch/touch.c
*/
time_t
dateconv(char *arg)
{
time_t timet;
struct tm *t;
int yearset;
char *p;
/* Start with the current time. */
if (time(&timet) == -1)
err(1, "time");
if ((t = localtime(&timet)) == NULL)
err(1, "localtime");
/* [[[CC]YY]MMDD]hhmm[.SS] */
if ((p = strchr(arg, '.')) == NULL)
t->tm_sec = 0; /* Seconds defaults to 0. */
else {
if (strlen(p + 1) != 2)
goto terr;
*p++ = '\0';
t->tm_sec = ATOI2(p);
}
yearset = 0;
switch (strlen(arg)) {
case 12: /* CCYYMMDDhhmm */
t->tm_year = ATOI2(arg);
t->tm_year *= 100;
yearset = 1;
/* FALLTHROUGH */
case 10: /* YYMMDDhhmm */
if (yearset) {
yearset = ATOI2(arg);
t->tm_year += yearset;
} else {
yearset = ATOI2(arg);
if (yearset < 69)
t->tm_year = yearset + 2000;
else
t->tm_year = yearset + 1900;
}
t->tm_year -= 1900; /* Convert to UNIX time. */
/* FALLTHROUGH */
case 8: /* MMDDhhmm */
t->tm_mon = ATOI2(arg);
--t->tm_mon; /* Convert from 01-12 to 00-11 */
t->tm_mday = ATOI2(arg);
t->tm_hour = ATOI2(arg);
t->tm_min = ATOI2(arg);
break;
case 4: /* hhmm */
t->tm_hour = ATOI2(arg);
t->tm_min = ATOI2(arg);
break;
default:
goto terr;
}
t->tm_isdst = -1; /* Figure out DST. */
timet = mktime(t);
if (timet == -1)
terr: errx(1, "out of range or illegal time specification: "
"[[[CC]YY]MMDD]hhmm[.SS]");
return (timet);
}
/*
* on interrupt, we inform the user how far we've gotten
*/
void
onintr(int signo)
{
char str[1024], *ct, ctbuf[26];
ct = ctime_r(&buf[0].ut_time, ctbuf);
snprintf(str, sizeof str, "\ninterrupted %10.10s %8.8s \n",
ct, ct + 11);
write(STDOUT_FILENO, str, strlen(str));
if (signo == SIGINT)
_exit(1);
}
void
usage(void)
{
extern char *__progname;
fprintf(stderr,
"usage: %s [-csT] [-d date] [-f file] [-h host]"
" [-n number] [-t tty] [user ...]\n", __progname);
exit(1);
}
|
e93dc90452650def1831560609cf991b95bb6770
|
f342990997706a962df8a42867fa1b46da2d2a0d
|
/Pods/Headers/Private/ComponentKit/CKComponentPreparationQueueListenerAnnouncer.h
|
8870125ae9c3d4b84e012f4e89d46cd383066703
|
[
"MIT"
] |
permissive
|
MarcoSero/HackerNews
|
11cd793a475fc6e875705035046f20dcce16b13a
|
92822de869c7eaaed751be98be9d0059391e5017
|
refs/heads/master
| 2021-01-21T01:59:36.492767
| 2016-03-05T10:51:02
| 2016-03-05T10:51:02
| 39,442,230
| 128
| 18
| null | 2016-03-05T10:51:05
| 2015-07-21T11:46:27
|
HTML
|
UTF-8
|
C
| false
| false
| 100
|
h
|
CKComponentPreparationQueueListenerAnnouncer.h
|
../../../ComponentKit/ComponentKit/DataSources/Common/CKComponentPreparationQueueListenerAnnouncer.h
|
2b9d2bd0115062fd9792b10b7e7c57cd1b333eb2
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/drivers/hid/hid-wiimote.h
|
c81dbeb086c556b097dbfb3030bdf2dc62b382f3
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 5,524
|
h
|
hid-wiimote.h
|
#ifndef __HID_WIIMOTE_H
#define __HID_WIIMOTE_H
/*
* HID driver for Nintendo Wiimote devices
* Copyright (c) 2011 David Herrmann
*/
/*
* 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/completion.h>
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/input.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/power_supply.h>
#include <linux/spinlock.h>
#define WIIMOTE_NAME "Nintendo Wii Remote"
#define WIIMOTE_BUFSIZE 32
#define WIIPROTO_FLAG_LED1 0x01
#define WIIPROTO_FLAG_LED2 0x02
#define WIIPROTO_FLAG_LED3 0x04
#define WIIPROTO_FLAG_LED4 0x08
#define WIIPROTO_FLAG_RUMBLE 0x10
#define WIIPROTO_FLAG_ACCEL 0x20
#define WIIPROTO_FLAG_IR_BASIC 0x40
#define WIIPROTO_FLAG_IR_EXT 0x80
#define WIIPROTO_FLAG_IR_FULL 0xc0 /* IR_BASIC | IR_EXT */
#define WIIPROTO_FLAGS_LEDS (WIIPROTO_FLAG_LED1 | WIIPROTO_FLAG_LED2 | \
WIIPROTO_FLAG_LED3 | WIIPROTO_FLAG_LED4)
#define WIIPROTO_FLAGS_IR (WIIPROTO_FLAG_IR_BASIC | WIIPROTO_FLAG_IR_EXT | \
WIIPROTO_FLAG_IR_FULL)
/* return flag for led \num */
#define WIIPROTO_FLAG_LED(num) (WIIPROTO_FLAG_LED1 << (num - 1))
struct wiimote_buf {
__u8 data[HID_MAX_BUFFER_SIZE];
size_t size;
};
struct wiimote_state {
spinlock_t lock;
__u8 flags;
__u8 accel_split[2];
__u8 drm;
/* synchronous cmd requests */
struct mutex sync;
struct completion ready;
int cmd;
__u32 opt;
/* results of synchronous requests */
__u8 cmd_battery;
__u8 cmd_err;
__u8 *cmd_read_buf;
__u8 cmd_read_size;
};
struct wiimote_data {
struct hid_device *hdev;
struct input_dev *input;
struct led_classdev *leds[4];
struct input_dev *accel;
struct input_dev *ir;
struct power_supply battery;
struct wiimote_ext *ext;
struct wiimote_debug *debug;
spinlock_t qlock;
__u8 head;
__u8 tail;
struct wiimote_buf outq[WIIMOTE_BUFSIZE];
struct work_struct worker;
struct wiimote_state state;
};
enum wiiproto_reqs {
WIIPROTO_REQ_NULL = 0x0,
WIIPROTO_REQ_RUMBLE = 0x10,
WIIPROTO_REQ_LED = 0x11,
WIIPROTO_REQ_DRM = 0x12,
WIIPROTO_REQ_IR1 = 0x13,
WIIPROTO_REQ_SREQ = 0x15,
WIIPROTO_REQ_WMEM = 0x16,
WIIPROTO_REQ_RMEM = 0x17,
WIIPROTO_REQ_IR2 = 0x1a,
WIIPROTO_REQ_STATUS = 0x20,
WIIPROTO_REQ_DATA = 0x21,
WIIPROTO_REQ_RETURN = 0x22,
WIIPROTO_REQ_DRM_K = 0x30,
WIIPROTO_REQ_DRM_KA = 0x31,
WIIPROTO_REQ_DRM_KE = 0x32,
WIIPROTO_REQ_DRM_KAI = 0x33,
WIIPROTO_REQ_DRM_KEE = 0x34,
WIIPROTO_REQ_DRM_KAE = 0x35,
WIIPROTO_REQ_DRM_KIE = 0x36,
WIIPROTO_REQ_DRM_KAIE = 0x37,
WIIPROTO_REQ_DRM_E = 0x3d,
WIIPROTO_REQ_DRM_SKAI1 = 0x3e,
WIIPROTO_REQ_DRM_SKAI2 = 0x3f,
WIIPROTO_REQ_MAX
};
#define dev_to_wii(pdev) hid_get_drvdata(container_of(pdev, struct hid_device, \
dev))
extern void wiiproto_req_drm(struct wiimote_data *wdata, __u8 drm);
extern int wiimote_cmd_write(struct wiimote_data *wdata, __u32 offset,
const __u8 *wmem, __u8 size);
extern ssize_t wiimote_cmd_read(struct wiimote_data *wdata, __u32 offset,
__u8 *rmem, __u8 size);
#define wiiproto_req_rreg(wdata, os, sz) \
wiiproto_req_rmem((wdata), false, (os), (sz))
#define wiiproto_req_reeprom(wdata, os, sz) \
wiiproto_req_rmem((wdata), true, (os), (sz))
extern void wiiproto_req_rmem(struct wiimote_data *wdata, bool eeprom,
__u32 offset, __u16 size);
#ifdef CONFIG_HID_WIIMOTE_EXT
extern int wiiext_init(struct wiimote_data *wdata);
extern void wiiext_deinit(struct wiimote_data *wdata);
extern void wiiext_event(struct wiimote_data *wdata, bool plugged);
extern bool wiiext_active(struct wiimote_data *wdata);
extern void wiiext_handle(struct wiimote_data *wdata, const __u8 *payload);
#else
static inline int wiiext_init(void *u) { return 0; }
static inline void wiiext_deinit(void *u) { }
static inline void wiiext_event(void *u, bool p) { }
static inline bool wiiext_active(void *u) { return false; }
static inline void wiiext_handle(void *u, const __u8 *p) { }
#endif
#ifdef CONFIG_DEBUG_FS
extern int wiidebug_init(struct wiimote_data *wdata);
extern void wiidebug_deinit(struct wiimote_data *wdata);
#else
static inline int wiidebug_init(void *u) { return 0; }
static inline void wiidebug_deinit(void *u) { }
#endif
/* requires the state.lock spinlock to be held */
static inline bool wiimote_cmd_pending(struct wiimote_data *wdata, int cmd,
__u32 opt)
{
return wdata->state.cmd == cmd && wdata->state.opt == opt;
}
/* requires the state.lock spinlock to be held */
static inline void wiimote_cmd_complete(struct wiimote_data *wdata)
{
wdata->state.cmd = WIIPROTO_REQ_NULL;
complete(&wdata->state.ready);
}
static inline int wiimote_cmd_acquire(struct wiimote_data *wdata)
{
return mutex_lock_interruptible(&wdata->state.sync) ? -ERESTARTSYS : 0;
}
/* requires the state.lock spinlock to be held */
static inline void wiimote_cmd_set(struct wiimote_data *wdata, int cmd,
__u32 opt)
{
INIT_COMPLETION(wdata->state.ready);
wdata->state.cmd = cmd;
wdata->state.opt = opt;
}
static inline void wiimote_cmd_release(struct wiimote_data *wdata)
{
mutex_unlock(&wdata->state.sync);
}
static inline int wiimote_cmd_wait(struct wiimote_data *wdata)
{
int ret;
ret = wait_for_completion_interruptible_timeout(&wdata->state.ready, HZ);
if (ret < 0)
return -ERESTARTSYS;
else if (ret == 0)
return -EIO;
else
return 0;
}
#endif
|
2e8a9e0551497409ac94b3f88b8ae67d510fb6ca
|
89db60818afeb3dc7c3b7abe9ceae155f074f7f2
|
/src/cmd/ip/snoopy/hdlc.c
|
e7bf37390c62f0e4f83fb75baed197a0640ecf79
|
[
"bzip2-1.0.6",
"LPL-1.02",
"MIT"
] |
permissive
|
9fans/plan9port
|
63c3d01928c6f8a8617d3ea6ecc05bac72391132
|
65c090346a38a8c30cb242d345aa71060116340c
|
refs/heads/master
| 2023-08-25T17:14:26.233105
| 2023-08-23T13:21:37
| 2023-08-23T18:47:08
| 26,095,474
| 1,645
| 468
|
NOASSERTION
| 2023-09-05T16:55:41
| 2014-11-02T22:40:13
|
C
|
UTF-8
|
C
| false
| false
| 4,283
|
c
|
hdlc.c
|
#include <u.h>
#include <libc.h>
#include <ip.h>
#include "dat.h"
#include "protos.h"
enum {
HDLC_frame= 0x7e,
HDLC_esc= 0x7d,
/* PPP frame fields */
PPP_addr= 0xff,
PPP_ctl= 0x3,
PPP_initfcs= 0xffff,
PPP_goodfcs= 0xf0b8
};
/*
* Calculate FCS - rfc 1331
*/
ushort fcstab[256] =
{
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
static uchar inbuf[16*1024];
static int inlen;
static Mux p_mux[] =
{
{"ppp", (PPP_addr<<8)|PPP_ctl, } ,
{0}
};
enum
{
Ot = 1
};
static void
p_compile(Filter *f)
{
Mux *m;
for(m = p_mux; m->name != nil; m++)
if(strcmp(f->s, m->name) == 0){
f->pr = m->pr;
f->ulv = m->val;
f->subop = Ot;
return;
}
sysfatal("unknown ethernet field or protocol: %s", f->s);
}
static int
p_filter(Filter *f, Msg *m)
{
ulong t;
if(m->pe-m->ps < 2)
return 0;
switch(f->subop){
case Ot:
t = (m->ps[0]<<8)|m->ps[1];
if(t != f->ulv)
return 0;
break;
}
return 1;
}
static int
p_seprint(Msg *m)
{
ulong t;
if(m->pe-m->ps < 2)
return -1;
t = (m->ps[0]<<8)|m->ps[1];
m->ps += 2;
demux(p_mux, t, t, m, &dump);
return 0;
}
static int
p_framer(int fd, uchar *pkt, int pktlen)
{
ushort fcs;
uchar *from, *efrom, *to, *eto;
int n;
ulong c;
eto = pkt+pktlen;
for(;;){
efrom = memchr(inbuf, HDLC_frame, inlen);
if(efrom == nil){
if(inlen >= sizeof(inbuf))
inlen = 0;
n = read(fd, inbuf+inlen, sizeof(inbuf)-inlen);
if(n <= 0)
break;
inlen += n;
continue;
}
/* checksum and unescape the frame */
fcs = PPP_initfcs;
to = pkt;
for(from = inbuf; from < efrom;){
c = *from++;
if(c == HDLC_esc)
c = (*from++) ^ 0x20;
if(to < eto)
*to++ = c;
fcs = (fcs >> 8) ^ fcstab[(fcs ^ c) & 0xff];
}
/* move down anything that's left */
inlen -= efrom+1-inbuf;
memmove(inbuf, efrom+1, inlen);
/* accept if this is a good packet */
if(fcs != PPP_goodfcs)
print("bad frame %ld %2.2ux %2.2ux!\n", to-pkt, pkt[0], pkt[1]);
else
return to-pkt;
}
return -1;
}
Proto hdlc =
{
"hdlc",
p_compile,
p_filter,
p_seprint,
p_mux,
"%#.4lux",
nil,
p_framer
};
|
768e76d085cc132e9301a8e2222ef5078faeebdc
|
e1cddfd754d952134e72dfd03522c5ea4fb6008e
|
/src/vnet/dpo/pw_cw.h
|
96f8c72c9d0ab64d5af81305abaa6a29f12719c7
|
[
"Apache-2.0"
] |
permissive
|
FDio/vpp
|
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
|
f234b0d4626d7e686422cc9dfd25958584f4931e
|
refs/heads/master
| 2023-08-31T16:09:04.068646
| 2022-03-14T09:49:15
| 2023-08-31T09:50:00
| 96,556,718
| 1,048
| 630
|
Apache-2.0
| 2023-06-21T05:39:17
| 2017-07-07T16:29:40
|
C
|
UTF-8
|
C
| false
| false
| 2,100
|
h
|
pw_cw.h
|
/*
* Copyright (c) 2019 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __PW_CW_DPO_H__
#define __PW_CW_DPO_H__
#include <vnet/vnet.h>
#include <vnet/mpls/packet.h>
#include <vnet/dpo/dpo.h>
/**
* A Psuedo Wire Control Word is 4 bytes
*/
typedef u32 pw_cw_t;
/**
* A representation of a Psuedo Wire Control Word pop DPO
*/
typedef struct pw_cw_dpo_t
{
/**
* Next DPO in the graph
*/
dpo_id_t pwcw_parent;
/**
* Number of locks/users of the label
*/
u16 pwcw_locks;
} pw_cw_dpo_t;
/**
* @brief Assert that the MPLS label object is less than a cache line in size.
* Should this get any bigger then we will need to reconsider how many labels
* can be pushed in one object.
*/
STATIC_ASSERT_SIZEOF(pw_cw_dpo_t, 2 * sizeof(u64));
/* #define STATIC_ASSERT_ALIGNOF(d, s) \ */
/* STATIC_ASSERT (alignof (d) == sizeof(s), "Align of " #d " must be " # s " bytes") */
/* STATIC_ASSERT_AIGNOF(pw_cw_dpo_t, u64); */
/**
* @brief Create an PW CW pop
*
* @param parent The parent of the created MPLS label object
* @param dpo The PW CW DPO created
*/
extern void pw_cw_dpo_create(const dpo_id_t *paremt,
dpo_id_t *dpo);
extern u8* format_pw_cw_dpo(u8 *s, va_list *args);
/*
* Encapsulation violation for fast data-path access
*/
extern pw_cw_dpo_t *pw_cw_dpo_pool;
static inline pw_cw_dpo_t *
pw_cw_dpo_get (index_t index)
{
return (pool_elt_at_index(pw_cw_dpo_pool, index));
}
extern void pw_cw_dpo_module_init(void);
#endif
|
35f172c9ab9145f9193ed69d35af0490466139f4
|
e79cb86744b9cc5d46912f2f9acdb5ffd434f745
|
/src/odb/src/lef/clef/lefiEncryptExt.c
|
65fbfec39ba66dd9bfc7ce55c1cf069c345e4040
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MPL-2.0"
] |
permissive
|
The-OpenROAD-Project/OpenROAD
|
555cbb00ec250bb09b9e4f9a7d1454e7ac7a01ab
|
1f6ccc9066e7df4509ed391d87b01eadb4b3b197
|
refs/heads/master
| 2023-08-31T05:35:25.363354
| 2023-08-31T05:04:27
| 2023-08-31T05:04:27
| 218,110,222
| 979
| 461
|
BSD-3-Clause
| 2023-09-14T21:51:36
| 2019-10-28T17:48:14
|
Verilog
|
UTF-8
|
C
| false
| false
| 677
|
c
|
lefiEncryptExt.c
|
/*
* This file is part of the Cadence LEF/DEF Open Source
* Distribution, Product Version 5.7, and is subject to the Cadence LEF/DEF
* Open Source License Agreement. Your continued use of this file
* constitutes your acceptance of the terms of the LEF/DEF Open Source
* License and an agreement to abide by its terms. If you don't agree
* with this, you must remove this and any other files which are part of the
* distribution and destroy any copies made.
*
* For updates, support, or to become part of the LEF/DEF Community, check
* www.openeda.org for details.
*/
#include <stdlib.h>
/*
* Global variables
*/
int lefrReadEncrypted = 0;
|
2fbf7ce22938e5c7d97301710b67fd830b831f77
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/third_party/libxslt/src/libxslt/imports.c
|
bf2196e9936ce5e870d68c685f967e8a7dd9ae78
|
[
"LicenseRef-scancode-x11-xconsortium-veillard",
"X11",
"MIT",
"BSD-3-Clause",
"GPL-1.0-or-later",
"LGPL-2.0-or-later",
"Apache-2.0"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C
| false
| false
| 10,211
|
c
|
imports.c
|
/*
* imports.c: Implementation of the XSLT imports
*
* Reference:
* http://www.w3.org/TR/1999/REC-xslt-19991116
*
* See Copyright for the status of this software.
*
* daniel@veillard.com
*/
#define IN_LIBXSLT
#include "libxslt.h"
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/tree.h>
#include <libxml/hash.h>
#include <libxml/xmlerror.h>
#include <libxml/uri.h>
#include "xslt.h"
#include "xsltInternals.h"
#include "xsltutils.h"
#include "preproc.h"
#include "imports.h"
#include "documents.h"
#include "security.h"
#include "pattern.h"
/************************************************************************
* *
* Module interfaces *
* *
************************************************************************/
/**
* xsltFixImportedCompSteps:
* @master: the "master" stylesheet
* @style: the stylesheet being imported by the master
*
* normalize the comp steps for the stylesheet being imported
* by the master, together with any imports within that.
*
*/
static void xsltFixImportedCompSteps(xsltStylesheetPtr master,
xsltStylesheetPtr style) {
xsltStylesheetPtr res;
xmlHashScan(style->templatesHash, xsltNormalizeCompSteps, master);
master->extrasNr += style->extrasNr;
for (res = style->imports; res != NULL; res = res->next) {
xsltFixImportedCompSteps(master, res);
}
}
static int
xsltCheckCycle(xsltStylesheetPtr style, const xmlChar *URI) {
xsltStylesheetPtr ancestor;
xsltDocumentPtr docptr;
/*
* in order to detect recursion, we check all previously included
* stylesheets.
*/
docptr = style->includes;
while (docptr != NULL) {
if (xmlStrEqual(docptr->doc->URL, URI))
return(-1);
docptr = docptr->includes;
}
/*
* Also check imported stylesheets.
*/
ancestor = style;
while (ancestor != NULL) {
if (xmlStrEqual(ancestor->doc->URL, URI))
return(-1);
ancestor = ancestor->parent;
}
return(0);
}
/**
* xsltParseStylesheetImport:
* @style: the XSLT stylesheet
* @cur: the import element
*
* parse an XSLT stylesheet import element
*
* Returns 0 in case of success -1 in case of failure.
*/
int
xsltParseStylesheetImport(xsltStylesheetPtr style, xmlNodePtr cur) {
int ret = -1;
xmlDocPtr import = NULL;
xmlChar *base = NULL;
xmlChar *uriRef = NULL;
xmlChar *URI = NULL;
xsltStylesheetPtr res;
xsltSecurityPrefsPtr sec;
if ((cur == NULL) || (style == NULL))
return (ret);
uriRef = xmlGetNsProp(cur, (const xmlChar *)"href", NULL);
if (uriRef == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:import : missing href attribute\n");
goto error;
}
base = xmlNodeGetBase(style->doc, cur);
URI = xmlBuildURI(uriRef, base);
if (URI == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:import : invalid URI reference %s\n", uriRef);
goto error;
}
if (xsltCheckCycle(style, URI) < 0) {
xsltTransformError(NULL, style, cur,
"xsl:import : recursion detected on imported URL %s\n", URI);
goto error;
}
/*
* Security framework check
*/
sec = xsltGetDefaultSecurityPrefs();
if (sec != NULL) {
int secres;
secres = xsltCheckRead(sec, NULL, URI);
if (secres <= 0) {
if (secres == 0)
xsltTransformError(NULL, NULL, NULL,
"xsl:import: read rights for %s denied\n",
URI);
goto error;
}
}
import = xsltDocDefaultLoader(URI, style->dict, XSLT_PARSE_OPTIONS,
(void *) style, XSLT_LOAD_STYLESHEET);
if (import == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:import : unable to load %s\n", URI);
goto error;
}
res = xsltParseStylesheetImportedDoc(import, style);
if (res != NULL) {
res->next = style->imports;
style->imports = res;
if (style->parent == NULL) {
xsltFixImportedCompSteps(style, res);
}
ret = 0;
} else {
xmlFreeDoc(import);
}
error:
if (uriRef != NULL)
xmlFree(uriRef);
if (base != NULL)
xmlFree(base);
if (URI != NULL)
xmlFree(URI);
return (ret);
}
/**
* xsltParseStylesheetInclude:
* @style: the XSLT stylesheet
* @cur: the include node
*
* parse an XSLT stylesheet include element
*
* Returns 0 in case of success -1 in case of failure
*/
int
xsltParseStylesheetInclude(xsltStylesheetPtr style, xmlNodePtr cur) {
int ret = -1;
xmlDocPtr oldDoc;
xmlChar *base = NULL;
xmlChar *uriRef = NULL;
xmlChar *URI = NULL;
xsltStylesheetPtr result;
xsltDocumentPtr include;
int oldNopreproc;
if ((cur == NULL) || (style == NULL))
return (ret);
uriRef = xmlGetNsProp(cur, (const xmlChar *)"href", NULL);
if (uriRef == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:include : missing href attribute\n");
goto error;
}
base = xmlNodeGetBase(style->doc, cur);
URI = xmlBuildURI(uriRef, base);
if (URI == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:include : invalid URI reference %s\n", uriRef);
goto error;
}
if (xsltCheckCycle(style, URI) < 0) {
xsltTransformError(NULL, style, cur,
"xsl:include : recursion detected on included URL %s\n", URI);
goto error;
}
include = xsltLoadStyleDocument(style, URI);
if (include == NULL) {
xsltTransformError(NULL, style, cur,
"xsl:include : unable to load %s\n", URI);
goto error;
}
#ifdef XSLT_REFACTORED
if (IS_XSLT_ELEM_FAST(cur) && (cur->psvi != NULL)) {
((xsltStyleItemIncludePtr) cur->psvi)->include = include;
} else {
xsltTransformError(NULL, style, cur,
"Internal error: (xsltParseStylesheetInclude) "
"The xsl:include element was not compiled.\n", URI);
style->errors++;
}
#endif
oldDoc = style->doc;
style->doc = include->doc;
/* chain to stylesheet for recursion checking */
include->includes = style->includes;
style->includes = include;
oldNopreproc = style->nopreproc;
style->nopreproc = include->preproc;
/*
* TODO: This will change some values of the
* including stylesheet with every included module
* (e.g. excluded-result-prefixes)
* We need to strictly seperate such stylesheet-owned values.
*/
result = xsltParseStylesheetProcess(style, include->doc);
style->nopreproc = oldNopreproc;
include->preproc = 1;
style->includes = include->includes;
style->doc = oldDoc;
if (result == NULL) {
ret = -1;
goto error;
}
ret = 0;
error:
if (uriRef != NULL)
xmlFree(uriRef);
if (base != NULL)
xmlFree(base);
if (URI != NULL)
xmlFree(URI);
return (ret);
}
/**
* xsltNextImport:
* @cur: the current XSLT stylesheet
*
* Find the next stylesheet in import precedence.
*
* Returns the next stylesheet or NULL if it was the last one
*/
xsltStylesheetPtr
xsltNextImport(xsltStylesheetPtr cur) {
if (cur == NULL)
return(NULL);
if (cur->imports != NULL)
return(cur->imports);
if (cur->next != NULL)
return(cur->next) ;
do {
cur = cur->parent;
if (cur == NULL) break;
if (cur->next != NULL) return(cur->next);
} while (cur != NULL);
return(cur);
}
/**
* xsltNeedElemSpaceHandling:
* @ctxt: an XSLT transformation context
*
* Checks whether that stylesheet requires white-space stripping
*
* Returns 1 if space should be stripped, 0 if not
*/
int
xsltNeedElemSpaceHandling(xsltTransformContextPtr ctxt) {
xsltStylesheetPtr style;
if (ctxt == NULL)
return(0);
style = ctxt->style;
while (style != NULL) {
if (style->stripSpaces != NULL)
return(1);
style = xsltNextImport(style);
}
return(0);
}
/**
* xsltFindElemSpaceHandling:
* @ctxt: an XSLT transformation context
* @node: an XML node
*
* Find strip-space or preserve-space information for an element
* respect the import precedence or the wildcards
*
* Returns 1 if space should be stripped, 0 if not, and 2 if everything
* should be CDTATA wrapped.
*/
int
xsltFindElemSpaceHandling(xsltTransformContextPtr ctxt, xmlNodePtr node) {
xsltStylesheetPtr style;
const xmlChar *val;
if ((ctxt == NULL) || (node == NULL))
return(0);
style = ctxt->style;
while (style != NULL) {
if (node->ns != NULL) {
val = (const xmlChar *)
xmlHashLookup2(style->stripSpaces, node->name, node->ns->href);
if (val == NULL) {
val = (const xmlChar *)
xmlHashLookup2(style->stripSpaces, BAD_CAST "*",
node->ns->href);
}
} else {
val = (const xmlChar *)
xmlHashLookup2(style->stripSpaces, node->name, NULL);
}
if (val != NULL) {
if (xmlStrEqual(val, (xmlChar *) "strip"))
return(1);
if (xmlStrEqual(val, (xmlChar *) "preserve"))
return(0);
}
if (style->stripAll == 1)
return(1);
if (style->stripAll == -1)
return(0);
style = xsltNextImport(style);
}
return(0);
}
/**
* xsltFindTemplate:
* @ctxt: an XSLT transformation context
* @name: the template name
* @nameURI: the template name URI
*
* Finds the named template, apply import precedence rule.
* REVISIT TODO: We'll change the nameURI fields of
* templates to be in the string dict, so if the
* specified @nameURI is in the same dict, then use pointer
* comparison. Check if this can be done in a sane way.
* Maybe this function is not needed internally at
* transformation-time if we hard-wire the called templates
* to the caller.
*
* Returns the xsltTemplatePtr or NULL if not found
*/
xsltTemplatePtr
xsltFindTemplate(xsltTransformContextPtr ctxt, const xmlChar *name,
const xmlChar *nameURI) {
xsltTemplatePtr cur;
xsltStylesheetPtr style;
if ((ctxt == NULL) || (name == NULL))
return(NULL);
style = ctxt->style;
while (style != NULL) {
if (style->namedTemplates != NULL) {
cur = (xsltTemplatePtr)
xmlHashLookup2(style->namedTemplates, name, nameURI);
if (cur != NULL)
return(cur);
}
style = xsltNextImport(style);
}
return(NULL);
}
|
2f8d4fde0ef45777949487db29623eb568e419c7
|
431a5c28b8dfcc7d6ca6f4f97bf370cd770547a7
|
/src/tmx/Asn_J2735/include/asn_j2735_r63/RegionalExtension.h
|
ac17e75615b6dd3b323920b229b6c3cd1744463f
|
[
"Apache-2.0"
] |
permissive
|
usdot-fhwa-OPS/V2X-Hub
|
134061cfb55d8c83e871f7fd4bbfa5d8d3092eb0
|
aae33e6a16b8a30e1faee31a7ee863d191be06b8
|
refs/heads/develop
| 2023-08-26T10:10:59.989176
| 2023-08-24T14:58:21
| 2023-08-24T14:58:21
| 168,020,929
| 106
| 63
| null | 2023-09-11T20:24:45
| 2019-01-28T19:16:45
|
C
|
UTF-8
|
C
| false
| false
| 1,638
|
h
|
RegionalExtension.h
|
/*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "DSRC"
* found in "J2735_201603_2022-11-21.asn"
* `asn1c -fcompound-names -D ../include/generated/`
*/
#ifndef _RegionalExtension_H_
#define _RegionalExtension_H_
#include <asn_application.h>
/* Including external dependencies */
#include "RegionId.h"
#include <ANY.h>
#include <asn_ioc.h>
#include "BasicSafetyMessage-addGrpCarma.h"
#include <OPEN_TYPE.h>
#include <constr_CHOICE.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum Reg_BasicSafetyMessage__regExtValue_PR {
Reg_BasicSafetyMessage__regExtValue_PR_NOTHING, /* No components present */
Reg_BasicSafetyMessage__regExtValue_PR_BasicSafetyMessage_addGrpCarma
} Reg_BasicSafetyMessage__regExtValue_PR;
/* RegionalExtension */
typedef struct Reg_BasicSafetyMessage {
RegionId_t regionId;
struct Reg_BasicSafetyMessage__regExtValue {
Reg_BasicSafetyMessage__regExtValue_PR present;
union Reg_BasicSafetyMessage__regExtValue_u {
BasicSafetyMessage_addGrpCarma_t BasicSafetyMessage_addGrpCarma;
} choice;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} regExtValue;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} Reg_BasicSafetyMessage_t;
/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_Reg_BasicSafetyMessage;
extern asn_SEQUENCE_specifics_t asn_SPC_Reg_BasicSafetyMessage_specs_1;
extern asn_TYPE_member_t asn_MBR_Reg_BasicSafetyMessage_1[2];
#ifdef __cplusplus
}
#endif
#endif /* _RegionalExtension_H_ */
#include <asn_internal.h>
|
8c8cfe519ebaa3639b87a750d80d1f5c47b713a9
|
a5a99f646e371b45974a6fb6ccc06b0a674818f2
|
/CondFormats/GBRForest/src/headers.h
|
1b1c58639ea69d88086774aa761ffbf621e10d29
|
[
"Apache-2.0"
] |
permissive
|
cms-sw/cmssw
|
4ecd2c1105d59c66d385551230542c6615b9ab58
|
19c178740257eb48367778593da55dcad08b7a4f
|
refs/heads/master
| 2023-08-23T21:57:42.491143
| 2023-08-22T20:22:40
| 2023-08-22T20:22:40
| 10,969,551
| 1,006
| 3,696
|
Apache-2.0
| 2023-09-14T19:14:28
| 2013-06-26T14:09:07
|
C++
|
UTF-8
|
C
| false
| false
| 330
|
h
|
headers.h
|
#include "CondFormats/GBRForest/interface/GBRTree.h"
#include "CondFormats/GBRForest/interface/GBRForest.h"
#include "CondFormats/GBRForest/interface/GBRTree2D.h"
#include "CondFormats/GBRForest/interface/GBRForest2D.h"
#include "CondFormats/GBRForest/interface/GBRTreeD.h"
#include "CondFormats/GBRForest/interface/GBRForestD.h"
|
92f0dad2a00c3736c5ee296d4226ad0d2378ca6a
|
1895962fec46d652d226650b7bb9b024c16d9fa6
|
/resources/extldr/usbgecko.h
|
82911f562000ad456d5ff304f2bd6420d6d93760
|
[] |
no_license
|
Fledge68/WiiFlow_Lite
|
6b91090c1ba375ef79fcae1ddea745e412746717
|
5415c95fefa44dba79e0a6e88f25b4a7a3766bf1
|
refs/heads/master
| 2023-08-23T20:14:40.332005
| 2023-05-26T22:32:58
| 2023-05-26T22:32:58
| 144,065,000
| 405
| 112
| null | 2023-08-04T11:59:08
| 2018-08-08T20:37:43
|
C
|
UTF-8
|
C
| false
| false
| 111
|
h
|
usbgecko.h
|
#ifndef __USBGECKO_H__
#define __USBGECKO_H__
void usbgecko_init();
void gprintf(const char* string);
#endif
|
e0aed03f04bf0d33f3af06885f6484f2e71dd1b0
|
2e28c1eca20462ac36a801377364cf7f28454a07
|
/ext/zlib-ng/test/switchlevels.c
|
a065dbcff006dbf2cad14b2b7ee530f53f9012af
|
[
"Zlib",
"CC-BY-4.0",
"LicenseRef-scancode-public-domain",
"CC-BY-3.0",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
pachterlab/kallisto
|
0fbe2a0058eca81d07cb968d6af6c662b9bea48b
|
ff32921dbeb4f9853984a88c1c7534562e256d7a
|
refs/heads/master
| 2023-09-01T13:00:40.473948
| 2023-07-02T01:41:55
| 2023-07-02T01:41:55
| 26,562,905
| 605
| 207
|
BSD-2-Clause
| 2023-08-27T09:13:53
| 2014-11-13T00:27:48
|
C
|
UTF-8
|
C
| false
| false
| 4,470
|
c
|
switchlevels.c
|
/* Compresses a user-specified number of chunks from stdin into stdout as a single gzip stream.
* Each chunk is compressed with a user-specified level.
*/
#include "zbuild.h"
#ifdef ZLIB_COMPAT
# include "zlib.h"
#else
# include "zlib-ng.h"
#endif
#include <stdio.h>
#if defined(_WIN32) || defined(__CYGWIN__)
# include <fcntl.h>
# include <io.h>
# define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
#else
# define SET_BINARY_MODE(file)
#endif
static int read_all(unsigned char *buf, size_t size) {
size_t total_read = 0;
while (total_read < size) {
size_t n_read = fread(buf + total_read, 1, size - total_read, stdin);
if (ferror(stdin)) {
perror("fread\n");
return 1;
}
if (n_read == 0) {
fprintf(stderr, "Premature EOF\n");
return 1;
}
total_read += n_read;
}
return 0;
}
static int write_all(unsigned char *buf, size_t size) {
size_t total_written = 0;
while (total_written < size) {
size_t n_written = fwrite(buf + total_written, 1, size - total_written, stdout);
if (ferror(stdout)) {
perror("fwrite\n");
return 1;
}
total_written += n_written;
}
return 0;
}
static int compress_chunk(PREFIX3(stream) *strm, int level, int size, int last) {
int ret = 1;
int err = 0;
unsigned long compsize;
unsigned char *buf;
if (size <= 0) {
fprintf(stderr, "compress_chunk() invalid size %d\n", size);
goto done;
}
if (level < 0 || level > 9) {
fprintf(stderr, "compress_chunk() invalid level %d\n", level);
goto done;
}
compsize = PREFIX(deflateBound)(strm, size);
buf = malloc(size + compsize);
if (buf == NULL) {
fprintf(stderr, "Out of memory\n");
goto done;
}
if (read_all(buf, size) != 0) {
goto free_buf;
}
/* Provide only output buffer to deflateParams(). It might need some space to flush the leftovers from the last
* deflate(), but we don't want it to compress anything new. */
strm->next_in = NULL;
strm->avail_in = 0;
strm->next_out = buf + size;
strm->avail_out = compsize;
err = PREFIX(deflateParams)(strm, level, Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
fprintf(stderr, "deflateParams() failed with code %d\n", err);
goto free_buf;
}
/* Provide input buffer to deflate(). */
strm->next_in = buf;
strm->avail_in = size;
err = PREFIX(deflate)(strm, last ? Z_FINISH : Z_SYNC_FLUSH);
if ((!last && err != Z_OK) || (last && err != Z_STREAM_END)) {
fprintf(stderr, "deflate() failed with code %d\n", err);
goto free_buf;
}
if (strm->avail_in != 0) {
fprintf(stderr, "deflate() did not consume %d bytes of input\n", strm->avail_in);
goto free_buf;
}
if (write_all(buf + size, compsize - strm->avail_out) != 0) {
goto free_buf;
}
ret = 0;
free_buf:
free(buf);
done:
return ret;
}
void show_help(void)
{
printf("Usage: switchlevels [-w bits] level1 size1 [level2 size2 ...]\n\n" \
" -w : window bits (8 to 15 for gzip, -8 to -15 for zlib)\n\n");
}
int main(int argc, char **argv) {
int ret = EXIT_FAILURE;
int err = 0;
int size = 0;
int level = Z_DEFAULT_COMPRESSION;
int level_arg = 1;
int window_bits = MAX_WBITS + 16;
PREFIX3(stream) strm;
if ((argc == 1) || (argc == 2 && strcmp(argv[1], "--help") == 0)) {
show_help();
return 0;
}
SET_BINARY_MODE(stdin);
SET_BINARY_MODE(stdout);
memset(&strm, 0, sizeof(strm));
for (int i = 1; i < argc - 1; i++) {
if (strcmp(argv[i], "-w") == 0 && i+1 < argc) {
window_bits = atoi(argv[++i]);
} else {
level_arg = i;
level = atoi(argv[i]);
break;
}
}
err = PREFIX(deflateInit2)(&strm, level, Z_DEFLATED, window_bits, 8, Z_DEFAULT_STRATEGY);
if (err != Z_OK) {
fprintf(stderr, "deflateInit() failed with code %d\n", err);
goto done;
}
for (int i = level_arg; i < argc - 1; i += 2) {
level = atoi(argv[i]);
size = atoi(argv[i + 1]);
if (compress_chunk(&strm, level, size, i + 2 >= argc - 1) != 0) {
goto deflate_end;
}
}
ret = EXIT_SUCCESS;
deflate_end:
PREFIX(deflateEnd)(&strm);
done:
return ret;
}
|
6cee60fc4bf9e4be128ebfa6f042a6e75af2678a
|
0882ed3c9e1078a8f69a1fc720d2c05c9289dd23
|
/src/lib/Iex/Iex.h
|
efbabfd9cc556b6c44ec97cdd6ef1d142bf3e831
|
[
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
AcademySoftwareFoundation/openexr
|
846500ee441cc7b60d717ca4377050c55949ecde
|
1ee0ffec3a499ac8bae1ad7e5eff60571d1d83de
|
refs/heads/main
| 2023-09-01T11:33:55.842765
| 2023-08-31T20:30:32
| 2023-08-31T20:30:32
| 3,533,348
| 782
| 281
|
BSD-3-Clause
| 2023-09-14T20:59:10
| 2012-02-24T06:30:00
|
C
|
UTF-8
|
C
| false
| false
| 697
|
h
|
Iex.h
|
//
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
#ifndef INCLUDED_IEX_H
#define INCLUDED_IEX_H
//--------------------------------
//
// Exception handling
//
//--------------------------------
#include "IexBaseExc.h"
#include "IexMacros.h"
#include "IexMathExc.h"
#include "IexThrowErrnoExc.h"
// Note that we do not include file IexErrnoExc.h here. That file
// defines over 150 classes and significantly slows down compilation.
// If you throw ErrnoExc exceptions using the throwErrnoExc() function,
// you don't need IexErrnoExc.h. You have to include IexErrnoExc.h
// only if you want to catch specific subclasses of ErrnoExc.
#endif
|
f4123efedd81bb8de340032abab19762ee31f922
|
84682a2b98de735840333237c5ae11d202860a7c
|
/plugins/py-sculpt_grab_brush_r16/res/c4d_symbols.h
|
55b16ab3970d557f759df0494de1175ded3e7b62
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
PluginCafe/cinema4d_py_sdk_extended
|
f6cf9cb69aef461bab69071cebb482c0bdbf7a1e
|
b1ea3fce533df34094bc3d0bd6460dfb84306e53
|
refs/heads/master
| 2023-04-15T17:11:29.521837
| 2023-03-29T14:47:41
| 2023-03-29T14:47:41
| 206,030,155
| 112
| 45
|
Apache-2.0
| 2022-11-03T15:14:54
| 2019-09-03T08:41:00
|
Python
|
UTF-8
|
C
| false
| false
| 235
|
h
|
c4d_symbols.h
|
#ifndef C4D_SYMBOLS_H__
#define C4D_SYMBOLS_H__
enum
{
// string table definitions
IDS_PYTHON_BRUSH_GRAB = 10000,
IDS_PYTHON_BRUSH_GRAB_HELP,
// End of symbol definition
_DUMMY_ELEMENT_
};
#endif // C4D_SYMBOLS_H__
|
69744d768dc610baea6e6966dd64afe25786ccb1
|
c6759b857e55991fea3ef0b465dbcee53fa38714
|
/examples/gap8/basic/bsp/ble/ble_nina_b112/ble_main.c
|
351e7d57b1e2bd662524217ab3fc0e3f7a9d48a0
|
[
"Apache-2.0"
] |
permissive
|
GreenWaves-Technologies/gap_sdk
|
1b343bba97b7a5ce62a24162bd72eef5cc67e269
|
3fea306d52ee33f923f2423c5a75d9eb1c07e904
|
refs/heads/master
| 2023-09-01T14:38:34.270427
| 2023-08-10T09:04:44
| 2023-08-10T09:04:44
| 133,324,605
| 145
| 96
|
Apache-2.0
| 2023-08-27T19:03:52
| 2018-05-14T07:50:29
|
C
|
UTF-8
|
C
| false
| false
| 1,850
|
c
|
ble_main.c
|
#include "stdio.h"
/* PMSIS includes. */
#include "pmsis.h"
#include "bsp/bsp.h"
#include "ble_protocol.h"
#define AT_RESP_ARRAY_LENGTH ( 64 )
static struct pi_device ble;
unsigned char action = 0;
static uint8_t rx_buffer[AT_RESP_ARRAY_LENGTH];
void test_ble(void)
{
int32_t errors = 0;
struct pi_nina_b112_conf conf;
pi_ble_nina_b112_conf_init(&ble, &conf);
pi_open_from_conf(&ble, &conf);
errors += pi_ble_open(&ble);
if (errors)
{
printf("Failed to open nina ble %ld\n", errors);
pmsis_exit(-1);
}
printf("BLE UART init done\n");
errors += pi_ble_ioctl(&ble, PI_NINA_B112_CLIENT_CONFIGURE, NULL);
/* Retrieve BLE module name. */
pi_ble_at_cmd(&ble, "+UBTLN?", (void *) rx_buffer, 1);
printf("BLE name: %s\n", rx_buffer);
/* Retrieve BLE HCI configuration. */
pi_ble_at_cmd(&ble, "+UMRS?", (void *) rx_buffer, 1);
printf("BLE UART settings: %s\n", rx_buffer);
// After Reboot of NINA, central connects to NINA and NINA will provide
// unsollicited AT event: +UUBTACLC:<peer handle,0,<remote BT address>)
// (...but sometimes just provides empty event instead !?)
// Just make sure NINA sends something as AT unsolicited response, therefore is ready :
pi_ble_ioctl(&ble, PI_NINA_B112_WAIT_FOR_EVENT, (void *) rx_buffer);
printf("Received Event after reboot: %s\n", rx_buffer);
// Enter Data Mode
pi_ble_ioctl(&ble, PI_NINA_B112_DATA_MODE_ENTER, NULL);
printf("Data Mode Entered!\n");
/* Wait 50 ms. */
pi_time_wait_us(50 * 1000);
while (1)
{
pi_ble_data_get(&ble, &action, 1);
printf("Action: %d\n", action);
}
printf("Exiting BLE test\n");
pmsis_exit(0);
}
int main(void)
{
printf("Start NINA BLE module test\n");
return pmsis_kickoff((void *) test_ble);
}
|
dbf388348cd2deb2b986f030da6c07b86cda366f
|
fb0f9abad373cd635c2635bbdf491ea0f32da5ff
|
/src/mono/mono/mini/memory-access.c
|
ceae7a3decf6300eaede4d1be501af1e04e8e889
|
[
"MIT"
] |
permissive
|
dotnet/runtime
|
f6fd23936752e202f8e4d6d94f3a4f3b0e77f58f
|
47bb554d298e1e34c4e3895d7731e18ad1c47d02
|
refs/heads/main
| 2023-09-03T15:35:46.493337
| 2023-09-03T08:13:23
| 2023-09-03T08:13:23
| 210,716,005
| 13,765
| 5,179
|
MIT
| 2023-09-14T21:58:52
| 2019-09-24T23:36:39
|
C#
|
UTF-8
|
C
| false
| false
| 19,901
|
c
|
memory-access.c
|
/**
* Emit memory access for the front-end.
*
*/
#include <config.h>
#include <mono/utils/mono-compiler.h>
#ifndef DISABLE_JIT
#include <mono/metadata/gc-internals.h>
#include <mono/metadata/abi-details.h>
#include <mono/utils/mono-memory-model.h>
#include "mini.h"
#include "mini-runtime.h"
#include "ir-emit.h"
#include "jit-icalls.h"
#define MAX_INLINE_COPIES 16
#define MAX_INLINE_COPY_SIZE 10000
void
mini_emit_memset (MonoCompile *cfg, int destreg, int offset, int size, int val, int align)
{
int val_reg;
/*FIXME arbitrary hack to avoid unbound code expansion.*/
g_assert (size < MAX_INLINE_COPY_SIZE);
g_assert (val == 0);
g_assert (align > 0);
if ((size <= SIZEOF_REGISTER) && (size <= align)) {
switch (size) {
case 1:
MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI1_MEMBASE_IMM, destreg, offset, val);
return;
case 2:
MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI2_MEMBASE_IMM, destreg, offset, val);
return;
case 4:
MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI4_MEMBASE_IMM, destreg, offset, val);
return;
#if SIZEOF_REGISTER == 8
case 8:
MONO_EMIT_NEW_STORE_MEMBASE_IMM (cfg, OP_STOREI8_MEMBASE_IMM, destreg, offset, val);
return;
#endif
}
}
val_reg = alloc_preg (cfg);
MONO_DISABLE_WARNING(4127) /* conditional expression is constant */
if (SIZEOF_REGISTER == 8)
MONO_EMIT_NEW_I8CONST (cfg, val_reg, val);
else
MONO_EMIT_NEW_ICONST (cfg, val_reg, val);
if (align < TARGET_SIZEOF_VOID_P) {
if (align % 2 == 1)
goto set_1;
if (align % 4 == 2)
goto set_2;
if (TARGET_SIZEOF_VOID_P == 8 && align % 8 == 4)
goto set_4;
}
//Unaligned offsets don't naturaly happen in the runtime, so it's ok to be conservative in how we copy
//We assume that input src and dest are be aligned to `align` so offset just worsen it
int offsets_mask;
offsets_mask = offset & 0x7; //we only care about the misalignment part
if (offsets_mask) {
if (offsets_mask % 2 == 1)
goto set_1;
if (offsets_mask % 4 == 2)
goto set_2;
if (TARGET_SIZEOF_VOID_P == 8 && offsets_mask % 8 == 4)
goto set_4;
}
if (SIZEOF_REGISTER == 8) {
while (size >= 8) {
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, offset, val_reg);
offset += 8;
size -= 8;
}
}
MONO_RESTORE_WARNING
set_4:
while (size >= 4) {
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, val_reg);
offset += 4;
size -= 4;
}
set_2:
while (size >= 2) {
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, val_reg);
offset += 2;
size -= 2;
}
set_1:
while (size >= 1) {
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, val_reg);
offset += 1;
size -= 1;
}
}
void
mini_emit_memcpy (MonoCompile *cfg, int destreg, int doffset, int srcreg, int soffset, int size, int align)
{
int cur_reg;
if (size >= MAX_INLINE_COPY_SIZE) {
MonoInst *iargs [3];
int reg = alloc_ireg (cfg);
EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, reg, destreg);
reg = alloc_ireg (cfg);
EMIT_NEW_UNALU (cfg, iargs [1], OP_MOVE, reg, srcreg);
EMIT_NEW_ICONST (cfg, iargs [2], size);
mono_emit_method_call (cfg, mini_get_memcpy_method (), iargs, NULL);
return;
}
g_assert (align > 0);
MONO_DISABLE_WARNING(4127) /* conditional expression is constant */
if (align < TARGET_SIZEOF_VOID_P) {
if (align == 4)
goto copy_4;
if (align == 2)
goto copy_2;
goto copy_1;
}
//Unaligned offsets don't naturaly happen in the runtime, so it's ok to be conservative in how we copy
//We assume that input src and dest are be aligned to `align` so offset just worsen it
int offsets_mask;
offsets_mask = (doffset | soffset) & 0x7; //we only care about the misalignment part
if (offsets_mask) {
if (offsets_mask % 2 == 1)
goto copy_1;
if (offsets_mask % 4 == 2)
goto copy_2;
if (TARGET_SIZEOF_VOID_P == 8 && offsets_mask % 8 == 4)
goto copy_4;
}
if (SIZEOF_REGISTER == 8) {
while (size >= 8) {
cur_reg = alloc_preg (cfg);
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI8_MEMBASE, cur_reg, srcreg, soffset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, destreg, doffset, cur_reg);
doffset += 8;
soffset += 8;
size -= 8;
}
}
MONO_RESTORE_WARNING
copy_4:
while (size >= 4) {
cur_reg = alloc_preg (cfg);
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, cur_reg, srcreg, soffset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, doffset, cur_reg);
doffset += 4;
soffset += 4;
size -= 4;
}
copy_2:
while (size >= 2) {
cur_reg = alloc_preg (cfg);
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, cur_reg, srcreg, soffset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, doffset, cur_reg);
doffset += 2;
soffset += 2;
size -= 2;
}
copy_1:
while (size >= 1) {
cur_reg = alloc_preg (cfg);
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, cur_reg, srcreg, soffset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, doffset, cur_reg);
doffset += 1;
soffset += 1;
size -= 1;
}
}
static void
mini_emit_memcpy_internal (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoInst *size_ins, int size, int align)
{
/* FIXME: Optimize the case when src/dest is OP_LDADDR */
/* We can't do copies at a smaller granule than the provided alignment */
if (size_ins || (size / align > MAX_INLINE_COPIES) || !(cfg->opt & MONO_OPT_INTRINS)) {
MonoInst *iargs [3];
iargs [0] = dest;
iargs [1] = src;
if (!size_ins)
EMIT_NEW_ICONST (cfg, size_ins, size);
iargs [2] = size_ins;
if (COMPILE_LLVM (cfg)) {
MonoInst *ins;
MONO_INST_NEW (cfg, ins, OP_MEMMOVE);
ins->sreg1 = iargs [0]->dreg;
ins->sreg2 = iargs [1]->dreg;
ins->sreg3 = iargs [2]->dreg;
MONO_ADD_INS (cfg->cbb, ins);
} else {
mono_emit_method_call (cfg, mini_get_memcpy_method (), iargs, NULL);
}
} else {
mini_emit_memcpy (cfg, dest->dreg, 0, src->dreg, 0, size, align);
}
}
static void
mini_emit_memset_internal (MonoCompile *cfg, MonoInst *dest, MonoInst *value_ins, int value, MonoInst *size_ins, int size, int align)
{
/* FIXME: Optimize the case when dest is OP_LDADDR */
/* We can't do copies at a smaller granule than the provided alignment */
if (value_ins || size_ins || value != 0 || (size / align > MAX_INLINE_COPIES) || !(cfg->opt & MONO_OPT_INTRINS)) {
MonoInst *iargs [3];
iargs [0] = dest;
if (!value_ins)
EMIT_NEW_ICONST (cfg, value_ins, value);
iargs [1] = value_ins;
if (!size_ins)
EMIT_NEW_ICONST (cfg, size_ins, size);
iargs [2] = size_ins;
mono_emit_method_call (cfg, mini_get_memset_method (), iargs, NULL);
} else {
mini_emit_memset (cfg, dest->dreg, 0, size, value, align);
}
}
static void
mini_emit_memcpy_const_size (MonoCompile *cfg, MonoInst *dest, MonoInst *src, int size, int align)
{
mini_emit_memcpy_internal (cfg, dest, src, NULL, size, align);
}
static void
mini_emit_memset_const_size (MonoCompile *cfg, MonoInst *dest, int value, int size, int align)
{
mini_emit_memset_internal (cfg, dest, NULL, value, NULL, size, align);
}
static void
create_write_barrier_bitmap (MonoCompile *cfg, MonoClass *klass, unsigned *wb_bitmap, int offset)
{
MonoClassField *field;
gpointer iter = NULL;
while ((field = mono_class_get_fields_internal (klass, &iter))) {
int foffset;
if (field->type->attrs & FIELD_ATTRIBUTE_STATIC)
continue;
foffset = m_class_is_valuetype (klass) ? m_field_get_offset (field) - MONO_ABI_SIZEOF (MonoObject): m_field_get_offset (field);
if (mini_type_is_reference (mono_field_get_type_internal (field))) {
g_assert ((foffset % TARGET_SIZEOF_VOID_P) == 0);
*wb_bitmap |= 1 << ((offset + foffset) / TARGET_SIZEOF_VOID_P);
} else {
MonoClass *field_class = mono_class_from_mono_type_internal (field->type);
if (cfg->gshared)
field_class = mono_class_from_mono_type_internal (mini_get_underlying_type (m_class_get_byval_arg (field_class)));
if (m_class_has_references (field_class))
create_write_barrier_bitmap (cfg, field_class, wb_bitmap, offset + foffset);
}
}
}
static gboolean
mini_emit_wb_aware_memcpy (MonoCompile *cfg, MonoClass *klass, MonoInst *iargs[4], int size, int align)
{
int dest_ptr_reg, tmp_reg, destreg, srcreg, offset;
unsigned need_wb = 0;
if (align == 0)
align = 4;
/*types with references can't have alignment smaller than sizeof(void*) */
if (align < TARGET_SIZEOF_VOID_P)
return FALSE;
if (size > 5 * TARGET_SIZEOF_VOID_P)
return FALSE;
create_write_barrier_bitmap (cfg, klass, &need_wb, 0);
destreg = iargs [0]->dreg;
srcreg = iargs [1]->dreg;
offset = 0;
dest_ptr_reg = alloc_preg (cfg);
tmp_reg = alloc_preg (cfg);
/*tmp = dreg*/
EMIT_NEW_UNALU (cfg, iargs [0], OP_MOVE, dest_ptr_reg, destreg);
if ((need_wb & 0x1) && !mini_debug_options.weak_memory_model)
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
while (size >= TARGET_SIZEOF_VOID_P) {
MonoInst *load_inst;
MONO_INST_NEW (cfg, load_inst, OP_LOAD_MEMBASE);
load_inst->dreg = tmp_reg;
load_inst->inst_basereg = srcreg;
load_inst->inst_offset = offset;
MONO_ADD_INS (cfg->cbb, load_inst);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREP_MEMBASE_REG, dest_ptr_reg, 0, tmp_reg);
if (need_wb & 0x1)
mini_emit_write_barrier (cfg, iargs [0], load_inst);
offset += TARGET_SIZEOF_VOID_P;
size -= TARGET_SIZEOF_VOID_P;
need_wb >>= 1;
/*tmp += sizeof (void*)*/
if (size >= TARGET_SIZEOF_VOID_P) {
NEW_BIALU_IMM (cfg, iargs [0], OP_PADD_IMM, dest_ptr_reg, dest_ptr_reg, TARGET_SIZEOF_VOID_P);
MONO_ADD_INS (cfg->cbb, iargs [0]);
}
}
/* Those cannot be references since size < sizeof (void*) */
while (size >= 4) {
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI4_MEMBASE, tmp_reg, srcreg, offset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI4_MEMBASE_REG, destreg, offset, tmp_reg);
offset += 4;
size -= 4;
}
while (size >= 2) {
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI2_MEMBASE, tmp_reg, srcreg, offset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI2_MEMBASE_REG, destreg, offset, tmp_reg);
offset += 2;
size -= 2;
}
while (size >= 1) {
MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADI1_MEMBASE, tmp_reg, srcreg, offset);
MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI1_MEMBASE_REG, destreg, offset, tmp_reg);
offset += 1;
size -= 1;
}
return TRUE;
}
static void
mini_emit_memory_copy_internal (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, int explicit_align, gboolean native,
gboolean stack_store)
{
MonoInst *iargs [4];
int size;
guint32 align = 0;
MonoInst *size_ins = NULL;
MonoInst *memcpy_ins = NULL;
g_assert (klass);
/*
Fun fact about @native. It's false that @klass will have no ref when @native is true.
This happens in pinvoke2. What goes is that marshal.c uses CEE_MONO_LDOBJNATIVE and pass klass.
The actual stuff being copied will have no refs, but @klass might.
This means we can't assert !(klass->has_references && native).
*/
if (cfg->gshared)
klass = mono_class_from_mono_type_internal (mini_get_underlying_type (m_class_get_byval_arg (klass)));
/*
* This check breaks with spilled vars... need to handle it during verification anyway.
* g_assert (klass && klass == src->klass && klass == dest->klass);
*/
if (mini_is_gsharedvt_klass (klass)) {
g_assert (!native);
size_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_VALUE_SIZE);
memcpy_ins = mini_emit_get_gsharedvt_info_klass (cfg, klass, MONO_RGCTX_INFO_MEMCPY);
}
if (native)
size = mono_class_native_size (klass, &align);
else
size = mono_class_value_size (klass, &align);
if (!align)
align = TARGET_SIZEOF_VOID_P;
if (explicit_align)
align = explicit_align;
if (mini_type_is_reference (m_class_get_byval_arg (klass))) { // Refs *MUST* be naturally aligned
MonoInst *store, *load;
int dreg = alloc_ireg_ref (cfg);
NEW_LOAD_MEMBASE (cfg, load, OP_LOAD_MEMBASE, dreg, src->dreg, 0);
MONO_ADD_INS (cfg->cbb, load);
if (!mini_debug_options.weak_memory_model)
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
NEW_STORE_MEMBASE (cfg, store, OP_STORE_MEMBASE_REG, dest->dreg, 0, dreg);
MONO_ADD_INS (cfg->cbb, store);
mini_emit_write_barrier (cfg, dest, load);
return;
} else if (cfg->gen_write_barriers && (m_class_has_references (klass) || size_ins) &&
!native && !stack_store) { /* if native is true there should be no references in the struct */
/* Avoid barriers when storing to the stack */
if (!((dest->opcode == OP_ADD_IMM && dest->sreg1 == cfg->frame_reg) ||
(dest->opcode == OP_LDADDR))) {
int context_used;
iargs [0] = dest;
iargs [1] = src;
context_used = mini_class_check_context_used (cfg, klass);
/* It's ok to intrinsify under gsharing since shared code types are layout stable. */
if (!size_ins && (cfg->opt & MONO_OPT_INTRINS) && mini_emit_wb_aware_memcpy (cfg, klass, iargs, size, align)) {
} else if (size_ins || align < TARGET_SIZEOF_VOID_P) {
if (context_used) {
iargs [2] = mini_emit_get_rgctx_klass (cfg, context_used, klass, MONO_RGCTX_INFO_KLASS);
} else {
iargs [2] = mini_emit_runtime_constant (cfg, MONO_PATCH_INFO_CLASS, klass);
if (!cfg->compile_aot)
mono_class_compute_gc_descriptor (klass);
}
if (size_ins)
mono_emit_jit_icall (cfg, mono_gsharedvt_value_copy, iargs);
else
mono_emit_jit_icall (cfg, mono_value_copy_internal, iargs);
} else {
/* We don't unroll more than 5 stores to avoid code bloat. */
/*This is harmless and simplify mono_gc_get_range_copy_func */
size += (TARGET_SIZEOF_VOID_P - 1);
size &= ~(TARGET_SIZEOF_VOID_P - 1);
EMIT_NEW_ICONST (cfg, iargs [2], size);
mono_emit_jit_icall (cfg, mono_gc_wbarrier_range_copy, iargs);
}
return;
}
}
if (size_ins) {
iargs [0] = dest;
iargs [1] = src;
iargs [2] = size_ins;
mini_emit_calli (cfg, mono_method_signature_internal (mini_get_memcpy_method ()), iargs, memcpy_ins, NULL, NULL);
} else {
mini_emit_memcpy_const_size (cfg, dest, src, size, align);
}
}
MonoInst*
mini_emit_memory_load (MonoCompile *cfg, MonoType *type, MonoInst *src, int offset, int ins_flag)
{
MonoInst *ins;
/* LLVM can handle unaligned loads and stores, so there's no reason to
* manually decompose an unaligned load here into a memcpy if we're
* using LLVM. */
if ((ins_flag & MONO_INST_UNALIGNED) && !COMPILE_LLVM (cfg)) {
MonoInst *addr, *tmp_var;
int align;
int size = mono_type_size (type, &align);
if (offset) {
MonoInst *add_offset;
NEW_BIALU_IMM (cfg, add_offset, OP_PADD_IMM, alloc_preg (cfg), src->dreg, offset);
MONO_ADD_INS (cfg->cbb, add_offset);
src = add_offset;
}
tmp_var = mono_compile_create_var (cfg, type, OP_LOCAL);
EMIT_NEW_VARLOADA (cfg, addr, tmp_var, tmp_var->inst_vtype);
mini_emit_memcpy_const_size (cfg, addr, src, size, 1);
EMIT_NEW_TEMPLOAD (cfg, ins, tmp_var->inst_c0);
} else {
EMIT_NEW_LOAD_MEMBASE_TYPE (cfg, ins, type, src->dreg, offset);
}
ins->flags |= ins_flag;
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_ACQ);
}
return ins;
}
void
mini_emit_memory_store (MonoCompile *cfg, MonoType *type, MonoInst *dest, MonoInst *value, int ins_flag)
{
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
} else if (!mini_debug_options.weak_memory_model && mini_type_is_reference (type) && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER)
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
if (!(ins_flag & MONO_INST_NONULLCHECK))
MONO_EMIT_NULL_CHECK (cfg, dest->dreg, FALSE);
if ((ins_flag & MONO_INST_UNALIGNED) && !COMPILE_LLVM (cfg)) {
MonoInst *addr, *mov, *tmp_var;
tmp_var = mono_compile_create_var (cfg, type, OP_LOCAL);
EMIT_NEW_TEMPSTORE (cfg, mov, tmp_var->inst_c0, value);
EMIT_NEW_VARLOADA (cfg, addr, tmp_var, tmp_var->inst_vtype);
mini_emit_memory_copy_internal (cfg, dest, addr, mono_class_from_mono_type_internal (type), 1, FALSE, (ins_flag & MONO_INST_STACK_STORE) != 0);
} else {
MonoInst *ins;
/* FIXME: should check item at sp [1] is compatible with the type of the store. */
EMIT_NEW_STORE_MEMBASE_TYPE (cfg, ins, type, dest->dreg, 0, value->dreg);
ins->flags |= ins_flag;
}
if (cfg->gen_write_barriers && cfg->method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER &&
mini_type_is_reference (type) && !MONO_INS_IS_PCONST_NULL (value)) {
/* insert call to write barrier */
mini_emit_write_barrier (cfg, dest, value);
}
}
void
mini_emit_memory_copy_bytes (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoInst *size, int ins_flag)
{
int align = (ins_flag & MONO_INST_UNALIGNED) ? 1 : TARGET_SIZEOF_VOID_P;
/*
* FIXME: It's unclear whether we should be emitting both the acquire
* and release barriers for cpblk. It is technically both a load and
* store operation, so it seems like that's the sensible thing to do.
*
* FIXME: We emit full barriers on both sides of the operation for
* simplicity. We should have a separate atomic memcpy method instead.
*/
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
}
if ((cfg->opt & MONO_OPT_INTRINS) && (size->opcode == OP_ICONST)) {
mini_emit_memcpy_const_size (cfg, dest, src, GTMREG_TO_INT (size->inst_c0), align);
} else {
mini_emit_memcpy_internal (cfg, dest, src, size, 0, align);
}
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
}
}
void
mini_emit_memory_init_bytes (MonoCompile *cfg, MonoInst *dest, MonoInst *value, MonoInst *size, int ins_flag)
{
int align = (ins_flag & MONO_INST_UNALIGNED) ? 1 : TARGET_SIZEOF_VOID_P;
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile stores have release semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_REL);
}
//FIXME unrolled memset only supports zeroing
if ((cfg->opt & MONO_OPT_INTRINS) && (size->opcode == OP_ICONST) && (value->opcode == OP_ICONST) && (value->inst_c0 == 0)) {
mini_emit_memset_const_size (cfg, dest, GTMREG_TO_INT (value->inst_c0), GTMREG_TO_INT (size->inst_c0), align);
} else {
mini_emit_memset_internal (cfg, dest, value, 0, size, 0, align);
}
}
/*
* If @klass is a valuetype, emit code to copy a value with source address in @src and destination address in @dest.
* If @klass is a ref type, copy a pointer instead.
*/
void
mini_emit_memory_copy (MonoCompile *cfg, MonoInst *dest, MonoInst *src, MonoClass *klass, gboolean native, int ins_flag)
{
int explicit_align = 0;
if (ins_flag & MONO_INST_UNALIGNED)
explicit_align = 1;
/*
* FIXME: It's unclear whether we should be emitting both the acquire
* and release barriers for cpblk. It is technically both a load and
* store operation, so it seems like that's the sensible thing to do.
*
* FIXME: We emit full barriers on both sides of the operation for
* simplicity. We should have a separate atomic memcpy method instead.
*/
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
}
mini_emit_memory_copy_internal (cfg, dest, src, klass, explicit_align, native, (ins_flag & MONO_INST_STACK_STORE) != 0);
if (ins_flag & MONO_INST_VOLATILE) {
/* Volatile loads have acquire semantics, see 12.6.7 in Ecma 335 */
mini_emit_memory_barrier (cfg, MONO_MEMORY_BARRIER_SEQ);
}
}
#else /* !DISABLE_JIT */
MONO_EMPTY_SOURCE_FILE (memory_access);
#endif
|
1736e4dd16c8f22241b3f6bb35a2762011b4ef4f
|
1eb4d584daf34393db3a9e7a73fdc5af4a0e38e7
|
/transport-native-kqueue/src/main/c/netty_kqueue_eventarray.c
|
ad7a20d6546aedde2985c98acf18c865dabd118e
|
[
"Apache-2.0",
"CC-PDDC",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only"
] |
permissive
|
YunaiV/netty
|
cd96c948684b8e196af2425fb4bf4bd8671a76c5
|
2c9022aabffc261c103e60c682c041c8cac83045
|
refs/heads/4.1
| 2021-06-23T18:17:32.028915
| 2019-02-09T14:25:32
| 2019-02-09T14:25:32
| 139,227,249
| 153
| 216
|
Apache-2.0
| 2019-06-28T14:27:39
| 2018-06-30T07:04:53
|
Java
|
UTF-8
|
C
| false
| false
| 5,487
|
c
|
netty_kqueue_eventarray.c
|
/*
* Copyright 2016 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include "netty_kqueue_eventarray.h"
#include "netty_unix_errors.h"
#include "netty_unix_jni.h"
#include "netty_unix_util.h"
jfieldID kqueueJniPtrFieldId = NULL;
static void netty_kqueue_eventarray_evSet(JNIEnv* env, jclass clzz, jlong keventAddress, jobject channel, jint ident, jshort filter, jshort flags, jint fflags) {
// Create a global pointer, cast it as a long, and retain it in java to re-use and free later.
jlong jniSelfPtr = (*env)->GetLongField(env, channel, kqueueJniPtrFieldId);
if (jniSelfPtr == 0) {
jniSelfPtr = (jlong) (*env)->NewGlobalRef(env, channel);
(*env)->SetLongField(env, channel, kqueueJniPtrFieldId, jniSelfPtr);
} else if ((flags & EV_DELETE) != 0) {
// If the event is deleted, make sure it no longer has a reference to the jniSelfPtr because it shouldn't be used after this point.
jniSelfPtr = 0;
}
EV_SET((struct kevent*) keventAddress, ident, filter, flags, fflags, 0, (jobject) jniSelfPtr);
}
static jobject netty_kqueue_eventarray_getChannel(JNIEnv* env, jclass clazz, jlong keventAddress) {
struct kevent* event = (struct kevent*) keventAddress;
return event->udata == NULL ? NULL : (jobject) event->udata;
}
static void netty_kqueue_eventarray_deleteGlobalRefs(JNIEnv* env, jclass clazz, jlong channelAddressStart, jlong channelAddressEnd) {
// Iterate over an array of longs, which are really pointers to the jobject NewGlobalRef created above in evSet
// and delete each one. The field has already been set to 0 in java.
jlong* itr = (jlong*) channelAddressStart;
const jlong* end = (jlong*) channelAddressEnd;
for (; itr != end; ++itr) {
(*env)->DeleteGlobalRef(env, (jobject) *itr);
}
}
// JNI Method Registration Table Begin
static const JNINativeMethod fixed_method_table[] = {
{ "deleteGlobalRefs", "(JJ)V", (void *) netty_kqueue_eventarray_deleteGlobalRefs }
// "evSet" has a dynamic signature
// "getChannel" has a dynamic signature
};
static const jint fixed_method_table_size = sizeof(fixed_method_table) / sizeof(fixed_method_table[0]);
static jint dynamicMethodsTableSize() {
return fixed_method_table_size + 2;
}
static JNINativeMethod* createDynamicMethodsTable(const char* packagePrefix) {
JNINativeMethod* dynamicMethods = malloc(sizeof(JNINativeMethod) * dynamicMethodsTableSize());
memcpy(dynamicMethods, fixed_method_table, sizeof(fixed_method_table));
char* dynamicTypeName = netty_unix_util_prepend(packagePrefix, "io/netty/channel/kqueue/AbstractKQueueChannel;ISSI)V");
JNINativeMethod* dynamicMethod = &dynamicMethods[fixed_method_table_size];
dynamicMethod->name = "evSet";
dynamicMethod->signature = netty_unix_util_prepend("(JL", dynamicTypeName);
dynamicMethod->fnPtr = (void *) netty_kqueue_eventarray_evSet;
free(dynamicTypeName);
++dynamicMethod;
dynamicTypeName = netty_unix_util_prepend(packagePrefix, "io/netty/channel/kqueue/AbstractKQueueChannel;");
dynamicMethod->name = "getChannel";
dynamicMethod->signature = netty_unix_util_prepend("(J)L", dynamicTypeName);
dynamicMethod->fnPtr = (void *) netty_kqueue_eventarray_getChannel;
free(dynamicTypeName);
return dynamicMethods;
}
static void freeDynamicMethodsTable(JNINativeMethod* dynamicMethods) {
jint fullMethodTableSize = dynamicMethodsTableSize();
jint i = fixed_method_table_size;
for (; i < fullMethodTableSize; ++i) {
free(dynamicMethods[i].signature);
}
free(dynamicMethods);
}
// JNI Method Registration Table End
jint netty_kqueue_eventarray_JNI_OnLoad(JNIEnv* env, const char* packagePrefix) {
JNINativeMethod* dynamicMethods = createDynamicMethodsTable(packagePrefix);
if (netty_unix_util_register_natives(env,
packagePrefix,
"io/netty/channel/kqueue/KQueueEventArray",
dynamicMethods,
dynamicMethodsTableSize()) != 0) {
freeDynamicMethodsTable(dynamicMethods);
return JNI_ERR;
}
freeDynamicMethodsTable(dynamicMethods);
dynamicMethods = NULL;
char* nettyClassName = netty_unix_util_prepend(packagePrefix, "io/netty/channel/kqueue/AbstractKQueueChannel");
jclass kqueueChannelCls = (*env)->FindClass(env, nettyClassName);
free(nettyClassName);
nettyClassName = NULL;
if (kqueueChannelCls == NULL) {
return JNI_ERR;
}
kqueueJniPtrFieldId = (*env)->GetFieldID(env, kqueueChannelCls, "jniSelfPtr", "J");
if (kqueueJniPtrFieldId == NULL) {
netty_unix_errors_throwRuntimeException(env, "failed to get field ID: AbstractKQueueChannel.jniSelfPtr");
return JNI_ERR;
}
return NETTY_JNI_VERSION;
}
void netty_kqueue_eventarray_JNI_OnUnLoad(JNIEnv* env) {
}
|
6d5b304a91cfd09bf459439ab13d833494bdfbf3
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/u-boot_new/include/i2s.h
|
8dd2cc388ab0455646d866e3bd1c297280229f34
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"GPL-2.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 3,511
|
h
|
i2s.h
|
/*
* Copyright (C) 2012 Samsung Electronics
* R. Chandrasekar <rcsekar@samsung.com>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __I2S_H__
#define __I2S_H__
/*
* DAI hardware audio formats.
*
* Describes the physical PCM data formating and clocking. Add new formats
* to the end.
*/
#define SND_SOC_DAIFMT_I2S 1 /* I2S mode */
#define SND_SOC_DAIFMT_RIGHT_J 2 /* Right Justified mode */
#define SND_SOC_DAIFMT_LEFT_J 3 /* Left Justified mode */
#define SND_SOC_DAIFMT_DSP_A 4 /* L data MSB after FRM LRC */
#define SND_SOC_DAIFMT_DSP_B 5 /* L data MSB during FRM LRC */
#define SND_SOC_DAIFMT_AC97 6 /* AC97 */
#define SND_SOC_DAIFMT_PDM 7 /* Pulse density modulation */
/* left and right justified also known as MSB and LSB respectively */
#define SND_SOC_DAIFMT_MSB SND_SOC_DAIFMT_LEFT_J
#define SND_SOC_DAIFMT_LSB SND_SOC_DAIFMT_RIGHT_J
/*
* DAI hardware signal inversions.
*
* Specifies whether the DAI can also support inverted clocks for the specified
* format.
*/
#define SND_SOC_DAIFMT_NB_NF (1 << 8) /* normal bit clock + frame */
#define SND_SOC_DAIFMT_NB_IF (2 << 8) /* normal BCLK + inv FRM */
#define SND_SOC_DAIFMT_IB_NF (3 << 8) /* invert BCLK + nor FRM */
#define SND_SOC_DAIFMT_IB_IF (4 << 8) /* invert BCLK + FRM */
/*
* DAI hardware clock masters.
*
* This is wrt the codec, the inverse is true for the interface
* i.e. if the codec is clk and FRM master then the interface is
* clk and frame slave.
*/
#define SND_SOC_DAIFMT_CBM_CFM (1 << 12) /* codec clk & FRM master */
#define SND_SOC_DAIFMT_CBS_CFM (2 << 12) /* codec clk slave & FRM master */
#define SND_SOC_DAIFMT_CBM_CFS (3 << 12) /* codec clk master & frame slave */
#define SND_SOC_DAIFMT_CBS_CFS (4 << 12) /* codec clk & FRM slave */
#define SND_SOC_DAIFMT_FORMAT_MASK 0x000f
#define SND_SOC_DAIFMT_CLOCK_MASK 0x00f0
#define SND_SOC_DAIFMT_INV_MASK 0x0f00
#define SND_SOC_DAIFMT_MASTER_MASK 0xf000
/*
* Master Clock Directions
*/
#define SND_SOC_CLOCK_IN 0
#define SND_SOC_CLOCK_OUT 1
/* I2S Tx Control */
#define I2S_TX_ON 1
#define I2S_TX_OFF 0
#define FIFO_LENGTH 64
/* I2s Registers */
struct i2s_reg {
unsigned int con; /* base + 0 , Control register */
unsigned int mod; /* Mode register */
unsigned int fic; /* FIFO control register */
unsigned int psr; /* Reserved */
unsigned int txd; /* Transmit data register */
unsigned int rxd; /* Receive Data Register */
};
/* This structure stores the i2s related information */
struct i2stx_info {
unsigned int rfs; /* LR clock frame size */
unsigned int bfs; /* Bit slock frame size */
unsigned int audio_pll_clk; /* Audio pll frequency in Hz */
unsigned int samplingrate; /* sampling rate */
unsigned int bitspersample; /* bits per sample */
unsigned int channels; /* audio channels */
unsigned int base_address; /* I2S Register Base */
unsigned int id; /* I2S controller id */
};
/*
* Sends the given data through i2s tx
*
* @param pi2s_tx pointer of i2s transmitter parameter structure.
* @param data address of the data buffer
* @param data_size array size of the int buffer (total size / size of int)
*
* @return int value 0 for success, -1 in case of error
*/
int i2s_transfer_tx_data(struct i2stx_info *pi2s_tx, unsigned *data,
unsigned long data_size);
/*
* Initialise i2s transmiter
*
* @param pi2s_tx pointer of i2s transmitter parameter structure.
*
* @return int value 0 for success, -1 in case of error
*/
int i2s_tx_init(struct i2stx_info *pi2s_tx);
#endif /* __I2S_H__ */
|
09704472ff72cc2484cc5e5945cef85e608574a6
|
8551168c7b71c31eebad0f9b0c71eebbcc743000
|
/src/lib/ultra/io/pfsdeletefile.c
|
58a2523d55b53eaf1d41486f127655653d844af7
|
[
"MIT"
] |
permissive
|
n64decomp/perfect_dark
|
0db80e8ecba74741b959962e55c835a91c920f44
|
0235a971d6fb1a0d4421856d5a65aa8067bd4658
|
refs/heads/master
| 2023-08-31T04:27:53.864767
| 2023-08-29T11:36:58
| 2023-08-29T11:36:58
| 241,214,589
| 452
| 47
|
MIT
| 2023-08-21T08:53:40
| 2020-02-17T21:46:45
|
C
|
UTF-8
|
C
| false
| false
| 1,804
|
c
|
pfsdeletefile.c
|
#include <os_internal.h>
#include "controller.h"
s32 osPfsDeleteFile(OSPfs *pfs, u16 company_code, u32 game_code, u8 *game_name, u8 *ext_name)
{
s32 file_no;
s32 ret;
__OSInode inode;
__OSDir dir;
__OSInodeUnit last_page;
u8 startpage;
u8 bank;
if (company_code == 0 || game_code == 0) {
return PFS_ERR_INVALID;
}
if ((ret = osPfsFindFile(pfs, company_code, game_code, game_name, ext_name, &file_no)) != 0) {
return ret;
}
if (pfs->activebank != 0 && (ret = __osPfsSelectBank(pfs, 0)) != 0) {
return ret;
}
if ((ret = __osContRamRead(pfs->queue, pfs->channel, pfs->dir_table + file_no, (u8*)&dir)) != 0) {
return ret;
}
startpage = dir.start_page.inode_t.page;
for (bank = dir.start_page.inode_t.bank; bank < pfs->banks;) {
if ((ret = __osPfsRWInode(pfs, &inode, PFS_READ, bank)) != 0) {
return ret;
}
if ((ret = __osPfsReleasePages(pfs, &inode, startpage, bank, &last_page)) != 0) {
return ret;
}
if ((ret = __osPfsRWInode(pfs, &inode, PFS_WRITE, bank)) != 0) {
return ret;
}
if (last_page.ipage == 1) {
break;
}
bank = last_page.inode_t.bank;
startpage = last_page.inode_t.page;
}
if (bank >= pfs->banks) {
return PFS_ERR_INCONSISTENT;
}
bzero(&dir, sizeof(__OSDir));
ret = __osContRamWrite(pfs->queue, pfs->channel, pfs->dir_table + file_no, (u8*)&dir, 0);
return ret;
}
s32 __osPfsReleasePages(OSPfs *pfs, __OSInode *inode, u8 initial_page, u8 bank, __OSInodeUnit *final_page)
{
__OSInodeUnit next;
__OSInodeUnit prev;
s32 ret = 0;
next.ipage = (u16)((bank << 8) + initial_page);
do {
prev = next;
next = inode->inode_page[next.inode_t.page];
inode->inode_page[prev.inode_t.page].ipage = 3;
} while (next.ipage >= pfs->inode_start_page && next.inode_t.bank == bank);
*final_page = next;
return ret;
}
|
6946c505ceac5fc47da604a6338f69cb0129ffff
|
8838eb997879add5759b6dfb23f9a646464e53ca
|
/src/drivers/block_dev/partition/partition.h
|
41c31db82b9c144943039925bf1ac6b6aac12f9f
|
[
"BSD-2-Clause"
] |
permissive
|
embox/embox
|
d6aacec876978522f01cdc4b8de37a668c6f4c80
|
98e3c06e33f3fdac10a29c069c20775568e0a6d1
|
refs/heads/master
| 2023-09-04T03:02:20.165042
| 2023-09-02T14:55:31
| 2023-09-02T14:55:31
| 33,078,138
| 1,087
| 325
|
BSD-2-Clause
| 2023-09-14T16:58:34
| 2015-03-29T15:27:48
|
C
|
UTF-8
|
C
| false
| false
| 312
|
h
|
partition.h
|
/**
* @file
* @brief
* @author Denis Deryugin <deryugin.denis@gmail.com>
* @version 0.1
* @date 2015-10-27
*/
#ifndef DRIVERS_BLOCK_DEV_PARTITION_H_
#define DRIVERS_BLOCK_DEV_PARTITION_H_
struct block_dev;
extern int create_partitions(struct block_dev *hd);
#endif /* DRIVERS_BLOCK_DEV_PARTITION_H_ */
|
c8cd802a5f8d8d9dcf2ffae74a351712bd8bdee8
|
aa3befea459382dc5c01c925653d54f435b3fb0f
|
/arch/xtensa/src/esp32s3/esp32s3_user.c
|
d263bee0552558f0ff47fb083896243f7abc2b5e
|
[
"MIT-open-group",
"BSD-3-Clause",
"HPND-sell-variant",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"LicenseRef-scancode-bsd-atmel",
"LicenseRef-scancode-gary-s-brown",
"LicenseRef-scancode-proprietary-license",
"SunPro",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"LicenseRef-scancode-other-permissive",
"HPND",
"ISC",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"GPL-1.0-or-later",
"CC-BY-2.0",
"CC-BY-4.0"
] |
permissive
|
apache/nuttx
|
14519a7bff4a87935d94fb8fb2b19edb501c7cec
|
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
|
refs/heads/master
| 2023-08-25T06:55:45.822534
| 2023-08-23T16:03:31
| 2023-08-24T21:25:47
| 228,103,273
| 407
| 241
|
Apache-2.0
| 2023-09-14T18:26:05
| 2019-12-14T23:27:55
|
C
|
UTF-8
|
C
| false
| false
| 2,557
|
c
|
esp32s3_user.c
|
/****************************************************************************
* arch/xtensa/src/esp32s3/esp32s3_user.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 <stdint.h>
#include "xtensa.h"
/****************************************************************************
* Public Data
****************************************************************************/
/****************************************************************************
* Private Data
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: xtensa_user
*
* Description:
* ESP32-S3-specific user exception handler.
*
* Input Parameters:
* exccause - Identifies the EXCCAUSE of the user exception.
* regs - The register save are at the time of the interrupt.
*
* Returned Value:
* Does not return.
*
****************************************************************************/
uint32_t *xtensa_user(int exccause, uint32_t *regs)
{
/* xtensa_user_panic never returns. */
xtensa_user_panic(exccause, regs);
while (1)
{
}
}
|
8fe060c0e553c26593dcec58c601f6a9f8021196
|
24ed6f6bec90986e60641c991afcea9409df40af
|
/src/ft2_mouse.c
|
294498899eb18bfef810d09cdb9446e469aa3bba
|
[
"BSD-3-Clause",
"CC-BY-NC-SA-4.0"
] |
permissive
|
8bitbubsy/ft2-clone
|
24b851b989ee0dd27d24041524c95c06a4648485
|
7c6a629b5407f0acfd1df7235903f475156051de
|
refs/heads/master
| 2023-09-04T12:34:02.982464
| 2023-08-16T10:01:41
| 2023-08-16T10:01:41
| 225,352,979
| 560
| 48
|
BSD-3-Clause
| 2023-05-09T17:26:38
| 2019-12-02T10:59:22
|
C
|
UTF-8
|
C
| false
| false
| 22,103
|
c
|
ft2_mouse.c
|
// for finding memory leaks in debug mode with Visual Studio
#if defined _DEBUG && defined _MSC_VER
#include <crtdbg.h>
#endif
#include <stdio.h>
#include <stdbool.h>
#include "ft2_header.h"
#include "ft2_gui.h"
#include "ft2_video.h"
#include "scopes/ft2_scopes.h"
#include "ft2_help.h"
#include "ft2_sample_ed.h"
#include "ft2_inst_ed.h"
#include "ft2_pattern_ed.h"
#include "ft2_mouse.h"
#include "ft2_config.h"
#include "ft2_diskop.h"
#include "ft2_audioselector.h"
#include "ft2_midi.h"
#include "ft2_bmp.h"
#include "ft2_structs.h"
#define NUM_CURSORS 6
mouse_t mouse; // globalized
static bool mouseBusyGfxBackwards;
static int16_t mouseShape;
static int32_t mouseModeGfxOffs, mouseBusyGfxFrame;
static SDL_Cursor *cursors[NUM_CURSORS];
static bool setSystemCursor(SDL_Cursor *cur)
{
if (config.specialFlags2 & USE_OS_MOUSE_POINTER)
{
SDL_SetCursor(SDL_GetDefaultCursor());
return true;
}
if (cur == NULL)
{
SDL_SetCursor(SDL_GetDefaultCursor());
return false;
}
SDL_SetCursor(cur);
return true;
}
void freeMouseCursors(void)
{
SDL_SetCursor(SDL_GetDefaultCursor());
for (int32_t i = 0; i < NUM_CURSORS; i++)
{
if (cursors[i] != NULL)
{
SDL_FreeCursor(cursors[i]);
cursors[i] = NULL;
}
}
}
bool createMouseCursors(void) // creates scaled SDL surfaces for current mouse pointer shape
{
freeMouseCursors();
const uint8_t *cursorsSrc = bmp.mouseCursors;
switch (config.mouseType)
{
case MOUSE_IDLE_SHAPE_NICE: cursorsSrc += 0 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_UGLY: cursorsSrc += 1 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_AWFUL: cursorsSrc += 2 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_USABLE: cursorsSrc += 3 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
default: break;
}
for (int32_t i = 0; i < NUM_CURSORS; i++)
{
int32_t scaleFactor = video.yScale;
if (scaleFactor > 8) // just in case
scaleFactor = 8;
SDL_Surface *surface = SDL_CreateRGBSurface(0, MOUSE_CURSOR_W*scaleFactor, MOUSE_CURSOR_H*scaleFactor, 32, 0, 0, 0, 0);
if (surface == NULL)
{
freeMouseCursors();
if (config.specialFlags2 & USE_OS_MOUSE_POINTER)
{
SDL_ShowCursor(SDL_TRUE);
}
else
{
// enable software mouse
config.specialFlags2 &= ~HARDWARE_MOUSE;
SDL_ShowCursor(SDL_FALSE);
}
return false;
}
const uint32_t colorkey = SDL_MapRGB(surface->format, 0x00, 0xFF, 0x00); // colorkey
const uint32_t fg = SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF); // foreground
const uint32_t border = SDL_MapRGB(surface->format, 0x00, 0x00, 0x00); // border
SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_NONE);
SDL_SetColorKey(surface, SDL_TRUE, colorkey);
SDL_SetSurfaceRLE(surface, SDL_TRUE);
const uint8_t *srcPixels8;
if (i == 3) // text edit cursor
srcPixels8 = &bmp.mouseCursors[12 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)];
else if (i == 4) // mouse busy (wall clock)
srcPixels8 = &bmp.mouseCursorBusyClock[2 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)]; // pick a good still-frame
else if (i == 5) // mouse busy (hourglass)
srcPixels8 = &bmp.mouseCursorBusyGlass[2 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)]; // pick a good still-frame
else // normal idle cursor + disk op. "delete/rename" cursors
srcPixels8 = &cursorsSrc[i * (4 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H))];
SDL_LockSurface(surface);
uint32_t *dstPixels32 = (uint32_t *)surface->pixels;
for (int32_t k = 0; k < surface->w*surface->h; k++) // fill surface with colorkey pixels
dstPixels32[k] = colorkey;
// blit upscaled cursor to surface
for (int32_t y = 0; y < MOUSE_CURSOR_H; y++)
{
uint32_t *outX = &dstPixels32[(y * scaleFactor) * surface->w];
for (int32_t yScale = 0; yScale < scaleFactor; yScale++)
{
const uint8_t *srcPtr = &srcPixels8[y * MOUSE_CURSOR_W];
for (int32_t x = 0; x < MOUSE_CURSOR_W; x++)
{
const uint8_t srcPix = srcPtr[x];
if (srcPix != PAL_TRANSPR)
{
uint32_t pixel = colorkey;
if (srcPix == PAL_MOUSEPT)
pixel = fg;
else if (srcPix == PAL_BCKGRND)
pixel = border;
for (int32_t xScale = 0; xScale < scaleFactor; xScale++)
outX[xScale] = pixel;
}
outX += scaleFactor;
}
}
}
SDL_UnlockSurface(surface);
uint32_t hotX = 0;
uint32_t hotY = 0;
if (i == 3) // text edit cursor bias
{
hotX = 2 * video.xScale;
hotY = 6 * video.yScale;
}
cursors[i] = SDL_CreateColorCursor(surface, hotX, hotY);
if (cursors[i] == NULL)
{
SDL_FreeSurface(surface);
freeMouseCursors();
if (config.specialFlags2 & USE_OS_MOUSE_POINTER)
{
SDL_ShowCursor(SDL_TRUE);
}
else
{
// enable software mouse
config.specialFlags2 &= ~HARDWARE_MOUSE;
SDL_ShowCursor(SDL_FALSE);
}
return false;
}
SDL_FreeSurface(surface);
}
if (config.specialFlags2 & HARDWARE_MOUSE)
{
if (mouse.mode == MOUSE_MODE_NORMAL) setSystemCursor(cursors[0]);
else if (mouse.mode == MOUSE_MODE_DELETE) setSystemCursor(cursors[1]);
else if (mouse.mode == MOUSE_MODE_RENAME) setSystemCursor(cursors[2]);
SDL_ShowCursor(SDL_TRUE);
}
else
{
SDL_ShowCursor(SDL_FALSE);
}
return true;
}
void setMousePosToCenter(void)
{
if (video.fullscreen)
{
mouse.setPosX = video.displayW >> 1;
mouse.setPosY = video.displayH >> 1;
}
else
{
mouse.setPosX = video.renderW >> 1;
mouse.setPosY = video.renderH >> 1;
}
mouse.setPosFlag = true;
}
void animateBusyMouse(void)
{
if (config.mouseAnimType == MOUSE_BUSY_SHAPE_CLOCK)
{
if (config.specialFlags2 & HARDWARE_MOUSE)
{
setSystemCursor(cursors[4]);
return;
}
if ((editor.framesPassed % 7) == 6)
{
if (mouseBusyGfxBackwards)
{
if (--mouseBusyGfxFrame <= 0)
{
mouseBusyGfxFrame = 0;
mouseBusyGfxBackwards = false;
}
}
else
{
if (++mouseBusyGfxFrame >= MOUSE_CLOCK_ANI_FRAMES-1)
{
mouseBusyGfxFrame = MOUSE_CLOCK_ANI_FRAMES - 1;
mouseBusyGfxBackwards = true;
}
}
changeSpriteData(SPRITE_MOUSE_POINTER,
&bmp.mouseCursorBusyClock[(mouseBusyGfxFrame % MOUSE_CLOCK_ANI_FRAMES) * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)]);
}
}
else
{
if (config.specialFlags2 & HARDWARE_MOUSE)
{
setSystemCursor(cursors[5]);
return;
}
if ((editor.framesPassed % 5) == 4)
{
mouseBusyGfxFrame = (mouseBusyGfxFrame + 1) % MOUSE_GLASS_ANI_FRAMES;
changeSpriteData(SPRITE_MOUSE_POINTER,
&bmp.mouseCursorBusyGlass[mouseBusyGfxFrame * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)]);
}
}
}
void setMouseShape(int16_t shape)
{
const uint8_t *gfxPtr;
if (editor.busy)
{
if (config.mouseAnimType == MOUSE_BUSY_SHAPE_CLOCK)
gfxPtr = &bmp.mouseCursorBusyClock[(mouseBusyGfxFrame % MOUSE_GLASS_ANI_FRAMES) * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)];
else
gfxPtr = &bmp.mouseCursorBusyGlass[(mouseBusyGfxFrame % MOUSE_CLOCK_ANI_FRAMES) * (MOUSE_CURSOR_W * MOUSE_CURSOR_H)];
}
else
{
gfxPtr = &bmp.mouseCursors[mouseModeGfxOffs];
switch (shape)
{
case MOUSE_IDLE_SHAPE_NICE: gfxPtr += 0 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_UGLY: gfxPtr += 1 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_AWFUL: gfxPtr += 2 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_SHAPE_USABLE: gfxPtr += 3 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
case MOUSE_IDLE_TEXT_EDIT: gfxPtr += 12 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); break;
default: return;
}
}
mouseShape = shape;
changeSpriteData(SPRITE_MOUSE_POINTER, gfxPtr);
if (config.specialFlags2 & HARDWARE_MOUSE)
{
if (mouse.mode == MOUSE_MODE_NORMAL) setSystemCursor(cursors[0]);
else if (mouse.mode == MOUSE_MODE_DELETE) setSystemCursor(cursors[1]);
else if (mouse.mode == MOUSE_MODE_RENAME) setSystemCursor(cursors[2]);
}
}
static void setTextEditMouse(void)
{
setMouseShape(MOUSE_IDLE_TEXT_EDIT);
mouse.xBias = -2;
mouse.yBias = -6;
if (config.specialFlags2 & HARDWARE_MOUSE)
setSystemCursor(cursors[3]);
}
static void clearTextEditMouse(void)
{
setMouseShape(config.mouseType);
mouse.xBias = 0;
mouse.yBias = 0;
if (config.specialFlags2 & HARDWARE_MOUSE)
setSystemCursor(cursors[0]);
}
static void changeCursorIfOverTextBoxes(void)
{
int32_t i;
mouse.mouseOverTextBox = false;
if (editor.busy || mouse.mode != MOUSE_MODE_NORMAL)
return;
const int32_t mx = mouse.x;
const int32_t my = mouse.y;
textBox_t *t = textBoxes;
for (i = 0; i < NUM_TEXTBOXES; i++, t++)
{
if (ui.sysReqShown && i != 0) // Sys. Req can only have one (special) text box
continue;
if (!t->visible)
continue;
if (!t->changeMouseCursor && (!editor.editTextFlag || i != mouse.lastEditBox))
continue; // some kludge of sorts
if (my >= t->y && my < t->y+t->h && mx >= t->x && mx < t->x+t->w)
{
mouse.mouseOverTextBox = true;
if (mouseShape != MOUSE_IDLE_TEXT_EDIT)
setTextEditMouse();
return;
}
}
// we're not inside a text edit box, set back mouse cursor
if (i == NUM_TEXTBOXES && mouseShape == MOUSE_IDLE_TEXT_EDIT)
clearTextEditMouse();
}
void setMouseMode(uint8_t mode)
{
switch (mode)
{
case MOUSE_MODE_NORMAL: { mouse.mode = mode; mouseModeGfxOffs = 0 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); } break;
case MOUSE_MODE_DELETE: { mouse.mode = mode; mouseModeGfxOffs = 4 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); } break;
case MOUSE_MODE_RENAME: { mouse.mode = mode; mouseModeGfxOffs = 8 * (MOUSE_CURSOR_W * MOUSE_CURSOR_H); } break;
default: return;
}
setMouseShape(config.mouseType);
}
void resetMouseBusyAnimation(void)
{
mouseBusyGfxBackwards = false;
mouseBusyGfxFrame = 0;
}
void setMouseBusy(bool busy) // can be called from other threads
{
if (busy)
{
ui.setMouseIdle = false;
ui.setMouseBusy = true;
}
else
{
ui.setMouseBusy = false;
ui.setMouseIdle = true;
}
}
void mouseAnimOn(void)
{
ui.setMouseBusy = false;
ui.setMouseIdle = false;
editor.busy = true;
setMouseShape(config.mouseAnimType);
}
void mouseAnimOff(void)
{
ui.setMouseBusy = false;
ui.setMouseIdle = false;
editor.busy = false;
setMouseShape(config.mouseType);
}
static void mouseWheelDecRow(void)
{
if (songPlaying)
return;
int16_t row = editor.row - 1;
if (row < 0)
row = patternNumRows[editor.editPattern] - 1;
setPos(-1, row, true);
}
static void mouseWheelIncRow(void)
{
if (songPlaying)
return;
int16_t row = editor.row + 1;
if (row >= patternNumRows[editor.editPattern])
row = 0;
setPos(-1, row, true);
}
void mouseWheelHandler(bool directionUp)
{
if (ui.sysReqShown || editor.editTextFlag)
return;
if (ui.extended)
{
if (mouse.y <= 52)
{
if (mouse.x <= 111) directionUp ? decSongPos() : incSongPos();
else if (mouse.x >= 386) directionUp ? decCurIns() : incCurIns();
}
else
{
directionUp ? mouseWheelDecRow() : mouseWheelIncRow();
}
return;
}
if (mouse.y < 173)
{
// top screens
if (ui.helpScreenShown)
{
// help screen
if (directionUp)
{
helpScrollUp();
helpScrollUp();
}
else
{
helpScrollDown();
helpScrollDown();
}
}
else if (ui.diskOpShown)
{
// disk op - 3x speed
if (mouse.x <= 355)
{
if (directionUp)
{
pbDiskOpListUp();
pbDiskOpListUp();
pbDiskOpListUp();
}
else
{
pbDiskOpListDown();
pbDiskOpListDown();
pbDiskOpListDown();
}
}
}
else if (ui.configScreenShown)
{
if (editor.currConfigScreen == CONFIG_SCREEN_AUDIO)
{
// audio device selectors
if (mouse.x >= 110 && mouse.x <= 355 && mouse.y <= 173)
{
if (mouse.y < 87)
directionUp ? scrollAudOutputDevListUp() : scrollAudOutputDevListDown();
else
directionUp ? scrollAudInputDevListUp() : scrollAudInputDevListDown();
}
}
#ifdef HAS_MIDI
else if (editor.currConfigScreen == CONFIG_SCREEN_MIDI_INPUT)
{
// midi input device selector
if (mouse.x >= 110 && mouse.x <= 503 && mouse.y <= 173)
directionUp ? scrollMidiInputDevListUp() : scrollMidiInputDevListDown();
}
#endif
}
if (!ui.aboutScreenShown && !ui.helpScreenShown &&
!ui.configScreenShown && !ui.nibblesShown)
{
if (mouse.x >= 421 && mouse.y <= 173)
{
if (mouse.y <= 93) directionUp ? decCurIns() : incCurIns();
else if (mouse.y >= 94) directionUp ? decCurSmp() : incCurSmp();
}
else if (!ui.diskOpShown && mouse.x <= 111 && mouse.y <= 76)
{
directionUp ? decSongPos() : incSongPos();
}
}
}
else
{
// bottom screens
if (ui.sampleEditorShown)
{
if (mouse.y >= 174 && mouse.y <= 328)
directionUp ? mouseZoomSampleDataIn() : mouseZoomSampleDataOut();
}
else if (ui.patternEditorShown)
{
directionUp ? mouseWheelDecRow() : mouseWheelIncRow();
}
}
}
static bool testSamplerDataMouseDown(void)
{
if (ui.sampleEditorShown && mouse.y >= 174 && mouse.y <= 327 && ui.sampleDataOrLoopDrag == -1)
{
handleSampleDataMouseDown(false);
return true;
}
return false;
}
static bool testPatternDataMouseDown(void)
{
if (ui.patternEditorShown)
{
const int32_t y1 = ui.extended ? 56 : 176;
const int32_t y2 = ui.pattChanScrollShown ? 382 : 396;
if (mouse.y >= y1 && mouse.y <= y2 && mouse.x >= 29 && mouse.x <= 602)
{
handlePatternDataMouseDown(false);
return true;
}
}
return false;
}
void mouseButtonUpHandler(uint8_t mouseButton)
{
if (mouseButton == SDL_BUTTON_LEFT)
{
mouse.leftButtonPressed = false;
mouse.leftButtonReleased = true;
if (ui.leftLoopPinMoving)
{
setLeftLoopPinState(false);
ui.leftLoopPinMoving = false;
}
if (ui.rightLoopPinMoving)
{
setRightLoopPinState(false);
ui.rightLoopPinMoving = false;
}
}
else if (mouseButton == SDL_BUTTON_RIGHT)
{
mouse.rightButtonPressed = false;
mouse.rightButtonReleased = true;
if (editor.editSampleFlag)
{
// right mouse button released after hand-editing sample data
if (instr[editor.curInstr] != NULL)
fixSample(&instr[editor.curInstr]->smp[editor.curSmp]);
resumeAudio();
if (ui.sampleEditorShown)
writeSample(true);
setSongModifiedFlag();
editor.editSampleFlag = false;
}
}
mouse.firstTimePressingButton = false;
mouse.buttonCounter = 0;
editor.textCursorBlinkCounter = 0;
// if we used both mouse button at the same time and released *one*, don't release GUI object
if ( mouse.leftButtonPressed && !mouse.rightButtonPressed) return;
if (!mouse.leftButtonPressed && mouse.rightButtonPressed) return;
if (ui.sampleEditorShown)
testSmpEdMouseUp();
mouse.lastX = 0;
mouse.lastY = 0;
ui.sampleDataOrLoopDrag = -1;
// check if we released a GUI object
testDiskOpMouseRelease();
testPushButtonMouseRelease(true);
testCheckBoxMouseRelease();
testScrollBarMouseRelease();
testRadioButtonMouseRelease();
// revert "delete/rename" mouse modes (disk op.)
if (mouse.mode != MOUSE_MODE_NORMAL)
{
if (mouse.lastUsedObjectID != PB_DISKOP_DELETE && mouse.lastUsedObjectID != PB_DISKOP_RENAME)
setMouseMode(MOUSE_MODE_NORMAL);
}
mouse.lastUsedObjectID = OBJECT_ID_NONE;
mouse.lastUsedObjectType = OBJECT_NONE;
}
void mouseButtonDownHandler(uint8_t mouseButton)
{
// if already holding left button and clicking right, don't do mouse down handling
if (mouseButton == SDL_BUTTON_RIGHT && mouse.leftButtonPressed)
{
if (ui.sampleDataOrLoopDrag == -1)
{
mouse.rightButtonPressed = true;
mouse.rightButtonReleased = false;
}
// kludge - we must do scope solo/unmute all here
if (!ui.sysReqShown)
testScopesMouseDown();
return;
}
// if already holding right button and clicking left, don't do mouse down handling
if (mouseButton == SDL_BUTTON_LEFT && mouse.rightButtonPressed)
{
if (ui.sampleDataOrLoopDrag == -1)
{
mouse.leftButtonPressed = true;
mouse.leftButtonReleased = false;
}
// kludge - we must do scope solo/unmute all here
if (!ui.sysReqShown)
testScopesMouseDown();
return;
}
// mouse 0,0 = open exit dialog (also make sure the test always works in fullscreen mode)
if ((mouse.x == 0 && mouse.y == 0) || (video.fullscreen && (video.renderX > 0 || video.renderY > 0) && (mouse.rawX == 0 && mouse.rawY == 0)))
{
if (quitBox(false) == 1)
editor.throwExit = true;
// release button presses from okBox()
mouse.leftButtonPressed = false;
mouse.rightButtonPressed = false;
mouse.leftButtonReleased = false;
mouse.rightButtonReleased = false;
return;
}
if (mouseButton == SDL_BUTTON_LEFT)
mouse.leftButtonPressed = true;
else if (mouseButton == SDL_BUTTON_RIGHT)
mouse.rightButtonPressed = true;
mouse.leftButtonReleased = false;
mouse.rightButtonReleased = false;
// don't do mouse down testing here if we already are using an object
if (mouse.lastUsedObjectType != OBJECT_NONE)
return;
// kludge #2
if (mouse.lastUsedObjectType != OBJECT_PUSHBUTTON && mouse.lastUsedObjectID != OBJECT_ID_NONE)
return;
// kludge #3 :(
if (!mouse.rightButtonPressed)
mouse.lastUsedObjectID = OBJECT_ID_NONE;
// check if we pressed a GUI object
/* test objects like this - clickable things *never* overlap, so no need to test all
** other objects if we clicked on one already
*/
testInstrSwitcherMouseDown(); // kludge: allow right click to both change ins. and edit text
if (testTextBoxMouseDown()) return;
if (testPushButtonMouseDown()) return;
if (testCheckBoxMouseDown()) return;
if (testScrollBarMouseDown()) return;
if (testRadioButtonMouseDown()) return;
// at this point, we don't need to test more widgets if a system request is shown
if (ui.sysReqShown)
return;
if (testInstrVolEnvMouseDown(false)) return;
if (testInstrPanEnvMouseDown(false)) return;
if (testDiskOpMouseDown(false)) return;
if (testPianoKeysMouseDown(false)) return;
if (testSamplerDataMouseDown()) return;
if (testPatternDataMouseDown()) return;
if (testScopesMouseDown()) return;
if (testAudioDeviceListsMouseDown()) return;
#ifdef HAS_MIDI
if (testMidiInputDeviceListMouseDown()) return;
#endif
}
static void sendMouseButtonUpEvent(uint8_t button)
{
SDL_Event event;
memset(&event, 0, sizeof (event));
event.type = SDL_MOUSEBUTTONUP;
event.button.button = button;
SDL_PushEvent(&event);
}
void handleLastGUIObjectDown(void)
{
if (mouse.lastUsedObjectType == OBJECT_NONE)
return;
if (mouse.leftButtonPressed || mouse.rightButtonPressed)
{
if (mouse.lastUsedObjectID != OBJECT_ID_NONE)
{
switch (mouse.lastUsedObjectType)
{
case OBJECT_PUSHBUTTON: handlePushButtonsWhileMouseDown(); break;
case OBJECT_RADIOBUTTON: handleRadioButtonsWhileMouseDown(); break;
case OBJECT_CHECKBOX: handleCheckBoxesWhileMouseDown(); break;
case OBJECT_SCROLLBAR: handleScrollBarsWhileMouseDown(); break;
case OBJECT_TEXTBOX: handleTextBoxWhileMouseDown(); break;
default: break;
}
}
else
{
// test non-standard GUI elements
switch (mouse.lastUsedObjectType)
{
case OBJECT_INSTRSWITCH: testInstrSwitcherMouseDown(); break;
case OBJECT_PATTERNMARK: handlePatternDataMouseDown(true); break;
case OBJECT_DISKOPLIST: testDiskOpMouseDown(true); break;
case OBJECT_SMPDATA: handleSampleDataMouseDown(true); break;
case OBJECT_PIANO: testPianoKeysMouseDown(true); break;
case OBJECT_INSVOLENV: testInstrVolEnvMouseDown(true); break;
case OBJECT_INSPANENV: testInstrPanEnvMouseDown(true); break;
default: break;
}
}
/* Hack to send "mouse button up" events if we released the mouse button(s)
** outside of the window...
*/
if (mouse.x < 0 || mouse.x >= SCREEN_W || mouse.y < 0 || mouse.y >= SCREEN_H)
{
if (mouse.leftButtonPressed && !(mouse.buttonState & SDL_BUTTON_LMASK))
sendMouseButtonUpEvent(SDL_BUTTON_LEFT);
if (mouse.rightButtonPressed && !(mouse.buttonState & SDL_BUTTON_RMASK))
sendMouseButtonUpEvent(SDL_BUTTON_RIGHT);
}
}
}
void updateMouseScaling(void)
{
if (video.renderW > 0.0) video.fMouseXMul = (float)SCREEN_W / video.renderW;
if (video.renderH > 0.0) video.fMouseYMul = (float)SCREEN_H / video.renderH;
}
void readMouseXY(void)
{
int32_t mx, my, windowX, windowY;
if (mouse.setPosFlag)
{
if (!video.windowHidden)
SDL_WarpMouseInWindow(video.window, mouse.setPosX, mouse.setPosY);
mouse.setPosFlag = false;
return;
}
if (video.useDesktopMouseCoords)
{
mouse.buttonState = SDL_GetGlobalMouseState(&mx, &my);
mouse.absX = mx;
mouse.absY = my;
// convert desktop coords to window coords
SDL_GetWindowPosition(video.window, &windowX, &windowY);
mx -= windowX;
my -= windowY;
}
else
{
// special mode for KMSDRM (XXX: Confirm that this still works...)
mouse.buttonState = SDL_GetMouseState(&mx, &my);
mouse.absX = mx;
mouse.absY = my;
}
mouse.rawX = mx;
mouse.rawY = my;
if (video.fullscreen)
{
// centered fullscreen mode (not stretched) needs further coord translation
if (!(config.specialFlags2 & STRETCH_IMAGE))
{
// if software mouse is enabled, warp mouse inside render space
if (!(config.specialFlags2 & HARDWARE_MOUSE))
{
bool warpMouse = false;
if (mx < video.renderX)
{
mx = video.renderX;
warpMouse = true;
}
else if (mx >= video.renderX+video.renderW)
{
mx = (video.renderX + video.renderW) - 1;
warpMouse = true;
}
if (my < video.renderY)
{
my = video.renderY;
warpMouse = true;
}
else if (my >= video.renderY+video.renderH)
{
my = (video.renderY + video.renderH) - 1;
warpMouse = true;
}
if (warpMouse)
SDL_WarpMouseInWindow(video.window, mx, my);
}
// convert fullscreen coords to window (centered image) coords
mx -= video.renderX;
my -= video.renderY;
}
}
// multiply coords by video upscaling factors (don't round)
mouse.x = (int32_t)(mx * video.fMouseXMul);
mouse.y = (int32_t)(my * video.fMouseYMul);
if (config.specialFlags2 & HARDWARE_MOUSE)
{
// hardware mouse mode (OS)
hideSprite(SPRITE_MOUSE_POINTER);
}
else
{
// software mouse mode (FT2 mouse)
setSpritePos(SPRITE_MOUSE_POINTER, mouse.x + mouse.xBias, mouse.y + mouse.yBias);
}
changeCursorIfOverTextBoxes();
}
|
68251acb40f2a55f76e9bf47e60c3a250e42f871
|
a8966368090e6972bd838a3a79d86ac03d52e27f
|
/thirdparty/oso.h
|
9a59fd6a0fc786fc72c4c70b67e128953adf8d78
|
[
"MIT"
] |
permissive
|
hundredrabbits/Orca-c
|
f98fb363a4b1d4409fabc6d668158b84575bb1d0
|
e6a9a30ba09f71e18ec85aa613fb0ebdd6c9bec6
|
refs/heads/master
| 2023-08-06T14:39:40.982012
| 2022-11-28T10:05:51
| 2022-11-28T10:05:51
| 158,889,536
| 444
| 56
|
MIT
| 2022-02-24T11:17:59
| 2018-11-24T00:33:53
|
C
|
UTF-8
|
C
| false
| false
| 8,220
|
h
|
oso.h
|
#pragma once
// Heap-allocated string handling.
// Inspired by antirez's sds and gingerBill's gb_string.h.
//
// "I need null-terminated strings to interact with libc and/or POSIX, and my
// software isn't serious enough to warrant using arena or page allocation
// strategies. Manually fussing with null-terminated strings with libc sucks,
// even though we're allocating everything individually on the heap! Why can't
// we at least get a nicer interface for the trade-off we've already made?"
//
// EXAMPLE
// ---------
// oso *mystring = NULL;
// osoput(&mystring, "Hello World");
// printf((char *)mystring);
// osoput(&mystring, "How about some pancakes?");
// printf((char *)mystring);
// osocat(&mstring, " Sure!");
// printf((char *)mystring);
// osofree(mystring);
//
// > Hello World!
// > How about some pancakes?
// > How about some pancakes? Sure!
//
// RULES
// -------
// 1. `oso *` can always be cast to `char *`, but it's your job to check if
// it's null before passing it to on something that doesn't tolerate null
// pointers.
//
// 2. The functions defined in this header tolerate null pointers like this:
//
// `oso *` -> OK to be null.
// `char const *` -> Must not be null.
// `oso **` -> Must not be null, but the `oso *` pointed to
// can be null. The pointed-to `oso *` may be
// modified during the call.
//
// 3. `oso *` and `char const *` as arguments to the functions here must not
// overlap in memory. During the call, the buffer pointed to by a `oso *`
// might need to be reallocated in memory to make room for the `char const
// *` contents, and if the `char const *` contents end up being moved by
// that operation, the pointer will no longer be pointing at valid memory.
// (This also applies to functions which accept two `oso *` as inputs.)
//
// Parameters with the type `oso *` are safe to pass as a null pointer. But
// `oso **` parameters shouldn't be null. The `oso *` pointed to by the `oso
// **` can be null, though. In other words, you need to do `&mystring` to pass
// a `oso **` argument.
//
// During the function call, if the `oso *` pointed to by the `oso **` needs to
// become non-null, or if the existing buffer needs to be moved to grow larger,
// the `oso *` will be set to a new value.
//
// oso *mystring = NULL;
// osolen(mystring); // Gives 0
// osocat(&mystring, "waffles");
// osolen(mystring); // Gives 7
// osofree(mystring);
//
// NAMES
// -------
// osoput______ -> Copy a string into an oso string.
// osocat______ -> Append a string onto the end of an oso string.
// ______len -> Do it with an explicit length argument, so the C-string
// doesn't have to be '\0'-terminated.
// ______oso -> Do it with a second oso string.
// ______printf -> Do it by using printf.
//
// ALLOC FAILURE
// ---------------
// If an allocation fails (including failing to reallocate) the `oso *` will be
// set to null. If you decide to handle memory allocation failures, you'll need
// to check for that.
//
// In the oso code, if a reallocation of an existing buffer fails (`realloc()`
// returns null) then the old, still-valid buffer is immediately freed.
// Therefore, in an out-of-memory situation, it's possible that you will *lose*
// your strings without getting a chance to do something with the old buffers.
//
// Variations of the oso functions may be added in the future, with a _c suffix
// or something, which preserve the old buffer and return an error code in the
// event of a reallocation failure. I'm not sure how important this is, since
// most existing libc-based software doesn't handle out-of-memory conditions
// for small strings without imploding.
//
// (sds, for example, will lose your string *and* leak the old buffer if a
// reallocation fails.)
#include <stdarg.h>
#include <stddef.h>
#if (defined(__GNUC__) || defined(__clang__)) && defined(__has_attribute)
#if __has_attribute(format)
#define OSO_PRINTF(...) __attribute__((format(printf, __VA_ARGS__)))
#endif
#if __has_attribute(nonnull)
#define OSO_NONNULL(...) __attribute__((nonnull(__VA_ARGS__)))
#endif
#endif
#ifndef OSO_PRINTF
#define OSO_PRINTF(...)
#endif
#ifndef OSO_NONNULL
#define OSO_NONNULL(...)
#endif
typedef struct oso oso;
#define osoc(s) ((char const *)s)
void osoput(oso **p, char const *cstr) OSO_NONNULL();
// ^- Copies the '\0'-terminated string into the `oso *` string located at
// `*p`. If `*p` is null or there isn't enough capacity to hold `cstr`, it
// will be reallocated. The pointer value at `*p` will be updated if
// necessary. `*p` and `cstr` must not point to overlapping memory.
void osoputlen(oso **p, char const *cstr, size_t len) OSO_NONNULL();
// ^- Same as above, but uses an additional parameter that specifies the length
// of `cstr, and `cstr` does not have to be '\0'-terminated.
// `*p` and `cstr` must not point to overlapping memory.
void osoputoso(oso **p, oso const *other) OSO_NONNULL(1);
// ^- Same as above, but using another `oso`. `*p` and `other` must not point
// to overlapping memory.
void osoputvprintf(oso **p, char const *fmt, va_list ap) OSO_NONNULL(1, 2)
OSO_PRINTF(2, 0);
void osoputprintf(oso **p, char const *fmt, ...) OSO_NONNULL(1, 2)
OSO_PRINTF(2, 3);
// ^- Same as above, but do it by using printf.
void osocat(oso **p, char const *cstr) OSO_NONNULL();
void osocatlen(oso **p, char const *cstr, size_t len) OSO_NONNULL();
void osocatoso(oso **p, oso const *other) OSO_NONNULL(1);
void osocatvprintf(oso **p, char const *fmt, va_list ap) OSO_NONNULL(1, 2)
OSO_PRINTF(2, 0);
void osocatprintf(oso **p, char const *fmt, ...) OSO_NONNULL(1, 2)
OSO_PRINTF(2, 3);
// ^- Append string to oso string. Same rules as `osoput` family.
void osoensurecap(oso **p, size_t cap) OSO_NONNULL();
// ^- Ensure that s has at least `cap` memory allocated for it. This does not
// care about the strlen of the characters or the prefixed length count --
// only the backing memory allocation.
void osomakeroomfor(oso **p, size_t len) OSO_NONNULL();
// ^- Ensure that s has enough allocated space after the '\0'-terminnation
// character to hold an additional add_len characters. It does not adjust
// the `length` number value, only the capacity, if necessary.
//
// Both `osoensurecap()` and `osomakeroomfor()` can be used to avoid making
// multiple smaller reallactions as the string grows in the future. You can
// also use them if you're going to modify the string buffer manually in
// your own code, and need to create some space in the buffer.
void osoclear(oso **p) OSO_NONNULL();
// ^- Set len to 0, write '\0' at pos 0. Leaves allocated memory in place.
void osofree(oso *s);
// ^- You know. And calling with null is allowed.
void osowipe(oso **p) OSO_NONNULL();
// ^- It's like `osofree()`, except you give it a ptr-to-ptr, and it also sets
// `*p` to null for you when it's done freeing the memory.
void ososwap(oso **a, oso **b) OSO_NONNULL();
// ^- Swaps the two pointers. Yeah, that's all it does. Why? Because it's
// common when dealing memory management for individually allocated strings
// and changing between old and new string values.
void osopokelen(oso *s, size_t len) OSO_NONNULL();
// ^- Manually updates length field. Doesn't do anything else for you.
size_t osolen(oso const *s);
// ^- Bytes in use by the string (not including the '\0' character.)
size_t osocap(oso const *s);
// ^- Bytes allocated on heap (not including the '\0' terminator.)
void osolencap(oso const *s, size_t *out_len, size_t *out_cap)
OSO_NONNULL(2, 3);
// ^- Get both the len and the cap in one call.
size_t osoavail(oso const *s);
// ^- osocap(s) - osolen(s)
void osotrim(oso *restrict s, char const *restrict cut_set) OSO_NONNULL(2);
// ^- Remove the characters in `cut_set` from the beginning and ending of `s`.
#undef OSO_PRINTF
#undef OSO_NONNULL
|
66898b7a536dda903b2754d88f6ebce76e0b8dbb
|
de21f9075f55640514c29ef0f1fe3f0690845764
|
/regression/cprover/arrays/array4.c
|
f148237d110d6357e896ba7e10244e4bbc3df554
|
[
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-4-Clause"
] |
permissive
|
diffblue/cbmc
|
975a074ac445febb3b5715f8792beb545522dc18
|
decd2839c2f51a54b2ad0f3e89fdc1b4bf78cd16
|
refs/heads/develop
| 2023-08-31T05:52:05.342195
| 2023-08-30T13:31:51
| 2023-08-30T13:31:51
| 51,877,056
| 589
| 309
|
NOASSERTION
| 2023-09-14T18:49:17
| 2016-02-16T23:03:52
|
C++
|
UTF-8
|
C
| false
| false
| 120
|
c
|
array4.c
|
int main()
{
int a[100];
int *p = a;
__CPROVER_assert(p[23] == a[23], "property 1"); // should pass
return 0;
}
|
1f752307f4f37a31d519dd757521ffae4e7f4959
|
79d343002bb63a44f8ab0dbac0c9f4ec54078c3a
|
/lib/libc/include/any-macos-any/nl_types.h
|
2cc919e72769983e616aa4f8e586a6fcc8cafe73
|
[
"MIT"
] |
permissive
|
ziglang/zig
|
4aa75d8d3bcc9e39bf61d265fd84b7f005623fc5
|
f4c9e19bc3213c2bc7e03d7b06d7129882f39f6c
|
refs/heads/master
| 2023-08-31T13:16:45.980913
| 2023-08-31T05:50:29
| 2023-08-31T05:50:29
| 40,276,274
| 25,560
| 2,399
|
MIT
| 2023-09-14T21:09:50
| 2015-08-06T00:51:28
|
Zig
|
UTF-8
|
C
| false
| false
| 3,456
|
h
|
nl_types.h
|
/* $NetBSD: nl_types.h,v 1.9 2000/10/03 19:53:32 sommerfeld Exp $ */
/*-
* Copyright (c) 1996 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by J.T. Conklin.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD 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 NETBSD FOUNDATION, INC. 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.
*
* $FreeBSD: src/include/nl_types.h,v 1.11 2005/02/27 16:20:53 phantom Exp $
*/
#ifndef _NL_TYPES_H_
#define _NL_TYPES_H_
#include <sys/cdefs.h>
#include <sys/types.h>
#include <_types.h>
#ifdef _NLS_PRIVATE
/*
* MESSAGE CATALOG FILE FORMAT.
*
* The NetBSD/FreeBSD message catalog format is similar to the format used by
* Svr4 systems. The differences are:
* * fixed byte order (big endian)
* * fixed data field sizes
*
* A message catalog contains four data types: a catalog header, one
* or more set headers, one or more message headers, and one or more
* text strings.
*/
#define _NLS_MAGIC 0xff88ff89
struct _nls_cat_hdr {
int32_t __magic;
int32_t __nsets;
int32_t __mem;
int32_t __msg_hdr_offset;
int32_t __msg_txt_offset;
} ;
struct _nls_set_hdr {
int32_t __setno; /* set number: 0 < x <= NL_SETMAX */
int32_t __nmsgs; /* number of messages in the set */
int32_t __index; /* index of first msg_hdr in msg_hdr table */
} ;
struct _nls_msg_hdr {
int32_t __msgno; /* msg number: 0 < x <= NL_MSGMAX */
int32_t __msglen;
int32_t __offset;
} ;
#endif /* _NLS_PRIVATE */
#define NL_SETD 1
#define NL_CAT_LOCALE 1
typedef struct __nl_cat_d {
void *__data;
int __size;
} *nl_catd;
#include <_types/_nl_item.h>
__BEGIN_DECLS
nl_catd catopen(const char *, int);
char *catgets(nl_catd, int, int, const char *)
__attribute__((__format_arg__(4)));
int catclose(nl_catd);
__END_DECLS
#endif /* _NL_TYPES_H_ */
|
f6597a6c1f363c3547047c5a6901ad4f28d1a5c6
|
35e28d7705773eed54345af4440700522c9d1863
|
/deps/libgdal/gdal/frmts/grib/degrib/g2clib/gbits.c
|
0f56f3515f270d4799667e550857baa43a910c13
|
[
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"SunPro",
"LicenseRef-scancode-info-zip-2005-02",
"BSD-3-Clause"
] |
permissive
|
naturalatlas/node-gdal
|
0ee3447861bf2d1abc48d4fbdbcf15aba5473a27
|
c83e7858a9ec566cc91d65db74fd07b99789c0f0
|
refs/heads/master
| 2023-09-03T00:11:41.576937
| 2022-03-12T20:41:59
| 2022-03-12T20:41:59
| 19,504,824
| 522
| 122
|
Apache-2.0
| 2022-06-04T20:03:43
| 2014-05-06T18:02:34
|
C++
|
UTF-8
|
C
| false
| false
| 4,561
|
c
|
gbits.c
|
#include "grib2.h"
#include "limits.h"
int gbit(unsigned char *in,g2int *iout,g2int iskip,g2int nbyte)
{
return gbits(in,G2_UNKNOWN_SIZE,iout,iskip,nbyte,(g2int)0,(g2int)1);
}
int gbit2(unsigned char *in,g2int in_length,g2int *iout,g2int iskip,g2int nbyte)
{
return gbits(in,in_length,iout,iskip,nbyte,(g2int)0,(g2int)1);
}
void sbit(unsigned char *out,const g2int *in,g2int iskip,g2int nbyte)
{
sbits(out,in,iskip,nbyte,(g2int)0,(g2int)1);
}
int gbits(unsigned char *in,g2int in_length,g2int *iout,g2int iskip,g2int nbyte,g2int nskip,
g2int n)
/* Get bits - unpack bits: Extract arbitrary size values from a
/ packed bit string, right justifying each value in the unpacked
/ iout array.
/ *in = pointer to character array input
/ *iout = pointer to unpacked array output
/ iskip = initial number of bits to skip
/ nbyte = number of bits to take
/ nskip = additional number of bits to skip on each iteration
/ n = number of iterations
/ v1.1
*/
{
g2int i,tbit,bitcnt,ibit,itmp;
g2int nbit,l_index;
static const g2int ones[]={1,3,7,15,31,63,127,255};
// nbit is the start position of the field in bits
nbit = iskip;
if( n> 0 && (nbyte + nskip > INT_MAX / n ||
iskip > INT_MAX - n*(nbyte + nskip)) )
return -1;
for (i=0;i<n;i++) {
bitcnt = nbyte;
l_index=nbit/8;
ibit=nbit%8;
nbit = nbit + nbyte + nskip;
// first byte
tbit= ( bitcnt < (8-ibit) ) ? bitcnt : 8-ibit; // find min
if( in_length != G2_UNKNOWN_SIZE && l_index >= in_length )
return -1;
itmp = (int)*(in+l_index) & ones[7-ibit];
if (tbit != 8-ibit) itmp >>= (8-ibit-tbit);
l_index++;
bitcnt = bitcnt - tbit;
// now transfer whole bytes
while (bitcnt >= 8) {
if( in_length != G2_UNKNOWN_SIZE && l_index >= in_length )
return -1;
itmp = (int)(((unsigned)itmp)<<8 | (int)*(in+l_index));
bitcnt = bitcnt - 8;
l_index++;
}
// get data from last byte
if (bitcnt > 0) {
if( in_length != G2_UNKNOWN_SIZE && l_index >= in_length )
return -1;
itmp = (int)( (unsigned)itmp << bitcnt ) | ( ((int)*(in+l_index) >> (8-bitcnt)) & ones[bitcnt-1] );
}
*(iout+i) = itmp;
}
return 0;
}
void sbits(unsigned char *out,const g2int *in,g2int iskip,g2int nbyte,g2int nskip,
g2int n)
/*C Store bits - pack bits: Put arbitrary size values into a
/ packed bit string, taking the low order bits from each value
/ in the unpacked array.
/ *iout = pointer to packed array output
/ *in = pointer to unpacked array input
/ iskip = initial number of bits to skip
/ nbyte = number of bits to pack
/ nskip = additional number of bits to skip on each iteration
/ n = number of iterations
/ v1.1
*/
{
g2int i;
unsigned bitcnt,tbit,ibit,itmp,imask,itmp2,itmp3;
unsigned nbit,l_index;
static const unsigned ones[]={1,3,7,15,31,63,127,255};
const unsigned* u_in = (const unsigned*)in;
// number bits from zero to ...
// nbit is the last bit of the field to be filled
nbit = iskip + nbyte - 1;
for (i=0;i<n;i++) {
itmp = *(u_in+i);
bitcnt = nbyte;
l_index=nbit/8;
ibit=nbit%8;
nbit = nbit + nbyte + nskip;
// make byte aligned
if (ibit != 7) {
tbit= ( bitcnt < (ibit+1) ) ? bitcnt : ibit+1; // find min
imask = ones[tbit-1] << (7-ibit);
itmp2 = (itmp << (7-ibit)) & imask;
itmp3 = (int)*(out+l_index) & (255-imask);
out[l_index] = (unsigned char)(itmp2 | itmp3);
bitcnt = bitcnt - tbit;
itmp = itmp >> tbit;
l_index--;
}
// now byte aligned
// do by bytes
while (bitcnt >= 8) {
out[l_index] = (unsigned char)(itmp & 255);
itmp = itmp >> 8;
bitcnt = bitcnt - 8;
l_index--;
}
// do last byte
if (bitcnt > 0) {
itmp2 = itmp & ones[bitcnt-1];
itmp3 = (int)*(out+l_index) & (255-ones[bitcnt-1]);
out[l_index] = (unsigned char)(itmp2 | itmp3);
}
}
}
|
cdbe7ae3f4ae0b0320343be4585460fda90ee9a7
|
fbe68d84e97262d6d26dd65c704a7b50af2b3943
|
/third_party/virtualbox/src/VBox/Devices/PC/BIOS/ebda.h
|
e28ccef0c7d9cbd4bd0c16612de1cc4058a508a2
|
[
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"CDDL-1.0",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LGPL-2.1-or-later",
"GPL-2.0-or-later",
"MPL-1.0",
"LicenseRef-scancode-generic-exception",
"Apache-2.0",
"OpenSSL"
] |
permissive
|
thalium/icebox
|
c4e6573f2b4f0973b6c7bb0bf068fe9e795fdcfb
|
6f78952d58da52ea4f0e55b2ab297f28e80c1160
|
refs/heads/master
| 2022-08-14T00:19:36.984579
| 2022-02-22T13:10:31
| 2022-02-22T13:10:31
| 190,019,914
| 585
| 109
|
MIT
| 2022-01-13T20:58:15
| 2019-06-03T14:18:12
|
C++
|
UTF-8
|
C
| false
| false
| 12,079
|
h
|
ebda.h
|
/* $Id: ebda.h $ */
/** @file
* PC BIOS - ???
*/
/*
* Copyright (C) 2006-2017 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
* --------------------------------------------------------------------
*
* This code is based on:
*
* ROM BIOS for use with Bochs/Plex86/QEMU emulation environment
*
* Copyright (C) 2002 MandrakeSoft S.A.
*
* MandrakeSoft S.A.
* 43, rue d'Aboukir
* 75002 Paris - France
* http://www.linux-mandrake.com/
* http://www.mandrakesoft.com/
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/*
* Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
* other than GPL or LGPL is available it will apply instead, Oracle elects to use only
* the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
* a choice of LGPL license versions is made available with the language indicating
* that LGPLv2 or any later version may be used, or where a choice of which version
* of the LGPL is applied is otherwise unspecified.
*/
#include <stdint.h>
/* Must be defined here (EBDA structures depend on these). */
#define BX_MAX_ATA_INTERFACES 4
#define BX_MAX_ATA_DEVICES (BX_MAX_ATA_INTERFACES*2)
#define BX_USE_ATADRV 1
#define BX_ELTORITO_BOOT 1
#ifdef VBOX_WITH_SCSI
/* Enough for now */
#define BX_MAX_SCSI_DEVICES 4
/* A SCSI device starts always at BX_MAX_ATA_DEVICES. */
#define VBOX_IS_SCSI_DEVICE(device_id) (device_id >= BX_MAX_ATA_DEVICES)
#define VBOX_GET_SCSI_DEVICE(device_id) (device_id - BX_MAX_ATA_DEVICES)
#else
#define BX_MAX_SCSI_DEVICES 0
#endif
#ifdef VBOX_WITH_AHCI
/* Four should be enough for now */
#define BX_MAX_AHCI_DEVICES 4
/* An AHCI device starts always at BX_MAX_ATA_DEVICES + BX_MAX_SCSI_DEVICES. */
#define VBOX_IS_AHCI_DEVICE(device_id) (device_id >= (BX_MAX_ATA_DEVICES + BX_MAX_SCSI_DEVICES))
#define VBOX_GET_AHCI_DEVICE(device_id) (device_id - (BX_MAX_ATA_DEVICES + BX_MAX_SCSI_DEVICES))
#else
#define BX_MAX_AHCI_DEVICES 0
#endif
#define BX_MAX_STORAGE_DEVICES (BX_MAX_ATA_DEVICES + BX_MAX_SCSI_DEVICES + BX_MAX_AHCI_DEVICES)
/* Generic storage device types. These depend on the controller type and
* determine which device access routines should be called.
*/
enum dsk_type_enm {
DSK_TYPE_NONE, /* Unknown device. */
DSK_TYPE_UNKNOWN, /* Unknown ATA device. */
DSK_TYPE_ATA, /* ATA disk. */
DSK_TYPE_ATAPI, /* ATAPI device. */
DSK_TYPE_SCSI, /* SCSI disk. */
DSK_TYPE_AHCI, /* SATA disk via AHCI. */
DSKTYP_CNT /* Number of disk types. */
};
/* Disk device types. */
//@todo: Do we really need these?
#define DSK_DEVICE_NONE 0x00 /* No device attached. */
#define DSK_DEVICE_HD 0xFF /* Device is a hard disk. */
#define DSK_DEVICE_CDROM 0x05 /* Device is a CD-ROM. */
/* Geometry translation modes. */
enum geo_xlat_enm {
GEO_TRANSLATION_NONE, /* No geometry translation. */
GEO_TRANSLATION_LBA, /* LBA translation. */
GEO_TRANSLATION_LARGE, /* Large CHS translation. */
GEO_TRANSLATION_RECHS
};
#if 1 //BX_USE_ATADRV
/* Note: The DPTE and FDPT structures are industry standards and
* may not be modified. The other disk-related structures are
* internal to the BIOS.
*/
/* Translated DPT (Device Parameter Table). */
typedef struct {
uint16_t iobase1;
uint16_t iobase2;
uint8_t prefix;
uint8_t unused;
uint8_t irq;
uint8_t blkcount;
uint8_t dma;
uint8_t pio;
uint16_t options;
uint16_t reserved;
uint8_t revision;
uint8_t checksum;
} dpte_t;
ct_assert(sizeof(dpte_t) == 16); /* Ensure correct size. */
#pragma pack(0)
/* FDPT - Fixed Disk Parameter Table. PC/AT compatible; note
* that this structure is slightly misaligned.
*/
typedef struct {
uint16_t lcyl;
uint8_t lhead;
uint8_t sig;
uint8_t spt;
uint8_t resvd1[4];
uint16_t cyl;
uint8_t head;
uint8_t resvd2[2];
uint8_t lspt;
uint8_t csum;
} fdpt_t;
#pragma pack()
ct_assert(sizeof(fdpt_t) == 16); /* Ensure correct size. */
/* C/H/S geometry information. */
typedef struct {
uint16_t heads; /* Number of heads. */
uint16_t cylinders; /* Number of cylinders. */
uint16_t spt; /* Number of sectors per track. */
} chs_t;
/* IDE/ATA specific device information. */
typedef struct {
uint8_t iface; /* ISA or PCI. */
uint8_t irq; /* IRQ (on the PIC). */
uint16_t iobase1; /* I/O base 1. */
uint16_t iobase2; /* I/O base 2. */
} ata_chan_t;
#ifdef VBOX_WITH_SCSI
/* SCSI specific device information. */
typedef struct {
uint16_t io_base; /* Port base for HBA communication. */
uint8_t target_id; /* Target ID. */
} scsi_dev_t;
#endif
#ifdef VBOX_WITH_AHCI
/* AHCI specific device information. */
typedef struct {
uint8_t port; /* SATA port. */
} ahci_dev_t;
#endif
/* Generic disk information. */
typedef struct {
uint8_t type; /* Device type (ATA/ATAPI/SCSI/none/unknown). */
uint8_t device; /* Detected type of attached device (HD/CD/none). */
uint8_t removable; /* Removable device flag. */
uint8_t lock; /* Lock count for removable devices. */
//@todo: ATA specific - move?
uint8_t mode; /* Transfer mode: PIO 16/32 bits - IRQ - ISADMA - PCIDMA. */
uint8_t translation; /* Type of geometry translation. */
uint16_t blksize; /* Disk block size. */
chs_t lchs; /* Logical CHS geometry. */
chs_t pchs; /* Physical CHS geometry. */
uint64_t sectors; /* Total sector count. */
} disk_dev_t;
/* A structure for passing disk request information around. This structure
* is designed for saving stack space. As BIOS requests cannot be overlapped,
* one such structure is sufficient.
*/
typedef struct {
uint64_t lba; /* Starting LBA. */
void __far *buffer; /* Read/write data buffer pointer. */
uint8_t dev_id; /* Device ID; index into devices array. */
uint16_t nsect; /* Number of sectors to be transferred. */
uint16_t sect_sz; /* Size of a sector in bytes. */
uint16_t cylinder; /* Starting cylinder (CHS only). */
uint16_t head; /* Starting head (CHS only). */
uint16_t sector; /* Starting sector (CHS only). */
uint16_t trsfsectors; /* Actual sectors transferred. */
uint32_t trsfbytes; /* Actual bytes transferred. */
uint16_t skip_b; /* Bytes to skip before transfer. */
uint16_t skip_a; /* Bytes to skip after transfer. */
} disk_req_t;
extern uint16_t ahci_cmd_packet(uint16_t device_id, uint8_t cmdlen, char __far *cmdbuf,
uint16_t header, uint32_t length, uint8_t inout, char __far *buffer);
extern uint16_t scsi_cmd_packet(uint16_t device, uint8_t cmdlen, char __far *cmdbuf,
uint16_t header, uint32_t length, uint8_t inout, char __far *buffer);
extern uint16_t ata_cmd_packet(uint16_t device, uint8_t cmdlen, char __far *cmdbuf,
uint16_t header, uint32_t length, uint8_t inout, char __far *buffer);
extern uint16_t ata_soft_reset(uint16_t device);
/* All BIOS disk information. Disk-related code in the BIOS should not need
* anything outside of this structure.
*/
typedef struct {
disk_req_t drqp; /* Disk request packet. */
/* Bus-independent disk device information. */
disk_dev_t devices[BX_MAX_STORAGE_DEVICES];
uint8_t hdcount; /* Total number of BIOS disks. */
/* Map between (BIOS disk ID - 0x80) and ATA/SCSI/AHCI disks. */
uint8_t hdidmap[BX_MAX_STORAGE_DEVICES];
uint8_t cdcount; /* Number of CD-ROMs. */
/* Map between (BIOS CD-ROM ID - 0xE0) and ATA/SCSI/AHCI devices. */
uint8_t cdidmap[BX_MAX_STORAGE_DEVICES];
/* ATA bus-specific device information. */
ata_chan_t channels[BX_MAX_ATA_INTERFACES];
#ifdef VBOX_WITH_SCSI
/* SCSI bus-specific device information. */
scsi_dev_t scsidev[BX_MAX_SCSI_DEVICES];
uint8_t scsi_devcount; /* Number of SCSI devices. */
#endif
#ifdef VBOX_WITH_AHCI
/* SATA (AHCI) bus-specific device information. */
ahci_dev_t ahcidev[BX_MAX_AHCI_DEVICES];
uint8_t ahci_devcnt; /* Number of SATA devices. */
uint16_t ahci_seg; /* Segment of AHCI data block. */
#endif
dpte_t dpte; /* Buffer for building a DPTE. */
} bio_dsk_t;
#if BX_ELTORITO_BOOT
/* El Torito device emulation state. */
typedef struct {
uint8_t active;
uint8_t media;
uint8_t emulated_drive;
uint8_t controller_index;
uint16_t device_spec;
uint16_t buffer_segment;
uint32_t ilba;
uint16_t load_segment;
uint16_t sector_count;
chs_t vdevice; /* Virtual device geometry. */
} cdemu_t;
#endif
// for access to EBDA area
// The EBDA structure should conform to
// http://www.frontiernet.net/~fys/rombios.htm document
// I made the ata and cdemu structs begin at 0x121 in the EBDA seg
/* MS-DOS KEYB.COM may overwrite the word at offset 0x117 in the EBDA
* which contains the keyboard ID for PS/2 BIOSes.
*/
typedef struct {
uint8_t filler1[0x3D];
fdpt_t fdpt0; /* FDPTs for the first two ATA disks. */
fdpt_t fdpt1;
uint8_t filler2[0xC4];
bio_dsk_t bdisk; /* Disk driver data (ATA/SCSI/AHCI). */
#if BX_ELTORITO_BOOT
cdemu_t cdemu; /* El Torito floppy/HD emulation data. */
#endif
unsigned char uForceBootDrive;
unsigned char uForceBootDevice;
} ebda_data_t;
ct_assert(sizeof(ebda_data_t) < 0x380); /* Must be under 1K in size. */
// the last 16 bytes of the EBDA segment are used for the MPS floating
// pointer structure (though only if an I/O APIC is present)
#define EbdaData ((ebda_data_t *) 0)
/* Note: Using fastcall reduces stack usage a little. */
int __fastcall ata_read_sectors(bio_dsk_t __far *bios_dsk);
int __fastcall ata_write_sectors(bio_dsk_t __far *bios_dsk);
int __fastcall scsi_read_sectors(bio_dsk_t __far *bios_dsk);
int __fastcall scsi_write_sectors(bio_dsk_t __far *bios_dsk);
int __fastcall ahci_read_sectors(bio_dsk_t __far *bios_dsk);
int __fastcall ahci_write_sectors(bio_dsk_t __far *bios_dsk);
extern void set_geom_lba(chs_t __far *lgeo, uint64_t nsectors);
// @todo: put this elsewhere (and change/eliminate?)
#define SET_DISK_RET_STATUS(status) write_byte(0x0040, 0x0074, status)
#endif
|
00154419d809d1171eba68e61d23bd0bb6edb7d3
|
011e552512f45ca313615e428924d001a427e8e6
|
/vm/amap.c
|
bdf82735a320803246fa9f222830a80bb4ce81d7
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
phoenix-rtos/phoenix-rtos-kernel
|
3d4c1d0e7703ea5ce50c2642d35fbb79c1f2afd6
|
e15898bac82e168f7e6aaea60d413790a282f389
|
refs/heads/master
| 2023-09-01T15:04:26.226958
| 2023-09-01T09:21:17
| 2023-09-01T09:45:00
| 125,823,596
| 115
| 39
|
BSD-3-Clause
| 2023-09-14T13:34:22
| 2018-03-19T08:14:43
|
C
|
UTF-8
|
C
| false
| false
| 5,359
|
c
|
amap.c
|
/*
* Phoenix-RTOS
*
* Operating system kernel
*
* Virtual memory manager - amap abstraction
*
* Copyright 2017 Phoenix Systems
* Author: Pawel Pisarczyk, Jan Sikorski
*
* This file is part of Phoenix-RTOS.
*
* %LICENSE%
*/
#include "../hal/hal.h"
#include "../include/errno.h"
#include "../lib/lib.h"
#include "page.h"
#include "../proc/proc.h"
#include "amap.h"
#include "map.h"
struct {
vm_object_t *kernel;
vm_map_t *kmap;
} amap_common;
static anon_t *amap_putanon(anon_t *a)
{
if (a == NULL)
return NULL;
proc_lockSet(&a->lock);
if (--a->refs) {
proc_lockClear(&a->lock);
return a;
}
vm_pageFree(a->page);
proc_lockClear(&a->lock);
proc_lockDone(&a->lock);
vm_kfree(a);
return NULL;
}
void amap_putanons(amap_t *amap, int offset, int size)
{
int i;
if (amap == NULL)
return;
proc_lockSet(&amap->lock);
for (i = offset / SIZE_PAGE; i < (offset + size) / SIZE_PAGE; ++i)
amap_putanon(amap->anons[i]);
proc_lockClear(&amap->lock);
}
static anon_t *amap_getanon(anon_t *a)
{
if (a == NULL)
return NULL;
proc_lockSet(&a->lock);
++a->refs;
proc_lockClear(&a->lock);
return a;
}
void amap_getanons(amap_t *amap, int offset, int size)
{
int i;
if (amap == NULL)
return;
proc_lockSet(&amap->lock);
for (i = offset / SIZE_PAGE; i < (offset + size) / SIZE_PAGE; ++i)
amap_getanon(amap->anons[i]);
proc_lockClear(&amap->lock);
}
amap_t *amap_ref(amap_t *amap)
{
if (amap == NULL)
return NULL;
proc_lockSet(&amap->lock);
amap->refs++;
proc_lockClear(&amap->lock);
return amap;
}
amap_t *amap_create(amap_t *amap, int *offset, size_t size)
{
int i = size / SIZE_PAGE;
amap_t *new;
if (amap != NULL) {
proc_lockSet(&amap->lock);
if (amap->refs == 1) {
proc_lockClear(&amap->lock);
return amap;
}
amap->refs--;
}
/* Allocate anon pointer arrays in chunks
* to facilitate merging of amaps */
if (i < (512 - sizeof(amap_t)) / sizeof(anon_t *))
i = (512 - sizeof(amap_t)) / sizeof(anon_t *);
if ((new = vm_kmalloc(sizeof(amap_t) + i * sizeof(anon_t *))) == NULL) {
if (amap != NULL)
proc_lockClear(&amap->lock);
return NULL;
}
proc_lockInit(&new->lock, "amap.map");
new->size = i;
new->refs = 1;
*offset = *offset / SIZE_PAGE;
for (i = 0; i < size / SIZE_PAGE; ++i)
new->anons[i] = (amap == NULL) ? NULL : amap->anons[*offset + i];
while (i < new->size)
new->anons[i++] = NULL;
if (amap != NULL)
proc_lockClear(&amap->lock);
*offset = 0;
return new;
}
void amap_put(amap_t *amap)
{
if (amap == NULL)
return;
proc_lockSet(&amap->lock);
if (--amap->refs) {
proc_lockClear(&amap->lock);
return;
}
proc_lockDone(&amap->lock);
vm_kfree(amap);
}
void amap_clear(amap_t *amap, size_t offset, size_t size)
{
int i;
proc_lockSet(&amap->lock);
for (i = offset / SIZE_PAGE; i < (offset + size) / SIZE_PAGE; i++)
amap->anons[i] = NULL;
proc_lockClear(&amap->lock);
}
static anon_t *anon_new(page_t *p)
{
anon_t *a;
if ((a = vm_kmalloc(sizeof(anon_t))) == NULL)
return NULL;
a->page = p;
a->refs = 1;
proc_lockInit(&a->lock, "amap.anon");
return a;
}
static void *amap_map(vm_map_t *map, page_t *p)
{
if (map == amap_common.kmap)
return _vm_mmap(amap_common.kmap, NULL, p, SIZE_PAGE, PROT_READ | PROT_WRITE, amap_common.kernel, -1, MAP_NONE);
return vm_mmap(amap_common.kmap, NULL, p, SIZE_PAGE, PROT_READ | PROT_WRITE, amap_common.kernel, -1, MAP_NONE);
}
static int amap_unmap(vm_map_t *map, void *v)
{
if (map == amap_common.kmap)
return _vm_munmap(amap_common.kmap, v, SIZE_PAGE);
return vm_munmap(amap_common.kmap, v, SIZE_PAGE);
}
page_t *amap_page(vm_map_t *map, amap_t *amap, vm_object_t *o, void *vaddr, int aoffs, offs_t offs, int prot)
{
page_t *p = NULL;
anon_t *a;
void *v, *w;
proc_lockSet(&amap->lock);
if ((a = amap->anons[aoffs / SIZE_PAGE]) != NULL) {
proc_lockSet(&a->lock);
p = a->page;
if (!(a->refs > 1 && (prot & PROT_WRITE))) {
proc_lockClear(&a->lock);
proc_lockClear(&amap->lock);
return p;
}
a->refs--;
}
else if ((p = vm_objectPage(map, &amap, o, vaddr, offs)) == NULL) {
/* amap could be invalidated while fetching from the object's store */
if (amap != NULL)
proc_lockClear(&amap->lock);
return NULL;
}
else if (o != NULL && !(prot & PROT_WRITE)) {
proc_lockClear(&amap->lock);
return p;
}
if ((v = amap_map(map, p)) == NULL) {
if (a != NULL) {
proc_lockClear(&a->lock);
}
proc_lockClear(&amap->lock);
return NULL;
}
if (a != NULL || o != NULL) {
/* Copy from object or shared anon */
if ((p = vm_pageAlloc(SIZE_PAGE, PAGE_OWNER_APP)) == NULL) {
amap_unmap(map, v);
if (a != NULL) {
proc_lockClear(&a->lock);
}
proc_lockClear(&amap->lock);
return NULL;
}
if ((w = amap_map(map, p)) == NULL) {
vm_pageFree(p);
amap_unmap(map, v);
if (a != NULL) {
proc_lockClear(&a->lock);
}
proc_lockClear(&amap->lock);
return NULL;
}
hal_memcpy(w, v, SIZE_PAGE);
amap_unmap(map, w);
}
else {
hal_memset(v, 0, SIZE_PAGE);
}
amap_unmap(map, v);
if (a != NULL) {
proc_lockClear(&a->lock);
}
if ((amap->anons[aoffs / SIZE_PAGE] = anon_new(p)) == NULL) {
vm_pageFree(p);
p = NULL;
}
proc_lockClear(&amap->lock);
return p;
}
void _amap_init(vm_map_t *kmap, vm_object_t *kernel)
{
amap_common.kmap = kmap;
amap_common.kernel = kernel;
}
|
4523ee01487962845fb87633a5b1c3ddac006bbf
|
afd2087e80478010d9df66e78280f75e1ff17d45
|
/c10/util/win32-headers.h
|
6a3e8bc2caf42f02fba1925970dd33770a40abfa
|
[
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-secret-labs-2011",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0"
] |
permissive
|
pytorch/pytorch
|
7521ac50c47d18b916ae47a6592c4646c2cb69b5
|
a6f7dd4707ac116c0f5fb5f44f42429f38d23ab4
|
refs/heads/main
| 2023-08-03T05:05:02.822937
| 2023-08-03T00:40:33
| 2023-08-03T04:14:52
| 65,600,975
| 77,092
| 24,610
|
NOASSERTION
| 2023-09-14T21:58:39
| 2016-08-13T05:26:41
|
Python
|
UTF-8
|
C
| false
| false
| 858
|
h
|
win32-headers.h
|
#pragma once
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef NOKERNEL
#define NOKERNEL
#endif
#ifndef NOUSER
#define NOUSER
#endif
#ifndef NOSERVICE
#define NOSERVICE
#endif
#ifndef NOSOUND
#define NOSOUND
#endif
#ifndef NOMCX
#define NOMCX
#endif
#ifndef NOGDI
#define NOGDI
#endif
#ifndef NOMSG
#define NOMSG
#endif
#ifndef NOMB
#define NOMB
#endif
#ifndef NOCLIPBOARD
#define NOCLIPBOARD
#endif
// dbghelp seems to require windows.h.
// clang-format off
#include <windows.h>
#include <dbghelp.h>
// clang-format on
#undef VOID
#undef DELETE
#undef IN
#undef THIS
#undef CONST
#undef NAN
#undef UNKNOWN
#undef NONE
#undef ANY
#undef IGNORE
#undef STRICT
#undef GetObject
#undef CreateSemaphore
#undef Yield
#undef RotateRight32
#undef RotateLeft32
#undef RotateRight64
#undef RotateLeft64
|
e46909c9b6b8f58aa9d652693344739711ac06f9
|
5ab69c8644a936a3d9dec1669a86c7369c911bf8
|
/examples/platform-specific/cc2538-common/crypto/cbc-mac-test.c
|
3193f9394cca419dd98c743fa9d422089285157c
|
[
"BSD-3-Clause"
] |
permissive
|
contiki-ng/contiki-ng
|
393d36f68b98f5ee3544ea32502cf662ffb2fe9f
|
31fcaadf7a0dc8ceea07f438cd69db73174879e6
|
refs/heads/develop
| 2023-09-01T20:10:30.000765
| 2023-09-01T14:37:12
| 2023-09-01T14:37:12
| 91,191,972
| 1,242
| 788
|
BSD-3-Clause
| 2023-09-14T19:08:35
| 2017-05-13T17:37:59
|
C
|
UTF-8
|
C
| false
| false
| 22,356
|
c
|
cbc-mac-test.c
|
/*
* Copyright (c) 2016, Benoît Thébaudeau <benoit.thebaudeau.dev@gmail.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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 copyright holder 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.
*/
/**
* \addtogroup cc2538-examples
* @{
*
* \defgroup cc2538-cbc-mac-test cc2538 AES-CBC-MAC Test Project
*
* AES-CBC-MAC access example for CC2538-based platforms
*
* This example shows how AES-CBC-MAC should be used. The example also
* verifies the AES-CBC-MAC functionality.
*
* @{
*
* \file
* Example demonstrating AES-CBC-MAC
*/
#include "contiki.h"
#include "sys/rtimer.h"
#include "dev/rom-util.h"
#include "dev/cbc-mac.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
/*---------------------------------------------------------------------------*/
#define MDATA_MAX_LEN 160
/*---------------------------------------------------------------------------*/
PROCESS(cbc_mac_test_process, "cbc_mac test process");
AUTOSTART_PROCESSES(&cbc_mac_test_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(cbc_mac_test_process, ev, data)
{
static const char *const str_res[] = {
"success",
"invalid param",
"NULL error",
"resource in use",
"DMA bus error",
"keystore read error",
"keystore write error",
"authentication failed"
};
static const uint8_t keys128[][128 / 8] = {
{ 0x1f, 0x8e, 0x49, 0x73, 0x95, 0x3f, 0x3f, 0xb0,
0xbd, 0x6b, 0x16, 0x66, 0x2e, 0x9a, 0x3c, 0x17 },
{ 0xb7, 0xf3, 0xc9, 0x57, 0x6e, 0x12, 0xdd, 0x0d,
0xb6, 0x3e, 0x8f, 0x8f, 0xac, 0x2b, 0x9a, 0x39 },
{ 0x89, 0xa5, 0x53, 0x73, 0x04, 0x33, 0xf7, 0xe6,
0xd6, 0x7d, 0x16, 0xd3, 0x73, 0xbd, 0x53, 0x60 },
{ 0x2c, 0x14, 0x41, 0x37, 0x51, 0xc3, 0x1e, 0x27,
0x30, 0x57, 0x0b, 0xa3, 0x36, 0x1c, 0x78, 0x6b },
{ 0x6a, 0x70, 0x82, 0xcf, 0x8c, 0xda, 0x13, 0xef,
0xf4, 0x8c, 0x81, 0x58, 0xdd, 0xa2, 0x06, 0xae },
{ 0x7b, 0x1a, 0xb9, 0x14, 0x4b, 0x02, 0x39, 0x31,
0x5c, 0xd5, 0xee, 0xc6, 0xc7, 0x56, 0x63, 0xbd },
{ 0xba, 0xb0, 0xcc, 0xed, 0xdc, 0x0a, 0xbd, 0x63,
0xe3, 0xf8, 0x2e, 0x9f, 0xbf, 0xf7, 0xb8, 0xaa },
{ 0x97, 0xa1, 0x02, 0x55, 0x29, 0xb9, 0x92, 0x5e,
0x25, 0xbb, 0xe7, 0x87, 0x70, 0xca, 0x2f, 0x99 }
};
static const uint8_t keys192[][192 / 8] = {
{ 0xba, 0x75, 0xf4, 0xd1, 0xd9, 0xd7, 0xcf, 0x7f,
0x55, 0x14, 0x45, 0xd5, 0x6c, 0xc1, 0xa8, 0xab,
0x2a, 0x07, 0x8e, 0x15, 0xe0, 0x49, 0xdc, 0x2c },
{ 0x16, 0x2a, 0xd5, 0x0e, 0xe6, 0x4a, 0x07, 0x02,
0xaa, 0x55, 0x1f, 0x57, 0x1d, 0xed, 0xc1, 0x6b,
0x2c, 0x1b, 0x6a, 0x1e, 0x4d, 0x4b, 0x5e, 0xee },
{ 0x8e, 0x27, 0x40, 0xfb, 0xa1, 0x57, 0xae, 0xf2,
0x42, 0x2e, 0x44, 0x23, 0x12, 0xd1, 0x5c, 0x14,
0xd3, 0x12, 0x55, 0x36, 0x84, 0xfc, 0xdc, 0x15 },
{ 0x50, 0x9b, 0xaf, 0x46, 0xfb, 0x9d, 0xe3, 0x42,
0x81, 0xda, 0xfc, 0xc3, 0xdb, 0x79, 0x59, 0x3b,
0xff, 0xa8, 0x42, 0x69, 0x04, 0x30, 0x26, 0x88 }
};
static const uint8_t keys256[][256 / 8] = {
{ 0x6e, 0xd7, 0x6d, 0x2d, 0x97, 0xc6, 0x9f, 0xd1,
0x33, 0x95, 0x89, 0x52, 0x39, 0x31, 0xf2, 0xa6,
0xcf, 0xf5, 0x54, 0xb1, 0x5f, 0x73, 0x8f, 0x21,
0xec, 0x72, 0xdd, 0x97, 0xa7, 0x33, 0x09, 0x07 },
{ 0x48, 0xbe, 0x59, 0x7e, 0x63, 0x2c, 0x16, 0x77,
0x23, 0x24, 0xc8, 0xd3, 0xfa, 0x1d, 0x9c, 0x5a,
0x9e, 0xcd, 0x01, 0x0f, 0x14, 0xec, 0x5d, 0x11,
0x0d, 0x3b, 0xfe, 0xc3, 0x76, 0xc5, 0x53, 0x2b },
{ 0x43, 0xe9, 0x53, 0xb2, 0xae, 0xa0, 0x8a, 0x3a,
0xd5, 0x2d, 0x18, 0x2f, 0x58, 0xc7, 0x2b, 0x9c,
0x60, 0xfb, 0xe4, 0xa9, 0xca, 0x46, 0xa3, 0xcb,
0x89, 0xe3, 0x86, 0x38, 0x45, 0xe2, 0x2c, 0x9e },
{ 0x87, 0x72, 0x5b, 0xd4, 0x3a, 0x45, 0x60, 0x88,
0x14, 0x18, 0x07, 0x73, 0xf0, 0xe7, 0xab, 0x95,
0xa3, 0xc8, 0x59, 0xd8, 0x3a, 0x21, 0x30, 0xe8,
0x84, 0x19, 0x0e, 0x44, 0xd1, 0x4c, 0x69, 0x96 }
};
static const struct {
const void *keys;
uint8_t key_size;
uint8_t count;
} keys[] = {
{ keys128, AES_KEY_STORE_SIZE_KEY_SIZE_128,
sizeof(keys128) / sizeof(keys128[0]) },
{ keys192, AES_KEY_STORE_SIZE_KEY_SIZE_192,
sizeof(keys192) / sizeof(keys192[0]) },
{ keys256, AES_KEY_STORE_SIZE_KEY_SIZE_256,
sizeof(keys256) / sizeof(keys256[0]) }
};
static const struct {
uint8_t key_size_index;
uint8_t key_area;
uint8_t mdata[MDATA_MAX_LEN];
uint16_t mdata_len;
uint8_t mac[CBC_MAC_MAC_LEN];
} vectors[] = {
{
0, /* key_size_index */
0, /* key_area */
{ 0x45, 0xcf, 0x12, 0x96, 0x4f, 0xc8, 0x24, 0xab,
0x76, 0x61, 0x6a, 0xe2, 0xf4, 0xbf, 0x08, 0x22 }, /* mdata */
16, /* mdata_len */
{ 0x97, 0x67, 0x0c, 0x83, 0x99, 0x24, 0xa4, 0xc6,
0x15, 0xb0, 0xf6, 0x14, 0xae, 0x75, 0xa8, 0x69 } /* mac */
}, {
0, /* key_size_index */
1, /* key_area */
{ 0x9a, 0xc1, 0x99, 0x54, 0xce, 0x13, 0x19, 0xb3,
0x54, 0xd3, 0x22, 0x04, 0x60, 0xf7, 0x1c, 0x1e,
0x37, 0x3f, 0x1c, 0xd3, 0x36, 0x24, 0x08, 0x81,
0x16, 0x0c, 0xfd, 0xe4, 0x6e, 0xbf, 0xed, 0x2e,
0x79, 0x1e, 0x8d, 0x5a, 0x1a, 0x13, 0x6e, 0xbd,
0x1d, 0xc4, 0x69, 0xde, 0xc0, 0x0c, 0x41, 0x87,
0x72, 0x2b, 0x84, 0x1c, 0xda, 0xbc, 0xb2, 0x2c,
0x1b, 0xe8, 0xa1, 0x46, 0x57, 0xda, 0x20, 0x0e }, /* mdata */
64, /* mdata_len */
{ 0x9d, 0x15, 0xb9, 0xfb, 0xff, 0xe2, 0x32, 0x97,
0x56, 0x36, 0x36, 0x6d, 0x13, 0x65, 0x78, 0xb5 } /* mac */
}, {
0, /* key_size_index */
2, /* key_area */
{ 0x80, 0x7b, 0xc4, 0xea, 0x68, 0x4e, 0xed, 0xcf,
0xdc, 0xca, 0x30, 0x18, 0x06, 0x80, 0xb0, 0xf1,
0xae, 0x28, 0x14, 0xf3, 0x5f, 0x36, 0xd0, 0x53,
0xc5, 0xae, 0xa6, 0x59, 0x5a, 0x38, 0x6c, 0x14,
0x42, 0x77, 0x0f, 0x4d, 0x72, 0x97, 0xd8, 0xb9,
0x18, 0x25, 0xee, 0x72, 0x37, 0x24, 0x1d, 0xa8,
0x92, 0x5d, 0xd5, 0x94, 0xcc, 0xf6, 0x76, 0xae,
0xcd, 0x46, 0xca, 0x20, 0x68, 0xe8, 0xd3, 0x7a,
0x3a, 0x0e, 0xc8, 0xa7, 0xd5, 0x18, 0x5a, 0x20,
0x1e, 0x66, 0x3b, 0x5f, 0xf3, 0x6a, 0xe1, 0x97,
0x11, 0x01, 0x88, 0xa2, 0x35, 0x03, 0x76, 0x3b,
0x82, 0x18, 0x82, 0x6d, 0x23, 0xce, 0xd7, 0x4b,
0x31, 0xe9, 0xf6, 0xe2, 0xd7, 0xfb, 0xfa, 0x6c,
0xb4, 0x34, 0x20, 0xc7, 0x80, 0x7a, 0x86, 0x25 }, /* mdata */
112, /* mdata_len */
{ 0x5f, 0x4f, 0x06, 0xe0, 0x62, 0x65, 0xf2, 0xeb,
0x16, 0x1c, 0xda, 0x9f, 0x30, 0xe9, 0x79, 0x53 } /* mac */
}, {
0, /* key_size_index */
3, /* key_area */
{ 0x40, 0xd9, 0x30, 0xf9, 0xa0, 0x53, 0x34, 0xd9,
0x81, 0x6f, 0xe2, 0x04, 0x99, 0x9c, 0x3f, 0x82,
0xa0, 0x3f, 0x6a, 0x04, 0x57, 0xa8, 0xc4, 0x75,
0xc9, 0x45, 0x53, 0xd1, 0xd1, 0x16, 0x69, 0x3a,
0xdc, 0x61, 0x80, 0x49, 0xf0, 0xa7, 0x69, 0xa2,
0xee, 0xd6, 0xa6, 0xcb, 0x14, 0xc0, 0x14, 0x3e,
0xc5, 0xcc, 0xcd, 0xbc, 0x8d, 0xec, 0x4c, 0xe5,
0x60, 0xcf, 0xd2, 0x06, 0x22, 0x57, 0x09, 0x32,
0x6d, 0x4d, 0xe7, 0x94, 0x8e, 0x54, 0xd6, 0x03,
0xd0, 0x1b, 0x12, 0xd7, 0xfe, 0xd7, 0x52, 0xfb,
0x23, 0xf1, 0xaa, 0x44, 0x94, 0xfb, 0xb0, 0x01,
0x30, 0xe9, 0xde, 0xd4, 0xe7, 0x7e, 0x37, 0xc0,
0x79, 0x04, 0x2d, 0x82, 0x80, 0x40, 0xc3, 0x25,
0xb1, 0xa5, 0xef, 0xd1, 0x5f, 0xc8, 0x42, 0xe4,
0x40, 0x14, 0xca, 0x43, 0x74, 0xbf, 0x38, 0xf3,
0xc3, 0xfc, 0x3e, 0xe3, 0x27, 0x73, 0x3b, 0x0c,
0x8a, 0xee, 0x1a, 0xbc, 0xd0, 0x55, 0x77, 0x2f,
0x18, 0xdc, 0x04, 0x60, 0x3f, 0x7b, 0x2c, 0x1e,
0xa6, 0x9f, 0xf6, 0x62, 0x36, 0x1f, 0x2b, 0xe0,
0xa1, 0x71, 0xbb, 0xdc, 0xea, 0x1e, 0x5d, 0x3f }, /* mdata */
160, /* mdata_len */
{ 0xda, 0x15, 0x2d, 0xf1, 0xf5, 0x6a, 0x44, 0x0e,
0x1c, 0x7e, 0x27, 0x80, 0xed, 0x87, 0xd9, 0x3d } /* mac */
}, {
0, /* key_size_index */
4, /* key_area */
{ 0xf8, 0xeb, 0x31, 0xb3, 0x1e, 0x37, 0x4e, 0x96,
0x00, 0x30, 0xcd, 0x1c, 0xad, 0xb0, 0xef, 0x0c }, /* mdata */
16, /* mdata_len */
{ 0x11, 0x0b, 0x18, 0xdb, 0xe0, 0x97, 0x56, 0x39,
0xf7, 0x1d, 0x87, 0x7d, 0x6d, 0x07, 0x27, 0x55 } /* mac */
}, {
0, /* key_size_index */
5, /* key_area */
{ 0xd3, 0xf8, 0x9b, 0x71, 0xe0, 0x33, 0x07, 0x0f,
0x9d, 0x75, 0x16, 0xa6, 0xcb, 0x4e, 0xa5, 0xef,
0x51, 0xd6, 0xfb, 0x63, 0xd4, 0xf0, 0xfe, 0xa0,
0x89, 0xd0, 0xa6, 0x0e, 0x47, 0xbb, 0xb3, 0xc2,
0xe1, 0x0e, 0x9b, 0xa3, 0xb2, 0x82, 0xc7, 0xcb,
0x79, 0xae, 0xfe, 0x30, 0x68, 0xce, 0x22, 0x83,
0x77, 0xc2, 0x1a, 0x58, 0xfe, 0x5a, 0x0f, 0x88,
0x83, 0xd0, 0xdb, 0xd3, 0xd0, 0x96, 0xbe, 0xca }, /* mdata */
64, /* mdata_len */
{ 0x6d, 0x91, 0x75, 0x52, 0x10, 0xcc, 0x69, 0x4a,
0xde, 0x6c, 0xf6, 0xa0, 0xcd, 0x2d, 0x51, 0x8e } /* mac */
}, {
0, /* key_size_index */
6, /* key_area */
{ 0xc6, 0x5b, 0x94, 0xb1, 0xf2, 0x91, 0xfa, 0x9f,
0x06, 0x00, 0xf2, 0x2c, 0x3c, 0x04, 0x32, 0xc8,
0x95, 0xad, 0x5d, 0x17, 0x7b, 0xcc, 0xcc, 0x9e,
0xa4, 0x4e, 0x8e, 0xc3, 0x39, 0xc9, 0xad, 0xf4,
0x38, 0x55, 0xb3, 0x26, 0x17, 0x9d, 0x6d, 0x81,
0xaa, 0x36, 0xef, 0x59, 0x46, 0x2f, 0xd8, 0x61,
0x27, 0xe9, 0xd8, 0x1b, 0x0f, 0x28, 0x6f, 0x93,
0x30, 0x6b, 0xf7, 0x4d, 0x4c, 0x79, 0xe4, 0x7c,
0x1b, 0x3d, 0x4b, 0x74, 0xed, 0xd3, 0xa1, 0x62,
0x90, 0xe3, 0xc6, 0x3b, 0x74, 0x2e, 0x41, 0xf2,
0x0d, 0x66, 0xce, 0xee, 0x79, 0x43, 0x16, 0xbb,
0x63, 0xd3, 0xbd, 0x00, 0x27, 0x12, 0xa1, 0xb1,
0x36, 0xba, 0x61, 0x85, 0xbd, 0x5c, 0x1d, 0xab,
0x81, 0xb0, 0x7d, 0xb9, 0x0d, 0x2a, 0xf5, 0xe5 }, /* mdata */
112, /* mdata_len */
{ 0x47, 0x12, 0x32, 0xdc, 0x47, 0xca, 0x7e, 0xe2,
0xd8, 0xd6, 0x43, 0x6c, 0xe5, 0x75, 0x03, 0xb9 } /* mac */
}, {
0, /* key_size_index */
7, /* key_area */
{ 0x22, 0xcd, 0xc3, 0x30, 0x6f, 0xcd, 0x4d, 0x31,
0xcc, 0xd3, 0x27, 0x20, 0xcb, 0xb6, 0x1b, 0xad,
0x28, 0xd8, 0x55, 0x67, 0x06, 0x57, 0xc4, 0x8c,
0x7b, 0x88, 0xc3, 0x1f, 0x4f, 0xa1, 0xf9, 0x3c,
0x01, 0xb5, 0x7d, 0xa9, 0x0b, 0xe6, 0x3e, 0xad,
0x67, 0xd6, 0xa3, 0x25, 0x52, 0x5e, 0x6e, 0xd4,
0x50, 0x83, 0xe6, 0xfb, 0x70, 0xa5, 0x35, 0x29,
0xd1, 0xfa, 0x0f, 0x55, 0x65, 0x3b, 0x94, 0x2a,
0xf5, 0x9d, 0x78, 0xa2, 0x66, 0x03, 0x61, 0xd6,
0x3a, 0x72, 0x90, 0x15, 0x5a, 0xc5, 0xc4, 0x33,
0x12, 0xa2, 0x5b, 0x23, 0x5d, 0xac, 0xbb, 0xc8,
0x63, 0xfa, 0xf0, 0x09, 0x40, 0xc9, 0x96, 0x24,
0x07, 0x6d, 0xfa, 0x44, 0x06, 0x8e, 0x7c, 0x55,
0x4c, 0x90, 0x38, 0x17, 0x69, 0x53, 0xe5, 0x71,
0x75, 0x1d, 0xfc, 0x09, 0x54, 0xd4, 0x1d, 0x11,
0x37, 0x71, 0xb0, 0x64, 0x66, 0xb1, 0xc8, 0xd1,
0x3e, 0x0d, 0x4c, 0xb6, 0x75, 0xed, 0x58, 0xd1,
0xa6, 0x19, 0xe1, 0x54, 0x09, 0x70, 0x98, 0x37,
0x81, 0xdc, 0x11, 0xd2, 0xdd, 0x85, 0x25, 0xab,
0x57, 0x45, 0x95, 0x8d, 0x61, 0x5d, 0xef, 0xda }, /* mdata */
160, /* mdata_len */
{ 0xe9, 0xae, 0x7e, 0x63, 0x54, 0x23, 0xc3, 0x66,
0xd5, 0x23, 0xf9, 0x7c, 0x0e, 0xdb, 0x18, 0xb0 } /* mac */
}, {
1, /* key_size_index */
0, /* key_area */
{ 0xc5, 0x1f, 0xc2, 0x76, 0x77, 0x4d, 0xad, 0x94,
0xbc, 0xdc, 0x1d, 0x28, 0x91, 0xec, 0x86, 0x68 }, /* mdata */
16, /* mdata_len */
{ 0x40, 0xd1, 0x7f, 0x9a, 0x6f, 0x5b, 0xc6, 0xaf,
0x34, 0x1e, 0x6a, 0xc5, 0xe4, 0x9e, 0x71, 0xad } /* mac */
}, {
1, /* key_size_index */
2, /* key_area */
{ 0xbe, 0x8a, 0xbf, 0x00, 0x90, 0x13, 0x63, 0x98,
0x7a, 0x82, 0xcc, 0x77, 0xd0, 0xec, 0x91, 0x69,
0x7b, 0xa3, 0x85, 0x7f, 0x9e, 0x4f, 0x84, 0xbd,
0x79, 0x40, 0x6c, 0x13, 0x8d, 0x02, 0x69, 0x8f,
0x00, 0x32, 0x76, 0xd0, 0x44, 0x91, 0x20, 0xbe,
0xf4, 0x57, 0x8d, 0x78, 0xfe, 0xca, 0xbe, 0x8e,
0x07, 0x0e, 0x11, 0x71, 0x0b, 0x3f, 0x0a, 0x27,
0x44, 0xbd, 0x52, 0x43, 0x4e, 0xc7, 0x00, 0x15,
0x88, 0x4c, 0x18, 0x1e, 0xbd, 0xfd, 0x51, 0xc6,
0x04, 0xa7, 0x1c, 0x52, 0xe4, 0xc0, 0xe1, 0x10,
0xbc, 0x40, 0x8c, 0xd4, 0x62, 0xb2, 0x48, 0xa8,
0x0b, 0x8a, 0x8a, 0xc0, 0x6b, 0xb9, 0x52, 0xac,
0x1d, 0x7f, 0xae, 0xd1, 0x44, 0x80, 0x7f, 0x1a,
0x73, 0x1b, 0x7f, 0xeb, 0xca, 0xf7, 0x83, 0x57,
0x62, 0xde, 0xfe, 0x92, 0xec, 0xcf, 0xc7, 0xa9,
0x94, 0x4e, 0x1c, 0x70, 0x2c, 0xff, 0xe6, 0xbc,
0x86, 0x73, 0x3e, 0xd3, 0x21, 0x42, 0x31, 0x21,
0x08, 0x5a, 0xc0, 0x2d, 0xf8, 0x96, 0x2b, 0xcb,
0xc1, 0x93, 0x70, 0x92, 0xee, 0xbf, 0x0e, 0x90,
0xa8, 0xb2, 0x0e, 0x3d, 0xd8, 0xc2, 0x44, 0xae }, /* mdata */
160, /* mdata_len */
{ 0xea, 0x57, 0x08, 0xb7, 0x8b, 0xf0, 0x51, 0xd6,
0x94, 0xeb, 0x37, 0x01, 0xca, 0x6b, 0xd5, 0x7b } /* mac */
}, {
1, /* key_size_index */
4, /* key_area */
{ 0x39, 0xa9, 0xb4, 0x2d, 0xe1, 0x9e, 0x51, 0x2a,
0xb7, 0xf3, 0x04, 0x35, 0x64, 0xc3, 0x51, 0x5a }, /* mdata */
16, /* mdata_len */
{ 0xa8, 0xd9, 0x3d, 0x9e, 0x1c, 0x14, 0xe4, 0x1e,
0xa3, 0xf0, 0xaa, 0x50, 0xa4, 0xa3, 0x26, 0x09 } /* mac */
}, {
1, /* key_size_index */
6, /* key_area */
{ 0x69, 0x28, 0x29, 0x9c, 0x52, 0xb4, 0xf0, 0x47,
0x92, 0x6f, 0x8a, 0x54, 0x15, 0x29, 0xda, 0x2d,
0x6b, 0xba, 0xa3, 0x99, 0x14, 0x3c, 0xed, 0x8e,
0xfb, 0x77, 0xab, 0x47, 0x40, 0x9d, 0x9a, 0x95,
0x3a, 0x38, 0x6c, 0x7a, 0xbd, 0x60, 0x26, 0xf4,
0x98, 0x31, 0xc7, 0x17, 0x62, 0x7c, 0x2a, 0x5e,
0x77, 0xbd, 0x2d, 0x43, 0x3d, 0x4d, 0x13, 0x0d,
0xac, 0xd9, 0x27, 0xea, 0x0d, 0x13, 0xa2, 0x3d,
0x01, 0xa7, 0xcf, 0x39, 0xc6, 0x71, 0x6d, 0xaf,
0xb6, 0xed, 0x55, 0x24, 0x10, 0xef, 0x5d, 0x27,
0xfb, 0x94, 0x7b, 0xe2, 0xc8, 0x78, 0x2e, 0xee,
0x78, 0x29, 0x19, 0x6c, 0x7e, 0xdc, 0xf1, 0x51,
0xc6, 0x5f, 0x9a, 0x01, 0xf5, 0x4f, 0x8d, 0x20,
0xf3, 0x8b, 0x7d, 0xa4, 0xa7, 0xe8, 0x3a, 0x2f,
0x01, 0x27, 0xd5, 0x9d, 0x3e, 0x24, 0x05, 0xd8,
0x67, 0x4f, 0xc9, 0xf4, 0x1b, 0x60, 0x4f, 0x78,
0x8f, 0x47, 0x15, 0xf9, 0xd3, 0x62, 0x4e, 0xee,
0x57, 0xf3, 0x87, 0xbf, 0xad, 0xd1, 0x8a, 0x1f,
0x90, 0x5e, 0x83, 0x9c, 0x26, 0xb8, 0x61, 0x74,
0x82, 0x34, 0x7f, 0xab, 0x6d, 0x08, 0x84, 0x5a }, /* mdata */
160, /* mdata_len */
{ 0x69, 0x27, 0xe7, 0xfb, 0x4c, 0xb9, 0x9d, 0x9c,
0x54, 0xe2, 0x7f, 0x1c, 0x76, 0x20, 0xa0, 0x07 } /* mac */
}, {
2, /* key_size_index */
0, /* key_area */
{ 0x62, 0x82, 0xb8, 0xc0, 0x5c, 0x5c, 0x15, 0x30,
0xb9, 0x7d, 0x48, 0x16, 0xca, 0x43, 0x47, 0x62 }, /* mdata */
16, /* mdata_len */
{ 0xa1, 0x07, 0x61, 0x82, 0xc1, 0xf4, 0x33, 0xc3,
0xda, 0xfb, 0xe1, 0x1d, 0x3e, 0x71, 0xdd, 0x8a } /* mac */
}, {
2, /* key_size_index */
2, /* key_area */
{ 0x0c, 0x63, 0xd4, 0x13, 0xd3, 0x86, 0x45, 0x70,
0xe7, 0x0b, 0xb6, 0x61, 0x8b, 0xf8, 0xa4, 0xb9,
0x58, 0x55, 0x86, 0x68, 0x8c, 0x32, 0xbb, 0xa0,
0xa5, 0xec, 0xc1, 0x36, 0x2f, 0xad, 0xa7, 0x4a,
0xda, 0x32, 0xc5, 0x2a, 0xcf, 0xd1, 0xaa, 0x74,
0x44, 0xba, 0x56, 0x7b, 0x4e, 0x7d, 0xaa, 0xec,
0xf7, 0xcc, 0x1c, 0xb2, 0x91, 0x82, 0xaf, 0x16,
0x4a, 0xe5, 0x23, 0x2b, 0x00, 0x28, 0x68, 0x69,
0x56, 0x35, 0x59, 0x98, 0x07, 0xa9, 0xa7, 0xf0,
0x7a, 0x1f, 0x13, 0x7e, 0x97, 0xb1, 0xe1, 0xc9,
0xda, 0xbc, 0x89, 0xb6, 0xa5, 0xe4, 0xaf, 0xa9,
0xdb, 0x58, 0x55, 0xed, 0xaa, 0x57, 0x50, 0x56,
0xa8, 0xf4, 0xf8, 0x24, 0x22, 0x16, 0x24, 0x2b,
0xb0, 0xc2, 0x56, 0x31, 0x0d, 0x9d, 0x32, 0x98,
0x26, 0xac, 0x35, 0x3d, 0x71, 0x5f, 0xa3, 0x9f,
0x80, 0xce, 0xc1, 0x44, 0xd6, 0x42, 0x45, 0x58,
0xf9, 0xf7, 0x0b, 0x98, 0xc9, 0x20, 0x09, 0x6e,
0x0f, 0x2c, 0x85, 0x5d, 0x59, 0x48, 0x85, 0xa0,
0x06, 0x25, 0x88, 0x0e, 0x9d, 0xfb, 0x73, 0x41,
0x63, 0xce, 0xce, 0xf7, 0x2c, 0xf0, 0x30, 0xb8 }, /* mdata */
160, /* mdata_len */
{ 0xf2, 0xb7, 0x45, 0x13, 0xd6, 0xcf, 0x2d, 0x80,
0xe6, 0x72, 0xb8, 0x37, 0x45, 0xfa, 0xdc, 0x0f } /* mac */
}, {
2, /* key_size_index */
4, /* key_area */
{ 0xd5, 0x1d, 0x19, 0xde, 0xd5, 0xca, 0x4a, 0xe1,
0x4b, 0x2b, 0x20, 0xb0, 0x27, 0xff, 0xb0, 0x20 }, /* mdata */
16, /* mdata_len */
{ 0xb0, 0x52, 0xa1, 0xdf, 0xe6, 0xa4, 0x8e, 0x63,
0x43, 0x23, 0xdc, 0xaa, 0x85, 0xfa, 0xda, 0x3c } /* mac */
}, {
2, /* key_size_index */
6, /* key_area */
{ 0x5b, 0x97, 0xa9, 0xd4, 0x23, 0xf4, 0xb9, 0x74,
0x13, 0xf3, 0x88, 0xd9, 0xa3, 0x41, 0xe7, 0x27,
0xbb, 0x33, 0x9f, 0x8e, 0x18, 0xa3, 0xfa, 0xc2,
0xf2, 0xfb, 0x85, 0xab, 0xdc, 0x8f, 0x13, 0x5d,
0xeb, 0x30, 0x05, 0x4a, 0x1a, 0xfd, 0xc9, 0xb6,
0xed, 0x7d, 0xa1, 0x6c, 0x55, 0xeb, 0xa6, 0xb0,
0xd4, 0xd1, 0x0c, 0x74, 0xe1, 0xd9, 0xa7, 0xcf,
0x8e, 0xdf, 0xae, 0xaa, 0x68, 0x4a, 0xc0, 0xbd,
0x9f, 0x9d, 0x24, 0xba, 0x67, 0x49, 0x55, 0xc7,
0x9d, 0xc6, 0xbe, 0x32, 0xae, 0xe1, 0xc2, 0x60,
0xb5, 0x58, 0xff, 0x07, 0xe3, 0xa4, 0xd4, 0x9d,
0x24, 0x16, 0x20, 0x11, 0xff, 0x25, 0x4d, 0xb8,
0xbe, 0x07, 0x8e, 0x8a, 0xd0, 0x7e, 0x64, 0x8e,
0x6b, 0xf5, 0x67, 0x93, 0x76, 0xcb, 0x43, 0x21,
0xa5, 0xef, 0x01, 0xaf, 0xe6, 0xad, 0x88, 0x16,
0xfc, 0xc7, 0x63, 0x46, 0x69, 0xc8, 0xc4, 0x38,
0x92, 0x95, 0xc9, 0x24, 0x1e, 0x45, 0xff, 0xf3,
0x9f, 0x32, 0x25, 0xf7, 0x74, 0x50, 0x32, 0xda,
0xee, 0xbe, 0x99, 0xd4, 0xb1, 0x9b, 0xcb, 0x21,
0x5d, 0x1b, 0xfd, 0xb3, 0x6e, 0xda, 0x2c, 0x24 }, /* mdata */
160, /* mdata_len */
{ 0xc9, 0xa0, 0x14, 0x60, 0xaa, 0x2f, 0x85, 0x25,
0x88, 0x75, 0xa1, 0x76, 0xcc, 0x85, 0x46, 0xf9 } /* mac */
}
};
static uint8_t mdata[MDATA_MAX_LEN];
static uint8_t mac[CBC_MAC_MAC_LEN];
static int i;
static uint8_t key_size_index = -1, ret;
static rtimer_clock_t time, time2, total_time;
PROCESS_BEGIN();
puts("-----------------------------------------\n"
"Initializing cryptoprocessor...");
crypto_init();
for(i = 0; i < sizeof(vectors) / sizeof(vectors[0]); i++) {
if(key_size_index != vectors[i].key_size_index) {
key_size_index = vectors[i].key_size_index;
printf("-----------------------------------------\n"
"Filling %d-bit key store...\n", 128 + (key_size_index << 6));
time = RTIMER_NOW();
ret = aes_load_keys(keys[key_size_index].keys,
keys[key_size_index].key_size, keys[key_size_index].count, 0);
time = RTIMER_NOW() - time;
printf("aes_load_keys(): %s, %" PRIu32 " us\n", str_res[ret],
(uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
PROCESS_PAUSE();
if(ret != CRYPTO_SUCCESS) {
break;
}
}
printf("-----------------------------------------\n"
"Test vector #%d:\n"
"key_area=%d mdata_len=%d\n",
i, vectors[i].key_area, vectors[i].mdata_len);
/* mdata has to be in SRAM. */
rom_util_memcpy(mdata, vectors[i].mdata, vectors[i].mdata_len);
time = RTIMER_NOW();
ret = cbc_mac_auth_start(vectors[i].key_area, mdata, vectors[i].mdata_len,
&cbc_mac_test_process);
time2 = RTIMER_NOW();
time = time2 - time;
total_time = time;
if(ret == CRYPTO_SUCCESS) {
PROCESS_WAIT_EVENT_UNTIL(cbc_mac_auth_check_status());
time2 = RTIMER_NOW() - time2;
total_time += time2;
}
printf("cbc_mac_auth_start(): %s, %" PRIu32 " us\n", str_res[ret],
(uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
if(ret != CRYPTO_SUCCESS) {
PROCESS_PAUSE();
continue;
}
printf("cbc_mac_auth_check_status() wait: %" PRIu32 " us\n",
(uint32_t)((uint64_t)time2 * 1000000 / RTIMER_SECOND));
time = RTIMER_NOW();
ret = cbc_mac_auth_get_result(vectors[i].mac, mac);
time = RTIMER_NOW() - time;
total_time += time;
printf("cbc_mac_auth_get_result(): %s, %" PRIu32 " us\n", str_res[ret],
(uint32_t)((uint64_t)time * 1000000 / RTIMER_SECOND));
PROCESS_PAUSE();
if(ret != CRYPTO_SUCCESS) {
continue;
}
if(rom_util_memcmp(mac, vectors[i].mac, CBC_MAC_MAC_LEN)) {
puts("MAC does not match expected one");
} else {
puts("MAC OK");
}
printf("Total duration: %" PRIu32 " us\n",
(uint32_t)((uint64_t)total_time * 1000000 / RTIMER_SECOND));
}
puts("-----------------------------------------\n"
"Disabling cryptoprocessor...");
crypto_disable();
puts("Done!");
PROCESS_END();
}
/*---------------------------------------------------------------------------*/
/**
* @}
* @}
*/
|
7d28904a0ad1ff09a82ea3545327fa7c9add3d48
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/libc/nt/struct/win32finddata.h
|
7ed71233a4124eae6aa3cf76b1d5cc36f4636b47
|
[
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 691
|
h
|
win32finddata.h
|
#ifndef COSMOPOLITAN_LIBC_NT_STRUCT_WIN32FINDDATA_H_
#define COSMOPOLITAN_LIBC_NT_STRUCT_WIN32FINDDATA_H_
#include "libc/nt/struct/filetime.h"
#if !(__ASSEMBLER__ + __LINKER__ + 0)
struct NtWin32FindData {
uint32_t dwFileAttributes;
struct NtFileTime ftCreationTime;
struct NtFileTime ftLastAccessTime;
struct NtFileTime ftLastWriteTime;
uint32_t nFileSizeHigh;
uint32_t nFileSizeLow;
uint32_t dwReserved0;
uint32_t dwReserved1;
char16_t cFileName[260];
char16_t cAlternateFileName[14];
uint32_t dwFileType;
uint32_t dwCreatorType;
uint16_t wFinderFlags;
};
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_LIBC_NT_STRUCT_WIN32FINDDATA_H_ */
|
5ffcb33fc018e7a996d6d87142c61e765fb34328
|
bece8b97cdb15988562c8c8dc27a5b58cd3acb90
|
/fin7/Resources/Step5/samcats-source/mimikatz/modules/dpapi/packages/kuhl_m_dpapi_creds.h
|
d08217e553717ac74d54f0e42c4f1708382f0af5
|
[
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"CC-BY-4.0"
] |
permissive
|
center-for-threat-informed-defense/adversary_emulation_library
|
4382e78f56faa635d5a6cc89bce5b36f3b74476c
|
4b1d1327ebfbd550ba7e5f1b5562c1f3db61311e
|
refs/heads/master
| 2023-08-12T20:08:57.078612
| 2023-07-17T16:54:16
| 2023-07-17T16:54:16
| 259,753,257
| 1,220
| 243
|
Apache-2.0
| 2023-09-06T16:23:00
| 2020-04-28T21:16:54
|
C
|
UTF-8
|
C
| false
| false
| 935
|
h
|
kuhl_m_dpapi_creds.h
|
/* Benjamin DELPY `gentilkiwi`
http://blog.gentilkiwi.com
benjamin@gentilkiwi.com
Licence : https://creativecommons.org/licenses/by/4.0/
*/
#pragma once
#include "../kuhl_m_dpapi.h"
#include "../modules/kull_m_cred.h"
#include "../../sekurlsa/kuhl_m_sekurlsa.h"
typedef struct _KUHL_M_DPAPI_ENCRYPTED_CRED {
DWORD version;
DWORD blobSize;
DWORD unk;
BYTE blob[ANYSIZE_ARRAY];
} KUHL_M_DPAPI_ENCRYPTED_CRED, *PKUHL_M_DPAPI_ENCRYPTED_CRED;
NTSTATUS kuhl_m_dpapi_cred(int argc, wchar_t * argv[]);
NTSTATUS kuhl_m_dpapi_vault(int argc, wchar_t * argv[]);
void kuhl_m_dpapi_cred_tryEncrypted(LPCWSTR target, LPCBYTE data, DWORD dataLen, int argc, wchar_t * argv[]);
BOOL kuhl_m_dpapi_vault_key_type(PKULL_M_CRED_VAULT_CREDENTIAL_ATTRIBUTE attribute, HCRYPTPROV hProv, BYTE aes128[AES_128_KEY_SIZE], BYTE aes256[AES_256_KEY_SIZE], HCRYPTKEY *hKey, BOOL *isAttr);
void kuhl_m_dpapi_vault_basic(PVOID data, DWORD size, GUID *schema);
|
295376d586407c5f0314f77d4b17aa15b5c84e3f
|
800c3c4eee1687e46edc16fb5ed3a5c49f64b6fd
|
/test/917257daa0fe.c
|
aecdb7bcfdec508414a8924e58063b0e60d84023
|
[
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"Linux-syscall-note",
"MIT",
"LGPL-2.1-only",
"GPL-2.0-only"
] |
permissive
|
axboe/liburing
|
8ced1953de2fca05bf689e322d4f68a6a2b4ef1e
|
58ec7c1aea2d57acbc3d398d0c8b2625746eaf04
|
refs/heads/master
| 2023-09-04T04:34:14.490712
| 2023-08-26T14:17:34
| 2023-08-28T14:22:13
| 200,663,555
| 2,276
| 374
|
MIT
| 2023-09-13T14:12:03
| 2019-08-05T13:43:57
|
C
|
UTF-8
|
C
| false
| false
| 1,430
|
c
|
917257daa0fe.c
|
/* SPDX-License-Identifier: MIT */
// autogenerated by syzkaller (https://github.com/google/syzkaller)
#include <endian.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include "liburing.h"
#include "helpers.h"
#include "../src/syscall.h"
int main(int argc, char *argv[])
{
if (argc > 1)
return T_EXIT_SKIP;
mmap((void *) 0x20000000, 0x1000000, 3, MAP_ANON|MAP_PRIVATE, -1, 0);
*(uint32_t*)0x20000000 = 0;
*(uint32_t*)0x20000004 = 0;
*(uint32_t*)0x20000008 = 6;
*(uint32_t*)0x2000000c = 0;
*(uint32_t*)0x20000010 = 0x3af;
*(uint32_t*)0x20000014 = 0;
*(uint32_t*)0x20000018 = 0;
*(uint32_t*)0x2000001c = 0;
*(uint32_t*)0x20000020 = 0;
*(uint32_t*)0x20000024 = 0;
*(uint32_t*)0x20000028 = 0;
*(uint32_t*)0x2000002c = 0;
*(uint32_t*)0x20000030 = 0;
*(uint32_t*)0x20000034 = 0;
*(uint32_t*)0x20000038 = 0;
*(uint32_t*)0x2000003c = 0;
*(uint32_t*)0x20000040 = 0;
*(uint32_t*)0x20000044 = 0;
*(uint64_t*)0x20000048 = 0;
*(uint32_t*)0x20000050 = 0;
*(uint32_t*)0x20000054 = 0;
*(uint32_t*)0x20000058 = 0;
*(uint32_t*)0x2000005c = 0;
*(uint32_t*)0x20000060 = 0;
*(uint32_t*)0x20000064 = 0;
*(uint32_t*)0x20000068 = 0;
*(uint32_t*)0x2000006c = 0;
*(uint64_t*)0x20000070 = 0;
__sys_io_uring_setup(0x7a6, (struct io_uring_params *) 0x20000000UL);
return T_EXIT_PASS;
}
|
850bbbfefe106842a6255ebee6a3b80384ad93f8
|
5d814ca12e2efdab3475870f836e182dd4abaf7f
|
/src/tms/core/entity.h
|
6e24f18e8298af12d1645f6b0ce14dee0f3c2238
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
Bithack/principia
|
dc5eb36f3ccc5c525c5a3f352463d0373bdbfc48
|
789b7090970ed62e10afa35d6631fb1c86fa9893
|
refs/heads/master
| 2023-09-04T02:58:59.499137
| 2023-09-03T21:05:15
| 2023-09-03T21:05:15
| 55,718,601
| 211
| 25
|
NOASSERTION
| 2023-09-04T17:26:19
| 2016-04-07T18:34:03
|
C
|
UTF-8
|
C
| false
| false
| 3,015
|
h
|
entity.h
|
#ifndef _TMS_ENTITY__H_
#define _TMS_ENTITY__H_
/** @relates tms_entity @{ **/
#include <tms/core/tms.h>
#include <tms/math/vector.h>
#define TMS_MAX_GRAPHS_PER_SCENE 4
struct tms_material;
struct tms_mesh;
struct tms_scene;
struct tms_uniform_val;
struct tms_entity_graph_loc {
struct _branch *branch;
int pos;
};
/**
* An entity is any object added to a tms_scene.
**/
struct tms_entity {
int type;
uint32_t id;
uintptr_t prio;
int prio_bias;
struct tms_material *material;/**< must never be set directly but through tms_entity_set_material */
struct tms_mesh *mesh; /**< must never be set directly but through tms_entity_set_mesh */
int cull_step;
unsigned num_children;
struct tms_entity **children;
struct tms_entity *parent;
float M[16];
float N[9];
struct tms_uniform_val *uniforms;
int num_uniforms;
void (*update)(struct tms_entity *e);
/* scene info, if this entity is added to a scene this will be filled */
struct tms_scene *scene;
struct tms_entity_graph_loc graph_loc[TMS_MAX_GRAPHS_PER_SCENE];
void *data;
};
struct tms_entity* tms_entity_alloc(void);
int tms_entity_init(struct tms_entity *e);
int tms_entity_uninit(struct tms_entity *e);
struct tms_entity* tms_entity_dup(struct tms_entity *e);
void tms_entity_copy(struct tms_entity *dest, struct tms_entity *source);
int tms_entity_set_material(struct tms_entity *e, struct tms_material *m);
int tms_entity_set_mesh(struct tms_entity *e, struct tms_mesh *m);
void tms_entity_apply_uniforms(struct tms_entity *e, int pipeline);
int tms_entity_add_child(struct tms_entity *e, struct tms_entity *child);
int tms_entity_remove_child(struct tms_entity *e, struct tms_entity *child);
int tms_entity_set_uniform4f(struct tms_entity *e, const char *name, float r, float g, float b, float a);
int tms_entity_set_uniform2f(struct tms_entity *e, const char *name, float r, float g);
int tms_entity_set_uniform1f(struct tms_entity *e, const char *name, float r);
int tms_entity_set_uniform_fn(struct tms_entity *e, const char *name, void *fn);
void tms_entity_readd(struct tms_entity *e);
void tms_entity_set_prio_all(struct tms_entity *e, uintptr_t prio);
TMS_STATIC_INLINE void tms_entity_update(struct tms_entity *e)
{
if (e->update)
e->update(e);
}
TMS_STATIC_INLINE void tms_entity_update_with_children(struct tms_entity *e)
{
if (e->update)
e->update(e);
for (unsigned x=0; x<e->num_children; ++x)
tms_entity_update_with_children(e->children[x]);
}
TMS_STATIC_INLINE struct tms_scene* tms_entity_get_scene(struct tms_entity *e)
{
return e->scene;
}
TMS_STATIC_INLINE void tms_entity_set_update_fn(struct tms_entity *e, void *fn)
{
e->update = (void(*)(struct tms_entity*))fn;
}
TMS_STATIC_INLINE void tms_entity_set_type(struct tms_entity *e, int type) {
e->type = type;
}
TMS_STATIC_INLINE int tms_entity_get_type(struct tms_entity *e)
{
return e->type;
}
#endif
|
3e8c37c772ed58c6cc0703cc785f38752d43c642
|
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
|
/update_notifier/thirdparty/wxWidgets/docs/doxygen/groups/class_managedwnd.h
|
c2786503729a3f5672df823995d14cd7f64250ca
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"WxWindows-exception-3.1",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"IJG",
"GPL-2.0-only",
"LGPL-2.0-only"
] |
permissive
|
ric2b/Vivaldi-browser
|
388a328b4cb838a4c3822357a5529642f86316a5
|
87244f4ee50062e59667bf8b9ca4d5291b6818d7
|
refs/heads/master
| 2022-12-21T04:44:13.804535
| 2022-12-17T16:30:35
| 2022-12-17T16:30:35
| 86,637,416
| 166
| 41
|
BSD-3-Clause
| 2021-03-31T18:49:30
| 2017-03-29T23:09:05
| null |
UTF-8
|
C
| false
| false
| 710
|
h
|
class_managedwnd.h
|
/////////////////////////////////////////////////////////////////////////////
// Name: class_managedwnd.h
// Purpose: Managed Windows classes group docs
// Author: wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
/**
@defgroup group_class_managedwnd Managed Windows
@ingroup group_class
There are several types of window that are directly controlled by the window
manager (such as MS Windows, or the Motif Window Manager). Frames and dialogs
are similar in wxWidgets, but only dialogs may be modal.
Related Overviews: @ref overview_cmndlg
Related macros/global-functions group: @ref group_funcmacro_dialog
*/
|
fbc548e3ad20114a26c3ec1f6f304fca68e1eeb0
|
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
|
/third_party/chibicc/test/vector_test.c
|
ea8160bf1e626c9ee73dd52372a1722caef4fad2
|
[
"MIT",
"LicenseRef-scancode-free-unknown",
"ISC"
] |
permissive
|
jart/cosmopolitan
|
fb11b5658939023977060a7c6c71a74093d9cb44
|
0d748ad58e1063dd1f8560f18a0c75293b9415b7
|
refs/heads/master
| 2023-09-06T09:17:29.303607
| 2023-09-02T03:49:13
| 2023-09-02T03:50:18
| 272,457,606
| 11,887
| 435
|
ISC
| 2023-09-14T17:47:58
| 2020-06-15T14:16:13
|
C
|
UTF-8
|
C
| false
| false
| 3,353
|
c
|
vector_test.c
|
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2020 Justine Alexandra Roberts Tunney │
│ │
│ 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. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "third_party/chibicc/test/test.h"
typedef char byte16 __attribute__((__vector_size__(16)));
typedef float float4 __attribute__((__vector_size__(16)));
typedef float float4a1 __attribute__((__vector_size__(16), __aligned__(1)));
typedef float float4a16 __attribute__((__vector_size__(16), __aligned__(16)));
typedef double double2 __attribute__((__vector_size__(16)));
typedef double double2a1 __attribute__((__vector_size__(16), __aligned__(1)));
typedef double double2a16 __attribute__((__vector_size__(16), __aligned__(16)));
int main(void) {
ASSERT(16, sizeof(float4));
ASSERT(16, sizeof(float4a1));
ASSERT(16, sizeof(float4a16));
ASSERT(16, sizeof(double2));
ASSERT(16, sizeof(double2a1));
ASSERT(16, sizeof(double2a16));
ASSERT(16, _Alignof(float4));
ASSERT(1, _Alignof(float4a1));
ASSERT(16, _Alignof(float4a16));
ASSERT(16, _Alignof(double2));
ASSERT(1, _Alignof(double2a1));
ASSERT(16, _Alignof(double2a16));
{
float4 v1;
float4 v2;
float x[4] = {1, 2, 3, 4};
float y[4] = {1, 1, 1, 1};
memcpy(&v1, x, 16);
memcpy(&v2, y, 16);
v1 = v1 + v2;
memcpy(x, &v1, 16);
ASSERT(2, x[0]);
// TODO(jart): fix me
/* ASSERT(3, x[1]); */
/* ASSERT(4, x[2]); */
/* ASSERT(5, x[3]); */
}
{
byte16 v;
float x1[4] = {1, 2, 3, 4};
float x2[4];
memcpy(&v, x1, 16);
__builtin_ia32_movntdq(x1, &v);
memcpy(x2, &v, 16);
ASSERT(1, x2[0]);
// TODO(jart): fix me
/* ASSERT(2, x[1]); */
}
return 0;
}
|
58f99740129f4cd4692bde71ef7f5b1d49d0b602
|
32be357e08164f0434174b4402b1a63a09be7d55
|
/CosBase/include/cos/cos/cast.h
|
69a900285f0e06cb226967f5e62a80218e842133
|
[
"Apache-2.0"
] |
permissive
|
CObjectSystem/COS
|
e4a4c284c870b875e5fb949282a6d3cffa58a771
|
fc2f3ed275d2291d3fb2499fa3572dcfe3dd9db2
|
refs/heads/master
| 2023-07-24T21:13:15.083070
| 2023-01-08T15:31:16
| 2023-01-08T15:31:16
| 2,830,240
| 341
| 49
|
Apache-2.0
| 2023-07-22T09:55:49
| 2011-11-22T19:16:13
|
C
|
UTF-8
|
C
| false
| false
| 3,128
|
h
|
cast.h
|
#ifndef COS_COS_CAST_H
#define COS_COS_CAST_H
/**
* C Object System
* COS cast operators
*
* Copyright 2006+ Laurent Deniau <laurent.deniau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COS_COS_COS_H
#error "COS: use <cos/cos/cos.h> instead of <cos/cos/cast.h>"
#endif
#ifdef COS_DISABLE_ALL
#define COS_DISABLE_CAST
#define COS_DISABLE_cast
#define COS_DISABLE_dyncast
#define COS_DISABLE_ecast
#define COS_DISABLE_edyncast
#define COS_DISABLE_ecastLoc
#define COS_DISABLE_edyncastLoc
#define COS_DISABLE_dbgcast
#endif
#ifndef COS_DISABLE_CAST
#define CAST(typename,value) COS_CAST(typename,value)
#endif
#ifndef COS_DISABLE_cast
#define cast(class,object) COS_OBJECT_CAST(class,object)
#endif
#ifndef COS_DISABLE_dyncast
#define dyncast(class,object) COS_OBJECT_DYNCAST(class,object)
#endif
#ifndef COS_DISABLE_ecast
#define ecast(class,object) COS_OBJECT_ECAST(class,object)
#endif
#ifndef COS_DISABLE_edyncast
#define edyncast(class,object) COS_OBJECT_EDYNCAST(class,object)
#endif
#ifndef COS_DISABLE_ecastLoc
#define ecastLoc(cls,obj,file,line) COS_OBJECT_ECASTLOC(cls,obj,file,line)
#endif
#ifndef COS_DISABLE_edyncastLoc
#define edyncastLoc(cls,obj,file,line) COS_OBJECT_EDYNCASTLOC(cls,obj,file,line)
#endif
#ifndef COS_DISABLE_dbgcast
#define dbgcast(class,object) COS_OBJECT_DBGCAST(class,object)
#endif
/***********************************************************
* Implementation
*/
// convert value (C cast)
#define COS_CAST(type,value) ((type) (value))
// convert object (COS cast)
#define COS_OBJECT_CAST(cls,obj) \
((struct cls*) cos_object_cast(obj,classref(cls)))
// convert object (COS downcast)
#define COS_OBJECT_DYNCAST(cls,obj) \
((struct cls*) cos_object_dyncast(obj,classref(cls)))
// convert object (COS cast or throw)
#define COS_OBJECT_ECAST(cls,obj) \
COS_OBJECT_ECASTLOC(cls,obj,__FILE__,__LINE__)
// convert object (COS downcast or throw)
#define COS_OBJECT_EDYNCAST(cls,obj) \
COS_OBJECT_EDYNCASTLOC(cls,obj,__FILE__,__LINE__)
// convert object (COS cast or throw)
#define COS_OBJECT_ECASTLOC(cls,obj,file,line) \
((struct cls*) cos_object_ecast(obj,classref(cls),file,line))
// convert object (COS downcast or throw)
#define COS_OBJECT_EDYNCASTLOC(cls,obj,file,line) \
((struct cls*) cos_object_edyncast(obj,classref(cls),file,line))
// convert value (static cast in release mode, dynamic cast in debug mode)
#define COS_OBJECT_DBGCAST(cls,obj) \
COS_PP_IFNDEF(COS_DEBUG)( COS_CAST(struct cls*, obj), \
COS_OBJECT_EDYNCASTLOC(cls,obj,__FILE__,__LINE__) )
#endif // COS_COS_CAST_H
|
be69c1cbab780c420fd2ee74f2d5e561ae630916
|
d38ed5f31d74a79a054ed55dd9123a8d615283b9
|
/third_party/libgit2/src/win32/version.h
|
79667697f00fbad59937e071b98fd1febdb4e745
|
[
"GPL-2.0-only",
"LicenseRef-scancode-public-domain",
"GCC-exception-2.0",
"LGPL-2.0-or-later",
"Zlib",
"LGPL-2.1-or-later",
"LGPL-2.1-only",
"ISC",
"MIT",
"Apache-2.0"
] |
permissive
|
chigraph/chigraph
|
8ff76a14337da29fa2b2a84d5c35f2eac4156c6e
|
6981bdd6763db54edfe284c1f7d223193584c69a
|
refs/heads/master
| 2022-12-21T13:46:57.273039
| 2022-12-17T18:41:19
| 2022-12-17T18:41:19
| 60,776,831
| 364
| 65
|
Apache-2.0
| 2019-12-13T14:46:43
| 2016-06-09T13:27:37
|
C++
|
UTF-8
|
C
| false
| false
| 1,276
|
h
|
version.h
|
/*
* Copyright (C) the libgit2 contributors. All rights reserved.
*
* This file is part of libgit2, distributed under the GNU GPL v2 with
* a Linking Exception. For full terms see the included COPYING file.
*/
#ifndef INCLUDE_win32_version_h__
#define INCLUDE_win32_version_h__
#include <windows.h>
GIT_INLINE(int) git_has_win32_version(int major, int minor, int service_pack)
{
OSVERSIONINFOEX version_test = {0};
DWORD version_test_mask;
DWORDLONG version_condition_mask = 0;
version_test.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
version_test.dwMajorVersion = major;
version_test.dwMinorVersion = minor;
version_test.wServicePackMajor = (WORD)service_pack;
version_test.wServicePackMinor = 0;
version_test_mask = (VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR | VER_SERVICEPACKMINOR);
VER_SET_CONDITION(version_condition_mask, VER_MAJORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(version_condition_mask, VER_MINORVERSION, VER_GREATER_EQUAL);
VER_SET_CONDITION(version_condition_mask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
VER_SET_CONDITION(version_condition_mask, VER_SERVICEPACKMINOR, VER_GREATER_EQUAL);
if (!VerifyVersionInfo(&version_test, version_test_mask, version_condition_mask))
return 0;
return 1;
}
#endif
|
c718986ef8ac8be346c8a25c7faa5fa0b3b4fb48
|
9e0c8c8d8bafa73d133e41f201badc756c92978a
|
/kernel/gcov.c
|
d25ffcdef8fc402b92be904ce9d7eaef97d5f65d
|
[
"BSD-2-Clause",
"MIT",
"CC0-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause-Views"
] |
permissive
|
vvaltchev/tilck
|
ccf8d9933be1269b85388e5b21645b831ecf5412
|
e9c27da4dd15f5f8a927b11f31484aec3f1429f0
|
refs/heads/master
| 2023-08-16T00:07:42.593483
| 2023-07-04T21:00:31
| 2023-07-19T23:25:42
| 53,845,595
| 2,142
| 115
|
BSD-2-Clause
| 2023-09-03T05:36:46
| 2016-03-14T10:02:41
|
C
|
UTF-8
|
C
| false
| false
| 12,098
|
c
|
gcov.c
|
/* SPDX-License-Identifier: BSD-2-Clause */
#include <tilck/common/basic_defs.h>
#include <tilck/common/string_util.h>
#include <tilck/kernel/kmalloc.h>
#include <tilck/kernel/errno.h>
#include <tilck/kernel/user.h>
#include <tilck/kernel/fault_resumable.h>
typedef u64 gcov_type;
typedef u32 gcov_unsigned_t;
/*
* Unfortunately, GCOV_COUNTERS changes with GCC's versions. Hopefully, the
* following logic is correct and we've missed no cases.
*
* Q: How the value of GCOV_COUNTERS for each GCC version has been found?
* A: Short story: using GCC's git history.
*
* Long story: the value of GCOV_COUNTERS depends on the number of
* DEF_GCOV_COUNTER() instances in gcc/gcov-counter.def
*
* List of changes (excluding updates of copyright years) affecting
* gcov-counter.def (from git://gcc.gnu.org/git/gcc.git)
*
* 596341c741a Rename SINGE_VALUE to TOPN_VALUES counters.
* BASE-VER: 10.0.0
* GCOV_COUNTERS: 8
*
* e37333bad7b Remove indirect call top N counter type.
* BASE-VER: 10.0.0
* GCOV_COUNTERS: 8
*
* 571e95ccc90 Merged to ToT dated 13th Feb 2017.
* BASE-VER: 7.0.1
* GCOV_COUNTERS: 9
*
* 56b653f1a37 Remove __gcov_merge_delta (PR bootstrap/77749)
* BASE-VER: 7.0.0
* GCOV_COUNTERS: 9
*
* afe0c5ee91a Makefile.in: Fix dependence.
* BASE-VER: 5.0.0
* GCOV_COUNTERS: 10
* Notes: in basepoints/gcc-5 GCOV_COUNTERS is still 9, but there has never
* been a gcc 5.0 release. The project jumped from 4.9.4 to 5.1.0.
*
* c77556a5d1e Add gcov-tool: an offline gcda profile processing tool Support.
* BASE-VER: 4.10.0
* GCOV_COUNTERS: 9
*
* Before that, the value was explicitly defined in gcc/gcov-io.h and commit
* that made GCOV_COUNTERS=9 was:
*
* 86ce5d2fc19 Time profiler introduced
* BASE-VER: 4.9.0
* GCOV_COUNTERS: 9
* Before that, the value of GCOV_COUNTERS was 8, but it doesn't make sense to
* go further back, because older GCC versions than 4.9.0 are not supported
* anyway.
*
* As a double-check, the following bash script checked the value of
* GCOV_COUNTERS for each released version after gcc 4.0:
*
* for x in `git tag | grep -E '^releases/gcc-(4|5|6|7|8|9|10).' | sort -V`;
* do
* git reset --hard &> /dev/null;
* git clean -fd &> /dev/null;
* git checkout "$x" &> /dev/null;
* echo -n "$x -> ";
* if [ -f gcc/gcov-counter.def ]; then
* grep 'DEF_GCOV_COUNTER(GCOV_' gcc/gcov-counter.def | wc -l;
* else
* grep -Eo '#define GCOV_COUNTERS[^_]+[0-9]+' gcc/gcov-io.h |
* grep -Eo '[0-9]+';
* fi;
* done
*
* Its output was:
*
* releases/gcc-4.0.0 -> 5
* releases/gcc-4.0.1 -> 5
* releases/gcc-4.0.2 -> 5
* releases/gcc-4.0.3 -> 5
* releases/gcc-4.0.4 -> 5
* releases/gcc-4.1.0 -> 5
* releases/gcc-4.1.1 -> 5
* releases/gcc-4.1.2 -> 5
* releases/gcc-4.2.0 -> 5
* releases/gcc-4.2.1 -> 5
* releases/gcc-4.2.2 -> 5
* releases/gcc-4.2.3 -> 5
* releases/gcc-4.2.4 -> 5
* releases/gcc-4.3.0 -> 8
* releases/gcc-4.3.1 -> 8
* releases/gcc-4.3.2 -> 8
* releases/gcc-4.3.3 -> 8
* releases/gcc-4.3.4 -> 8
* releases/gcc-4.3.5 -> 8
* releases/gcc-4.3.6 -> 8
* releases/gcc-4.4.0 -> 8
* releases/gcc-4.4.1 -> 8
* releases/gcc-4.4.2 -> 8
* releases/gcc-4.4.3 -> 8
* releases/gcc-4.4.4 -> 8
* releases/gcc-4.4.5 -> 8
* releases/gcc-4.4.6 -> 8
* releases/gcc-4.4.7 -> 8
* releases/gcc-4.5.0 -> 8
* releases/gcc-4.5.1 -> 8
* releases/gcc-4.5.2 -> 8
* releases/gcc-4.5.3 -> 8
* releases/gcc-4.5.4 -> 8
* releases/gcc-4.6.0 -> 8
* releases/gcc-4.6.1 -> 8
* releases/gcc-4.6.2 -> 8
* releases/gcc-4.6.3 -> 8
* releases/gcc-4.6.4 -> 8
* releases/gcc-4.7.0 -> 8
* releases/gcc-4.7.1 -> 8
* releases/gcc-4.7.2 -> 8
* releases/gcc-4.7.3 -> 8
* releases/gcc-4.7.4 -> 8
* releases/gcc-4.8.0 -> 8
* releases/gcc-4.8.1 -> 8
* releases/gcc-4.8.2 -> 8
* releases/gcc-4.8.3 -> 8
* releases/gcc-4.8.4 -> 8
* releases/gcc-4.8.5 -> 8
* releases/gcc-4.9.0 -> 9
* releases/gcc-4.9.1 -> 9
* releases/gcc-4.9.2 -> 9
* releases/gcc-4.9.3 -> 9
* releases/gcc-4.9.4 -> 9
* releases/gcc-5.1.0 -> 10
* releases/gcc-5.2.0 -> 10
* releases/gcc-5.3.0 -> 10
* releases/gcc-5.4.0 -> 10
* releases/gcc-5.5.0 -> 10
* releases/gcc-6.1.0 -> 10
* releases/gcc-6.2.0 -> 10
* releases/gcc-6.3.0 -> 10
* releases/gcc-6.4.0 -> 10
* releases/gcc-6.5.0 -> 10
* releases/gcc-7.1.0 -> 9
* releases/gcc-7.2.0 -> 9
* releases/gcc-7.3.0 -> 9
* releases/gcc-7.4.0 -> 9
* releases/gcc-7.5.0 -> 9
* releases/gcc-8.1.0 -> 9
* releases/gcc-8.2.0 -> 9
* releases/gcc-8.3.0 -> 9
* releases/gcc-8.4.0 -> 9
* releases/gcc-9.1.0 -> 9
* releases/gcc-9.2.0 -> 9
* releases/gcc-9.3.0 -> 9
* releases/gcc-10.1.0 -> 8
* releases/gcc-10.2.0 -> 8
*/
#if __GNUC__ >= 10
#define GCOV_COUNTERS 8
#elif __GNUC__ >= 7
#define GCOV_COUNTERS 9
#elif __GNUC__ >= 5
#define GCOV_COUNTERS 10
#elif __GNUC__ == 4 && __GNUC_MINOR__ >= 9
#define GCOV_COUNTERS 9
#else
#define GCOV_COUNTERS 8
#endif
/*
* --------------------------------------------------------------------------
* Data structures (w/ comments) copied from GCC's source: libgcc/libgcov.h
* --------------------------------------------------------------------------
*/
/* Information about counters for a single function. */
struct gcov_ctr_info
{
gcov_unsigned_t num; /* number of counters. */
gcov_type *values; /* their values. */
};
/* Information about a single function. This uses the trailing array
idiom. The number of counters is determined from the merge pointer
array in gcov_info. The key is used to detect which of a set of
comdat functions was selected -- it points to the gcov_info object
of the object file containing the selected comdat function. */
struct gcov_fn_info
{
const struct gcov_info *key; /* comdat key */
gcov_unsigned_t ident; /* unique ident of function */
gcov_unsigned_t lineno_checksum; /* function lineo_checksum */
gcov_unsigned_t cfg_checksum; /* function cfg checksum */
struct gcov_ctr_info ctrs[1]; /* instrumented counters */
};
/* Type of function used to merge counters. */
typedef void (*gcov_merge_fn) (gcov_type *, gcov_unsigned_t);
/* Information about a single object file. */
struct gcov_info
{
gcov_unsigned_t version; /* expected version number */
struct gcov_info *next; /* link to next, used by libgcov */
gcov_unsigned_t stamp; /* uniquifying time stamp */
const char *filename; /* output file name */
gcov_merge_fn merge[GCOV_COUNTERS]; /* merge functions (null for unused) */
unsigned n_functions; /* number of functions */
const struct gcov_fn_info *const *functions; /* pointer to pointers
to function information */
};
/*
* --------------------------------------------------------------------------
* END
* --------------------------------------------------------------------------
*/
static int files_count;
#if KERNEL_GCOV || defined(KERNEL_TEST)
#define FILE_ARRAY_SIZE 1024
#else
#define FILE_ARRAY_SIZE 1
#endif
static struct gcov_info *files_array[FILE_ARRAY_SIZE];
static void gcov_reset_counters(struct gcov_info *gi);
#if !defined(KERNEL_TEST)
static struct gcov_info *gi_list;
void __gcov_merge_add(gcov_type *counters, u32 n) { }
void __gcov_exit(void) { }
void __gcov_init(struct gcov_info *info)
{
if (!gi_list) {
gi_list = info;
} else {
info->next = gi_list;
gi_list = info;
}
files_array[files_count++] = info;
gcov_reset_counters(info);
}
#endif
/*
* Dump counters to a GCDA file.
* Definitions taken from GCC's source: gcc/gcov-io.h.
*/
/* File magic. Must not be palindromes. */
#define GCOV_DATA_MAGIC ((gcov_unsigned_t)0x67636461) /* "gcda" */
#define GCOV_TAG_FUNCTION ((gcov_unsigned_t)0x01000000)
#define GCOV_TAG_FUNCTION_LENGTH (3)
#define GCOV_TAG_COUNTER_BASE ((gcov_unsigned_t)0x01a10000)
#define GCOV_TAG_COUNTER_LENGTH(NUM) ((NUM) * 2)
/* Convert a counter index to a tag. */
#define GCOV_TAG_FOR_COUNTER(COUNT) \
(GCOV_TAG_COUNTER_BASE + ((gcov_unsigned_t)(COUNT) << 17))
// ----------------------------------------------------------------
static u32 compute_gcda_file_size(const struct gcov_info *info)
{
const struct gcov_ctr_info *counters;
u32 size = 0;
// header
size += 3 * sizeof(u32);
for (u32 i = 0; i < info->n_functions; i++) {
// function tag & checksums
size += 5 * sizeof(u32);
counters = info->functions[i]->ctrs;
for (u32 j = 0; j < GCOV_COUNTERS; j++) {
if (!info->merge[j])
continue; /* no merge func -> the counter is NOT used */
size += 2 * sizeof(u32);
size += counters->num * sizeof(u64);
counters++;
}
}
return size;
}
// ----------------------------------------------------------------
int sys_gcov_get_file_count(void)
{
return files_count;
}
int sys_gcov_get_file_info(int fn,
char *user_fname_buf,
u32 fname_buf_size,
u32 *user_fsize)
{
if (fn < 0 || fn >= files_count)
return -EINVAL;
int rc;
const struct gcov_info *gi = files_array[fn];
const u32 fname_len = (u32)strlen(gi->filename);
if (fname_buf_size < fname_len + 1) {
return -ENOBUFS;
}
rc = copy_to_user(user_fname_buf, gi->filename, fname_len + 1);
if (rc != 0)
return -EFAULT;
if (user_fsize != NULL) {
u32 s = compute_gcda_file_size(gi);
rc = copy_to_user(user_fsize, &s, sizeof(s));
if (rc != 0)
return -EFAULT;
}
return 0;
}
static void gcov_reset_counters(struct gcov_info *gi)
{
const struct gcov_ctr_info *counters;
for (u32 i = 0; i < gi->n_functions; i++) {
counters = gi->functions[i]->ctrs;
for (u32 j = 0; j < GCOV_COUNTERS; j++) {
if (!gi->merge[j])
continue; /* no merge func -> the counter is NOT used */
bzero(&counters->values[0], counters->num * sizeof(gcov_type));
counters++;
}
}
}
static void gcov_dump_file_to_buf(const struct gcov_info *gi, void *buf)
{
const struct gcov_fn_info *func;
const struct gcov_ctr_info *counters;
u32 *ptr = buf;
// Header
*ptr++ = GCOV_DATA_MAGIC;
*ptr++ = gi->version;
*ptr++ = gi->stamp;
for (u32 i = 0; i < gi->n_functions; i++) {
func = gi->functions[i];
*ptr++ = GCOV_TAG_FUNCTION;
*ptr++ = GCOV_TAG_FUNCTION_LENGTH;
*ptr++ = func->ident;
*ptr++ = func->lineno_checksum;
*ptr++ = func->cfg_checksum;
counters = func->ctrs;
for (u32 j = 0; j < GCOV_COUNTERS; j++) {
if (!gi->merge[j])
continue; /* no merge func -> the counter is NOT used */
*ptr++ = GCOV_TAG_FOR_COUNTER(j);
*ptr++ = GCOV_TAG_COUNTER_LENGTH(counters->num);
for (u32 k = 0; k < counters->num; k++) {
u64 val = counters->values[k];
*ptr++ = val & 0xffffffffull;
*ptr++ = val >> 32;
}
counters++;
} // for (u32 j = 0; j < GCOV_COUNTERS; j++)
} // for (u32 i = 0; i < info->n_functions; i++)
}
int sys_gcov_get_file(int fn, char *user_buf)
{
if (fn < 0 || fn >= files_count)
return -EINVAL;
u32 rc;
const struct gcov_info *gi = files_array[fn];
rc = fault_resumable_call(ALL_FAULTS_MASK, // mask
&gcov_dump_file_to_buf, // func
2, // #args
gi, // arg1
user_buf); // arg2
if (rc != 0)
return -EFAULT;
return 0;
}
|
8dd728b2dc4b9f635dd2408c0862840a63894a14
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/include/sound/pcm-indirect.h
|
1df7acaaa53527b10a79f390ab07573f17474881
|
[
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 5,743
|
h
|
pcm-indirect.h
|
/*
* Helper functions for indirect PCM data transfer
*
* Copyright (c) by Takashi Iwai <tiwai@suse.de>
* Jaroslav Kysela <perex@perex.cz>
*
* 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.
*/
#ifndef __SOUND_PCM_INDIRECT_H
#define __SOUND_PCM_INDIRECT_H
#include <sound/pcm.h>
struct snd_pcm_indirect {
unsigned int hw_buffer_size; /* Byte size of hardware buffer */
unsigned int hw_queue_size; /* Max queue size of hw buffer (0 = buffer size) */
unsigned int hw_data; /* Offset to next dst (or src) in hw ring buffer */
unsigned int hw_io; /* Ring buffer hw pointer */
int hw_ready; /* Bytes ready for play (or captured) in hw ring buffer */
unsigned int sw_buffer_size; /* Byte size of software buffer */
unsigned int sw_data; /* Offset to next dst (or src) in sw ring buffer */
unsigned int sw_io; /* Current software pointer in bytes */
int sw_ready; /* Bytes ready to be transferred to/from hw */
snd_pcm_uframes_t appl_ptr; /* Last seen appl_ptr */
};
typedef void (*snd_pcm_indirect_copy_t)(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, size_t bytes);
/*
* helper function for playback ack callback
*/
static inline void
snd_pcm_indirect_playback_transfer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec,
snd_pcm_indirect_copy_t copy)
{
struct snd_pcm_runtime *runtime = substream->runtime;
snd_pcm_uframes_t appl_ptr = runtime->control->appl_ptr;
snd_pcm_sframes_t diff = appl_ptr - rec->appl_ptr;
int qsize;
if (diff) {
if (diff < -(snd_pcm_sframes_t) (runtime->boundary / 2))
diff += runtime->boundary;
rec->sw_ready += (int)frames_to_bytes(runtime, diff);
rec->appl_ptr = appl_ptr;
}
qsize = rec->hw_queue_size ? rec->hw_queue_size : rec->hw_buffer_size;
while (rec->hw_ready < qsize && rec->sw_ready > 0) {
unsigned int hw_to_end = rec->hw_buffer_size - rec->hw_data;
unsigned int sw_to_end = rec->sw_buffer_size - rec->sw_data;
unsigned int bytes = qsize - rec->hw_ready;
if (rec->sw_ready < (int)bytes)
bytes = rec->sw_ready;
if (hw_to_end < bytes)
bytes = hw_to_end;
if (sw_to_end < bytes)
bytes = sw_to_end;
if (! bytes)
break;
copy(substream, rec, bytes);
rec->hw_data += bytes;
if (rec->hw_data == rec->hw_buffer_size)
rec->hw_data = 0;
rec->sw_data += bytes;
if (rec->sw_data == rec->sw_buffer_size)
rec->sw_data = 0;
rec->hw_ready += bytes;
rec->sw_ready -= bytes;
}
}
/*
* helper function for playback pointer callback
* ptr = current byte pointer
*/
static inline snd_pcm_uframes_t
snd_pcm_indirect_playback_pointer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, unsigned int ptr)
{
int bytes = ptr - rec->hw_io;
if (bytes < 0)
bytes += rec->hw_buffer_size;
rec->hw_io = ptr;
rec->hw_ready -= bytes;
rec->sw_io += bytes;
if (rec->sw_io >= rec->sw_buffer_size)
rec->sw_io -= rec->sw_buffer_size;
if (substream->ops->ack)
substream->ops->ack(substream);
return bytes_to_frames(substream->runtime, rec->sw_io);
}
/*
* helper function for capture ack callback
*/
static inline void
snd_pcm_indirect_capture_transfer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec,
snd_pcm_indirect_copy_t copy)
{
struct snd_pcm_runtime *runtime = substream->runtime;
snd_pcm_uframes_t appl_ptr = runtime->control->appl_ptr;
snd_pcm_sframes_t diff = appl_ptr - rec->appl_ptr;
if (diff) {
if (diff < -(snd_pcm_sframes_t) (runtime->boundary / 2))
diff += runtime->boundary;
rec->sw_ready -= frames_to_bytes(runtime, diff);
rec->appl_ptr = appl_ptr;
}
while (rec->hw_ready > 0 &&
rec->sw_ready < (int)rec->sw_buffer_size) {
size_t hw_to_end = rec->hw_buffer_size - rec->hw_data;
size_t sw_to_end = rec->sw_buffer_size - rec->sw_data;
size_t bytes = rec->sw_buffer_size - rec->sw_ready;
if (rec->hw_ready < (int)bytes)
bytes = rec->hw_ready;
if (hw_to_end < bytes)
bytes = hw_to_end;
if (sw_to_end < bytes)
bytes = sw_to_end;
if (! bytes)
break;
copy(substream, rec, bytes);
rec->hw_data += bytes;
if ((int)rec->hw_data == rec->hw_buffer_size)
rec->hw_data = 0;
rec->sw_data += bytes;
if (rec->sw_data == rec->sw_buffer_size)
rec->sw_data = 0;
rec->hw_ready -= bytes;
rec->sw_ready += bytes;
}
}
/*
* helper function for capture pointer callback,
* ptr = current byte pointer
*/
static inline snd_pcm_uframes_t
snd_pcm_indirect_capture_pointer(struct snd_pcm_substream *substream,
struct snd_pcm_indirect *rec, unsigned int ptr)
{
int qsize;
int bytes = ptr - rec->hw_io;
if (bytes < 0)
bytes += rec->hw_buffer_size;
rec->hw_io = ptr;
rec->hw_ready += bytes;
qsize = rec->hw_queue_size ? rec->hw_queue_size : rec->hw_buffer_size;
if (rec->hw_ready > qsize)
return SNDRV_PCM_POS_XRUN;
rec->sw_io += bytes;
if (rec->sw_io >= rec->sw_buffer_size)
rec->sw_io -= rec->sw_buffer_size;
if (substream->ops->ack)
substream->ops->ack(substream);
return bytes_to_frames(substream->runtime, rec->sw_io);
}
#endif /* __SOUND_PCM_INDIRECT_H */
|
6950253aaaf189ff17d14ed0604d10daf8a34308
|
c9bc99866cfab223c777cfb741083be3e9439d81
|
/product/tc0/include/tc0_power_domain.h
|
9a7636d13f1dab2904abc0c744104712ebe658d3
|
[
"BSD-3-Clause"
] |
permissive
|
ARM-software/SCP-firmware
|
4738ca86ce42d82588ddafc2226a1f353ff2c797
|
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
|
refs/heads/master
| 2023-09-01T16:13:36.962036
| 2023-08-17T13:00:20
| 2023-08-31T07:43:37
| 134,399,880
| 211
| 165
|
NOASSERTION
| 2023-09-13T14:27:10
| 2018-05-22T10:35:56
|
C
|
UTF-8
|
C
| false
| false
| 537
|
h
|
tc0_power_domain.h
|
/*
* Arm SCP/MCP Software
* Copyright (c) 2020-2021, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef TC0_POWER_DOMAIN_H
#define TC0_POWER_DOMAIN_H
#include <mod_power_domain.h>
/*! Mask for the cluster valid power states */
#define TC0_CLUSTER_VALID_STATE_MASK \
(MOD_PD_STATE_OFF_MASK | MOD_PD_STATE_ON_MASK)
/*! Mask for the core valid power states */
#define TC0_CORE_VALID_STATE_MASK (MOD_PD_STATE_OFF_MASK | MOD_PD_STATE_ON_MASK)
#endif /* TC0_POWER_DOMAIN_H */
|
eef90d428bade5567deb7cfa6e6df65a84fd2f7a
|
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
|
/SOFTWARE/A64-TERES/linux-a64/arch/ia64/include/uapi/asm/mman.h
|
8740819adc54f676de8ca12ee3a476aa36e7a792
|
[
"Linux-syscall-note",
"GPL-2.0-only",
"GPL-1.0-or-later",
"LicenseRef-scancode-free-unknown",
"Apache-2.0"
] |
permissive
|
OLIMEX/DIY-LAPTOP
|
ae82f4ee79c641d9aee444db9a75f3f6709afa92
|
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
|
refs/heads/rel3
| 2023-08-04T01:54:19.483792
| 2023-04-03T07:18:12
| 2023-04-03T07:18:12
| 80,094,055
| 507
| 92
|
Apache-2.0
| 2023-04-03T07:05:59
| 2017-01-26T07:25:50
|
C
|
UTF-8
|
C
| false
| false
| 325
|
h
|
mman.h
|
/*
* Based on <asm-i386/mman.h>.
*
* Modified 1998-2000, 2002
* David Mosberger-Tang <davidm@hpl.hp.com>, Hewlett-Packard Co
*/
#ifndef _UAPI_ASM_IA64_MMAN_H
#define _UAPI_ASM_IA64_MMAN_H
#include <asm-generic/mman.h>
#define MAP_GROWSUP 0x0200 /* register stack-like segment */
#endif /* _UAPI_ASM_IA64_MMAN_H */
|
b6b7f8fc4735d15c04852bde9af0a1c611802445
|
a00712528fef854d2c6fbe8c8c9a940ee88035bf
|
/Engine/Toolkit/Utils/Coroutine.c
|
af8eeecf7d9f4b3207cec69b8951529ea9eefdaa
|
[
"MIT"
] |
permissive
|
scottcgi/Mojoc
|
c7f43344dfeeb604d8500024c34ac66d3567df1a
|
097dde01cad6111acc5e3015ad13c12c1f140243
|
refs/heads/master
| 2023-07-20T14:15:05.546293
| 2023-07-07T14:19:43
| 2023-07-07T14:19:43
| 83,890,107
| 1,209
| 199
|
MIT
| 2023-03-28T23:01:15
| 2017-03-04T11:57:24
|
C
|
UTF-8
|
C
| false
| false
| 3,569
|
c
|
Coroutine.c
|
/*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project Mojoc, which is a pure C Game Engine hosted on GitHub.
* The Mojoc Game Engine is licensed under the MIT License, and will continue to be iterated with coding passion.
*
* License : https://github.com/scottcgi/Mojoc/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/Mojoc
* CodeStyle: https://github.com/scottcgi/Mojoc/blob/master/Docs/CodeStyle.md
*
* Since : 2016-11-13
* Update : 2019-1-9
* Author : scott.cgi
*/
#include <stdlib.h>
#include "Engine/Toolkit/HeaderUtils/Define.h"
#include "Engine/Toolkit/Utils/Coroutine.h"
#include "Engine/Toolkit/Platform/Log.h"
static ArrayList(Coroutine*) coroutineRunningList[1] = AArrayList_Init(Coroutine*, 25);
static ArrayList(Coroutine*) coroutineCacheList [1] = AArrayList_Init(Coroutine*, 25);
static Coroutine* StartCoroutine(CoroutineRun Run)
{
Coroutine* coroutine = AArrayList_Pop(coroutineCacheList, Coroutine*);
if (coroutine == NULL)
{
coroutine = malloc(sizeof(Coroutine));
AArrayList->Init(sizeof(Coroutine*), coroutine->waits);
coroutine->waits->increase = 4;
}
else
{
AArrayList->Clear(coroutine->waits);
}
coroutine->Run = Run;
coroutine->step = 0;
coroutine->waitValue = 0.0f;
coroutine->curWaitValue = 0.0f;
coroutine->waitType = CoroutineWaitType_Null;
coroutine->state = CoroutineState_Ready;
AUserData_Init(coroutine->userData);
AArrayList_Add(coroutineRunningList, coroutine);
return coroutine;
}
static void Update(float deltaSeconds)
{
for (int i = coroutineRunningList->size - 1; i > -1; --i)
{
Coroutine* coroutine = AArrayList_Get(coroutineRunningList, i, Coroutine*);
if (coroutine->waitType == CoroutineWaitType_Coroutines)
{
continue;
}
else if (coroutine->curWaitValue >= coroutine->waitValue)
{
coroutine->Run(coroutine);
if (coroutine->state == CoroutineState_Finish)
{
AArrayList->RemoveByLast(coroutineRunningList, i);
// add to cache
AArrayList_Add(coroutineCacheList, coroutine);
// set waiting coroutines execute forward
for (int j = 0; j < coroutine->waits->size; ++j)
{
Coroutine* wait = AArrayList_Get(coroutine->waits, j, Coroutine*);
ALog_A
(
wait->state != CoroutineState_Finish,
"Coroutine [%p] cannot finish before wait coroutine [%p] finish",
wait,
coroutine
);
wait->waitType = CoroutineWaitType_Null;
}
continue;
}
}
else
{
switch (coroutine->waitType)
{
case CoroutineWaitType_Frames:
coroutine->curWaitValue += 1.0f;
break;
case CoroutineWaitType_Seconds:
coroutine->curWaitValue += deltaSeconds;
break;
case CoroutineWaitType_Null:
break;
case CoroutineWaitType_Coroutines:
break;
}
}
}
}
struct ACoroutine ACoroutine[1] =
{{
StartCoroutine,
Update,
}};
|
41a8dfd10c0b799143373e2e0bb66b1e5bb76a9c
|
99bdb3251fecee538e0630f15f6574054dfc1468
|
/components/dfs/dfs_v1/filesystems/devfs/devfs.c
|
993f967131ef69ed6a3aaf878f91bd61170a178d
|
[
"Apache-2.0"
] |
permissive
|
RT-Thread/rt-thread
|
03a7c52c2aeb1b06a544143b0e803d72f47d1ece
|
3602f891211904a27dcbd51e5ba72fefce7326b2
|
refs/heads/master
| 2023-09-01T04:10:20.295801
| 2023-08-31T16:20:55
| 2023-08-31T16:20:55
| 7,408,108
| 9,599
| 5,805
|
Apache-2.0
| 2023-09-14T13:37:26
| 2013-01-02T14:49:21
|
C
|
UTF-8
|
C
| false
| false
| 10,250
|
c
|
devfs.c
|
/*
* Copyright (c) 2006-2021, RT-Thread Development Team
*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2018-02-11 Bernard Ignore O_CREAT flag in open.
*/
#include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <dfs.h>
#include <dfs_fs.h>
#include <dfs_file.h>
#include "devfs.h"
struct device_dirent
{
rt_device_t *devices;
rt_uint16_t read_index;
rt_uint16_t device_count;
};
int dfs_device_fs_mount(struct dfs_filesystem *fs, unsigned long rwflag, const void *data)
{
return RT_EOK;
}
int dfs_device_fs_statfs(struct dfs_filesystem *fs, struct statfs *buf)
{
buf->f_bsize = 512;
buf->f_blocks = 2048 * 64; // 64M
buf->f_bfree = buf->f_blocks;
buf->f_bavail = buf->f_bfree;
return RT_EOK;
}
int dfs_device_fs_ioctl(struct dfs_file *file, int cmd, void *args)
{
rt_err_t result;
rt_device_t dev_id;
RT_ASSERT(file != RT_NULL);
/* get device handler */
dev_id = (rt_device_t)file->vnode->data;
RT_ASSERT(dev_id != RT_NULL);
if ((file->vnode->path[0] == '/') && (file->vnode->path[1] == '\0'))
return -RT_ENOSYS;
/* close device handler */
result = rt_device_control(dev_id, cmd, args);
if (result == RT_EOK)
return RT_EOK;
return result;
}
ssize_t dfs_device_fs_read(struct dfs_file *file, void *buf, size_t count)
{
int result;
rt_device_t dev_id;
RT_ASSERT(file != RT_NULL);
/* get device handler */
dev_id = (rt_device_t)file->vnode->data;
RT_ASSERT(dev_id != RT_NULL);
if ((file->vnode->path[0] == '/') && (file->vnode->path[1] == '\0'))
return -RT_ENOSYS;
/* read device data */
result = rt_device_read(dev_id, file->pos, buf, count);
file->pos += result;
return result;
}
ssize_t dfs_device_fs_write(struct dfs_file *file, const void *buf, size_t count)
{
int result;
rt_device_t dev_id;
RT_ASSERT(file != RT_NULL);
/* get device handler */
dev_id = (rt_device_t)file->vnode->data;
RT_ASSERT(dev_id != RT_NULL);
if ((file->vnode->path[0] == '/') && (file->vnode->path[1] == '\0'))
return -RT_ENOSYS;
/* read device data */
result = rt_device_write(dev_id, file->pos, buf, count);
file->pos += result;
return result;
}
int dfs_device_fs_close(struct dfs_file *file)
{
rt_err_t result;
rt_device_t dev_id;
RT_ASSERT(file != RT_NULL);
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
return 0;
}
if (file->vnode->type == FT_DIRECTORY && (file->vnode->path[0] == '/') && (file->vnode->path[1] == '\0'))
{
struct device_dirent *root_dirent;
root_dirent = (struct device_dirent *)file->vnode->data;
RT_ASSERT(root_dirent != RT_NULL);
/* release dirent */
rt_free(root_dirent);
return RT_EOK;
}
/* get device handler */
dev_id = (rt_device_t)file->vnode->data;
RT_ASSERT(dev_id != RT_NULL);
/* close device handler */
result = rt_device_close(dev_id);
if (result == RT_EOK)
{
file->vnode->data = RT_NULL;
return RT_EOK;
}
return -EIO;
}
int dfs_device_fs_open(struct dfs_file *file)
{
rt_err_t result;
rt_device_t device;
RT_ASSERT(file->vnode->ref_count > 0);
if (file->vnode->ref_count > 1)
{
file->pos = 0;
return 0;
}
/* open root directory */
if ((file->vnode->path[0] == '/') && (file->vnode->path[1] == '\0') &&
(file->flags & O_DIRECTORY))
{
struct rt_object *object;
struct rt_list_node *node;
struct rt_object_information *information;
struct device_dirent *root_dirent;
rt_uint32_t count = 0;
/* lock scheduler */
rt_enter_critical();
/* traverse device object */
information = rt_object_get_information(RT_Object_Class_Device);
RT_ASSERT(information != RT_NULL);
for (node = information->object_list.next; node != &(information->object_list); node = node->next)
{
count ++;
}
rt_exit_critical();
root_dirent = (struct device_dirent *)rt_malloc(sizeof(struct device_dirent) +
count * sizeof(rt_device_t));
if (root_dirent != RT_NULL)
{
/* lock scheduler */
rt_enter_critical();
root_dirent->devices = (rt_device_t *)(root_dirent + 1);
root_dirent->read_index = 0;
root_dirent->device_count = count;
count = 0;
/* get all device node */
for (node = information->object_list.next; node != &(information->object_list); node = node->next)
{
/* avoid memory write through */
if (count == root_dirent->device_count)
{
rt_kprintf("warning: There are newly added devices that are not displayed!");
break;
}
object = rt_list_entry(node, struct rt_object, list);
root_dirent->devices[count] = (rt_device_t)object;
count ++;
}
rt_exit_critical();
}
/* set data */
file->vnode->data = root_dirent;
return RT_EOK;
}
#ifdef RT_USING_DEV_BUS
else if (file->flags & O_CREAT)
{
if (!(file->flags & O_DIRECTORY))
{
return -ENOSYS;
}
/* regester bus device */
if (rt_device_bus_create(&file->vnode->path[1], 0) == RT_NULL)
{
return -EEXIST;
}
}
#endif
device = rt_device_find(&file->vnode->path[1]);
if (device == RT_NULL)
{
return -ENODEV;
}
#ifdef RT_USING_POSIX_DEVIO
if (device->fops)
{
/* use device fops */
file->vnode->fops = device->fops;
file->vnode->data = (void *)device;
/* use fops */
if (file->vnode->fops->open)
{
result = file->vnode->fops->open(file);
if (result == RT_EOK || result == -RT_ENOSYS)
{
file->vnode->type = FT_DEVICE;
return 0;
}
}
}
else
#endif /* RT_USING_POSIX_DEVIO */
{
result = rt_device_open(device, RT_DEVICE_OFLAG_RDWR);
if (result == RT_EOK || result == -RT_ENOSYS)
{
file->vnode->data = device;
file->vnode->type = FT_DEVICE;
return RT_EOK;
}
}
file->vnode->data = RT_NULL;
/* open device failed. */
return -EIO;
}
int dfs_device_fs_unlink(struct dfs_filesystem *fs, const char *path)
{
#ifdef RT_USING_DEV_BUS
rt_device_t dev_id;
dev_id = rt_device_find(&path[1]);
if (dev_id == RT_NULL)
{
return -1;
}
if (dev_id->type != RT_Device_Class_Bus)
{
return -1;
}
rt_device_bus_destroy(dev_id);
#endif
return RT_EOK;
}
int dfs_device_fs_stat(struct dfs_filesystem *fs, const char *path, struct stat *st)
{
/* stat root directory */
if ((path[0] == '/') && (path[1] == '\0'))
{
st->st_dev = 0;
st->st_mode = S_IFREG | S_IRUSR | S_IRGRP | S_IROTH |
S_IWUSR | S_IWGRP | S_IWOTH;
st->st_mode &= ~S_IFREG;
st->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
st->st_size = 0;
st->st_mtime = 0;
return RT_EOK;
}
else
{
rt_device_t dev_id;
dev_id = rt_device_find(&path[1]);
if (dev_id != RT_NULL)
{
st->st_dev = 0;
st->st_mode = S_IRUSR | S_IRGRP | S_IROTH |
S_IWUSR | S_IWGRP | S_IWOTH;
if (dev_id->type == RT_Device_Class_Char)
st->st_mode |= S_IFCHR;
else if (dev_id->type == RT_Device_Class_Block)
st->st_mode |= S_IFBLK;
else if (dev_id->type == RT_Device_Class_Pipe)
st->st_mode |= S_IFIFO;
else if (dev_id->type == RT_Device_Class_Bus)
st->st_mode |= S_IFDIR;
else
st->st_mode |= S_IFREG;
st->st_size = 0;
st->st_mtime = 0;
return RT_EOK;
}
}
return -ENOENT;
}
int dfs_device_fs_getdents(struct dfs_file *file, struct dirent *dirp, uint32_t count)
{
rt_uint32_t index;
rt_object_t object;
struct dirent *d;
struct device_dirent *root_dirent;
root_dirent = (struct device_dirent *)file->vnode->data;
RT_ASSERT(root_dirent != RT_NULL);
/* make integer count */
count = (count / sizeof(struct dirent));
if (count == 0)
return -EINVAL;
for (index = 0; index < count && index + root_dirent->read_index < root_dirent->device_count;
index ++)
{
object = (rt_object_t)root_dirent->devices[root_dirent->read_index + index];
d = dirp + index;
if ((((rt_device_t)object)->type) == RT_Device_Class_Bus)
{
d->d_type = DT_DIR;
}
else
{
d->d_type = DT_REG;
}
d->d_namlen = RT_NAME_MAX;
d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
rt_strncpy(d->d_name, object->name, RT_NAME_MAX);
}
root_dirent->read_index += index;
return index * sizeof(struct dirent);
}
static int dfs_device_fs_poll(struct dfs_file *fd, struct rt_pollreq *req)
{
int mask = 0;
return mask;
}
static const struct dfs_file_ops _device_fops =
{
dfs_device_fs_open,
dfs_device_fs_close,
dfs_device_fs_ioctl,
dfs_device_fs_read,
dfs_device_fs_write,
RT_NULL, /* flush */
RT_NULL, /* lseek */
dfs_device_fs_getdents,
dfs_device_fs_poll,
};
static const struct dfs_filesystem_ops _device_fs =
{
"devfs",
DFS_FS_FLAG_DEFAULT,
&_device_fops,
dfs_device_fs_mount,
RT_NULL, /*unmount*/
RT_NULL, /*mkfs*/
dfs_device_fs_statfs,
dfs_device_fs_unlink,
dfs_device_fs_stat,
RT_NULL, /*rename*/
};
int devfs_init(void)
{
/* register device file system */
dfs_register(&_device_fs);
return 0;
}
|
792c9e79b0089d63a2eba82bfd5b2e6900817dd4
|
ce99bd11ca505967277f4689c621479c1987698e
|
/src/music.h
|
7c236fd63d1654768b4012c736427a396f778e29
|
[] |
no_license
|
n64decomp/007
|
5951258890f15431f273e1503674c5e0402c66e0
|
c46751089ddc18b12ef7a45b6a3e03de2054c422
|
refs/heads/master
| 2022-11-08T23:34:54.021033
| 2022-10-29T14:41:01
| 2022-10-29T14:41:01
| 241,212,109
| 359
| 48
| null | 2020-11-21T23:30:31
| 2020-02-17T21:31:00
|
C
|
UTF-8
|
C
| false
| false
| 2,709
|
h
|
music.h
|
#ifndef _MUSIC_H_
#define _MUSIC_H_
#include <ultra64.h>
#include <PR/libaudio.h>
#define VOLUME_MAX 0x7fff
/**
* Counting definitions for music in this file, there
* are 63 distinct entries. This exlcudes the "NONE" music
* and control sequence entries.
*/
#define NUM_MUSIC_TRACKS 63
/**
* Metadata for a sequence "file" entry / data content of single sequence.
* Based on original ALSeqData in n64devkit\ultra\usr\include\PR\libaudio.h.
*/
typedef struct
{
// address is offset from the start of .sbk file
u8 *address;
// seq length after uncompressed.
u16 uncompressed_len;
// len is data segment length in the rom. This is the 1172 compressed length.
u16 len;
} RareALSeqData;
/**
* Structure for storing collection of sequence metadatas.
* These are stored 1172 compressed.
* Based on original ALSeqFile in n64devkit\ultra\usr\include\PR\libaudio.h.
*/
typedef struct
{
/**
* number of sequences.
*/
u16 seqCount;
/**
* Unknown, maybe unused padding.
*/
u16 unk;
/**
* ARRAY of sequence info. This is a "dynamic" array, more space
* will be allocated from ALHeap at runtime.
*/
RareALSeqData seqArray[1];
} RareALSeqBankFile;
typedef enum MUSIC_FADESTATE_e {
/**
* Music track is fading out.
*/
MUSIC_FADESTATE_FADE_OUT = -1,
/**
* Default state. Also reached when forcibly halted by application.
*/
MUSIC_FADESTATE_UNSET,
/**
* Music track is fading in.
*/
MUSIC_FADESTATE_FADE_IN
} MUSIC_FADESTATE;
void musicSeqPlayerInit(void);
void musicTrack1Play(s32 track);
void musicTrack1Stop(void);
u16 musicTrack1GetVolume(void);
void musicTrack1ApplySeqpVol(u16 volume);
void musicTrack1SaveCurrentVolumeAsTrackDefault(void);
void musicTrack1FadeOut(f32 fadeTime);
void musicTrack1FadeIn(f32 fadeTime, u16 volume);
void musicTrack2Play(s32 track);
void musicTrack2Stop(void);
u16 musicTrack2GetVolume(void);
void musicTrack2ApplySeqpVol(u16 volume);
void musicTrack2SaveCurrentVolumeAsTrackDefault(void);
void musicTrack2FadeOut(f32 fadeTime);
void musicTrack2FadeIn(f32 fadeTime, u16 volume);
void musicTrack3Play(s32 track);
void musicTrack3Stop(void);
u16 musicTrack3GetVolume(void);
void musicTrack3ApplySeqpVol(u16 volume);
void musicTrack3SaveCurrentVolumeAsTrackDefault(void);
void musicTrack3FadeOut(f32 fadeTime);
void musicTrack3FadeIn(f32 fadeTime, u16 volume);
void musicFadeTick(void);
extern s32 g_musicXTrack1Fade;
extern s32 g_musicXTrack2Fade;
extern s32 g_musicXTrack3Fade;
extern ALBank *g_musicSfxBufferPtr;
extern ALSndPlayer g_sndPlayer;
extern s16 *g_sndSfxSlotVolume;
extern u16 *g_sndSfxSlotNaturalVolume;
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.