filename
stringlengths
3
9
code
stringlengths
4
1.05M
569291.c
struct A { int a[1]; int b; }; extern int c; static int o[] = { [__builtin_offsetof(struct A, b)] = 0, // OK [__builtin_offsetof(struct A, a[0])] = 0, // OK [__builtin_offsetof(struct A, a[0*0])] = 0, // OK [__builtin_offsetof(struct A, a[c])] = 0 // KO }; /* * check-name: constexprness __builtin_offsetof() * * check-error-start constexpr-offsetof.c:12:39: error: bad constant expression * check-error-end */
740909.c
/** ****************************************************************************** * @file stm32f0xx_crc.c * @author MCD Application Team * @version V1.5.0 * @date 05-December-2014 * @brief This file provides firmware functions to manage the following * functionalities of CRC computation unit peripheral: * + Configuration of the CRC computation unit * + CRC computation of one/many 32-bit data * + CRC Independent register (IDR) access * * @verbatim =============================================================================== ##### How to use this driver ##### =============================================================================== [..] (+) Enable CRC AHB clock using RCC_AHBPeriphClockCmd(RCC_AHBPeriph_CRC, ENABLE) function (+) If required, select the reverse operation on input data using CRC_ReverseInputDataSelect() (+) If required, enable the reverse operation on output data using CRC_ReverseOutputDataCmd(Enable) (+) use CRC_CalcCRC() function to compute the CRC of a 32-bit data or use CRC_CalcBlockCRC() function to compute the CRC if a 32-bit data buffer (@) To compute the CRC of a new data use CRC_ResetDR() to reset the CRC computation unit before starting the computation otherwise you can get wrong CRC values. @endverbatim * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_crc.h" /** @addtogroup STM32F0xx_StdPeriph_Driver * @{ */ /** @defgroup CRC * @brief CRC driver modules * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** @defgroup CRC_Private_Functions * @{ */ /** @defgroup CRC_Group1 Configuration of the CRC computation unit functions * @brief Configuration of the CRC computation unit functions * @verbatim =============================================================================== ##### CRC configuration functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Deinitializes CRC peripheral registers to their default reset values. * @param None * @retval None */ void CRC_DeInit(void) { /* Set DR register to reset value */ CRC->DR = 0xFFFFFFFF; /* Set the POL register to the reset value: 0x04C11DB7 */ CRC->POL = 0x04C11DB7; /* Reset IDR register */ CRC->IDR = 0x00; /* Set INIT register to reset value */ CRC->INIT = 0xFFFFFFFF; /* Reset the CRC calculation unit */ CRC->CR = CRC_CR_RESET; } /** * @brief Resets the CRC calculation unit and sets INIT register content in DR register. * @param None * @retval None */ void CRC_ResetDR(void) { /* Reset CRC generator */ CRC->CR |= CRC_CR_RESET; } /** * @brief Selects the polynomial size. This function is only applicable for * STM32F072 devices. * @param CRC_PolSize: Specifies the polynomial size. * This parameter can be: * @arg CRC_PolSize_7: 7-bit polynomial for CRC calculation * @arg CRC_PolSize_8: 8-bit polynomial for CRC calculation * @arg CRC_PolSize_16: 16-bit polynomial for CRC calculation * @arg CRC_PolSize_32: 32-bit polynomial for CRC calculation * @retval None */ void CRC_PolynomialSizeSelect(uint32_t CRC_PolSize) { uint32_t tmpcr = 0; /* Check the parameter */ assert_param(IS_CRC_POL_SIZE(CRC_PolSize)); /* Get CR register value */ tmpcr = CRC->CR; /* Reset POL_SIZE bits */ tmpcr &= (uint32_t)~((uint32_t)CRC_CR_POLSIZE); /* Set the polynomial size */ tmpcr |= (uint32_t)CRC_PolSize; /* Write to CR register */ CRC->CR = (uint32_t)tmpcr; } /** * @brief Selects the reverse operation to be performed on input data. * @param CRC_ReverseInputData: Specifies the reverse operation on input data. * This parameter can be: * @arg CRC_ReverseInputData_No: No reverse operation is performed * @arg CRC_ReverseInputData_8bits: reverse operation performed on 8 bits * @arg CRC_ReverseInputData_16bits: reverse operation performed on 16 bits * @arg CRC_ReverseInputData_32bits: reverse operation performed on 32 bits * @retval None */ void CRC_ReverseInputDataSelect(uint32_t CRC_ReverseInputData) { uint32_t tmpcr = 0; /* Check the parameter */ assert_param(IS_CRC_REVERSE_INPUT_DATA(CRC_ReverseInputData)); /* Get CR register value */ tmpcr = CRC->CR; /* Reset REV_IN bits */ tmpcr &= (uint32_t)~((uint32_t)CRC_CR_REV_IN); /* Set the reverse operation */ tmpcr |= (uint32_t)CRC_ReverseInputData; /* Write to CR register */ CRC->CR = (uint32_t)tmpcr; } /** * @brief Enables or disable the reverse operation on output data. * The reverse operation on output data is performed on 32-bit. * @param NewState: new state of the reverse operation on output data. * This parameter can be: ENABLE or DISABLE. * @retval None */ void CRC_ReverseOutputDataCmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable reverse operation on output data */ CRC->CR |= CRC_CR_REV_OUT; } else { /* Disable reverse operation on output data */ CRC->CR &= (uint32_t)~((uint32_t)CRC_CR_REV_OUT); } } /** * @brief Initializes the INIT register. * @note After resetting CRC calculation unit, CRC_InitValue is stored in DR register * @param CRC_InitValue: Programmable initial CRC value * @retval None */ void CRC_SetInitRegister(uint32_t CRC_InitValue) { CRC->INIT = CRC_InitValue; } /** * @brief Initializes the polynomail coefficients. This function is only * applicable for STM32F072 devices. * @param CRC_Pol: Polynomial to be used for CRC calculation. * @retval None */ void CRC_SetPolynomial(uint32_t CRC_Pol) { CRC->POL = CRC_Pol; } /** * @} */ /** @defgroup CRC_Group2 CRC computation of one/many 32-bit data functions * @brief CRC computation of one/many 32-bit data functions * @verbatim =============================================================================== ##### CRC computation functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Computes the 32-bit CRC of a given data word(32-bit). * @param CRC_Data: data word(32-bit) to compute its CRC * @retval 32-bit CRC */ uint32_t CRC_CalcCRC(uint32_t CRC_Data) { CRC->DR = CRC_Data; return (CRC->DR); } /** * @brief Computes the 16-bit CRC of a given 16-bit data. This function is only * applicable for STM32F072 devices. * @param CRC_Data: data half-word(16-bit) to compute its CRC * @retval 16-bit CRC */ uint32_t CRC_CalcCRC16bits(uint16_t CRC_Data) { *(uint16_t*)(CRC_BASE) = (uint16_t) CRC_Data; return (CRC->DR); } /** * @brief Computes the 8-bit CRC of a given 8-bit data. This function is only * applicable for STM32F072 devices. * @param CRC_Data: 8-bit data to compute its CRC * @retval 8-bit CRC */ uint32_t CRC_CalcCRC8bits(uint8_t CRC_Data) { *(uint8_t*)(CRC_BASE) = (uint8_t) CRC_Data; return (CRC->DR); } /** * @brief Computes the 32-bit CRC of a given buffer of data word(32-bit). * @param pBuffer: pointer to the buffer containing the data to be computed * @param BufferLength: length of the buffer to be computed * @retval 32-bit CRC */ uint32_t CRC_CalcBlockCRC(uint32_t pBuffer[], uint32_t BufferLength) { uint32_t index = 0; for(index = 0; index < BufferLength; index++) { CRC->DR = pBuffer[index]; } return (CRC->DR); } /** * @brief Returns the current CRC value. * @param None * @retval 32-bit CRC */ uint32_t CRC_GetCRC(void) { return (CRC->DR); } /** * @} */ /** @defgroup CRC_Group3 CRC Independent Register (IDR) access functions * @brief CRC Independent Register (IDR) access (write/read) functions * @verbatim =============================================================================== ##### CRC Independent Register (IDR) access functions ##### =============================================================================== @endverbatim * @{ */ /** * @brief Stores an 8-bit data in the Independent Data(ID) register. * @param CRC_IDValue: 8-bit value to be stored in the ID register * @retval None */ void CRC_SetIDRegister(uint8_t CRC_IDValue) { CRC->IDR = CRC_IDValue; } /** * @brief Returns the 8-bit data stored in the Independent Data(ID) register * @param None * @retval 8-bit value of the ID register */ uint8_t CRC_GetIDRegister(void) { return (CRC->IDR); } /** * @} */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
786881.c
/** ****************************************************************************** * @file system_stm32f3xx.c * @author MCD Application Team * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. * * 1. This file provides two functions and one global variable to be called from * user application: * - SystemInit(): This function is called at startup just after reset and * before branch to main program. This call is made inside * the "startup_stm32f3xx.s" file. * * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used * by the user application to setup the SysTick * timer or configure other parameters. * * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must * be called whenever the core clock is changed * during program execution. * * 2. After each device reset the HSI (8 MHz) is used as system clock source. * Then SystemInit() function is called, in "startup_stm32f3xx.s" file, to * configure the system clock before to branch to main program. * * 3. This file configures the system clock as follows: *============================================================================= * Supported STM32F3xx device *----------------------------------------------------------------------------- * System Clock source | HSI *----------------------------------------------------------------------------- * SYSCLK(Hz) | 8000000 *----------------------------------------------------------------------------- * HCLK(Hz) | 8000000 *----------------------------------------------------------------------------- * AHB Prescaler | 1 *----------------------------------------------------------------------------- * APB2 Prescaler | 1 *----------------------------------------------------------------------------- * APB1 Prescaler | 1 *----------------------------------------------------------------------------- * USB Clock | DISABLE *----------------------------------------------------------------------------- *============================================================================= ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f3xx_system * @{ */ /** @addtogroup STM32F3xx_System_Private_Includes * @{ */ #include "stm32f3xx.h" /** * @} */ /** @addtogroup STM32F3xx_System_Private_TypesDefinitions * @{ */ /** * @} */ /** @addtogroup STM32F3xx_System_Private_Defines * @{ */ #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. This value can be provided and adapted by the user application. */ #endif /* HSI_VALUE */ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ #ifndef VECT_TAB_OFFSET #define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ #endif /** * @} */ /** @addtogroup STM32F3xx_System_Private_Macros * @{ */ /** * @} */ /** @addtogroup STM32F3xx_System_Private_Variables * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ uint32_t SystemCoreClock = 8000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} */ /** @addtogroup STM32F3xx_System_Private_FunctionPrototypes * @{ */ /** * @} */ /** @addtogroup STM32F3xx_System_Private_Functions * @{ */ /** * @brief Setup the microcontroller system * Initialize the FPU setting, vector table location and the PLL configuration is reset. * @param None * @retval None */ void SystemInit(void) { /* FPU settings --------------------------------------------------------------*/ #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ #endif /* Reset the RCC clock configuration to the default reset state ------------*/ /* Set HSION bit */ RCC->CR |= 0x00000001U; /* Reset CFGR register */ RCC->CFGR &= 0xF87FC00CU; /* Reset HSEON, CSSON and PLLON bits */ RCC->CR &= 0xFEF6FFFFU; /* Reset HSEBYP bit */ RCC->CR &= 0xFFFBFFFFU; /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE bits */ RCC->CFGR &= 0xFF80FFFFU; /* Reset PREDIV1[3:0] bits */ RCC->CFGR2 &= 0xFFFFFFF0U; /* Reset USARTSW[1:0], I2CSW and TIMs bits */ RCC->CFGR3 &= 0xFF00FCCCU; /* Disable all interrupts */ RCC->CIR = 0x00000000U; #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ #else SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ #endif } /** * @brief Update SystemCoreClock variable according to Clock Register Values. * The SystemCoreClock variable contains the core clock (HCLK), it can * be used by the user application to setup the SysTick timer or configure * other parameters. * * @note Each time the core clock (HCLK) changes, this function must be called * to update SystemCoreClock variable value. Otherwise, any configuration * based on this variable will be incorrect. * * @note - The system frequency computed by this function is not the real * frequency in the chip. It is calculated based on the predefined * constant and the selected clock source: * * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) * * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) * * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) * or HSI_VALUE(*) multiplied/divided by the PLL factors. * * (*) HSI_VALUE is a constant defined in stm32f3xx_hal.h file (default value * 8 MHz) but the real value may vary depending on the variations * in voltage and temperature. * * (**) HSE_VALUE is a constant defined in stm32f3xx_hal.h file (default value * 8 MHz), user has to ensure that HSE_VALUE is same as the real * frequency of the crystal used. Otherwise, this function may * have wrong result. * * - The result of this function could be not correct when using fractional * value for HSE crystal. * * @param None * @retval None */ void SystemCoreClockUpdate (void) { uint32_t tmp = 0, pllmull = 0, pllsource = 0, predivfactor = 0; /* Get SYSCLK source -------------------------------------------------------*/ tmp = RCC->CFGR & RCC_CFGR_SWS; switch (tmp) { case RCC_CFGR_SWS_HSI: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; case RCC_CFGR_SWS_HSE: /* HSE used as system clock */ SystemCoreClock = HSE_VALUE; break; case RCC_CFGR_SWS_PLL: /* PLL used as system clock */ /* Get PLL clock source and multiplication factor ----------------------*/ pllmull = RCC->CFGR & RCC_CFGR_PLLMUL; pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; pllmull = ( pllmull >> 18) + 2; #if defined (STM32F302xE) || defined (STM32F303xE) || defined (STM32F398xx) predivfactor = (RCC->CFGR2 & RCC_CFGR2_PREDIV) + 1; if (pllsource == RCC_CFGR_PLLSRC_HSE_PREDIV) { /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / predivfactor) * pllmull; } else { /* HSI oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSI_VALUE / predivfactor) * pllmull; } #else if (pllsource == RCC_CFGR_PLLSRC_HSI_DIV2) { /* HSI oscillator clock divided by 2 selected as PLL clock entry */ SystemCoreClock = (HSI_VALUE >> 1) * pllmull; } else { predivfactor = (RCC->CFGR2 & RCC_CFGR2_PREDIV) + 1; /* HSE oscillator clock selected as PREDIV1 clock entry */ SystemCoreClock = (HSE_VALUE / predivfactor) * pllmull; } #endif /* STM32F302xE || STM32F303xE || STM32F398xx */ break; default: /* HSI used as system clock */ SystemCoreClock = HSI_VALUE; break; } /* Compute HCLK clock frequency ----------------*/ /* Get HCLK prescaler */ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK clock frequency */ SystemCoreClock >>= tmp; } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
287354.c
/* * Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, * Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, * Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, * Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl * * This file is part of acados. * * The 2-Clause BSD 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. * * 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.; */ // standard #include <stdio.h> #include <stdlib.h> // acados #include "acados/utils/print.h" #include "acados_c/ocp_nlp_interface.h" #include "acados_c/external_function_interface.h" // example specific #include "{{ model.name }}_model/{{ model.name }}_model.h" {% if constraints.constr_type == "BGP" and dims.nphi %} #include "{{ model.name }}_constraints/{{ model.name }}_phi_constraint.h" {% endif %} {% if constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} #include "{{ model.name }}_constraints/{{ model.name }}_phi_e_constraint.h" {% endif %} {% if constraints.constr_type == "BGH" and dims.nh > 0 %} #include "{{ model.name }}_constraints/{{ model.name }}_h_constraint.h" {% endif %} {% if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} #include "{{ model.name }}_constraints/{{ model.name }}_h_e_constraint.h" {% endif %} {%- if cost.cost_type == "NONLINEAR_LS" %} #include "{{ model.name }}_cost/{{ model.name }}_cost_y_fun.h" {%- elif cost.cost_type == "EXTERNAL" %} #include "{{ model.name }}_cost/{{ model.name }}_external_cost.h" {%- endif %} {%- if cost.cost_type_0 == "NONLINEAR_LS" %} #include "{{ model.name }}_cost/{{ model.name }}_cost_y_0_fun.h" {%- elif cost.cost_type_0 == "EXTERNAL" %} #include "{{ model.name }}_cost/{{ model.name }}_external_cost_0.h" {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" %} #include "{{ model.name }}_cost/{{ model.name }}_cost_y_e_fun.h" {%- elif cost.cost_type_e == "EXTERNAL" %} #include "{{ model.name }}_cost/{{ model.name }}_external_cost_e.h" {%- endif %} #include "acados_solver_{{ model.name }}.h" #define NX {{ model.name | upper }}_NX #define NZ {{ model.name | upper }}_NZ #define NU {{ model.name | upper }}_NU #define NP {{ model.name | upper }}_NP #define NBX {{ model.name | upper }}_NBX #define NBX0 {{ model.name | upper }}_NBX0 #define NBU {{ model.name | upper }}_NBU #define NSBX {{ model.name | upper }}_NSBX #define NSBU {{ model.name | upper }}_NSBU #define NSH {{ model.name | upper }}_NSH #define NSG {{ model.name | upper }}_NSG #define NSPHI {{ model.name | upper }}_NSPHI #define NSHN {{ model.name | upper }}_NSHN #define NSGN {{ model.name | upper }}_NSGN #define NSPHIN {{ model.name | upper }}_NSPHIN #define NSBXN {{ model.name | upper }}_NSBXN #define NS {{ model.name | upper }}_NS #define NSN {{ model.name | upper }}_NSN #define NG {{ model.name | upper }}_NG #define NBXN {{ model.name | upper }}_NBXN #define NGN {{ model.name | upper }}_NGN #define NY0 {{ model.name | upper }}_NY0 #define NY {{ model.name | upper }}_NY #define NYN {{ model.name | upper }}_NYN // #define N {{ model.name | upper }}_N #define NH {{ model.name | upper }}_NH #define NPHI {{ model.name | upper }}_NPHI #define NHN {{ model.name | upper }}_NHN #define NPHIN {{ model.name | upper }}_NPHIN #define NR {{ model.name | upper }}_NR // ** solver data ** {{ model.name }}_solver_capsule * {{ model.name }}_acados_create_capsule(void) { void* capsule_mem = malloc(sizeof({{ model.name }}_solver_capsule)); {{ model.name }}_solver_capsule *capsule = ({{ model.name }}_solver_capsule *) capsule_mem; return capsule; } int {{ model.name }}_acados_free_capsule({{ model.name }}_solver_capsule *capsule) { free(capsule); return 0; } int {{ model.name }}_acados_create({{ model.name }}_solver_capsule * capsule) { int N_shooting_intervals = {{ model.name | upper }}_N; double* new_time_steps = NULL; // NULL -> don't alter the code generated time-steps return {{ model.name }}_acados_create_with_discretization(capsule, N_shooting_intervals, new_time_steps); } int {{ model.name }}_acados_update_time_steps({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps) { if (N != capsule->nlp_solver_plan->N) { fprintf(stderr, "{{ model.name }}_acados_update_time_steps: given number of time steps (= %d) " \ "differs from the currently allocated number of " \ "time steps (= %d)!\n" \ "Please recreate with new discretization and provide a new vector of time_stamps!\n", N, capsule->nlp_solver_plan->N); return 1; } ocp_nlp_config * nlp_config = capsule->nlp_config; ocp_nlp_dims * nlp_dims = capsule->nlp_dims; ocp_nlp_in * nlp_in = capsule->nlp_in; for (int i = 0; i < N; i++) { ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &new_time_steps[i]); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &new_time_steps[i]); } return 0; } int {{ model.name }}_acados_create_with_discretization({{ model.name }}_solver_capsule * capsule, int N, double* new_time_steps) { int status = 0; // If N does not match the number of shooting intervals used for code generation, new_time_steps must be given. if (N != {{ model.name | upper }}_N && !new_time_steps) { fprintf(stderr, "{{ model.name }}_acados_create_with_discretization: new_time_steps is NULL " \ "but the number of shooting intervals (= %d) differs from the number of " \ "shooting intervals (= %d) during code generation! Please provide a new vector of time_stamps!\n", \ N, {{ model.name | upper }}_N); return 1; } // number of expected runtime parameters capsule->nlp_np = NP; /************************************************ * plan & config ************************************************/ ocp_nlp_plan * nlp_solver_plan = ocp_nlp_plan_create(N); capsule->nlp_solver_plan = nlp_solver_plan; {%- if solver_options.nlp_solver_type == "SQP" %} nlp_solver_plan->nlp_solver = SQP; {% else %} nlp_solver_plan->nlp_solver = SQP_RTI; {%- endif %} nlp_solver_plan->ocp_qp_solver_plan.qp_solver = {{ solver_options.qp_solver }}; nlp_solver_plan->nlp_cost[0] = {{ cost.cost_type_0 }}; for (int i = 1; i < N; i++) nlp_solver_plan->nlp_cost[i] = {{ cost.cost_type }}; nlp_solver_plan->nlp_cost[N] = {{ cost.cost_type_e }}; for (int i = 0; i < N; i++) { {% if solver_options.integrator_type == "DISCRETE" %} nlp_solver_plan->nlp_dynamics[i] = DISCRETE_MODEL; // discrete dynamics does not need sim solver option, this field is ignored nlp_solver_plan->sim_solver_plan[i].sim_solver = INVALID_SIM_SOLVER; {% else %} nlp_solver_plan->nlp_dynamics[i] = CONTINUOUS_MODEL; nlp_solver_plan->sim_solver_plan[i].sim_solver = {{ solver_options.integrator_type }}; {%- endif %} } for (int i = 0; i < N; i++) { {% if constraints.constr_type == "BGP" %} nlp_solver_plan->nlp_constraints[i] = BGP; {%- else -%} nlp_solver_plan->nlp_constraints[i] = BGH; {%- endif %} } {%- if constraints.constr_type_e == "BGP" %} nlp_solver_plan->nlp_constraints[N] = BGP; {% else %} nlp_solver_plan->nlp_constraints[N] = BGH; {%- endif %} {%- if solver_options.hessian_approx == "EXACT" %} {%- if solver_options.regularize_method == "NO_REGULARIZE" %} nlp_solver_plan->regularization = NO_REGULARIZE; {%- elif solver_options.regularize_method == "MIRROR" %} nlp_solver_plan->regularization = MIRROR; {%- elif solver_options.regularize_method == "PROJECT" %} nlp_solver_plan->regularization = PROJECT; {%- elif solver_options.regularize_method == "PROJECT_REDUC_HESS" %} nlp_solver_plan->regularization = PROJECT_REDUC_HESS; {%- elif solver_options.regularize_method == "CONVEXIFY" %} nlp_solver_plan->regularization = CONVEXIFY; {%- endif %} {%- endif %} ocp_nlp_config * nlp_config = ocp_nlp_config_create(*nlp_solver_plan); capsule->nlp_config = nlp_config; /************************************************ * dimensions ************************************************/ #define NINTNP1MEMS 17 int* intNp1mem = (int*)malloc( (N+1)*sizeof(int)*NINTNP1MEMS ); int* nx = intNp1mem + (N+1)*0; int* nu = intNp1mem + (N+1)*1; int* nbx = intNp1mem + (N+1)*2; int* nbu = intNp1mem + (N+1)*3; int* nsbx = intNp1mem + (N+1)*4; int* nsbu = intNp1mem + (N+1)*5; int* nsg = intNp1mem + (N+1)*6; int* nsh = intNp1mem + (N+1)*7; int* nsphi = intNp1mem + (N+1)*8; int* ns = intNp1mem + (N+1)*9; int* ng = intNp1mem + (N+1)*10; int* nh = intNp1mem + (N+1)*11; int* nphi = intNp1mem + (N+1)*12; int* nz = intNp1mem + (N+1)*13; int* ny = intNp1mem + (N+1)*14; int* nr = intNp1mem + (N+1)*15; int* nbxe = intNp1mem + (N+1)*16; for (int i = 0; i < N+1; i++) { // common nx[i] = NX; nu[i] = NU; nz[i] = NZ; ns[i] = NS; // cost ny[i] = NY; // constraints nbx[i] = NBX; nbu[i] = NBU; nsbx[i] = NSBX; nsbu[i] = NSBU; nsg[i] = NSG; nsh[i] = NSH; nsphi[i] = NSPHI; ng[i] = NG; nh[i] = NH; nphi[i] = NPHI; nr[i] = NR; nbxe[i] = 0; } // for initial state nbx[0] = NBX0; nsbx[0] = 0; ns[0] = NS - NSBX; nbxe[0] = {{ dims.nbxe_0 }}; ny[0] = NY0; // terminal - common nu[N] = 0; nz[N] = 0; ns[N] = NSN; // cost ny[N] = NYN; // constraint nbx[N] = NBXN; nbu[N] = 0; ng[N] = NGN; nh[N] = NHN; nphi[N] = NPHIN; nr[N] = {{ dims.nr_e }}; nsbx[N] = NSBXN; nsbu[N] = 0; nsg[N] = NSGN; nsh[N] = NSHN; nsphi[N] = NSPHIN; /* create and set ocp_nlp_dims */ ocp_nlp_dims * nlp_dims = ocp_nlp_dims_create(nlp_config); capsule->nlp_dims = nlp_dims; ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nx", nx); ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nu", nu); ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "nz", nz); ocp_nlp_dims_set_opt_vars(nlp_config, nlp_dims, "ns", ns); for (int i = 0; i <= N; i++) { ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbx", &nbx[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbu", &nbu[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbx", &nsbx[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsbu", &nsbu[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "ng", &ng[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsg", &nsg[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nbxe", &nbxe[i]); } {%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} ocp_nlp_dims_set_cost(nlp_config, nlp_dims, 0, "ny", &ny[0]); {%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} for (int i = 1; i < N; i++) ocp_nlp_dims_set_cost(nlp_config, nlp_dims, i, "ny", &ny[i]); {%- endif %} for (int i = 0; i < N; i++) { {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nh", &nh[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsh", &nsh[i]); {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nr", &nr[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nphi", &nphi[i]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, i, "nsphi", &nsphi[i]); {%- endif %} } {%- if constraints.constr_type_e == "BGH" %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nh", &nh[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsh", &nsh[N]); {%- elif constraints.constr_type_e == "BGP" %} ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nr", &nr[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nphi", &nphi[N]); ocp_nlp_dims_set_constraints(nlp_config, nlp_dims, N, "nsphi", &nsphi[N]); {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" or cost.cost_type_e == "LINEAR_LS" %} ocp_nlp_dims_set_cost(nlp_config, nlp_dims, N, "ny", &ny[N]); {%- endif %} free(intNp1mem); {% if solver_options.integrator_type == "GNSF" -%} // GNSF specific dimensions int gnsf_nx1 = {{ dims.gnsf_nx1 }}; int gnsf_nz1 = {{ dims.gnsf_nz1 }}; int gnsf_nout = {{ dims.gnsf_nout }}; int gnsf_ny = {{ dims.gnsf_ny }}; int gnsf_nuhat = {{ dims.gnsf_nuhat }}; for (int i = 0; i < N; i++) { if (nlp_solver_plan->sim_solver_plan[i].sim_solver == GNSF) { ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nx1", &gnsf_nx1); ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nz1", &gnsf_nz1); ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nout", &gnsf_nout); ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_ny", &gnsf_ny); ocp_nlp_dims_set_dynamics(nlp_config, nlp_dims, i, "gnsf_nuhat", &gnsf_nuhat); } } {%- endif %} /************************************************ * external functions ************************************************/ {%- if constraints.constr_type == "BGP" %} capsule->phi_constraint = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { // nonlinear part of convex-composite constraint capsule->phi_constraint[i].casadi_fun = &{{ model.name }}_phi_constraint; capsule->phi_constraint[i].casadi_n_in = &{{ model.name }}_phi_constraint_n_in; capsule->phi_constraint[i].casadi_n_out = &{{ model.name }}_phi_constraint_n_out; capsule->phi_constraint[i].casadi_sparsity_in = &{{ model.name }}_phi_constraint_sparsity_in; capsule->phi_constraint[i].casadi_sparsity_out = &{{ model.name }}_phi_constraint_sparsity_out; capsule->phi_constraint[i].casadi_work = &{{ model.name }}_phi_constraint_work; external_function_param_casadi_create(&capsule->phi_constraint[i], {{ dims.np }}); } {%- endif %} {%- if constraints.constr_type_e == "BGP" %} // nonlinear part of convex-composite constraint capsule->phi_e_constraint.casadi_fun = &{{ model.name }}_phi_e_constraint; capsule->phi_e_constraint.casadi_n_in = &{{ model.name }}_phi_e_constraint_n_in; capsule->phi_e_constraint.casadi_n_out = &{{ model.name }}_phi_e_constraint_n_out; capsule->phi_e_constraint.casadi_sparsity_in = &{{ model.name }}_phi_e_constraint_sparsity_in; capsule->phi_e_constraint.casadi_sparsity_out = &{{ model.name }}_phi_e_constraint_sparsity_out; capsule->phi_e_constraint.casadi_work = &{{ model.name }}_phi_e_constraint_work; external_function_param_casadi_create(&capsule->phi_e_constraint, {{ dims.np }}); {% endif %} {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} capsule->nl_constr_h_fun_jac = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->nl_constr_h_fun_jac[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_zt; capsule->nl_constr_h_fun_jac[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_in; capsule->nl_constr_h_fun_jac[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_n_out; capsule->nl_constr_h_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_in; capsule->nl_constr_h_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_sparsity_out; capsule->nl_constr_h_fun_jac[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_zt_work; external_function_param_casadi_create(&capsule->nl_constr_h_fun_jac[i], {{ dims.np }}); } capsule->nl_constr_h_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->nl_constr_h_fun[i].casadi_fun = &{{ model.name }}_constr_h_fun; capsule->nl_constr_h_fun[i].casadi_n_in = &{{ model.name }}_constr_h_fun_n_in; capsule->nl_constr_h_fun[i].casadi_n_out = &{{ model.name }}_constr_h_fun_n_out; capsule->nl_constr_h_fun[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_sparsity_in; capsule->nl_constr_h_fun[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_sparsity_out; capsule->nl_constr_h_fun[i].casadi_work = &{{ model.name }}_constr_h_fun_work; external_function_param_casadi_create(&capsule->nl_constr_h_fun[i], {{ dims.np }}); } {% if solver_options.hessian_approx == "EXACT" %} capsule->nl_constr_h_fun_jac_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->nl_constr_h_fun_jac_hess[i].casadi_fun = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess; capsule->nl_constr_h_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_in; capsule->nl_constr_h_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_n_out; capsule->nl_constr_h_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_in; capsule->nl_constr_h_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_sparsity_out; capsule->nl_constr_h_fun_jac_hess[i].casadi_work = &{{ model.name }}_constr_h_fun_jac_uxt_zt_hess_work; external_function_param_casadi_create(&capsule->nl_constr_h_fun_jac_hess[i], {{ dims.np }}); } {% endif %} {% endif %} {%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} capsule->nl_constr_h_e_fun_jac.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt; capsule->nl_constr_h_e_fun_jac.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_in; capsule->nl_constr_h_e_fun_jac.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_n_out; capsule->nl_constr_h_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_in; capsule->nl_constr_h_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_sparsity_out; capsule->nl_constr_h_e_fun_jac.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_work; external_function_param_casadi_create(&capsule->nl_constr_h_e_fun_jac, {{ dims.np }}); capsule->nl_constr_h_e_fun.casadi_fun = &{{ model.name }}_constr_h_e_fun; capsule->nl_constr_h_e_fun.casadi_n_in = &{{ model.name }}_constr_h_e_fun_n_in; capsule->nl_constr_h_e_fun.casadi_n_out = &{{ model.name }}_constr_h_e_fun_n_out; capsule->nl_constr_h_e_fun.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_sparsity_in; capsule->nl_constr_h_e_fun.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_sparsity_out; capsule->nl_constr_h_e_fun.casadi_work = &{{ model.name }}_constr_h_e_fun_work; external_function_param_casadi_create(&capsule->nl_constr_h_e_fun, {{ dims.np }}); {% if solver_options.hessian_approx == "EXACT" %} capsule->nl_constr_h_e_fun_jac_hess.casadi_fun = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess; capsule->nl_constr_h_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_in; capsule->nl_constr_h_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_n_out; capsule->nl_constr_h_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_in; capsule->nl_constr_h_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_sparsity_out; capsule->nl_constr_h_e_fun_jac_hess.casadi_work = &{{ model.name }}_constr_h_e_fun_jac_uxt_zt_hess_work; external_function_param_casadi_create(&capsule->nl_constr_h_e_fun_jac_hess, {{ dims.np }}); {% endif %} {%- endif %} {% if solver_options.integrator_type == "ERK" %} // explicit ode capsule->forw_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->forw_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_vde_forw; capsule->forw_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_vde_forw_n_in; capsule->forw_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_vde_forw_n_out; capsule->forw_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_vde_forw_sparsity_in; capsule->forw_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_vde_forw_sparsity_out; capsule->forw_vde_casadi[i].casadi_work = &{{ model.name }}_expl_vde_forw_work; external_function_param_casadi_create(&capsule->forw_vde_casadi[i], {{ dims.np }}); } capsule->expl_ode_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->expl_ode_fun[i].casadi_fun = &{{ model.name }}_expl_ode_fun; capsule->expl_ode_fun[i].casadi_n_in = &{{ model.name }}_expl_ode_fun_n_in; capsule->expl_ode_fun[i].casadi_n_out = &{{ model.name }}_expl_ode_fun_n_out; capsule->expl_ode_fun[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_fun_sparsity_in; capsule->expl_ode_fun[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_fun_sparsity_out; capsule->expl_ode_fun[i].casadi_work = &{{ model.name }}_expl_ode_fun_work; external_function_param_casadi_create(&capsule->expl_ode_fun[i], {{ dims.np }}); } {%- if solver_options.hessian_approx == "EXACT" %} capsule->hess_vde_casadi = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->hess_vde_casadi[i].casadi_fun = &{{ model.name }}_expl_ode_hess; capsule->hess_vde_casadi[i].casadi_n_in = &{{ model.name }}_expl_ode_hess_n_in; capsule->hess_vde_casadi[i].casadi_n_out = &{{ model.name }}_expl_ode_hess_n_out; capsule->hess_vde_casadi[i].casadi_sparsity_in = &{{ model.name }}_expl_ode_hess_sparsity_in; capsule->hess_vde_casadi[i].casadi_sparsity_out = &{{ model.name }}_expl_ode_hess_sparsity_out; capsule->hess_vde_casadi[i].casadi_work = &{{ model.name }}_expl_ode_hess_work; external_function_param_casadi_create(&capsule->hess_vde_casadi[i], {{ dims.np }}); } {%- endif %} {% elif solver_options.integrator_type == "IRK" %} // implicit dae capsule->impl_dae_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_fun[i].casadi_fun = &{{ model.name }}_impl_dae_fun; capsule->impl_dae_fun[i].casadi_work = &{{ model.name }}_impl_dae_fun_work; capsule->impl_dae_fun[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; capsule->impl_dae_fun[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; capsule->impl_dae_fun[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; capsule->impl_dae_fun[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; external_function_param_casadi_create(&capsule->impl_dae_fun[i], {{ dims.np }}); } capsule->impl_dae_fun_jac_x_xdot_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z; capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_work; capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_in; capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_sparsity_out; capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_in; capsule->impl_dae_fun_jac_x_xdot_z[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_z_n_out; external_function_param_casadi_create(&capsule->impl_dae_fun_jac_x_xdot_z[i], {{ dims.np }}); } capsule->impl_dae_jac_x_xdot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_jac_x_xdot_u_z[i].casadi_fun = &{{ model.name }}_impl_dae_jac_x_xdot_u_z; capsule->impl_dae_jac_x_xdot_u_z[i].casadi_work = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_work; capsule->impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_in; capsule->impl_dae_jac_x_xdot_u_z[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_sparsity_out; capsule->impl_dae_jac_x_xdot_u_z[i].casadi_n_in = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_in; capsule->impl_dae_jac_x_xdot_u_z[i].casadi_n_out = &{{ model.name }}_impl_dae_jac_x_xdot_u_z_n_out; external_function_param_casadi_create(&capsule->impl_dae_jac_x_xdot_u_z[i], {{ dims.np }}); } {%- if solver_options.hessian_approx == "EXACT" %} capsule->impl_dae_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_hess[i].casadi_fun = &{{ model.name }}_impl_dae_hess; capsule->impl_dae_hess[i].casadi_work = &{{ model.name }}_impl_dae_hess_work; capsule->impl_dae_hess[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_hess_sparsity_in; capsule->impl_dae_hess[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_hess_sparsity_out; capsule->impl_dae_hess[i].casadi_n_in = &{{ model.name }}_impl_dae_hess_n_in; capsule->impl_dae_hess[i].casadi_n_out = &{{ model.name }}_impl_dae_hess_n_out; external_function_param_casadi_create(&capsule->impl_dae_hess[i], {{ dims.np }}); } {%- endif %} {% elif solver_options.integrator_type == "LIFTED_IRK" %} // external functions (implicit model) capsule->impl_dae_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_fun[i].casadi_fun = &{{ model.name }}_impl_dae_fun; capsule->impl_dae_fun[i].casadi_work = &{{ model.name }}_impl_dae_fun_work; capsule->impl_dae_fun[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_sparsity_in; capsule->impl_dae_fun[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_sparsity_out; capsule->impl_dae_fun[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_n_in; capsule->impl_dae_fun[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_n_out; external_function_param_casadi_create(&capsule->impl_dae_fun[i], {{ dims.np }}); } capsule->impl_dae_fun_jac_x_xdot_u = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_fun = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u; capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_work = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_work; capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_sparsity_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_in; capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_sparsity_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_sparsity_out; capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_n_in = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_in; capsule->impl_dae_fun_jac_x_xdot_u[i].casadi_n_out = &{{ model.name }}_impl_dae_fun_jac_x_xdot_u_n_out; external_function_param_casadi_create(&capsule->impl_dae_fun_jac_x_xdot_u[i], {{ dims.np }}); } {% elif solver_options.integrator_type == "GNSF" %} {% if model.gnsf.purely_linear != 1 %} capsule->gnsf_phi_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->gnsf_phi_fun[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun; capsule->gnsf_phi_fun[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_work; capsule->gnsf_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_sparsity_in; capsule->gnsf_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_sparsity_out; capsule->gnsf_phi_fun[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_n_in; capsule->gnsf_phi_fun[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_n_out; external_function_param_casadi_create(&capsule->gnsf_phi_fun[i], {{ dims.np }}); } capsule->gnsf_phi_fun_jac_y = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->gnsf_phi_fun_jac_y[i].casadi_fun = &{{ model.name }}_gnsf_phi_fun_jac_y; capsule->gnsf_phi_fun_jac_y[i].casadi_work = &{{ model.name }}_gnsf_phi_fun_jac_y_work; capsule->gnsf_phi_fun_jac_y[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_in; capsule->gnsf_phi_fun_jac_y[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_fun_jac_y_sparsity_out; capsule->gnsf_phi_fun_jac_y[i].casadi_n_in = &{{ model.name }}_gnsf_phi_fun_jac_y_n_in; capsule->gnsf_phi_fun_jac_y[i].casadi_n_out = &{{ model.name }}_gnsf_phi_fun_jac_y_n_out; external_function_param_casadi_create(&capsule->gnsf_phi_fun_jac_y[i], {{ dims.np }}); } capsule->gnsf_phi_jac_y_uhat = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->gnsf_phi_jac_y_uhat[i].casadi_fun = &{{ model.name }}_gnsf_phi_jac_y_uhat; capsule->gnsf_phi_jac_y_uhat[i].casadi_work = &{{ model.name }}_gnsf_phi_jac_y_uhat_work; capsule->gnsf_phi_jac_y_uhat[i].casadi_sparsity_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_in; capsule->gnsf_phi_jac_y_uhat[i].casadi_sparsity_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_sparsity_out; capsule->gnsf_phi_jac_y_uhat[i].casadi_n_in = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_in; capsule->gnsf_phi_jac_y_uhat[i].casadi_n_out = &{{ model.name }}_gnsf_phi_jac_y_uhat_n_out; external_function_param_casadi_create(&capsule->gnsf_phi_jac_y_uhat[i], {{ dims.np }}); } {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->gnsf_f_lo_jac_x1_x1dot_u_z = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_fun = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz; capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_work = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_work; capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_in; capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_sparsity_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_sparsity_out; capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_in = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_in; capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i].casadi_n_out = &{{ model.name }}_gnsf_f_lo_fun_jac_x1k1uz_n_out; external_function_param_casadi_create(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i], {{ dims.np }}); } {%- endif %} {%- endif %} capsule->gnsf_get_matrices_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N; i++) { capsule->gnsf_get_matrices_fun[i].casadi_fun = &{{ model.name }}_gnsf_get_matrices_fun; capsule->gnsf_get_matrices_fun[i].casadi_work = &{{ model.name }}_gnsf_get_matrices_fun_work; capsule->gnsf_get_matrices_fun[i].casadi_sparsity_in = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_in; capsule->gnsf_get_matrices_fun[i].casadi_sparsity_out = &{{ model.name }}_gnsf_get_matrices_fun_sparsity_out; capsule->gnsf_get_matrices_fun[i].casadi_n_in = &{{ model.name }}_gnsf_get_matrices_fun_n_in; capsule->gnsf_get_matrices_fun[i].casadi_n_out = &{{ model.name }}_gnsf_get_matrices_fun_n_out; external_function_param_casadi_create(&capsule->gnsf_get_matrices_fun[i], {{ dims.np }}); } {% elif solver_options.integrator_type == "DISCRETE" %} // discrete dynamics capsule->discr_dyn_phi_fun = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} capsule->discr_dyn_phi_fun[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun; capsule->discr_dyn_phi_fun[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_n_in; capsule->discr_dyn_phi_fun[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_n_out; capsule->discr_dyn_phi_fun[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_sparsity_in; capsule->discr_dyn_phi_fun[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_sparsity_out; capsule->discr_dyn_phi_fun[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_work; {%- else %} capsule->discr_dyn_phi_fun[i].fun = &{{ model.dyn_disc_fun }}; {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun[i], {{ dims.np }}); } capsule->discr_dyn_phi_fun_jac_ut_xt = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac; capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_n_in; capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_n_out; capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_in; capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_sparsity_out; capsule->discr_dyn_phi_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_work; {%- else %} capsule->discr_dyn_phi_fun_jac_ut_xt[i].fun = &{{ model.dyn_disc_fun_jac }}; {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt[i], {{ dims.np }}); } {%- if solver_options.hessian_approx == "EXACT" %} capsule->discr_dyn_phi_fun_jac_ut_xt_hess = (external_function_param_{{ model.dyn_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ model.dyn_ext_fun_type }})*N); for (int i = 0; i < N; i++) { {%- if model.dyn_ext_fun_type == "casadi" %} capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_fun = &{{ model.name }}_dyn_disc_phi_fun_jac_hess; capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_in; capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_n_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_n_out; capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_in = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_in; capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_sparsity_out = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_sparsity_out; capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].casadi_work = &{{ model.name }}_dyn_disc_phi_fun_jac_hess_work; {%- else %} capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i].fun = &{{ model.dyn_disc_fun_jac_hess }}; {%- endif %} external_function_param_{{ model.dyn_ext_fun_type }}_create(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i], {{ dims.np }}); } {%- endif %} {%- endif %} {%- if cost.cost_type_0 == "NONLINEAR_LS" %} // nonlinear least square function capsule->cost_y_0_fun.casadi_fun = &{{ model.name }}_cost_y_0_fun; capsule->cost_y_0_fun.casadi_n_in = &{{ model.name }}_cost_y_0_fun_n_in; capsule->cost_y_0_fun.casadi_n_out = &{{ model.name }}_cost_y_0_fun_n_out; capsule->cost_y_0_fun.casadi_sparsity_in = &{{ model.name }}_cost_y_0_fun_sparsity_in; capsule->cost_y_0_fun.casadi_sparsity_out = &{{ model.name }}_cost_y_0_fun_sparsity_out; capsule->cost_y_0_fun.casadi_work = &{{ model.name }}_cost_y_0_fun_work; external_function_param_casadi_create(&capsule->cost_y_0_fun, {{ dims.np }}); capsule->cost_y_0_fun_jac_ut_xt.casadi_fun = &{{ model.name }}_cost_y_0_fun_jac_ut_xt; capsule->cost_y_0_fun_jac_ut_xt.casadi_n_in = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_n_in; capsule->cost_y_0_fun_jac_ut_xt.casadi_n_out = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_n_out; capsule->cost_y_0_fun_jac_ut_xt.casadi_sparsity_in = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_in; capsule->cost_y_0_fun_jac_ut_xt.casadi_sparsity_out = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_sparsity_out; capsule->cost_y_0_fun_jac_ut_xt.casadi_work = &{{ model.name }}_cost_y_0_fun_jac_ut_xt_work; external_function_param_casadi_create(&capsule->cost_y_0_fun_jac_ut_xt, {{ dims.np }}); capsule->cost_y_0_hess.casadi_fun = &{{ model.name }}_cost_y_0_hess; capsule->cost_y_0_hess.casadi_n_in = &{{ model.name }}_cost_y_0_hess_n_in; capsule->cost_y_0_hess.casadi_n_out = &{{ model.name }}_cost_y_0_hess_n_out; capsule->cost_y_0_hess.casadi_sparsity_in = &{{ model.name }}_cost_y_0_hess_sparsity_in; capsule->cost_y_0_hess.casadi_sparsity_out = &{{ model.name }}_cost_y_0_hess_sparsity_out; capsule->cost_y_0_hess.casadi_work = &{{ model.name }}_cost_y_0_hess_work; external_function_param_casadi_create(&capsule->cost_y_0_hess, {{ dims.np }}); {%- elif cost.cost_type_0 == "EXTERNAL" %} // external cost {% if cost.cost_ext_fun_type_0 == "casadi" %} capsule->ext_cost_0_fun.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun; capsule->ext_cost_0_fun.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_n_in; capsule->ext_cost_0_fun.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_n_out; capsule->ext_cost_0_fun.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_sparsity_in; capsule->ext_cost_0_fun.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_sparsity_out; capsule->ext_cost_0_fun.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_work; {% else %} capsule->ext_cost_0_fun.fun = &{{ cost.cost_function_ext_cost_0 }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun, {{ dims.np }}); // external cost {% if cost.cost_ext_fun_type_0 == "casadi" %} capsule->ext_cost_0_fun_jac.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun_jac; capsule->ext_cost_0_fun_jac.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_n_in; capsule->ext_cost_0_fun_jac.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_n_out; capsule->ext_cost_0_fun_jac.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_in; capsule->ext_cost_0_fun_jac.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_sparsity_out; capsule->ext_cost_0_fun_jac.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_jac_work; {% else %} capsule->ext_cost_0_fun_jac.fun = &{{ cost.cost_function_ext_cost_0 }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac, {{ dims.np }}); // external cost {% if cost.cost_ext_fun_type_0 == "casadi" %} capsule->ext_cost_0_fun_jac_hess.casadi_fun = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess; capsule->ext_cost_0_fun_jac_hess.casadi_n_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_in; capsule->ext_cost_0_fun_jac_hess.casadi_n_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_n_out; capsule->ext_cost_0_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_in; capsule->ext_cost_0_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_sparsity_out; capsule->ext_cost_0_fun_jac_hess.casadi_work = &{{ model.name }}_cost_ext_cost_0_fun_jac_hess_work; {% else %} capsule->ext_cost_0_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_0 }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_create(&capsule->ext_cost_0_fun_jac_hess, {{ dims.np }}); {%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" %} // nonlinear least squares cost capsule->cost_y_fun = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { capsule->cost_y_fun[i].casadi_fun = &{{ model.name }}_cost_y_fun; capsule->cost_y_fun[i].casadi_n_in = &{{ model.name }}_cost_y_fun_n_in; capsule->cost_y_fun[i].casadi_n_out = &{{ model.name }}_cost_y_fun_n_out; capsule->cost_y_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_sparsity_in; capsule->cost_y_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_sparsity_out; capsule->cost_y_fun[i].casadi_work = &{{ model.name }}_cost_y_fun_work; external_function_param_casadi_create(&capsule->cost_y_fun[i], {{ dims.np }}); } capsule->cost_y_fun_jac_ut_xt = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { capsule->cost_y_fun_jac_ut_xt[i].casadi_fun = &{{ model.name }}_cost_y_fun_jac_ut_xt; capsule->cost_y_fun_jac_ut_xt[i].casadi_n_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_in; capsule->cost_y_fun_jac_ut_xt[i].casadi_n_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_n_out; capsule->cost_y_fun_jac_ut_xt[i].casadi_sparsity_in = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_in; capsule->cost_y_fun_jac_ut_xt[i].casadi_sparsity_out = &{{ model.name }}_cost_y_fun_jac_ut_xt_sparsity_out; capsule->cost_y_fun_jac_ut_xt[i].casadi_work = &{{ model.name }}_cost_y_fun_jac_ut_xt_work; external_function_param_casadi_create(&capsule->cost_y_fun_jac_ut_xt[i], {{ dims.np }}); } capsule->cost_y_hess = (external_function_param_casadi *) malloc(sizeof(external_function_param_casadi)*N); for (int i = 0; i < N-1; i++) { capsule->cost_y_hess[i].casadi_fun = &{{ model.name }}_cost_y_hess; capsule->cost_y_hess[i].casadi_n_in = &{{ model.name }}_cost_y_hess_n_in; capsule->cost_y_hess[i].casadi_n_out = &{{ model.name }}_cost_y_hess_n_out; capsule->cost_y_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_y_hess_sparsity_in; capsule->cost_y_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_y_hess_sparsity_out; capsule->cost_y_hess[i].casadi_work = &{{ model.name }}_cost_y_hess_work; external_function_param_casadi_create(&capsule->cost_y_hess[i], {{ dims.np }}); } {%- elif cost.cost_type == "EXTERNAL" %} // external cost capsule->ext_cost_fun = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { {% if cost.cost_ext_fun_type == "casadi" %} capsule->ext_cost_fun[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun; capsule->ext_cost_fun[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_n_in; capsule->ext_cost_fun[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_n_out; capsule->ext_cost_fun[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_sparsity_in; capsule->ext_cost_fun[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_sparsity_out; capsule->ext_cost_fun[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_work; {% else %} capsule->ext_cost_fun[i].fun = &{{ cost.cost_function_ext_cost }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun[i], {{ dims.np }}); } capsule->ext_cost_fun_jac = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { {% if cost.cost_ext_fun_type == "casadi" %} capsule->ext_cost_fun_jac[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac; capsule->ext_cost_fun_jac[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_n_in; capsule->ext_cost_fun_jac[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_n_out; capsule->ext_cost_fun_jac[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_in; capsule->ext_cost_fun_jac[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_sparsity_out; capsule->ext_cost_fun_jac[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_work; {% else %} capsule->ext_cost_fun_jac[i].fun = &{{ cost.cost_function_ext_cost }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac[i], {{ dims.np }}); } capsule->ext_cost_fun_jac_hess = (external_function_param_{{ cost.cost_ext_fun_type }} *) malloc(sizeof(external_function_param_{{ cost.cost_ext_fun_type }})*N); for (int i = 0; i < N-1; i++) { {% if cost.cost_ext_fun_type == "casadi" %} capsule->ext_cost_fun_jac_hess[i].casadi_fun = &{{ model.name }}_cost_ext_cost_fun_jac_hess; capsule->ext_cost_fun_jac_hess[i].casadi_n_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_in; capsule->ext_cost_fun_jac_hess[i].casadi_n_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_n_out; capsule->ext_cost_fun_jac_hess[i].casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_in; capsule->ext_cost_fun_jac_hess[i].casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_fun_jac_hess_sparsity_out; capsule->ext_cost_fun_jac_hess[i].casadi_work = &{{ model.name }}_cost_ext_cost_fun_jac_hess_work; {% else %} capsule->ext_cost_fun_jac_hess[i].fun = &{{ cost.cost_function_ext_cost }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type }}_create(&capsule->ext_cost_fun_jac_hess[i], {{ dims.np }}); } {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" %} // nonlinear least square function capsule->cost_y_e_fun.casadi_fun = &{{ model.name }}_cost_y_e_fun; capsule->cost_y_e_fun.casadi_n_in = &{{ model.name }}_cost_y_e_fun_n_in; capsule->cost_y_e_fun.casadi_n_out = &{{ model.name }}_cost_y_e_fun_n_out; capsule->cost_y_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_sparsity_in; capsule->cost_y_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_sparsity_out; capsule->cost_y_e_fun.casadi_work = &{{ model.name }}_cost_y_e_fun_work; external_function_param_casadi_create(&capsule->cost_y_e_fun, {{ dims.np }}); capsule->cost_y_e_fun_jac_ut_xt.casadi_fun = &{{ model.name }}_cost_y_e_fun_jac_ut_xt; capsule->cost_y_e_fun_jac_ut_xt.casadi_n_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_in; capsule->cost_y_e_fun_jac_ut_xt.casadi_n_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_n_out; capsule->cost_y_e_fun_jac_ut_xt.casadi_sparsity_in = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_in; capsule->cost_y_e_fun_jac_ut_xt.casadi_sparsity_out = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_sparsity_out; capsule->cost_y_e_fun_jac_ut_xt.casadi_work = &{{ model.name }}_cost_y_e_fun_jac_ut_xt_work; external_function_param_casadi_create(&capsule->cost_y_e_fun_jac_ut_xt, {{ dims.np }}); capsule->cost_y_e_hess.casadi_fun = &{{ model.name }}_cost_y_e_hess; capsule->cost_y_e_hess.casadi_n_in = &{{ model.name }}_cost_y_e_hess_n_in; capsule->cost_y_e_hess.casadi_n_out = &{{ model.name }}_cost_y_e_hess_n_out; capsule->cost_y_e_hess.casadi_sparsity_in = &{{ model.name }}_cost_y_e_hess_sparsity_in; capsule->cost_y_e_hess.casadi_sparsity_out = &{{ model.name }}_cost_y_e_hess_sparsity_out; capsule->cost_y_e_hess.casadi_work = &{{ model.name }}_cost_y_e_hess_work; external_function_param_casadi_create(&capsule->cost_y_e_hess, {{ dims.np }}); {%- elif cost.cost_type_e == "EXTERNAL" %} // external cost {% if cost.cost_ext_fun_type_e == "casadi" %} capsule->ext_cost_e_fun.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun; capsule->ext_cost_e_fun.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_n_in; capsule->ext_cost_e_fun.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_n_out; capsule->ext_cost_e_fun.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_in; capsule->ext_cost_e_fun.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_sparsity_out; capsule->ext_cost_e_fun.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_work; {% else %} capsule->ext_cost_e_fun.fun = &{{ cost.cost_function_ext_cost_e }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun, {{ dims.np }}); // external cost {% if cost.cost_ext_fun_type_e == "casadi" %} capsule->ext_cost_e_fun_jac.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac; capsule->ext_cost_e_fun_jac.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_in; capsule->ext_cost_e_fun_jac.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_n_out; capsule->ext_cost_e_fun_jac.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_in; capsule->ext_cost_e_fun_jac.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_sparsity_out; capsule->ext_cost_e_fun_jac.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_work; {% else %} capsule->ext_cost_e_fun_jac.fun = &{{ cost.cost_function_ext_cost_e }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac, {{ dims.np }}); // external cost {% if cost.cost_ext_fun_type_e == "casadi" %} capsule->ext_cost_e_fun_jac_hess.casadi_fun = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess; capsule->ext_cost_e_fun_jac_hess.casadi_n_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_in; capsule->ext_cost_e_fun_jac_hess.casadi_n_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_n_out; capsule->ext_cost_e_fun_jac_hess.casadi_sparsity_in = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_in; capsule->ext_cost_e_fun_jac_hess.casadi_sparsity_out = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_sparsity_out; capsule->ext_cost_e_fun_jac_hess.casadi_work = &{{ model.name }}_cost_ext_cost_e_fun_jac_hess_work; {% else %} capsule->ext_cost_e_fun_jac_hess.fun = &{{ cost.cost_function_ext_cost_e }}; {% endif %} external_function_param_{{ cost.cost_ext_fun_type_e }}_create(&capsule->ext_cost_e_fun_jac_hess, {{ dims.np }}); {%- endif %} /************************************************ * nlp_in ************************************************/ ocp_nlp_in * nlp_in = ocp_nlp_in_create(nlp_config, nlp_dims); capsule->nlp_in = nlp_in; // set up time_steps {% set all_equal = true -%} {%- set val = solver_options.time_steps[0] %} {%- for j in range(start=1, end=dims.N) %} {%- if val != solver_options.time_steps[j] %} {%- set_global all_equal = false %} {%- break %} {%- endif %} {%- endfor %} if (new_time_steps) { {{ model.name }}_acados_update_time_steps(capsule, N, new_time_steps); } else { {%- if all_equal == true -%} // all time_steps are identical double time_step = {{ solver_options.time_steps[0] }}; for (int i = 0; i < N; i++) { ocp_nlp_in_set(nlp_config, nlp_dims, nlp_in, i, "Ts", &time_step); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "scaling", &time_step); } {%- else -%} // time_steps are different double* time_steps = malloc(N*sizeof(double)); {%- for j in range(end=dims.N) %} time_steps[{{ j }}] = {{ solver_options.time_steps[j] }}; {%- endfor %} {{ model.name }}_acados_update_time_steps(capsule, N, time_steps); free(time_steps); {%- endif %} } /**** Dynamics ****/ for (int i = 0; i < N; i++) { {%- if solver_options.integrator_type == "ERK" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_vde_forw", &capsule->forw_vde_casadi[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_fun", &capsule->expl_ode_fun[i]); {%- if solver_options.hessian_approx == "EXACT" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "expl_ode_hess", &capsule->hess_vde_casadi[i]); {%- endif %} {% elif solver_options.integrator_type == "IRK" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun_jac_x_xdot_z", &capsule->impl_dae_fun_jac_x_xdot_z[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_jac_x_xdot_u", &capsule->impl_dae_jac_x_xdot_u_z[i]); {%- if solver_options.hessian_approx == "EXACT" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_hess", &capsule->impl_dae_hess[i]); {%- endif %} {% elif solver_options.integrator_type == "LIFTED_IRK" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun", &capsule->impl_dae_fun[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "impl_dae_fun_jac_x_xdot_u", &capsule->impl_dae_fun_jac_x_xdot_u[i]); {% elif solver_options.integrator_type == "GNSF" %} {% if model.gnsf.purely_linear != 1 %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun", &capsule->gnsf_phi_fun[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_fun_jac_y", &capsule->gnsf_phi_fun_jac_y[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "phi_jac_y_uhat", &capsule->gnsf_phi_jac_y_uhat[i]); {% if model.gnsf.nontrivial_f_LO == 1 %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "f_lo_jac_x1_x1dot_u_z", &capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); {%- endif %} {%- endif %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "gnsf_get_matrices_fun", &capsule->gnsf_get_matrices_fun[i]); {% elif solver_options.integrator_type == "DISCRETE" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun", &capsule->discr_dyn_phi_fun[i]); ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac", &capsule->discr_dyn_phi_fun_jac_ut_xt[i]); {%- if solver_options.hessian_approx == "EXACT" %} ocp_nlp_dynamics_model_set(nlp_config, nlp_dims, nlp_in, i, "disc_dyn_fun_jac_hess", &capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); {%- endif %} {%- endif %} } /**** Cost ****/ {%- if cost.cost_type_0 == "NONLINEAR_LS" or cost.cost_type_0 == "LINEAR_LS" %} {% if dims.ny_0 > 0 %} double* W_0 = calloc(NY0*NY0, sizeof(double)); // change only the non-zero elements: {%- for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.ny_0) %} {%- if cost.W_0[j][k] != 0 %} W_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.W_0[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "W", W_0); free(W_0); double* yref_0 = calloc(NY0, sizeof(double)); // change only the non-zero elements: {%- for j in range(end=dims.ny_0) %} {%- if cost.yref_0[j] != 0 %} yref_0[{{ j }}] = {{ cost.yref_0[j] }}; {%- endif %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "yref", yref_0); free(yref_0); {% endif %} {% endif %} {%- if cost.cost_type == "NONLINEAR_LS" or cost.cost_type == "LINEAR_LS" %} {% if dims.ny > 0 %} double* W = calloc(NY*NY, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} {%- for k in range(end=dims.ny) %} {%- if cost.W[j][k] != 0 %} W[{{ j }}+(NY) * {{ k }}] = {{ cost.W[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} double* yref = calloc(NY, sizeof(double)); // change only the non-zero elements: {%- for j in range(end=dims.ny) %} {%- if cost.yref[j] != 0 %} yref[{{ j }}] = {{ cost.yref[j] }}; {%- endif %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "W", W); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "yref", yref); } free(W); free(yref); {% endif %} {% endif %} {%- if cost.cost_type_0 == "LINEAR_LS" %} double* Vx_0 = calloc(NY0*NX, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.nx) %} {%- if cost.Vx_0[j][k] != 0 %} Vx_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vx_0[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vx", Vx_0); free(Vx_0); {% if dims.ny_0 > 0 and dims.nu > 0 %} double* Vu_0 = calloc(NY0*NU, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.nu) %} {%- if cost.Vu_0[j][k] != 0 %} Vu_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vu_0[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vu", Vu_0); free(Vu_0); {% endif %} {% if dims.ny_0 > 0 and dims.nz > 0 %} double* Vz_0 = calloc(NY0*NZ, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_0) %} {%- for k in range(end=dims.nz) %} {%- if cost.Vz_0[j][k] != 0 %} Vz_0[{{ j }}+(NY0) * {{ k }}] = {{ cost.Vz_0[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "Vz", Vz_0); free(Vz_0); {%- endif %} {%- endif %}{# LINEAR LS #} {%- if cost.cost_type == "LINEAR_LS" %} double* Vx = calloc(NY*NX, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} {%- for k in range(end=dims.nx) %} {%- if cost.Vx[j][k] != 0 %} Vx[{{ j }}+(NY) * {{ k }}] = {{ cost.Vx[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vx", Vx); } free(Vx); {% if dims.ny > 0 and dims.nu > 0 %} double* Vu = calloc(NY*NU, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} {%- for k in range(end=dims.nu) %} {%- if cost.Vu[j][k] != 0 %} Vu[{{ j }}+(NY) * {{ k }}] = {{ cost.Vu[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vu", Vu); } free(Vu); {% endif %} {% if dims.ny > 0 and dims.nz > 0 %} double* Vz = calloc(NY*NZ, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny) %} {%- for k in range(end=dims.nz) %} {%- if cost.Vz[j][k] != 0 %} Vz[{{ j }}+(NY) * {{ k }}] = {{ cost.Vz[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Vz", Vz); } free(Vz); {%- endif %} {%- endif %}{# LINEAR LS #} {%- if cost.cost_type_0 == "NONLINEAR_LS" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun", &capsule->cost_y_0_fun); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_fun_jac", &capsule->cost_y_0_fun_jac_ut_xt); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "nls_y_hess", &capsule->cost_y_0_hess); {%- elif cost.cost_type_0 == "EXTERNAL" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun", &capsule->ext_cost_0_fun); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac", &capsule->ext_cost_0_fun_jac); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, 0, "ext_cost_fun_jac_hess", &capsule->ext_cost_0_fun_jac_hess); {%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun", &capsule->cost_y_fun[i-1]); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_fun_jac", &capsule->cost_y_fun_jac_ut_xt[i-1]); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "nls_y_hess", &capsule->cost_y_hess[i-1]); } {%- elif cost.cost_type == "EXTERNAL" %} for (int i = 1; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun", &capsule->ext_cost_fun[i-1]); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac", &capsule->ext_cost_fun_jac[i-1]); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "ext_cost_fun_jac_hess", &capsule->ext_cost_fun_jac_hess[i-1]); } {%- endif %} {% if dims.ns > 0 %} double* zlumem = calloc(4*NS, sizeof(double)); double* Zl = zlumem+NS*0; double* Zu = zlumem+NS*1; double* zl = zlumem+NS*2; double* zu = zlumem+NS*3; // change only the non-zero elements: {%- for j in range(end=dims.ns) %} {%- if cost.Zl[j] != 0 %} Zl[{{ j }}] = {{ cost.Zl[j] }}; {%- endif %} {%- endfor %} {%- for j in range(end=dims.ns) %} {%- if cost.Zu[j] != 0 %} Zu[{{ j }}] = {{ cost.Zu[j] }}; {%- endif %} {%- endfor %} {%- for j in range(end=dims.ns) %} {%- if cost.zl[j] != 0 %} zl[{{ j }}] = {{ cost.zl[j] }}; {%- endif %} {%- endfor %} {%- for j in range(end=dims.ns) %} {%- if cost.zu[j] != 0 %} zu[{{ j }}] = {{ cost.zu[j] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zl", Zl); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "Zu", Zu); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zl", zl); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, i, "zu", zu); } free(zlumem); {% endif %} // terminal cost {% if cost.cost_type_e == "LINEAR_LS" or cost.cost_type_e == "NONLINEAR_LS" %} {% if dims.ny_e > 0 %} double* yref_e = calloc(NYN, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_e) %} {%- if cost.yref_e[j] != 0 %} yref_e[{{ j }}] = {{ cost.yref_e[j] }}; {%- endif %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "yref", yref_e); free(yref_e); double* W_e = calloc(NYN*NYN, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_e) %} {%- for k in range(end=dims.ny_e) %} {%- if cost.W_e[j][k] != 0 %} W_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.W_e[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "W", W_e); free(W_e); {%- if cost.cost_type_e == "LINEAR_LS" %} double* Vx_e = calloc(NYN*NX, sizeof(double)); // change only the non-zero elements: {% for j in range(end=dims.ny_e) %} {%- for k in range(end=dims.nx) %} {%- if cost.Vx_e[j][k] != 0 %} Vx_e[{{ j }}+(NYN) * {{ k }}] = {{ cost.Vx_e[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Vx", Vx_e); free(Vx_e); {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun", &capsule->cost_y_e_fun); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_fun_jac", &capsule->cost_y_e_fun_jac_ut_xt); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "nls_y_hess", &capsule->cost_y_e_hess); {%- endif %} {%- endif %}{# ny_e > 0 #} {%- elif cost.cost_type_e == "EXTERNAL" %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun", &capsule->ext_cost_e_fun); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac", &capsule->ext_cost_e_fun_jac); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "ext_cost_fun_jac_hess", &capsule->ext_cost_e_fun_jac_hess); {%- endif %} {% if dims.ns_e > 0 %} double* zluemem = calloc(4*NSN, sizeof(double)); double* Zl_e = zluemem+NSN*0; double* Zu_e = zluemem+NSN*1; double* zl_e = zluemem+NSN*2; double* zu_e = zluemem+NSN*3; // change only the non-zero elements: {% for j in range(end=dims.ns_e) %} {%- if cost.Zl_e[j] != 0 %} Zl_e[{{ j }}] = {{ cost.Zl_e[j] }}; {%- endif %} {%- endfor %} {% for j in range(end=dims.ns_e) %} {%- if cost.Zu_e[j] != 0 %} Zu_e[{{ j }}] = {{ cost.Zu_e[j] }}; {%- endif %} {%- endfor %} {% for j in range(end=dims.ns_e) %} {%- if cost.zl_e[j] != 0 %} zl_e[{{ j }}] = {{ cost.zl_e[j] }}; {%- endif %} {%- endfor %} {% for j in range(end=dims.ns_e) %} {%- if cost.zu_e[j] != 0 %} zu_e[{{ j }}] = {{ cost.zu_e[j] }}; {%- endif %} {%- endfor %} ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zl", Zl_e); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "Zu", Zu_e); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zl", zl_e); ocp_nlp_cost_model_set(nlp_config, nlp_dims, nlp_in, N, "zu", zu_e); free(zluemem); {%- endif %} /**** Constraints ****/ // bounds for initial stage {% if dims.nbx_0 > 0 %} // x0 int* idxbx0 = malloc(NBX0 * sizeof(int)); {%- for i in range(end=dims.nbx_0) %} idxbx0[{{ i }}] = {{ constraints.idxbx_0[i] }}; {%- endfor %} double* lubx0 = calloc(2*NBX0, sizeof(double)); double* lbx0 = lubx0; double* ubx0 = lubx0 + NBX0; // change only the non-zero elements: {%- for i in range(end=dims.nbx_0) %} {%- if constraints.lbx_0[i] != 0 %} lbx0[{{ i }}] = {{ constraints.lbx_0[i] }}; {%- endif %} {%- if constraints.ubx_0[i] != 0 %} ubx0[{{ i }}] = {{ constraints.ubx_0[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbx", idxbx0); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lbx", lbx0); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "ubx", ubx0); free(idxbx0); free(lubx0); {% endif %} {% if dims.nbxe_0 > 0 %} // idxbxe_0 int* idxbxe_0 = malloc({{ dims.nbxe_0 }} * sizeof(int)); {% for i in range(end=dims.nbxe_0) %} idxbxe_0[{{ i }}] = {{ constraints.idxbxe_0[i] }}; {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxbxe", idxbxe_0); free(idxbxe_0); {% endif %} /* constraints that are the same for initial and intermediate */ {%- if dims.nsbx > 0 %} {# TODO: introduce nsbx0 & move this block down!! #} // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "idxsbx", idxsbx); // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "lsbx", lsbx); // ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, 0, "usbx", usbx); // soft bounds on x int* idxsbx = malloc(NSBX * sizeof(int)); {% for i in range(end=dims.nsbx) %} idxsbx[{{ i }}] = {{ constraints.idxsbx[i] }}; {%- endfor %} double* lusbx = calloc(2*NSBX, sizeof(double)); double* lsbx = lusbx; double* usbx = lusbx + NSBX; {% for i in range(end=dims.nsbx) %} {%- if constraints.lsbx[i] != 0 %} lsbx[{{ i }}] = {{ constraints.lsbx[i] }}; {%- endif %} {%- if constraints.usbx[i] != 0 %} usbx[{{ i }}] = {{ constraints.usbx[i] }}; {%- endif %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbx", idxsbx); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbx", lsbx); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbx", usbx); } free(idxsbx); free(lusbx); {%- endif %} {% if dims.nbu > 0 %} // u int* idxbu = malloc(NBU * sizeof(int)); {% for i in range(end=dims.nbu) %} idxbu[{{ i }}] = {{ constraints.idxbu[i] }}; {%- endfor %} double* lubu = calloc(2*NBU, sizeof(double)); double* lbu = lubu; double* ubu = lubu + NBU; {% for i in range(end=dims.nbu) %} {%- if constraints.lbu[i] != 0 %} lbu[{{ i }}] = {{ constraints.lbu[i] }}; {%- endif %} {%- if constraints.ubu[i] != 0 %} ubu[{{ i }}] = {{ constraints.ubu[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbu", idxbu); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbu", lbu); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubu", ubu); } free(idxbu); free(lubu); {% endif %} {% if dims.nsbu > 0 %} // set up soft bounds for u int* idxsbu = malloc(NSBU * sizeof(int)); {% for i in range(end=dims.nsbu) %} idxsbu[{{ i }}] = {{ constraints.idxsbu[i] }}; {%- endfor %} double* lusbu = calloc(2*NSBU, sizeof(double)); double* lsbu = lusbu; double* usbu = lusbu + NSBU; {% for i in range(end=dims.nsbu) %} {%- if constraints.lsbu[i] != 0 %} lsbu[{{ i }}] = {{ constraints.lsbu[i] }}; {%- endif %} {%- if constraints.usbu[i] != 0 %} usbu[{{ i }}] = {{ constraints.usbu[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsbu", idxsbu); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsbu", lsbu); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usbu", usbu); } free(idxsbu); free(lusbu); {% endif %} {% if dims.nsg > 0 %} // set up soft bounds for general linear constraints int* idxsg = malloc(NSG * sizeof(int)); {% for i in range(end=dims.nsg) %} idxsg[{{ i }}] = {{ constraints.idxsg[i] }}; {%- endfor %} double* lusg = calloc(2*NSG, sizeof(double)); double* lsg = lusg; double* usg = lusg + NSG; {% for i in range(end=dims.nsg) %} {%- if constraints.lsg[i] != 0 %} lsg[{{ i }}] = {{ constraints.lsg[i] }}; {%- endif %} {%- if constraints.usg[i] != 0 %} usg[{{ i }}] = {{ constraints.usg[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsg", idxsg); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsg", lsg); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usg", usg); } free(idxsg); free(lusg); {% endif %} {% if dims.nsh > 0 %} // set up soft bounds for nonlinear constraints int* idxsh = malloc(NSH * sizeof(int)); {% for i in range(end=dims.nsh) %} idxsh[{{ i }}] = {{ constraints.idxsh[i] }}; {%- endfor %} double* lush = calloc(2*NSH, sizeof(double)); double* lsh = lush; double* ush = lush + NSH; {% for i in range(end=dims.nsh) %} {%- if constraints.lsh[i] != 0 %} lsh[{{ i }}] = {{ constraints.lsh[i] }}; {%- endif %} {%- if constraints.ush[i] != 0 %} ush[{{ i }}] = {{ constraints.ush[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsh", idxsh); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsh", lsh); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ush", ush); } free(idxsh); free(lush); {% endif %} {% if dims.nsphi > 0 %} // set up soft bounds for convex-over-nonlinear constraints int* idxsphi = malloc(NSPHI * sizeof(int)); {% for i in range(end=dims.nsphi) %} idxsphi[{{ i }}] = {{ constraints.idxsphi[i] }}; {%- endfor %} double* lusphi = calloc(2*NSPHI, sizeof(double)); double* lsphi = lusphi; double* usphi = lusphi + NSPHI; {% for i in range(end=dims.nsphi) %} {%- if constraints.lsphi[i] != 0 %} lsphi[{{ i }}] = {{ constraints.lsphi[i] }}; {%- endif %} {%- if constraints.usphi[i] != 0 %} usphi[{{ i }}] = {{ constraints.usphi[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxsphi", idxsphi); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lsphi", lsphi); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "usphi", usphi); } free(idxsphi); free(lusphi); {% endif %} {% if dims.nbx > 0 %} // x int* idxbx = malloc(NBX * sizeof(int)); {% for i in range(end=dims.nbx) %} idxbx[{{ i }}] = {{ constraints.idxbx[i] }}; {%- endfor %} double* lubx = calloc(2*NBX, sizeof(double)); double* lbx = lubx; double* ubx = lubx + NBX; {% for i in range(end=dims.nbx) %} {%- if constraints.lbx[i] != 0 %} lbx[{{ i }}] = {{ constraints.lbx[i] }}; {%- endif %} {%- if constraints.ubx[i] != 0 %} ubx[{{ i }}] = {{ constraints.ubx[i] }}; {%- endif %} {%- endfor %} for (int i = 1; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "idxbx", idxbx); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lbx", lbx); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ubx", ubx); } free(idxbx); free(lubx); {% endif %} {% if dims.ng > 0 %} // set up general constraints for stage 0 to N-1 double* D = calloc(NG*NU, sizeof(double)); double* C = calloc(NG*NX, sizeof(double)); double* lug = calloc(2*NG, sizeof(double)); double* lg = lug; double* ug = lug + NG; {% for j in range(end=dims.ng) -%} {% for k in range(end=dims.nu) %} {%- if constraints.D[j][k] != 0 %} D[{{ j }}+NG * {{ k }}] = {{ constraints.D[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} {% for j in range(end=dims.ng) -%} {% for k in range(end=dims.nx) %} {%- if constraints.C[j][k] != 0 %} C[{{ j }}+NG * {{ k }}] = {{ constraints.C[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} {% for i in range(end=dims.ng) %} {%- if constraints.lg[i] != 0 %} lg[{{ i }}] = {{ constraints.lg[i] }}; {%- endif %} {%- endfor %} {% for i in range(end=dims.ng) %} {%- if constraints.ug[i] != 0 %} ug[{{ i }}] = {{ constraints.ug[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "D", D); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "C", C); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lg", lg); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "ug", ug); } free(D); free(C); free(lug); {% endif %} {% if dims.nh > 0 %} // set up nonlinear constraints for stage 0 to N-1 double* luh = calloc(2*NH, sizeof(double)); double* lh = luh; double* uh = luh + NH; {% for i in range(end=dims.nh) %} {%- if constraints.lh[i] != 0 %} lh[{{ i }}] = {{ constraints.lh[i] }}; {%- endif %} {%- endfor %} {% for i in range(end=dims.nh) %} {%- if constraints.uh[i] != 0 %} uh[{{ i }}] = {{ constraints.uh[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { // nonlinear constraints for stages 0 to N-1 ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun_jac", &capsule->nl_constr_h_fun_jac[i]); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun", &capsule->nl_constr_h_fun[i]); {% if solver_options.hessian_approx == "EXACT" %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_h_fun_jac_hess", &capsule->nl_constr_h_fun_jac_hess[i]); {% endif %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lh", lh); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uh", uh); } free(luh); {% endif %} {% if dims.nphi > 0 and constraints.constr_type == "BGP" %} // set up convex-over-nonlinear constraints for stage 0 to N-1 double* luphi = calloc(2*NPHI, sizeof(double)); double* lphi = luphi; double* uphi = luphi + NPHI; {% for i in range(end=dims.nphi) %} {%- if constraints.lphi[i] != 0 %} lphi[{{ i }}] = {{ constraints.lphi[i] }}; {%- endif %} {%- endfor %} {% for i in range(end=dims.nphi) %} {%- if constraints.uphi[i] != 0 %} uphi[{{ i }}] = {{ constraints.uphi[i] }}; {%- endif %} {%- endfor %} for (int i = 0; i < N; i++) { ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_constraint[i]); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "lphi", lphi); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, i, "uphi", uphi); } free(luphi); {% endif %} /* terminal constraints */ {% if dims.nbx_e > 0 %} // set up bounds for last stage // x int* idxbx_e = malloc(NBXN * sizeof(int)); {% for i in range(end=dims.nbx_e) %} idxbx_e[{{ i }}] = {{ constraints.idxbx_e[i] }}; {%- endfor %} double* lubx_e = calloc(2*NBXN, sizeof(double)); double* lbx_e = lubx_e; double* ubx_e = lubx_e + NBXN; {% for i in range(end=dims.nbx_e) %} {%- if constraints.lbx_e[i] != 0 %} lbx_e[{{ i }}] = {{ constraints.lbx_e[i] }}; {%- endif %} {%- if constraints.ubx_e[i] != 0 %} ubx_e[{{ i }}] = {{ constraints.ubx_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxbx", idxbx_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lbx", lbx_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ubx", ubx_e); free(idxbx_e); free(lubx_e); {%- endif %} {% if dims.nsg_e > 0 %} // set up soft bounds for general linear constraints int* idxsg_e = calloc(NSGN, sizeof(int)); {% for i in range(end=dims.nsg_e) %} idxsg_e[{{ i }}] = {{ constraints.idxsg_e[i] }}; {%- endfor %} double* lusg_e = calloc(2*NSGN, sizeof(double)); double* lsg_e = lusg_e; double* usg_e = lusg_e + NSGN; {% for i in range(end=dims.nsg_e) %} {%- if constraints.lsg_e[i] != 0 %} lsg_e[{{ i }}] = {{ constraints.lsg_e[i] }}; {%- endif %} {%- if constraints.usg_e[i] != 0 %} usg_e[{{ i }}] = {{ constraints.usg_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsg", idxsg_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsg", lsg_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usg", usg_e); free(idxsg_e); free(lusg_e); {%- endif %} {% if dims.nsh_e > 0 %} // set up soft bounds for nonlinear constraints int* idxsh_e = malloc(NSHN * sizeof(int)); {% for i in range(end=dims.nsh_e) %} idxsh_e[{{ i }}] = {{ constraints.idxsh_e[i] }}; {%- endfor %} double* lush_e = calloc(2*NSHN, sizeof(double)); double* lsh_e = lush_e; double* ush_e = lush_e + NSHN; {% for i in range(end=dims.nsh_e) %} {%- if constraints.lsh_e[i] != 0 %} lsh_e[{{ i }}] = {{ constraints.lsh_e[i] }}; {%- endif %} {%- if constraints.ush_e[i] != 0 %} ush_e[{{ i }}] = {{ constraints.ush_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsh", idxsh_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsh", lsh_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ush", ush_e); free(idxsh_e); free(lush_e); {%- endif %} {% if dims.nsphi_e > 0 %} // set up soft bounds for convex-over-nonlinear constraints int* idxsphi_e = malloc(NSPHIN * sizeof(int)); {% for i in range(end=dims.nsphi_e) %} idxsphi_e[{{ i }}] = {{ constraints.idxsphi_e[i] }}; {%- endfor %} double* lusphi_e = calloc(2*NSPHIN, sizeof(double)); double* lsphi_e = lusphi_e; double* usphi_e = lusphi_e + NSPHIN; {% for i in range(end=dims.nsphi_e) %} {%- if constraints.lsphi_e[i] != 0 %} lsphi_e[{{ i }}] = {{ constraints.lsphi_e[i] }}; {%- endif %} {%- if constraints.usphi_e[i] != 0 %} usphi_e[{{ i }}] = {{ constraints.usphi_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsphi", idxsphi_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsphi", lsphi_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usphi", usphi_e); free(idxsphi_e); free(lusphi_e); {%- endif %} {% if dims.nsbx_e > 0 %} // soft bounds on x int* idxsbx_e = malloc(NSBXN * sizeof(int)); {% for i in range(end=dims.nsbx_e) %} idxsbx_e[{{ i }}] = {{ constraints.idxsbx_e[i] }}; {%- endfor %} double* lusbx_e = calloc(2*NSBXN, sizeof(double)); double* lsbx_e = lusbx_e; double* usbx_e = lusbx_e + NSBXN; {% for i in range(end=dims.nsbx_e) %} {%- if constraints.lsbx_e[i] != 0 %} lsbx_e[{{ i }}] = {{ constraints.lsbx_e[i] }}; {%- endif %} {%- if constraints.usbx_e[i] != 0 %} usbx_e[{{ i }}] = {{ constraints.usbx_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "idxsbx", idxsbx_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lsbx", lsbx_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "usbx", usbx_e); free(idxsbx_e); free(lusbx_e); {% endif %} {% if dims.ng_e > 0 %} // set up general constraints for last stage double* C_e = calloc(NGN*NX, sizeof(double)); double* lug_e = calloc(2*NGN, sizeof(double)); double* lg_e = lug_e; double* ug_e = lug_e + NGN; {% for j in range(end=dims.ng) %} {%- for k in range(end=dims.nx) %} {%- if constraints.C_e[j][k] != 0 %} C_e[{{ j }}+NG * {{ k }}] = {{ constraints.C_e[j][k] }}; {%- endif %} {%- endfor %} {%- endfor %} {% for i in range(end=dims.ng_e) %} {%- if constraints.lg_e[i] != 0 %} lg_e[{{ i }}] = {{ constraints.lg_e[i] }}; {%- endif %} {%- if constraints.ug_e[i] != 0 %} ug_e[{{ i }}] = {{ constraints.ug_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "C", C_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lg", lg_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "ug", ug_e); free(C_e); free(lug_e); {%- endif %} {% if dims.nh_e > 0 %} // set up nonlinear constraints for last stage double* luh_e = calloc(2*NHN, sizeof(double)); double* lh_e = luh_e; double* uh_e = luh_e + NHN; {% for i in range(end=dims.nh_e) %} {%- if constraints.lh_e[i] != 0 %} lh_e[{{ i }}] = {{ constraints.lh_e[i] }}; {%- endif %} {%- endfor %} {% for i in range(end=dims.nh_e) %} {%- if constraints.uh_e[i] != 0 %} uh_e[{{ i }}] = {{ constraints.uh_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac", &capsule->nl_constr_h_e_fun_jac); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun", &capsule->nl_constr_h_e_fun); {% if solver_options.hessian_approx == "EXACT" %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_h_fun_jac_hess", &capsule->nl_constr_h_e_fun_jac_hess); {% endif %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lh", lh_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uh", uh_e); free(luh_e); {%- endif %} {% if dims.nphi_e > 0 and constraints.constr_type_e == "BGP" %} // set up convex-over-nonlinear constraints for last stage double* luphi_e = calloc(2*NPHIN, sizeof(double)); double* lphi_e = luphi_e; double* uphi_e = luphi_e + NPHIN; {% for i in range(end=dims.nphi_e) %} {%- if constraints.lphi_e[i] != 0 %} lphi_e[{{ i }}] = {{ constraints.lphi_e[i] }}; {%- endif %} {%- if constraints.uphi_e[i] != 0 %} uphi_e[{{ i }}] = {{ constraints.uphi_e[i] }}; {%- endif %} {%- endfor %} ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "lphi", lphi_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "uphi", uphi_e); ocp_nlp_constraints_model_set(nlp_config, nlp_dims, nlp_in, N, "nl_constr_phi_o_r_fun_phi_jac_ux_z_phi_hess_r_jac_ux", &capsule->phi_e_constraint); free(luphi_e); {% endif %} /************************************************ * opts ************************************************/ capsule->nlp_opts = ocp_nlp_solver_opts_create(nlp_config, nlp_dims); {% if solver_options.hessian_approx == "EXACT" %} bool nlp_solver_exact_hessian = true; // TODO: this if should not be needed! however, calling the setter with false leads to weird behavior. Investigate! if (nlp_solver_exact_hessian) { ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess", &nlp_solver_exact_hessian); } int exact_hess_dyn = {{ solver_options.exact_hess_dyn }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_dyn", &exact_hess_dyn); int exact_hess_cost = {{ solver_options.exact_hess_cost }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_cost", &exact_hess_cost); int exact_hess_constr = {{ solver_options.exact_hess_constr }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "exact_hess_constr", &exact_hess_constr); {%- endif -%} {%- if solver_options.globalization == "FIXED_STEP" %} ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization", "fixed_step"); {%- elif solver_options.globalization == "MERIT_BACKTRACKING" %} ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "globalization", "merit_backtracking"); double alpha_min = {{ solver_options.alpha_min }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "alpha_min", &alpha_min); double alpha_reduction = {{ solver_options.alpha_reduction }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "alpha_reduction", &alpha_reduction); {%- endif -%} {%- if dims.nz > 0 %} // TODO: these options are lower level -> should be encapsulated! maybe through hessian approx option. bool output_z_val = true; bool sens_algebraic_val = true; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_output_z", &output_z_val); for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_sens_algebraic", &sens_algebraic_val); {%- endif %} {%- if solver_options.integrator_type != "DISCRETE" %} // set collocation type (relevant for implicit integrators) sim_collocation_type collocation_type = {{ solver_options.collocation_type }}; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_collocation_type", &collocation_type); // set up sim_method_num_steps {%- set all_equal = true %} {%- set val = solver_options.sim_method_num_steps[0] %} {%- for j in range(start=1, end=dims.N) %} {%- if val != solver_options.sim_method_num_steps[j] %} {%- set_global all_equal = false %} {%- break %} {%- endif %} {%- endfor %} {%- if all_equal == true %} // all sim_method_num_steps are identical int sim_method_num_steps = {{ solver_options.sim_method_num_steps[0] }}; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps); {%- else %} // sim_method_num_steps are different int* sim_method_num_steps = malloc(N*sizeof(int)); {%- for j in range(end=dims.N) %} sim_method_num_steps[{{ j }}] = {{ solver_options.sim_method_num_steps[j] }}; {%- endfor %} for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_steps", &sim_method_num_steps[i]); free(sim_method_num_steps); {%- endif %} // set up sim_method_num_stages {%- set all_equal = true %} {%- set val = solver_options.sim_method_num_stages[0] %} {%- for j in range(start=1, end=dims.N) %} {%- if val != solver_options.sim_method_num_stages[j] %} {%- set_global all_equal = false %} {%- break %} {%- endif %} {%- endfor %} {%- if all_equal == true %} // all sim_method_num_stages are identical int sim_method_num_stages = {{ solver_options.sim_method_num_stages[0] }}; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages); {%- else %} int* sim_method_num_stages = malloc(N*sizeof(int)); {%- for j in range(end=dims.N) %} sim_method_num_stages[{{ j }}] = {{ solver_options.sim_method_num_stages[j] }}; {%- endfor %} for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_num_stages", &sim_method_num_stages[i]); free(sim_method_num_stages); {%- endif %} int newton_iter_val = {{ solver_options.sim_method_newton_iter }}; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_newton_iter", &newton_iter_val); // set up sim_method_jac_reuse {%- set all_equal = true %} {%- set val = solver_options.sim_method_jac_reuse[0] %} {%- for j in range(start=1, end=dims.N) %} {%- if val != solver_options.sim_method_jac_reuse[j] %} {%- set_global all_equal = false %} {%- break %} {%- endif %} {%- endfor %} {%- if all_equal == true %} bool tmp_bool = (bool) {{ solver_options.sim_method_jac_reuse[0] }}; for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_jac_reuse", &tmp_bool); {%- else %} bool* sim_method_jac_reuse = malloc(N*sizeof(bool)); {%- for j in range(end=dims.N) %} sim_method_jac_reuse[{{ j }}] = (bool){{ solver_options.sim_method_jac_reuse[j] }}; {%- endfor %} for (int i = 0; i < N; i++) ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "dynamics_jac_reuse", &sim_method_jac_reuse[i]); free(sim_method_jac_reuse); {%- endif %} {%- endif %} double nlp_solver_step_length = {{ solver_options.nlp_solver_step_length }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "step_length", &nlp_solver_step_length); {%- if solver_options.nlp_solver_warm_start_first_qp %} int nlp_solver_warm_start_first_qp = {{ solver_options.nlp_solver_warm_start_first_qp }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "warm_start_first_qp", &nlp_solver_warm_start_first_qp); {%- endif %} double levenberg_marquardt = {{ solver_options.levenberg_marquardt }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "levenberg_marquardt", &levenberg_marquardt); /* options QP solver */ {%- if solver_options.qp_solver is starting_with("PARTIAL_CONDENSING") %} int qp_solver_cond_N; {%- if solver_options.qp_solver_cond_N %} qp_solver_cond_N = {{ solver_options.qp_solver_cond_N }}; {% else %} // NOTE: there is no condensing happening here! qp_solver_cond_N = N; {%- endif %} ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_cond_N", &qp_solver_cond_N); {% endif %} int qp_solver_iter_max = {{ solver_options.qp_solver_iter_max }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_iter_max", &qp_solver_iter_max); {%- if solver_options.qp_solver_tol_stat %} double qp_solver_tol_stat = {{ solver_options.qp_solver_tol_stat }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_stat", &qp_solver_tol_stat); {%- endif -%} {%- if solver_options.qp_solver_tol_eq %} double qp_solver_tol_eq = {{ solver_options.qp_solver_tol_eq }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_eq", &qp_solver_tol_eq); {%- endif -%} {%- if solver_options.qp_solver_tol_ineq %} double qp_solver_tol_ineq = {{ solver_options.qp_solver_tol_ineq }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_ineq", &qp_solver_tol_ineq); {%- endif -%} {%- if solver_options.qp_solver_tol_comp %} double qp_solver_tol_comp = {{ solver_options.qp_solver_tol_comp }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_tol_comp", &qp_solver_tol_comp); {%- endif -%} {%- if solver_options.qp_solver_warm_start %} int qp_solver_warm_start = {{ solver_options.qp_solver_warm_start }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "qp_warm_start", &qp_solver_warm_start); {%- endif -%} {% if solver_options.nlp_solver_type == "SQP" %} // set SQP specific options double nlp_solver_tol_stat = {{ solver_options.nlp_solver_tol_stat }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_stat", &nlp_solver_tol_stat); double nlp_solver_tol_eq = {{ solver_options.nlp_solver_tol_eq }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_eq", &nlp_solver_tol_eq); double nlp_solver_tol_ineq = {{ solver_options.nlp_solver_tol_ineq }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_ineq", &nlp_solver_tol_ineq); double nlp_solver_tol_comp = {{ solver_options.nlp_solver_tol_comp }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "tol_comp", &nlp_solver_tol_comp); int nlp_solver_max_iter = {{ solver_options.nlp_solver_max_iter }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "max_iter", &nlp_solver_max_iter); int initialize_t_slacks = {{ solver_options.initialize_t_slacks }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "initialize_t_slacks", &initialize_t_slacks); {%- endif %} int print_level = {{ solver_options.print_level }}; ocp_nlp_solver_opts_set(nlp_config, capsule->nlp_opts, "print_level", &print_level); int ext_cost_num_hess = {{ solver_options.ext_cost_num_hess }}; {%- if cost.cost_type == "EXTERNAL" %} for (int i = 0; i < N; i++) { ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, i, "cost_numerical_hessian", &ext_cost_num_hess); } {%- endif %} {%- if cost.cost_type_e == "EXTERNAL" %} ocp_nlp_solver_opts_set_at_stage(nlp_config, capsule->nlp_opts, N, "cost_numerical_hessian", &ext_cost_num_hess); {%- endif %} /* out */ ocp_nlp_out * nlp_out = ocp_nlp_out_create(nlp_config, nlp_dims); capsule->nlp_out = nlp_out; /* sens_out */ ocp_nlp_out *sens_out = ocp_nlp_out_create(nlp_config, nlp_dims); capsule->sens_out = sens_out; // initialize primal solution double* xu0 = calloc(NX+NU, sizeof(double)); double* x0 = xu0; {% if dims.nbx_0 == dims.nx %} // initialize with x0 {% for item in constraints.lbx_0 %} {%- if item != 0 %} x0[{{ loop.index0 }}] = {{ item }}; {%- endif %} {%- endfor %} {% else %} // initialize with zeros {%- endif %} double* u0 = xu0 + NX; for (int i = 0; i < N; i++) { // x0 ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "x", x0); // u0 ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, i, "u", u0); } ocp_nlp_out_set(nlp_config, nlp_dims, nlp_out, N, "x", x0); free(xu0); capsule->nlp_solver = ocp_nlp_solver_create(nlp_config, nlp_dims, capsule->nlp_opts); {% if dims.np > 0 %} // initialize parameters to nominal value double* p = calloc(NP, sizeof(double)); {% for item in parameter_values %} {%- if item != 0 %} p[{{ loop.index0 }}] = {{ item }}; {%- endif %} {%- endfor %} for (int i = 0; i <= N; i++) { {{ model.name }}_acados_update_params(capsule, i, p, NP); } free(p); {%- endif %}{# if dims.np #} status = ocp_nlp_precompute(capsule->nlp_solver, nlp_in, nlp_out); if (status != ACADOS_SUCCESS) { printf("\nocp_precompute failed!\n\n"); exit(1); } return status; } int {{ model.name }}_acados_update_params({{ model.name }}_solver_capsule * capsule, int stage, double *p, int np) { int solver_status = 0; int casadi_np = {{ dims.np }}; if (casadi_np != np) { printf("acados_update_params: trying to set %i parameters for external functions." " External function has %i parameters. Exiting.\n", np, casadi_np); exit(1); } {%- if dims.np > 0 %} const int N = capsule->nlp_solver_plan->N; if (stage < N && stage >= 0) { {%- if solver_options.integrator_type == "IRK" %} capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_z+stage, p); capsule->impl_dae_jac_x_xdot_u_z[stage].set_param(capsule->impl_dae_jac_x_xdot_u_z+stage, p); {%- if solver_options.hessian_approx == "EXACT" %} capsule->impl_dae_hess[stage].set_param(capsule->impl_dae_hess+stage, p); {%- endif %} {% elif solver_options.integrator_type == "LIFTED_IRK" %} capsule->impl_dae_fun[stage].set_param(capsule->impl_dae_fun+stage, p); capsule->impl_dae_fun_jac_x_xdot_z[stage].set_param(capsule->impl_dae_fun_jac_x_xdot_z+stage, p); {% elif solver_options.integrator_type == "ERK" %} capsule->forw_vde_casadi[stage].set_param(capsule->forw_vde_casadi+stage, p); capsule->expl_ode_fun[stage].set_param(capsule->expl_ode_fun+stage, p); {%- if solver_options.hessian_approx == "EXACT" %} capsule->hess_vde_casadi[stage].set_param(capsule->hess_vde_casadi+stage, p); {%- endif %} {% elif solver_options.integrator_type == "GNSF" %} {% if model.gnsf.purely_linear != 1 %} capsule->gnsf_phi_fun[stage].set_param(capsule->gnsf_phi_fun+stage, p); capsule->gnsf_phi_fun_jac_y[stage].set_param(capsule->gnsf_phi_fun_jac_y+stage, p); capsule->gnsf_phi_jac_y_uhat[stage].set_param(capsule->gnsf_phi_jac_y_uhat+stage, p); {% if model.gnsf.nontrivial_f_LO == 1 %} capsule->gnsf_f_lo_jac_x1_x1dot_u_z[stage].set_param(capsule->gnsf_f_lo_jac_x1_x1dot_u_z+stage, p); {%- endif %} {%- endif %} {% elif solver_options.integrator_type == "DISCRETE" %} capsule->discr_dyn_phi_fun[stage].set_param(capsule->discr_dyn_phi_fun+stage, p); capsule->discr_dyn_phi_fun_jac_ut_xt[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt+stage, p); {%- if solver_options.hessian_approx == "EXACT" %} capsule->discr_dyn_phi_fun_jac_ut_xt_hess[stage].set_param(capsule->discr_dyn_phi_fun_jac_ut_xt_hess+stage, p); {% endif %} {%- endif %}{# integrator_type #} // constraints {% if constraints.constr_type == "BGP" %} capsule->phi_constraint[stage].set_param(capsule->phi_constraint+stage, p); {% elif constraints.constr_type == "BGH" and dims.nh > 0 %} capsule->nl_constr_h_fun_jac[stage].set_param(capsule->nl_constr_h_fun_jac+stage, p); capsule->nl_constr_h_fun[stage].set_param(capsule->nl_constr_h_fun+stage, p); {%- if solver_options.hessian_approx == "EXACT" %} capsule->nl_constr_h_fun_jac_hess[stage].set_param(capsule->nl_constr_h_fun_jac_hess+stage, p); {%- endif %} {%- endif %} // cost if (stage == 0) { {%- if cost.cost_type_0 == "NONLINEAR_LS" %} capsule->cost_y_0_fun.set_param(&capsule->cost_y_0_fun, p); capsule->cost_y_0_fun_jac_ut_xt.set_param(&capsule->cost_y_0_fun_jac_ut_xt, p); capsule->cost_y_0_hess.set_param(&capsule->cost_y_0_hess, p); {%- elif cost.cost_type_0 == "EXTERNAL" %} capsule->ext_cost_0_fun.set_param(&capsule->ext_cost_0_fun, p); capsule->ext_cost_0_fun_jac.set_param(&capsule->ext_cost_0_fun_jac, p); capsule->ext_cost_0_fun_jac_hess.set_param(&capsule->ext_cost_0_fun_jac_hess, p); {% endif %} } else // 0 < stage < N { {%- if cost.cost_type == "NONLINEAR_LS" %} capsule->cost_y_fun[stage-1].set_param(capsule->cost_y_fun+stage-1, p); capsule->cost_y_fun_jac_ut_xt[stage-1].set_param(capsule->cost_y_fun_jac_ut_xt+stage-1, p); capsule->cost_y_hess[stage-1].set_param(capsule->cost_y_hess+stage-1, p); {%- elif cost.cost_type == "EXTERNAL" %} capsule->ext_cost_fun[stage-1].set_param(capsule->ext_cost_fun+stage-1, p); capsule->ext_cost_fun_jac[stage-1].set_param(capsule->ext_cost_fun_jac+stage-1, p); capsule->ext_cost_fun_jac_hess[stage-1].set_param(capsule->ext_cost_fun_jac_hess+stage-1, p); {%- endif %} } } else // stage == N { // terminal shooting node has no dynamics // cost {%- if cost.cost_type_e == "NONLINEAR_LS" %} capsule->cost_y_e_fun.set_param(&capsule->cost_y_e_fun, p); capsule->cost_y_e_fun_jac_ut_xt.set_param(&capsule->cost_y_e_fun_jac_ut_xt, p); capsule->cost_y_e_hess.set_param(&capsule->cost_y_e_hess, p); {%- elif cost.cost_type_e == "EXTERNAL" %} capsule->ext_cost_e_fun.set_param(&capsule->ext_cost_e_fun, p); capsule->ext_cost_e_fun_jac.set_param(&capsule->ext_cost_e_fun_jac, p); capsule->ext_cost_e_fun_jac_hess.set_param(&capsule->ext_cost_e_fun_jac_hess, p); {% endif %} // constraints {% if constraints.constr_type_e == "BGP" %} capsule->phi_e_constraint.set_param(&capsule->phi_e_constraint, p); {% elif constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} capsule->nl_constr_h_e_fun_jac.set_param(&capsule->nl_constr_h_e_fun_jac, p); capsule->nl_constr_h_e_fun.set_param(&capsule->nl_constr_h_e_fun, p); {%- if solver_options.hessian_approx == "EXACT" %} capsule->nl_constr_h_e_fun_jac_hess.set_param(&capsule->nl_constr_h_e_fun_jac_hess, p); {%- endif %} {% endif %} } {% endif %}{# if dims.np #} return solver_status; } int {{ model.name }}_acados_solve({{ model.name }}_solver_capsule * capsule) { // solve NLP int solver_status = ocp_nlp_solve(capsule->nlp_solver, capsule->nlp_in, capsule->nlp_out); return solver_status; } int {{ model.name }}_acados_free({{ model.name }}_solver_capsule * capsule) { // before destroying, keep some info const int N = capsule->nlp_solver_plan->N; // free memory ocp_nlp_solver_opts_destroy(capsule->nlp_opts); ocp_nlp_in_destroy(capsule->nlp_in); ocp_nlp_out_destroy(capsule->nlp_out); ocp_nlp_out_destroy(capsule->sens_out); ocp_nlp_solver_destroy(capsule->nlp_solver); ocp_nlp_dims_destroy(capsule->nlp_dims); ocp_nlp_config_destroy(capsule->nlp_config); ocp_nlp_plan_destroy(capsule->nlp_solver_plan); /* free external function */ // dynamics {%- if solver_options.integrator_type == "IRK" %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->impl_dae_fun[i]); external_function_param_casadi_free(&capsule->impl_dae_fun_jac_x_xdot_z[i]); external_function_param_casadi_free(&capsule->impl_dae_jac_x_xdot_u_z[i]); {%- if solver_options.hessian_approx == "EXACT" %} external_function_param_casadi_free(&capsule->impl_dae_hess[i]); {%- endif %} } free(capsule->impl_dae_fun); free(capsule->impl_dae_fun_jac_x_xdot_z); free(capsule->impl_dae_jac_x_xdot_u_z); {%- if solver_options.hessian_approx == "EXACT" %} free(capsule->impl_dae_hess); {%- endif %} {%- elif solver_options.integrator_type == "LIFTED_IRK" %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->impl_dae_fun[i]); external_function_param_casadi_free(&capsule->impl_dae_fun_jac_x_xdot_u[i]); } free(capsule->impl_dae_fun); free(capsule->impl_dae_fun_jac_x_xdot_u); {%- elif solver_options.integrator_type == "ERK" %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->forw_vde_casadi[i]); external_function_param_casadi_free(&capsule->expl_ode_fun[i]); {%- if solver_options.hessian_approx == "EXACT" %} external_function_param_casadi_free(&capsule->hess_vde_casadi[i]); {%- endif %} } free(capsule->forw_vde_casadi); free(capsule->expl_ode_fun); {%- if solver_options.hessian_approx == "EXACT" %} free(capsule->hess_vde_casadi); {%- endif %} {%- elif solver_options.integrator_type == "GNSF" %} for (int i = 0; i < N; i++) { {% if model.gnsf.purely_linear != 1 %} external_function_param_casadi_free(&capsule->gnsf_phi_fun[i]); external_function_param_casadi_free(&capsule->gnsf_phi_fun_jac_y[i]); external_function_param_casadi_free(&capsule->gnsf_phi_jac_y_uhat[i]); {% if model.gnsf.nontrivial_f_LO == 1 %} external_function_param_casadi_free(&capsule->gnsf_f_lo_jac_x1_x1dot_u_z[i]); {%- endif %} {%- endif %} external_function_param_casadi_free(&capsule->gnsf_get_matrices_fun[i]); } {% if model.gnsf.purely_linear != 1 %} free(capsule->gnsf_phi_fun); free(capsule->gnsf_phi_fun_jac_y); free(capsule->gnsf_phi_jac_y_uhat); {% if model.gnsf.nontrivial_f_LO == 1 %} free(capsule->gnsf_f_lo_jac_x1_x1dot_u_z); {%- endif %} {%- endif %} free(capsule->gnsf_get_matrices_fun); {%- elif solver_options.integrator_type == "DISCRETE" %} for (int i = 0; i < N; i++) { external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun[i]); external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt[i]); {%- if solver_options.hessian_approx == "EXACT" %} external_function_param_{{ model.dyn_ext_fun_type }}_free(&capsule->discr_dyn_phi_fun_jac_ut_xt_hess[i]); {%- endif %} } free(capsule->discr_dyn_phi_fun); free(capsule->discr_dyn_phi_fun_jac_ut_xt); {%- if solver_options.hessian_approx == "EXACT" %} free(capsule->discr_dyn_phi_fun_jac_ut_xt_hess); {%- endif %} {%- endif %} // cost {%- if cost.cost_type_0 == "NONLINEAR_LS" %} external_function_param_casadi_free(&capsule->cost_y_0_fun); external_function_param_casadi_free(&capsule->cost_y_0_fun_jac_ut_xt); external_function_param_casadi_free(&capsule->cost_y_0_hess); {%- elif cost.cost_type_0 == "EXTERNAL" %} external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun); external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac); external_function_param_{{ cost.cost_ext_fun_type_0 }}_free(&capsule->ext_cost_0_fun_jac_hess); {%- endif %} {%- if cost.cost_type == "NONLINEAR_LS" %} for (int i = 0; i < N - 1; i++) { external_function_param_casadi_free(&capsule->cost_y_fun[i]); external_function_param_casadi_free(&capsule->cost_y_fun_jac_ut_xt[i]); external_function_param_casadi_free(&capsule->cost_y_hess[i]); } free(capsule->cost_y_fun); free(capsule->cost_y_fun_jac_ut_xt); free(capsule->cost_y_hess); {%- elif cost.cost_type == "EXTERNAL" %} for (int i = 0; i < N - 1; i++) { external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun[i]); external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac[i]); external_function_param_{{ cost.cost_ext_fun_type }}_free(&capsule->ext_cost_fun_jac_hess[i]); } free(capsule->ext_cost_fun); free(capsule->ext_cost_fun_jac); free(capsule->ext_cost_fun_jac_hess); {%- endif %} {%- if cost.cost_type_e == "NONLINEAR_LS" %} external_function_param_casadi_free(&capsule->cost_y_e_fun); external_function_param_casadi_free(&capsule->cost_y_e_fun_jac_ut_xt); external_function_param_casadi_free(&capsule->cost_y_e_hess); {%- elif cost.cost_type_e == "EXTERNAL" %} external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun); external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac); external_function_param_{{ cost.cost_ext_fun_type_e }}_free(&capsule->ext_cost_e_fun_jac_hess); {%- endif %} // constraints {%- if constraints.constr_type == "BGH" and dims.nh > 0 %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac[i]); external_function_param_casadi_free(&capsule->nl_constr_h_fun[i]); } {%- if solver_options.hessian_approx == "EXACT" %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->nl_constr_h_fun_jac_hess[i]); } {%- endif %} free(capsule->nl_constr_h_fun_jac); free(capsule->nl_constr_h_fun); {%- if solver_options.hessian_approx == "EXACT" %} free(capsule->nl_constr_h_fun_jac_hess); {%- endif %} {%- elif constraints.constr_type == "BGP" and dims.nphi > 0 %} for (int i = 0; i < N; i++) { external_function_param_casadi_free(&capsule->phi_constraint[i]); } free(capsule->phi_constraint); {%- endif %} {%- if constraints.constr_type_e == "BGH" and dims.nh_e > 0 %} external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac); external_function_param_casadi_free(&capsule->nl_constr_h_e_fun); {%- if solver_options.hessian_approx == "EXACT" %} external_function_param_casadi_free(&capsule->nl_constr_h_e_fun_jac_hess); {%- endif %} {%- elif constraints.constr_type_e == "BGP" and dims.nphi_e > 0 %} external_function_param_casadi_free(&capsule->phi_e_constraint); {%- endif %} return 0; } ocp_nlp_in *{{ model.name }}_acados_get_nlp_in({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_in; } ocp_nlp_out *{{ model.name }}_acados_get_nlp_out({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_out; } ocp_nlp_out *{{ model.name }}_acados_get_sens_out({{ model.name }}_solver_capsule * capsule) { return capsule->sens_out; } ocp_nlp_solver *{{ model.name }}_acados_get_nlp_solver({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_solver; } ocp_nlp_config *{{ model.name }}_acados_get_nlp_config({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_config; } void *{{ model.name }}_acados_get_nlp_opts({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_opts; } ocp_nlp_dims *{{ model.name }}_acados_get_nlp_dims({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_dims; } ocp_nlp_plan *{{ model.name }}_acados_get_nlp_plan({{ model.name }}_solver_capsule * capsule) { return capsule->nlp_solver_plan; } void {{ model.name }}_acados_print_stats({{ model.name }}_solver_capsule * capsule) { int sqp_iter, stat_m, stat_n, tmp_int; ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "sqp_iter", &sqp_iter); ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_n", &stat_n); ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "stat_m", &stat_m); {% set stat_n_max = 10 %} double stat[{{ solver_options.nlp_solver_max_iter * stat_n_max }}]; ocp_nlp_get(capsule->nlp_config, capsule->nlp_solver, "statistics", stat); int nrow = sqp_iter+1 < stat_m ? sqp_iter+1 : stat_m; printf("iter\tres_stat\tres_eq\t\tres_ineq\tres_comp\tqp_stat\tqp_iter\n"); for (int i = 0; i < nrow; i++) { for (int j = 0; j < stat_n + 1; j++) { if (j == 0 || j > 4) { tmp_int = (int) stat[i + j * nrow]; printf("%d\t", tmp_int); } else { printf("%e\t", stat[i + j * nrow]); } } printf("\n"); } }
459766.c
/* pngread.c - read a PNG file * * Last changed in libpng 1.6.1 [March 28, 2013] * Copyright (c) 1998-2013 Glenn Randers-Pehrson * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h * * This file contains routines that an application calls directly to * read a PNG file or stream. */ #include "pngpriv.h" #if defined(PNG_SIMPLIFIED_READ_SUPPORTED) && defined(PNG_STDIO_SUPPORTED) # include <errno.h> #endif #ifdef PNG_READ_SUPPORTED /* Create a PNG structure for reading, and allocate any memory needed. */ PNG_FUNCTION(png_structp,PNGAPI png_create_read_struct,(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn),PNG_ALLOCATED) { #ifndef PNG_USER_MEM_SUPPORTED png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr, error_fn, warn_fn, NULL, NULL, NULL); #else return png_create_read_struct_2(user_png_ver, error_ptr, error_fn, warn_fn, NULL, NULL, NULL); } /* Alternate create PNG structure for reading, and allocate any memory * needed. */ PNG_FUNCTION(png_structp,PNGAPI png_create_read_struct_2,(png_const_charp user_png_ver, png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn),PNG_ALLOCATED) { png_structp png_ptr = png_create_png_struct(user_png_ver, error_ptr, error_fn, warn_fn, mem_ptr, malloc_fn, free_fn); #endif /* PNG_USER_MEM_SUPPORTED */ if (png_ptr != NULL) { png_ptr->mode = PNG_IS_READ_STRUCT; /* Added in libpng-1.6.0; this can be used to detect a read structure if * required (it will be zero in a write structure.) */ # ifdef PNG_SEQUENTIAL_READ_SUPPORTED png_ptr->IDAT_read_size = PNG_IDAT_READ_SIZE; # endif # ifdef PNG_BENIGN_READ_ERRORS_SUPPORTED png_ptr->flags |= PNG_FLAG_BENIGN_ERRORS_WARN; /* In stable builds only warn if an application error can be completely * handled. */ # if PNG_LIBPNG_BUILD_BASE_TYPE >= PNG_LIBPNG_BUILD_RC png_ptr->flags |= PNG_FLAG_APP_WARNINGS_WARN; # endif # endif /* TODO: delay this, it can be done in png_init_io (if the app doesn't * do it itself) avoiding setting the default function if it is not * required. */ png_set_read_fn(png_ptr, NULL, NULL); } return png_ptr; } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED /* Read the information before the actual image data. This has been * changed in v0.90 to allow reading a file that already has the magic * bytes read from the stream. You can tell libpng how many bytes have * been read from the beginning of the stream (up to the maximum of 8) * via png_set_sig_bytes(), and we will only check the remaining bytes * here. The application can then have access to the signature bytes we * read if it is determined that this isn't a valid PNG file. */ void PNGAPI png_read_info(png_structrp png_ptr, png_inforp info_ptr) { #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED int keep; #endif png_debug(1, "in png_read_info"); if (png_ptr == NULL || info_ptr == NULL) return; /* Read and check the PNG file signature. */ png_read_sig(png_ptr, info_ptr); for (;;) { png_uint_32 length = png_read_chunk_header(png_ptr); png_uint_32 chunk_name = png_ptr->chunk_name; /* IDAT logic needs to happen here to simplify getting the two flags * right. */ if (chunk_name == png_IDAT) { if (!(png_ptr->mode & PNG_HAVE_IHDR)) png_chunk_error(png_ptr, "Missing IHDR before IDAT"); else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && !(png_ptr->mode & PNG_HAVE_PLTE)) png_chunk_error(png_ptr, "Missing PLTE before IDAT"); else if (png_ptr->mode & PNG_AFTER_IDAT) png_chunk_benign_error(png_ptr, "Too many IDATs found"); png_ptr->mode |= PNG_HAVE_IDAT; } else if (png_ptr->mode & PNG_HAVE_IDAT) png_ptr->mode |= PNG_AFTER_IDAT; /* This should be a binary subdivision search or a hash for * matching the chunk name rather than a linear search. */ if (chunk_name == png_IHDR) png_handle_IHDR(png_ptr, info_ptr, length); else if (chunk_name == png_IEND) png_handle_IEND(png_ptr, info_ptr, length); #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0) { png_handle_unknown(png_ptr, info_ptr, length, keep); if (chunk_name == png_PLTE) png_ptr->mode |= PNG_HAVE_PLTE; else if (chunk_name == png_IDAT) { png_ptr->idat_size = 0; /* It has been consumed */ break; } } #endif else if (chunk_name == png_PLTE) png_handle_PLTE(png_ptr, info_ptr, length); else if (chunk_name == png_IDAT) { png_ptr->idat_size = length; break; } #ifdef PNG_READ_bKGD_SUPPORTED else if (chunk_name == png_bKGD) png_handle_bKGD(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_cHRM_SUPPORTED else if (chunk_name == png_cHRM) png_handle_cHRM(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_gAMA_SUPPORTED else if (chunk_name == png_gAMA) png_handle_gAMA(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_hIST_SUPPORTED else if (chunk_name == png_hIST) png_handle_hIST(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_oFFs_SUPPORTED else if (chunk_name == png_oFFs) png_handle_oFFs(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_pCAL_SUPPORTED else if (chunk_name == png_pCAL) png_handle_pCAL(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sCAL_SUPPORTED else if (chunk_name == png_sCAL) png_handle_sCAL(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_pHYs_SUPPORTED else if (chunk_name == png_pHYs) png_handle_pHYs(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sBIT_SUPPORTED else if (chunk_name == png_sBIT) png_handle_sBIT(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sRGB_SUPPORTED else if (chunk_name == png_sRGB) png_handle_sRGB(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_iCCP_SUPPORTED else if (chunk_name == png_iCCP) png_handle_iCCP(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sPLT_SUPPORTED else if (chunk_name == png_sPLT) png_handle_sPLT(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tEXt_SUPPORTED else if (chunk_name == png_tEXt) png_handle_tEXt(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tIME_SUPPORTED else if (chunk_name == png_tIME) png_handle_tIME(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tRNS_SUPPORTED else if (chunk_name == png_tRNS) png_handle_tRNS(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_zTXt_SUPPORTED else if (chunk_name == png_zTXt) png_handle_zTXt(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_iTXt_SUPPORTED else if (chunk_name == png_iTXt) png_handle_iTXt(png_ptr, info_ptr, length); #endif else png_handle_unknown(png_ptr, info_ptr, length, PNG_HANDLE_CHUNK_AS_DEFAULT); } } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ /* Optional call to update the users info_ptr structure */ void PNGAPI png_read_update_info(png_structrp png_ptr, png_inforp info_ptr) { png_debug(1, "in png_read_update_info"); if (png_ptr != NULL) { if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0) { png_read_start_row(png_ptr); # ifdef PNG_READ_TRANSFORMS_SUPPORTED png_read_transform_info(png_ptr, info_ptr); # else PNG_UNUSED(info_ptr) # endif } /* New in 1.6.0 this avoids the bug of doing the initializations twice */ else png_app_error(png_ptr, "png_read_update_info/png_start_read_image: duplicate call"); } } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED /* Initialize palette, background, etc, after transformations * are set, but before any reading takes place. This allows * the user to obtain a gamma-corrected palette, for example. * If the user doesn't call this, we will do it ourselves. */ void PNGAPI png_start_read_image(png_structrp png_ptr) { png_debug(1, "in png_start_read_image"); if (png_ptr != NULL) { if ((png_ptr->flags & PNG_FLAG_ROW_INIT) == 0) png_read_start_row(png_ptr); /* New in 1.6.0 this avoids the bug of doing the initializations twice */ else png_app_error(png_ptr, "png_start_read_image/png_read_update_info: duplicate call"); } } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ #ifdef PNG_SEQUENTIAL_READ_SUPPORTED void PNGAPI png_read_row(png_structrp png_ptr, png_bytep row, png_bytep dsp_row) { png_row_info row_info; if (png_ptr == NULL) return; png_debug2(1, "in png_read_row (row %lu, pass %d)", (unsigned long)png_ptr->row_number, png_ptr->pass); /* png_read_start_row sets the information (in particular iwidth) for this * interlace pass. */ if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) png_read_start_row(png_ptr); /* 1.5.6: row_info moved out of png_struct to a local here. */ row_info.width = png_ptr->iwidth; /* NOTE: width of current interlaced row */ row_info.color_type = png_ptr->color_type; row_info.bit_depth = png_ptr->bit_depth; row_info.channels = png_ptr->channels; row_info.pixel_depth = png_ptr->pixel_depth; row_info.rowbytes = PNG_ROWBYTES(row_info.pixel_depth, row_info.width); if (png_ptr->row_number == 0 && png_ptr->pass == 0) { /* Check for transforms that have been set but were defined out */ #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED) if (png_ptr->transformations & PNG_INVERT_MONO) png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED) if (png_ptr->transformations & PNG_FILLER) png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && \ !defined(PNG_READ_PACKSWAP_SUPPORTED) if (png_ptr->transformations & PNG_PACKSWAP) png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED) if (png_ptr->transformations & PNG_PACK) png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) if (png_ptr->transformations & PNG_SHIFT) png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED) if (png_ptr->transformations & PNG_BGR) png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined"); #endif #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED) if (png_ptr->transformations & PNG_SWAP_BYTES) png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined"); #endif } #ifdef PNG_READ_INTERLACING_SUPPORTED /* If interlaced and we do not need a new row, combine row and return. * Notice that the pixels we have from previous rows have been transformed * already; we can only combine like with like (transformed or * untransformed) and, because of the libpng API for interlaced images, this * means we must transform before de-interlacing. */ if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) { switch (png_ptr->pass) { case 0: if (png_ptr->row_number & 0x07) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; case 1: if ((png_ptr->row_number & 0x07) || png_ptr->width < 5) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; case 2: if ((png_ptr->row_number & 0x07) != 4) { if (dsp_row != NULL && (png_ptr->row_number & 4)) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; case 3: if ((png_ptr->row_number & 3) || png_ptr->width < 3) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; case 4: if ((png_ptr->row_number & 3) != 2) { if (dsp_row != NULL && (png_ptr->row_number & 2)) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; case 5: if ((png_ptr->row_number & 1) || png_ptr->width < 2) { if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 1/*display*/); png_read_finish_row(png_ptr); return; } break; default: case 6: if (!(png_ptr->row_number & 1)) { png_read_finish_row(png_ptr); return; } break; } } #endif if (!(png_ptr->mode & PNG_HAVE_IDAT)) png_error(png_ptr, "Invalid attempt to read row data"); /* Fill the row with IDAT data: */ png_read_IDAT_data(png_ptr, png_ptr->row_buf, row_info.rowbytes + 1); if (png_ptr->row_buf[0] > PNG_FILTER_VALUE_NONE) { if (png_ptr->row_buf[0] < PNG_FILTER_VALUE_LAST) png_read_filter_row(png_ptr, &row_info, png_ptr->row_buf + 1, png_ptr->prev_row + 1, png_ptr->row_buf[0]); else png_error(png_ptr, "bad adaptive filter value"); } /* libpng 1.5.6: the following line was copying png_ptr->rowbytes before * 1.5.6, while the buffer really is this big in current versions of libpng * it may not be in the future, so this was changed just to copy the * interlaced count: */ memcpy(png_ptr->prev_row, png_ptr->row_buf, row_info.rowbytes + 1); #ifdef PNG_MNG_FEATURES_SUPPORTED if ((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) && (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING)) { /* Intrapixel differencing */ png_do_read_intrapixel(&row_info, png_ptr->row_buf + 1); } #endif #ifdef PNG_READ_TRANSFORMS_SUPPORTED if (png_ptr->transformations) png_do_read_transformations(png_ptr, &row_info); #endif /* The transformed pixel depth should match the depth now in row_info. */ if (png_ptr->transformed_pixel_depth == 0) { png_ptr->transformed_pixel_depth = row_info.pixel_depth; if (row_info.pixel_depth > png_ptr->maximum_pixel_depth) png_error(png_ptr, "sequential row overflow"); } else if (png_ptr->transformed_pixel_depth != row_info.pixel_depth) png_error(png_ptr, "internal sequential row size calculation error"); #ifdef PNG_READ_INTERLACING_SUPPORTED /* Blow up interlaced rows to full size */ if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) { if (png_ptr->pass < 6) png_do_read_interlace(&row_info, png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, 1/*display*/); if (row != NULL) png_combine_row(png_ptr, row, 0/*row*/); } else #endif { if (row != NULL) png_combine_row(png_ptr, row, -1/*ignored*/); if (dsp_row != NULL) png_combine_row(png_ptr, dsp_row, -1/*ignored*/); } png_read_finish_row(png_ptr); if (png_ptr->read_row_fn != NULL) (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass); } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ #ifdef PNG_SEQUENTIAL_READ_SUPPORTED /* Read one or more rows of image data. If the image is interlaced, * and png_set_interlace_handling() has been called, the rows need to * contain the contents of the rows from the previous pass. If the * image has alpha or transparency, and png_handle_alpha()[*] has been * called, the rows contents must be initialized to the contents of the * screen. * * "row" holds the actual image, and pixels are placed in it * as they arrive. If the image is displayed after each pass, it will * appear to "sparkle" in. "display_row" can be used to display a * "chunky" progressive image, with finer detail added as it becomes * available. If you do not want this "chunky" display, you may pass * NULL for display_row. If you do not want the sparkle display, and * you have not called png_handle_alpha(), you may pass NULL for rows. * If you have called png_handle_alpha(), and the image has either an * alpha channel or a transparency chunk, you must provide a buffer for * rows. In this case, you do not have to provide a display_row buffer * also, but you may. If the image is not interlaced, or if you have * not called png_set_interlace_handling(), the display_row buffer will * be ignored, so pass NULL to it. * * [*] png_handle_alpha() does not exist yet, as of this version of libpng */ void PNGAPI png_read_rows(png_structrp png_ptr, png_bytepp row, png_bytepp display_row, png_uint_32 num_rows) { png_uint_32 i; png_bytepp rp; png_bytepp dp; png_debug(1, "in png_read_rows"); if (png_ptr == NULL) return; rp = row; dp = display_row; if (rp != NULL && dp != NULL) for (i = 0; i < num_rows; i++) { png_bytep rptr = *rp++; png_bytep dptr = *dp++; png_read_row(png_ptr, rptr, dptr); } else if (rp != NULL) for (i = 0; i < num_rows; i++) { png_bytep rptr = *rp; png_read_row(png_ptr, rptr, NULL); rp++; } else if (dp != NULL) for (i = 0; i < num_rows; i++) { png_bytep dptr = *dp; png_read_row(png_ptr, NULL, dptr); dp++; } } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ #ifdef PNG_SEQUENTIAL_READ_SUPPORTED /* Read the entire image. If the image has an alpha channel or a tRNS * chunk, and you have called png_handle_alpha()[*], you will need to * initialize the image to the current image that PNG will be overlaying. * We set the num_rows again here, in case it was incorrectly set in * png_read_start_row() by a call to png_read_update_info() or * png_start_read_image() if png_set_interlace_handling() wasn't called * prior to either of these functions like it should have been. You can * only call this function once. If you desire to have an image for * each pass of a interlaced image, use png_read_rows() instead. * * [*] png_handle_alpha() does not exist yet, as of this version of libpng */ void PNGAPI png_read_image(png_structrp png_ptr, png_bytepp image) { png_uint_32 i, image_height; int pass, j; png_bytepp rp; png_debug(1, "in png_read_image"); if (png_ptr == NULL) return; #ifdef PNG_READ_INTERLACING_SUPPORTED if (!(png_ptr->flags & PNG_FLAG_ROW_INIT)) { pass = png_set_interlace_handling(png_ptr); /* And make sure transforms are initialized. */ png_start_read_image(png_ptr); } else { if (png_ptr->interlaced && !(png_ptr->transformations & PNG_INTERLACE)) { /* Caller called png_start_read_image or png_read_update_info without * first turning on the PNG_INTERLACE transform. We can fix this here, * but the caller should do it! */ png_warning(png_ptr, "Interlace handling should be turned on when " "using png_read_image"); /* Make sure this is set correctly */ png_ptr->num_rows = png_ptr->height; } /* Obtain the pass number, which also turns on the PNG_INTERLACE flag in * the above error case. */ pass = png_set_interlace_handling(png_ptr); } #else if (png_ptr->interlaced) png_error(png_ptr, "Cannot read interlaced image -- interlace handler disabled"); pass = 1; #endif image_height=png_ptr->height; for (j = 0; j < pass; j++) { rp = image; for (i = 0; i < image_height; i++) { png_read_row(png_ptr, *rp, NULL); rp++; } } } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ #ifdef PNG_SEQUENTIAL_READ_SUPPORTED /* Read the end of the PNG file. Will not read past the end of the * file, will verify the end is accurate, and will read any comments * or time information at the end of the file, if info is not NULL. */ void PNGAPI png_read_end(png_structrp png_ptr, png_inforp info_ptr) { #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED int keep; #endif png_debug(1, "in png_read_end"); if (png_ptr == NULL) return; /* If png_read_end is called in the middle of reading the rows there may * still be pending IDAT data and an owned zstream. Deal with this here. */ #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED if (!png_chunk_unknown_handling(png_ptr, png_IDAT)) #endif png_read_finish_IDAT(png_ptr); #ifdef PNG_READ_CHECK_FOR_INVALID_INDEX_SUPPORTED /* Report invalid palette index; added at libng-1.5.10 */ if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_palette_max > png_ptr->num_palette) png_benign_error(png_ptr, "Read palette index exceeding num_palette"); #endif do { png_uint_32 length = png_read_chunk_header(png_ptr); png_uint_32 chunk_name = png_ptr->chunk_name; if (chunk_name == png_IHDR) png_handle_IHDR(png_ptr, info_ptr, length); else if (chunk_name == png_IEND) png_handle_IEND(png_ptr, info_ptr, length); #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED else if ((keep = png_chunk_unknown_handling(png_ptr, chunk_name)) != 0) { if (chunk_name == png_IDAT) { if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT)) png_benign_error(png_ptr, "Too many IDATs found"); } png_handle_unknown(png_ptr, info_ptr, length, keep); if (chunk_name == png_PLTE) png_ptr->mode |= PNG_HAVE_PLTE; } #endif else if (chunk_name == png_IDAT) { /* Zero length IDATs are legal after the last IDAT has been * read, but not after other chunks have been read. */ if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT)) png_benign_error(png_ptr, "Too many IDATs found"); png_crc_finish(png_ptr, length); } else if (chunk_name == png_PLTE) png_handle_PLTE(png_ptr, info_ptr, length); #ifdef PNG_READ_bKGD_SUPPORTED else if (chunk_name == png_bKGD) png_handle_bKGD(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_cHRM_SUPPORTED else if (chunk_name == png_cHRM) png_handle_cHRM(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_gAMA_SUPPORTED else if (chunk_name == png_gAMA) png_handle_gAMA(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_hIST_SUPPORTED else if (chunk_name == png_hIST) png_handle_hIST(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_oFFs_SUPPORTED else if (chunk_name == png_oFFs) png_handle_oFFs(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_pCAL_SUPPORTED else if (chunk_name == png_pCAL) png_handle_pCAL(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sCAL_SUPPORTED else if (chunk_name == png_sCAL) png_handle_sCAL(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_pHYs_SUPPORTED else if (chunk_name == png_pHYs) png_handle_pHYs(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sBIT_SUPPORTED else if (chunk_name == png_sBIT) png_handle_sBIT(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sRGB_SUPPORTED else if (chunk_name == png_sRGB) png_handle_sRGB(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_iCCP_SUPPORTED else if (chunk_name == png_iCCP) png_handle_iCCP(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_sPLT_SUPPORTED else if (chunk_name == png_sPLT) png_handle_sPLT(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tEXt_SUPPORTED else if (chunk_name == png_tEXt) png_handle_tEXt(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tIME_SUPPORTED else if (chunk_name == png_tIME) png_handle_tIME(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_tRNS_SUPPORTED else if (chunk_name == png_tRNS) png_handle_tRNS(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_zTXt_SUPPORTED else if (chunk_name == png_zTXt) png_handle_zTXt(png_ptr, info_ptr, length); #endif #ifdef PNG_READ_iTXt_SUPPORTED else if (chunk_name == png_iTXt) png_handle_iTXt(png_ptr, info_ptr, length); #endif else png_handle_unknown(png_ptr, info_ptr, length, PNG_HANDLE_CHUNK_AS_DEFAULT); } while (!(png_ptr->mode & PNG_HAVE_IEND)); } #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ /* Free all memory used in the read struct */ static void png_read_destroy(png_structrp png_ptr) { png_debug(1, "in png_read_destroy"); #ifdef PNG_READ_GAMMA_SUPPORTED png_destroy_gamma_table(png_ptr); #endif png_free(png_ptr, png_ptr->big_row_buf); png_free(png_ptr, png_ptr->big_prev_row); png_free(png_ptr, png_ptr->read_buffer); #ifdef PNG_READ_QUANTIZE_SUPPORTED png_free(png_ptr, png_ptr->palette_lookup); png_free(png_ptr, png_ptr->quantize_index); #endif if (png_ptr->free_me & PNG_FREE_PLTE) png_zfree(png_ptr, png_ptr->palette); png_ptr->free_me &= ~PNG_FREE_PLTE; #if defined(PNG_tRNS_SUPPORTED) || \ defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) if (png_ptr->free_me & PNG_FREE_TRNS) png_free(png_ptr, png_ptr->trans_alpha); png_ptr->free_me &= ~PNG_FREE_TRNS; #endif inflateEnd(&png_ptr->zstream); #ifdef PNG_PROGRESSIVE_READ_SUPPORTED png_free(png_ptr, png_ptr->save_buffer); #endif #if defined(PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED) &&\ defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED) png_free(png_ptr, png_ptr->unknown_chunk.data); #endif #ifdef PNG_SET_UNKNOWN_CHUNKS_SUPPORTED png_free(png_ptr, png_ptr->chunk_list); #endif /* NOTE: the 'setjmp' buffer may still be allocated and the memory and error * callbacks are still set at this point. They are required to complete the * destruction of the png_struct itself. */ } /* Free all memory used by the read */ void PNGAPI png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr) { png_structrp png_ptr = NULL; png_debug(1, "in png_destroy_read_struct"); if (png_ptr_ptr != NULL) png_ptr = *png_ptr_ptr; if (png_ptr == NULL) return; /* libpng 1.6.0: use the API to destroy info structs to ensure consistent * behavior. Prior to 1.6.0 libpng did extra 'info' destruction in this API. * The extra was, apparently, unnecessary yet this hides memory leak bugs. */ png_destroy_info_struct(png_ptr, end_info_ptr_ptr); png_destroy_info_struct(png_ptr, info_ptr_ptr); *png_ptr_ptr = NULL; png_read_destroy(png_ptr); png_destroy_png_struct(png_ptr); } void PNGAPI png_set_read_status_fn(png_structrp png_ptr, png_read_status_ptr read_row_fn) { if (png_ptr == NULL) return; png_ptr->read_row_fn = read_row_fn; } #ifdef PNG_SEQUENTIAL_READ_SUPPORTED #ifdef PNG_INFO_IMAGE_SUPPORTED void PNGAPI png_read_png(png_structrp png_ptr, png_inforp info_ptr, int transforms, voidp params) { int row; if (png_ptr == NULL || info_ptr == NULL) return; /* png_read_info() gives us all of the information from the * PNG file before the first IDAT (image data chunk). */ png_read_info(png_ptr, info_ptr); if (info_ptr->height > PNG_UINT_32_MAX/(sizeof (png_bytep))) png_error(png_ptr, "Image is too high to process with png_read_png()"); /* -------------- image transformations start here ------------------- */ #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* Tell libpng to strip 16-bit/color files down to 8 bits per color. */ if (transforms & PNG_TRANSFORM_SCALE_16) { /* Added at libpng-1.5.4. "strip_16" produces the same result that it * did in earlier versions, while "scale_16" is now more accurate. */ png_set_scale_16(png_ptr); } #endif #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED /* If both SCALE and STRIP are required pngrtran will effectively cancel the * latter by doing SCALE first. This is ok and allows apps not to check for * which is supported to get the right answer. */ if (transforms & PNG_TRANSFORM_STRIP_16) png_set_strip_16(png_ptr); #endif #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED /* Strip alpha bytes from the input data without combining with * the background (not recommended). */ if (transforms & PNG_TRANSFORM_STRIP_ALPHA) png_set_strip_alpha(png_ptr); #endif #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED) /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single * byte into separate bytes (useful for paletted and grayscale images). */ if (transforms & PNG_TRANSFORM_PACKING) png_set_packing(png_ptr); #endif #ifdef PNG_READ_PACKSWAP_SUPPORTED /* Change the order of packed pixels to least significant bit first * (not useful if you are using png_set_packing). */ if (transforms & PNG_TRANSFORM_PACKSWAP) png_set_packswap(png_ptr); #endif #ifdef PNG_READ_EXPAND_SUPPORTED /* Expand paletted colors into true RGB triplets * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel * Expand paletted or RGB images with transparency to full alpha * channels so the data will be available as RGBA quartets. */ if (transforms & PNG_TRANSFORM_EXPAND) if ((png_ptr->bit_depth < 8) || (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) || (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))) png_set_expand(png_ptr); #endif /* We don't handle background color or gamma transformation or quantizing. */ #ifdef PNG_READ_INVERT_SUPPORTED /* Invert monochrome files to have 0 as white and 1 as black */ if (transforms & PNG_TRANSFORM_INVERT_MONO) png_set_invert_mono(png_ptr); #endif #ifdef PNG_READ_SHIFT_SUPPORTED /* If you want to shift the pixel values from the range [0,255] or * [0,65535] to the original [0,7] or [0,31], or whatever range the * colors were originally in: */ if ((transforms & PNG_TRANSFORM_SHIFT) && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT)) { png_color_8p sig_bit; png_get_sBIT(png_ptr, info_ptr, &sig_bit); png_set_shift(png_ptr, sig_bit); } #endif #ifdef PNG_READ_BGR_SUPPORTED /* Flip the RGB pixels to BGR (or RGBA to BGRA) */ if (transforms & PNG_TRANSFORM_BGR) png_set_bgr(png_ptr); #endif #ifdef PNG_READ_SWAP_ALPHA_SUPPORTED /* Swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR) */ if (transforms & PNG_TRANSFORM_SWAP_ALPHA) png_set_swap_alpha(png_ptr); #endif #ifdef PNG_READ_SWAP_SUPPORTED /* Swap bytes of 16-bit files to least significant byte first */ if (transforms & PNG_TRANSFORM_SWAP_ENDIAN) png_set_swap(png_ptr); #endif /* Added at libpng-1.2.41 */ #ifdef PNG_READ_INVERT_ALPHA_SUPPORTED /* Invert the alpha channel from opacity to transparency */ if (transforms & PNG_TRANSFORM_INVERT_ALPHA) png_set_invert_alpha(png_ptr); #endif /* Added at libpng-1.2.41 */ #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED /* Expand grayscale image to RGB */ if (transforms & PNG_TRANSFORM_GRAY_TO_RGB) png_set_gray_to_rgb(png_ptr); #endif /* Added at libpng-1.5.4 */ #ifdef PNG_READ_EXPAND_16_SUPPORTED if (transforms & PNG_TRANSFORM_EXPAND_16) png_set_expand_16(png_ptr); #endif /* We don't handle adding filler bytes */ /* We use png_read_image and rely on that for interlace handling, but we also * call png_read_update_info therefore must turn on interlace handling now: */ (void)png_set_interlace_handling(png_ptr); /* Optional call to gamma correct and add the background to the palette * and update info structure. REQUIRED if you are expecting libpng to * update the palette for you (i.e., you selected such a transform above). */ png_read_update_info(png_ptr, info_ptr); /* -------------- image transformations end here ------------------- */ png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0); if (info_ptr->row_pointers == NULL) { png_uint_32 iptr; info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr, info_ptr->height * (sizeof (png_bytep))); for (iptr=0; iptr<info_ptr->height; iptr++) info_ptr->row_pointers[iptr] = NULL; info_ptr->free_me |= PNG_FREE_ROWS; for (row = 0; row < (int)info_ptr->height; row++) info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); } png_read_image(png_ptr, info_ptr->row_pointers); info_ptr->valid |= PNG_INFO_IDAT; /* Read rest of file, and get additional chunks in info_ptr - REQUIRED */ png_read_end(png_ptr, info_ptr); PNG_UNUSED(transforms) /* Quiet compiler warnings */ PNG_UNUSED(params) } #endif /* PNG_INFO_IMAGE_SUPPORTED */ #endif /* PNG_SEQUENTIAL_READ_SUPPORTED */ #ifdef PNG_SIMPLIFIED_READ_SUPPORTED /* SIMPLIFIED READ * * This code currently relies on the sequential reader, though it could easily * be made to work with the progressive one. */ /* Arguments to png_image_finish_read: */ /* Encoding of PNG data (used by the color-map code) */ /* TODO: change these, dang, ANSI-C reserves the 'E' namespace. */ # define E_NOTSET 0 /* File encoding not yet known */ # define E_sRGB 1 /* 8-bit encoded to sRGB gamma */ # define E_LINEAR 2 /* 16-bit linear: not encoded, NOT pre-multiplied! */ # define E_FILE 3 /* 8-bit encoded to file gamma, not sRGB or linear */ # define E_LINEAR8 4 /* 8-bit linear: only from a file value */ /* Color-map processing: after libpng has run on the PNG image further * processing may be needed to conver the data to color-map indicies. */ #define PNG_CMAP_NONE 0 #define PNG_CMAP_GA 1 /* Process GA data to a color-map with alpha */ #define PNG_CMAP_TRANS 2 /* Process GA data to a background index */ #define PNG_CMAP_RGB 3 /* Process RGB data */ #define PNG_CMAP_RGB_ALPHA 4 /* Process RGBA data */ /* The following document where the background is for each processing case. */ #define PNG_CMAP_NONE_BACKGROUND 256 #define PNG_CMAP_GA_BACKGROUND 231 #define PNG_CMAP_TRANS_BACKGROUND 254 #define PNG_CMAP_RGB_BACKGROUND 256 #define PNG_CMAP_RGB_ALPHA_BACKGROUND 216 typedef struct { /* Arguments: */ png_imagep image; png_voidp buffer; png_int_32 row_stride; png_voidp colormap; png_const_colorp background; /* Local variables: */ png_voidp local_row; png_voidp first_row; ptrdiff_t row_bytes; /* step between rows */ int file_encoding; /* E_ values above */ png_fixed_point gamma_to_linear; /* For E_FILE, reciprocal of gamma */ int colormap_processing; /* PNG_CMAP_ values above */ } png_image_read_control; /* Do all the *safe* initialization - 'safe' means that png_error won't be * called, so setting up the jmp_buf is not required. This means that anything * called from here must *not* call png_malloc - it has to call png_malloc_warn * instead so that control is returned safely back to this routine. */ static int png_image_read_init(png_imagep image) { if (image->opaque == NULL) { png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, image, png_safe_error, png_safe_warning); /* And set the rest of the structure to NULL to ensure that the various * fields are consistent. */ memset(image, 0, (sizeof *image)); image->version = PNG_IMAGE_VERSION; if (png_ptr != NULL) { png_infop info_ptr = png_create_info_struct(png_ptr); if (info_ptr != NULL) { png_controlp control = png_voidcast(png_controlp, png_malloc_warn(png_ptr, (sizeof *control))); if (control != NULL) { memset(control, 0, (sizeof *control)); control->png_ptr = png_ptr; control->info_ptr = info_ptr; control->for_write = 0; image->opaque = control; return 1; } /* Error clean up */ png_destroy_info_struct(png_ptr, &info_ptr); } png_destroy_read_struct(&png_ptr, NULL, NULL); } return png_image_error(image, "png_image_read: out of memory"); } return png_image_error(image, "png_image_read: opaque pointer not NULL"); } /* Utility to find the base format of a PNG file from a png_struct. */ static png_uint_32 png_image_format(png_structrp png_ptr) { png_uint_32 format = 0; if (png_ptr->color_type & PNG_COLOR_MASK_COLOR) format |= PNG_FORMAT_FLAG_COLOR; if (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) format |= PNG_FORMAT_FLAG_ALPHA; /* Use png_ptr here, not info_ptr, because by examination png_handle_tRNS * sets the png_struct fields; that's all we are interested in here. The * precise interaction with an app call to png_set_tRNS and PNG file reading * is unclear. */ else if (png_ptr->num_trans > 0) format |= PNG_FORMAT_FLAG_ALPHA; if (png_ptr->bit_depth == 16) format |= PNG_FORMAT_FLAG_LINEAR; if (png_ptr->color_type & PNG_COLOR_MASK_PALETTE) format |= PNG_FORMAT_FLAG_COLORMAP; return format; } /* Is the given gamma significantly different from sRGB? The test is the same * one used in pngrtran.c when deciding whether to do gamma correction. The * arithmetic optimizes the division by using the fact that the inverse of the * file sRGB gamma is 2.2 */ static int png_gamma_not_sRGB(png_fixed_point g) { if (g < PNG_FP_1) { /* An uninitialized gamma is assumed to be sRGB for the simplified API. */ if (g == 0) return 0; return png_gamma_significant((g * 11 + 2)/5 /* i.e. *2.2, rounded */); } return 1; } /* Do the main body of a 'png_image_begin_read' function; read the PNG file * header and fill in all the information. This is executed in a safe context, * unlike the init routine above. */ static int png_image_read_header(png_voidp argument) { png_imagep image = png_voidcast(png_imagep, argument); png_structrp png_ptr = image->opaque->png_ptr; png_inforp info_ptr = image->opaque->info_ptr; png_set_benign_errors(png_ptr, 1/*warn*/); png_read_info(png_ptr, info_ptr); /* Do this the fast way; just read directly out of png_struct. */ image->width = png_ptr->width; image->height = png_ptr->height; { png_uint_32 format = png_image_format(png_ptr); image->format = format; #ifdef PNG_COLORSPACE_SUPPORTED /* Does the colorspace match sRGB? If there is no color endpoint * (colorant) information assume yes, otherwise require the * 'ENDPOINTS_MATCHE_sRGB' colorspace flag to have been set. If the * colorspace has been determined to be invalid ignore it. */ if ((format & PNG_FORMAT_FLAG_COLOR) != 0 && ((png_ptr->colorspace.flags & (PNG_COLORSPACE_HAVE_ENDPOINTS|PNG_COLORSPACE_ENDPOINTS_MATCH_sRGB| PNG_COLORSPACE_INVALID)) == PNG_COLORSPACE_HAVE_ENDPOINTS)) image->flags |= PNG_IMAGE_FLAG_COLORSPACE_NOT_sRGB; #endif } /* We need the maximum number of entries regardless of the format the * application sets here. */ { png_uint_32 cmap_entries; switch (png_ptr->color_type) { case PNG_COLOR_TYPE_GRAY: cmap_entries = 1U << png_ptr->bit_depth; break; case PNG_COLOR_TYPE_PALETTE: cmap_entries = png_ptr->num_palette; break; default: cmap_entries = 256; break; } if (cmap_entries > 256) cmap_entries = 256; image->colormap_entries = cmap_entries; } return 1; } #ifdef PNG_STDIO_SUPPORTED int PNGAPI png_image_begin_read_from_stdio(png_imagep image, FILE* file) { if (image != NULL && image->version == PNG_IMAGE_VERSION) { if (file != NULL) { if (png_image_read_init(image)) { /* This is slightly evil, but png_init_io doesn't do anything other * than this and we haven't changed the standard IO functions so * this saves a 'safe' function. */ image->opaque->png_ptr->io_ptr = file; return png_safe_execute(image, png_image_read_header, image); } } else return png_image_error(image, "png_image_begin_read_from_stdio: invalid argument"); } else if (image != NULL) return png_image_error(image, "png_image_begin_read_from_stdio: incorrect PNG_IMAGE_VERSION"); return 0; } int PNGAPI png_image_begin_read_from_file(png_imagep image, const char *file_name) { if (image != NULL && image->version == PNG_IMAGE_VERSION) { if (file_name != NULL) { FILE *fp = fopen(file_name, "rb"); if (fp != NULL) { if (png_image_read_init(image)) { image->opaque->png_ptr->io_ptr = fp; image->opaque->owned_file = 1; return png_safe_execute(image, png_image_read_header, image); } /* Clean up: just the opened file. */ (void)fclose(fp); } else return png_image_error(image, strerror(errno)); } else return png_image_error(image, "png_image_begin_read_from_file: invalid argument"); } else if (image != NULL) return png_image_error(image, "png_image_begin_read_from_file: incorrect PNG_IMAGE_VERSION"); return 0; } #endif /* PNG_STDIO_SUPPORTED */ static void PNGCBAPI png_image_memory_read(png_structp png_ptr, png_bytep out, png_size_t need) { if (png_ptr != NULL) { png_imagep image = png_voidcast(png_imagep, png_ptr->io_ptr); if (image != NULL) { png_controlp cp = image->opaque; if (cp != NULL) { png_const_bytep memory = cp->memory; png_size_t size = cp->size; if (memory != NULL && size >= need) { memcpy(out, memory, need); cp->memory = memory + need; cp->size = size - need; return; } png_error(png_ptr, "read beyond end of data"); } } png_error(png_ptr, "invalid memory read"); } } int PNGAPI png_image_begin_read_from_memory(png_imagep image, png_const_voidp memory, png_size_t size) { if (image != NULL && image->version == PNG_IMAGE_VERSION) { if (memory != NULL && size > 0) { if (png_image_read_init(image)) { /* Now set the IO functions to read from the memory buffer and * store it into io_ptr. Again do this in-place to avoid calling a * libpng function that requires error handling. */ image->opaque->memory = png_voidcast(png_const_bytep, memory); image->opaque->size = size; image->opaque->png_ptr->io_ptr = image; image->opaque->png_ptr->read_data_fn = png_image_memory_read; return png_safe_execute(image, png_image_read_header, image); } } else return png_image_error(image, "png_image_begin_read_from_memory: invalid argument"); } else if (image != NULL) return png_image_error(image, "png_image_begin_read_from_memory: incorrect PNG_IMAGE_VERSION"); return 0; } /* Utility function to skip chunks that are not used by the simplified image * read functions and an appropriate macro to call it. */ #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED static void png_image_skip_unused_chunks(png_structrp png_ptr) { /* Prepare the reader to ignore all recognized chunks whose data will not * be used, i.e., all chunks recognized by libpng except for those * involved in basic image reading: * * IHDR, PLTE, IDAT, IEND * * Or image data handling: * * tRNS, bKGD, gAMA, cHRM, sRGB, iCCP and sBIT. * * This provides a small performance improvement and eliminates any * potential vulnerability to security problems in the unused chunks. */ { static PNG_CONST png_byte chunks_to_process[] = { 98, 75, 71, 68, '\0', /* bKGD */ 99, 72, 82, 77, '\0', /* cHRM */ 103, 65, 77, 65, '\0', /* gAMA */ 105, 67, 67, 80, '\0', /* iCCP */ 115, 66, 73, 84, '\0', /* sBIT */ 115, 82, 71, 66, '\0', /* sRGB */ }; /* Ignore unknown chunks and all other chunks except for the * IHDR, PLTE, tRNS, IDAT, and IEND chunks. */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_NEVER, NULL, -1); /* But do not ignore image data handling chunks */ png_set_keep_unknown_chunks(png_ptr, PNG_HANDLE_CHUNK_AS_DEFAULT, chunks_to_process, (sizeof chunks_to_process)/5); } } # define PNG_SKIP_CHUNKS(p) png_image_skip_unused_chunks(p) #else # define PNG_SKIP_CHUNKS(p) ((void)0) #endif /* PNG_HANDLE_AS_UNKNOWN_SUPPORTED */ /* The following macro gives the exact rounded answer for all values in the * range 0..255 (it actually divides by 51.2, but the rounding still generates * the correct numbers 0..5 */ #define PNG_DIV51(v8) (((v8) * 5 + 130) >> 8) /* Utility functions to make particular color-maps */ static void set_file_encoding(png_image_read_control *display) { png_fixed_point g = display->image->opaque->png_ptr->colorspace.gamma; if (png_gamma_significant(g)) { if (png_gamma_not_sRGB(g)) { display->file_encoding = E_FILE; display->gamma_to_linear = png_reciprocal(g); } else display->file_encoding = E_sRGB; } else display->file_encoding = E_LINEAR8; } static unsigned int decode_gamma(png_image_read_control *display, png_uint_32 value, int encoding) { if (encoding == E_FILE) /* double check */ encoding = display->file_encoding; if (encoding == E_NOTSET) /* must be the file encoding */ { set_file_encoding(display); encoding = display->file_encoding; } switch (encoding) { case E_FILE: value = png_gamma_16bit_correct(value*257, display->gamma_to_linear); break; case E_sRGB: value = png_sRGB_table[value]; break; case E_LINEAR: break; case E_LINEAR8: value *= 257; break; default: png_error(display->image->opaque->png_ptr, "unexpected encoding (internal error)"); break; } return value; } static png_uint_32 png_colormap_compose(png_image_read_control *display, png_uint_32 foreground, int foreground_encoding, png_uint_32 alpha, png_uint_32 background, int encoding) { /* The file value is composed on the background, the background has the given * encoding and so does the result, the file is encoded with E_FILE and the * file and alpha are 8-bit values. The (output) encoding will always be * E_LINEAR or E_sRGB. */ png_uint_32 f = decode_gamma(display, foreground, foreground_encoding); png_uint_32 b = decode_gamma(display, background, encoding); /* The alpha is always an 8-bit value (it comes from the palette), the value * scaled by 255 is what PNG_sRGB_FROM_LINEAR requires. */ f = f * alpha + b * (255-alpha); if (encoding == E_LINEAR) { /* Scale to 65535; divide by 255, approximately (in fact this is extremely * accurate, it divides by 255.00000005937181414556, with no overflow.) */ f *= 257; /* Now scaled by 65535 */ f += f >> 16; f = (f+32768) >> 16; } else /* E_sRGB */ f = PNG_sRGB_FROM_LINEAR(f); return f; } /* NOTE: E_LINEAR values to this routine must be 16-bit, but E_FILE values must * be 8-bit. */ static void png_create_colormap_entry(png_image_read_control *display, png_uint_32 ip, png_uint_32 red, png_uint_32 green, png_uint_32 blue, png_uint_32 alpha, int encoding) { png_imagep image = display->image; const int output_encoding = (image->format & PNG_FORMAT_FLAG_LINEAR) ? E_LINEAR : E_sRGB; const int convert_to_Y = (image->format & PNG_FORMAT_FLAG_COLOR) == 0 && (red != green || green != blue); if (ip > 255) png_error(image->opaque->png_ptr, "color-map index out of range"); /* Update the cache with whether the file gamma is significantly different * from sRGB. */ if (encoding == E_FILE) { if (display->file_encoding == E_NOTSET) set_file_encoding(display); /* Note that the cached value may be E_FILE too, but if it is then the * gamma_to_linear member has been set. */ encoding = display->file_encoding; } if (encoding == E_FILE) { png_fixed_point g = display->gamma_to_linear; red = png_gamma_16bit_correct(red*257, g); green = png_gamma_16bit_correct(green*257, g); blue = png_gamma_16bit_correct(blue*257, g); if (convert_to_Y || output_encoding == E_LINEAR) { alpha *= 257; encoding = E_LINEAR; } else { red = PNG_sRGB_FROM_LINEAR(red * 255); green = PNG_sRGB_FROM_LINEAR(green * 255); blue = PNG_sRGB_FROM_LINEAR(blue * 255); encoding = E_sRGB; } } else if (encoding == E_LINEAR8) { /* This encoding occurs quite frequently in test cases because PngSuite * includes a gAMA 1.0 chunk with most images. */ red *= 257; green *= 257; blue *= 257; alpha *= 257; encoding = E_LINEAR; } else if (encoding == E_sRGB && (convert_to_Y || output_encoding == E_LINEAR)) { /* The values are 8-bit sRGB values, but must be converted to 16-bit * linear. */ red = png_sRGB_table[red]; green = png_sRGB_table[green]; blue = png_sRGB_table[blue]; alpha *= 257; encoding = E_LINEAR; } /* This is set if the color isn't gray but the output is. */ if (encoding == E_LINEAR) { if (convert_to_Y) { /* NOTE: these values are copied from png_do_rgb_to_gray */ png_uint_32 y = (png_uint_32)6968 * red + (png_uint_32)23434 * green + (png_uint_32)2366 * blue; if (output_encoding == E_LINEAR) y = (y + 16384) >> 15; else { /* y is scaled by 32768, we need it scaled by 255: */ y = (y + 128) >> 8; y *= 255; y = PNG_sRGB_FROM_LINEAR((y + 64) >> 7); encoding = E_sRGB; } blue = red = green = y; } else if (output_encoding == E_sRGB) { red = PNG_sRGB_FROM_LINEAR(red * 255); green = PNG_sRGB_FROM_LINEAR(green * 255); blue = PNG_sRGB_FROM_LINEAR(blue * 255); alpha = PNG_DIV257(alpha); encoding = E_sRGB; } } if (encoding != output_encoding) png_error(image->opaque->png_ptr, "bad encoding (internal error)"); /* Store the value. */ { # ifdef PNG_FORMAT_BGR_SUPPORTED const int afirst = (image->format & PNG_FORMAT_FLAG_AFIRST) != 0 && (image->format & PNG_FORMAT_FLAG_ALPHA) != 0; # else # define afirst 0 # endif # ifdef PNG_FORMAT_BGR_SUPPORTED const int bgr = (image->format & PNG_FORMAT_FLAG_BGR) ? 2 : 0; # else # define bgr 0 # endif if (output_encoding == E_LINEAR) { png_uint_16p entry = png_voidcast(png_uint_16p, display->colormap); entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format); /* The linear 16-bit values must be pre-multiplied by the alpha channel * value, if less than 65535 (this is, effectively, composite on black * if the alpha channel is removed.) */ switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format)) { case 4: entry[afirst ? 0 : 3] = (png_uint_16)alpha; /* FALL THROUGH */ case 3: if (alpha < 65535) { if (alpha > 0) { blue = (blue * alpha + 32767U)/65535U; green = (green * alpha + 32767U)/65535U; red = (red * alpha + 32767U)/65535U; } else red = green = blue = 0; } entry[afirst + (2 ^ bgr)] = (png_uint_16)blue; entry[afirst + 1] = (png_uint_16)green; entry[afirst + bgr] = (png_uint_16)red; break; case 2: entry[1 ^ afirst] = (png_uint_16)alpha; /* FALL THROUGH */ case 1: if (alpha < 65535) { if (alpha > 0) green = (green * alpha + 32767U)/65535U; else green = 0; } entry[afirst] = (png_uint_16)green; break; default: break; } } else /* output encoding is E_sRGB */ { png_bytep entry = png_voidcast(png_bytep, display->colormap); entry += ip * PNG_IMAGE_SAMPLE_CHANNELS(image->format); switch (PNG_IMAGE_SAMPLE_CHANNELS(image->format)) { case 4: entry[afirst ? 0 : 3] = (png_byte)alpha; case 3: entry[afirst + (2 ^ bgr)] = (png_byte)blue; entry[afirst + 1] = (png_byte)green; entry[afirst + bgr] = (png_byte)red; break; case 2: entry[1 ^ afirst] = (png_byte)alpha; case 1: entry[afirst] = (png_byte)green; break; default: break; } } # ifdef afirst # undef afirst # endif # ifdef bgr # undef bgr # endif } } static int make_gray_file_colormap(png_image_read_control *display) { unsigned int i; for (i=0; i<256; ++i) png_create_colormap_entry(display, i, i, i, i, 255, E_FILE); return i; } static int make_gray_colormap(png_image_read_control *display) { unsigned int i; for (i=0; i<256; ++i) png_create_colormap_entry(display, i, i, i, i, 255, E_sRGB); return i; } #define PNG_GRAY_COLORMAP_ENTRIES 256 static int make_ga_colormap(png_image_read_control *display) { unsigned int i, a; /* Alpha is retained, the output will be a color-map with entries * selected by six levels of alpha. One transparent entry, 6 gray * levels for all the intermediate alpha values, leaving 230 entries * for the opaque grays. The color-map entries are the six values * [0..5]*51, the GA processing uses PNG_DIV51(value) to find the * relevant entry. * * if (alpha > 229) // opaque * { * // The 231 entries are selected to make the math below work: * base = 0; * entry = (231 * gray + 128) >> 8; * } * else if (alpha < 26) // transparent * { * base = 231; * entry = 0; * } * else // partially opaque * { * base = 226 + 6 * PNG_DIV51(alpha); * entry = PNG_DIV51(gray); * } */ i = 0; while (i < 231) { unsigned int gray = (i * 256 + 115) / 231; png_create_colormap_entry(display, i++, gray, gray, gray, 255, E_sRGB); } /* 255 is used here for the component values for consistency with the code * that undoes premultiplication in pngwrite.c. */ png_create_colormap_entry(display, i++, 255, 255, 255, 0, E_sRGB); for (a=1; a<5; ++a) { unsigned int g; for (g=0; g<6; ++g) png_create_colormap_entry(display, i++, g*51, g*51, g*51, a*51, E_sRGB); } return i; } #define PNG_GA_COLORMAP_ENTRIES 256 static int make_rgb_colormap(png_image_read_control *display) { unsigned int i, r; /* Build a 6x6x6 opaque RGB cube */ for (i=r=0; r<6; ++r) { unsigned int g; for (g=0; g<6; ++g) { unsigned int b; for (b=0; b<6; ++b) png_create_colormap_entry(display, i++, r*51, g*51, b*51, 255, E_sRGB); } } return i; } #define PNG_RGB_COLORMAP_ENTRIES 216 /* Return a palette index to the above palette given three 8-bit sRGB values. */ #define PNG_RGB_INDEX(r,g,b) \ ((png_byte)(6 * (6 * PNG_DIV51(r) + PNG_DIV51(g)) + PNG_DIV51(b))) static int png_image_read_colormap(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); const png_imagep image = display->image; const png_structrp png_ptr = image->opaque->png_ptr; const png_uint_32 output_format = image->format; const int output_encoding = (output_format & PNG_FORMAT_FLAG_LINEAR) ? E_LINEAR : E_sRGB; unsigned int cmap_entries; unsigned int output_processing; /* Output processing option */ unsigned int data_encoding = E_NOTSET; /* Encoding libpng must produce */ /* Background information; the background color and the index of this color * in the color-map if it exists (else 256). */ unsigned int background_index = 256; png_uint_32 back_r, back_g, back_b; /* Flags to accumulate things that need to be done to the input. */ int expand_tRNS = 0; /* Exclude the NYI feature of compositing onto a color-mapped buffer; it is * very difficult to do, the results look awful, and it is difficult to see * what possible use it is because the application can't control the * color-map. */ if (((png_ptr->color_type & PNG_COLOR_MASK_ALPHA) != 0 || png_ptr->num_trans > 0) /* alpha in input */ && ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) /* no alpha in output */) { if (output_encoding == E_LINEAR) /* compose on black */ back_b = back_g = back_r = 0; else if (display->background == NULL /* no way to remove it */) png_error(png_ptr, "a background color must be supplied to remove alpha/transparency"); /* Get a copy of the background color (this avoids repeating the checks * below.) The encoding is 8-bit sRGB or 16-bit linear, depending on the * output format. */ else { back_g = display->background->green; if (output_format & PNG_FORMAT_FLAG_COLOR) { back_r = display->background->red; back_b = display->background->blue; } else back_b = back_r = back_g; } } else if (output_encoding == E_LINEAR) back_b = back_r = back_g = 65535; else back_b = back_r = back_g = 255; /* Default the input file gamma if required - this is necessary because * libpng assumes that if no gamma information is present the data is in the * output format, but the simplified API deduces the gamma from the input * format. */ if ((png_ptr->colorspace.flags & PNG_COLORSPACE_HAVE_GAMMA) == 0) { /* Do this directly, not using the png_colorspace functions, to ensure * that it happens even if the colorspace is invalid (though probably if * it is the setting will be ignored) Note that the same thing can be * achieved at the application interface with png_set_gAMA. */ if (png_ptr->bit_depth == 16 && (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0) png_ptr->colorspace.gamma = PNG_GAMMA_LINEAR; else png_ptr->colorspace.gamma = PNG_GAMMA_sRGB_INVERSE; png_ptr->colorspace.flags |= PNG_COLORSPACE_HAVE_GAMMA; } /* Decide what to do based on the PNG color type of the input data. The * utility function png_create_colormap_entry deals with most aspects of the * output transformations; this code works out how to produce bytes of * color-map entries from the original format. */ switch (png_ptr->color_type) { case PNG_COLOR_TYPE_GRAY: if (png_ptr->bit_depth <= 8) { /* There at most 256 colors in the output, regardless of * transparency. */ unsigned int step, i, val, trans = 256/*ignore*/, back_alpha = 0; cmap_entries = 1U << png_ptr->bit_depth; if (cmap_entries > image->colormap_entries) png_error(png_ptr, "gray[8] color-map: too few entries"); step = 255 / (cmap_entries - 1); output_processing = PNG_CMAP_NONE; /* If there is a tRNS chunk then this either selects a transparent * value or, if the output has no alpha, the background color. */ if (png_ptr->num_trans > 0) { trans = png_ptr->trans_color.gray; if ((output_format & PNG_FORMAT_FLAG_ALPHA) == 0) back_alpha = output_encoding == E_LINEAR ? 65535 : 255; } /* png_create_colormap_entry just takes an RGBA and writes the * corresponding color-map entry using the format from 'image', * including the required conversion to sRGB or linear as * appropriate. The input values are always either sRGB (if the * gamma correction flag is 0) or 0..255 scaled file encoded values * (if the function must gamma correct them). */ for (i=val=0; i<cmap_entries; ++i, val += step) { /* 'i' is a file value. While this will result in duplicated * entries for 8-bit non-sRGB encoded files it is necessary to * have non-gamma corrected values to do tRNS handling. */ if (i != trans) png_create_colormap_entry(display, i, val, val, val, 255, E_FILE/*8-bit with file gamma*/); /* Else this entry is transparent. The colors don't matter if * there is an alpha channel (back_alpha == 0), but it does no * harm to pass them in; the values are not set above so this * passes in white. * * NOTE: this preserves the full precision of the application * supplied background color when it is used. */ else png_create_colormap_entry(display, i, back_r, back_g, back_b, back_alpha, output_encoding); } /* We need libpng to preserve the original encoding. */ data_encoding = E_FILE; /* The rows from libpng, while technically gray values, are now also * color-map indicies; however, they may need to be expanded to 1 * byte per pixel. This is what png_set_packing does (i.e., it * unpacks the bit values into bytes.) */ if (png_ptr->bit_depth < 8) png_set_packing(png_ptr); } else /* bit depth is 16 */ { /* The 16-bit input values can be converted directly to 8-bit gamma * encoded values; however, if a tRNS chunk is present 257 color-map * entries are required. This means that the extra entry requires * special processing; add an alpha channel, sacrifice gray level * 254 and convert transparent (alpha==0) entries to that. * * Use libpng to chop the data to 8 bits. Convert it to sRGB at the * same time to minimize quality loss. If a tRNS chunk is present * this means libpng must handle it too; otherwise it is impossible * to do the exact match on the 16-bit value. * * If the output has no alpha channel *and* the background color is * gray then it is possible to let libpng handle the substitution by * ensuring that the corresponding gray level matches the background * color exactly. */ data_encoding = E_sRGB; if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "gray[16] color-map: too few entries"); cmap_entries = make_gray_colormap(display); if (png_ptr->num_trans > 0) { unsigned int back_alpha; if (output_format & PNG_FORMAT_FLAG_ALPHA) back_alpha = 0; else { if (back_r == back_g && back_g == back_b) { /* Background is gray; no special processing will be * required. */ png_color_16 c; png_uint_32 gray = back_g; if (output_encoding == E_LINEAR) { gray = PNG_sRGB_FROM_LINEAR(gray * 255); /* And make sure the corresponding palette entry * matches. */ png_create_colormap_entry(display, gray, back_g, back_g, back_g, 65535, E_LINEAR); } /* The background passed to libpng, however, must be the * sRGB value. */ c.index = 0; /*unused*/ c.gray = c.red = c.green = c.blue = (png_uint_16)gray; /* NOTE: does this work without expanding tRNS to alpha? * It should be the color->gray case below apparently * doesn't. */ png_set_background_fixed(png_ptr, &c, PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/, 0/*gamma: not used*/); output_processing = PNG_CMAP_NONE; break; } back_alpha = output_encoding == E_LINEAR ? 65535 : 255; } /* output_processing means that the libpng-processed row will be * 8-bit GA and it has to be processing to single byte color-map * values. Entry 254 is replaced by either a completely * transparent entry or by the background color at full * precision (and the background color is not a simple gray leve * in this case.) */ expand_tRNS = 1; output_processing = PNG_CMAP_TRANS; background_index = 254; /* And set (overwrite) color-map entry 254 to the actual * background color at full precision. */ png_create_colormap_entry(display, 254, back_r, back_g, back_b, back_alpha, output_encoding); } else output_processing = PNG_CMAP_NONE; } break; case PNG_COLOR_TYPE_GRAY_ALPHA: /* 8-bit or 16-bit PNG with two channels - gray and alpha. A minimum * of 65536 combinations. If, however, the alpha channel is to be * removed there are only 256 possibilities if the background is gray. * (Otherwise there is a subset of the 65536 possibilities defined by * the triangle between black, white and the background color.) * * Reduce 16-bit files to 8-bit and sRGB encode the result. No need to * worry about tRNS matching - tRNS is ignored if there is an alpha * channel. */ data_encoding = E_sRGB; if (output_format & PNG_FORMAT_FLAG_ALPHA) { if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "gray+alpha color-map: too few entries"); cmap_entries = make_ga_colormap(display); background_index = PNG_CMAP_GA_BACKGROUND; output_processing = PNG_CMAP_GA; } else /* alpha is removed */ { /* Alpha must be removed as the PNG data is processed when the * background is a color because the G and A channels are * independent and the vector addition (non-parallel vectors) is a * 2-D problem. * * This can be reduced to the same algorithm as above by making a * colormap containing gray levels (for the opaque grays), a * background entry (for a transparent pixel) and a set of four six * level color values, one set for each intermediate alpha value. * See the comments in make_ga_colormap for how this works in the * per-pixel processing. * * If the background is gray, however, we only need a 256 entry gray * level color map. It is sufficient to make the entry generated * for the background color be exactly the color specified. */ if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0 || (back_r == back_g && back_g == back_b)) { /* Background is gray; no special processing will be required. */ png_color_16 c; png_uint_32 gray = back_g; if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "gray-alpha color-map: too few entries"); cmap_entries = make_gray_colormap(display); if (output_encoding == E_LINEAR) { gray = PNG_sRGB_FROM_LINEAR(gray * 255); /* And make sure the corresponding palette entry matches. */ png_create_colormap_entry(display, gray, back_g, back_g, back_g, 65535, E_LINEAR); } /* The background passed to libpng, however, must be the sRGB * value. */ c.index = 0; /*unused*/ c.gray = c.red = c.green = c.blue = (png_uint_16)gray; png_set_background_fixed(png_ptr, &c, PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/, 0/*gamma: not used*/); output_processing = PNG_CMAP_NONE; } else { png_uint_32 i, a; /* This is the same as png_make_ga_colormap, above, except that * the entries are all opaque. */ if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "ga-alpha color-map: too few entries"); i = 0; while (i < 231) { png_uint_32 gray = (i * 256 + 115) / 231; png_create_colormap_entry(display, i++, gray, gray, gray, 255, E_sRGB); } /* NOTE: this preserves the full precision of the application * background color. */ background_index = i; png_create_colormap_entry(display, i++, back_r, back_g, back_b, output_encoding == E_LINEAR ? 65535U : 255U, output_encoding); /* For non-opaque input composite on the sRGB background - this * requires inverting the encoding for each component. The input * is still converted to the sRGB encoding because this is a * reasonable approximate to the logarithmic curve of human * visual sensitivity, at least over the narrow range which PNG * represents. Consequently 'G' is always sRGB encoded, while * 'A' is linear. We need the linear background colors. */ if (output_encoding == E_sRGB) /* else already linear */ { /* This may produce a value not exactly matching the * background, but that's ok because these numbers are only * used when alpha != 0 */ back_r = png_sRGB_table[back_r]; back_g = png_sRGB_table[back_g]; back_b = png_sRGB_table[back_b]; } for (a=1; a<5; ++a) { unsigned int g; /* PNG_sRGB_FROM_LINEAR expects a 16-bit linear value scaled * by an 8-bit alpha value (0..255). */ png_uint_32 alpha = 51 * a; png_uint_32 back_rx = (255-alpha) * back_r; png_uint_32 back_gx = (255-alpha) * back_g; png_uint_32 back_bx = (255-alpha) * back_b; for (g=0; g<6; ++g) { png_uint_32 gray = png_sRGB_table[g*51] * alpha; png_create_colormap_entry(display, i++, PNG_sRGB_FROM_LINEAR(gray + back_rx), PNG_sRGB_FROM_LINEAR(gray + back_gx), PNG_sRGB_FROM_LINEAR(gray + back_bx), 255, E_sRGB); } } cmap_entries = i; output_processing = PNG_CMAP_GA; } } break; case PNG_COLOR_TYPE_RGB: case PNG_COLOR_TYPE_RGB_ALPHA: /* Exclude the case where the output is gray; we can always handle this * with the cases above. */ if ((output_format & PNG_FORMAT_FLAG_COLOR) == 0) { /* The color-map will be grayscale, so we may as well convert the * input RGB values to a simple grayscale and use the grayscale * code above. * * NOTE: calling this apparently damages the recognition of the * transparent color in background color handling; call * png_set_tRNS_to_alpha before png_set_background_fixed. */ png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, -1, -1); data_encoding = E_sRGB; /* The output will now be one or two 8-bit gray or gray+alpha * channels. The more complex case arises when the input has alpha. */ if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_ptr->num_trans > 0) && (output_format & PNG_FORMAT_FLAG_ALPHA) != 0) { /* Both input and output have an alpha channel, so no background * processing is required; just map the GA bytes to the right * color-map entry. */ expand_tRNS = 1; if (PNG_GA_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "rgb[ga] color-map: too few entries"); cmap_entries = make_ga_colormap(display); background_index = PNG_CMAP_GA_BACKGROUND; output_processing = PNG_CMAP_GA; } else { /* Either the input or the output has no alpha channel, so there * will be no non-opaque pixels in the color-map; it will just be * grayscale. */ if (PNG_GRAY_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "rgb[gray] color-map: too few entries"); /* Ideally this code would use libpng to do the gamma correction, * but if an input alpha channel is to be removed we will hit the * libpng bug in gamma+compose+rgb-to-gray (the double gamma * correction bug). Fix this by dropping the gamma correction in * this case and doing it in the palette; this will result in * duplicate palette entries, but that's better than the * alternative of double gamma correction. */ if ((png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_ptr->num_trans > 0) && png_gamma_not_sRGB(png_ptr->colorspace.gamma)) { cmap_entries = make_gray_file_colormap(display); data_encoding = E_FILE; } else cmap_entries = make_gray_colormap(display); /* But if the input has alpha or transparency it must be removed */ if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_ptr->num_trans > 0) { png_color_16 c; png_uint_32 gray = back_g; /* We need to ensure that the application background exists in * the colormap and that completely transparent pixels map to * it. Achieve this simply by ensuring that the entry * selected for the background really is the background color. */ if (data_encoding == E_FILE) /* from the fixup above */ { /* The app supplied a gray which is in output_encoding, we * need to convert it to a value of the input (E_FILE) * encoding then set this palette entry to the required * output encoding. */ if (output_encoding == E_sRGB) gray = png_sRGB_table[gray]; /* now E_LINEAR */ gray = PNG_DIV257(png_gamma_16bit_correct(gray, png_ptr->colorspace.gamma)); /* now E_FILE */ /* And make sure the corresponding palette entry contains * exactly the required sRGB value. */ png_create_colormap_entry(display, gray, back_g, back_g, back_g, 0/*unused*/, output_encoding); } else if (output_encoding == E_LINEAR) { gray = PNG_sRGB_FROM_LINEAR(gray * 255); /* And make sure the corresponding palette entry matches. */ png_create_colormap_entry(display, gray, back_g, back_g, back_g, 0/*unused*/, E_LINEAR); } /* The background passed to libpng, however, must be the * output (normally sRGB) value. */ c.index = 0; /*unused*/ c.gray = c.red = c.green = c.blue = (png_uint_16)gray; /* NOTE: the following is apparently a bug in libpng. Without * it the transparent color recognition in * png_set_background_fixed seems to go wrong. */ expand_tRNS = 1; png_set_background_fixed(png_ptr, &c, PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/, 0/*gamma: not used*/); } output_processing = PNG_CMAP_NONE; } } else /* output is color */ { /* We could use png_quantize here so long as there is no transparent * color or alpha; png_quantize ignores alpha. Easier overall just * to do it once and using PNG_DIV51 on the 6x6x6 reduced RGB cube. * Consequently we always want libpng to produce sRGB data. */ data_encoding = E_sRGB; /* Is there any transparency or alpha? */ if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA || png_ptr->num_trans > 0) { /* Is there alpha in the output too? If so all four channels are * processed into a special RGB cube with alpha support. */ if (output_format & PNG_FORMAT_FLAG_ALPHA) { png_uint_32 r; if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries) png_error(png_ptr, "rgb+alpha color-map: too few entries"); cmap_entries = make_rgb_colormap(display); /* Add a transparent entry. */ png_create_colormap_entry(display, cmap_entries, 255, 255, 255, 0, E_sRGB); /* This is stored as the background index for the processing * algorithm. */ background_index = cmap_entries++; /* Add 27 r,g,b entries each with alpha 0.5. */ for (r=0; r<256; r = (r << 1) | 0x7f) { png_uint_32 g; for (g=0; g<256; g = (g << 1) | 0x7f) { png_uint_32 b; /* This generates components with the values 0, 127 and * 255 */ for (b=0; b<256; b = (b << 1) | 0x7f) png_create_colormap_entry(display, cmap_entries++, r, g, b, 128, E_sRGB); } } expand_tRNS = 1; output_processing = PNG_CMAP_RGB_ALPHA; } else { /* Alpha/transparency must be removed. The background must * exist in the color map (achieved by setting adding it after * the 666 color-map). If the standard processing code will * pick up this entry automatically that's all that is * required; libpng can be called to do the background * processing. */ unsigned int sample_size = PNG_IMAGE_SAMPLE_SIZE(output_format); png_uint_32 r, g, b; /* sRGB background */ if (PNG_RGB_COLORMAP_ENTRIES+1+27 > image->colormap_entries) png_error(png_ptr, "rgb-alpha color-map: too few entries"); cmap_entries = make_rgb_colormap(display); png_create_colormap_entry(display, cmap_entries, back_r, back_g, back_b, 0/*unused*/, output_encoding); if (output_encoding == E_LINEAR) { r = PNG_sRGB_FROM_LINEAR(back_r * 255); g = PNG_sRGB_FROM_LINEAR(back_g * 255); b = PNG_sRGB_FROM_LINEAR(back_b * 255); } else { r = back_r; g = back_g; b = back_g; } /* Compare the newly-created color-map entry with the one the * PNG_CMAP_RGB algorithm will use. If the two entries don't * match, add the new one and set this as the background * index. */ if (memcmp((png_const_bytep)display->colormap + sample_size * cmap_entries, (png_const_bytep)display->colormap + sample_size * PNG_RGB_INDEX(r,g,b), sample_size) != 0) { /* The background color must be added. */ background_index = cmap_entries++; /* Add 27 r,g,b entries each with created by composing with * the background at alpha 0.5. */ for (r=0; r<256; r = (r << 1) | 0x7f) { for (g=0; g<256; g = (g << 1) | 0x7f) { /* This generates components with the values 0, 127 * and 255 */ for (b=0; b<256; b = (b << 1) | 0x7f) png_create_colormap_entry(display, cmap_entries++, png_colormap_compose(display, r, E_sRGB, 128, back_r, output_encoding), png_colormap_compose(display, g, E_sRGB, 128, back_g, output_encoding), png_colormap_compose(display, b, E_sRGB, 128, back_b, output_encoding), 0/*unused*/, output_encoding); } } expand_tRNS = 1; output_processing = PNG_CMAP_RGB_ALPHA; } else /* background color is in the standard color-map */ { png_color_16 c; c.index = 0; /*unused*/ c.red = (png_uint_16)back_r; c.gray = c.green = (png_uint_16)back_g; c.blue = (png_uint_16)back_b; png_set_background_fixed(png_ptr, &c, PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/, 0/*gamma: not used*/); output_processing = PNG_CMAP_RGB; } } } else /* no alpha or transparency in the input */ { /* Alpha in the output is irrelevant, simply map the opaque input * pixels to the 6x6x6 color-map. */ if (PNG_RGB_COLORMAP_ENTRIES > image->colormap_entries) png_error(png_ptr, "rgb color-map: too few entries"); cmap_entries = make_rgb_colormap(display); output_processing = PNG_CMAP_RGB; } } break; case PNG_COLOR_TYPE_PALETTE: /* It's already got a color-map. It may be necessary to eliminate the * tRNS entries though. */ { unsigned int num_trans = png_ptr->num_trans; png_const_bytep trans = num_trans > 0 ? png_ptr->trans_alpha : NULL; png_const_colorp colormap = png_ptr->palette; const int do_background = trans != NULL && (output_format & PNG_FORMAT_FLAG_ALPHA) == 0; unsigned int i; /* Just in case: */ if (trans == NULL) num_trans = 0; output_processing = PNG_CMAP_NONE; data_encoding = E_FILE; /* Don't change from color-map indicies */ cmap_entries = png_ptr->num_palette; if (cmap_entries > 256) cmap_entries = 256; if (cmap_entries > image->colormap_entries) png_error(png_ptr, "palette color-map: too few entries"); for (i=0; i < cmap_entries; ++i) { if (do_background && i < num_trans && trans[i] < 255) { if (trans[i] == 0) png_create_colormap_entry(display, i, back_r, back_g, back_b, 0, output_encoding); else { /* Must compose the PNG file color in the color-map entry * on the sRGB color in 'back'. */ png_create_colormap_entry(display, i, png_colormap_compose(display, colormap[i].red, E_FILE, trans[i], back_r, output_encoding), png_colormap_compose(display, colormap[i].green, E_FILE, trans[i], back_g, output_encoding), png_colormap_compose(display, colormap[i].blue, E_FILE, trans[i], back_b, output_encoding), output_encoding == E_LINEAR ? trans[i] * 257U : trans[i], output_encoding); } } else png_create_colormap_entry(display, i, colormap[i].red, colormap[i].green, colormap[i].blue, i < num_trans ? trans[i] : 255U, E_FILE/*8-bit*/); } /* The PNG data may have indicies packed in fewer than 8 bits, it * must be expanded if so. */ if (png_ptr->bit_depth < 8) png_set_packing(png_ptr); } break; default: png_error(png_ptr, "invalid PNG color type"); /*NOT REACHED*/ break; } /* Now deal with the output processing */ if (expand_tRNS && png_ptr->num_trans > 0 && (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) == 0) png_set_tRNS_to_alpha(png_ptr); switch (data_encoding) { default: png_error(png_ptr, "bad data option (internal error)"); break; case E_sRGB: /* Change to 8-bit sRGB */ png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, PNG_GAMMA_sRGB); /* FALL THROUGH */ case E_FILE: if (png_ptr->bit_depth > 8) png_set_scale_16(png_ptr); break; } if (cmap_entries > 256 || cmap_entries > image->colormap_entries) png_error(png_ptr, "color map overflow (BAD internal error)"); image->colormap_entries = cmap_entries; /* Double check using the recorded background index */ switch (output_processing) { case PNG_CMAP_NONE: if (background_index != PNG_CMAP_NONE_BACKGROUND) goto bad_background; break; case PNG_CMAP_GA: if (background_index != PNG_CMAP_GA_BACKGROUND) goto bad_background; break; case PNG_CMAP_TRANS: if (background_index >= cmap_entries || background_index != PNG_CMAP_TRANS_BACKGROUND) goto bad_background; break; case PNG_CMAP_RGB: if (background_index != PNG_CMAP_RGB_BACKGROUND) goto bad_background; break; case PNG_CMAP_RGB_ALPHA: if (background_index != PNG_CMAP_RGB_ALPHA_BACKGROUND) goto bad_background; break; default: png_error(png_ptr, "bad processing option (internal error)"); bad_background: png_error(png_ptr, "bad background index (internal error)"); } display->colormap_processing = output_processing; return 1/*ok*/; } /* The final part of the color-map read called from png_image_finish_read. */ static int png_image_read_and_map(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); png_imagep image = display->image; png_structrp png_ptr = image->opaque->png_ptr; int passes; /* Called when the libpng data must be transformed into the color-mapped * form. There is a local row buffer in display->local and this routine must * do the interlace handling. */ switch (png_ptr->interlaced) { case PNG_INTERLACE_NONE: passes = 1; break; case PNG_INTERLACE_ADAM7: passes = PNG_INTERLACE_ADAM7_PASSES; break; default: passes = 0; png_error(png_ptr, "unknown interlace type"); } { png_uint_32 height = image->height; png_uint_32 width = image->width; int proc = display->colormap_processing; png_bytep first_row = png_voidcast(png_bytep, display->first_row); ptrdiff_t step_row = display->row_bytes; int pass; for (pass = 0; pass < passes; ++pass) { unsigned int startx, stepx, stepy; png_uint_32 y; if (png_ptr->interlaced == PNG_INTERLACE_ADAM7) { /* The row may be empty for a short image: */ if (PNG_PASS_COLS(width, pass) == 0) continue; startx = PNG_PASS_START_COL(pass); stepx = PNG_PASS_COL_OFFSET(pass); y = PNG_PASS_START_ROW(pass); stepy = PNG_PASS_ROW_OFFSET(pass); } else { y = 0; startx = 0; stepx = stepy = 1; } for (; y<height; y += stepy) { png_bytep inrow = png_voidcast(png_bytep, display->local_row); png_bytep outrow = first_row + y * step_row; png_const_bytep end_row = outrow + width; /* Read read the libpng data into the temporary buffer. */ png_read_row(png_ptr, inrow, NULL); /* Now process the row according to the processing option, note * that the caller verifies that the format of the libpng output * data is as required. */ outrow += startx; switch (proc) { case PNG_CMAP_GA: for (; outrow < end_row; outrow += stepx) { /* The data is always in the PNG order */ unsigned int gray = *inrow++; unsigned int alpha = *inrow++; unsigned int entry; /* NOTE: this code is copied as a comment in * make_ga_colormap above. Please update the * comment if you change this code! */ if (alpha > 229) /* opaque */ { entry = (231 * gray + 128) >> 8; } else if (alpha < 26) /* transparent */ { entry = 231; } else /* partially opaque */ { entry = 226 + 6 * PNG_DIV51(alpha) + PNG_DIV51(gray); } *outrow = (png_byte)entry; } break; case PNG_CMAP_TRANS: for (; outrow < end_row; outrow += stepx) { png_byte gray = *inrow++; png_byte alpha = *inrow++; if (alpha == 0) *outrow = PNG_CMAP_TRANS_BACKGROUND; else if (gray != PNG_CMAP_TRANS_BACKGROUND) *outrow = gray; else *outrow = (png_byte)(PNG_CMAP_TRANS_BACKGROUND+1); } break; case PNG_CMAP_RGB: for (; outrow < end_row; outrow += stepx) { *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]); inrow += 3; } break; case PNG_CMAP_RGB_ALPHA: for (; outrow < end_row; outrow += stepx) { unsigned int alpha = inrow[3]; /* Because the alpha entries only hold alpha==0.5 values * split the processing at alpha==0.25 (64) and 0.75 * (196). */ if (alpha >= 196) *outrow = PNG_RGB_INDEX(inrow[0], inrow[1], inrow[2]); else if (alpha < 64) *outrow = PNG_CMAP_RGB_ALPHA_BACKGROUND; else { /* Likewise there are three entries for each of r, g * and b. We could select the entry by popcount on * the top two bits on those architectures that * support it, this is what the code below does, * crudely. */ unsigned int back_i = PNG_CMAP_RGB_ALPHA_BACKGROUND+1; /* Here are how the values map: * * 0x00 .. 0x3f -> 0 * 0x40 .. 0xbf -> 1 * 0xc0 .. 0xff -> 2 * * So, as above with the explicit alpha checks, the * breakpoints are at 64 and 196. */ if (inrow[0] & 0x80) back_i += 9; /* red */ if (inrow[0] & 0x40) back_i += 9; if (inrow[0] & 0x80) back_i += 3; /* green */ if (inrow[0] & 0x40) back_i += 3; if (inrow[0] & 0x80) back_i += 1; /* blue */ if (inrow[0] & 0x40) back_i += 1; *outrow = (png_byte)back_i; } inrow += 4; } break; default: break; } } } } return 1; } static int png_image_read_colormapped(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); png_imagep image = display->image; png_controlp control = image->opaque; png_structrp png_ptr = control->png_ptr; png_inforp info_ptr = control->info_ptr; int passes = 0; /* As a flag */ PNG_SKIP_CHUNKS(png_ptr); /* Update the 'info' structure and make sure the result is as required; first * make sure to turn on the interlace handling if it will be required * (because it can't be turned on *after* the call to png_read_update_info!) */ if (display->colormap_processing == PNG_CMAP_NONE) passes = png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); /* The expected output can be deduced from the colormap_processing option. */ switch (display->colormap_processing) { case PNG_CMAP_NONE: /* Output must be one channel and one byte per pixel, the output * encoding can be anything. */ if ((info_ptr->color_type == PNG_COLOR_TYPE_PALETTE || info_ptr->color_type == PNG_COLOR_TYPE_GRAY) && info_ptr->bit_depth == 8) break; goto bad_output; case PNG_CMAP_TRANS: case PNG_CMAP_GA: /* Output must be two channels and the 'G' one must be sRGB, the latter * can be checked with an exact number because it should have been set * to this number above! */ if (info_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA && info_ptr->bit_depth == 8 && png_ptr->screen_gamma == PNG_GAMMA_sRGB && image->colormap_entries == 256) break; goto bad_output; case PNG_CMAP_RGB: /* Output must be 8-bit sRGB encoded RGB */ if (info_ptr->color_type == PNG_COLOR_TYPE_RGB && info_ptr->bit_depth == 8 && png_ptr->screen_gamma == PNG_GAMMA_sRGB && image->colormap_entries == 216) break; goto bad_output; case PNG_CMAP_RGB_ALPHA: /* Output must be 8-bit sRGB encoded RGBA */ if (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA && info_ptr->bit_depth == 8 && png_ptr->screen_gamma == PNG_GAMMA_sRGB && image->colormap_entries == 244 /* 216 + 1 + 27 */) break; /* goto bad_output; */ /* FALL THROUGH */ default: bad_output: png_error(png_ptr, "bad color-map processing (internal error)"); } /* Now read the rows. Do this here if it is possible to read directly into * the output buffer, otherwise allocate a local row buffer of the maximum * size libpng requires and call the relevant processing routine safely. */ { png_voidp first_row = display->buffer; ptrdiff_t row_bytes = display->row_stride; /* The following expression is designed to work correctly whether it gives * a signed or an unsigned result. */ if (row_bytes < 0) { char *ptr = png_voidcast(char*, first_row); ptr += (image->height-1) * (-row_bytes); first_row = png_voidcast(png_voidp, ptr); } display->first_row = first_row; display->row_bytes = row_bytes; } if (passes == 0) { int result; png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); display->local_row = row; result = png_safe_execute(image, png_image_read_and_map, display); display->local_row = NULL; png_free(png_ptr, row); return result; } else { png_alloc_size_t row_bytes = display->row_bytes; while (--passes >= 0) { png_uint_32 y = image->height; png_bytep row = png_voidcast(png_bytep, display->first_row); while (y-- > 0) { png_read_row(png_ptr, row, NULL); row += row_bytes; } } return 1; } } /* Just the row reading part of png_image_read. */ static int png_image_read_composite(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); png_imagep image = display->image; png_structrp png_ptr = image->opaque->png_ptr; int passes; switch (png_ptr->interlaced) { case PNG_INTERLACE_NONE: passes = 1; break; case PNG_INTERLACE_ADAM7: passes = PNG_INTERLACE_ADAM7_PASSES; break; default: passes = 0; png_error(png_ptr, "unknown interlace type"); } { png_uint_32 height = image->height; png_uint_32 width = image->width; ptrdiff_t step_row = display->row_bytes; unsigned int channels = (image->format & PNG_FORMAT_FLAG_COLOR) ? 3 : 1; int pass; for (pass = 0; pass < passes; ++pass) { unsigned int startx, stepx, stepy; png_uint_32 y; if (png_ptr->interlaced == PNG_INTERLACE_ADAM7) { /* The row may be empty for a short image: */ if (PNG_PASS_COLS(width, pass) == 0) continue; startx = PNG_PASS_START_COL(pass) * channels; stepx = PNG_PASS_COL_OFFSET(pass) * channels; y = PNG_PASS_START_ROW(pass); stepy = PNG_PASS_ROW_OFFSET(pass); } else { y = 0; startx = 0; stepx = channels; stepy = 1; } for (; y<height; y += stepy) { png_bytep inrow = png_voidcast(png_bytep, display->local_row); png_bytep outrow; png_const_bytep end_row; /* Read the row, which is packed: */ png_read_row(png_ptr, inrow, NULL); outrow = png_voidcast(png_bytep, display->first_row); outrow += y * step_row; end_row = outrow + width * channels; /* Now do the composition on each pixel in this row. */ outrow += startx; for (; outrow < end_row; outrow += stepx) { png_byte alpha = inrow[channels]; if (alpha > 0) /* else no change to the output */ { unsigned int c; for (c=0; c<channels; ++c) { png_uint_32 component = inrow[c]; if (alpha < 255) /* else just use component */ { /* This is PNG_OPTIMIZED_ALPHA, the component value * is a linear 8-bit value. Combine this with the * current outrow[c] value which is sRGB encoded. * Arithmetic here is 16-bits to preserve the output * values correctly. */ component *= 257*255; /* =65535 */ component += (255-alpha)*png_sRGB_table[outrow[c]]; /* So 'component' is scaled by 255*65535 and is * therefore appropriate for the sRGB to linear * conversion table. */ component = PNG_sRGB_FROM_LINEAR(component); } outrow[c] = (png_byte)component; } } inrow += channels+1; /* components and alpha channel */ } } } } return 1; } /* The do_local_background case; called when all the following transforms are to * be done: * * PNG_RGB_TO_GRAY * PNG_COMPOSITE * PNG_GAMMA * * This is a work-round for the fact that both the PNG_RGB_TO_GRAY and * PNG_COMPOSITE code performs gamma correction, so we get double gamma * correction. The fix-up is to prevent the PNG_COMPOSITE operation happening * inside libpng, so this routine sees an 8 or 16-bit gray+alpha row and handles * the removal or pre-multiplication of the alpha channel. */ static int png_image_read_background(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); png_imagep image = display->image; png_structrp png_ptr = image->opaque->png_ptr; png_inforp info_ptr = image->opaque->info_ptr; png_uint_32 height = image->height; png_uint_32 width = image->width; int pass, passes; /* Double check the convoluted logic below. We expect to get here with * libpng doing rgb to gray and gamma correction but background processing * left to the png_image_read_background function. The rows libpng produce * might be 8 or 16-bit but should always have two channels; gray plus alpha. */ if ((png_ptr->transformations & PNG_RGB_TO_GRAY) == 0) png_error(png_ptr, "lost rgb to gray"); if ((png_ptr->transformations & PNG_COMPOSE) != 0) png_error(png_ptr, "unexpected compose"); if (png_get_channels(png_ptr, info_ptr) != 2) png_error(png_ptr, "lost/gained channels"); /* Expect the 8-bit case to always remove the alpha channel */ if ((image->format & PNG_FORMAT_FLAG_LINEAR) == 0 && (image->format & PNG_FORMAT_FLAG_ALPHA) != 0) png_error(png_ptr, "unexpected 8-bit transformation"); switch (png_ptr->interlaced) { case PNG_INTERLACE_NONE: passes = 1; break; case PNG_INTERLACE_ADAM7: passes = PNG_INTERLACE_ADAM7_PASSES; break; default: passes = 0; png_error(png_ptr, "unknown interlace type"); } switch (png_get_bit_depth(png_ptr, info_ptr)) { default: png_error(png_ptr, "unexpected bit depth"); break; case 8: /* 8-bit sRGB gray values with an alpha channel; the alpha channel is * to be removed by composing on a backgroundi: either the row if * display->background is NULL or display->background->green if not. * Unlike the code above ALPHA_OPTIMIZED has *not* been done. */ { png_bytep first_row = png_voidcast(png_bytep, display->first_row); ptrdiff_t step_row = display->row_bytes; for (pass = 0; pass < passes; ++pass) { png_bytep row = png_voidcast(png_bytep, display->first_row); unsigned int startx, stepx, stepy; png_uint_32 y; if (png_ptr->interlaced == PNG_INTERLACE_ADAM7) { /* The row may be empty for a short image: */ if (PNG_PASS_COLS(width, pass) == 0) continue; startx = PNG_PASS_START_COL(pass); stepx = PNG_PASS_COL_OFFSET(pass); y = PNG_PASS_START_ROW(pass); stepy = PNG_PASS_ROW_OFFSET(pass); } else { y = 0; startx = 0; stepx = stepy = 1; } if (display->background == NULL) { for (; y<height; y += stepy) { png_bytep inrow = png_voidcast(png_bytep, display->local_row); png_bytep outrow = first_row + y * step_row; png_const_bytep end_row = outrow + width; /* Read the row, which is packed: */ png_read_row(png_ptr, inrow, NULL); /* Now do the composition on each pixel in this row. */ outrow += startx; for (; outrow < end_row; outrow += stepx) { png_byte alpha = inrow[1]; if (alpha > 0) /* else no change to the output */ { png_uint_32 component = inrow[0]; if (alpha < 255) /* else just use component */ { /* Since PNG_OPTIMIZED_ALPHA was not set it is * necessary to invert the sRGB transfer * function and multiply the alpha out. */ component = png_sRGB_table[component] * alpha; component += png_sRGB_table[outrow[0]] * (255-alpha); component = PNG_sRGB_FROM_LINEAR(component); } outrow[0] = (png_byte)component; } inrow += 2; /* gray and alpha channel */ } } } else /* constant background value */ { png_byte background8 = display->background->green; png_uint_16 background = png_sRGB_table[background8]; for (; y<height; y += stepy) { png_bytep inrow = png_voidcast(png_bytep, display->local_row); png_bytep outrow = first_row + y * step_row; png_const_bytep end_row = outrow + width; /* Read the row, which is packed: */ png_read_row(png_ptr, inrow, NULL); /* Now do the composition on each pixel in this row. */ outrow += startx; for (; outrow < end_row; outrow += stepx) { png_byte alpha = inrow[1]; if (alpha > 0) /* else use background */ { png_uint_32 component = inrow[0]; if (alpha < 255) /* else just use component */ { component = png_sRGB_table[component] * alpha; component += background * (255-alpha); component = PNG_sRGB_FROM_LINEAR(component); } outrow[0] = (png_byte)component; } else outrow[0] = background8; inrow += 2; /* gray and alpha channel */ } row += display->row_bytes; } } } } break; case 16: /* 16-bit linear with pre-multiplied alpha; the pre-multiplication must * still be done and, maybe, the alpha channel removed. This code also * handles the alpha-first option. */ { png_uint_16p first_row = png_voidcast(png_uint_16p, display->first_row); /* The division by two is safe because the caller passed in a * stride which was multiplied by 2 (below) to get row_bytes. */ ptrdiff_t step_row = display->row_bytes / 2; int preserve_alpha = (image->format & PNG_FORMAT_FLAG_ALPHA) != 0; unsigned int outchannels = 1+preserve_alpha; int swap_alpha = 0; if (preserve_alpha && (image->format & PNG_FORMAT_FLAG_AFIRST)) swap_alpha = 1; for (pass = 0; pass < passes; ++pass) { unsigned int startx, stepx, stepy; png_uint_32 y; /* The 'x' start and step are adjusted to output components here. */ if (png_ptr->interlaced == PNG_INTERLACE_ADAM7) { /* The row may be empty for a short image: */ if (PNG_PASS_COLS(width, pass) == 0) continue; startx = PNG_PASS_START_COL(pass) * outchannels; stepx = PNG_PASS_COL_OFFSET(pass) * outchannels; y = PNG_PASS_START_ROW(pass); stepy = PNG_PASS_ROW_OFFSET(pass); } else { y = 0; startx = 0; stepx = outchannels; stepy = 1; } for (; y<height; y += stepy) { png_const_uint_16p inrow; png_uint_16p outrow = first_row + y*step_row; png_uint_16p end_row = outrow + width * outchannels; /* Read the row, which is packed: */ png_read_row(png_ptr, png_voidcast(png_bytep, display->local_row), NULL); inrow = png_voidcast(png_const_uint_16p, display->local_row); /* Now do the pre-multiplication on each pixel in this row. */ outrow += startx; for (; outrow < end_row; outrow += stepx) { png_uint_32 component = inrow[0]; png_uint_16 alpha = inrow[1]; if (alpha > 0) /* else 0 */ { if (alpha < 65535) /* else just use component */ { component *= alpha; component += 32767; component /= 65535; } } else component = 0; outrow[swap_alpha] = (png_uint_16)component; if (preserve_alpha) outrow[1 ^ swap_alpha] = alpha; inrow += 2; /* components and alpha channel */ } } } } break; } return 1; } /* The guts of png_image_finish_read as a png_safe_execute callback. */ static int png_image_read_direct(png_voidp argument) { png_image_read_control *display = png_voidcast(png_image_read_control*, argument); png_imagep image = display->image; png_structrp png_ptr = image->opaque->png_ptr; png_inforp info_ptr = image->opaque->info_ptr; png_uint_32 format = image->format; int linear = (format & PNG_FORMAT_FLAG_LINEAR) != 0; int do_local_compose = 0; int do_local_background = 0; /* to avoid double gamma correction bug */ int passes = 0; /* Add transforms to ensure the correct output format is produced then check * that the required implementation support is there. Always expand; always * need 8 bits minimum, no palette and expanded tRNS. */ png_set_expand(png_ptr); /* Now check the format to see if it was modified. */ { png_uint_32 base_format = png_image_format(png_ptr) & ~PNG_FORMAT_FLAG_COLORMAP /* removed by png_set_expand */; png_uint_32 change = format ^ base_format; png_fixed_point output_gamma; int mode; /* alpha mode */ /* Do this first so that we have a record if rgb to gray is happening. */ if (change & PNG_FORMAT_FLAG_COLOR) { /* gray<->color transformation required. */ if (format & PNG_FORMAT_FLAG_COLOR) png_set_gray_to_rgb(png_ptr); else { /* libpng can't do both rgb to gray and * background/pre-multiplication if there is also significant gamma * correction, because both operations require linear colors and * the code only supports one transform doing the gamma correction. * Handle this by doing the pre-multiplication or background * operation in this code, if necessary. * * TODO: fix this by rewriting pngrtran.c (!) * * For the moment (given that fixing this in pngrtran.c is an * enormous change) 'do_local_background' is used to indicate that * the problem exists. */ if (base_format & PNG_FORMAT_FLAG_ALPHA) do_local_background = 1/*maybe*/; png_set_rgb_to_gray_fixed(png_ptr, PNG_ERROR_ACTION_NONE, PNG_RGB_TO_GRAY_DEFAULT, PNG_RGB_TO_GRAY_DEFAULT); } change &= ~PNG_FORMAT_FLAG_COLOR; } /* Set the gamma appropriately, linear for 16-bit input, sRGB otherwise. */ { png_fixed_point input_gamma_default; if ((base_format & PNG_FORMAT_FLAG_LINEAR) && (image->flags & PNG_IMAGE_FLAG_16BIT_sRGB) == 0) input_gamma_default = PNG_GAMMA_LINEAR; else input_gamma_default = PNG_DEFAULT_sRGB; /* Call png_set_alpha_mode to set the default for the input gamma; the * output gamma is set by a second call below. */ png_set_alpha_mode_fixed(png_ptr, PNG_ALPHA_PNG, input_gamma_default); } if (linear) { /* If there *is* an alpha channel in the input it must be multiplied * out; use PNG_ALPHA_STANDARD, otherwise just use PNG_ALPHA_PNG. */ if (base_format & PNG_FORMAT_FLAG_ALPHA) mode = PNG_ALPHA_STANDARD; /* associated alpha */ else mode = PNG_ALPHA_PNG; output_gamma = PNG_GAMMA_LINEAR; } else { mode = PNG_ALPHA_PNG; output_gamma = PNG_DEFAULT_sRGB; } /* If 'do_local_background' is set check for the presence of gamma * correction; this is part of the work-round for the libpng bug * described above. * * TODO: fix libpng and remove this. */ if (do_local_background) { png_fixed_point gtest; /* This is 'png_gamma_threshold' from pngrtran.c; the test used for * gamma correction, the screen gamma hasn't been set on png_struct * yet; it's set below. png_struct::gamma, however, is set to the * final value. */ if (png_muldiv(&gtest, output_gamma, png_ptr->colorspace.gamma, PNG_FP_1) && !png_gamma_significant(gtest)) do_local_background = 0; else if (mode == PNG_ALPHA_STANDARD) { do_local_background = 2/*required*/; mode = PNG_ALPHA_PNG; /* prevent libpng doing it */ } /* else leave as 1 for the checks below */ } /* If the bit-depth changes then handle that here. */ if (change & PNG_FORMAT_FLAG_LINEAR) { if (linear /*16-bit output*/) png_set_expand_16(png_ptr); else /* 8-bit output */ png_set_scale_16(png_ptr); change &= ~PNG_FORMAT_FLAG_LINEAR; } /* Now the background/alpha channel changes. */ if (change & PNG_FORMAT_FLAG_ALPHA) { /* Removing an alpha channel requires composition for the 8-bit * formats; for the 16-bit it is already done, above, by the * pre-multiplication and the channel just needs to be stripped. */ if (base_format & PNG_FORMAT_FLAG_ALPHA) { /* If RGB->gray is happening the alpha channel must be left and the * operation completed locally. * * TODO: fix libpng and remove this. */ if (do_local_background) do_local_background = 2/*required*/; /* 16-bit output: just remove the channel */ else if (linear) /* compose on black (well, pre-multiply) */ png_set_strip_alpha(png_ptr); /* 8-bit output: do an appropriate compose */ else if (display->background != NULL) { png_color_16 c; c.index = 0; /*unused*/ c.red = display->background->red; c.green = display->background->green; c.blue = display->background->blue; c.gray = display->background->green; /* This is always an 8-bit sRGB value, using the 'green' channel * for gray is much better than calculating the luminance here; * we can get off-by-one errors in that calculation relative to * the app expectations and that will show up in transparent * pixels. */ png_set_background_fixed(png_ptr, &c, PNG_BACKGROUND_GAMMA_SCREEN, 0/*need_expand*/, 0/*gamma: not used*/); } else /* compose on row: implemented below. */ { do_local_compose = 1; /* This leaves the alpha channel in the output, so it has to be * removed by the code below. Set the encoding to the 'OPTIMIZE' * one so the code only has to hack on the pixels that require * composition. */ mode = PNG_ALPHA_OPTIMIZED; } } else /* output needs an alpha channel */ { /* This is tricky because it happens before the swap operation has * been accomplished; however, the swap does *not* swap the added * alpha channel (weird API), so it must be added in the correct * place. */ png_uint_32 filler; /* opaque filler */ int where; if (linear) filler = 65535; else filler = 255; # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (format & PNG_FORMAT_FLAG_AFIRST) { where = PNG_FILLER_BEFORE; change &= ~PNG_FORMAT_FLAG_AFIRST; } else # endif where = PNG_FILLER_AFTER; png_set_add_alpha(png_ptr, filler, where); } /* This stops the (irrelevant) call to swap_alpha below. */ change &= ~PNG_FORMAT_FLAG_ALPHA; } /* Now set the alpha mode correctly; this is always done, even if there is * no alpha channel in either the input or the output because it correctly * sets the output gamma. */ png_set_alpha_mode_fixed(png_ptr, mode, output_gamma); # ifdef PNG_FORMAT_BGR_SUPPORTED if (change & PNG_FORMAT_FLAG_BGR) { /* Check only the output format; PNG is never BGR; don't do this if * the output is gray, but fix up the 'format' value in that case. */ if (format & PNG_FORMAT_FLAG_COLOR) png_set_bgr(png_ptr); else format &= ~PNG_FORMAT_FLAG_BGR; change &= ~PNG_FORMAT_FLAG_BGR; } # endif # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (change & PNG_FORMAT_FLAG_AFIRST) { /* Only relevant if there is an alpha channel - it's particularly * important to handle this correctly because do_local_compose may * be set above and then libpng will keep the alpha channel for this * code to remove. */ if (format & PNG_FORMAT_FLAG_ALPHA) { /* Disable this if doing a local background, * TODO: remove this when local background is no longer required. */ if (do_local_background != 2) png_set_swap_alpha(png_ptr); } else format &= ~PNG_FORMAT_FLAG_AFIRST; change &= ~PNG_FORMAT_FLAG_AFIRST; } # endif /* If the *output* is 16-bit then we need to check for a byte-swap on this * architecture. */ if (linear) { PNG_CONST png_uint_16 le = 0x0001; if (*(png_const_bytep)&le) png_set_swap(png_ptr); } /* If change is not now 0 some transformation is missing - error out. */ if (change) png_error(png_ptr, "png_read_image: unsupported transformation"); } PNG_SKIP_CHUNKS(png_ptr); /* Update the 'info' structure and make sure the result is as required; first * make sure to turn on the interlace handling if it will be required * (because it can't be turned on *after* the call to png_read_update_info!) * * TODO: remove the do_local_background fixup below. */ if (!do_local_compose && do_local_background != 2) passes = png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); { png_uint_32 info_format = 0; if (info_ptr->color_type & PNG_COLOR_MASK_COLOR) info_format |= PNG_FORMAT_FLAG_COLOR; if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA) { /* do_local_compose removes this channel below. */ if (!do_local_compose) { /* do_local_background does the same if required. */ if (do_local_background != 2 || (format & PNG_FORMAT_FLAG_ALPHA) != 0) info_format |= PNG_FORMAT_FLAG_ALPHA; } } else if (do_local_compose) /* internal error */ png_error(png_ptr, "png_image_read: alpha channel lost"); if (info_ptr->bit_depth == 16) info_format |= PNG_FORMAT_FLAG_LINEAR; # ifdef PNG_FORMAT_BGR_SUPPORTED if (png_ptr->transformations & PNG_BGR) info_format |= PNG_FORMAT_FLAG_BGR; # endif # ifdef PNG_FORMAT_AFIRST_SUPPORTED if (do_local_background == 2) { if (format & PNG_FORMAT_FLAG_AFIRST) info_format |= PNG_FORMAT_FLAG_AFIRST; } if ((png_ptr->transformations & PNG_SWAP_ALPHA) != 0 || ((png_ptr->transformations & PNG_ADD_ALPHA) != 0 && (png_ptr->flags & PNG_FLAG_FILLER_AFTER) == 0)) { if (do_local_background == 2) png_error(png_ptr, "unexpected alpha swap transformation"); info_format |= PNG_FORMAT_FLAG_AFIRST; } # endif /* This is actually an internal error. */ if (info_format != format) png_error(png_ptr, "png_read_image: invalid transformations"); } /* Now read the rows. If do_local_compose is set then it is necessary to use * a local row buffer. The output will be GA, RGBA or BGRA and must be * converted to G, RGB or BGR as appropriate. The 'local_row' member of the * display acts as a flag. */ { png_voidp first_row = display->buffer; ptrdiff_t row_bytes = display->row_stride; if (linear) row_bytes *= 2; /* The following expression is designed to work correctly whether it gives * a signed or an unsigned result. */ if (row_bytes < 0) { char *ptr = png_voidcast(char*, first_row); ptr += (image->height-1) * (-row_bytes); first_row = png_voidcast(png_voidp, ptr); } display->first_row = first_row; display->row_bytes = row_bytes; } if (do_local_compose) { int result; png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); display->local_row = row; result = png_safe_execute(image, png_image_read_composite, display); display->local_row = NULL; png_free(png_ptr, row); return result; } else if (do_local_background == 2) { int result; png_voidp row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); display->local_row = row; result = png_safe_execute(image, png_image_read_background, display); display->local_row = NULL; png_free(png_ptr, row); return result; } else { png_alloc_size_t row_bytes = display->row_bytes; while (--passes >= 0) { png_uint_32 y = image->height; png_bytep row = png_voidcast(png_bytep, display->first_row); while (y-- > 0) { png_read_row(png_ptr, row, NULL); row += row_bytes; } } return 1; } } int PNGAPI png_image_finish_read(png_imagep image, png_const_colorp background, void *buffer, png_int_32 row_stride, void *colormap) { if (image != NULL && image->version == PNG_IMAGE_VERSION) { png_uint_32 check; if (row_stride == 0) row_stride = PNG_IMAGE_ROW_STRIDE(*image); if (row_stride < 0) check = -row_stride; else check = row_stride; if (image->opaque != NULL && buffer != NULL && check >= PNG_IMAGE_ROW_STRIDE(*image)) { if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 || (image->colormap_entries > 0 && colormap != NULL)) { int result; png_image_read_control display; memset(&display, 0, (sizeof display)); display.image = image; display.buffer = buffer; display.row_stride = row_stride; display.colormap = colormap; display.background = background; display.local_row = NULL; /* Choose the correct 'end' routine; for the color-map case all the * setup has already been done. */ if (image->format & PNG_FORMAT_FLAG_COLORMAP) result = png_safe_execute(image, png_image_read_colormap, &display) && png_safe_execute(image, png_image_read_colormapped, &display); else result = png_safe_execute(image, png_image_read_direct, &display); png_image_free(image); return result; } else return png_image_error(image, "png_image_finish_read[color-map]: no color-map"); } else return png_image_error(image, "png_image_finish_read: invalid argument"); } else if (image != NULL) return png_image_error(image, "png_image_finish_read: damaged PNG_IMAGE_VERSION"); return 0; } #endif /* PNG_SIMPLIFIED_READ_SUPPORTED */ #endif /* PNG_READ_SUPPORTED */
131579.c
#ifdef _WIN32 __declspec(dllimport) #endif void foo(void); #include <stdio.h> void bar(void) { foo(); printf("bar()\n"); }
619534.c
/* e_lgammaf.c -- float version of e_lgamma.c. * Conversion to float by Ian Lance Taylor, Cygnus Support, [email protected]. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); /* __ieee754_lgammaf(x) * Return the logarithm of the Gamma function of x. * * Method: call __ieee754_lgammaf_r */ #include "math.h" #include "math_private.h" extern int signgam; float __ieee754_lgammaf(float x) { return __ieee754_lgammaf_r(x,&signgam); }
737207.c
#include "poly.h" #include "cbd.h" #include "NTT.h" #include "fips202.h" #include "pack_unpack.h" #define h1 (1 << (SABER_EQ - SABER_EP - 1)) #define h2 ((1 << (SABER_EP - 2)) - (1 << (SABER_EP - SABER_ET - 1)) + (1 << (SABER_EQ - SABER_EP - 1))) #define MAX(a,b) (((a)>(b))?(a):(b)) extern void __asm_poly_add_16(uint16_t *des, uint16_t *src1, uint16_t *src2); extern void __asm_poly_add_32(uint32_t *des, uint32_t *src1, uint32_t *src2); static inline shake128incctx shake128_absorb_seed(const uint8_t seed[SABER_SEEDBYTES]){ shake128incctx ctx; shake128_inc_init(&ctx); shake128_inc_absorb(&ctx, seed, SABER_SEEDBYTES); shake128_inc_finalize(&ctx); return ctx; } void MatrixVectorMulKeyPairNTT_A(uint8_t pk[SABER_INDCPA_PUBLICKEYBYTES], uint8_t sk[SABER_INDCPA_SECRETKEYBYTES]){ uint32_t s_NTT[SABER_N]; uint32_t acc_NTT[SABER_L * SABER_N]; uint32_t A_NTT[SABER_N]; uint16_t poly[SABER_N]; uint8_t shake_out[MAX(SABER_POLYBYTES, SABER_POLYCOINBYTES)]; uint8_t *seed_A = pk + SABER_POLYVECCOMPRESSEDBYTES; uint8_t *seed_s = sk; size_t i, j; shake128incctx shake_s_ctx = shake128_absorb_seed(seed_s); shake128incctx shake_A_ctx = shake128_absorb_seed(seed_A); for (i = 0; i < SABER_L; i++) { shake128_inc_squeeze(shake_out, SABER_POLYCOINBYTES, &shake_s_ctx); cbd(poly, shake_out); #ifdef SABER_COMPRESS_SECRETKEY POLmu2BS(sk + i * SABER_POLYSECRETBYTES, poly); // sk <- s #else POLq2BS(sk + i * SABER_POLYSECRETBYTES, poly); // sk <- s #endif NTT_forward_32(s_NTT, poly); for (j = 0; j < SABER_L; j++) { shake128_inc_squeeze(shake_out, SABER_POLYBYTES, &shake_A_ctx); BS2POLq(shake_out, poly); NTT_forward_32(A_NTT, poly); if(i == 0){ NTT_mul_32(acc_NTT + j * SABER_N, A_NTT, s_NTT); }else{ NTT_mul_32(A_NTT, A_NTT, s_NTT); __asm_poly_add_32(acc_NTT + j * SABER_N, acc_NTT + j * SABER_N, A_NTT); } } } shake128_inc_ctx_release(&shake_A_ctx); shake128_inc_ctx_release(&shake_s_ctx); for (i = 0; i < SABER_L; i++) { NTT_inv_32(poly, acc_NTT + i * SABER_N); for (j = 0; j < SABER_N; j++) { poly[j] = ((poly[j] + h1) >> (SABER_EQ - SABER_EP)); } POLp2BS(pk + i * SABER_POLYCOMPRESSEDBYTES, poly); } } uint32_t MatrixVectorMulEncNTT_A(uint8_t ct0[SABER_POLYVECCOMPRESSEDBYTES], uint8_t ct1[SABER_SCALEBYTES_KEM], const uint8_t seed_s[SABER_NOISE_SEEDBYTES], const uint8_t seed_A[SABER_SEEDBYTES], const uint8_t pk[SABER_INDCPA_PUBLICKEYBYTES], const uint8_t m[SABER_KEYBYTES], int compare){ uint32_t acc_NTT[SABER_N]; uint32_t A_NTT[SABER_N]; uint32_t s_NTT[SABER_L * SABER_N]; uint16_t poly[SABER_N]; uint16_t acc[SABER_N]; uint8_t shake_out[MAX(SABER_POLYBYTES, SABER_POLYCOINBYTES)]; uint16_t *mp = poly; size_t i, j; uint32_t fail = 0; shake128incctx shake_s_ctx = shake128_absorb_seed(seed_s); for(i = 0; i < SABER_L; i++){ shake128_inc_squeeze(shake_out, SABER_POLYCOINBYTES, &shake_s_ctx); cbd(poly, shake_out); NTT_forward_32(s_NTT + i * SABER_N, poly); } shake128_inc_ctx_release(&shake_s_ctx); shake128incctx shake_A_ctx = shake128_absorb_seed(seed_A); for (i = 0; i < SABER_L; i++) { for (j = 0; j < SABER_L; j++) { shake128_inc_squeeze(shake_out, SABER_POLYBYTES, &shake_A_ctx); BS2POLq(shake_out, poly); NTT_forward_32(A_NTT, poly); if (j == 0) { NTT_mul_32(acc_NTT, A_NTT, s_NTT + j * SABER_N); } else { NTT_mul_32(A_NTT, A_NTT, s_NTT + j * SABER_N); __asm_poly_add_32(acc_NTT, acc_NTT, A_NTT); } } NTT_inv_32(acc, acc_NTT); for (j = 0; j < SABER_N; j++) { acc[j] = ((acc[j] + h1) >> (SABER_EQ - SABER_EP)); } if (compare) { fail |= POLp2BS_cmp(ct0 + i * SABER_POLYCOMPRESSEDBYTES, acc); } else { POLp2BS(ct0 + i * SABER_POLYCOMPRESSEDBYTES, acc); } } shake128_inc_ctx_release(&shake_A_ctx); for(j = 0; j < SABER_L; j++){ BS2POLp(pk + j * SABER_POLYCOMPRESSEDBYTES, poly); NTT_forward_32(A_NTT, poly); if(j == 0){ NTT_mul_32(acc_NTT, A_NTT, s_NTT + j * SABER_N); }else{ NTT_mul_32(A_NTT, A_NTT, s_NTT + j * SABER_N); __asm_poly_add_32(acc_NTT, acc_NTT, A_NTT); } } NTT_inv_32(acc, acc_NTT); BS2POLmsg(m, mp); for(j = 0; j < SABER_N; j++){ acc[j] = (acc[j] - (mp[j] << (SABER_EP - 1)) + h1) >> (SABER_EP - SABER_ET); } if(compare){ fail |= POLT2BS_cmp(ct1, acc); }else{ POLT2BS(ct1, acc); } return fail; } void InnerProdDecNTT(uint8_t m[SABER_KEYBYTES], const uint8_t ciphertext[SABER_BYTES_CCA_DEC], const uint8_t sk[SABER_INDCPA_SECRETKEYBYTES]){ uint32_t acc_NTT[SABER_N]; uint32_t poly_NTT[SABER_N]; uint32_t buff_NTT[SABER_N]; uint16_t poly[SABER_N]; uint16_t cm[SABER_N]; size_t i; for (i = 0; i < SABER_L; i++) { #ifdef SABER_COMPRESS_SECRETKEY BS2POLmu(sk + i * SABER_POLYSECRETBYTES, poly); #else BS2POLq(sk + i * SABER_POLYSECRETBYTES, poly); #endif NTT_forward_32(poly_NTT, poly); BS2POLp(ciphertext + i * SABER_POLYCOMPRESSEDBYTES, poly); NTT_forward_32(buff_NTT, poly); if (i == 0) { NTT_mul_32(acc_NTT, poly_NTT, buff_NTT); } else { NTT_mul_32(poly_NTT, poly_NTT, buff_NTT); __asm_poly_add_32(acc_NTT, acc_NTT, poly_NTT); } } NTT_inv_32(poly, acc_NTT); BS2POLT(ciphertext + SABER_POLYVECCOMPRESSEDBYTES, cm); for (i = 0; i < SABER_N; i++) { poly[i] = (poly[i] + h2 - (cm[i] << (SABER_EP - SABER_ET))) >> (SABER_EP - 1); } POLmsg2BS(m, poly); } void InnerProdDecNTT_stack(uint8_t m[SABER_KEYBYTES], const uint8_t ciphertext[SABER_BYTES_CCA_DEC], const uint8_t sk[SABER_INDCPA_SECRETKEYBYTES]){ uint16_t buff1[SABER_N]; uint16_t buff2[SABER_N]; uint16_t buff3[SABER_N]; uint32_t acc[SABER_N]; uint16_t *acc_16 = (uint16_t*)acc; uint32_t *buff1_32 = (uint32_t*)buff1; uint32_t *buff2_32 = (uint32_t*)buff2; uint32_t *buff3_32 = (uint32_t*)buff3; size_t i; for (i = 0; i < SABER_L; i++) { BS2POLp(ciphertext + i * SABER_POLYCOMPRESSEDBYTES, buff3); NTT_forward_32(buff1_32, buff3); #ifdef SABER_COMPRESS_SECRETKEY BS2POLmu(sk + i * SABER_POLYSECRETBYTES, buff3); #else BS2POLq(sk + i * SABER_POLYSECRETBYTES, buff3); #endif NTT_forward2(buff3_32, buff3); if(i == 0){ NTT_mul_32x16_2(acc + 1 * SABER_N / 2, buff1_32, buff3_32); }else{ NTT_mul_32x16_2(buff3_32, buff1_32, buff3_32); __asm_poly_add_16(acc_16 + 1 * SABER_N, acc_16 + 1 * SABER_N, buff3); } MOD_1(buff1_32, buff1_32); #ifdef SABER_COMPRESS_SECRETKEY BS2POLmu(sk + i * SABER_POLYSECRETBYTES, buff2); #else BS2POLq(sk + i * SABER_POLYSECRETBYTES, buff2); #endif NTT_forward1(buff2_32, buff2); if(i == 0){ NTT_mul_16_1(acc + 0 * SABER_N / 2, buff1_32, buff2_32); }else{ NTT_mul_16_1(buff2_32, buff1_32, buff2_32); __asm_poly_add_16(acc_16 + 0 * SABER_N, acc_16 + 0 * SABER_N, buff2); } } solv_CRT(buff2_32, acc + 0 * SABER_N / 2, acc + 1 * SABER_N / 2); NTT_inv_32(buff1, buff2_32); BS2POLT(ciphertext + SABER_POLYVECCOMPRESSEDBYTES, buff2); for (i = 0; i < SABER_N; i++) { buff1[i] = (buff1[i] + h2 - (buff2[i] << (SABER_EP - SABER_ET))) >> (SABER_EP - 1); } POLmsg2BS(m, buff1); } void MatrixVectorMulKeyPairNTT_D(uint8_t pk[SABER_INDCPA_PUBLICKEYBYTES], uint8_t sk[SABER_INDCPA_SECRETKEYBYTES]){ uint8_t s_buff[SABER_N / 2]; uint16_t acc[SABER_L * SABER_N]; uint16_t buff1[SABER_N]; uint16_t buff2[SABER_N];; uint16_t buff3[MAX(SABER_N, MAX(SABER_POLYCOINBYTES, SABER_POLYBYTES) / 2)]; uint32_t *buff1_32 = (uint32_t*)buff1; uint32_t *buff2_32 = (uint32_t*)buff2; uint32_t *buff3_32 = (uint32_t*)buff3; uint8_t *shake_out = (uint8_t*)buff3; uint8_t *seed_A = pk + SABER_POLYVECCOMPRESSEDBYTES; uint8_t *seed_s = sk; size_t i, j; shake128incctx shake_s_ctx = shake128_absorb_seed(seed_s); shake128incctx shake_A_ctx = shake128_absorb_seed(seed_A); for (i = 0; i < SABER_L; i++) { shake128_inc_squeeze(shake_out, SABER_POLYCOINBYTES, &shake_s_ctx); cbd(buff2, shake_out); #ifdef SABER_COMPRESS_SECRETKEY POLmu2BS(sk + i * SABER_POLYSECRETBYTES, buff2); // sk <- s #else POLq2BS(sk + i * SABER_POLYSECRETBYTES, buff2); // sk <- s #endif POLmu2BS(s_buff, buff2); for (j = 0; j < SABER_L; j++) { shake128_inc_squeeze(shake_out, SABER_POLYBYTES, &shake_A_ctx); BS2POLq(shake_out, buff3); NTT_forward_32(buff1_32, buff3); BS2POLmu(s_buff, buff3); NTT_forward2(buff3_32, buff3); NTT_mul_32x16_2(buff3_32, buff1_32, buff3_32); MOD_1(buff1_32, buff1_32); BS2POLmu(s_buff, buff2); NTT_forward1(buff2_32, buff2); NTT_mul_16_1(buff2_32, buff1_32, buff2_32); solv_CRT(buff1_32, buff2_32, buff3_32); if(i == 0){ NTT_inv_32(acc + j * SABER_N, buff1_32); }else{ NTT_inv_32(buff3, buff1_32); __asm_poly_add_16(acc + j * SABER_N, acc + j * SABER_N, buff3); } } } shake128_inc_ctx_release(&shake_A_ctx); shake128_inc_ctx_release(&shake_s_ctx); for (i = 0; i < SABER_L; i++) { for (j = 0; j < SABER_N; j++) { acc[i * SABER_N + j] = ((acc[i * SABER_N + j] + h1) >> (SABER_EQ - SABER_EP)); } POLp2BS(pk + i * SABER_POLYCOMPRESSEDBYTES, acc + i * SABER_N); } } uint32_t MatrixVectorMulEncNTT_D(uint8_t ct0[SABER_POLYVECCOMPRESSEDBYTES], uint8_t ct1[SABER_SCALEBYTES_KEM], const uint8_t seed_s[SABER_NOISE_SEEDBYTES], const uint8_t seed_A[SABER_SEEDBYTES], const uint8_t pk[SABER_INDCPA_PUBLICKEYBYTES], const uint8_t m[SABER_KEYBYTES], int compare){ uint8_t s_buff[SABER_L * SABER_N / 2]; uint16_t acc[SABER_N]; uint16_t buff1[SABER_N]; uint16_t buff2[SABER_N]; uint16_t buff3[MAX(SABER_N, MAX(SABER_POLYBYTES, SABER_POLYCOINBYTES) / 2)]; uint32_t *buff1_32 = (uint32_t*)buff1; uint32_t *buff2_32 = (uint32_t*)buff2; uint32_t *buff3_32 = (uint32_t*)buff3; uint8_t *shake_out = (uint8_t*)buff3; uint16_t *mp = buff1; size_t i, j; uint32_t fail = 0; shake128incctx shake_s_ctx = shake128_absorb_seed(seed_s); for(i = 0; i < SABER_L; i++){ shake128_inc_squeeze(shake_out, SABER_POLYCOINBYTES, &shake_s_ctx); cbd(acc, shake_out); POLmu2BS(s_buff + i * SABER_N / 2, acc); } shake128_inc_ctx_release(&shake_s_ctx); shake128incctx shake_A_ctx = shake128_absorb_seed(seed_A); for (i = 0; i < SABER_L; i++) { for (j = 0; j < SABER_L; j++) { shake128_inc_squeeze(shake_out, SABER_POLYBYTES, &shake_A_ctx); BS2POLq(shake_out, buff3); NTT_forward_32(buff1_32, buff3); BS2POLmu(s_buff + j * SABER_N / 2, buff3); NTT_forward2(buff3_32, buff3); NTT_mul_32x16_2(buff3_32, buff1_32, buff3_32); MOD_1(buff1_32, buff1_32); BS2POLmu(s_buff + j * SABER_N / 2, buff2); NTT_forward1(buff2_32, buff2); NTT_mul_16_1(buff2_32, buff1_32, buff2_32); solv_CRT(buff1_32, buff2_32, buff3_32); if(j == 0){ NTT_inv_32(acc, buff1_32); }else{ NTT_inv_32(buff3, buff1_32); __asm_poly_add_16(acc, acc, buff3); } } for (j = 0; j < SABER_N; j++) { acc[j] = ((acc[j] + h1) >> (SABER_EQ - SABER_EP)); } if (compare) { fail |= POLp2BS_cmp(ct0 + i * SABER_POLYCOMPRESSEDBYTES, acc); } else { POLp2BS(ct0 + i * SABER_POLYCOMPRESSEDBYTES, acc); } } shake128_inc_ctx_release(&shake_A_ctx); for(j = 0; j < SABER_L; j++){ BS2POLp(pk + j * SABER_POLYCOMPRESSEDBYTES, buff3); NTT_forward_32(buff1_32, buff3); BS2POLmu(s_buff + j * SABER_N / 2, buff3); NTT_forward2(buff3_32, buff3); NTT_mul_32x16_2(buff3_32, buff1_32, buff3_32); MOD_1(buff1_32, buff1_32); BS2POLmu(s_buff + j * SABER_N / 2, buff2); NTT_forward1(buff2_32, buff2); NTT_mul_16_1(buff2_32, buff1_32, buff2_32); solv_CRT(buff1_32, buff2_32, buff3_32); if(j == 0){ NTT_inv_32(acc, buff1_32); }else{ NTT_inv_32(buff3, buff1_32); __asm_poly_add_16(acc, acc, buff3); } } BS2POLmsg(m, mp); for(j = 0; j < SABER_N; j++){ acc[j] = (acc[j] - (mp[j] << (SABER_EP - 1)) + h1) >> (SABER_EP - SABER_ET); } if(compare){ fail |= POLT2BS_cmp(ct1, acc); }else{ POLT2BS(ct1, acc); } return fail; }
299190.c
#include "debug_ui.h" #include "raylib.h" #include "platform.h" #include "profiler.h" //~ NOTE(zaklaus): helpers static inline debug_draw_result DrawFloat(float xpos, float ypos, float val) { char const *text = TextFormat("%.02f\n", val); UIDrawText(text, xpos, ypos, DBG_FONT_SIZE, RAYWHITE); return (debug_draw_result){.x = xpos + UIMeasureText(text, DBG_FONT_SIZE), .y = ypos + DBG_FONT_SPACING}; } static inline debug_draw_result DrawColoredText(float xpos, float ypos, char const *text, Color color) { ZPL_ASSERT(text); UIDrawText(text, xpos, ypos, DBG_FONT_SIZE, color); return (debug_draw_result){.x = xpos + UIMeasureText(text, DBG_FONT_SIZE), .y = ypos + DBG_FONT_SPACING}; } static inline debug_draw_result DrawFormattedText(float xpos, float ypos, char const *text) { return DrawColoredText(xpos, ypos, text, RAYWHITE); } //~ NOTE(zaklaus): widgets static inline debug_draw_result DrawCameraPos(debug_item *it, float xpos, float ypos) { (void)it; camera cam = camera_get(); return DrawFormattedText(xpos, ypos, TextFormat("%d %d", (int)(cam.x/WORLD_BLOCK_SIZE), (int)(cam.y/WORLD_BLOCK_SIZE))); } static inline debug_draw_result DrawUnmeasuredTime(debug_item *it, float xpos, float ypos) { (void)it; float total_time = profiler_delta(PROF_TOTAL_TIME); float acc_time = profiler_delta(PROF_MAIN_LOOP); return DrawFormattedText(xpos, ypos, TextFormat("%.02f ms", (total_time-acc_time) * 1000.0f)); } static inline debug_draw_result DrawDeltaTime(debug_item *it, float xpos, float ypos) { (void)it; float dt = GetFrameTime(); return DrawFormattedText(xpos, ypos, TextFormat("%.02f (%.02f fps)", dt * 1000.0f, 1.0f/dt)); } static inline debug_draw_result DrawZoom(debug_item *it, float xpos, float ypos) { (void)it; return DrawFloat(xpos, ypos, platform_zoom_get()); } static inline debug_draw_result DrawLiteral(debug_item *it, float xpos, float ypos) { ZPL_ASSERT(it->text); return DrawFormattedText(xpos, ypos, it->text); } static inline debug_draw_result DrawProfilerDelta(debug_item *it, float xpos, float ypos) { float dt = profiler_delta(it->val); return DrawFormattedText(xpos, ypos, TextFormat("%s: %.02f ms", profiler_name(it->val), dt * 1000.0f)); } static inline debug_draw_result DrawReplaySamples(debug_item *it, float xpos, float ypos) { (void)it; size_t cnt = 0; if (records) { cnt = zpl_array_count(records); } return DrawFormattedText(xpos, ypos, TextFormat("%d of %d", record_pos, cnt)); } static inline debug_draw_result DrawReplayFileName(debug_item *it, float xpos, float ypos) { (void)it; return DrawFormattedText(xpos, ypos, TextFormat("%s", replay_filename[0] ? replay_filename : "<unnamed>")); } // NOTE(zaklaus): demo npcs static inline debug_draw_result DrawDemoNPCCount(debug_item *it, float xpos, float ypos) { (void)it; return DrawFormattedText(xpos, ypos, TextFormat("%d", demo_npcs ? zpl_array_count(demo_npcs) : 0)); } // NOTE(zaklaus): world simulation static inline debug_draw_result DrawWorldStepSize(debug_item *it, float xpos, float ypos) { (void)it; return DrawFormattedText(xpos, ypos, TextFormat("%d ms", (int16_t)(sim_step_size*1000.f))); }
710541.c
/* opielogin.c: The infamous /bin/login %%% portions-copyright-cmetz-96 Portions of this software are Copyright 1996-1999 by Craig Metz, All Rights Reserved. The Inner Net License Version 2 applies to these portions of the software. You should have received a copy of the license with this software. If you didn't get a copy, you may request one from <[email protected]>. Portions of this software are Copyright 1995 by Randall Atkinson and Dan McDonald, All Rights Reserved. All Rights under this copyright are assigned to the U.S. Naval Research Laboratory (NRL). The NRL Copyright Notice and License Agreement applies to this software. History: Modified by cmetz for OPIE 2.4. Omit "/dev/" in lastlog entry. Don't chdir for invalid users. Fixed bug where getloginname() didn't actually change spaces to underscores. Use struct opie_key for key blocks. Do the home directory chdir() after doing the setuid() in case we're on superuser-mapped NFS. Initialize some variables explicitly. Call opieverify() if login times out. Use opiestrncpy(). Modified by cmetz for OPIE 2.32. Partially handle environment variables on the command line (a better implementation is coming soon). Handle failure to issue a challenge more gracefully. Modified by cmetz for OPIE 2.31. Use _PATH_NOLOGIN. Move Solaris drain bamage kluge after rflag check; it breaks rlogin. Use TCSAFLUSH instead of TCSANOW (except where it flushes data we need). Sleep before kluging for Solaris. Modified by cmetz for OPIE 2.3. Process login environment files. Made logindevperm/fbtab handling more generic. Kluge around Solaris drain bamage differently (maybe better?). Maybe allow cleartext logins even when opiechallenge() fails. Changed the conditions on when time.h and sys/time.h are included. Send debug info to syslog. Use opielogin() instead of dealing with utmp/setlogin() here. Modified by cmetz for OPIE 2.22. Call setlogin(). Decreased default timeout to two minutes. Use opiereadpass() flags to get around Solaris drain bamage. Modified by cmetz for OPIE 2.21. Took the sizeof() the wrong thing. Modified by cmetz for OPIE 2.2. Changed prompts to ask for OTP response where appropriate. Simple though small speed-up. Don't allow cleartext if echo on. Don't try to clear non-blocking I/O. Use opiereadpass(). Don't mess with termios (as much, at least) -- that's opiereadpass()'s job. Change opiereadpass() calls to add echo arg. Fixed CONTROL macro. Don't modify argv (at least, unless we have a reason to). Allow user in if ruserok() says so. Removed useless strings (I don't think that removing the ucb copyright one is a problem -- please let me know if I'm wrong). Use FUNCTION declaration et al. Moved definition of TRUE here. Ifdef around more headers. Make everything static. Removed support for omitting domain name if same domain -- it generally didn't work and it would be a big portability problem. Use opiereadpass() in getloginname() and then post- process. Added code to grab hpux time zone from /etc/src.sh. Renamed MAIL_DIR to PATH_MAIL. Removed dupe catchexit and extraneous closelog. openlog() as soon as possible because SunOS syslog is broken. Don't print an extra blank line before a new Response prompt. Modified at NRL for OPIE 2.2. Changed strip_crlf to stripcrlf. Do opiebackspace() on entries. Modified at NRL for OPIE 2.1. Since we don't seem to use the result of opiechallenge() anymore, discard it. Changed BSD4_3 to HAVE_GETTTYNAM. Other symbol changes for autoconf. Removed obselete usage comment. Removed des_crypt.h. File renamed to opielogin.c. Added bletch for setpriority. Added slash between MAIL_DIR and name. Modified at NRL for OPIE 2.02. Flush stdio after printing login prompt. Fixed Solaris shadow password problem introduced in OPIE 2.01 (the shadow password structure is spwd, not spasswd). Modified at NRL for OPIE 2.01. Changed password lookup handling to use a static structure to avoid problems with drain- bamaged shadow password packages. Make sure to close syslog by function to avoid problems with drain bamaged syslog implementations. Log a few interesting errors. Modified at NRL for OPIE 2.0. Modified at Bellcore for the Bellcore S/Key Version 1 software distribution. Originally from BSD. */ /* * Portions of this software are * Copyright (c) 1980,1987 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ #include "opie_cfg.h" /* OPIE: defines symbols for filenames & pathnames */ #if HAVE_SYS_PARAM_H #include <sys/param.h> #endif /* HAVE_SYS_PARAM_H */ #include <sys/stat.h> #include <sys/types.h> #if HAVE_SETPRIORITY && HAVE_SYS_RESOURCE_H #include <sys/resource.h> #endif /* HAVE_SETPRIORITY && HAVE_SYS_RESOURCE_H */ #if TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else /* TIME_WITH_SYS_TIME */ #if HAVE_SYS_TIME_H #include <sys/time.h> #else /* HAVE_SYS_TIME_H */ #include <time.h> #endif /* HAVE_SYS_TIME_H */ #endif /* TIME_WITH_SYS_TIME */ #if HAVE_SYS_FILE_H #include <sys/file.h> #endif /* HAVE_SYS_FILE_H */ #include <signal.h> #if HAVE_PWD_H #include <pwd.h> /* POSIX Password routines */ #endif /* HAVE_PWD_H */ #include <stdio.h> #include <errno.h> #if HAVE_UNISTD_H #include <unistd.h> /* Basic POSIX macros and functions */ #endif /* HAVE_UNISTD_H */ #include <termios.h> /* POSIX terminal I/O */ #if HAVE_STRING_H #include <string.h> /* ANSI C string functions */ #endif /* HAVE_STRING_H */ #include <fcntl.h> /* File I/O functions */ #include <syslog.h> #include <grp.h> #include <netdb.h> #include <netinet/in.h> /* contains types needed for next include file */ #include <arpa/inet.h> /* Inet addr<-->ascii functions */ #if HAVE_STDLIB_H #include <stdlib.h> #endif /* HAVE_STDLIB_H */ #if HAVE_SYS_SELECT_H #include <sys/select.h> #endif /* HAVE_SYS_SELECT_H */ #ifdef QUOTA #include <sys/quota.h> #endif #if HAVE_GETTTYNAM #include <sys/ioctl.h> /* non-portable routines used only a few places */ #include <ttyent.h> #endif /* HAVE_GETTTYNAM */ #include "opie.h" #define TTYGID(gid) tty_gid(gid) /* gid that owns all ttys */ #define NMAX 32 #define HMAX 256 #if HAVE_LASTLOG_H #include <lastlog.h> #endif /* HAVE_LASTLOG_H */ static int rflag = 0; static int usererr = -1; static int stopmotd = 0; static char rusername[NMAX + 1]; static char name[NMAX + 1] = ""; static char minusnam[16] = "-"; static char *envinit[1]; /* now set by setenv calls */ static char term[64] = ""; /* important to initialise to a NULL string */ static char host[HMAX + 1] = ""; static struct passwd nouser; static struct passwd thisuser; #if HAVE_SHADOW_H #include <shadow.h> #endif /* HAVE_SHADOW_H */ static char *ttyprompt; #ifdef PERMSFILE extern char *home; #endif /* PERMSFILE */ static struct termios attr; extern int errno; static int ouroptind; static char *ouroptarg; #if HAVE_LASTLOG_H #ifndef _PATH_LASTLOG #define _PATH_LASTLOG "/var/adm/lastlog" #endif /* _PATH_LASTLOG */ static char lastlog[] = _PATH_LASTLOG; #endif /* HAVE_LASTLOG_H */ /* * The "timeout" variable bounds the time given to login. * We initialize it here for safety and so that it can be * patched on machines where the default value is not appropriate. */ static int timeout = 120; static void getstr __P((char *, int, char *)); #if HAVE_CRYPT_H #include <crypt.h> #endif /* HAVE_CRYPT_H */ #undef TRUE #define TRUE -1 static int need_opieverify = 0; static struct opie opie; #ifdef TIOCSWINSZ /* Windowing variable relating to JWINSIZE/TIOCSWINSZ/TIOCGWINSZ. This is available on BSDish systems and at least Solaris 2.x, but portability to other systems is questionable. Use within this source code module is protected by suitable defines. I'd be interested in hearing about a more portable approach. rja */ static struct winsize win = {0, 0, 0, 0}; #endif /*------------------ BEGIN REAL CODE --------------------------------*/ /* We allow the malloc()s to potentially leak data out because we can only call this routine about four times in the lifetime of this process and the kernel will free all heap memory when we exit or exec. */ static int lookupuser FUNCTION_NOARGS { struct passwd *pwd; #if HAVE_SHADOW struct spwd *spwd; #endif /* HAVE_SHADOW */ memcpy(&thisuser, &nouser, sizeof(thisuser)); if (!(pwd = getpwnam(name))) return -1; thisuser.pw_uid = pwd->pw_uid; thisuser.pw_gid = pwd->pw_gid; if (!(thisuser.pw_name = malloc(strlen(pwd->pw_name) + 1))) goto lookupuserbad; strcpy(thisuser.pw_name, pwd->pw_name); if (!(thisuser.pw_dir = malloc(strlen(pwd->pw_dir) + 1))) goto lookupuserbad; strcpy(thisuser.pw_dir, pwd->pw_dir); if (!(thisuser.pw_shell = malloc(strlen(pwd->pw_shell) + 1))) goto lookupuserbad; strcpy(thisuser.pw_shell, pwd->pw_shell); #if HAVE_SHADOW if (!(spwd = getspnam(name))) goto lookupuserbad; pwd->pw_passwd = spwd->sp_pwdp; endspent(); #endif /* HAVE_SHADOW */ if (!(thisuser.pw_passwd = malloc(strlen(pwd->pw_passwd) + 1))) goto lookupuserbad; strcpy(thisuser.pw_passwd, pwd->pw_passwd); endpwent(); return ((thisuser.pw_passwd[0] == '*') || (thisuser.pw_passwd[0] == '#')); lookupuserbad: memcpy(&thisuser, &nouser, sizeof(thisuser)); return -1; } static VOIDRET getloginname FUNCTION_NOARGS { char *namep, d; int flags; static int first = 1; memset(name, 0, sizeof(name)); d = 0; while (name[0] == '\0') { flags = 1; if (ttyprompt) { if (first) { flags = 4; first--; } else printf(ttyprompt); } else printf("login: "); fflush(stdout); if (++d == 3) exit(0); if (!opiereadpass(name, sizeof(name)-1, flags)) { syslog(LOG_CRIT, "End-of-file (or other error?) on stdin!"); exit(0); } for (namep = name; *namep; namep++) { if (*namep == ' ') *namep = '_'; } } } static VOIDRET timedout FUNCTION((i), int i) { /* input variable declared just to keep the compiler quiet */ printf("Login timed out after %d seconds\n", timeout); syslog(LOG_CRIT, "Login timed out after %d seconds!", timeout); if (need_opieverify) opieverify(&opie, NULL); exit(0); } #if !HAVE_MOTD_IN_PROFILE static VOIDRET catch FUNCTION((i), int i) { /* the input variable is declared to keep the compiler quiet */ signal(SIGINT, SIG_IGN); stopmotd++; } #endif /* !HAVE_MOTD_IN_PROFILE */ static VOIDRET catchexit FUNCTION_NOARGS { int i; tcsetattr(STDIN_FILENO, TCSAFLUSH, &attr); putchar('\n'); closelog(); for (i = sysconf(_SC_OPEN_MAX); i > 2; i--) close(i); } static int rootterm FUNCTION((ttyn), char *ttyn) { #if HAVE_GETTTYNAM /* The getttynam() call and the ttyent structure first appeared in 4.3 BSD and are not portable to System V systems such as Solaris 2.x. or modern versions of IRIX rja */ register struct ttyent *t; char *tty; tty = strrchr(ttyn, '/'); if (tty == NULL) tty = ttyn; else tty++; if ((t = getttynam(tty)) != NULL) return (t->ty_status & TTY_SECURE); return (1); /* when in doubt, allow root logins */ #elif HAVE_ETC_DEFAULT_LOGIN FILE *filno; char line[128]; char *next, *next2; /* SVR4 only permits two security modes for root logins: 1) only from CONSOLE, if the string "CONSOLE=/dev/console" exists and is not commented out with "#" characters, or 2) from anywhere. So we open /etc/default/login file grab the file contents one line at a time verify that the line being tested isn't commented out check for the substring "CONSOLE" and decide whether to permit this attempted root login/su. */ if ((filno = fopen("/etc/default/login", "r")) != NULL) { while (fgets(line, 128, filno) != NULL) { next = line; if ((line[0] != '#') && (next = strstr(line, "CONSOLE"))) { next += 7; /* get past the string "CONSOLE" */ while (*next && (*next == ' ') || (*next == '\t')) next++; if (*(next++) != '=') break; /* some weird character, get next line */ next2 = next; while (*next2 && (*next2 != '\t') && (*next2 != ' ') && (*next2 != '\n')) next2++; *next2 = 0; return !strcmp(ttyn, next); /* Allow the login if and only if the user's terminal line matches the setting for CONSOLE */ } } /* end while another line could be obtained */ } /* end if could open file */ return (1); /* when no CONSOLE line exists, root can login from anywhere */ #elif HAVE_SECURETTY { FILE *f; char buffer[1024], *c; int rc = 0; if (!(f = fopen("/etc/securetty", "r"))) return 1; if (c = strstr(ttyn, "/dev/")) ttyn += 5; if (c = strrchr(ttyn, '/')) ttyn = ++c; while (fgets(buffer, sizeof(buffer), f)) { if (c = strrchr(buffer, '\n')) *c = 0; if (!(c = strrchr(buffer, '/'))) c = buffer; else c++; if (!strcmp(c, ttyn)) rc = 1; }; fclose(f); return rc; } #else return (1); /* when in doubt, allow root logins */ #endif } static int doremotelogin FUNCTION((host), char *host) { int rc; getstr(rusername, sizeof(rusername), "remuser"); getstr(name, sizeof(name), "locuser"); getstr(term, sizeof(term), "Terminal type"); if (getuid()) { memcpy(&thisuser, &nouser, sizeof(thisuser)); syslog(LOG_ERR, "getuid() failed"); return (-1); } if (lookupuser()) { syslog(LOG_ERR, "lookup failed for user %s", name); return (-1); } rc = ruserok(host, !thisuser.pw_uid, rusername, name); if (rc == -1) { syslog(LOG_ERR, "ruserok failed, host=%s, uid=%d, remote username=%s, local username=%s", host, thisuser.pw_uid, rusername, name); } return rc; } static VOIDRET getstr FUNCTION((buf, cnt, err), char *buf AND int cnt AND char *err) { char c; do { if (read(0, &c, 1) != 1) exit(1); if (--cnt < 0) { printf("%s too long\r\n", err); syslog(LOG_CRIT, "%s too long", err); exit(1); } *buf++ = c; } while ((c != 0) && (c != '~')); } struct speed_xlat { char *c; int i; } speeds[] = { #ifdef B0 { "0", B0 }, #endif /* B0 */ #ifdef B50 { "50", B50 }, #endif /* B50 */ #ifdef B75 { "75", B75 }, #endif /* B75 */ #ifdef B110 { "110", B110 }, #endif /* B110 */ #ifdef B134 { "134", B134 }, #endif /* B134 */ #ifdef B150 { "150", B150 }, #endif /* B150 */ #ifdef B200 { "200", B200 }, #endif /* B200 */ #ifdef B300 { "300", B300 }, #endif /* B300 */ #ifdef B600 { "600", B600 }, #endif /* B600 */ #ifdef B1200 { "1200", B1200 }, #endif /* B1200 */ #ifdef B1800 { "1800", B1800 }, #endif /* B1800 */ #ifdef B2400 { "2400", B2400 }, #endif /* B2400 */ #ifdef B4800 { "4800", B4800 }, #endif /* B4800 */ #ifdef B7200 { "7200", B7200 }, #endif /* B7200 */ #ifdef B9600 { "9600", B9600 }, #endif /* B9600 */ #ifdef B14400 { "14400", B14400 }, #endif /* B14400 */ #ifdef B19200 { "19200", B19200 }, #endif /* B19200 */ #ifdef B28800 { "28800", B28800 }, #endif /* B28800 */ #ifdef B38400 { "38400", B38400 }, #endif /* B38400 */ #ifdef B57600 { "57600", B57600 }, #endif /* B57600 */ #ifdef B115200 { "115200", B115200 }, #endif /* B115200 */ #ifdef B230400 { "230400", B230400 }, #endif /* 230400 */ { NULL, 0 } }; static VOIDRET doremoteterm FUNCTION((term), char *term) { register char *cp = strchr(term, '/'); char *speed; struct speed_xlat *x; if (cp) { *cp++ = '\0'; speed = cp; cp = strchr(speed, '/'); if (cp) *cp++ = '\0'; for (x = speeds; x->c != NULL; x++) if (strcmp(x->c, speed) == 0) { cfsetispeed(&attr, x->i); cfsetospeed(&attr, x->i); break; } } } static int tty_gid FUNCTION((default_gid), int default_gid) { struct group *gr; int gid = default_gid; gr = getgrnam(TTYGRPNAME); if (gr != (struct group *) 0) gid = gr->gr_gid; endgrent(); return (gid); } int main FUNCTION((argc, argv), int argc AND char *argv[]) { extern char **environ; register char *namep; int invalid, quietlog; FILE *nlfd; char *tty, host[256]; int pflag = 0, hflag = 0, fflag = 0; int t, c; int i; char *p; char opieprompt[OPIE_CHALLENGE_MAX + 1]; int af_pwok; int authsok = 0; char *pp; char buf[256]; int uid; int opiepassed; #ifndef DEBUG if (geteuid()) { fprintf(stderr, "This program requires super-user privileges.\n"); exit(1); } #endif /* DEBUG */ for (t = sysconf(_SC_OPEN_MAX); t > 2; t--) close(t); openlog("login", 0, LOG_AUTH); /* initialisation */ host[0] = '\0'; opieprompt[0] = '\0'; if (p = getenv("TERM")) { #ifdef DEBUG syslog(LOG_DEBUG, "environment TERM=%s", p); #endif /* DEBUG */ opiestrncpy(term, p, sizeof(term)); }; memset(&nouser, 0, sizeof(nouser)); nouser.pw_uid = -1; nouser.pw_gid = -1; nouser.pw_passwd = "#nope"; nouser.pw_name = nouser.pw_gecos = nouser.pw_dir = nouser.pw_shell = ""; #if HAVE_SETPRIORITY && HAVE_SYS_RESOURCE_H setpriority(PRIO_PROCESS, 0, 0); #endif /* HAVE_SETPRIORITY && HAVE_SYS_RESOURCE_H */ signal(SIGALRM, timedout); alarm(timeout); signal(SIGQUIT, SIG_IGN); signal(SIGINT, SIG_IGN); #if DOTTYPROMPT ttyprompt = (char *) getenv("TTYPROMPT"); #endif /* TTYPROMPT */ #ifdef QUOTA quota(Q_SETUID, 0, 0, 0); #endif #ifdef DEBUG syslog(LOG_DEBUG, "my args are: (argc=%d)", i = argc); while (--i) syslog(LOG_DEBUG, "%d: %s", i, argv[i]); #endif /* DEBUG */ /* Implement our own getopt()-like functionality, but do so in a much more strict manner to prevent security problems. */ for (ouroptind = 1; ouroptind < argc; ouroptind++) { if (!argv[ouroptind]) continue; if (argv[ouroptind][0] == '-') { char *c = argv[ouroptind] + 1; while(*c) { switch(*(c++)) { case 'd': if (*c || (++ouroptind == argc)) exit(1); /* The '-d' option is apparently a performance hack to get around ttyname() being slow. The potential does exist for it to be used for malice, and it does not seem to be strictly necessary, so we will just eat it. */ break; case 'r': if (rflag || hflag || fflag) { fprintf(stderr, "Other options not allowed with -r\n"); exit(1); } if (*c || (++ouroptind == argc)) exit(1); if (!(ouroptarg = argv[ouroptind])) exit(1); rflag = -1; if (!doremotelogin(ouroptarg)) rflag = 1; opiestrncpy(host, ouroptarg, sizeof(host)); break; case 'h': if (!getuid()) { if (rflag || hflag || fflag) { fprintf(stderr, "Other options not allowed with -h\n"); exit(1); } hflag = 1; if (*c || (++ouroptind == argc)) exit(1); if (!(ouroptarg = argv[ouroptind])) exit(1); opiestrncpy(host, ouroptarg, sizeof(host)); } break; case 'f': if (rflag) { fprintf(stderr, "Only one of -r and -f allowed\n"); exit(1); } fflag = 1; if (*c || (++ouroptind == argc)) exit(1); if (!(ouroptarg = argv[ouroptind])) exit(1); opiestrncpy(name, ouroptarg, sizeof(name)); break; case 'p': pflag = 1; break; }; }; continue; }; if (strchr(argv[ouroptind], '=')) { if (!strncmp(argv[ouroptind], "TERM=", 5)) { opiestrncpy(term, &(argv[ouroptind][5]), sizeof(term)); #ifdef DEBUG syslog(LOG_DEBUG, "passed TERM=%s, ouroptind = %d", term, ouroptind); #endif /* DEBUG */ } else { #ifdef DEBUG syslog(LOG_DEBUG, "eating %s, ouroptind = %d", argv[ouroptind], ouroptind); #endif /* DEBUG */ }; continue; }; opiestrncpy(name, argv[ouroptind], sizeof(name)); }; #ifdef TIOCNXCL /* BSDism: not sure how to rewrite for POSIX. rja */ ioctl(0, TIOCNXCL, 0); /* set non-exclusive use of tty */ #endif /* get original termio attributes */ if (tcgetattr(STDIN_FILENO, &attr) != 0) return (-1); /* If talking to an rlogin process, propagate the terminal type and baud rate across the network. */ if (rflag) doremoteterm(term); else { struct termios termios; fd_set fds; struct timeval timeval; memset(&timeval, 0, sizeof(struct timeval)); FD_ZERO(&fds); FD_SET(0, &fds); #if HAVE_USLEEP usleep(1); #endif /* HAVE_USLEEP */ if (select(1, &fds, NULL, NULL, &timeval)) { #ifdef DEBUG syslog(LOG_DEBUG, "reading user name from tty buffer"); #endif /* DEBUG */ if (tcgetattr(0, &termios)) { #ifdef DEBUG syslog(LOG_DEBUG, "tcgetattr(0, &termios) failed"); #endif /* DEBUG */ exit(1); } termios.c_lflag &= ~ECHO; if (tcsetattr(0, TCSANOW, &termios)) { #ifdef DEBUG syslog(LOG_DEBUG, "tcsetattr(0, &termios) failed"); #endif /* DEBUG */ exit(1); } if ((i = read(0, name, sizeof(name)-1)) > 0) name[i] = 0; if ((p = strchr(name, '\r'))) *p = 0; if ((p = strchr(name, '\n'))) *p = 0; } } /* Force termios portable control characters to the system default values as specified in termios.h. This should help the one-time password login feel the same as the vendor-supplied login. Common extensions are also set for completeness, but these are set within appropriate defines for portability. */ #define CONTROL(x) (x - 64) #ifdef VEOF #ifdef CEOF attr.c_cc[VEOF] = CEOF; #else /* CEOF */ attr.c_cc[VEOF] = CONTROL('D'); #endif /* CEOF */ #endif /* VEOF */ #ifdef VEOL #ifdef CEOL attr.c_cc[VEOL] = CEOL; #else /* CEOL */ attr.c_cc[VEOL] = CONTROL('J'); #endif /* CEOL */ #endif /* VEOL */ #ifdef VERASE #ifdef CERASE attr.c_cc[VERASE] = CERASE; #else /* CERASE */ attr.c_cc[VERASE] = CONTROL('H'); #endif /* CERASE */ #endif /* VERASE */ #ifdef VINTR #ifdef CINTR attr.c_cc[VINTR] = CINTR; #else /* CINTR */ attr.c_cc[VINTR] = CONTROL('C'); #endif /* CINTR */ #endif /* VINTR */ #ifdef VKILL #ifdef CKILL attr.c_cc[VKILL] = CKILL; #else /* CKILL */ attr.c_cc[VKILL] = CONTROL('U'); #endif /* CKILL */ #endif /* VKILL */ #ifdef VQUIT #ifdef CQUIT attr.c_cc[VQUIT] = CQUIT; #else /* CQUIT */ attr.c_cc[VQUIT] = CONTROL('\\'); #endif /* CQUIT */ #endif /* VQUIT */ #ifdef VSUSP #ifdef CSUSP attr.c_cc[VSUSP] = CSUSP; #else /* CSUSP */ attr.c_cc[VSUSP] = CONTROL('Z'); #endif /* CSUSP */ #endif /* VSUSP */ #ifdef VSTOP #ifdef CSTOP attr.c_cc[VSTOP] = CSTOP; #else /* CSTOP */ attr.c_cc[VSTOP] = CONTROL('S'); #endif /* CSTOP */ #endif /* VSTOP */ #ifdef VSTART #ifdef CSTART attr.c_cc[VSTART] = CSTART; #else /* CSTART */ attr.c_cc[VSTART] = CONTROL('Q'); #endif /* CSTART */ #endif /* VSTART */ #ifdef VDSUSP #ifdef CDSUSP attr.c_cc[VDSUSP] = CDSUSP; #else /* CDSUSP */ attr.c_cc[VDSUSP] = 0; #endif /* CDSUSP */ #endif /* VDSUSP */ #ifdef VEOL2 #ifdef CEOL2 attr.c_cc[VEOL2] = CEOL2; #else /* CEOL2 */ attr.c_cc[VEOL2] = 0; #endif /* CEOL2 */ #endif /* VEOL2 */ #ifdef VREPRINT #ifdef CRPRNT attr.c_cc[VREPRINT] = CRPRNT; #else /* CRPRNT */ attr.c_cc[VREPRINT] = 0; #endif /* CRPRNT */ #endif /* VREPRINT */ #ifdef VWERASE #ifdef CWERASE attr.c_cc[VWERASE] = CWERASE; #else /* CWERASE */ attr.c_cc[VWERASE] = 0; #endif /* CWERASE */ #endif /* VWERASE */ #ifdef VLNEXT #ifdef CLNEXT attr.c_cc[VLNEXT] = CLNEXT; #else /* CLNEXT */ attr.c_cc[VLNEXT] = 0; #endif /* CLNEXT */ #endif /* VLNEXT */ attr.c_lflag |= ICANON; /* enable canonical input processing */ attr.c_lflag &= ~ISIG; /* disable INTR, QUIT,& SUSP signals */ attr.c_lflag |= (ECHO | ECHOE); /* enable echo and erase */ #ifdef ONLCR /* POSIX does not specify any output processing flags, but the usage below is SVID compliant and is generally portable to modern versions of UNIX. */ attr.c_oflag |= ONLCR; /* map CR to CRNL on output */ #endif #ifdef ICRNL attr.c_iflag |= ICRNL; #endif /* ICRNL */ attr.c_oflag |= OPOST; attr.c_lflag |= ICANON; /* enable canonical input */ attr.c_lflag |= ECHO; attr.c_lflag |= ECHOE; /* enable ERASE character */ attr.c_lflag |= ECHOK; /* enable KILL to delete line */ attr.c_cflag |= HUPCL; /* hangup on close */ /* Set revised termio attributes */ if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &attr)) return (-1); atexit(catchexit); tty = ttyname(0); if (tty == (char *) 0 || *tty == '\0') tty = "UNKNOWN"; /* was: "/dev/tty??" */ #if HAVE_SETVBUF && defined(_IONBF) #if SETVBUF_REVERSED setvbuf(stdout, _IONBF, NULL, 0); setvbuf(stderr, _IONBF, NULL, 0); #else /* SETVBUF_REVERSED */ setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); #endif /* SETVBUF_REVERSED */ #endif /* HAVE_SETVBUF && defined(_IONBF) */ #ifdef DEBUG syslog(LOG_DEBUG, "tty = %s", tty); #endif /* DEBUG */ #ifdef HAVE_LOGIN_ENVFILE { FILE *f; if (f = fopen(HAVE_LOGIN_ENVFILE, "r")) { char line[128], *c, *c2; while(fgets(line, sizeof(line)-1, f)) { c = line; while(*c && (isalnum(*c) || (*c == '_'))) c++; if (*c == '=') { *(c++) = 0; if (c2 = strchr(c, ';')) *c2 = 0; if (c2 = strchr(c, '\n')) *c2 = 0; if (c2 = strchr(c, ' ')) continue; if (c2 = strchr(c, '\t')) continue; if (!strcmp(line, "TZ")) continue; if (setenv(line, c, 1) < 0) { fprintf(stderr, "setenv() failed -- environment full?\n"); break; } } } fclose(f); } } #endif /* HAVE_LOGIN_ENVFILE */ t = 0; invalid = TRUE; af_pwok = opieaccessfile(host); if (name[0]) if (name[0] == '-') { fprintf(stderr, "User names can't start with '-'.\n"); syslog(LOG_AUTH, "Attempt to use invalid username: %s.", name); exit(1); } else invalid = lookupuser(); do { /* If remote login take given name, otherwise prompt user for something. */ if (invalid && !name[0]) { getloginname(); invalid = lookupuser(); authsok = 0; } #ifdef DEBUG syslog(LOG_DEBUG, "login name is +%s+, of length %d, [0] = %d", name, strlen(name), name[0]); #endif /* DEBUG */ if (fflag) { uid = getuid(); if (uid != 0 && uid != thisuser.pw_uid) fflag = 0; /* Disallow automatic login for root. */ if (thisuser.pw_uid == 0) fflag = 0; } if (feof(stdin)) exit(0); /* If no remote login authentication and a password exists for this user, prompt for and verify a password. */ if (!fflag && (rflag < 1) && *thisuser.pw_passwd) { #ifdef DEBUG syslog(LOG_DEBUG, "login name is +%s+, of length %d, [0] = %d\n", name, strlen(name), name[0]); #endif /* DEBUG */ /* Attempt a one-time password challenge */ i = opiechallenge(&opie, name, opieprompt); need_opieverify = TRUE; if ((i < 0) || (i > 1)) { syslog(LOG_ERR, "error: opiechallenge() returned %d, errno=%d!\n", i, errno); } else { printf("%s\n", opieprompt); authsok |= 1; } if (!memcmp(&thisuser, &nouser, sizeof(thisuser))) if (host[0]) syslog(LOG_WARNING, "Invalid login attempt for %s on %s from %s.", name, tty, host); else syslog(LOG_WARNING, "Invalid login attempt for %s on %s.", name, tty); if (af_pwok && opiealways(thisuser.pw_dir)) authsok |= 2; #if DEBUG syslog(LOG_DEBUG, "af_pwok = %d, authsok = %d", af_pwok, authsok); #endif /* DEBUG */ if (!authsok) syslog(LOG_ERR, "no authentication methods are available for %s!", name); #if NEW_PROMPTS if ((authsok & 1) || !authsok) printf("Response"); if (((authsok & 3) == 3) || !authsok) printf(" or "); if ((authsok & 2) || !authsok) printf("Password"); printf(": "); fflush(stdout); if (!opiereadpass(buf, sizeof(buf), !(authsok & 2))) invalid = TRUE; #else /* NEW_PROMPTS */ if ((authsok & 3) == 1) printf("(OTP response required)\n"); printf("Password:"); fflush(stdout); if (!opiereadpass(buf, sizeof(buf), 0)) invalid = TRUE; #endif /* NEW_PROMPTS */ if (!buf[0] && (authsok & 1)) { authsok &= ~2; /* Null line entered, so display appropriate prompt & flush current data. */ #if NEW_PROMPTS printf("Response: "); #else /* NEW_PROMPTS */ printf(" (echo on)\nPassword:"); #endif /* NEW_PROMPTS */ if (!opiereadpass(buf, sizeof(buf), 1)) invalid = TRUE; } if (authsok & 1) { i = opiegetsequence(&opie); opiepassed = !opieverify(&opie, buf); need_opieverify = 0; #ifdef DEBUG syslog(LOG_DEBUG, "opiepassed = %d", opiepassed); #endif /* DEBUG */ } if (!invalid) { if ((authsok & 1) && opiepassed) { if (i < 10) { printf("Warning: Re-initialize your OTP information"); if (i < 5) printf(" NOW!"); printf("\n"); } } else { if (authsok & 2) { pp = crypt(buf, thisuser.pw_passwd); invalid = strcmp(pp, thisuser.pw_passwd); } else invalid = TRUE; } } } /* If user not super-user, check for logins disabled. */ if (thisuser.pw_uid) { if (nlfd = fopen(_PATH_NOLOGIN, "r")) { while ((c = getc(nlfd)) != EOF) putchar(c); fflush(stdout); sleep(5); exit(0); } } /* If valid so far and root is logging in, see if root logins on this terminal are permitted. */ if (!invalid && !thisuser.pw_uid && !rootterm(tty)) { if (host[0]) syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s FROM %.*s", tty, HMAX, host); else syslog(LOG_CRIT, "ROOT LOGIN REFUSED ON %s", tty); invalid = TRUE; } /* If invalid, then log failure attempt data to appropriate system logfiles and close the connection. */ if (invalid) { printf("Login incorrect\n"); if (host[0]) syslog(LOG_ERR, "LOGIN FAILURE ON %s FROM %.*s, %.*s", tty, HMAX, host, sizeof(name), name); else syslog(LOG_ERR, "LOGIN FAILURE ON %s, %.*s", tty, sizeof(name), name); if (++t >= 5) exit(1); } if (*thisuser.pw_shell == '\0') thisuser.pw_shell = "/bin/sh"; /* Remote login invalid must have been because of a restriction of some sort, no extra chances. */ if (invalid) { if (!usererr) exit(1); name[0] = 0; } } while (invalid); /* Committed to login -- turn off timeout */ alarm(0); #ifdef QUOTA if (quota(Q_SETUID, thisuser.pw_uid, 0, 0) < 0 && errno != EINVAL) { if (errno == EUSERS) printf("%s.\n%s.\n", "Too many users logged on already", "Try again later"); else if (errno == EPROCLIM) printf("You have too many processes running.\n"); else perror("quota (Q_SETUID)"); sleep(5); exit(0); } #endif if (opielogin(tty, name, host)) syslog(LOG_ERR, "can't record login: tty %s, name %s, host %s", tty, name, host); quietlog = !access(QUIET_LOGIN_FILE, F_OK); #if HAVE_LASTLOG_H { int f; if ((f = open(lastlog, O_RDWR)) >= 0) { struct lastlog ll; lseek(f, (long)thisuser.pw_uid * sizeof(struct lastlog), 0); if ((sizeof(ll) == read(f, (char *) &ll, sizeof(ll))) && (ll.ll_time != 0) && (!quietlog)) { printf("Last login: %.*s ", 24 - 5, (char *) ctime(&ll.ll_time)); if (*ll.ll_host != '\0') printf("from %.*s\n", sizeof(ll.ll_host), ll.ll_host); else printf("on %.*s\n", sizeof(ll.ll_line), ll.ll_line); } lseek(f, (long)thisuser.pw_uid * sizeof(struct lastlog), 0); time(&ll.ll_time); if (!strncmp(tty, "/dev/", 5)) opiestrncpy(ll.ll_line, tty + 5, sizeof(ll.ll_line)); else opiestrncpy(ll.ll_line, tty, sizeof(ll.ll_line)); opiestrncpy(ll.ll_host, host, sizeof(ll.ll_host)); write(f, (char *) &ll, sizeof ll); close(f); } } #endif /* HAVE_LASTLOG_H */ chown(tty, thisuser.pw_uid, TTYGID(thisuser.pw_gid)); #ifdef TIOCSWINSZ /* POSIX does not specify any interface to set/get window sizes, so this is not portable. It should work on most recent BSDish systems and the defines should protect it on older System Vish systems. It does work under Solaris 2.4, though it isn't clear how many other SVR4 systems support it. I'd be interested in hearing of a more portable approach. rja */ if (!hflag && !rflag) ioctl(0, TIOCSWINSZ, &win); /* set window size to 0,0,0,0 */ #endif chmod(tty, 0622); setgid(thisuser.pw_gid); initgroups(name, thisuser.pw_gid); #ifdef QUOTA quota(Q_DOWARN, thisuser.pw_uid, (dev_t) - 1, 0); #endif #ifdef PERMSFILE home = thisuser.pw_dir; permsfile(name, tty, thisuser.pw_uid, thisuser.pw_gid); fflush(stderr); #endif /* PERMSFILE */ setuid(thisuser.pw_uid); /* destroy environment unless user has asked to preserve it */ if (!pflag) environ = envinit; setenv("HOME", thisuser.pw_dir, 1); setenv("SHELL", thisuser.pw_shell, 1); if (chdir(thisuser.pw_dir) < 0) { #if DEBUG syslog(LOG_DEBUG, "chdir(%s): %s(%d)", thisuser.pw_dir, strerror(errno), errno); #endif /* DEBUG */ if (chdir("/") < 0) { printf("No directory!\n"); invalid = TRUE; } else { printf("No directory! %s\n", "Logging in with HOME=/"); strcpy(thisuser.pw_dir, "/"); } } if (!term[0]) { #if HAVE_GETTTYNAM /* * The getttynam() call and the ttyent structure first appeared in 4.3 BSD. * They are not portable to System V systems such as Solaris 2.x. * rja */ register struct ttyent *t; register char *c; if (c = strrchr(tty, '/')) c++; else c = tty; if (t = getttynam(c)) opiestrncpy(term, t->ty_type, sizeof(term)); else #endif /* HAVE_GETTTYNAM */ strcpy(term, "unknown"); } setenv("USER", name, 1); setenv("LOGNAME", name, 1); setenv("PATH", DEFAULT_PATH, 0); if (term[0]) { #ifdef DEBUG syslog(LOG_DEBUG, "setting TERM=%s", term); #endif /* DEBUG */ setenv("TERM", term, 1); } #ifdef HAVE_LOGIN_ENVFILE { FILE *f; if (f = fopen(HAVE_LOGIN_ENVFILE, "r")) { char line[128], *c, *c2; while(fgets(line, sizeof(line)-1, f)) { c = line; while(*c && (isalnum(*c) || (*c == '_'))) c++; if (*c == '=') { *(c++) = 0; if (c2 = strchr(c, ';')) *c2 = 0; if (c2 = strchr(c, '\n')) *c2 = 0; if (c2 = strchr(c, ' ')) continue; if (c2 = strchr(c, '\t')) continue; if (setenv(line, c, 0) < 0) { fprintf(stderr, "setenv() failed -- environment full?\n"); break; } } } fclose(f); } } #endif /* HAVE_LOGIN_ENVFILE */ if ((namep = strrchr(thisuser.pw_shell, '/')) == NULL) namep = thisuser.pw_shell; else namep++; strcat(minusnam, namep); if (tty[sizeof("tty") - 1] == 'd') syslog(LOG_INFO, "DIALUP %s, %s", tty, name); if (!thisuser.pw_uid) if (host[0]) syslog(LOG_NOTICE, "ROOT LOGIN %s FROM %.*s", tty, HMAX, host); else syslog(LOG_NOTICE, "ROOT LOGIN %s", tty); #if !HAVE_MOTD_IN_PROFILE if (!quietlog) { FILE *mf; register c; signal(SIGINT, catch); if ((mf = fopen(MOTD_FILE, "r")) != NULL) { while ((c = getc(mf)) != EOF && !stopmotd) putchar(c); fclose(mf); } signal(SIGINT, SIG_IGN); } #endif /* !HAVE_MOTD_IN_PROFILE */ #if !HAVE_MAILCHECK_IN_PROFILE if (!quietlog) { struct stat st; char buf[128]; int len; opiestrncpy(buf, PATH_MAIL, sizeof(buf) - 2); len = strlen(buf); if (*(buf + len - 1) != '/') { *(buf + len) = '/'; *(buf + len + 1) = 0; } strcat(buf, name); #if DEBUG syslog(LOG_DEBUG, "statting %s", buf); #endif /* DEBUG */ if (!stat(buf, &st) && st.st_size) printf("You have %smail.\n", (st.st_mtime > st.st_atime) ? "new " : ""); } #endif /* !HAVE_MAILCHECK_IN_PROFILE */ signal(SIGALRM, SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGINT, SIG_DFL); signal(SIGTSTP, SIG_IGN); attr.c_lflag |= (ISIG | IEXTEN); catchexit(); execlp(thisuser.pw_shell, minusnam, 0); perror(thisuser.pw_shell); printf("No shell\n"); exit(0); }
550713.c
/* Write Python objects to files and read them back. This is primarily intended for writing and reading compiled Python code, even though dicts, lists, sets and frozensets, not commonly seen in code objects, are supported. Version 3 of this protocol properly supports circular links and sharing. */ #define PY_SSIZE_T_CLEAN #include "Python.h" #include "longintrepr.h" #include "code.h" #include "marshal.h" /* High water mark to determine when the marshalled object is dangerously deep * and risks coring the interpreter. When the object stack gets this deep, * raise an exception instead of continuing. * On Windows debug builds, reduce this value. */ #if defined(MS_WINDOWS) && defined(_DEBUG) #define MAX_MARSHAL_STACK_DEPTH 1500 #else #define MAX_MARSHAL_STACK_DEPTH 2000 #endif #define TYPE_NULL '0' #define TYPE_NONE 'N' #define TYPE_FALSE 'F' #define TYPE_TRUE 'T' #define TYPE_STOPITER 'S' #define TYPE_ELLIPSIS '.' #define TYPE_INT 'i' #define TYPE_FLOAT 'f' #define TYPE_BINARY_FLOAT 'g' #define TYPE_COMPLEX 'x' #define TYPE_BINARY_COMPLEX 'y' #define TYPE_LONG 'l' #define TYPE_STRING 's' #define TYPE_INTERNED 't' #define TYPE_REF 'r' #define TYPE_TUPLE '(' #define TYPE_LIST '[' #define TYPE_DICT '{' #define TYPE_CODE 'c' #define TYPE_UNICODE 'u' #define TYPE_UNKNOWN '?' #define TYPE_SET '<' #define TYPE_FROZENSET '>' #define FLAG_REF '\x80' /* with a type, add obj to index */ #define TYPE_ASCII 'a' #define TYPE_ASCII_INTERNED 'A' #define TYPE_SMALL_TUPLE ')' #define TYPE_SHORT_ASCII 'z' #define TYPE_SHORT_ASCII_INTERNED 'Z' #define WFERR_OK 0 #define WFERR_UNMARSHALLABLE 1 #define WFERR_NESTEDTOODEEP 2 #define WFERR_NOMEMORY 3 typedef struct { FILE *fp; int error; /* see WFERR_* values */ int depth; /* If fp == NULL, the following are valid: */ PyObject *readable; /* Stream-like object being read from */ PyObject *str; PyObject *current_filename; char *ptr; char *end; char *buf; Py_ssize_t buf_size; PyObject *refs; /* dict on marshal, list on unmarshal */ int version; } WFILE; #define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \ else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \ else w_more((c), p) static void w_more(char c, WFILE *p) { Py_ssize_t size, newsize; if (p->str == NULL) return; /* An error already occurred */ size = PyBytes_Size(p->str); newsize = size + size + 1024; if (newsize > 32*1024*1024) { newsize = size + (size >> 3); /* 12.5% overallocation */ } if (_PyBytes_Resize(&p->str, newsize) != 0) { p->ptr = p->end = NULL; } else { p->ptr = PyBytes_AS_STRING((PyBytesObject *)p->str) + size; p->end = PyBytes_AS_STRING((PyBytesObject *)p->str) + newsize; *p->ptr++ = c; } } static void w_string(const char *s, Py_ssize_t n, WFILE *p) { if (p->fp != NULL) { fwrite(s, 1, n, p->fp); } else { while (--n >= 0) { w_byte(*s, p); s++; } } } static void w_short(int x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); } static void w_long(long x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); w_byte((char)((x>>16) & 0xff), p); w_byte((char)((x>>24) & 0xff), p); } #define SIZE32_MAX 0x7FFFFFFF #if SIZEOF_SIZE_T > 4 # define W_SIZE(n, p) do { \ if ((n) > SIZE32_MAX) { \ (p)->depth--; \ (p)->error = WFERR_UNMARSHALLABLE; \ return; \ } \ w_long((long)(n), p); \ } while(0) #else # define W_SIZE w_long #endif static void w_pstring(const char *s, Py_ssize_t n, WFILE *p) { W_SIZE(n, p); w_string(s, n, p); } static void w_short_pstring(const char *s, Py_ssize_t n, WFILE *p) { w_byte(Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char), p); w_string(s, n, p); } /* We assume that Python ints are stored internally in base some power of 2**15; for the sake of portability we'll always read and write them in base exactly 2**15. */ #define PyLong_MARSHAL_SHIFT 15 #define PyLong_MARSHAL_BASE ((short)1 << PyLong_MARSHAL_SHIFT) #define PyLong_MARSHAL_MASK (PyLong_MARSHAL_BASE - 1) #if PyLong_SHIFT % PyLong_MARSHAL_SHIFT != 0 #error "PyLong_SHIFT must be a multiple of PyLong_MARSHAL_SHIFT" #endif #define PyLong_MARSHAL_RATIO (PyLong_SHIFT / PyLong_MARSHAL_SHIFT) #define W_TYPE(t, p) do { \ w_byte((t) | flag, (p)); \ } while(0) static void w_PyLong(const PyLongObject *ob, char flag, WFILE *p) { Py_ssize_t i, j, n, l; digit d; W_TYPE(TYPE_LONG, p); if (Py_SIZE(ob) == 0) { w_long((long)0, p); return; } /* set l to number of base PyLong_MARSHAL_BASE digits */ n = Py_ABS(Py_SIZE(ob)); l = (n-1) * PyLong_MARSHAL_RATIO; d = ob->ob_digit[n-1]; assert(d != 0); /* a PyLong is always normalized */ do { d >>= PyLong_MARSHAL_SHIFT; l++; } while (d != 0); if (l > SIZE32_MAX) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p); for (i=0; i < n-1; i++) { d = ob->ob_digit[i]; for (j=0; j < PyLong_MARSHAL_RATIO; j++) { w_short(d & PyLong_MARSHAL_MASK, p); d >>= PyLong_MARSHAL_SHIFT; } assert (d == 0); } d = ob->ob_digit[n-1]; do { w_short(d & PyLong_MARSHAL_MASK, p); d >>= PyLong_MARSHAL_SHIFT; } while (d != 0); } static int w_ref(PyObject *v, char *flag, WFILE *p) { PyObject *id; PyObject *idx; if (p->version < 3 || p->refs == NULL) return 0; /* not writing object references */ /* if it has only one reference, it definitely isn't shared */ if (Py_REFCNT(v) == 1) return 0; id = PyLong_FromVoidPtr((void*)v); if (id == NULL) goto err; idx = PyDict_GetItem(p->refs, id); if (idx != NULL) { /* write the reference index to the stream */ long w = PyLong_AsLong(idx); Py_DECREF(id); if (w == -1 && PyErr_Occurred()) { goto err; } /* we don't store "long" indices in the dict */ assert(0 <= w && w <= 0x7fffffff); w_byte(TYPE_REF, p); w_long(w, p); return 1; } else { int ok; Py_ssize_t s = PyDict_Size(p->refs); /* we don't support long indices */ if (s >= 0x7fffffff) { PyErr_SetString(PyExc_ValueError, "too many objects"); goto err; } idx = PyLong_FromSsize_t(s); ok = idx && PyDict_SetItem(p->refs, id, idx) == 0; Py_DECREF(id); Py_XDECREF(idx); if (!ok) goto err; *flag |= FLAG_REF; return 0; } err: p->error = WFERR_UNMARSHALLABLE; return 1; } static void w_complex_object(PyObject *v, char flag, WFILE *p); static void w_object(PyObject *v, WFILE *p) { char flag = '\0'; p->depth++; if (p->depth > MAX_MARSHAL_STACK_DEPTH) { p->error = WFERR_NESTEDTOODEEP; } else if (v == NULL) { w_byte(TYPE_NULL, p); } else if (v == Py_None) { w_byte(TYPE_NONE, p); } else if (v == PyExc_StopIteration) { w_byte(TYPE_STOPITER, p); } else if (v == Py_Ellipsis) { w_byte(TYPE_ELLIPSIS, p); } else if (v == Py_False) { w_byte(TYPE_FALSE, p); } else if (v == Py_True) { w_byte(TYPE_TRUE, p); } else if (!w_ref(v, &flag, p)) w_complex_object(v, flag, p); p->depth--; } static void w_complex_object(PyObject *v, char flag, WFILE *p) { Py_ssize_t i, n; if (PyLong_CheckExact(v)) { long x = PyLong_AsLong(v); if ((x == -1) && PyErr_Occurred()) { PyLongObject *ob = (PyLongObject *)v; PyErr_Clear(); w_PyLong(ob, flag, p); } else { #if SIZEOF_LONG > 4 long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31); if (y && y != -1) { /* Too large for TYPE_INT */ w_PyLong((PyLongObject*)v, flag, p); } else #endif { W_TYPE(TYPE_INT, p); w_long(x, p); } } } else if (PyFloat_CheckExact(v)) { if (p->version > 1) { unsigned char buf[8]; if (_PyFloat_Pack8(PyFloat_AsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_BINARY_FLOAT, p); w_string((char*)buf, 8, p); } else { char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); W_TYPE(TYPE_FLOAT, p); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); } } else if (PyComplex_CheckExact(v)) { if (p->version > 1) { unsigned char buf[8]; if (_PyFloat_Pack8(PyComplex_RealAsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_BINARY_COMPLEX, p); w_string((char*)buf, 8, p); if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v), buf, 1) < 0) { p->error = WFERR_UNMARSHALLABLE; return; } w_string((char*)buf, 8, p); } else { char *buf; W_TYPE(TYPE_COMPLEX, p); buf = PyOS_double_to_string(PyComplex_RealAsDouble(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v), 'g', 17, 0, NULL); if (!buf) { p->error = WFERR_NOMEMORY; return; } n = strlen(buf); w_byte((int)n, p); w_string(buf, n, p); PyMem_Free(buf); } } else if (PyBytes_CheckExact(v)) { W_TYPE(TYPE_STRING, p); w_pstring(PyBytes_AS_STRING(v), PyBytes_GET_SIZE(v), p); } else if (PyUnicode_CheckExact(v)) { if (p->version >= 4 && PyUnicode_IS_ASCII(v)) { int is_short = PyUnicode_GET_LENGTH(v) < 256; if (is_short) { if (PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_SHORT_ASCII_INTERNED, p); else W_TYPE(TYPE_SHORT_ASCII, p); w_short_pstring((char *) PyUnicode_1BYTE_DATA(v), PyUnicode_GET_LENGTH(v), p); } else { if (PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_ASCII_INTERNED, p); else W_TYPE(TYPE_ASCII, p); w_pstring((char *) PyUnicode_1BYTE_DATA(v), PyUnicode_GET_LENGTH(v), p); } } else { PyObject *utf8; utf8 = PyUnicode_AsEncodedString(v, "utf8", "surrogatepass"); if (utf8 == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } if (p->version >= 3 && PyUnicode_CHECK_INTERNED(v)) W_TYPE(TYPE_INTERNED, p); else W_TYPE(TYPE_UNICODE, p); w_pstring(PyBytes_AS_STRING(utf8), PyBytes_GET_SIZE(utf8), p); Py_DECREF(utf8); } } else if (PyTuple_CheckExact(v)) { n = PyTuple_Size(v); if (p->version >= 4 && n < 256) { W_TYPE(TYPE_SMALL_TUPLE, p); w_byte((unsigned char)n, p); } else { W_TYPE(TYPE_TUPLE, p); W_SIZE(n, p); } for (i = 0; i < n; i++) { w_object(PyTuple_GET_ITEM(v, i), p); } } else if (PyList_CheckExact(v)) { W_TYPE(TYPE_LIST, p); n = PyList_GET_SIZE(v); W_SIZE(n, p); for (i = 0; i < n; i++) { w_object(PyList_GET_ITEM(v, i), p); } } else if (PyDict_CheckExact(v)) { Py_ssize_t pos; PyObject *key, *value; W_TYPE(TYPE_DICT, p); /* This one is NULL object terminated! */ pos = 0; while (PyDict_Next(v, &pos, &key, &value)) { w_object(key, p); w_object(value, p); } w_object((PyObject *)NULL, p); } else if (PyAnySet_CheckExact(v)) { PyObject *value, *it; if (PyObject_TypeCheck(v, &PySet_Type)) W_TYPE(TYPE_SET, p); else W_TYPE(TYPE_FROZENSET, p); n = PyObject_Size(v); if (n == -1) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } W_SIZE(n, p); it = PyObject_GetIter(v); if (it == NULL) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } while ((value = PyIter_Next(it)) != NULL) { w_object(value, p); Py_DECREF(value); } Py_DECREF(it); if (PyErr_Occurred()) { p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } } else if (PyCode_Check(v)) { PyCodeObject *co = (PyCodeObject *)v; W_TYPE(TYPE_CODE, p); w_long(co->co_argcount, p); w_long(co->co_kwonlyargcount, p); w_long(co->co_nlocals, p); w_long(co->co_stacksize, p); w_long(co->co_flags, p); w_object(co->co_code, p); w_object(co->co_consts, p); w_object(co->co_names, p); w_object(co->co_varnames, p); w_object(co->co_freevars, p); w_object(co->co_cellvars, p); w_object(co->co_filename, p); w_object(co->co_name, p); w_long(co->co_firstlineno, p); w_object(co->co_lnotab, p); } else if (PyObject_CheckBuffer(v)) { /* Write unknown buffer-style objects as a string */ Py_buffer view; if (PyObject_GetBuffer(v, &view, PyBUF_SIMPLE) != 0) { w_byte(TYPE_UNKNOWN, p); p->depth--; p->error = WFERR_UNMARSHALLABLE; return; } W_TYPE(TYPE_STRING, p); w_pstring(view.buf, view.len, p); PyBuffer_Release(&view); } else { W_TYPE(TYPE_UNKNOWN, p); p->error = WFERR_UNMARSHALLABLE; } } /* version currently has no effect for writing ints. */ void PyMarshal_WriteLongToFile(long x, FILE *fp, int version) { WFILE wf; wf.fp = fp; wf.error = WFERR_OK; wf.depth = 0; wf.refs = NULL; wf.version = version; w_long(x, &wf); } void PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version) { WFILE wf; wf.fp = fp; wf.error = WFERR_OK; wf.depth = 0; if (version >= 3) { if ((wf.refs = PyDict_New()) == NULL) return; /* caller mush check PyErr_Occurred() */ } else wf.refs = NULL; wf.version = version; w_object(x, &wf); Py_XDECREF(wf.refs); } typedef WFILE RFILE; /* Same struct with different invariants */ static char * r_string(Py_ssize_t n, RFILE *p) { Py_ssize_t read = -1; if (p->ptr != NULL) { /* Fast path for loads() */ char *res = p->ptr; Py_ssize_t left = p->end - p->ptr; if (left < n) { PyErr_SetString(PyExc_EOFError, "marshal data too short"); return NULL; } p->ptr += n; return res; } if (p->buf == NULL) { p->buf = PyMem_MALLOC(n); if (p->buf == NULL) { PyErr_NoMemory(); return NULL; } p->buf_size = n; } else if (p->buf_size < n) { p->buf = PyMem_REALLOC(p->buf, n); if (p->buf == NULL) { PyErr_NoMemory(); return NULL; } p->buf_size = n; } if (!p->readable) { assert(p->fp != NULL); read = fread(p->buf, 1, n, p->fp); } else { _Py_IDENTIFIER(readinto); PyObject *res, *mview; Py_buffer buf; if (PyBuffer_FillInfo(&buf, NULL, p->buf, n, 0, PyBUF_CONTIG) == -1) return NULL; mview = PyMemoryView_FromBuffer(&buf); if (mview == NULL) return NULL; res = _PyObject_CallMethodId(p->readable, &PyId_readinto, "N", mview); if (res != NULL) { read = PyNumber_AsSsize_t(res, PyExc_ValueError); Py_DECREF(res); } } if (read != n) { if (!PyErr_Occurred()) { if (read > n) PyErr_Format(PyExc_ValueError, "read() returned too much data: " "%zd bytes requested, %zd returned", n, read); else PyErr_SetString(PyExc_EOFError, "EOF read where not expected"); } return NULL; } return p->buf; } static int r_byte(RFILE *p) { int c = EOF; if (p->ptr != NULL) { if (p->ptr < p->end) c = (unsigned char) *p->ptr++; return c; } if (!p->readable) { assert(p->fp); c = getc(p->fp); } else { char *ptr = r_string(1, p); if (ptr != NULL) c = *(unsigned char *) ptr; } return c; } static int r_short(RFILE *p) { short x = -1; unsigned char *buffer; buffer = (unsigned char *) r_string(2, p); if (buffer != NULL) { x = buffer[0]; x |= buffer[1] << 8; /* Sign-extension, in case short greater than 16 bits */ x |= -(x & 0x8000); } return x; } static long r_long(RFILE *p) { long x = -1; unsigned char *buffer; buffer = (unsigned char *) r_string(4, p); if (buffer != NULL) { x = buffer[0]; x |= (long)buffer[1] << 8; x |= (long)buffer[2] << 16; x |= (long)buffer[3] << 24; #if SIZEOF_LONG > 4 /* Sign extension for 64-bit machines */ x |= -(x & 0x80000000L); #endif } return x; } static PyObject * r_PyLong(RFILE *p) { PyLongObject *ob; long n, size, i; int j, md, shorts_in_top_digit; digit d; n = r_long(p); if (PyErr_Occurred()) return NULL; if (n == 0) return (PyObject *)_PyLong_New(0); if (n < -SIZE32_MAX || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (long size out of range)"); return NULL; } size = 1 + (Py_ABS(n) - 1) / PyLong_MARSHAL_RATIO; shorts_in_top_digit = 1 + (Py_ABS(n) - 1) % PyLong_MARSHAL_RATIO; ob = _PyLong_New(size); if (ob == NULL) return NULL; Py_SIZE(ob) = n > 0 ? size : -size; for (i = 0; i < size-1; i++) { d = 0; for (j=0; j < PyLong_MARSHAL_RATIO; j++) { md = r_short(p); if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; d += (digit)md << j*PyLong_MARSHAL_SHIFT; } ob->ob_digit[i] = d; } d = 0; for (j=0; j < shorts_in_top_digit; j++) { md = r_short(p); if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } if (md < 0 || md > PyLong_MARSHAL_BASE) goto bad_digit; /* topmost marshal digit should be nonzero */ if (md == 0 && j == shorts_in_top_digit - 1) { Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (unnormalized long data)"); return NULL; } d += (digit)md << j*PyLong_MARSHAL_SHIFT; } if (PyErr_Occurred()) { Py_DECREF(ob); return NULL; } /* top digit should be nonzero, else the resulting PyLong won't be normalized */ ob->ob_digit[size-1] = d; return (PyObject *)ob; bad_digit: Py_DECREF(ob); PyErr_SetString(PyExc_ValueError, "bad marshal data (digit out of range in long)"); return NULL; } /* allocate the reflist index for a new object. Return -1 on failure */ static Py_ssize_t r_ref_reserve(int flag, RFILE *p) { if (flag) { /* currently only FLAG_REF is defined */ Py_ssize_t idx = PyList_GET_SIZE(p->refs); if (idx >= 0x7ffffffe) { PyErr_SetString(PyExc_ValueError, "bad marshal data (index list too large)"); return -1; } if (PyList_Append(p->refs, Py_None) < 0) return -1; return idx; } else return 0; } /* insert the new object 'o' to the reflist at previously * allocated index 'idx'. * 'o' can be NULL, in which case nothing is done. * if 'o' was non-NULL, and the function succeeds, 'o' is returned. * if 'o' was non-NULL, and the function fails, 'o' is released and * NULL returned. This simplifies error checking at the call site since * a single test for NULL for the function result is enough. */ static PyObject * r_ref_insert(PyObject *o, Py_ssize_t idx, int flag, RFILE *p) { if (o != NULL && flag) { /* currently only FLAG_REF is defined */ PyObject *tmp = PyList_GET_ITEM(p->refs, idx); Py_INCREF(o); PyList_SET_ITEM(p->refs, idx, o); Py_DECREF(tmp); } return o; } /* combination of both above, used when an object can be * created whenever it is seen in the file, as opposed to * after having loaded its sub-objects. */ static PyObject * r_ref(PyObject *o, int flag, RFILE *p) { assert(flag & FLAG_REF); if (o == NULL) return NULL; if (PyList_Append(p->refs, o) < 0) { Py_DECREF(o); /* release the new object */ return NULL; } return o; } static PyObject * r_object(RFILE *p) { /* NULL is a valid return value, it does not necessarily means that an exception is set. */ PyObject *v, *v2; Py_ssize_t idx = 0; long i, n; int type, code = r_byte(p); int flag, is_interned = 0; PyObject *retval = NULL; if (code == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); return NULL; } p->depth++; if (p->depth > MAX_MARSHAL_STACK_DEPTH) { p->depth--; PyErr_SetString(PyExc_ValueError, "recursion limit exceeded"); return NULL; } flag = code & FLAG_REF; type = code & ~FLAG_REF; #define R_REF(O) do{\ if (flag) \ O = r_ref(O, flag, p);\ } while (0) switch (type) { case TYPE_NULL: break; case TYPE_NONE: Py_INCREF(Py_None); retval = Py_None; break; case TYPE_STOPITER: Py_INCREF(PyExc_StopIteration); retval = PyExc_StopIteration; break; case TYPE_ELLIPSIS: Py_INCREF(Py_Ellipsis); retval = Py_Ellipsis; break; case TYPE_FALSE: Py_INCREF(Py_False); retval = Py_False; break; case TYPE_TRUE: Py_INCREF(Py_True); retval = Py_True; break; case TYPE_INT: n = r_long(p); retval = PyErr_Occurred() ? NULL : PyLong_FromLong(n); R_REF(retval); break; case TYPE_LONG: retval = r_PyLong(p); R_REF(retval); break; case TYPE_FLOAT: { char buf[256], *ptr; double dx; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; dx = PyOS_string_to_double(buf, NULL, NULL); if (dx == -1.0 && PyErr_Occurred()) break; retval = PyFloat_FromDouble(dx); R_REF(retval); break; } case TYPE_BINARY_FLOAT: { unsigned char *buf; double x; buf = (unsigned char *) r_string(8, p); if (buf == NULL) break; x = _PyFloat_Unpack8(buf, 1); if (x == -1.0 && PyErr_Occurred()) break; retval = PyFloat_FromDouble(x); R_REF(retval); break; } case TYPE_COMPLEX: { char buf[256], *ptr; Py_complex c; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; c.real = PyOS_string_to_double(buf, NULL, NULL); if (c.real == -1.0 && PyErr_Occurred()) break; n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } ptr = r_string(n, p); if (ptr == NULL) break; memcpy(buf, ptr, n); buf[n] = '\0'; c.imag = PyOS_string_to_double(buf, NULL, NULL); if (c.imag == -1.0 && PyErr_Occurred()) break; retval = PyComplex_FromCComplex(c); R_REF(retval); break; } case TYPE_BINARY_COMPLEX: { unsigned char *buf; Py_complex c; buf = (unsigned char *) r_string(8, p); if (buf == NULL) break; c.real = _PyFloat_Unpack8(buf, 1); if (c.real == -1.0 && PyErr_Occurred()) break; buf = (unsigned char *) r_string(8, p); if (buf == NULL) break; c.imag = _PyFloat_Unpack8(buf, 1); if (c.imag == -1.0 && PyErr_Occurred()) break; retval = PyComplex_FromCComplex(c); R_REF(retval); break; } case TYPE_STRING: { char *ptr; n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)"); break; } v = PyBytes_FromStringAndSize((char *)NULL, n); if (v == NULL) break; ptr = r_string(n, p); if (ptr == NULL) { Py_DECREF(v); break; } memcpy(PyBytes_AS_STRING(v), ptr, n); retval = v; R_REF(retval); break; } case TYPE_ASCII_INTERNED: is_interned = 1; case TYPE_ASCII: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); break; } goto _read_ascii; case TYPE_SHORT_ASCII_INTERNED: is_interned = 1; case TYPE_SHORT_ASCII: n = r_byte(p); if (n == EOF) { PyErr_SetString(PyExc_EOFError, "EOF read where object expected"); break; } _read_ascii: { char *ptr; ptr = r_string(n, p); if (ptr == NULL) break; v = PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, ptr, n); if (v == NULL) break; if (is_interned) PyUnicode_InternInPlace(&v); retval = v; R_REF(retval); break; } case TYPE_INTERNED: is_interned = 1; case TYPE_UNICODE: { char *buffer; n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)"); break; } if (n != 0) { buffer = r_string(n, p); if (buffer == NULL) break; v = PyUnicode_DecodeUTF8(buffer, n, "surrogatepass"); } else { v = PyUnicode_New(0, 0); } if (v == NULL) break; if (is_interned) PyUnicode_InternInPlace(&v); retval = v; R_REF(retval); break; } case TYPE_SMALL_TUPLE: n = (unsigned char) r_byte(p); if (PyErr_Occurred()) break; goto _read_tuple; case TYPE_TUPLE: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)"); break; } _read_tuple: v = PyTuple_New(n); R_REF(v); if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for tuple"); Py_DECREF(v); v = NULL; break; } PyTuple_SET_ITEM(v, i, v2); } retval = v; break; case TYPE_LIST: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)"); break; } v = PyList_New(n); R_REF(v); if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for list"); Py_DECREF(v); v = NULL; break; } PyList_SET_ITEM(v, i, v2); } retval = v; break; case TYPE_DICT: v = PyDict_New(); R_REF(v); if (v == NULL) break; for (;;) { PyObject *key, *val; key = r_object(p); if (key == NULL) break; val = r_object(p); if (val == NULL) { Py_DECREF(key); break; } if (PyDict_SetItem(v, key, val) < 0) { Py_DECREF(key); Py_DECREF(val); break; } Py_DECREF(key); Py_DECREF(val); } if (PyErr_Occurred()) { Py_DECREF(v); v = NULL; } retval = v; break; case TYPE_SET: case TYPE_FROZENSET: n = r_long(p); if (PyErr_Occurred()) break; if (n < 0 || n > SIZE32_MAX) { PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)"); break; } v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL); if (type == TYPE_SET) { R_REF(v); } else { /* must use delayed registration of frozensets because they must * be init with a refcount of 1 */ idx = r_ref_reserve(flag, p); if (idx < 0) Py_CLEAR(v); /* signal error */ } if (v == NULL) break; for (i = 0; i < n; i++) { v2 = r_object(p); if ( v2 == NULL ) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for set"); Py_DECREF(v); v = NULL; break; } if (PySet_Add(v, v2) == -1) { Py_DECREF(v); Py_DECREF(v2); v = NULL; break; } Py_DECREF(v2); } if (type != TYPE_SET) v = r_ref_insert(v, idx, flag, p); retval = v; break; case TYPE_CODE: { int argcount; int kwonlyargcount; int nlocals; int stacksize; int flags; PyObject *code = NULL; PyObject *consts = NULL; PyObject *names = NULL; PyObject *varnames = NULL; PyObject *freevars = NULL; PyObject *cellvars = NULL; PyObject *filename = NULL; PyObject *name = NULL; int firstlineno; PyObject *lnotab = NULL; idx = r_ref_reserve(flag, p); if (idx < 0) break; v = NULL; /* XXX ignore long->int overflows for now */ argcount = (int)r_long(p); if (PyErr_Occurred()) goto code_error; kwonlyargcount = (int)r_long(p); if (PyErr_Occurred()) goto code_error; nlocals = (int)r_long(p); if (PyErr_Occurred()) goto code_error; stacksize = (int)r_long(p); if (PyErr_Occurred()) goto code_error; flags = (int)r_long(p); if (PyErr_Occurred()) goto code_error; code = r_object(p); if (code == NULL) goto code_error; consts = r_object(p); if (consts == NULL) goto code_error; names = r_object(p); if (names == NULL) goto code_error; varnames = r_object(p); if (varnames == NULL) goto code_error; freevars = r_object(p); if (freevars == NULL) goto code_error; cellvars = r_object(p); if (cellvars == NULL) goto code_error; filename = r_object(p); if (filename == NULL) goto code_error; if (PyUnicode_CheckExact(filename)) { if (p->current_filename != NULL) { if (!PyUnicode_Compare(filename, p->current_filename)) { Py_DECREF(filename); Py_INCREF(p->current_filename); filename = p->current_filename; } } else { p->current_filename = filename; } } name = r_object(p); if (name == NULL) goto code_error; firstlineno = (int)r_long(p); if (firstlineno == -1 && PyErr_Occurred()) break; lnotab = r_object(p); if (lnotab == NULL) goto code_error; v = (PyObject *) PyCode_New( argcount, kwonlyargcount, nlocals, stacksize, flags, code, consts, names, varnames, freevars, cellvars, filename, name, firstlineno, lnotab); v = r_ref_insert(v, idx, flag, p); code_error: Py_XDECREF(code); Py_XDECREF(consts); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(freevars); Py_XDECREF(cellvars); Py_XDECREF(filename); Py_XDECREF(name); Py_XDECREF(lnotab); } retval = v; break; case TYPE_REF: n = r_long(p); if (n < 0 || n >= PyList_GET_SIZE(p->refs)) { if (n == -1 && PyErr_Occurred()) break; PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)"); break; } v = PyList_GET_ITEM(p->refs, n); if (v == Py_None) { PyErr_SetString(PyExc_ValueError, "bad marshal data (invalid reference)"); break; } Py_INCREF(v); retval = v; break; default: /* Bogus data got written, which isn't ideal. This will let you keep working and recover. */ PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)"); break; } p->depth--; return retval; } static PyObject * read_object(RFILE *p) { PyObject *v; if (PyErr_Occurred()) { fprintf(stderr, "XXX readobject called with exception set\n"); return NULL; } v = r_object(p); if (v == NULL && !PyErr_Occurred()) PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object"); return v; } int PyMarshal_ReadShortFromFile(FILE *fp) { RFILE rf; int res; assert(fp); rf.readable = NULL; rf.fp = fp; rf.current_filename = NULL; rf.end = rf.ptr = NULL; rf.buf = NULL; res = r_short(&rf); if (rf.buf != NULL) PyMem_FREE(rf.buf); return res; } long PyMarshal_ReadLongFromFile(FILE *fp) { RFILE rf; long res; rf.fp = fp; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = rf.end = NULL; rf.buf = NULL; res = r_long(&rf); if (rf.buf != NULL) PyMem_FREE(rf.buf); return res; } #ifdef HAVE_FSTAT /* Return size of file in bytes; < 0 if unknown. */ static off_t getfilesize(FILE *fp) { struct stat st; if (fstat(fileno(fp), &st) != 0) return -1; else return st.st_size; } #endif /* If we can get the size of the file up-front, and it's reasonably small, * read it in one gulp and delegate to ...FromString() instead. Much quicker * than reading a byte at a time from file; speeds .pyc imports. * CAUTION: since this may read the entire remainder of the file, don't * call it unless you know you're done with the file. */ PyObject * PyMarshal_ReadLastObjectFromFile(FILE *fp) { /* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */ #define REASONABLE_FILE_LIMIT (1L << 18) #ifdef HAVE_FSTAT off_t filesize; filesize = getfilesize(fp); if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) { char* pBuf = (char *)PyMem_MALLOC(filesize); if (pBuf != NULL) { size_t n = fread(pBuf, 1, (size_t)filesize, fp); PyObject* v = PyMarshal_ReadObjectFromString(pBuf, n); PyMem_FREE(pBuf); return v; } } #endif /* We don't have fstat, or we do but the file is larger than * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time. */ return PyMarshal_ReadObjectFromFile(fp); #undef REASONABLE_FILE_LIMIT } PyObject * PyMarshal_ReadObjectFromFile(FILE *fp) { RFILE rf; PyObject *result; rf.fp = fp; rf.readable = NULL; rf.current_filename = NULL; rf.depth = 0; rf.ptr = rf.end = NULL; rf.buf = NULL; rf.refs = PyList_New(0); if (rf.refs == NULL) return NULL; result = r_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); return result; } PyObject * PyMarshal_ReadObjectFromString(const char *str, Py_ssize_t len) { RFILE rf; PyObject *result; rf.fp = NULL; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = (char *)str; rf.end = (char *)str + len; rf.buf = NULL; rf.depth = 0; rf.refs = PyList_New(0); if (rf.refs == NULL) return NULL; result = r_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); return result; } PyObject * PyMarshal_WriteObjectToString(PyObject *x, int version) { WFILE wf; wf.fp = NULL; wf.readable = NULL; wf.str = PyBytes_FromStringAndSize((char *)NULL, 50); if (wf.str == NULL) return NULL; wf.ptr = PyBytes_AS_STRING((PyBytesObject *)wf.str); wf.end = wf.ptr + PyBytes_Size(wf.str); wf.error = WFERR_OK; wf.depth = 0; wf.version = version; if (version >= 3) { if ((wf.refs = PyDict_New()) == NULL) return NULL; } else wf.refs = NULL; w_object(x, &wf); Py_XDECREF(wf.refs); if (wf.str != NULL) { char *base = PyBytes_AS_STRING((PyBytesObject *)wf.str); if (wf.ptr - base > PY_SSIZE_T_MAX) { Py_DECREF(wf.str); PyErr_SetString(PyExc_OverflowError, "too much marshal data for a string"); return NULL; } if (_PyBytes_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)) < 0) return NULL; } if (wf.error != WFERR_OK) { Py_XDECREF(wf.str); if (wf.error == WFERR_NOMEMORY) PyErr_NoMemory(); else PyErr_SetString(PyExc_ValueError, (wf.error==WFERR_UNMARSHALLABLE)?"unmarshallable object" :"object too deeply nested to marshal"); return NULL; } return wf.str; } /* And an interface for Python programs... */ static PyObject * marshal_dump(PyObject *self, PyObject *args) { /* XXX Quick hack -- need to do this differently */ PyObject *x; PyObject *f; int version = Py_MARSHAL_VERSION; PyObject *s; PyObject *res; _Py_IDENTIFIER(write); if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version)) return NULL; s = PyMarshal_WriteObjectToString(x, version); if (s == NULL) return NULL; res = _PyObject_CallMethodId(f, &PyId_write, "O", s); Py_DECREF(s); return res; } PyDoc_STRVAR(dump_doc, "dump(value, file[, version])\n\ \n\ Write the value on the open file. The value must be a supported type.\n\ The file must be an open file object such as sys.stdout or returned by\n\ open() or os.popen(). It must be opened in binary mode ('wb' or 'w+b').\n\ \n\ If the value has (or contains an object that has) an unsupported type, a\n\ ValueError exception is raised — but garbage data will also be written\n\ to the file. The object will not be properly read back by load()\n\ \n\ The version argument indicates the data format that dump should use."); static PyObject * marshal_load(PyObject *self, PyObject *f) { PyObject *data, *result; _Py_IDENTIFIER(read); RFILE rf; /* * Make a call to the read method, but read zero bytes. * This is to ensure that the object passed in at least * has a read method which returns bytes. * This can be removed if we guarantee good error handling * for r_string() */ data = _PyObject_CallMethodId(f, &PyId_read, "i", 0); if (data == NULL) return NULL; if (!PyBytes_Check(data)) { PyErr_Format(PyExc_TypeError, "f.read() returned not bytes but %.100s", data->ob_type->tp_name); result = NULL; } else { rf.depth = 0; rf.fp = NULL; rf.readable = f; rf.current_filename = NULL; rf.ptr = rf.end = NULL; rf.buf = NULL; if ((rf.refs = PyList_New(0)) != NULL) { result = read_object(&rf); Py_DECREF(rf.refs); if (rf.buf != NULL) PyMem_FREE(rf.buf); } else result = NULL; } Py_DECREF(data); return result; } PyDoc_STRVAR(load_doc, "load(file)\n\ \n\ Read one value from the open file and return it. If no valid value is\n\ read (e.g. because the data has a different Python version’s\n\ incompatible marshal format), raise EOFError, ValueError or TypeError.\n\ The file must be an open file object opened in binary mode ('rb' or\n\ 'r+b').\n\ \n\ Note: If an object containing an unsupported type was marshalled with\n\ dump(), load() will substitute None for the unmarshallable type."); static PyObject * marshal_dumps(PyObject *self, PyObject *args) { PyObject *x; int version = Py_MARSHAL_VERSION; if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version)) return NULL; return PyMarshal_WriteObjectToString(x, version); } PyDoc_STRVAR(dumps_doc, "dumps(value[, version])\n\ \n\ Return the string that would be written to a file by dump(value, file).\n\ The value must be a supported type. Raise a ValueError exception if\n\ value has (or contains an object that has) an unsupported type.\n\ \n\ The version argument indicates the data format that dumps should use."); static PyObject * marshal_loads(PyObject *self, PyObject *args) { RFILE rf; Py_buffer p; char *s; Py_ssize_t n; PyObject* result; if (!PyArg_ParseTuple(args, "y*:loads", &p)) return NULL; s = p.buf; n = p.len; rf.fp = NULL; rf.readable = NULL; rf.current_filename = NULL; rf.ptr = s; rf.end = s + n; rf.depth = 0; if ((rf.refs = PyList_New(0)) == NULL) return NULL; result = read_object(&rf); PyBuffer_Release(&p); Py_DECREF(rf.refs); return result; } PyDoc_STRVAR(loads_doc, "loads(bytes)\n\ \n\ Convert the bytes object to a value. If no valid value is found, raise\n\ EOFError, ValueError or TypeError. Extra characters in the input are\n\ ignored."); static PyMethodDef marshal_methods[] = { {"dump", marshal_dump, METH_VARARGS, dump_doc}, {"load", marshal_load, METH_O, load_doc}, {"dumps", marshal_dumps, METH_VARARGS, dumps_doc}, {"loads", marshal_loads, METH_VARARGS, loads_doc}, {NULL, NULL} /* sentinel */ }; PyDoc_STRVAR(module_doc, "This module contains functions that can read and write Python values in\n\ a binary format. The format is specific to Python, but independent of\n\ machine architecture issues.\n\ \n\ Not all Python object types are supported; in general, only objects\n\ whose value is independent from a particular invocation of Python can be\n\ written and read by this module. The following types are supported:\n\ None, integers, floating point numbers, strings, bytes, bytearrays,\n\ tuples, lists, sets, dictionaries, and code objects, where it\n\ should be understood that tuples, lists and dictionaries are only\n\ supported as long as the values contained therein are themselves\n\ supported; and recursive lists and dictionaries should not be written\n\ (they will cause infinite loops).\n\ \n\ Variables:\n\ \n\ version -- indicates the format that the module uses. Version 0 is the\n\ historical format, version 1 shares interned strings and version 2\n\ uses a binary format for floating point numbers.\n\ Version 3 shares common object references (New in version 3.4).\n\ \n\ Functions:\n\ \n\ dump() -- write value to a file\n\ load() -- read value from a file\n\ dumps() -- write value to a string\n\ loads() -- read value from a string"); static struct PyModuleDef marshalmodule = { PyModuleDef_HEAD_INIT, "marshal", module_doc, 0, marshal_methods, NULL, NULL, NULL, NULL }; PyMODINIT_FUNC PyMarshal_Init(void) { PyObject *mod = PyModule_Create(&marshalmodule); if (mod == NULL) return NULL; PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION); return mod; }
27763.c
/******************************************************************************* * * Module Name: dsutils - Dispatcher utilities * ******************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2020, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following 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, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any 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. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include <contrib/dev/acpica/include/acpi.h> #include <contrib/dev/acpica/include/accommon.h> #include <contrib/dev/acpica/include/acparser.h> #include <contrib/dev/acpica/include/amlcode.h> #include <contrib/dev/acpica/include/acdispat.h> #include <contrib/dev/acpica/include/acinterp.h> #include <contrib/dev/acpica/include/acnamesp.h> #include <contrib/dev/acpica/include/acdebug.h> #define _COMPONENT ACPI_DISPATCHER ACPI_MODULE_NAME ("dsutils") /******************************************************************************* * * FUNCTION: AcpiDsClearImplicitReturn * * PARAMETERS: WalkState - Current State * * RETURN: None. * * DESCRIPTION: Clear and remove a reference on an implicit return value. Used * to delete "stale" return values (if enabled, the return value * from every operator is saved at least momentarily, in case the * parent method exits.) * ******************************************************************************/ void AcpiDsClearImplicitReturn ( ACPI_WALK_STATE *WalkState) { ACPI_FUNCTION_NAME (DsClearImplicitReturn); /* * Slack must be enabled for this feature */ if (!AcpiGbl_EnableInterpreterSlack) { return; } if (WalkState->ImplicitReturnObj) { /* * Delete any "stale" implicit return. However, in * complex statements, the implicit return value can be * bubbled up several levels. */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Removing reference on stale implicit return obj %p\n", WalkState->ImplicitReturnObj)); AcpiUtRemoveReference (WalkState->ImplicitReturnObj); WalkState->ImplicitReturnObj = NULL; } } /******************************************************************************* * * FUNCTION: AcpiDsDoImplicitReturn * * PARAMETERS: ReturnDesc - The return value * WalkState - Current State * AddReference - True if a reference should be added to the * return object * * RETURN: TRUE if implicit return enabled, FALSE otherwise * * DESCRIPTION: Implements the optional "implicit return". We save the result * of every ASL operator and control method invocation in case the * parent method exit. Before storing a new return value, we * delete the previous return value. * ******************************************************************************/ BOOLEAN AcpiDsDoImplicitReturn ( ACPI_OPERAND_OBJECT *ReturnDesc, ACPI_WALK_STATE *WalkState, BOOLEAN AddReference) { ACPI_FUNCTION_NAME (DsDoImplicitReturn); /* * Slack must be enabled for this feature, and we must * have a valid return object */ if ((!AcpiGbl_EnableInterpreterSlack) || (!ReturnDesc)) { return (FALSE); } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result %p will be implicitly returned; Prev=%p\n", ReturnDesc, WalkState->ImplicitReturnObj)); /* * Delete any "stale" implicit return value first. However, in * complex statements, the implicit return value can be * bubbled up several levels, so we don't clear the value if it * is the same as the ReturnDesc. */ if (WalkState->ImplicitReturnObj) { if (WalkState->ImplicitReturnObj == ReturnDesc) { return (TRUE); } AcpiDsClearImplicitReturn (WalkState); } /* Save the implicit return value, add a reference if requested */ WalkState->ImplicitReturnObj = ReturnDesc; if (AddReference) { AcpiUtAddReference (ReturnDesc); } return (TRUE); } /******************************************************************************* * * FUNCTION: AcpiDsIsResultUsed * * PARAMETERS: Op - Current Op * WalkState - Current State * * RETURN: TRUE if result is used, FALSE otherwise * * DESCRIPTION: Check if a result object will be used by the parent * ******************************************************************************/ BOOLEAN AcpiDsIsResultUsed ( ACPI_PARSE_OBJECT *Op, ACPI_WALK_STATE *WalkState) { const ACPI_OPCODE_INFO *ParentInfo; ACPI_FUNCTION_TRACE_PTR (DsIsResultUsed, Op); /* Must have both an Op and a Result Object */ if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_UINT8 (TRUE); } /* * We know that this operator is not a * Return() operator (would not come here.) The following code is the * optional support for a so-called "implicit return". Some AML code * assumes that the last value of the method is "implicitly" returned * to the caller. Just save the last result as the return value. * NOTE: this is optional because the ASL language does not actually * support this behavior. */ (void) AcpiDsDoImplicitReturn (WalkState->ResultObj, WalkState, TRUE); /* * Now determine if the parent will use the result * * If there is no parent, or the parent is a ScopeOp, we are executing * at the method level. An executing method typically has no parent, * since each method is parsed separately. A method invoked externally * via ExecuteControlMethod has a ScopeOp as the parent. */ if ((!Op->Common.Parent) || (Op->Common.Parent->Common.AmlOpcode == AML_SCOPE_OP)) { /* No parent, the return value cannot possibly be used */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "At Method level, result of [%s] not used\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode))); return_UINT8 (FALSE); } /* Get info on the parent. The RootOp is AML_SCOPE */ ParentInfo = AcpiPsGetOpcodeInfo (Op->Common.Parent->Common.AmlOpcode); if (ParentInfo->Class == AML_CLASS_UNKNOWN) { ACPI_ERROR ((AE_INFO, "Unknown parent opcode Op=%p", Op)); return_UINT8 (FALSE); } /* * Decide what to do with the result based on the parent. If * the parent opcode will not use the result, delete the object. * Otherwise leave it as is, it will be deleted when it is used * as an operand later. */ switch (ParentInfo->Class) { case AML_CLASS_CONTROL: switch (Op->Common.Parent->Common.AmlOpcode) { case AML_RETURN_OP: /* Never delete the return value associated with a return opcode */ goto ResultUsed; case AML_IF_OP: case AML_WHILE_OP: /* * If we are executing the predicate AND this is the predicate op, * we will use the return value */ if ((WalkState->ControlState->Common.State == ACPI_CONTROL_PREDICATE_EXECUTING) && (WalkState->ControlState->Control.PredicateOp == Op)) { goto ResultUsed; } break; default: /* Ignore other control opcodes */ break; } /* The general control opcode returns no result */ goto ResultNotUsed; case AML_CLASS_CREATE: /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; case AML_CLASS_NAMED_OBJECT: if ((Op->Common.Parent->Common.AmlOpcode == AML_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_DATA_REGION_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BUFFER_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_INT_EVAL_SUBTREE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_BANK_FIELD_OP)) { /* * These opcodes allow TermArg(s) as operands and therefore * the operands can be method calls. The result is used. */ goto ResultUsed; } goto ResultNotUsed; default: /* * In all other cases. the parent will actually use the return * object, so keep it. */ goto ResultUsed; } ResultUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (TRUE); ResultNotUsed: ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Result of [%s] not used by Parent [%s] Op=%p\n", AcpiPsGetOpcodeName (Op->Common.AmlOpcode), AcpiPsGetOpcodeName (Op->Common.Parent->Common.AmlOpcode), Op)); return_UINT8 (FALSE); } /******************************************************************************* * * FUNCTION: AcpiDsDeleteResultIfNotUsed * * PARAMETERS: Op - Current parse Op * ResultObj - Result of the operation * WalkState - Current state * * RETURN: Status * * DESCRIPTION: Used after interpretation of an opcode. If there is an internal * result descriptor, check if the parent opcode will actually use * this result. If not, delete the result now so that it will * not become orphaned. * ******************************************************************************/ void AcpiDsDeleteResultIfNotUsed ( ACPI_PARSE_OBJECT *Op, ACPI_OPERAND_OBJECT *ResultObj, ACPI_WALK_STATE *WalkState) { ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_FUNCTION_TRACE_PTR (DsDeleteResultIfNotUsed, ResultObj); if (!Op) { ACPI_ERROR ((AE_INFO, "Null Op")); return_VOID; } if (!ResultObj) { return_VOID; } if (!AcpiDsIsResultUsed (Op, WalkState)) { /* Must pop the result stack (ObjDesc should be equal to ResultObj) */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_SUCCESS (Status)) { AcpiUtRemoveReference (ResultObj); } } return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsResolveOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: Status * * DESCRIPTION: Resolve all operands to their values. Used to prepare * arguments to a control method invocation (a call from one * method to another.) * ******************************************************************************/ ACPI_STATUS AcpiDsResolveOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_STATUS Status = AE_OK; ACPI_FUNCTION_TRACE_PTR (DsResolveOperands, WalkState); /* * Attempt to resolve each of the valid operands * Method arguments are passed by reference, not by value. This means * that the actual objects are passed, not copies of the objects. */ for (i = 0; i < WalkState->NumOperands; i++) { Status = AcpiExResolveToValue (&WalkState->Operands[i], WalkState); if (ACPI_FAILURE (Status)) { break; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiDsClearOperands * * PARAMETERS: WalkState - Current walk state with operands on stack * * RETURN: None * * DESCRIPTION: Clear all operands on the current walk state operand stack. * ******************************************************************************/ void AcpiDsClearOperands ( ACPI_WALK_STATE *WalkState) { UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsClearOperands, WalkState); /* Remove a reference on each operand on the stack */ for (i = 0; i < WalkState->NumOperands; i++) { /* * Remove a reference to all operands, including both * "Arguments" and "Targets". */ AcpiUtRemoveReference (WalkState->Operands[i]); WalkState->Operands[i] = NULL; } WalkState->NumOperands = 0; return_VOID; } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperand * * PARAMETERS: WalkState - Current walk state * Arg - Parse object for the argument * ArgIndex - Which argument (zero based) * * RETURN: Status * * DESCRIPTION: Translate a parse tree object that is an argument to an AML * opcode to the equivalent interpreter object. This may include * looking up a name or entering a new name into the internal * namespace. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperand ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Arg, UINT32 ArgIndex) { ACPI_STATUS Status = AE_OK; char *NameString; UINT32 NameLength; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_PARSE_OBJECT *ParentOp; UINT16 Opcode; ACPI_INTERPRETER_MODE InterpreterMode; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (DsCreateOperand, Arg); /* A valid name must be looked up in the namespace */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && (Arg->Common.Value.String) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Getting a name: Arg=%p\n", Arg)); /* Get the entire name string from the AML stream */ Status = AcpiExGetNameString (ACPI_TYPE_ANY, Arg->Common.Value.Buffer, &NameString, &NameLength); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* All prefixes have been handled, and the name is in NameString */ /* * Special handling for BufferField declarations. This is a deferred * opcode that unfortunately defines the field name as the last * parameter instead of the first. We get here when we are performing * the deferred execution, so the actual name of the field is already * in the namespace. We don't want to attempt to look it up again * because we may be executing in a different scope than where the * actual opcode exists. */ if ((WalkState->DeferredNode) && (WalkState->DeferredNode->Type == ACPI_TYPE_BUFFER_FIELD) && (ArgIndex == (UINT32) ((WalkState->Opcode == AML_CREATE_FIELD_OP) ? 3 : 2))) { ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, WalkState->DeferredNode); Status = AE_OK; } else /* All other opcodes */ { /* * Differentiate between a namespace "create" operation * versus a "lookup" operation (IMODE_LOAD_PASS2 vs. * IMODE_EXECUTE) in order to support the creation of * namespace objects during the execution of control methods. */ ParentOp = Arg->Common.Parent; OpInfo = AcpiPsGetOpcodeInfo (ParentOp->Common.AmlOpcode); if ((OpInfo->Flags & AML_NSNODE) && (ParentOp->Common.AmlOpcode != AML_INT_METHODCALL_OP) && (ParentOp->Common.AmlOpcode != AML_REGION_OP) && (ParentOp->Common.AmlOpcode != AML_INT_NAMEPATH_OP)) { /* Enter name into namespace if not found */ InterpreterMode = ACPI_IMODE_LOAD_PASS2; } else { /* Return a failure if name not found */ InterpreterMode = ACPI_IMODE_EXECUTE; } Status = AcpiNsLookup (WalkState->ScopeInfo, NameString, ACPI_TYPE_ANY, InterpreterMode, ACPI_NS_SEARCH_PARENT | ACPI_NS_DONT_OPEN_SCOPE, WalkState, ACPI_CAST_INDIRECT_PTR (ACPI_NAMESPACE_NODE, &ObjDesc)); /* * The only case where we pass through (ignore) a NOT_FOUND * error is for the CondRefOf opcode. */ if (Status == AE_NOT_FOUND) { if (ParentOp->Common.AmlOpcode == AML_CONDITIONAL_REF_OF_OP) { /* * For the Conditional Reference op, it's OK if * the name is not found; We just need a way to * indicate this to the interpreter, set the * object to the root */ ObjDesc = ACPI_CAST_PTR ( ACPI_OPERAND_OBJECT, AcpiGbl_RootNode); Status = AE_OK; } else if (ParentOp->Common.AmlOpcode == AML_EXTERNAL_OP) { /* * This opcode should never appear here. It is used only * by AML disassemblers and is surrounded by an If(0) * by the ASL compiler. * * Therefore, if we see it here, it is a serious error. */ Status = AE_AML_BAD_OPCODE; } else { /* * We just plain didn't find it -- which is a * very serious error at this point */ Status = AE_AML_NAME_NOT_FOUND; } } if (ACPI_FAILURE (Status)) { ACPI_ERROR_NAMESPACE (WalkState->ScopeInfo, NameString, Status); } } /* Free the namestring created above */ ACPI_FREE (NameString); /* Check status from the lookup */ if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Put the resulting object onto the current object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } else { /* Check for null name case */ if ((Arg->Common.AmlOpcode == AML_INT_NAMEPATH_OP) && !(Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * If the name is null, this means that this is an * optional result parameter that was not specified * in the original ASL. Create a Zero Constant for a * placeholder. (Store to a constant is a Noop.) */ Opcode = AML_ZERO_OP; /* Has no arguments! */ ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Null namepath: Arg=%p\n", Arg)); } else { Opcode = Arg->Common.AmlOpcode; } /* Get the object type of the argument */ OpInfo = AcpiPsGetOpcodeInfo (Opcode); if (OpInfo->ObjectType == ACPI_TYPE_INVALID) { return_ACPI_STATUS (AE_NOT_IMPLEMENTED); } if ((OpInfo->Flags & AML_HAS_RETVAL) || (Arg->Common.Flags & ACPI_PARSEOP_IN_STACK)) { /* * Use value that was already previously returned * by the evaluation of this argument */ Status = AcpiDsResultPop (&ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { /* * Only error is underflow, and this indicates * a missing or null operand! */ ACPI_EXCEPTION ((AE_INFO, Status, "Missing or null operand")); return_ACPI_STATUS (Status); } } else { /* Create an ACPI_INTERNAL_OBJECT for the argument */ ObjDesc = AcpiUtCreateInternalObject (OpInfo->ObjectType); if (!ObjDesc) { return_ACPI_STATUS (AE_NO_MEMORY); } /* Initialize the new object */ Status = AcpiDsInitObjectFromOp ( WalkState, Arg, Opcode, &ObjDesc); if (ACPI_FAILURE (Status)) { AcpiUtDeleteObjectDesc (ObjDesc); return_ACPI_STATUS (Status); } } /* Put the operand object on the object stack */ Status = AcpiDsObjStackPush (ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiDbDisplayArgumentObject (ObjDesc, WalkState); } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiDsCreateOperands * * PARAMETERS: WalkState - Current state * FirstArg - First argument of a parser argument tree * * RETURN: Status * * DESCRIPTION: Convert an operator's arguments from a parse tree format to * namespace objects and place those argument object on the object * stack in preparation for evaluation by the interpreter. * ******************************************************************************/ ACPI_STATUS AcpiDsCreateOperands ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *FirstArg) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg; ACPI_PARSE_OBJECT *Arguments[ACPI_OBJ_NUM_OPERANDS]; UINT32 ArgCount = 0; UINT32 Index = WalkState->NumOperands; UINT32 i; ACPI_FUNCTION_TRACE_PTR (DsCreateOperands, FirstArg); /* Get all arguments in the list */ Arg = FirstArg; while (Arg) { if (Index >= ACPI_OBJ_NUM_OPERANDS) { return_ACPI_STATUS (AE_BAD_DATA); } Arguments[Index] = Arg; WalkState->Operands [Index] = NULL; /* Move on to next argument, if any */ Arg = Arg->Common.Next; ArgCount++; Index++; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "NumOperands %d, ArgCount %d, Index %d\n", WalkState->NumOperands, ArgCount, Index)); /* Create the interpreter arguments, in reverse order */ Index--; for (i = 0; i < ArgCount; i++) { Arg = Arguments[Index]; WalkState->OperandIndex = (UINT8) Index; Status = AcpiDsCreateOperand (WalkState, Arg, Index); if (ACPI_FAILURE (Status)) { goto Cleanup; } ACPI_DEBUG_PRINT ((ACPI_DB_DISPATCH, "Created Arg #%u (%p) %u args total\n", Index, Arg, ArgCount)); Index--; } return_ACPI_STATUS (Status); Cleanup: /* * We must undo everything done above; meaning that we must * pop everything off of the operand stack and delete those * objects */ AcpiDsObjStackPopAndDelete (ArgCount, WalkState); ACPI_EXCEPTION ((AE_INFO, Status, "While creating Arg %u", Index)); return_ACPI_STATUS (Status); } /***************************************************************************** * * FUNCTION: AcpiDsEvaluateNamePath * * PARAMETERS: WalkState - Current state of the parse tree walk, * the opcode of current operation should be * AML_INT_NAMEPATH_OP * * RETURN: Status * * DESCRIPTION: Translate the -NamePath- parse tree object to the equivalent * interpreter object, convert it to value, if needed, duplicate * it, if needed, and push it onto the current result stack. * ****************************************************************************/ ACPI_STATUS AcpiDsEvaluateNamePath ( ACPI_WALK_STATE *WalkState) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op = WalkState->Op; ACPI_OPERAND_OBJECT **Operand = &WalkState->Operands[0]; ACPI_OPERAND_OBJECT *NewObjDesc; UINT8 Type; ACPI_FUNCTION_TRACE_PTR (DsEvaluateNamePath, WalkState); if (!Op->Common.Parent) { /* This happens after certain exception processing */ goto Exit; } if ((Op->Common.Parent->Common.AmlOpcode == AML_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_VARIABLE_PACKAGE_OP) || (Op->Common.Parent->Common.AmlOpcode == AML_REF_OF_OP)) { /* TBD: Should we specify this feature as a bit of OpInfo->Flags of these opcodes? */ goto Exit; } Status = AcpiDsCreateOperand (WalkState, Op, 0); if (ACPI_FAILURE (Status)) { goto Exit; } if (Op->Common.Flags & ACPI_PARSEOP_TARGET) { NewObjDesc = *Operand; goto PushResult; } Type = (*Operand)->Common.Type; Status = AcpiExResolveToValue (Operand, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } if (Type == ACPI_TYPE_INTEGER) { /* It was incremented by AcpiExResolveToValue */ AcpiUtRemoveReference (*Operand); Status = AcpiUtCopyIobjectToIobject ( *Operand, &NewObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Exit; } } else { /* * The object either was anew created or is * a Namespace node - don't decrement it. */ NewObjDesc = *Operand; } /* Cleanup for name-path operand */ Status = AcpiDsObjStackPop (1, WalkState); if (ACPI_FAILURE (Status)) { WalkState->ResultObj = NewObjDesc; goto Exit; } PushResult: WalkState->ResultObj = NewObjDesc; Status = AcpiDsResultPush (WalkState->ResultObj, WalkState); if (ACPI_SUCCESS (Status)) { /* Force to take it from stack */ Op->Common.Flags |= ACPI_PARSEOP_IN_STACK; } Exit: return_ACPI_STATUS (Status); }
577055.c
/******************************************************************************* * Includes ******************************************************************************/ #include <stdio.h> #include "board.h" #include "peripherals.h" #include "pin_mux.h" #include "clock_config.h" #include "MKL02Z4.h" #include "fsl_debug_console.h" #include "sdk_hal_gpio.h" #include "sdk_hal_uart0.h" #include "sdk_hal_i2c0.h" /******************************************************************************* * Definitions ******************************************************************************/ #define MMA851_I2C_DEVICE_ADDRESS 0x1D #define MMA8451_WHO_AM_I_MEMORY_ADDRESS 0x0D /******************************************************************************* * Private Prototypes ******************************************************************************/ /******************************************************************************* * External vars ******************************************************************************/ /******************************************************************************* * Local vars ******************************************************************************/ /******************************************************************************* * Private Source Code ******************************************************************************/ /******************************************************************************* * Public Source Code ******************************************************************************/ int main(void) { status_t status; uint8_t nuevo_byte_uart; uint8_t nuevo_dato_i2c; /* Init board hardware. */ BOARD_InitBootPins(); BOARD_InitBootClocks(); BOARD_InitBootPeripherals(); #ifndef BOARD_INIT_DEBUG_CONSOLE_PERIPHERAL /* Init FSL debug console. */ BOARD_InitDebugConsole(); #endif (void)uart0Inicializar(115200); //115200bps (void)i2c0MasterInit(100000); //100kbps PRINTF("Usar teclado para controlar LEDs\r\n"); PRINTF("r-R led ROJO\r\n"); PRINTF("v-V led VERDE\r\n"); PRINTF("a-A led AZUL\r\n"); PRINTF("M buscar acelerometro\r\n"); while(1) { if(uart0CuantosDatosHayEnBuffer()>0){ status=uart0LeerByteDesdeBuffer(&nuevo_byte_uart); if(status==kStatus_Success){ printf("dato:%c\r\n",nuevo_byte_uart); switch (nuevo_byte_uart) { case 'a': case 'A': gpioPutToggle(KPTB10); break; case 'v': gpioPutHigh(KPTB7); break; case 'V': gpioPutLow(KPTB7); break; case 'r': gpioPutValue(KPTB6,1); break; case 'R': gpioPutValue(KPTB6,0); break; case 'M': i2c0MasterReadByte(&nuevo_dato_i2c, MMA851_I2C_DEVICE_ADDRESS, MMA8451_WHO_AM_I_MEMORY_ADDRESS); if(nuevo_dato_i2c==0x1A) printf("MMA8451 encontrado!!\r\n"); else printf("MMA8451 error\r\n"); break; } }else{ printf("error\r\n"); } } } return 0 ; }
656830.c
/* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice 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. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ /* Freescale includes. */ #include "common.h" #include "eth_phy.h" #include "enet.h" #include "mii.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" /* uIP includes. */ #include "net/uip.h" /* The time to wait between attempts to obtain a free buffer. */ #define emacBUFFER_WAIT_DELAY_ms ( 3 / portTICK_PERIOD_MS ) /* The number of times emacBUFFER_WAIT_DELAY_ms should be waited before giving up on attempting to obtain a free buffer all together. */ #define emacBUFFER_WAIT_ATTEMPTS ( 30 ) /* The number of Rx descriptors. */ #define emacNUM_RX_DESCRIPTORS 8 /* The number of Tx descriptors. When using uIP there is not point in having more than two. */ #define emacNUM_TX_BUFFERS 2 /* The total number of EMAC buffers to allocate. */ #define emacNUM_BUFFERS ( emacNUM_RX_DESCRIPTORS + emacNUM_TX_BUFFERS ) /* The time to wait for the Tx descriptor to become free. */ #define emacTX_WAIT_DELAY_ms ( 10 / portTICK_PERIOD_MS ) /* The total number of times to wait emacTX_WAIT_DELAY_ms for the Tx descriptor to become free. */ #define emacTX_WAIT_ATTEMPTS ( 50 ) /* Constants used for set up and initialisation. */ #define emacTX_INTERRUPT_NO ( 76 ) #define emacRX_INTERRUPT_NO ( 77 ) #define emacERROR_INTERRUPT_NO ( 78 ) #define emacLINK_DELAY ( 500 / portTICK_PERIOD_MS ) #define emacPHY_STATUS ( 0x1F ) #define emacPHY_DUPLEX_STATUS ( 4 << 2 ) #define emacPHY_SPEED_STATUS ( 1 << 2 ) /*-----------------------------------------------------------*/ /* * Initialise both the Rx and Tx descriptors. */ static void prvInitialiseDescriptors( void ); /* * Return a pointer to a free buffer within xEthernetBuffers. */ static unsigned char *prvGetNextBuffer( void ); /* * Return a buffer to the list of free buffers. */ static void prvReturnBuffer( unsigned char *pucBuffer ); /* * Examine the status of the next Rx descriptor to see if it contains new data. */ static unsigned short prvCheckRxStatus( void ); /* * Something has gone wrong with the descriptor usage. Reset all the buffers * and descriptors. */ static void prvResetEverything( void ); /*-----------------------------------------------------------*/ /* The buffers and descriptors themselves. */ #pragma data_alignment=16 volatile NBUF xRxDescriptors[ emacNUM_RX_DESCRIPTORS ]; #pragma data_alignment=16 volatile NBUF xTxDescriptors[ emacNUM_TX_BUFFERS ]; #pragma data_alignment=16 char xEthernetBuffers[ emacNUM_BUFFERS ][ UIP_BUFSIZE ]; /* Used to indicate which buffers are free and which are in use. If an index contains 0 then the corresponding buffer in xEthernetBuffers is free, otherwise the buffer is in use or about to be used. */ static unsigned char ucBufferInUse[ emacNUM_BUFFERS ]; /* Points to the Rx descriptor currently in use. */ static volatile NBUF *pxCurrentRxDesc = NULL; /* pxCurrentRxDesc points to descriptor within the xRxDescriptors array that has an index defined by ulRxDescriptorIndex. */ static unsigned long ulRxDescriptorIndex = 0UL; /* The buffer used by the uIP stack to both receive and send. This points to one of the Ethernet buffers when its actually in use. */ unsigned char *uip_buf = NULL; /*-----------------------------------------------------------*/ void vEMACInit( void ) { int iData; extern int periph_clk_khz; const unsigned char ucMACAddress[] = { configMAC_ADDR0, configMAC_ADDR1, configMAC_ADDR2, configMAC_ADDR3, configMAC_ADDR4, configMAC_ADDR5 }; /* Enable the ENET clock. */ SIM_SCGC2 |= SIM_SCGC2_ENET_MASK; /* Allow concurrent access to MPU controller to avoid bus errors. */ MPU_CESR = 0; prvInitialiseDescriptors(); /* Reset and enable. */ ENET_ECR = ENET_ECR_RESET_MASK; /* Wait at least 8 clock cycles */ vTaskDelay( 2 ); /* Start the MII interface*/ mii_init( 0, periph_clk_khz / 1000L ); /* Configure the transmit interrupt. */ set_irq_priority( emacTX_INTERRUPT_NO, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); enable_irq( emacTX_INTERRUPT_NO ); /* Configure the receive interrupt. */ set_irq_priority( emacRX_INTERRUPT_NO, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); enable_irq( emacRX_INTERRUPT_NO ); /* Configure the error interrupt. */ set_irq_priority( emacERROR_INTERRUPT_NO, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY ); enable_irq( emacERROR_INTERRUPT_NO ); /* Configure the pins to the PHY - RMII mode used. */ PORTB_PCR0 = PORT_PCR_MUX( 4 ); /* RMII0_MDIO / MII0_MDIO. */ PORTB_PCR1 = PORT_PCR_MUX( 4 ); /* RMII0_MDC / MII0_MDC */ PORTA_PCR14 = PORT_PCR_MUX( 4 ); /* RMII0_CRS_DV / MII0_RXDV */ PORTA_PCR12 = PORT_PCR_MUX( 4 ); /* RMII0_RXD1 / MII0_RXD1 */ PORTA_PCR13 = PORT_PCR_MUX( 4 ); /* RMII0_RXD0/MII0_RXD0 */ PORTA_PCR15 = PORT_PCR_MUX( 4 ); /* RMII0_TXEN/MII0_TXEN */ PORTA_PCR16 = PORT_PCR_MUX( 4 ); /* RMII0_TXD0/MII0_TXD0 */ PORTA_PCR17 = PORT_PCR_MUX( 4 ); /* RMII0_TXD1/MII0_TXD1 */ /* Is there communication with the PHY? */ do { vTaskDelay( emacLINK_DELAY ); iData = 0xFFFF; mii_read( 0, configPHY_ADDRESS, PHY_PHYIDR1, &iData ); } while( iData == 0xFFFF ); /* Start to auto negotiate. */ mii_write( 0, configPHY_ADDRESS, PHY_BMCR, ( PHY_BMCR_AN_RESTART | PHY_BMCR_AN_ENABLE ) ); /* Wait for auto negotiate to complete. */ do { vTaskDelay( emacLINK_DELAY ); mii_read( 0, configPHY_ADDRESS, PHY_BMSR, &iData ); } while( !( iData & PHY_BMSR_AN_COMPLETE ) ); /* A link has been established. What was negotiated? */ iData = 0; mii_read( 0, configPHY_ADDRESS, emacPHY_STATUS, &iData ); /* Clear the Individual and Group Address Hash registers */ ENET_IALR = 0; ENET_IAUR = 0; ENET_GALR = 0; ENET_GAUR = 0; /* Set the Physical Address for the selected ENET */ enet_set_address( 0, ucMACAddress ); ENET_RCR = ENET_RCR_MAX_FL( UIP_BUFSIZE ) | ENET_RCR_MII_MODE_MASK | ENET_RCR_CRCFWD_MASK | ENET_RCR_RMII_MODE_MASK; /* Clear the control registers. */ ENET_TCR = 0; if( iData & emacPHY_DUPLEX_STATUS ) { /* Full duplex */ ENET_RCR &= ( unsigned long )~ENET_RCR_DRT_MASK; ENET_TCR |= ENET_TCR_FDEN_MASK; } else { /* Half duplex */ ENET_RCR |= ENET_RCR_DRT_MASK; ENET_TCR &= (unsigned long)~ENET_TCR_FDEN_MASK; } if( iData & emacPHY_SPEED_STATUS ) { /* 10Mbps */ ENET_RCR |= ENET_RCR_RMII_10T_MASK; } ENET_ECR = ENET_ECR_EN1588_MASK; /* Store and forward checksum. */ ENET_TFWR = ENET_TFWR_STRFWD_MASK; /* Set Rx Buffer Size */ ENET_MRBR = ( unsigned short ) UIP_BUFSIZE; /* Point to the start of the circular Rx buffer descriptor queue */ ENET_RDSR = ( unsigned long ) &( xRxDescriptors[ 0 ] ); /* Point to the start of the circular Tx buffer descriptor queue */ ENET_TDSR = ( unsigned long ) &( xTxDescriptors[ 0 ] ); /* Clear all ENET interrupt events */ ENET_EIR = ( unsigned long ) -1; /* Enable interrupts. */ ENET_EIMR = 0 /*rx irqs*/ | ENET_EIMR_RXF_MASK/* only for complete frame, not partial buffer descriptor | ENET_EIMR_RXB_MASK*/ /*xmit irqs*/ | ENET_EIMR_TXF_MASK/* only for complete frame, not partial buffer descriptor | ENET_EIMR_TXB_MASK*/ /*enet irqs*/ | ENET_EIMR_UN_MASK | ENET_EIMR_RL_MASK | ENET_EIMR_LC_MASK | ENET_EIMR_BABT_MASK | ENET_EIMR_BABR_MASK | ENET_EIMR_EBERR_MASK ; /* Enable the MAC itself. */ ENET_ECR |= ENET_ECR_ETHEREN_MASK; /* Indicate that there have been empty receive buffers produced */ ENET_RDAR = ENET_RDAR_RDAR_MASK; } /*-----------------------------------------------------------*/ static void prvInitialiseDescriptors( void ) { volatile NBUF *pxDescriptor; long x; for( x = 0; x < emacNUM_BUFFERS; x++ ) { /* Ensure none of the buffers are shown as in use at the start. */ ucBufferInUse[ x ] = pdFALSE; } /* Initialise the Rx descriptors. */ for( x = 0; x < emacNUM_RX_DESCRIPTORS; x++ ) { pxDescriptor = &( xRxDescriptors[ x ] ); pxDescriptor->data = ( uint8_t* ) &( xEthernetBuffers[ x ][ 0 ] ); pxDescriptor->data = ( uint8_t* ) __REV( ( unsigned long ) pxDescriptor->data ); pxDescriptor->length = 0; pxDescriptor->status = RX_BD_E; pxDescriptor->bdu = 0; pxDescriptor->ebd_status = RX_BD_INT; /* Mark this buffer as in use. */ ucBufferInUse[ x ] = pdTRUE; } /* The last descriptor points back to the start. */ pxDescriptor->status |= RX_BD_W; /* Initialise the Tx descriptors. */ for( x = 0; x < emacNUM_TX_BUFFERS; x++ ) { pxDescriptor = &( xTxDescriptors[ x ] ); /* A buffer is not allocated to the Tx descriptor until a send is actually required. */ pxDescriptor->data = NULL; pxDescriptor->length = 0; pxDescriptor->status = TX_BD_TC; pxDescriptor->ebd_status = TX_BD_INT; } /* The last descriptor points back to the start. */ pxDescriptor->status |= TX_BD_W; /* Use the first Rx descriptor to start with. */ ulRxDescriptorIndex = 0UL; pxCurrentRxDesc = &( xRxDescriptors[ 0 ] ); } /*-----------------------------------------------------------*/ void vEMACWrite( void ) { long x; /* Wait until the second transmission of the last packet has completed. */ for( x = 0; x < emacTX_WAIT_ATTEMPTS; x++ ) { if( ( xTxDescriptors[ 1 ].status & TX_BD_R ) != 0 ) { /* Descriptor is still active. */ vTaskDelay( emacTX_WAIT_DELAY_ms ); } else { break; } } /* Is the descriptor free after waiting for it? */ if( ( xTxDescriptors[ 1 ].status & TX_BD_R ) != 0 ) { /* Something has gone wrong. */ prvResetEverything(); } /* Setup both descriptors to transmit the frame. */ xTxDescriptors[ 0 ].data = ( uint8_t * ) __REV( ( unsigned long ) uip_buf ); xTxDescriptors[ 0 ].length = __REVSH( uip_len ); xTxDescriptors[ 1 ].data = ( uint8_t * ) __REV( ( unsigned long ) uip_buf ); xTxDescriptors[ 1 ].length = __REVSH( uip_len ); /* uip_buf is being sent by the Tx descriptor. Allocate a new buffer for use by the stack. */ uip_buf = prvGetNextBuffer(); /* Clear previous settings and go. */ xTxDescriptors[ 0 ].status |= ( TX_BD_R | TX_BD_L ); xTxDescriptors[ 1 ].status |= ( TX_BD_R | TX_BD_L ); /* Start the Tx. */ ENET_TDAR = ENET_TDAR_TDAR_MASK; } /*-----------------------------------------------------------*/ static unsigned char *prvGetNextBuffer( void ) { long x; unsigned char *pucReturn = NULL; unsigned long ulAttempts = 0; while( pucReturn == NULL ) { /* Look through the buffers to find one that is not in use by anything else. */ for( x = 0; x < emacNUM_BUFFERS; x++ ) { if( ucBufferInUse[ x ] == pdFALSE ) { ucBufferInUse[ x ] = pdTRUE; pucReturn = ( unsigned char * ) &( xEthernetBuffers[ x ][ 0 ] ); break; } } /* Was a buffer found? */ if( pucReturn == NULL ) { ulAttempts++; if( ulAttempts >= emacBUFFER_WAIT_ATTEMPTS ) { break; } /* Wait then look again. */ vTaskDelay( emacBUFFER_WAIT_DELAY_ms ); } } return pucReturn; } /*-----------------------------------------------------------*/ static void prvResetEverything( void ) { /* Temporary code just to see if this gets called. This function has not been implemented. */ portDISABLE_INTERRUPTS(); for( ;; ); } /*-----------------------------------------------------------*/ unsigned short usEMACRead( void ) { unsigned short usBytesReceived; usBytesReceived = prvCheckRxStatus(); usBytesReceived = __REVSH( usBytesReceived ); if( usBytesReceived > 0 ) { /* Mark the pxDescriptor buffer as free as uip_buf is going to be set to the buffer that contains the received data. */ prvReturnBuffer( uip_buf ); /* Point uip_buf to the data about to be processed. */ uip_buf = ( void * ) pxCurrentRxDesc->data; uip_buf = ( void * ) __REV( ( unsigned long ) uip_buf ); /* Allocate a new buffer to the descriptor, as uip_buf is now using it's old descriptor. */ pxCurrentRxDesc->data = ( uint8_t * ) prvGetNextBuffer(); pxCurrentRxDesc->data = ( uint8_t* ) __REV( ( unsigned long ) pxCurrentRxDesc->data ); /* Prepare the descriptor to go again. */ pxCurrentRxDesc->status |= RX_BD_E; /* Move onto the next buffer in the ring. */ ulRxDescriptorIndex++; if( ulRxDescriptorIndex >= emacNUM_RX_DESCRIPTORS ) { ulRxDescriptorIndex = 0UL; } pxCurrentRxDesc = &( xRxDescriptors[ ulRxDescriptorIndex ] ); /* Restart Ethernet if it has stopped */ ENET_RDAR = ENET_RDAR_RDAR_MASK; } return usBytesReceived; } /*-----------------------------------------------------------*/ static void prvReturnBuffer( unsigned char *pucBuffer ) { unsigned long ul; /* Return a buffer to the pool of free buffers. */ for( ul = 0; ul < emacNUM_BUFFERS; ul++ ) { if( &( xEthernetBuffers[ ul ][ 0 ] ) == ( void * ) pucBuffer ) { ucBufferInUse[ ul ] = pdFALSE; break; } } } /*-----------------------------------------------------------*/ static unsigned short prvCheckRxStatus( void ) { unsigned long usReturn = 0; if( ( pxCurrentRxDesc->status & RX_BD_E ) != 0 ) { /* Current descriptor is still active. */ } else { /* The descriptor contains a frame. Because of the size of the buffers the frame should always be complete. */ usReturn = pxCurrentRxDesc->length; } return usReturn; } /*-----------------------------------------------------------*/ void vEMAC_TxISRHandler( void ) { /* Clear the interrupt. */ ENET_EIR = ENET_EIR_TXF_MASK; /* Check the buffers have not already been freed in the first of the two Tx interrupts - which could potentially happen if the second Tx completed during the interrupt for the first Tx. */ if( xTxDescriptors[ 0 ].data != NULL ) { if( ( ( xTxDescriptors[ 0 ].status & TX_BD_R ) == 0 ) && ( ( xTxDescriptors[ 0 ].status & TX_BD_R ) == 0 ) ) { configASSERT( xTxDescriptors[ 0 ].data == xTxDescriptors[ 1 ].data ); xTxDescriptors[ 0 ].data = ( uint8_t* ) __REV( ( unsigned long ) xTxDescriptors[ 0 ].data ); prvReturnBuffer( xTxDescriptors[ 0 ].data ); /* Just to mark the fact that the buffer has already been released. */ xTxDescriptors[ 0 ].data = NULL; } } } /*-----------------------------------------------------------*/ void vEMAC_RxISRHandler( void ) { const unsigned long ulRxEvent = uipETHERNET_RX_EVENT; long lHigherPriorityTaskWoken = pdFALSE; extern QueueHandle_t xEMACEventQueue; /* Clear the interrupt. */ ENET_EIR = ENET_EIR_RXF_MASK; /* An Ethernet Rx event has occurred. */ xQueueSendFromISR( xEMACEventQueue, &ulRxEvent, &lHigherPriorityTaskWoken ); portEND_SWITCHING_ISR( lHigherPriorityTaskWoken ); } /*-----------------------------------------------------------*/ void vEMAC_ErrorISRHandler( void ) { /* Clear the interrupt. */ ENET_EIR = ENET_EIR & ENET_EIMR; /* Attempt recovery. Not very sophisticated. */ prvInitialiseDescriptors(); ENET_RDAR = ENET_RDAR_RDAR_MASK; } /*-----------------------------------------------------------*/
298218.c
/* dfslib library for random data generation, T10.273-T10.717; $DVS:time$ */ #include <stdlib.h> #include <time.h> #if !defined(_WIN32) && !defined(_WIN64) #include <unistd.h> #include <sys/time.h> #include <sys/times.h> #define USE_RAND48 #else #include <Windows.h> #include <process.h> #define getpid _getpid #endif #include "dfslib_random.h" #ifdef __cplusplus extern "C" { #endif unsigned dfslib_random_get(unsigned limit) { unsigned res; #ifdef USE_RAND48 res = mrand48(); #else res = rand(); #endif if (limit) res %= limit; return res; } void dfslib_random_fill(void *buf, unsigned long len, int xor, struct dfslib_string *tip) { unsigned res = 0, bytes3 = 0, rnd, tmp = 0; while (len) { rnd = dfslib_random_get(0); if (tip) { int uni = dfslib_unicode_read(tip, &tmp); if (uni < 0) { tmp = 0; uni = dfslib_unicode_read(tip, &tmp); } rnd += uni; } res *= 41, res += rnd % 41, bytes3 += 2; if (bytes3 >= 10) { if (xor) *(unsigned char *)buf ^= (unsigned char)res; else *(unsigned char *)buf = (unsigned char)res; res >>= 8, bytes3 -= 3; buf = (unsigned char *)buf + 1, --len; } } } void dfslib_random_sector(dfs32 *sector, struct dfslib_crypt *crypt0, struct dfslib_string *password, struct dfslib_string *tip) { struct dfslib_crypt crypt[1]; struct dfslib_string tip0[1]; char tips[6 * DFSLIB_CRYPT_PWDLEN]; dfs64 nsector; int i; if (crypt0) dfslib_crypt_copy_password(crypt, crypt0); else dfslib_crypt_set_password(crypt, password); if (!tip) { for (i = 0; i < DFSLIB_CRYPT_PWDLEN; ++i) { dfs32 res = crypt->pwd[i]; int j; for (j = 0; j < 6; ++j) tips[i * 6 + j] = (res % 41) + 0x21, res /= 41; } dfslib_utf8_string(tip0, tips, 6 * DFSLIB_CRYPT_PWDLEN); tip = tip0; } for (i = 0; i < 3; ++i) { dfslib_random_fill(sector, 512, i, tip); dfslib_random_fill(&nsector, 8, i, tip); dfslib_crypt_set_sector0(crypt, sector); dfslib_encrypt_sector(crypt, sector, nsector); } } void dfslib_random_init(void) { dfs64 seed = 0, time1, time2, clock, pid; #if !defined(_WIN32) && !defined(_WIN64) struct timeval tv[1]; struct tms tms[1]; gettimeofday(tv, NULL); time1 = tv->tv_sec; time2 = tv->tv_usec; clock = times(tms); #else FILETIME ft[1]; GetSystemTimeAsFileTime(ft); time1 = ft->dwHighDateTime; time2 = ft->dwLowDateTime; clock = GetTickCount(); #endif pid = getpid(); seed ^= time1; seed *= 0x8E230615u; seed ^= time2; seed *= 0x40D95A7Bu; seed ^= clock; seed *= 0x0EE493B1u; seed ^= pid; seed *= 0xB8204941u; dfslib_random_fill(&seed, 8, 1, 0); #if 0 printf("dfslib_random: time=(%lX, %lX), times=%lX, pid=%lX, seed=%llX\n", (long)tv->tv_sec, (long)tv->tv_usec, (long)clock, (long)pid, seed); #endif #ifdef USE_RAND48 { unsigned short xsubi[3]; int i; for (i = 0; i < 3; ++i) xsubi[i] = seed & 0xFFFF, seed >>= 16; seed48(xsubi); } #else srand((unsigned)seed); #endif } #ifdef __cplusplus } #endif
597513.c
// This is an open source non-commercial project. Dear PVS-Studio, please check // it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* * hardcopy.c: printing to paper */ #include <assert.h> #include <inttypes.h> #include <string.h> #include "nvim/ascii.h" #include "nvim/vim.h" #ifdef HAVE_LOCALE_H # include <locale.h> #endif #include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/eval.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/fileio.h" #include "nvim/garray.h" #include "nvim/hardcopy.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" #include "nvim/message.h" #include "nvim/option.h" #include "nvim/os/input.h" #include "nvim/os/os.h" #include "nvim/path.h" #include "nvim/screen.h" #include "nvim/strings.h" #include "nvim/syntax.h" #include "nvim/ui.h" #include "nvim/version.h" /* * To implement printing on a platform, the following functions must be * defined: * * int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) * Called once. Code should display printer dialogue (if appropriate) and * determine printer font and margin settings. Reset has_color if the printer * doesn't support colors at all. * Returns FAIL to abort. * * int mch_print_begin(prt_settings_T *settings) * Called to start the print job. * Return FALSE to abort. * * int mch_print_begin_page(char_u *msg) * Called at the start of each page. * "msg" indicates the progress of the print job, can be NULL. * Return FALSE to abort. * * int mch_print_end_page() * Called at the end of each page. * Return FALSE to abort. * * int mch_print_blank_page() * Called to generate a blank page for collated, duplex, multiple copy * document. Return FALSE to abort. * * void mch_print_end(prt_settings_T *psettings) * Called at normal end of print job. * * void mch_print_cleanup() * Called if print job ends normally or is abandoned. Free any memory, close * devices and handles. Also called when mch_print_begin() fails, but not * when mch_print_init() fails. * * void mch_print_set_font(int Bold, int Italic, int Underline); * Called whenever the font style changes. * * void mch_print_set_bg(uint32_t bgcol); * Called to set the background color for the following text. Parameter is an * RGB value. * * void mch_print_set_fg(uint32_t fgcol); * Called to set the foreground color for the following text. Parameter is an * RGB value. * * mch_print_start_line(int margin, int page_line) * Sets the current position at the start of line "page_line". * If margin is TRUE start in the left margin (for header and line number). * * int mch_print_text_out(char_u *p, size_t len); * Output one character of text p[len] at the current position. * Return TRUE if there is no room for another character in the same line. * * Note that the generic code has no idea of margins. The machine code should * simply make the page look smaller! The header and the line numbers are * printed in the margin. */ static option_table_T printer_opts[OPT_PRINT_NUM_OPTIONS] = { { "top", TRUE, 0, NULL, 0, FALSE }, { "bottom", TRUE, 0, NULL, 0, FALSE }, { "left", TRUE, 0, NULL, 0, FALSE }, { "right", TRUE, 0, NULL, 0, FALSE }, { "header", TRUE, 0, NULL, 0, FALSE }, { "syntax", FALSE, 0, NULL, 0, FALSE }, { "number", FALSE, 0, NULL, 0, FALSE }, { "wrap", FALSE, 0, NULL, 0, FALSE }, { "duplex", FALSE, 0, NULL, 0, FALSE }, { "portrait", FALSE, 0, NULL, 0, FALSE }, { "paper", FALSE, 0, NULL, 0, FALSE }, { "collate", FALSE, 0, NULL, 0, FALSE }, { "jobsplit", FALSE, 0, NULL, 0, FALSE }, { "formfeed", FALSE, 0, NULL, 0, FALSE }, } ; static const uint32_t cterm_color_8[8] = { 0x000000, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, 0x00ffff, 0xffffff }; static const uint32_t cterm_color_16[16] = { 0x000000, 0x0000c0, 0x008000, 0x004080, 0xc00000, 0xc000c0, 0x808000, 0xc0c0c0, 0x808080, 0x6060ff, 0x00ff00, 0x00ffff, 0xff8080, 0xff40ff, 0xffff00, 0xffffff }; static int current_syn_id; #define PRCOLOR_BLACK 0 #define PRCOLOR_WHITE 0xffffff static TriState curr_italic; static TriState curr_bold; static TriState curr_underline; static uint32_t curr_bg; static uint32_t curr_fg; static int page_count; #define OPT_MBFONT_USECOURIER 0 #define OPT_MBFONT_ASCII 1 #define OPT_MBFONT_REGULAR 2 #define OPT_MBFONT_BOLD 3 #define OPT_MBFONT_OBLIQUE 4 #define OPT_MBFONT_BOLDOBLIQUE 5 #define OPT_MBFONT_NUM_OPTIONS 6 static option_table_T mbfont_opts[OPT_MBFONT_NUM_OPTIONS] = { { "c", FALSE, 0, NULL, 0, FALSE }, { "a", FALSE, 0, NULL, 0, FALSE }, { "r", FALSE, 0, NULL, 0, FALSE }, { "b", FALSE, 0, NULL, 0, FALSE }, { "i", FALSE, 0, NULL, 0, FALSE }, { "o", FALSE, 0, NULL, 0, FALSE }, }; /* * These values determine the print position on a page. */ typedef struct { int lead_spaces; // remaining spaces for a TAB int print_pos; // virtual column for computing TABs colnr_T column; // byte column linenr_T file_line; // line nr in the buffer size_t bytes_printed; // bytes printed so far int ff; // seen form feed character } prt_pos_T; struct prt_mediasize_S { char *name; double width; // width and height in points for portrait double height; }; // PS font names, must be in Roman, Bold, Italic, Bold-Italic order struct prt_ps_font_S { int wx; int uline_offset; int uline_width; int bbox_min_y; int bbox_max_y; char *(ps_fontname[4]); }; /* Structures to map user named encoding and mapping to PS equivalents for * building CID font name */ struct prt_ps_encoding_S { char *encoding; char *cmap_encoding; int needs_charset; }; struct prt_ps_charset_S { char *charset; char *cmap_charset; int has_charset; }; // Collections of encodings and charsets for multi-byte printing struct prt_ps_mbfont_S { int num_encodings; struct prt_ps_encoding_S *encodings; int num_charsets; struct prt_ps_charset_S *charsets; char *ascii_enc; char *defcs; }; // Types of PS resource file currently used typedef enum { PRT_RESOURCE_TYPE_PROCSET = 0, PRT_RESOURCE_TYPE_ENCODING = 1, PRT_RESOURCE_TYPE_CMAP = 2, } PrtResourceType; // String versions of PS resource types static const char *const prt_resource_types[] = { [PRT_RESOURCE_TYPE_PROCSET] = "procset", [PRT_RESOURCE_TYPE_ENCODING] = "encoding", [PRT_RESOURCE_TYPE_CMAP] = "cmap", }; struct prt_ps_resource_S { char_u name[64]; char_u filename[MAXPATHL + 1]; PrtResourceType type; char_u title[256]; char_u version[256]; }; struct prt_dsc_comment_S { char *string; int len; int type; }; struct prt_dsc_line_S { int type; char_u *string; int len; }; /* Static buffer to read initial comments in a resource file, some can have a * couple of KB of comments! */ #define PRT_FILE_BUFFER_LEN (2048) struct prt_resfile_buffer_S { char_u buffer[PRT_FILE_BUFFER_LEN]; int len; int line_start; int line_end; }; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "hardcopy.c.generated.h" #endif /* * Parse 'printoptions' and set the flags in "printer_opts". * Returns an error message or NULL; */ char_u *parse_printoptions(void) { return parse_list_options(p_popt, printer_opts, OPT_PRINT_NUM_OPTIONS); } /* * Parse 'printoptions' and set the flags in "printer_opts". * Returns an error message or NULL; */ char_u *parse_printmbfont(void) { return parse_list_options(p_pmfn, mbfont_opts, OPT_MBFONT_NUM_OPTIONS); } /* * Parse a list of options in the form * option:value,option:value,option:value * * "value" can start with a number which is parsed out, e.g. margin:12mm * * Returns an error message for an illegal option, NULL otherwise. * Only used for the printer at the moment... */ static char_u *parse_list_options(char_u *option_str, option_table_T *table, size_t table_size) { option_table_T *old_opts; char_u *ret = NULL; char_u *stringp; char_u *colonp; char_u *commap; char_u *p; size_t idx = 0; // init for GCC int len; // Save the old values, so that they can be restored in case of an error. old_opts = (option_table_T *)xmalloc(sizeof(option_table_T) * table_size); for (idx = 0; idx < table_size; idx++) { old_opts[idx] = table[idx]; table[idx].present = false; } /* * Repeat for all comma separated parts. */ stringp = option_str; while (*stringp) { colonp = vim_strchr(stringp, ':'); if (colonp == NULL) { ret = (char_u *)N_("E550: Missing colon"); break; } commap = vim_strchr(stringp, ','); if (commap == NULL) { commap = option_str + STRLEN(option_str); } len = (int)(colonp - stringp); for (idx = 0; idx < table_size; ++idx) { if (STRNICMP(stringp, table[idx].name, len) == 0) { break; } } if (idx == table_size) { ret = (char_u *)N_("E551: Illegal component"); break; } p = colonp + 1; table[idx].present = TRUE; if (table[idx].hasnum) { if (!ascii_isdigit(*p)) { ret = (char_u *)N_("E552: digit expected"); break; } table[idx].number = getdigits_int(&p, false, 0); } table[idx].string = p; table[idx].strlen = (int)(commap - p); stringp = commap; if (*stringp == ',') { ++stringp; } } if (ret != NULL) { // Restore old options in case of error for (idx = 0; idx < table_size; idx++) { table[idx] = old_opts[idx]; } } xfree(old_opts); return ret; } /* * If using a dark background, the colors will probably be too bright to show * up well on white paper, so reduce their brightness. */ static uint32_t darken_rgb(uint32_t rgb) { return ((rgb >> 17) << 16) + (((rgb & 0xff00) >> 9) << 8) + ((rgb & 0xff) >> 1); } static uint32_t prt_get_term_color(int colorindex) { // TODO(vim): Should check for xterm with 88 or 256 colors. if (t_colors > 8) { return cterm_color_16[colorindex % 16]; } return cterm_color_8[colorindex % 8]; } static void prt_get_attr(int hl_id, prt_text_attr_T *pattr, int modec) { int colorindex; uint32_t fg_color; pattr->bold = (highlight_has_attr(hl_id, HL_BOLD, modec) != NULL); pattr->italic = (highlight_has_attr(hl_id, HL_ITALIC, modec) != NULL); pattr->underline = (highlight_has_attr(hl_id, HL_UNDERLINE, modec) != NULL); pattr->undercurl = (highlight_has_attr(hl_id, HL_UNDERCURL, modec) != NULL); { const char *color = highlight_color(hl_id, "fg", modec); if (color == NULL) { colorindex = 0; } else { colorindex = atoi(color); } if (colorindex >= 0 && colorindex < t_colors) { fg_color = prt_get_term_color(colorindex); } else { fg_color = PRCOLOR_BLACK; } } if (fg_color == PRCOLOR_WHITE) { fg_color = PRCOLOR_BLACK; } else if (*p_bg == 'd') { fg_color = darken_rgb(fg_color); } pattr->fg_color = fg_color; pattr->bg_color = PRCOLOR_WHITE; } static void prt_set_fg(uint32_t fg) { if (fg != curr_fg) { curr_fg = fg; mch_print_set_fg(fg); } } static void prt_set_bg(uint32_t bg) { if (bg != curr_bg) { curr_bg = bg; mch_print_set_bg(bg); } } static void prt_set_font(const TriState bold, const TriState italic, const TriState underline) { if (curr_bold != bold || curr_italic != italic || curr_underline != underline) { curr_underline = underline; curr_italic = italic; curr_bold = bold; mch_print_set_font(bold, italic, underline); } } // Print the line number in the left margin. static void prt_line_number(prt_settings_T *const psettings, const int page_line, const linenr_T lnum) { prt_set_fg(psettings->number.fg_color); prt_set_bg(psettings->number.bg_color); prt_set_font(psettings->number.bold, psettings->number.italic, psettings->number.underline); mch_print_start_line(true, page_line); // Leave two spaces between the number and the text; depends on // PRINT_NUMBER_WIDTH. char_u tbuf[20]; snprintf((char *)tbuf, sizeof(tbuf), "%6ld", (long)lnum); for (int i = 0; i < 6; i++) { (void)mch_print_text_out(&tbuf[i], 1); } if (psettings->do_syntax) { // Set colors for next character. current_syn_id = -1; } else { // Set colors and font back to normal. prt_set_fg(PRCOLOR_BLACK); prt_set_bg(PRCOLOR_WHITE); prt_set_font(kFalse, kFalse, kFalse); } } /* * Get the currently effective header height. */ int prt_header_height(void) { if (printer_opts[OPT_PRINT_HEADERHEIGHT].present) { return printer_opts[OPT_PRINT_HEADERHEIGHT].number; } return 2; } /* * Return TRUE if using a line number for printing. */ int prt_use_number(void) { return printer_opts[OPT_PRINT_NUMBER].present && TOLOWER_ASC(printer_opts[OPT_PRINT_NUMBER].string[0]) == 'y'; } /* * Return the unit used in a margin item in 'printoptions'. * Returns PRT_UNIT_NONE if not recognized. */ int prt_get_unit(int idx) { int u = PRT_UNIT_NONE; int i; static char *(units[4]) = PRT_UNIT_NAMES; if (printer_opts[idx].present) { for (i = 0; i < 4; ++i) { if (STRNICMP(printer_opts[idx].string, units[i], 2) == 0) { u = i; break; } } } return u; } // Print the page header. static void prt_header(prt_settings_T *const psettings, const int pagenum, const linenr_T lnum) { int width = psettings->chars_per_line; // Also use the space for the line number. if (prt_use_number()) { width += PRINT_NUMBER_WIDTH; } assert(width >= 0); const size_t tbuf_size = (size_t)width + IOSIZE; char_u *tbuf = xmalloc(tbuf_size); if (*p_header != NUL) { linenr_T tmp_lnum, tmp_topline, tmp_botline; int use_sandbox = FALSE; /* * Need to (temporarily) set current line number and first/last line * number on the 'window'. Since we don't know how long the page is, * set the first and current line number to the top line, and guess * that the page length is 64. */ tmp_lnum = curwin->w_cursor.lnum; tmp_topline = curwin->w_topline; tmp_botline = curwin->w_botline; curwin->w_cursor.lnum = lnum; curwin->w_topline = lnum; curwin->w_botline = lnum + 63; printer_page_num = pagenum; use_sandbox = was_set_insecurely(curwin, (char_u *)"printheader", 0); build_stl_str_hl(curwin, tbuf, (size_t)width + IOSIZE, p_header, use_sandbox, ' ', width, NULL, NULL); // Reset line numbers curwin->w_cursor.lnum = tmp_lnum; curwin->w_topline = tmp_topline; curwin->w_botline = tmp_botline; } else { snprintf((char *)tbuf, tbuf_size, _("Page %d"), pagenum); } prt_set_fg(PRCOLOR_BLACK); prt_set_bg(PRCOLOR_WHITE); prt_set_font(kTrue, kFalse, kFalse); // Use a negative line number to indicate printing in the top margin. int page_line = 0 - prt_header_height(); mch_print_start_line(true, page_line); for (char_u *p = tbuf; *p != NUL; ) { const int l = (*mb_ptr2len)(p); assert(l >= 0); if (mch_print_text_out(p, (size_t)l)) { page_line++; if (page_line >= 0) { // out of room in header break; } mch_print_start_line(true, page_line); } p += l; } xfree(tbuf); if (psettings->do_syntax) { // Set colors for next character. current_syn_id = -1; } else { // Set colors and font back to normal. prt_set_fg(PRCOLOR_BLACK); prt_set_bg(PRCOLOR_WHITE); prt_set_font(kFalse, kFalse, kFalse); } } /* * Display a print status message. */ static void prt_message(char_u *s) { // TODO(bfredl): delete this grid_fill(&default_grid, Rows - 1, Rows, 0, Columns, ' ', ' ', 0); grid_puts(&default_grid, s, Rows - 1, 0, HL_ATTR(HLF_R)); ui_flush(); } void ex_hardcopy(exarg_T *eap) { linenr_T lnum; int collated_copies, uncollated_copies; prt_settings_T settings; size_t bytes_to_print = 0; int page_line; int jobsplit; memset(&settings, 0, sizeof(prt_settings_T)); settings.has_color = TRUE; if (*eap->arg == '>') { char_u *errormsg = NULL; // Expand things like "%.ps". if (expand_filename(eap, eap->cmdlinep, &errormsg) == FAIL) { if (errormsg != NULL) { EMSG(errormsg); } return; } settings.outfile = skipwhite(eap->arg + 1); } else if (*eap->arg != NUL) { settings.arguments = eap->arg; } /* * Initialise for printing. Ask the user for settings, unless forceit is * set. * The mch_print_init() code should set up margins if applicable. (It may * not be a real printer - for example the engine might generate HTML or * PS.) */ if (mch_print_init(&settings, curbuf->b_fname == NULL ? buf_spname(curbuf) : curbuf->b_sfname == NULL ? curbuf->b_fname : curbuf->b_sfname, eap->forceit) == FAIL) { return; } settings.modec = 'c'; if (!syntax_present(curwin)) { settings.do_syntax = FALSE; } else if (printer_opts[OPT_PRINT_SYNTAX].present && TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) != 'a') { settings.do_syntax = (TOLOWER_ASC(printer_opts[OPT_PRINT_SYNTAX].string[0]) == 'y'); } else { settings.do_syntax = settings.has_color; } // Set up printing attributes for line numbers settings.number.fg_color = PRCOLOR_BLACK; settings.number.bg_color = PRCOLOR_WHITE; settings.number.bold = kFalse; settings.number.italic = kTrue; settings.number.underline = kFalse; // Syntax highlighting of line numbers. if (prt_use_number() && settings.do_syntax) { int id = syn_name2id((char_u *)"LineNr"); if (id > 0) { id = syn_get_final_id(id); } prt_get_attr(id, &settings.number, settings.modec); } /* * Estimate the total lines to be printed */ for (lnum = eap->line1; lnum <= eap->line2; lnum++) { bytes_to_print += STRLEN(skipwhite(ml_get(lnum))); } if (bytes_to_print == 0) { MSG(_("No text to be printed")); goto print_fail_no_begin; } // Set colors and font to normal. curr_bg = 0xffffffff; curr_fg = 0xffffffff; curr_italic = kNone; curr_bold = kNone; curr_underline = kNone; prt_set_fg(PRCOLOR_BLACK); prt_set_bg(PRCOLOR_WHITE); prt_set_font(kFalse, kFalse, kFalse); current_syn_id = -1; jobsplit = (printer_opts[OPT_PRINT_JOBSPLIT].present && TOLOWER_ASC(printer_opts[OPT_PRINT_JOBSPLIT].string[0]) == 'y'); if (!mch_print_begin(&settings)) { goto print_fail_no_begin; } /* * Loop over collated copies: 1 2 3, 1 2 3, ... */ page_count = 0; for (collated_copies = 0; collated_copies < settings.n_collated_copies; collated_copies++) { prt_pos_T prtpos; // current print position prt_pos_T page_prtpos; // print position at page start int side; memset(&page_prtpos, 0, sizeof(prt_pos_T)); page_prtpos.file_line = eap->line1; prtpos = page_prtpos; if (jobsplit && collated_copies > 0) { // Splitting jobs: Stop a previous job and start a new one. mch_print_end(&settings); if (!mch_print_begin(&settings)) { goto print_fail_no_begin; } } /* * Loop over all pages in the print job: 1 2 3 ... */ for (page_count = 0; prtpos.file_line <= eap->line2; ++page_count) { /* * Loop over uncollated copies: 1 1 1, 2 2 2, 3 3 3, ... * For duplex: 12 12 12 34 34 34, ... */ for (uncollated_copies = 0; uncollated_copies < settings.n_uncollated_copies; uncollated_copies++) { // Set the print position to the start of this page. prtpos = page_prtpos; /* * Do front and rear side of a page. */ for (side = 0; side <= settings.duplex; ++side) { /* * Print one page. */ // Check for interrupt character every page. os_breakcheck(); if (got_int || settings.user_abort) { goto print_fail; } assert(prtpos.bytes_printed <= SIZE_MAX / 100); sprintf((char *)IObuff, _("Printing page %d (%zu%%)"), page_count + 1 + side, prtpos.bytes_printed * 100 / bytes_to_print); if (!mch_print_begin_page(IObuff)) { goto print_fail; } if (settings.n_collated_copies > 1) { sprintf((char *)IObuff + STRLEN(IObuff), _(" Copy %d of %d"), collated_copies + 1, settings.n_collated_copies); } prt_message(IObuff); /* * Output header if required */ if (prt_header_height() > 0) { prt_header(&settings, page_count + 1 + side, prtpos.file_line); } for (page_line = 0; page_line < settings.lines_per_page; ++page_line) { prtpos.column = hardcopy_line(&settings, page_line, &prtpos); if (prtpos.column == 0) { // finished a file line prtpos.bytes_printed += STRLEN(skipwhite(ml_get(prtpos.file_line))); if (++prtpos.file_line > eap->line2) { break; // reached the end } } else if (prtpos.ff) { /* Line had a formfeed in it - start new page but * stay on the current line */ break; } } if (!mch_print_end_page()) { goto print_fail; } if (prtpos.file_line > eap->line2) { break; // reached the end } } /* * Extra blank page for duplexing with odd number of pages and * more copies to come. */ if (prtpos.file_line > eap->line2 && settings.duplex && side == 0 && uncollated_copies + 1 < settings.n_uncollated_copies) { if (!mch_print_blank_page()) { goto print_fail; } } } if (settings.duplex && prtpos.file_line <= eap->line2) { ++page_count; } // Remember the position where the next page starts. page_prtpos = prtpos; } vim_snprintf((char *)IObuff, IOSIZE, _("Printed: %s"), settings.jobname); prt_message(IObuff); } print_fail: if (got_int || settings.user_abort) { sprintf((char *)IObuff, "%s", _("Printing aborted")); prt_message(IObuff); } mch_print_end(&settings); print_fail_no_begin: mch_print_cleanup(); } /* * Print one page line. * Return the next column to print, or zero if the line is finished. */ static colnr_T hardcopy_line(prt_settings_T *psettings, int page_line, prt_pos_T *ppos) { colnr_T col; char_u *line; int need_break = FALSE; int outputlen; int tab_spaces; int print_pos; prt_text_attr_T attr; int id; if (ppos->column == 0 || ppos->ff) { print_pos = 0; tab_spaces = 0; if (!ppos->ff && prt_use_number()) { prt_line_number(psettings, page_line, ppos->file_line); } ppos->ff = FALSE; } else { // left over from wrap halfway through a tab print_pos = ppos->print_pos; tab_spaces = ppos->lead_spaces; } mch_print_start_line(false, page_line); line = ml_get(ppos->file_line); /* * Loop over the columns until the end of the file line or right margin. */ for (col = ppos->column; line[col] != NUL && !need_break; col += outputlen) { if ((outputlen = (*mb_ptr2len)(line + col)) < 1) { outputlen = 1; } // syntax highlighting stuff. if (psettings->do_syntax) { id = syn_get_id(curwin, ppos->file_line, col, 1, NULL, FALSE); if (id > 0) { id = syn_get_final_id(id); } else { id = 0; } // Get the line again, a multi-line regexp may invalidate it. line = ml_get(ppos->file_line); if (id != current_syn_id) { current_syn_id = id; prt_get_attr(id, &attr, psettings->modec); prt_set_font(attr.bold, attr.italic, attr.underline); prt_set_fg(attr.fg_color); prt_set_bg(attr.bg_color); } } /* * Appropriately expand any tabs to spaces. */ if (line[col] == TAB || tab_spaces != 0) { if (tab_spaces == 0) { tab_spaces = tabstop_padding(print_pos, curbuf->b_p_ts, curbuf->b_p_vts_array); } while (tab_spaces > 0) { need_break = mch_print_text_out((char_u *)" ", 1); print_pos++; tab_spaces--; if (need_break) { break; } } // Keep the TAB if we didn't finish it. if (need_break && tab_spaces > 0) { break; } } else if (line[col] == FF && printer_opts[OPT_PRINT_FORMFEED].present && TOLOWER_ASC(printer_opts[OPT_PRINT_FORMFEED].string[0]) == 'y') { ppos->ff = TRUE; need_break = 1; } else { need_break = mch_print_text_out(line + col, (size_t)outputlen); print_pos += utf_ptr2cells(line + col); } } ppos->lead_spaces = tab_spaces; ppos->print_pos = print_pos; /* * Start next line of file if we clip lines, or have reached end of the * line, unless we are doing a formfeed. */ if (!ppos->ff && (line[col] == NUL || (printer_opts[OPT_PRINT_WRAP].present && TOLOWER_ASC(printer_opts[OPT_PRINT_WRAP].string[0]) == 'n'))) { return 0; } return col; } /* * PS printer stuff. * * Sources of information to help maintain the PS printing code: * * 1. PostScript Language Reference, 3rd Edition, * Addison-Wesley, 1999, ISBN 0-201-37922-8 * 2. PostScript Language Program Design, * Addison-Wesley, 1988, ISBN 0-201-14396-8 * 3. PostScript Tutorial and Cookbook, * Addison Wesley, 1985, ISBN 0-201-10179-3 * 4. PostScript Language Document Structuring Conventions Specification, * version 3.0, * Adobe Technote 5001, 25th September 1992 * 5. PostScript Printer Description File Format Specification, Version 4.3, * Adobe technote 5003, 9th February 1996 * 6. Adobe Font Metrics File Format Specification, Version 4.1, * Adobe Technote 5007, 7th October 1998 * 7. Adobe CMap and CIDFont Files Specification, Version 1.0, * Adobe Technote 5014, 8th October 1996 * 8. Adobe CJKV Character Collections and CMaps for CID-Keyed Fonts, * Adoboe Technote 5094, 8th September, 2001 * 9. CJKV Information Processing, 2nd Edition, * O'Reilly, 2002, ISBN 1-56592-224-7 * * Some of these documents can be found in PDF form on Adobe's web site - * http://www.adobe.com */ #define PRT_PS_DEFAULT_DPI (72) // Default user space resolution #define PRT_PS_DEFAULT_FONTSIZE (10) #define PRT_MEDIASIZE_LEN (sizeof(prt_mediasize) / \ sizeof(struct prt_mediasize_S)) static struct prt_mediasize_S prt_mediasize[] = { { "A4", 595.0, 842.0 }, { "letter", 612.0, 792.0 }, { "10x14", 720.0, 1008.0 }, { "A3", 842.0, 1191.0 }, { "A5", 420.0, 595.0 }, { "B4", 729.0, 1032.0 }, { "B5", 516.0, 729.0 }, { "executive", 522.0, 756.0 }, { "folio", 595.0, 935.0 }, { "ledger", 1224.0, 792.0 }, // Yes, it is wider than taller! { "legal", 612.0, 1008.0 }, { "quarto", 610.0, 780.0 }, { "statement", 396.0, 612.0 }, { "tabloid", 792.0, 1224.0 } }; #define PRT_PS_FONT_ROMAN (0) #define PRT_PS_FONT_BOLD (1) #define PRT_PS_FONT_OBLIQUE (2) #define PRT_PS_FONT_BOLDOBLIQUE (3) // Standard font metrics for Courier family static struct prt_ps_font_S prt_ps_courier_font = { 600, -100, 50, -250, 805, { "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique" } }; // Generic font metrics for multi-byte fonts static struct prt_ps_font_S prt_ps_mb_font = { 1000, -100, 50, -250, 805, { NULL, NULL, NULL, NULL } }; // Pointer to current font set being used static struct prt_ps_font_S *prt_ps_font; #define CS_JIS_C_1978 (0x01) #define CS_JIS_X_1983 (0x02) #define CS_JIS_X_1990 (0x04) #define CS_NEC (0x08) #define CS_MSWINDOWS (0x10) #define CS_CP932 (0x20) #define CS_KANJITALK6 (0x40) #define CS_KANJITALK7 (0x80) // Japanese encodings and charsets static struct prt_ps_encoding_S j_encodings[] = { { "iso-2022-jp", NULL, (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990| CS_NEC) }, { "euc-jp", "EUC", (CS_JIS_C_1978|CS_JIS_X_1983|CS_JIS_X_1990) }, { "sjis", "RKSJ", (CS_JIS_C_1978|CS_JIS_X_1983|CS_MSWINDOWS| CS_KANJITALK6|CS_KANJITALK7) }, { "cp932", "RKSJ", CS_JIS_X_1983 }, { "ucs-2", "UCS2", CS_JIS_X_1990 }, { "utf-8", "UTF8", CS_JIS_X_1990 } }; static struct prt_ps_charset_S j_charsets[] = { { "JIS_C_1978", "78", CS_JIS_C_1978 }, { "JIS_X_1983", NULL, CS_JIS_X_1983 }, { "JIS_X_1990", "Hojo", CS_JIS_X_1990 }, { "NEC", "Ext", CS_NEC }, { "MSWINDOWS", "90ms", CS_MSWINDOWS }, { "CP932", "90ms", CS_JIS_X_1983 }, { "KANJITALK6", "83pv", CS_KANJITALK6 }, { "KANJITALK7", "90pv", CS_KANJITALK7 } }; #define CS_GB_2312_80 (0x01) #define CS_GBT_12345_90 (0x02) #define CS_GBK2K (0x04) #define CS_SC_MAC (0x08) #define CS_GBT_90_MAC (0x10) #define CS_GBK (0x20) #define CS_SC_ISO10646 (0x40) // Simplified Chinese encodings and charsets static struct prt_ps_encoding_S sc_encodings[] = { { "iso-2022", NULL, (CS_GB_2312_80|CS_GBT_12345_90) }, { "gb18030", NULL, CS_GBK2K }, { "euc-cn", "EUC", (CS_GB_2312_80|CS_GBT_12345_90|CS_SC_MAC| CS_GBT_90_MAC) }, { "gbk", "EUC", CS_GBK }, { "ucs-2", "UCS2", CS_SC_ISO10646 }, { "utf-8", "UTF8", CS_SC_ISO10646 } }; static struct prt_ps_charset_S sc_charsets[] = { { "GB_2312-80", "GB", CS_GB_2312_80 }, { "GBT_12345-90", "GBT", CS_GBT_12345_90 }, { "MAC", "GBpc", CS_SC_MAC }, { "GBT-90_MAC", "GBTpc", CS_GBT_90_MAC }, { "GBK", "GBK", CS_GBK }, { "GB18030", "GBK2K", CS_GBK2K }, { "ISO10646", "UniGB", CS_SC_ISO10646 } }; #define CS_CNS_PLANE_1 (0x01) #define CS_CNS_PLANE_2 (0x02) #define CS_CNS_PLANE_1_2 (0x04) #define CS_B5 (0x08) #define CS_ETEN (0x10) #define CS_HK_GCCS (0x20) #define CS_HK_SCS (0x40) #define CS_HK_SCS_ETEN (0x80) #define CS_MTHKL (0x100) #define CS_MTHKS (0x200) #define CS_DLHKL (0x400) #define CS_DLHKS (0x800) #define CS_TC_ISO10646 (0x1000) // Traditional Chinese encodings and charsets static struct prt_ps_encoding_S tc_encodings[] = { { "iso-2022", NULL, (CS_CNS_PLANE_1|CS_CNS_PLANE_2) }, { "euc-tw", "EUC", CS_CNS_PLANE_1_2 }, { "big5", "B5", (CS_B5|CS_ETEN|CS_HK_GCCS|CS_HK_SCS| CS_HK_SCS_ETEN|CS_MTHKL|CS_MTHKS|CS_DLHKL| CS_DLHKS) }, { "cp950", "B5", CS_B5 }, { "ucs-2", "UCS2", CS_TC_ISO10646 }, { "utf-8", "UTF8", CS_TC_ISO10646 }, { "utf-16", "UTF16", CS_TC_ISO10646 }, { "utf-32", "UTF32", CS_TC_ISO10646 } }; static struct prt_ps_charset_S tc_charsets[] = { { "CNS_1992_1", "CNS1", CS_CNS_PLANE_1 }, { "CNS_1992_2", "CNS2", CS_CNS_PLANE_2 }, { "CNS_1993", "CNS", CS_CNS_PLANE_1_2 }, { "BIG5", NULL, CS_B5 }, { "CP950", NULL, CS_B5 }, { "ETEN", "ETen", CS_ETEN }, { "HK_GCCS", "HKgccs", CS_HK_GCCS }, { "SCS", "HKscs", CS_HK_SCS }, { "SCS_ETEN", "ETHK", CS_HK_SCS_ETEN }, { "MTHKL", "HKm471", CS_MTHKL }, { "MTHKS", "HKm314", CS_MTHKS }, { "DLHKL", "HKdla", CS_DLHKL }, { "DLHKS", "HKdlb", CS_DLHKS }, { "ISO10646", "UniCNS", CS_TC_ISO10646 } }; #define CS_KR_X_1992 (0x01) #define CS_KR_MAC (0x02) #define CS_KR_X_1992_MS (0x04) #define CS_KR_ISO10646 (0x08) // Korean encodings and charsets static struct prt_ps_encoding_S k_encodings[] = { { "iso-2022-kr", NULL, CS_KR_X_1992 }, { "euc-kr", "EUC", (CS_KR_X_1992|CS_KR_MAC) }, { "johab", "Johab", CS_KR_X_1992 }, { "cp1361", "Johab", CS_KR_X_1992 }, { "uhc", "UHC", CS_KR_X_1992_MS }, { "cp949", "UHC", CS_KR_X_1992_MS }, { "ucs-2", "UCS2", CS_KR_ISO10646 }, { "utf-8", "UTF8", CS_KR_ISO10646 } }; static struct prt_ps_charset_S k_charsets[] = { { "KS_X_1992", "KSC", CS_KR_X_1992 }, { "CP1361", "KSC", CS_KR_X_1992 }, { "MAC", "KSCpc", CS_KR_MAC }, { "MSWINDOWS", "KSCms", CS_KR_X_1992_MS }, { "CP949", "KSCms", CS_KR_X_1992_MS }, { "WANSUNG", "KSCms", CS_KR_X_1992_MS }, { "ISO10646", "UniKS", CS_KR_ISO10646 } }; static struct prt_ps_mbfont_S prt_ps_mbfonts[] = { { ARRAY_SIZE(j_encodings), j_encodings, ARRAY_SIZE(j_charsets), j_charsets, "jis_roman", "JIS_X_1983" }, { ARRAY_SIZE(sc_encodings), sc_encodings, ARRAY_SIZE(sc_charsets), sc_charsets, "gb_roman", "GB_2312-80" }, { ARRAY_SIZE(tc_encodings), tc_encodings, ARRAY_SIZE(tc_charsets), tc_charsets, "cns_roman", "BIG5" }, { ARRAY_SIZE(k_encodings), k_encodings, ARRAY_SIZE(k_charsets), k_charsets, "ks_roman", "KS_X_1992" } }; /* The PS prolog file version number has to match - if the prolog file is * updated, increment the number in the file and here. Version checking was * added as of VIM 6.2. * The CID prolog file version number behaves as per PS prolog. * Table of VIM and prolog versions: * * VIM Prolog CIDProlog * 6.2 1.3 * 7.0 1.4 1.0 */ #define PRT_PROLOG_VERSION ((char_u *)"1.4") #define PRT_CID_PROLOG_VERSION ((char_u *)"1.0") // Strings to look for in a PS resource file #define PRT_RESOURCE_HEADER "%!PS-Adobe-" #define PRT_RESOURCE_RESOURCE "Resource-" #define PRT_RESOURCE_PROCSET "ProcSet" #define PRT_RESOURCE_ENCODING "Encoding" #define PRT_RESOURCE_CMAP "CMap" /* Data for table based DSC comment recognition, easy to extend if VIM needs to * read more comments. */ #define PRT_DSC_MISC_TYPE (-1) #define PRT_DSC_TITLE_TYPE (1) #define PRT_DSC_VERSION_TYPE (2) #define PRT_DSC_ENDCOMMENTS_TYPE (3) #define PRT_DSC_TITLE "%%Title:" #define PRT_DSC_VERSION "%%Version:" #define PRT_DSC_ENDCOMMENTS "%%EndComments:" #define SIZEOF_CSTR(s) (sizeof(s) - 1) static struct prt_dsc_comment_S prt_dsc_table[] = { { PRT_DSC_TITLE, SIZEOF_CSTR(PRT_DSC_TITLE), PRT_DSC_TITLE_TYPE }, { PRT_DSC_VERSION, SIZEOF_CSTR(PRT_DSC_VERSION), PRT_DSC_VERSION_TYPE }, { PRT_DSC_ENDCOMMENTS, SIZEOF_CSTR(PRT_DSC_ENDCOMMENTS), PRT_DSC_ENDCOMMENTS_TYPE } }; /* * Variables for the output PostScript file. */ static FILE *prt_ps_fd; static int prt_file_error; static char_u *prt_ps_file_name = NULL; /* * Various offsets and dimensions in default PostScript user space (points). * Used for text positioning calculations */ static double prt_page_width; static double prt_page_height; static double prt_left_margin; static double prt_right_margin; static double prt_top_margin; static double prt_bottom_margin; static double prt_line_height; static double prt_first_line_height; static double prt_char_width; static double prt_number_width; static double prt_bgcol_offset; static double prt_pos_x_moveto = 0.0; static double prt_pos_y_moveto = 0.0; /* * Various control variables used to decide when and how to change the * PostScript graphics state. */ static bool prt_need_moveto; static bool prt_do_moveto; static bool prt_need_font; static int prt_font; static bool prt_need_underline; static TriState prt_underline; static TriState prt_do_underline; static bool prt_need_fgcol; static uint32_t prt_fgcol; static bool prt_need_bgcol; static bool prt_do_bgcol; static uint32_t prt_bgcol; static uint32_t prt_new_bgcol; static bool prt_attribute_change; static double prt_text_run; static int prt_page_num; static int prt_bufsiz; /* * Variables controlling physical printing. */ static int prt_media; static int prt_portrait; static int prt_num_copies; static int prt_duplex; static int prt_tumble; static int prt_collate; /* * Buffers used when generating PostScript output */ static char_u prt_line_buffer[257]; static garray_T prt_ps_buffer = GA_EMPTY_INIT_VALUE; static int prt_do_conv; static vimconv_T prt_conv; static int prt_out_mbyte; static int prt_custom_cmap; static char prt_cmap[80]; static int prt_use_courier; static bool prt_in_ascii; static bool prt_half_width; static char *prt_ascii_encoding; static char_u prt_hexchar[] = "0123456789abcdef"; static void prt_write_file_raw_len(char_u *buffer, size_t bytes) { if (!prt_file_error && fwrite(buffer, sizeof(char_u), bytes, prt_ps_fd) != bytes) { EMSG(_("E455: Error writing to PostScript output file")); prt_file_error = TRUE; } } static void prt_write_file(char_u *buffer) { prt_write_file_len(buffer, STRLEN(buffer)); } static void prt_write_file_len(char_u *buffer, size_t bytes) { prt_write_file_raw_len(buffer, bytes); } /* * Write a string. */ static void prt_write_string(char *s) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%s", s); prt_write_file(prt_line_buffer); } /* * Write an int and a space. */ static void prt_write_int(int i) { sprintf((char *)prt_line_buffer, "%d ", i); prt_write_file(prt_line_buffer); } /* * Write a boolean and a space. */ static void prt_write_boolean(int b) { sprintf((char *)prt_line_buffer, "%s ", (b ? "T" : "F")); prt_write_file(prt_line_buffer); } /* * Write PostScript to re-encode and define the font. */ static void prt_def_font(char *new_name, char *encoding, int height, char *font) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/_%s /VIM-%s /%s ref\n", new_name, encoding, font); prt_write_file(prt_line_buffer); if (prt_out_mbyte) { sprintf((char *)prt_line_buffer, "/%s %d %f /_%s sffs\n", new_name, height, 500./prt_ps_courier_font.wx, new_name); } else { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/%s %d /_%s ffs\n", new_name, height, new_name); } prt_write_file(prt_line_buffer); } /* * Write a line to define the CID font. */ static void prt_def_cidfont(char *new_name, int height, char *cidfont) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/_%s /%s[/%s] vim_composefont\n", new_name, prt_cmap, cidfont); prt_write_file(prt_line_buffer); vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/%s %d /_%s ffs\n", new_name, height, new_name); prt_write_file(prt_line_buffer); } /* * Write a line to define a duplicate of a CID font */ static void prt_dup_cidfont(char *original_name, char *new_name) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/%s %s d\n", new_name, original_name); prt_write_file(prt_line_buffer); } /* * Convert a real value into an integer and fractional part as integers, with * the fractional part being in the range [0,10^precision). The fractional part * is also rounded based on the precision + 1'th fractional digit. */ static void prt_real_bits(double real, int precision, int *pinteger, int *pfraction) { int integer = (int)real; double fraction = real - integer; if (real < integer) { fraction = -fraction; } for (int i = 0; i < precision; i++) { fraction *= 10.0; } *pinteger = integer; *pfraction = (int)(fraction + 0.5); } /* * Write a real and a space. Save bytes if real value has no fractional part! * We use prt_real_bits() as %f in sprintf uses the locale setting to decide * what decimal point character to use, but PS always requires a '.'. */ static void prt_write_real(double val, int prec) { int integer; int fraction; prt_real_bits(val, prec, &integer, &fraction); // Emit integer part snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%d", integer); prt_write_file(prt_line_buffer); // Only emit fraction if necessary if (fraction != 0) { // Remove any trailing zeros while ((fraction % 10) == 0) { prec--; fraction /= 10; } // Emit fraction left padded with zeros snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), ".%0*d", prec, fraction); prt_write_file(prt_line_buffer); } sprintf((char *)prt_line_buffer, " "); prt_write_file(prt_line_buffer); } /* * Write a line to define a numeric variable. */ static void prt_def_var(char *name, double value, int prec) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "/%s ", name); prt_write_file(prt_line_buffer); prt_write_real(value, prec); sprintf((char *)prt_line_buffer, "d\n"); prt_write_file(prt_line_buffer); } // Convert size from font space to user space at current font scale #define PRT_PS_FONT_TO_USER(scale, size) ((size) * ((scale)/1000.0)) static void prt_flush_buffer(void) { if (!GA_EMPTY(&prt_ps_buffer)) { // Any background color must be drawn first if (prt_do_bgcol && (prt_new_bgcol != PRCOLOR_WHITE)) { unsigned int r, g, b; if (prt_do_moveto) { prt_write_real(prt_pos_x_moveto, 2); prt_write_real(prt_pos_y_moveto, 2); prt_write_string("m\n"); prt_do_moveto = false; } // Size of rect of background color on which text is printed prt_write_real(prt_text_run, 2); prt_write_real(prt_line_height, 2); // Lastly add the color of the background r = (prt_new_bgcol & 0xff0000) >> 16; g = (prt_new_bgcol & 0xff00) >> 8; b = prt_new_bgcol & 0xff; prt_write_real(r / 255.0, 3); prt_write_real(g / 255.0, 3); prt_write_real(b / 255.0, 3); prt_write_string("bg\n"); } /* Draw underlines before the text as it makes it slightly easier to * find the starting point. */ if (prt_do_underline) { if (prt_do_moveto) { prt_write_real(prt_pos_x_moveto, 2); prt_write_real(prt_pos_y_moveto, 2); prt_write_string("m\n"); prt_do_moveto = false; } // Underline length of text run prt_write_real(prt_text_run, 2); prt_write_string("ul\n"); } // Draw the text if (prt_out_mbyte) { prt_write_string("<"); } else { prt_write_string("("); } assert(prt_ps_buffer.ga_len >= 0); prt_write_file_raw_len(prt_ps_buffer.ga_data, (size_t)prt_ps_buffer.ga_len); if (prt_out_mbyte) { prt_write_string(">"); } else { prt_write_string(")"); } // Add a moveto if need be and use the appropriate show procedure if (prt_do_moveto) { prt_write_real(prt_pos_x_moveto, 2); prt_write_real(prt_pos_y_moveto, 2); // moveto and a show prt_write_string("ms\n"); prt_do_moveto = false; } else { // Simple show prt_write_string("s\n"); } ga_clear(&prt_ps_buffer); ga_init(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz); } } static void prt_resource_name(char_u *filename, void *cookie) { char_u *resource_filename = cookie; if (STRLEN(filename) >= MAXPATHL) { *resource_filename = NUL; } else { STRCPY(resource_filename, filename); } } static int prt_find_resource(char *name, struct prt_ps_resource_S *resource) { char_u *buffer; int retval; buffer = xmallocz(MAXPATHL); STRLCPY(resource->name, name, 64); // Look for named resource file in runtimepath STRCPY(buffer, "print"); add_pathsep((char *)buffer); xstrlcat((char *)buffer, name, MAXPATHL); xstrlcat((char *)buffer, ".ps", MAXPATHL); resource->filename[0] = NUL; retval = (do_in_runtimepath(buffer, 0, prt_resource_name, resource->filename) && resource->filename[0] != NUL); xfree(buffer); return retval; } // PS CR and LF characters have platform independent values #define PSLF (0x0a) #define PSCR (0x0d) static struct prt_resfile_buffer_S prt_resfile; static int prt_resfile_next_line(void) { int idx; // Move to start of next line and then find end of line idx = prt_resfile.line_end + 1; while (idx < prt_resfile.len) { if (prt_resfile.buffer[idx] != PSLF && prt_resfile.buffer[idx] != PSCR) { break; } idx++; } prt_resfile.line_start = idx; while (idx < prt_resfile.len) { if (prt_resfile.buffer[idx] == PSLF || prt_resfile.buffer[idx] == PSCR) { break; } idx++; } prt_resfile.line_end = idx; return idx < prt_resfile.len; } static int prt_resfile_strncmp(int offset, const char *string, int len) FUNC_ATTR_NONNULL_ALL { // Force not equal if string is longer than remainder of line if (len > (prt_resfile.line_end - (prt_resfile.line_start + offset))) { return 1; } return STRNCMP(&prt_resfile.buffer[prt_resfile.line_start + offset], string, len); } static int prt_resfile_skip_nonws(int offset) { int idx; idx = prt_resfile.line_start + offset; while (idx < prt_resfile.line_end) { if (isspace(prt_resfile.buffer[idx])) { return idx - prt_resfile.line_start; } idx++; } return -1; } static int prt_resfile_skip_ws(int offset) { int idx; idx = prt_resfile.line_start + offset; while (idx < prt_resfile.line_end) { if (!isspace(prt_resfile.buffer[idx])) { return idx - prt_resfile.line_start; } idx++; } return -1; } /* prt_next_dsc() - returns detail on next DSC comment line found. Returns true * if a DSC comment is found, else false */ static bool prt_next_dsc(struct prt_dsc_line_S *p_dsc_line) FUNC_ATTR_NONNULL_ALL { int comment; int offset; // Move to start of next line if (!prt_resfile_next_line()) { return false; } // DSC comments always start %% if (prt_resfile_strncmp(0, "%%", 2) != 0) { return false; } // Find type of DSC comment for (comment = 0; comment < (int)ARRAY_SIZE(prt_dsc_table); comment++) { if (prt_resfile_strncmp(0, prt_dsc_table[comment].string, prt_dsc_table[comment].len) == 0) { break; } } if (comment != ARRAY_SIZE(prt_dsc_table)) { // Return type of comment p_dsc_line->type = prt_dsc_table[comment].type; offset = prt_dsc_table[comment].len; } else { // Unrecognised DSC comment, skip to ws after comment leader p_dsc_line->type = PRT_DSC_MISC_TYPE; offset = prt_resfile_skip_nonws(0); if (offset == -1) { return false; } } // Skip ws to comment value offset = prt_resfile_skip_ws(offset); if (offset == -1) { return false; } p_dsc_line->string = &prt_resfile.buffer[prt_resfile.line_start + offset]; p_dsc_line->len = prt_resfile.line_end - (prt_resfile.line_start + offset); return true; } /* Improved hand crafted parser to get the type, title, and version number of a * PS resource file so the file details can be added to the DSC header comments. */ static bool prt_open_resource(struct prt_ps_resource_S *resource) FUNC_ATTR_NONNULL_ALL { struct prt_dsc_line_S dsc_line; FILE *fd_resource = os_fopen((char *)resource->filename, READBIN); if (fd_resource == NULL) { EMSG2(_("E624: Can't open file \"%s\""), resource->filename); return false; } memset(prt_resfile.buffer, NUL, PRT_FILE_BUFFER_LEN); // Parse first line to ensure valid resource file prt_resfile.len = (int)fread((char *)prt_resfile.buffer, sizeof(char_u), PRT_FILE_BUFFER_LEN, fd_resource); if (ferror(fd_resource)) { EMSG2(_("E457: Can't read PostScript resource file \"%s\""), resource->filename); fclose(fd_resource); return false; } fclose(fd_resource); prt_resfile.line_end = -1; prt_resfile.line_start = 0; if (!prt_resfile_next_line()) { return false; } int offset = 0; if (prt_resfile_strncmp(offset, PRT_RESOURCE_HEADER, (int)STRLEN(PRT_RESOURCE_HEADER)) != 0) { EMSG2(_("E618: file \"%s\" is not a PostScript resource file"), resource->filename); return false; } // Skip over any version numbers and following ws offset += (int)STRLEN(PRT_RESOURCE_HEADER); offset = prt_resfile_skip_nonws(offset); if (offset == -1) { return false; } offset = prt_resfile_skip_ws(offset); if (offset == -1) { return false; } if (prt_resfile_strncmp(offset, PRT_RESOURCE_RESOURCE, (int)STRLEN(PRT_RESOURCE_RESOURCE)) != 0) { EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } offset += (int)STRLEN(PRT_RESOURCE_RESOURCE); // Decide type of resource in the file if (prt_resfile_strncmp(offset, PRT_RESOURCE_PROCSET, (int)STRLEN(PRT_RESOURCE_PROCSET)) == 0) { resource->type = PRT_RESOURCE_TYPE_PROCSET; } else if (prt_resfile_strncmp(offset, PRT_RESOURCE_ENCODING, (int)STRLEN(PRT_RESOURCE_ENCODING)) == 0) { resource->type = PRT_RESOURCE_TYPE_ENCODING; } else if (prt_resfile_strncmp(offset, PRT_RESOURCE_CMAP, (int)STRLEN(PRT_RESOURCE_CMAP)) == 0) { resource->type = PRT_RESOURCE_TYPE_CMAP; } else { EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } // Look for title and version of resource resource->title[0] = '\0'; resource->version[0] = '\0'; bool seen_title = false; bool seen_version = false; bool seen_all = false; while (!seen_all && prt_next_dsc(&dsc_line)) { switch (dsc_line.type) { case PRT_DSC_TITLE_TYPE: STRLCPY(resource->title, dsc_line.string, dsc_line.len + 1); seen_title = true; if (seen_version) { seen_all = true; } break; case PRT_DSC_VERSION_TYPE: STRLCPY(resource->version, dsc_line.string, dsc_line.len + 1); seen_version = true; if (seen_title) { seen_all = true; } break; case PRT_DSC_ENDCOMMENTS_TYPE: // Won't find title or resource after this comment, stop searching seen_all = true; break; case PRT_DSC_MISC_TYPE: // Not interested in whatever comment this line had break; } } if (!seen_title || !seen_version) { EMSG2(_("E619: file \"%s\" is not a supported PostScript resource file"), resource->filename); return false; } return true; } static bool prt_check_resource(const struct prt_ps_resource_S *resource, const char_u *version) FUNC_ATTR_NONNULL_ALL { // Version number m.n should match, the revision number does not matter if (STRNCMP(resource->version, version, STRLEN(version))) { EMSG2(_("E621: \"%s\" resource file has wrong version"), resource->name); return false; } // Other checks to be added as needed return true; } static void prt_dsc_start(void) { prt_write_string("%!PS-Adobe-3.0\n"); } static void prt_dsc_noarg(char *comment) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%%s\n", comment); prt_write_file(prt_line_buffer); } static void prt_dsc_textline(char *comment, char *text) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%%s: %s\n", comment, text); prt_write_file(prt_line_buffer); } static void prt_dsc_text(char *comment, char *text) { // TODO(vim): - should scan 'text' for any chars needing escaping! vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%%s: (%s)\n", comment, text); prt_write_file(prt_line_buffer); } #define prt_dsc_atend(c) prt_dsc_text((c), "atend") static void prt_dsc_ints(char *comment, int count, int *ints) { int i; vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%%s:", comment); prt_write_file(prt_line_buffer); for (i = 0; i < count; i++) { sprintf((char *)prt_line_buffer, " %d", ints[i]); prt_write_file(prt_line_buffer); } prt_write_string("\n"); } /// @param comment if NULL add to previous static void prt_dsc_resources(const char *comment, const char *type, const char *string) FUNC_ATTR_NONNULL_ARG(2, 3) { if (comment != NULL) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%%s: %s", comment, type); } else { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%+ %s", type); } prt_write_file(prt_line_buffer); vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), " %s\n", string); prt_write_file(prt_line_buffer); } static void prt_dsc_font_resource(char *resource, struct prt_ps_font_S *ps_font) { int i; prt_dsc_resources(resource, "font", ps_font->ps_fontname[PRT_PS_FONT_ROMAN]); for (i = PRT_PS_FONT_BOLD; i <= PRT_PS_FONT_BOLDOBLIQUE; i++) { if (ps_font->ps_fontname[i] != NULL) { prt_dsc_resources(NULL, "font", ps_font->ps_fontname[i]); } } } static void prt_dsc_requirements(int duplex, int tumble, int collate, int color, int num_copies) { /* Only output the comment if we need to. * Note: tumble is ignored if we are not duplexing */ if (!(duplex || collate || color || (num_copies > 1))) { return; } sprintf((char *)prt_line_buffer, "%%%%Requirements:"); prt_write_file(prt_line_buffer); if (duplex) { prt_write_string(" duplex"); if (tumble) { prt_write_string("(tumble)"); } } if (collate) { prt_write_string(" collate"); } if (color) { prt_write_string(" color"); } if (num_copies > 1) { prt_write_string(" numcopies("); // Note: no space wanted so don't use prt_write_int() snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%d", num_copies); prt_write_file(prt_line_buffer); prt_write_string(")"); } prt_write_string("\n"); } static void prt_dsc_docmedia(char *paper_name, double width, double height, double weight, char *colour, char *type) { vim_snprintf((char *)prt_line_buffer, sizeof(prt_line_buffer), "%%%%DocumentMedia: %s ", paper_name); prt_write_file(prt_line_buffer); prt_write_real(width, 2); prt_write_real(height, 2); prt_write_real(weight, 2); if (colour == NULL) { prt_write_string("()"); } else { prt_write_string(colour); } prt_write_string(" "); if (type == NULL) { prt_write_string("()"); } else { prt_write_string(type); } prt_write_string("\n"); } void mch_print_cleanup(void) { if (prt_out_mbyte) { int i; /* Free off all CID font names created, but first clear duplicate * pointers to the same string (when the same font is used for more than * one style). */ for (i = PRT_PS_FONT_ROMAN; i <= PRT_PS_FONT_BOLDOBLIQUE; i++) { if (prt_ps_mb_font.ps_fontname[i] != NULL) { xfree(prt_ps_mb_font.ps_fontname[i]); } prt_ps_mb_font.ps_fontname[i] = NULL; } } if (prt_do_conv) { convert_setup(&prt_conv, NULL, NULL); prt_do_conv = FALSE; } if (prt_ps_fd != NULL) { fclose(prt_ps_fd); prt_ps_fd = NULL; prt_file_error = FALSE; } if (prt_ps_file_name != NULL) { XFREE_CLEAR(prt_ps_file_name); } } static double to_device_units(int idx, double physsize, int def_number) { double ret; int nr; int u = prt_get_unit(idx); if (u == PRT_UNIT_NONE) { u = PRT_UNIT_PERC; nr = def_number; } else { nr = printer_opts[idx].number; } switch (u) { case PRT_UNIT_INCH: ret = nr * PRT_PS_DEFAULT_DPI; break; case PRT_UNIT_MM: ret = nr * PRT_PS_DEFAULT_DPI / 25.4; break; case PRT_UNIT_POINT: ret = nr; break; case PRT_UNIT_PERC: default: ret = physsize * nr / 100; break; } return ret; } /* * Calculate margins for given width and height from printoptions settings. */ static void prt_page_margins(double width, double height, double *left, double *right, double *top, double *bottom) { *left = to_device_units(OPT_PRINT_LEFT, width, 10); *right = width - to_device_units(OPT_PRINT_RIGHT, width, 5); *top = height - to_device_units(OPT_PRINT_TOP, height, 5); *bottom = to_device_units(OPT_PRINT_BOT, height, 5); } static void prt_font_metrics(int font_scale) { prt_line_height = (double)font_scale; prt_char_width = PRT_PS_FONT_TO_USER(font_scale, prt_ps_font->wx); } static int prt_get_cpl(void) { if (prt_use_number()) { prt_number_width = PRINT_NUMBER_WIDTH * prt_char_width; /* If we are outputting multi-byte characters then line numbers will be * printed with half width characters */ if (prt_out_mbyte) { prt_number_width /= 2; } prt_left_margin += prt_number_width; } else { prt_number_width = 0.0; } return (int)((prt_right_margin - prt_left_margin) / prt_char_width); } static void prt_build_cid_fontname(int font, char_u *name, int name_len) { assert(name_len >= 0); char *fontname = xstrndup((char *)name, (size_t)name_len); prt_ps_mb_font.ps_fontname[font] = fontname; } /* * Get number of lines of text that fit on a page (excluding the header). */ static int prt_get_lpp(void) { int lpp; /* * Calculate offset to lower left corner of background rect based on actual * font height (based on its bounding box) and the line height, handling the * case where the font height can exceed the line height. */ prt_bgcol_offset = PRT_PS_FONT_TO_USER(prt_line_height, prt_ps_font->bbox_min_y); if ((prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y) < 1000.0) { prt_bgcol_offset -= PRT_PS_FONT_TO_USER(prt_line_height, (1000.0 - (prt_ps_font->bbox_max_y - prt_ps_font->bbox_min_y)) / 2); } // Get height for topmost line based on background rect offset. prt_first_line_height = prt_line_height + prt_bgcol_offset; // Calculate lpp lpp = (int)((prt_top_margin - prt_bottom_margin) / prt_line_height); // Adjust top margin if there is a header prt_top_margin -= prt_line_height * prt_header_height(); return lpp - prt_header_height(); } static int prt_match_encoding(char *p_encoding, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_encoding_S **pp_mbenc) { int mbenc; int enc_len; struct prt_ps_encoding_S *p_mbenc; *pp_mbenc = NULL; // Look for recognised encoding enc_len = (int)STRLEN(p_encoding); p_mbenc = p_cmap->encodings; for (mbenc = 0; mbenc < p_cmap->num_encodings; mbenc++) { if (STRNICMP(p_mbenc->encoding, p_encoding, enc_len) == 0) { *pp_mbenc = p_mbenc; return TRUE; } p_mbenc++; } return FALSE; } static int prt_match_charset(char *p_charset, struct prt_ps_mbfont_S *p_cmap, struct prt_ps_charset_S **pp_mbchar) { int mbchar; int char_len; struct prt_ps_charset_S *p_mbchar; // Look for recognised character set, using default if one is not given if (*p_charset == NUL) { p_charset = p_cmap->defcs; } char_len = (int)STRLEN(p_charset); p_mbchar = p_cmap->charsets; for (mbchar = 0; mbchar < p_cmap->num_charsets; mbchar++) { if (STRNICMP(p_mbchar->charset, p_charset, char_len) == 0) { *pp_mbchar = p_mbchar; return TRUE; } p_mbchar++; } return FALSE; } int mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit) { int i; char *paper_name; int paper_strlen; int fontsize; char_u *p; int props; int cmap = 0; char_u *p_encoding; struct prt_ps_encoding_S *p_mbenc; struct prt_ps_encoding_S *p_mbenc_first; struct prt_ps_charset_S *p_mbchar = NULL; /* * Set up font and encoding. */ p_encoding = enc_skip(p_penc); if (*p_encoding == NUL) { p_encoding = enc_skip(p_enc); } /* Look for a multi-byte font that matches the encoding and character set. * Only look if multi-byte character set is defined, or using multi-byte * encoding other than Unicode. This is because a Unicode encoding does not * uniquely identify a CJK character set to use. */ p_mbenc = NULL; props = enc_canon_props(p_encoding); if (!(props & ENC_8BIT) && ((*p_pmcs != NUL) || !(props & ENC_UNICODE))) { p_mbenc_first = NULL; int effective_cmap = 0; for (cmap = 0; cmap < (int)ARRAY_SIZE(prt_ps_mbfonts); cmap++) { if (prt_match_encoding((char *)p_encoding, &prt_ps_mbfonts[cmap], &p_mbenc)) { if (p_mbenc_first == NULL) { p_mbenc_first = p_mbenc; effective_cmap = cmap; } if (prt_match_charset((char *)p_pmcs, &prt_ps_mbfonts[cmap], &p_mbchar)) { break; } } } // Use first encoding matched if no charset matched if (p_mbenc_first != NULL && p_mbchar == NULL) { p_mbenc = p_mbenc_first; cmap = effective_cmap; } assert(p_mbenc == NULL || cmap < (int)ARRAY_SIZE(prt_ps_mbfonts)); } prt_out_mbyte = (p_mbenc != NULL); if (prt_out_mbyte) { // Build CMap name - will be same for all multi-byte fonts used prt_cmap[0] = NUL; prt_custom_cmap = (p_mbchar == NULL); if (!prt_custom_cmap) { // Check encoding and character set are compatible if ((p_mbenc->needs_charset & p_mbchar->has_charset) == 0) { EMSG(_("E673: Incompatible multi-byte encoding and character set.")); return FALSE; } // Add charset name if not empty if (p_mbchar->cmap_charset != NULL) { STRLCPY(prt_cmap, p_mbchar->cmap_charset, sizeof(prt_cmap) - 2); STRCAT(prt_cmap, "-"); } } else { // Add custom CMap character set name if (*p_pmcs == NUL) { EMSG(_("E674: printmbcharset cannot be empty with multi-byte encoding.")); return FALSE; } STRLCPY(prt_cmap, p_pmcs, sizeof(prt_cmap) - 2); STRCAT(prt_cmap, "-"); } // CMap name ends with (optional) encoding name and -H for horizontal if (p_mbenc->cmap_encoding != NULL && STRLEN(prt_cmap) + STRLEN(p_mbenc->cmap_encoding) + 3 < sizeof(prt_cmap)) { STRCAT(prt_cmap, p_mbenc->cmap_encoding); STRCAT(prt_cmap, "-"); } STRCAT(prt_cmap, "H"); if (!mbfont_opts[OPT_MBFONT_REGULAR].present) { EMSG(_("E675: No default font specified for multi-byte printing.")); return FALSE; } // Derive CID font names with fallbacks if not defined prt_build_cid_fontname(PRT_PS_FONT_ROMAN, mbfont_opts[OPT_MBFONT_REGULAR].string, mbfont_opts[OPT_MBFONT_REGULAR].strlen); if (mbfont_opts[OPT_MBFONT_BOLD].present) { prt_build_cid_fontname(PRT_PS_FONT_BOLD, mbfont_opts[OPT_MBFONT_BOLD].string, mbfont_opts[OPT_MBFONT_BOLD].strlen); } if (mbfont_opts[OPT_MBFONT_OBLIQUE].present) { prt_build_cid_fontname(PRT_PS_FONT_OBLIQUE, mbfont_opts[OPT_MBFONT_OBLIQUE].string, mbfont_opts[OPT_MBFONT_OBLIQUE].strlen); } if (mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].present) { prt_build_cid_fontname(PRT_PS_FONT_BOLDOBLIQUE, mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].string, mbfont_opts[OPT_MBFONT_BOLDOBLIQUE].strlen); } // Check if need to use Courier for ASCII code range, and if so pick up // the encoding to use prt_use_courier = ( mbfont_opts[OPT_MBFONT_USECOURIER].present && (TOLOWER_ASC(mbfont_opts[OPT_MBFONT_USECOURIER].string[0]) == 'y')); if (prt_use_courier) { // Use national ASCII variant unless ASCII wanted if (mbfont_opts[OPT_MBFONT_ASCII].present && (TOLOWER_ASC(mbfont_opts[OPT_MBFONT_ASCII].string[0]) == 'y')) { prt_ascii_encoding = "ascii"; } else { prt_ascii_encoding = prt_ps_mbfonts[cmap].ascii_enc; } } prt_ps_font = &prt_ps_mb_font; } else { prt_use_courier = FALSE; prt_ps_font = &prt_ps_courier_font; } /* * Find the size of the paper and set the margins. */ prt_portrait = (!printer_opts[OPT_PRINT_PORTRAIT].present || TOLOWER_ASC(printer_opts[OPT_PRINT_PORTRAIT].string[0]) == 'y'); if (printer_opts[OPT_PRINT_PAPER].present) { paper_name = (char *)printer_opts[OPT_PRINT_PAPER].string; paper_strlen = printer_opts[OPT_PRINT_PAPER].strlen; } else { paper_name = "A4"; paper_strlen = 2; } for (i = 0; i < (int)PRT_MEDIASIZE_LEN; ++i) { if (STRLEN(prt_mediasize[i].name) == (unsigned)paper_strlen && STRNICMP(prt_mediasize[i].name, paper_name, paper_strlen) == 0) { break; } } if (i == PRT_MEDIASIZE_LEN) { i = 0; } prt_media = i; /* * Set PS pagesize based on media dimensions and print orientation. * Note: Media and page sizes have defined meanings in PostScript and should * be kept distinct. Media is the paper (or transparency, or ...) that is * printed on, whereas the page size is the area that the PostScript * interpreter renders into. */ if (prt_portrait) { prt_page_width = prt_mediasize[i].width; prt_page_height = prt_mediasize[i].height; } else { prt_page_width = prt_mediasize[i].height; prt_page_height = prt_mediasize[i].width; } // Set PS page margins based on the PS pagesize, not the mediasize - this // needs to be done before the cpl and lpp are calculated. double left, right, top, bottom; prt_page_margins(prt_page_width, prt_page_height, &left, &right, &top, &bottom); prt_left_margin = left; prt_right_margin = right; prt_top_margin = top; prt_bottom_margin = bottom; /* * Set up the font size. */ fontsize = PRT_PS_DEFAULT_FONTSIZE; for (p = p_pfn; (p = vim_strchr(p, ':')) != NULL; ++p) { if (p[1] == 'h' && ascii_isdigit(p[2])) { fontsize = atoi((char *)p + 2); } } prt_font_metrics(fontsize); /* * Return the number of characters per line, and lines per page for the * generic print code. */ psettings->chars_per_line = prt_get_cpl(); psettings->lines_per_page = prt_get_lpp(); // Catch margin settings that leave no space for output! if (psettings->chars_per_line <= 0 || psettings->lines_per_page <= 0) { return FAIL; } /* * Sort out the number of copies to be printed. PS by default will do * uncollated copies for you, so once we know how many uncollated copies are * wanted cache it away and lie to the generic code that we only want one * uncollated copy. */ psettings->n_collated_copies = 1; psettings->n_uncollated_copies = 1; prt_num_copies = 1; prt_collate = (!printer_opts[OPT_PRINT_COLLATE].present || TOLOWER_ASC(printer_opts[OPT_PRINT_COLLATE].string[0]) == 'y'); if (prt_collate) { // TODO(vim): Get number of collated copies wanted. } else { // TODO(vim): Get number of uncollated copies wanted and update the cached // count. } psettings->jobname = jobname; /* * Set up printer duplex and tumble based on Duplex option setting - default * is long sided duplex printing (i.e. no tumble). */ prt_duplex = TRUE; prt_tumble = FALSE; psettings->duplex = 1; if (printer_opts[OPT_PRINT_DUPLEX].present) { if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "off", 3) == 0) { prt_duplex = FALSE; psettings->duplex = 0; } else if (STRNICMP(printer_opts[OPT_PRINT_DUPLEX].string, "short", 5) == 0) { prt_tumble = TRUE; } } // For now user abort not supported psettings->user_abort = 0; // If the user didn't specify a file name, use a temp file. if (psettings->outfile == NULL) { prt_ps_file_name = vim_tempname(); if (prt_ps_file_name == NULL) { EMSG(_(e_notmp)); return FAIL; } prt_ps_fd = os_fopen((char *)prt_ps_file_name, WRITEBIN); } else { p = expand_env_save(psettings->outfile); if (p != NULL) { prt_ps_fd = os_fopen((char *)p, WRITEBIN); xfree(p); } } if (prt_ps_fd == NULL) { EMSG(_("E324: Can't open PostScript output file")); mch_print_cleanup(); return FAIL; } prt_bufsiz = psettings->chars_per_line; if (prt_out_mbyte) { prt_bufsiz *= 2; } ga_init(&prt_ps_buffer, (int)sizeof(char), prt_bufsiz); prt_page_num = 0; prt_attribute_change = false; prt_need_moveto = false; prt_need_font = false; prt_need_fgcol = false; prt_need_bgcol = false; prt_need_underline = false; prt_file_error = FALSE; return OK; } static int prt_add_resource(struct prt_ps_resource_S *resource) { FILE * fd_resource; char_u resource_buffer[512]; size_t bytes_read; fd_resource = os_fopen((char *)resource->filename, READBIN); if (fd_resource == NULL) { EMSG2(_("E456: Can't open file \"%s\""), resource->filename); return FALSE; } switch (resource->type) { case PRT_RESOURCE_TYPE_PROCSET: case PRT_RESOURCE_TYPE_ENCODING: case PRT_RESOURCE_TYPE_CMAP: prt_dsc_resources("BeginResource", prt_resource_types[resource->type], (char *)resource->title); break; default: return FALSE; } prt_dsc_textline("BeginDocument", (char *)resource->filename); for (;; ) { bytes_read = fread((char *)resource_buffer, sizeof(char_u), sizeof(resource_buffer), fd_resource); if (ferror(fd_resource)) { EMSG2(_("E457: Can't read PostScript resource file \"%s\""), resource->filename); fclose(fd_resource); return FALSE; } if (bytes_read == 0) { break; } prt_write_file_raw_len(resource_buffer, bytes_read); if (prt_file_error) { fclose(fd_resource); return FALSE; } } fclose(fd_resource); prt_dsc_noarg("EndDocument"); prt_dsc_noarg("EndResource"); return TRUE; } int mch_print_begin(prt_settings_T *psettings) { int bbox[4]; double left; double right; double top; double bottom; struct prt_ps_resource_S res_prolog; struct prt_ps_resource_S res_encoding; char buffer[256]; char_u *p_encoding; char_u *p; struct prt_ps_resource_S res_cidfont; struct prt_ps_resource_S res_cmap; int retval = FALSE; /* * PS DSC Header comments - no PS code! */ prt_dsc_start(); prt_dsc_textline("Title", (char *)psettings->jobname); if (os_get_user_name(buffer, 256) == FAIL) { STRCPY(buffer, "Unknown"); } prt_dsc_textline("For", buffer); prt_dsc_textline("Creator", longVersion); // Note: to ensure Clean8bit I don't think we can use LC_TIME char ctime_buf[50]; char *p_time = os_ctime(ctime_buf, sizeof(ctime_buf)); // Note: os_ctime() adds a \n so we have to remove it :-( p = vim_strchr((char_u *)p_time, '\n'); if (p != NULL) { *p = NUL; } prt_dsc_textline("CreationDate", p_time); prt_dsc_textline("DocumentData", "Clean8Bit"); prt_dsc_textline("Orientation", "Portrait"); prt_dsc_atend("Pages"); prt_dsc_textline("PageOrder", "Ascend"); /* The bbox does not change with orientation - it is always in the default * user coordinate system! We have to recalculate right and bottom * coordinates based on the font metrics for the bbox to be accurate. */ prt_page_margins(prt_mediasize[prt_media].width, prt_mediasize[prt_media].height, &left, &right, &top, &bottom); bbox[0] = (int)left; if (prt_portrait) { /* In portrait printing the fixed point is the top left corner so we * derive the bbox from that point. We have the expected cpl chars * across the media and lpp lines down the media. */ bbox[1] = (int)(top - (psettings->lines_per_page + prt_header_height()) * prt_line_height); bbox[2] = (int)(left + psettings->chars_per_line * prt_char_width + 0.5); bbox[3] = (int)(top + 0.5); } else { /* In landscape printing the fixed point is the bottom left corner so we * derive the bbox from that point. We have lpp chars across the media * and cpl lines up the media. */ bbox[1] = (int)bottom; bbox[2] = (int)(left + ((psettings->lines_per_page + prt_header_height()) * prt_line_height) + 0.5); bbox[3] = (int)(bottom + psettings->chars_per_line * prt_char_width + 0.5); } prt_dsc_ints("BoundingBox", 4, bbox); // The media width and height does not change with landscape printing! prt_dsc_docmedia(prt_mediasize[prt_media].name, prt_mediasize[prt_media].width, prt_mediasize[prt_media].height, (double)0, NULL, NULL); // Define fonts needed if (!prt_out_mbyte || prt_use_courier) { prt_dsc_font_resource("DocumentNeededResources", &prt_ps_courier_font); } if (prt_out_mbyte) { prt_dsc_font_resource((prt_use_courier ? NULL : "DocumentNeededResources"), &prt_ps_mb_font); if (!prt_custom_cmap) { prt_dsc_resources(NULL, "cmap", prt_cmap); } } // Search for external resources VIM supplies if (!prt_find_resource("prolog", &res_prolog)) { EMSG(_("E456: Can't find PostScript resource file \"prolog.ps\"")); return FALSE; } if (!prt_open_resource(&res_prolog)) { return FALSE; } if (!prt_check_resource(&res_prolog, PRT_PROLOG_VERSION)) { return FALSE; } if (prt_out_mbyte) { // Look for required version of multi-byte printing procset if (!prt_find_resource("cidfont", &res_cidfont)) { EMSG(_("E456: Can't find PostScript resource file \"cidfont.ps\"")); return FALSE; } if (!prt_open_resource(&res_cidfont)) { return FALSE; } if (!prt_check_resource(&res_cidfont, PRT_CID_PROLOG_VERSION)) { return FALSE; } } /* Find an encoding to use for printing. * Check 'printencoding'. If not set or not found, then use 'encoding'. If * that cannot be found then default to "latin1". * Note: VIM specific encoding header is always skipped. */ if (!prt_out_mbyte) { p_encoding = enc_skip(p_penc); if (*p_encoding == NUL || !prt_find_resource((char *)p_encoding, &res_encoding)) { // 'printencoding' not set or not supported - find alternate int props; p_encoding = enc_skip(p_enc); props = enc_canon_props(p_encoding); if (!(props & ENC_8BIT) || !prt_find_resource((char *)p_encoding, &res_encoding)) { // 8-bit 'encoding' is not supported // Use latin1 as default printing encoding p_encoding = (char_u *)"latin1"; if (!prt_find_resource((char *)p_encoding, &res_encoding)) { EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), p_encoding); return FALSE; } } } if (!prt_open_resource(&res_encoding)) { return FALSE; } /* For the moment there are no checks on encoding resource files to * perform */ } else { p_encoding = enc_skip(p_penc); if (*p_encoding == NUL) { p_encoding = enc_skip(p_enc); } if (prt_use_courier) { // Include ASCII range encoding vector if (!prt_find_resource(prt_ascii_encoding, &res_encoding)) { EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), prt_ascii_encoding); return FALSE; } if (!prt_open_resource(&res_encoding)) { return FALSE; } /* For the moment there are no checks on encoding resource files to * perform */ } } prt_conv.vc_type = CONV_NONE; if (!(enc_canon_props(p_enc) & enc_canon_props(p_encoding) & ENC_8BIT)) { // Set up encoding conversion if required if (convert_setup(&prt_conv, p_enc, p_encoding) == FAIL) { emsgf(_("E620: Unable to convert to print encoding \"%s\""), p_encoding); return false; } } prt_do_conv = prt_conv.vc_type != CONV_NONE; if (prt_out_mbyte && prt_custom_cmap) { // Find user supplied CMap if (!prt_find_resource(prt_cmap, &res_cmap)) { EMSG2(_("E456: Can't find PostScript resource file \"%s.ps\""), prt_cmap); return FALSE; } if (!prt_open_resource(&res_cmap)) { return FALSE; } } // List resources supplied STRCPY(buffer, res_prolog.title); STRCAT(buffer, " "); STRCAT(buffer, res_prolog.version); prt_dsc_resources("DocumentSuppliedResources", "procset", buffer); if (prt_out_mbyte) { STRCPY(buffer, res_cidfont.title); STRCAT(buffer, " "); STRCAT(buffer, res_cidfont.version); prt_dsc_resources(NULL, "procset", buffer); if (prt_custom_cmap) { STRCPY(buffer, res_cmap.title); STRCAT(buffer, " "); STRCAT(buffer, res_cmap.version); prt_dsc_resources(NULL, "cmap", buffer); } } if (!prt_out_mbyte || prt_use_courier) { STRCPY(buffer, res_encoding.title); STRCAT(buffer, " "); STRCAT(buffer, res_encoding.version); prt_dsc_resources(NULL, "encoding", buffer); } prt_dsc_requirements(prt_duplex, prt_tumble, prt_collate, psettings->do_syntax , prt_num_copies); prt_dsc_noarg("EndComments"); /* * PS Document page defaults */ prt_dsc_noarg("BeginDefaults"); // List font resources most likely common to all pages if (!prt_out_mbyte || prt_use_courier) { prt_dsc_font_resource("PageResources", &prt_ps_courier_font); } if (prt_out_mbyte) { prt_dsc_font_resource((prt_use_courier ? NULL : "PageResources"), &prt_ps_mb_font); if (!prt_custom_cmap) { prt_dsc_resources(NULL, "cmap", prt_cmap); } } // Paper will be used for all pages prt_dsc_textline("PageMedia", prt_mediasize[prt_media].name); prt_dsc_noarg("EndDefaults"); /* * PS Document prolog inclusion - all required procsets. */ prt_dsc_noarg("BeginProlog"); // Add required procsets - NOTE: order is important! if (!prt_add_resource(&res_prolog)) { return false; } if (prt_out_mbyte) { // Add CID font procset, and any user supplied CMap if (!prt_add_resource(&res_cidfont)) { return false; } if (prt_custom_cmap && !prt_add_resource(&res_cmap)) { return false; } } if (!prt_out_mbyte || prt_use_courier) { /* There will be only one Roman font encoding to be included in the PS * file. */ if (!prt_add_resource(&res_encoding)) { return FALSE; } } prt_dsc_noarg("EndProlog"); /* * PS Document setup - must appear after the prolog */ prt_dsc_noarg("BeginSetup"); // Device setup - page size and number of uncollated copies prt_write_int((int)prt_mediasize[prt_media].width); prt_write_int((int)prt_mediasize[prt_media].height); prt_write_int(0); prt_write_string("sps\n"); prt_write_int(prt_num_copies); prt_write_string("nc\n"); prt_write_boolean(prt_duplex); prt_write_boolean(prt_tumble); prt_write_string("dt\n"); prt_write_boolean(prt_collate); prt_write_string("c\n"); // Font resource inclusion and definition if (!prt_out_mbyte || prt_use_courier) { /* When using Courier for ASCII range when printing multi-byte, need to * pick up ASCII encoding to use with it. */ if (prt_use_courier) { p_encoding = (char_u *)prt_ascii_encoding; } prt_dsc_resources("IncludeResource", "font", prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]); prt_def_font("F0", (char *)p_encoding, (int)prt_line_height, prt_ps_courier_font.ps_fontname[PRT_PS_FONT_ROMAN]); prt_dsc_resources("IncludeResource", "font", prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]); prt_def_font("F1", (char *)p_encoding, (int)prt_line_height, prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLD]); prt_dsc_resources("IncludeResource", "font", prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]); prt_def_font("F2", (char *)p_encoding, (int)prt_line_height, prt_ps_courier_font.ps_fontname[PRT_PS_FONT_OBLIQUE]); prt_dsc_resources("IncludeResource", "font", prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]); prt_def_font("F3", (char *)p_encoding, (int)prt_line_height, prt_ps_courier_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]); } if (prt_out_mbyte) { /* Define the CID fonts to be used in the job. Typically CJKV fonts do * not have an italic form being a western style, so where no font is * defined for these faces VIM falls back to an existing face. * Note: if using Courier for the ASCII range then the printout will * have bold/italic/bolditalic regardless of the setting of printmbfont. */ prt_dsc_resources("IncludeResource", "font", prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]); if (!prt_custom_cmap) { prt_dsc_resources("IncludeResource", "cmap", prt_cmap); } prt_def_cidfont("CF0", (int)prt_line_height, prt_ps_mb_font.ps_fontname[PRT_PS_FONT_ROMAN]); if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD] != NULL) { prt_dsc_resources("IncludeResource", "font", prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]); if (!prt_custom_cmap) { prt_dsc_resources("IncludeResource", "cmap", prt_cmap); } prt_def_cidfont("CF1", (int)prt_line_height, prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLD]); } else { // Use ROMAN for BOLD prt_dup_cidfont("CF0", "CF1"); } if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE] != NULL) { prt_dsc_resources("IncludeResource", "font", prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]); if (!prt_custom_cmap) { prt_dsc_resources("IncludeResource", "cmap", prt_cmap); } prt_def_cidfont("CF2", (int)prt_line_height, prt_ps_mb_font.ps_fontname[PRT_PS_FONT_OBLIQUE]); } else { // Use ROMAN for OBLIQUE prt_dup_cidfont("CF0", "CF2"); } if (prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE] != NULL) { prt_dsc_resources("IncludeResource", "font", prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]); if (!prt_custom_cmap) { prt_dsc_resources("IncludeResource", "cmap", prt_cmap); } prt_def_cidfont("CF3", (int)prt_line_height, prt_ps_mb_font.ps_fontname[PRT_PS_FONT_BOLDOBLIQUE]); } else { // Use BOLD for BOLDOBLIQUE prt_dup_cidfont("CF1", "CF3"); } } // Misc constant vars used for underlining and background rects prt_def_var("UO", PRT_PS_FONT_TO_USER(prt_line_height, prt_ps_font->uline_offset), 2); prt_def_var("UW", PRT_PS_FONT_TO_USER(prt_line_height, prt_ps_font->uline_width), 2); prt_def_var("BO", prt_bgcol_offset, 2); prt_dsc_noarg("EndSetup"); // Fail if any problems writing out to the PS file retval = !prt_file_error; return retval; } void mch_print_end(prt_settings_T *psettings) { prt_dsc_noarg("Trailer"); /* * Output any info we don't know in toto until we finish */ prt_dsc_ints("Pages", 1, &prt_page_num); prt_dsc_noarg("EOF"); /* Write CTRL-D to close serial communication link if used. * NOTHING MUST BE WRITTEN AFTER THIS! */ prt_write_file((char_u *)"\004"); if (!prt_file_error && psettings->outfile == NULL && !got_int && !psettings->user_abort) { // Close the file first. if (prt_ps_fd != NULL) { fclose(prt_ps_fd); prt_ps_fd = NULL; } prt_message((char_u *)_("Sending to printer...")); // Not printing to a file: use 'printexpr' to print the file. if (eval_printexpr((char *)prt_ps_file_name, (char *)psettings->arguments) == FAIL) { EMSG(_("E365: Failed to print PostScript file")); } else { prt_message((char_u *)_("Print job sent.")); } } mch_print_cleanup(); } int mch_print_end_page(void) { prt_flush_buffer(); prt_write_string("re sp\n"); prt_dsc_noarg("PageTrailer"); return !prt_file_error; } int mch_print_begin_page(char_u *str) { int page_num[2]; prt_page_num++; page_num[0] = page_num[1] = prt_page_num; prt_dsc_ints("Page", 2, page_num); prt_dsc_noarg("BeginPageSetup"); prt_write_string("sv\n0 g\n"); prt_in_ascii = !prt_out_mbyte; if (prt_out_mbyte) { prt_write_string("CF0 sf\n"); } else { prt_write_string("F0 sf\n"); } prt_fgcol = PRCOLOR_BLACK; prt_bgcol = PRCOLOR_WHITE; prt_font = PRT_PS_FONT_ROMAN; // Set up page transformation for landscape printing. if (!prt_portrait) { prt_write_int(-((int)prt_mediasize[prt_media].width)); prt_write_string("sl\n"); } prt_dsc_noarg("EndPageSetup"); // We have reset the font attributes, force setting them again. curr_bg = 0xffffffff; curr_fg = 0xffffffff; curr_bold = kNone; return !prt_file_error; } int mch_print_blank_page(void) { return mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE; } static double prt_pos_x = 0; static double prt_pos_y = 0; void mch_print_start_line(const bool margin, const int page_line) { prt_pos_x = prt_left_margin; if (margin) { prt_pos_x -= prt_number_width; } prt_pos_y = prt_top_margin - prt_first_line_height - page_line * prt_line_height; prt_attribute_change = true; prt_need_moveto = true; prt_half_width = false; } int mch_print_text_out(char_u *const textp, size_t len) { char_u *p = textp; char_u ch; char_u ch_buff[8]; char_u *tofree = NULL; double char_width = prt_char_width; /* Ideally VIM would create a rearranged CID font to combine a Roman and * CJKV font to do what VIM is doing here - use a Roman font for characters * in the ASCII range, and the original CID font for everything else. * The problem is that GhostScript still (as of 8.13) does not support * rearranged fonts even though they have been documented by Adobe for 7 * years! If they ever do, a lot of this code will disappear. */ if (prt_use_courier) { const bool in_ascii = (len == 1 && *p < 0x80); if (prt_in_ascii) { if (!in_ascii) { // No longer in ASCII range - need to switch font prt_in_ascii = false; prt_need_font = true; prt_attribute_change = true; } } else if (in_ascii) { // Now in ASCII range - need to switch font prt_in_ascii = true; prt_need_font = true; prt_attribute_change = true; } } if (prt_out_mbyte) { const bool half_width = (utf_ptr2cells(p) == 1); if (half_width) { char_width /= 2; } if (prt_half_width) { if (!half_width) { prt_half_width = false; prt_pos_x += prt_char_width/4; prt_need_moveto = true; prt_attribute_change = true; } } else if (half_width) { prt_half_width = true; prt_pos_x += prt_char_width/4; prt_need_moveto = true; prt_attribute_change = true; } } /* Output any required changes to the graphics state, after flushing any * text buffered so far. */ if (prt_attribute_change) { prt_flush_buffer(); // Reset count of number of chars that will be printed prt_text_run = 0; if (prt_need_moveto) { prt_pos_x_moveto = prt_pos_x; prt_pos_y_moveto = prt_pos_y; prt_do_moveto = true; prt_need_moveto = false; } if (prt_need_font) { if (!prt_in_ascii) { prt_write_string("CF"); } else { prt_write_string("F"); } prt_write_int(prt_font); prt_write_string("sf\n"); prt_need_font = false; } if (prt_need_fgcol) { unsigned int r, g, b; r = (prt_fgcol & 0xff0000) >> 16; g = (prt_fgcol & 0xff00) >> 8; b = prt_fgcol & 0xff; prt_write_real(r / 255.0, 3); if (r == g && g == b) { prt_write_string("g\n"); } else { prt_write_real(g / 255.0, 3); prt_write_real(b / 255.0, 3); prt_write_string("r\n"); } prt_need_fgcol = false; } if (prt_bgcol != PRCOLOR_WHITE) { prt_new_bgcol = prt_bgcol; if (prt_need_bgcol) { prt_do_bgcol = true; } } else { prt_do_bgcol = false; } prt_need_bgcol = false; if (prt_need_underline) { prt_do_underline = prt_underline; } prt_need_underline = false; prt_attribute_change = false; } if (prt_do_conv) { // Convert from multi-byte to 8-bit encoding tofree = p = string_convert(&prt_conv, p, &len); if (p == NULL) { p = (char_u *)""; len = 0; } } if (prt_out_mbyte) { // Multi-byte character strings are represented more efficiently as hex // strings when outputting clean 8 bit PS. while (len-- > 0) { ch = prt_hexchar[(unsigned)(*p) >> 4]; ga_append(&prt_ps_buffer, (char)ch); ch = prt_hexchar[(*p) & 0xf]; ga_append(&prt_ps_buffer, (char)ch); p++; } } else { /* Add next character to buffer of characters to output. * Note: One printed character may require several PS characters to * represent it, but we only count them as one printed character. */ ch = *p; if (ch < 32 || ch == '(' || ch == ')' || ch == '\\') { /* Convert non-printing characters to either their escape or octal * sequence, ensures PS sent over a serial line does not interfere * with the comms protocol. */ ga_append(&prt_ps_buffer, '\\'); switch (ch) { case BS: ga_append(&prt_ps_buffer, 'b'); break; case TAB: ga_append(&prt_ps_buffer, 't'); break; case NL: ga_append(&prt_ps_buffer, 'n'); break; case FF: ga_append(&prt_ps_buffer, 'f'); break; case CAR: ga_append(&prt_ps_buffer, 'r'); break; case '(': ga_append(&prt_ps_buffer, '('); break; case ')': ga_append(&prt_ps_buffer, ')'); break; case '\\': ga_append(&prt_ps_buffer, '\\'); break; default: sprintf((char *)ch_buff, "%03o", (unsigned int)ch); ga_append(&prt_ps_buffer, (char)ch_buff[0]); ga_append(&prt_ps_buffer, (char)ch_buff[1]); ga_append(&prt_ps_buffer, (char)ch_buff[2]); break; } } else { ga_append(&prt_ps_buffer, (char)ch); } } // Need to free any translated characters xfree(tofree); prt_text_run += char_width; prt_pos_x += char_width; // The downside of fp - use relative error on right margin check const double next_pos = prt_pos_x + prt_char_width; const bool need_break = (next_pos > prt_right_margin) && ((next_pos - prt_right_margin) > (prt_right_margin * 1e-5)); if (need_break) { prt_flush_buffer(); } return need_break; } void mch_print_set_font(const TriState iBold, const TriState iItalic, const TriState iUnderline) { int font = 0; if (iBold) { font |= 0x01; } if (iItalic) { font |= 0x02; } if (font != prt_font) { prt_font = font; prt_attribute_change = true; prt_need_font = true; } if (prt_underline != iUnderline) { prt_underline = iUnderline; prt_attribute_change = true; prt_need_underline = true; } } void mch_print_set_bg(uint32_t bgcol) { prt_bgcol = bgcol; prt_attribute_change = true; prt_need_bgcol = true; } void mch_print_set_fg(uint32_t fgcol) { if (fgcol != prt_fgcol) { prt_fgcol = fgcol; prt_attribute_change = true; prt_need_fgcol = true; } }
234481.c
/* * Copyright (c) 1995 * The Regents of the University of California. All rights reserved. * Copyright (C) 1997 * John S. Dyson. All rights reserved. * Copyright (C) 2013-2017 * Matthew Dillon, All rights reserved. * * This code contains ideas from software contributed to Berkeley by * Avadis Tevanian, Jr., Michael Wayne Young, and the Mach Operating * System project at Carnegie-Mellon University. * * This code is derived from software contributed to The DragonFly Project * by Matthew Dillon <[email protected]>. Extensively rewritten. * * 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 "opt_lint.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/proc.h> #include <sys/lock.h> #include <sys/sysctl.h> #include <sys/spinlock.h> #include <sys/thread2.h> #include <sys/spinlock2.h> #include <sys/indefinite2.h> static void undo_shreq(struct lock *lkp); static int undo_upreq(struct lock *lkp); static int undo_exreq(struct lock *lkp); #ifdef DEBUG_CANCEL_LOCKS static int sysctl_cancel_lock(SYSCTL_HANDLER_ARGS); static int sysctl_cancel_test(SYSCTL_HANDLER_ARGS); static struct lock cancel_lk; LOCK_SYSINIT(cancellk, &cancel_lk, "cancel", 0); SYSCTL_PROC(_kern, OID_AUTO, cancel_lock, CTLTYPE_INT|CTLFLAG_RW, 0, 0, sysctl_cancel_lock, "I", "test cancelable locks"); SYSCTL_PROC(_kern, OID_AUTO, cancel_test, CTLTYPE_INT|CTLFLAG_RW, 0, 0, sysctl_cancel_test, "I", "test cancelable locks"); #endif int lock_test_mode; SYSCTL_INT(_debug, OID_AUTO, lock_test_mode, CTLFLAG_RW, &lock_test_mode, 0, ""); /* * Locking primitives implementation. * Locks provide shared/exclusive sychronization. */ #ifdef DEBUG_LOCKS #define COUNT(td, x) (td)->td_locks += (x) #else #define COUNT(td, x) do { } while (0) #endif /* * Helper, assert basic conditions */ static __inline void _lockmgr_assert(struct lock *lkp, u_int flags) { if (mycpu->gd_intr_nesting_level && (flags & LK_NOWAIT) == 0 && (flags & LK_TYPE_MASK) != LK_RELEASE && panic_cpu_gd != mycpu ) { panic("lockmgr %s from %p: called from interrupt, ipi, " "or hard code section", lkp->lk_wmesg, ((int **)&lkp)[-1]); } } /* * Acquire a shared lock */ int lockmgr_shared(struct lock *lkp, u_int flags) { uint32_t extflags; thread_t td; uint64_t count; int error; int pflags; int timo; int didloop; _lockmgr_assert(lkp, flags); extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK; td = curthread; count = lkp->lk_count; cpu_ccfence(); /* * If the caller already holds the lock exclusively then * we silently obtain another count on the exclusive lock. * Avoid accessing lk_lockholder until testing exclusivity. * * WARNING! The old FreeBSD behavior was to downgrade, * but this creates a problem when recursions * return to the caller and the caller expects * its original exclusive lock to remain exclusively * locked. */ if ((count & LKC_XMASK) && lkp->lk_lockholder == td) { KKASSERT(lkp->lk_count & LKC_XMASK); if ((extflags & LK_CANRECURSE) == 0) { if (extflags & LK_NOWAIT) return EBUSY; panic("lockmgr: locking against myself"); } atomic_add_64(&lkp->lk_count, 1); COUNT(td, 1); return 0; } /* * Unless TDF_DEADLKTREAT is set, we cannot add LKC_SCOUNT while * SHARED is set and either EXREQ or UPREQ are set. * * NOTE: In the race-to-0 case (see undo_shreq()), we could * theoretically work the SMASK == 0 case here. */ if ((td->td_flags & TDF_DEADLKTREAT) == 0) { while ((count & LKC_SHARED) && (count & (LKC_EXREQ | LKC_UPREQ))) { /* * Immediate failure conditions */ if (extflags & LK_CANCELABLE) { if (count & LKC_CANCEL) return ENOLCK; } if (extflags & LK_NOWAIT) return EBUSY; /* * Interlocked tsleep */ pflags = (extflags & LK_PCATCH) ? PCATCH : 0; timo = (extflags & LK_TIMELOCK) ? lkp->lk_timo : 0; tsleep_interlock(lkp, pflags); count = atomic_fetchadd_long(&lkp->lk_count, 0); if ((count & LKC_SHARED) && (count & (LKC_EXREQ | LKC_UPREQ))) { error = tsleep(lkp, pflags | PINTERLOCKED, lkp->lk_wmesg, timo); if (error) return error; count = lkp->lk_count; cpu_ccfence(); continue; } break; } } /* * Bump the SCOUNT field. The shared lock is granted only once * the SHARED flag gets set. If it is already set, we are done. * * (Racing an EXREQ or UPREQ operation is ok here, we already did * our duty above). */ count = atomic_fetchadd_64(&lkp->lk_count, LKC_SCOUNT) + LKC_SCOUNT; error = 0; didloop = 0; for (;;) { /* * We may be able to grant ourselves the bit trivially. * We're done once the SHARED bit is granted. */ if ((count & (LKC_XMASK | LKC_EXREQ | LKC_UPREQ | LKC_SHARED)) == 0) { if (atomic_fcmpset_64(&lkp->lk_count, &count, count | LKC_SHARED)) { /* count |= LKC_SHARED; NOT USED */ break; } continue; } if ((td->td_flags & TDF_DEADLKTREAT) && (count & (LKC_XMASK | LKC_SHARED)) == 0) { if (atomic_fcmpset_64(&lkp->lk_count, &count, count | LKC_SHARED)) { /* count |= LKC_SHARED; NOT USED */ break; } continue; } if (count & LKC_SHARED) break; /* * Slow path */ pflags = (extflags & LK_PCATCH) ? PCATCH : 0; timo = (extflags & LK_TIMELOCK) ? lkp->lk_timo : 0; if (extflags & LK_CANCELABLE) { if (count & LKC_CANCEL) { undo_shreq(lkp); error = ENOLCK; break; } } if (extflags & LK_NOWAIT) { undo_shreq(lkp); error = EBUSY; break; } /* * Interlocked after the first loop. */ if (didloop) { error = tsleep(lkp, pflags | PINTERLOCKED, lkp->lk_wmesg, timo); if (extflags & LK_SLEEPFAIL) { undo_shreq(lkp); error = ENOLCK; break; } if (error) { undo_shreq(lkp); break; } } didloop = 1; /* * Reload, shortcut grant case, then loop interlock * and loop. */ count = lkp->lk_count; if (count & LKC_SHARED) break; tsleep_interlock(lkp, pflags); count = atomic_fetchadd_64(&lkp->lk_count, 0); } if (error == 0) COUNT(td, 1); return error; } /* * Acquire an exclusive lock */ int lockmgr_exclusive(struct lock *lkp, u_int flags) { uint64_t count; uint64_t ncount; uint32_t extflags; thread_t td; int error; int pflags; int timo; _lockmgr_assert(lkp, flags); extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK; td = curthread; error = 0; count = lkp->lk_count; cpu_ccfence(); /* * Recursive lock if we already hold it exclusively. Avoid testing * lk_lockholder until after testing lk_count. */ if ((count & LKC_XMASK) && lkp->lk_lockholder == td) { if ((extflags & LK_CANRECURSE) == 0) { if (extflags & LK_NOWAIT) return EBUSY; panic("lockmgr: locking against myself"); } count = atomic_fetchadd_64(&lkp->lk_count, 1) + 1; KKASSERT((count & LKC_XMASK) > 1); COUNT(td, 1); return 0; } /* * Trivially acquire the lock, or block until we can set EXREQ. * Set EXREQ2 if EXREQ is already set or the lock is already * held exclusively. EXREQ2 is an aggregation bit to request * a wakeup. * * WARNING! We cannot set EXREQ if the lock is already held * exclusively because it may race another EXREQ * being cleared and granted. We use the exclusivity * to prevent both EXREQ and UPREQ from being set. * * This means that both shared and exclusive requests * have equal priority against a current exclusive holder's * release. Exclusive requests still have priority over * new shared requests when the lock is already held shared. */ for (;;) { /* * Normal trivial case */ if ((count & (LKC_UPREQ | LKC_EXREQ | LKC_XMASK)) == 0 && ((count & LKC_SHARED) == 0 || (count & LKC_SMASK) == 0)) { ncount = (count + 1) & ~LKC_SHARED; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { lkp->lk_lockholder = td; COUNT(td, 1); return 0; } continue; } if (extflags & LK_CANCELABLE) { if (count & LKC_CANCEL) return ENOLCK; } if (extflags & LK_NOWAIT) return EBUSY; /* * Interlock to set EXREQ or EXREQ2 */ pflags = (extflags & LK_PCATCH) ? PCATCH : 0; timo = (extflags & LK_TIMELOCK) ? lkp->lk_timo : 0; if (count & (LKC_EXREQ | LKC_XMASK)) ncount = count | LKC_EXREQ2; else ncount = count | LKC_EXREQ; tsleep_interlock(lkp, pflags); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { /* * If we successfully transitioned to EXREQ we * can break out, otherwise we had set EXREQ2 and * we block. */ if ((count & (LKC_EXREQ | LKC_XMASK)) == 0) { count = ncount; break; } error = tsleep(lkp, pflags | PINTERLOCKED, lkp->lk_wmesg, timo); count = lkp->lk_count; /* relod */ cpu_ccfence(); } #ifdef INVARIANTS if (lock_test_mode > 0) { --lock_test_mode; print_backtrace(8); } #endif if (error) return error; if (extflags & LK_SLEEPFAIL) return ENOLCK; } /* * Once EXREQ has been set, wait for it to be granted * We enter the loop with tsleep_interlock() already called. */ for (;;) { /* * Waiting for EXREQ to be granted to us. * * NOTE! If we try to trivially get the exclusive lock * (basically by racing undo_shreq()) and succeed, * we must still wakeup(lkp) for another exclusive * lock trying to acquire EXREQ. Easier to simply * wait for our own wakeup. */ if ((count & LKC_EXREQ) == 0) { KKASSERT(count & LKC_XMASK); lkp->lk_lockholder = td; COUNT(td, 1); break; } /* * Block waiting for our exreq to be granted. * Check cancelation. NOWAIT was already dealt with. */ if (extflags & LK_CANCELABLE) { if (count & LKC_CANCEL) { if (undo_exreq(lkp) == 0) { lkp->lk_lockholder = LK_KERNTHREAD; lockmgr_release(lkp, 0); } error = ENOLCK; break; } } pflags = (extflags & LK_PCATCH) ? PCATCH : 0; timo = (extflags & LK_TIMELOCK) ? lkp->lk_timo : 0; error = tsleep(lkp, pflags | PINTERLOCKED, lkp->lk_wmesg, timo); #ifdef INVARIANTS if (lock_test_mode > 0) { --lock_test_mode; print_backtrace(8); } #endif /* * A tsleep error is uncommon. If it occurs we have to * undo our EXREQ. If we are granted the exclusive lock * as we try to undo we have to deal with it. */ if (extflags & LK_SLEEPFAIL) { if (undo_exreq(lkp) == 0) { lkp->lk_lockholder = LK_KERNTHREAD; lockmgr_release(lkp, 0); } if (error == 0) error = ENOLCK; break; } if (error) { if (undo_exreq(lkp)) break; lkp->lk_lockholder = td; COUNT(td, 1); error = 0; break; } /* * Reload after sleep, shortcut grant case. * Then set the interlock and loop. */ count = lkp->lk_count; cpu_ccfence(); if ((count & LKC_EXREQ) == 0) { KKASSERT(count & LKC_XMASK); lkp->lk_lockholder = td; COUNT(td, 1); break; } tsleep_interlock(lkp, pflags); count = atomic_fetchadd_64(&lkp->lk_count, 0); } return error; } /* * Downgrade an exclusive lock to shared. * * This function always succeeds as long as the caller owns a legal * exclusive lock with one reference. UPREQ and EXREQ is ignored. */ int lockmgr_downgrade(struct lock *lkp, u_int flags) { uint64_t count; uint64_t ncount; uint32_t extflags; thread_t otd; thread_t td; extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK; td = curthread; count = lkp->lk_count; for (;;) { cpu_ccfence(); /* * Downgrade an exclusive lock into a shared lock. All * counts on a recursive exclusive lock become shared. * * NOTE: Currently to reduce confusion we only allow * there to be one exclusive lock count, and panic * if there are more. */ if (lkp->lk_lockholder != td || (count & LKC_XMASK) != 1) { panic("lockmgr: not holding exclusive lock: " "%p/%p %016jx", lkp->lk_lockholder, td, count); } /* * NOTE! Must NULL-out lockholder before releasing the * exclusive lock. * * NOTE! There might be pending shared requests, check * and wake them up. */ otd = lkp->lk_lockholder; lkp->lk_lockholder = NULL; ncount = (count & ~(LKC_XMASK | LKC_EXREQ2)) + ((count & LKC_XMASK) << LKC_SSHIFT); ncount |= LKC_SHARED; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { /* * Wakeup any shared waiters (prior SMASK), or * any exclusive requests that couldn't set EXREQ * because the lock had been held exclusively. */ if (count & (LKC_SMASK | LKC_EXREQ2)) wakeup(lkp); /* count = ncount; NOT USED */ break; } lkp->lk_lockholder = otd; /* retry */ } return 0; } /* * Upgrade a shared lock to exclusive. If LK_EXCLUPGRADE then guarantee * that no other exclusive requester can get in front of us and fail * immediately if another upgrade is pending. If we fail, the shared * lock is released. * * If LK_EXCLUPGRADE is not set and we cannot upgrade because someone * else is in front of us, we release the shared lock and acquire the * exclusive lock normally. If a failure occurs, the shared lock is * released. */ int lockmgr_upgrade(struct lock *lkp, u_int flags) { uint64_t count; uint64_t ncount; uint32_t extflags; thread_t td; int error; int pflags; int timo; _lockmgr_assert(lkp, flags); extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK; td = curthread; error = 0; count = lkp->lk_count; cpu_ccfence(); /* * If we already hold the lock exclusively this operation * succeeds and is a NOP. */ if (count & LKC_XMASK) { if (lkp->lk_lockholder == td) return 0; panic("lockmgr: upgrade unowned lock"); } if ((count & LKC_SMASK) == 0) panic("lockmgr: upgrade unowned lock"); /* * Loop to acquire LKC_UPREQ */ for (;;) { /* * If UPREQ is already pending, release the shared lock * and acquire an exclusive lock normally. * * If NOWAIT or EXCLUPGRADE the operation must be atomic, * and this isn't, so we fail. */ if (count & LKC_UPREQ) { lockmgr_release(lkp, 0); if ((flags & LK_TYPE_MASK) == LK_EXCLUPGRADE) error = EBUSY; else if (extflags & LK_NOWAIT) error = EBUSY; else error = lockmgr_exclusive(lkp, flags); return error; } /* * Try to immediately grant the upgrade, handle NOWAIT, * or release the shared lock and simultaneously set UPREQ. */ if ((count & LKC_SMASK) == LKC_SCOUNT) { /* * Immediate grant */ ncount = (count - LKC_SCOUNT + 1) & ~LKC_SHARED; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { lkp->lk_lockholder = td; return 0; } } else if (extflags & LK_NOWAIT) { /* * Early EBUSY if an immediate grant is impossible */ lockmgr_release(lkp, 0); return EBUSY; } else { /* * Multiple shared locks present, request the * upgrade and break to the next loop. */ pflags = (extflags & LK_PCATCH) ? PCATCH : 0; tsleep_interlock(lkp, pflags); ncount = (count - LKC_SCOUNT) | LKC_UPREQ; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { count = ncount; break; } } /* retry */ } /* * We have acquired LKC_UPREQ, wait until the upgrade is granted * or the tsleep fails. * * NOWAIT and EXCLUPGRADE have already been handled. The first * tsleep_interlock() has already been associated. */ for (;;) { cpu_ccfence(); /* * We were granted our upgrade. No other UPREQ can be * made pending because we are now exclusive. */ if ((count & LKC_UPREQ) == 0) { KKASSERT((count & LKC_XMASK) == 1); lkp->lk_lockholder = td; break; } if (extflags & LK_CANCELABLE) { if (count & LKC_CANCEL) { if (undo_upreq(lkp) == 0) { lkp->lk_lockholder = LK_KERNTHREAD; lockmgr_release(lkp, 0); } error = ENOLCK; break; } } pflags = (extflags & LK_PCATCH) ? PCATCH : 0; timo = (extflags & LK_TIMELOCK) ? lkp->lk_timo : 0; error = tsleep(lkp, pflags | PINTERLOCKED, lkp->lk_wmesg, timo); if (extflags & LK_SLEEPFAIL) { if (undo_upreq(lkp) == 0) { lkp->lk_lockholder = LK_KERNTHREAD; lockmgr_release(lkp, 0); } if (error == 0) error = ENOLCK; break; } if (error) { if (undo_upreq(lkp)) break; error = 0; } /* * Reload the lock, short-cut the UPGRANT code before * taking the time to interlock and loop. */ count = lkp->lk_count; if ((count & LKC_UPREQ) == 0) { KKASSERT((count & LKC_XMASK) == 1); lkp->lk_lockholder = td; break; } tsleep_interlock(lkp, pflags); count = atomic_fetchadd_64(&lkp->lk_count, 0); /* retry */ } return error; } /* * Release a held lock * * NOTE: When releasing to an unlocked state, we set the SHARED bit * to optimize shared lock requests. */ int lockmgr_release(struct lock *lkp, u_int flags) { uint64_t count; uint64_t ncount; uint32_t extflags; thread_t otd; thread_t td; extflags = (flags | lkp->lk_flags) & LK_EXTFLG_MASK; td = curthread; count = lkp->lk_count; cpu_ccfence(); for (;;) { /* * Release the currently held lock, grant all requests * possible. * * WARNING! lksleep() assumes that LK_RELEASE does not * block. * * Always succeeds. * Never blocks. */ if ((count & (LKC_SMASK | LKC_XMASK)) == 0) panic("lockmgr: LK_RELEASE: no lock held"); if (count & LKC_XMASK) { /* * Release exclusively held lock */ if (lkp->lk_lockholder != LK_KERNTHREAD && lkp->lk_lockholder != td) { panic("lockmgr: pid %d, not exclusive " "lock holder thr %p/%p unlocking", (td->td_proc ? td->td_proc->p_pid : -1), td, lkp->lk_lockholder); } if ((count & (LKC_UPREQ | LKC_EXREQ | LKC_XMASK)) == 1) { /* * Last exclusive count is being released * with no UPREQ or EXREQ. The SHARED * bit can be set or not without messing * anything up, so precondition it to * SHARED (which is the most cpu-optimal). * * Wakeup any EXREQ2. EXREQ cannot be * set while an exclusive count is present * so we have to wakeup any EXREQ2 we find. * * We could hint the EXREQ2 by leaving * SHARED unset, but atm I don't see any * usefulness. */ otd = lkp->lk_lockholder; lkp->lk_lockholder = NULL; ncount = (count - 1); ncount &= ~(LKC_CANCEL | LKC_EXREQ2); ncount |= LKC_SHARED; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { if (count & (LKC_SMASK | LKC_EXREQ2)) wakeup(lkp); if (otd != LK_KERNTHREAD) COUNT(td, -1); /* count = ncount; NOT USED */ break; } lkp->lk_lockholder = otd; /* retry */ } else if ((count & (LKC_UPREQ | LKC_XMASK)) == (LKC_UPREQ | 1)) { /* * Last exclusive count is being released but * an upgrade request is present, automatically * grant an exclusive state to the owner of * the upgrade request. Transfer count to * grant. * * EXREQ cannot be set while an exclusive * holder exists, so do not clear EXREQ2. */ otd = lkp->lk_lockholder; lkp->lk_lockholder = NULL; ncount = count & ~LKC_UPREQ; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); if (otd != LK_KERNTHREAD) COUNT(td, -1); /* count = ncount; NOT USED */ break; } lkp->lk_lockholder = otd; /* retry */ } else if ((count & (LKC_EXREQ | LKC_XMASK)) == (LKC_EXREQ | 1)) { /* * Last exclusive count is being released but * an exclusive request is present. We * automatically grant an exclusive state to * the owner of the exclusive request, * transfering our count. * * This case virtually never occurs because * EXREQ is not set while exclusive holders * exist. However, it might be set if a * an exclusive request is pending and a * shared holder upgrades. * * Don't bother clearing EXREQ2. A thread * waiting to set EXREQ can't do it while * an exclusive lock is present. */ otd = lkp->lk_lockholder; lkp->lk_lockholder = NULL; ncount = count & ~LKC_EXREQ; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); if (otd != LK_KERNTHREAD) COUNT(td, -1); /* count = ncount; NOT USED */ break; } lkp->lk_lockholder = otd; /* retry */ } else { /* * Multiple exclusive counts, drop by 1. * Since we are the holder and there is more * than one count, we can just decrement it. */ count = atomic_fetchadd_long(&lkp->lk_count, -1); /* count = count - 1 NOT NEEDED */ if (lkp->lk_lockholder != LK_KERNTHREAD) COUNT(td, -1); break; } /* retry */ } else { /* * Release shared lock */ KKASSERT((count & LKC_SHARED) && (count & LKC_SMASK)); if ((count & (LKC_EXREQ | LKC_UPREQ | LKC_SMASK)) == LKC_SCOUNT) { /* * Last shared count is being released, * no exclusive or upgrade request present. * Generally leave the shared bit set. * Clear the CANCEL bit. */ ncount = (count - LKC_SCOUNT) & ~LKC_CANCEL; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { COUNT(td, -1); /* count = ncount; NOT USED */ break; } /* retry */ } else if ((count & (LKC_UPREQ | LKC_SMASK)) == (LKC_UPREQ | LKC_SCOUNT)) { /* * Last shared count is being released but * an upgrade request is present, automatically * grant an exclusive state to the owner of * the upgrade request and transfer the count. */ ncount = (count - LKC_SCOUNT + 1) & ~(LKC_UPREQ | LKC_CANCEL | LKC_SHARED); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); COUNT(td, -1); /* count = ncount; NOT USED */ break; } /* retry */ } else if ((count & (LKC_EXREQ | LKC_SMASK)) == (LKC_EXREQ | LKC_SCOUNT)) { /* * Last shared count is being released but * an exclusive request is present, we * automatically grant an exclusive state to * the owner of the request and transfer * the count. */ ncount = (count - LKC_SCOUNT + 1) & ~(LKC_EXREQ | LKC_EXREQ2 | LKC_CANCEL | LKC_SHARED); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); COUNT(td, -1); /* count = ncount; NOT USED */ break; } /* retry */ } else { /* * Shared count is greater than 1. We can * just use undo_shreq() to clean things up. * undo_shreq() will also handle races to 0 * after the fact. */ undo_shreq(lkp); COUNT(td, -1); break; } /* retry */ } /* retry */ } return 0; } /* * Start canceling blocked requesters or later requestors. * Only blocked requesters using CANCELABLE can be canceled. * * This is intended to then allow other requesters (usually the * caller) to obtain a non-cancelable lock. * * Don't waste time issuing a wakeup if nobody is pending. */ int lockmgr_cancel_beg(struct lock *lkp, u_int flags) { uint64_t count; count = lkp->lk_count; for (;;) { cpu_ccfence(); KKASSERT((count & LKC_CANCEL) == 0); /* disallowed case */ /* issue w/lock held */ KKASSERT((count & (LKC_XMASK | LKC_SMASK)) != 0); if (!atomic_fcmpset_64(&lkp->lk_count, &count, count | LKC_CANCEL)) { continue; } /* count |= LKC_CANCEL; NOT USED */ /* * Wakeup any waiters. * * NOTE: EXREQ2 only matters when EXREQ is set, so don't * bother checking EXREQ2. */ if (count & (LKC_EXREQ | LKC_SMASK | LKC_UPREQ)) { wakeup(lkp); } break; } return 0; } /* * End our cancel request (typically after we have acquired * the lock ourselves). */ int lockmgr_cancel_end(struct lock *lkp, u_int flags) { atomic_clear_long(&lkp->lk_count, LKC_CANCEL); return 0; } /* * Backout SCOUNT from a failed shared lock attempt and handle any race * to 0. This function is also used by the release code for the less * optimal race to 0 case. * * WARNING! Since we are unconditionally decrementing LKC_SCOUNT, it is * possible for the lock to get into a LKC_SHARED + ZERO SCOUNT * situation. A shared request can block with a ZERO SCOUNT if * EXREQ or UPREQ is pending in this situation. Be sure to always * issue a wakeup() in this situation if we are unable to * transition to an exclusive lock, to handle the race. * * Always succeeds * Must not block */ static void undo_shreq(struct lock *lkp) { uint64_t count; uint64_t ncount; count = atomic_fetchadd_64(&lkp->lk_count, -LKC_SCOUNT) - LKC_SCOUNT; while ((count & (LKC_EXREQ | LKC_UPREQ | LKC_CANCEL)) && (count & (LKC_SMASK | LKC_XMASK)) == 0) { /* * Note that UPREQ must have priority over EXREQ, and EXREQ * over CANCEL, so if the atomic op fails we have to loop up. */ if (count & LKC_UPREQ) { ncount = (count + 1) & ~(LKC_UPREQ | LKC_CANCEL | LKC_SHARED); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); /* count = ncount; NOT USED */ break; } wakeup(lkp); continue; } if (count & LKC_EXREQ) { ncount = (count + 1) & ~(LKC_EXREQ | LKC_EXREQ2 | LKC_CANCEL | LKC_SHARED); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); /* count = ncount; NOT USED */ break; } wakeup(lkp); continue; } if (count & LKC_CANCEL) { ncount = count & ~LKC_CANCEL; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); /* count = ncount; NOT USED */ break; } } /* retry */ } } /* * Undo an exclusive request. Returns EBUSY if we were able to undo the * request, and 0 if the request was granted before we could undo it. * When 0 is returned, the lock state has not been modified. The caller * is responsible for setting the lockholder to curthread. */ static int undo_exreq(struct lock *lkp) { uint64_t count; uint64_t ncount; int error; count = lkp->lk_count; error = 0; for (;;) { cpu_ccfence(); if ((count & LKC_EXREQ) == 0) { /* * EXREQ was granted. We own the exclusive lock. */ break; } if (count & LKC_XMASK) { /* * Clear the EXREQ we still own. Only wakeup on * EXREQ2 if no UPREQ. There are still exclusive * holders so do not wake up any shared locks or * any UPREQ. * * If there is an UPREQ it will issue a wakeup() * for any EXREQ wait looops, so we can clear EXREQ2 * now. */ ncount = count & ~(LKC_EXREQ | LKC_EXREQ2); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { if ((count & (LKC_EXREQ2 | LKC_UPREQ)) == LKC_EXREQ2) { wakeup(lkp); } error = EBUSY; /* count = ncount; NOT USED */ break; } /* retry */ } else if (count & LKC_UPREQ) { /* * Clear the EXREQ we still own. We cannot wakeup any * shared or exclusive waiters because there is an * uprequest pending (that we do not handle here). * * If there is an UPREQ it will issue a wakeup() * for any EXREQ wait looops, so we can clear EXREQ2 * now. */ ncount = count & ~(LKC_EXREQ | LKC_EXREQ2); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { error = EBUSY; break; } /* retry */ } else if ((count & LKC_SHARED) && (count & LKC_SMASK)) { /* * No UPREQ, lock not held exclusively, but the lock * is held shared. Clear EXREQ, wakeup anyone trying * to get the EXREQ bit (they have to set it * themselves, EXREQ2 is an aggregation). * * We must also wakeup any shared locks blocked * by the EXREQ, so just issue the wakeup * unconditionally. See lockmgr_shared() + 76 lines * or so. */ ncount = count & ~(LKC_EXREQ | LKC_EXREQ2); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); error = EBUSY; /* count = ncount; NOT USED */ break; } /* retry */ } else { /* * No UPREQ, lock not held exclusively or shared. * Grant the EXREQ and wakeup anyone waiting on * EXREQ2. * * We must also issue a wakeup if SHARED is set, * even without an SCOUNT, due to pre-shared blocking * that can occur on EXREQ in lockmgr_shared(). */ ncount = (count + 1) & ~(LKC_EXREQ | LKC_EXREQ2); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { if (count & (LKC_EXREQ2 | LKC_SHARED)) wakeup(lkp); /* count = ncount; NOT USED */ /* we are granting, error == 0 */ break; } /* retry */ } /* retry */ } return error; } /* * Undo an upgrade request. Returns EBUSY if we were able to undo the * request, and 0 if the request was granted before we could undo it. * When 0 is returned, the lock state has not been modified. The caller * is responsible for setting the lockholder to curthread. */ static int undo_upreq(struct lock *lkp) { uint64_t count; uint64_t ncount; int error; count = lkp->lk_count; error = 0; for (;;) { cpu_ccfence(); if ((count & LKC_UPREQ) == 0) { /* * UPREQ was granted */ break; } if (count & LKC_XMASK) { /* * Clear the UPREQ we still own. Nobody to wakeup * here because there is an existing exclusive * holder. */ if (atomic_fcmpset_64(&lkp->lk_count, &count, count & ~LKC_UPREQ)) { error = EBUSY; /* count &= ~LKC_UPREQ; NOT USED */ break; } } else if (count & LKC_EXREQ) { /* * Clear the UPREQ we still own. Grant the exclusive * request and wake it up. */ ncount = (count + 1); ncount &= ~(LKC_EXREQ | LKC_EXREQ2 | LKC_UPREQ); if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { wakeup(lkp); error = EBUSY; /* count = ncount; NOT USED */ break; } } else { /* * Clear the UPREQ we still own. Wakeup any shared * waiters. * * We must also issue a wakeup if SHARED was set * even if no shared waiters due to pre-shared blocking * that can occur on UPREQ. */ ncount = count & ~LKC_UPREQ; if (count & LKC_SMASK) ncount |= LKC_SHARED; if (atomic_fcmpset_64(&lkp->lk_count, &count, ncount)) { if ((count & LKC_SHARED) || (ncount & LKC_SHARED)) { wakeup(lkp); } error = EBUSY; /* count = ncount; NOT USED */ break; } } /* retry */ } return error; } void lockmgr_kernproc(struct lock *lp) { struct thread *td __debugvar = curthread; if (lp->lk_lockholder != LK_KERNTHREAD) { KASSERT(lp->lk_lockholder == td, ("lockmgr_kernproc: lock not owned by curthread %p: %p", td, lp->lk_lockholder)); lp->lk_lockholder = LK_KERNTHREAD; COUNT(td, -1); } } /* * Initialize a lock; required before use. */ void lockinit(struct lock *lkp, const char *wmesg, int timo, int flags) { lkp->lk_flags = (flags & LK_EXTFLG_MASK); lkp->lk_count = 0; lkp->lk_wmesg = wmesg; lkp->lk_timo = timo; lkp->lk_lockholder = NULL; } /* * Reinitialize a lock that is being reused for a different purpose, but * which may have pending (blocked) threads sitting on it. The caller * must already hold the interlock. */ void lockreinit(struct lock *lkp, const char *wmesg, int timo, int flags) { lkp->lk_wmesg = wmesg; lkp->lk_timo = timo; } /* * De-initialize a lock. The structure must no longer be used by anyone. */ void lockuninit(struct lock *lkp) { uint64_t count __unused; count = lkp->lk_count; cpu_ccfence(); KKASSERT((count & (LKC_EXREQ | LKC_UPREQ)) == 0 && ((count & LKC_SHARED) || (count & LKC_SMASK) == 0)); } /* * Determine the status of a lock. */ int lockstatus(struct lock *lkp, struct thread *td) { int lock_type = 0; uint64_t count; count = lkp->lk_count; cpu_ccfence(); if (count & (LKC_XMASK | LKC_SMASK | LKC_EXREQ | LKC_UPREQ)) { if (count & LKC_XMASK) { if (td == NULL || lkp->lk_lockholder == td) lock_type = LK_EXCLUSIVE; else lock_type = LK_EXCLOTHER; } else if ((count & LKC_SMASK) && (count & LKC_SHARED)) { lock_type = LK_SHARED; } } return (lock_type); } /* * Return non-zero if the caller owns the lock shared or exclusive. * We can only guess re: shared locks. */ int lockowned(struct lock *lkp) { thread_t td = curthread; uint64_t count; count = lkp->lk_count; cpu_ccfence(); if (count & LKC_XMASK) return(lkp->lk_lockholder == td); else return((count & LKC_SMASK) != 0); } #if 0 /* * Determine the number of holders of a lock. * * REMOVED - Cannot be used due to our use of atomic_fetchadd_64() * for shared locks. Caller can only test if the lock has * a count or not using lockinuse(lk) (sys/lock.h) */ int lockcount(struct lock *lkp) { panic("lockcount cannot be used"); } int lockcountnb(struct lock *lkp) { panic("lockcount cannot be used"); } #endif /* * Print out information about state of a lock. Used by VOP_PRINT * routines to display status about contained locks. */ void lockmgr_printinfo(struct lock *lkp) { struct thread *td = lkp->lk_lockholder; struct proc *p; uint64_t count; count = lkp->lk_count; cpu_ccfence(); if (td && td != LK_KERNTHREAD) p = td->td_proc; else p = NULL; if (count & LKC_XMASK) { kprintf(" lock type %s: EXCLUS (count %016jx) by td %p pid %d", lkp->lk_wmesg, (intmax_t)count, td, p ? p->p_pid : -99); } else if ((count & LKC_SMASK) && (count & LKC_SHARED)) { kprintf(" lock type %s: SHARED (count %016jx)", lkp->lk_wmesg, (intmax_t)count); } else { kprintf(" lock type %s: NOTHELD", lkp->lk_wmesg); } if ((count & (LKC_EXREQ | LKC_UPREQ)) || ((count & LKC_XMASK) && (count & LKC_SMASK))) kprintf(" with waiters\n"); else kprintf("\n"); } void lock_sysinit(struct lock_args *arg) { lockinit(arg->la_lock, arg->la_desc, 0, arg->la_flags); } #ifdef DEBUG_CANCEL_LOCKS static int sysctl_cancel_lock(SYSCTL_HANDLER_ARGS) { int error; if (req->newptr) { SYSCTL_XUNLOCK(); lockmgr(&cancel_lk, LK_EXCLUSIVE); error = tsleep(&error, PCATCH, "canmas", hz * 5); lockmgr(&cancel_lk, LK_CANCEL_BEG); error = tsleep(&error, PCATCH, "canmas", hz * 5); lockmgr(&cancel_lk, LK_RELEASE); SYSCTL_XLOCK(); SYSCTL_OUT(req, &error, sizeof(error)); } error = 0; return error; } static int sysctl_cancel_test(SYSCTL_HANDLER_ARGS) { int error; if (req->newptr) { error = lockmgr(&cancel_lk, LK_EXCLUSIVE|LK_CANCELABLE); if (error == 0) lockmgr(&cancel_lk, LK_RELEASE); SYSCTL_OUT(req, &error, sizeof(error)); kprintf("test %d\n", error); } return 0; } #endif
712812.c
/* * Copyright (c) 2021 Johannes Teichrieb * MIT License */ #include "hashgen.h" #include <assert.h> #include <string.h> #include <argon2.h> #include <sha3.h> static void setDummySalt(void* salt) { // There is no salt, because no password is ever stored. The fixed value avoids zeros. // The seed for the salt is "dummy salt n", // where 'n' is the largest Mersenne prime that fits into uint64_t (2**61 - 1). const char s[] = "dummy salt 2305843009213693951"; sha3(s, sizeof s - 1, salt, LEPASD_HASH_SIZE); } static argon2_context argon2ContextTemplate(void) { argon2_context c = { // .out = NULL, .outlen = LEPASD_HASH_SIZE, // .pwd = NULL, // .pwdlen = 0, // .salt = NULL, .saltlen = LEPASD_HASH_SIZE, .secret = NULL, .secretlen = 0, .ad = NULL, .adlen = 0, .t_cost = 5, // passes .m_cost = 1 << 20, // memory in KB (1 GB) .lanes = 4, .threads = 4, .version = ARGON2_VERSION_13, .allocate_cbk = NULL, .free_cbk = NULL, .flags = ARGON2_FLAG_CLEAR_PASSWORD }; return c; } void lepasd_init(void* password, uint32_t length, void* contextOut) { uint8_t salt[LEPASD_HASH_SIZE]; setDummySalt(salt); uint8_t hash[LEPASD_HASH_SIZE]; argon2_context ac = argon2ContextTemplate(); ac.out = hash; ac.pwd = password; ac.pwdlen = length; ac.salt = salt; if (argon2d_ctx(&ac) != ARGON2_OK) { memset(password, 0, length); assert(0); } // password has been wiped (.flags in argon2_context) sha3_ctx_t sc; sha3_init(&sc, LEPASD_HASH_SIZE); sha3_update(&sc, hash, sizeof hash); memset(hash, 0, sizeof hash); _Static_assert(LEPASD_CONTEXT_SIZE == sizeof(sha3_ctx_t), "Invalid LEPASD_CONTEXT_SIZE"); *(sha3_ctx_t*)contextOut = sc; memset(&sc, 0, sizeof sc); } void lepasd_hash(const void* context, const void* tag, size_t tagLength, void* hashOut) { sha3_ctx_t c = *(const sha3_ctx_t*)context; sha3_update(&c, tag, tagLength); sha3_final(hashOut, &c); memset(&c, 0, sizeof c); }
693763.c
#include <api.h> void InitVelocity(ecs_iter_t *it) { ECS_COLUMN(it, Velocity, v, 1); int i; for (i = 0; i < it->count; i ++) { v[i].x = 10; v[i].y = 20; } } void InitMass(ecs_iter_t *it) { ECS_COLUMN(it, Mass, m, 1); int i; for (i = 0; i < it->count; i ++) { m[i] = 3; } } void Iter(ecs_iter_t *it) { ECS_COLUMN(it, Position, p, 1); Velocity *v = NULL; Mass *m = NULL; if (it->column_count >= 2) { v = ecs_column(it, Velocity, 2); test_assert(!ecs_is_owned(it, 2)); } if (it->column_count >= 3) { m = ecs_column(it, Mass, 3); test_assert(!m || !ecs_is_owned(it, 3)); } probe_system(it); int i; for (i = 0; i < it->count; i ++) { p[i].x += v->x; p[i].y += v->y; if (m) { p[i].x += *m; p[i].y += *m; } } } void System_w_FromSystem_2_column_1_from_system() { ecs_world_t *world = ecs_init(); ECS_COMPONENT(world, Position); ECS_COMPONENT(world, Velocity); ECS_TRIGGER(world, InitVelocity, EcsOnAdd, Velocity); ECS_SYSTEM(world, Iter, EcsOnUpdate, Position, SYSTEM:Velocity); test_assert( ecs_has(world, Iter, Velocity)); const Velocity *v = ecs_get(world, Iter, Velocity); test_assert(v != NULL); test_int(v->x, 10); test_int(v->y, 20); Probe ctx = {0}; ecs_set_context(world, &ctx); ecs_entity_t e = ecs_set(world, 0, Position, {0, 0}); ecs_progress(world, 1); test_int(ctx.count, 1); test_int(ctx.invoked, 1); test_int(ctx.system, Iter); test_int(ctx.column_count, 2); test_null(ctx.param); test_int(ctx.e[0], e); test_int(ctx.c[0][0], ecs_typeid(Position)); test_int(ctx.s[0][0], 0); test_int(ctx.c[0][1], ecs_typeid(Velocity)); test_int(ctx.s[0][1], Iter); const Position *p = ecs_get(world, e, Position); test_assert(p != NULL); test_int(p->x, 10); test_int(p->y, 20); ecs_progress(world, 1); test_int(p->x, 20); test_int(p->y, 40); ecs_fini(world); } void System_w_FromSystem_3_column_2_from_system() { ecs_world_t *world = ecs_init(); ECS_COMPONENT(world, Position); ECS_COMPONENT(world, Velocity); ECS_COMPONENT(world, Mass); ECS_TRIGGER(world, InitVelocity, EcsOnAdd, Velocity); ECS_TRIGGER(world, InitMass, EcsOnAdd, Mass); ECS_SYSTEM(world, Iter, EcsOnUpdate, Position, SYSTEM:Velocity, SYSTEM:Mass); test_assert( ecs_has(world, Iter, Velocity)); const Velocity *v = ecs_get(world, Iter, Velocity); test_assert(v != NULL); test_int(v->x, 10); test_int(v->y, 20); test_assert( ecs_has(world, Iter, Mass)); const Mass *m = ecs_get(world, Iter, Mass); test_assert(m != NULL); test_int(*m, 3); Probe ctx = {0}; ecs_set_context(world, &ctx); ecs_entity_t e = ecs_set(world, 0, Position, {0, 0}); ecs_progress(world, 1); test_int(ctx.count, 1); test_int(ctx.invoked, 1); test_int(ctx.system, Iter); test_int(ctx.column_count, 3); test_null(ctx.param); test_int(ctx.e[0], e); test_int(ctx.c[0][0], ecs_typeid(Position)); test_int(ctx.s[0][0], 0); test_int(ctx.c[0][1], ecs_typeid(Velocity)); test_int(ctx.s[0][1], Iter); test_int(ctx.c[0][2], ecs_typeid(Mass)); test_int(ctx.s[0][2], Iter); const Position *p = ecs_get(world, e, Position); test_assert(p != NULL); test_int(p->x, 13); test_int(p->y, 23); ecs_progress(world, 1); test_int(p->x, 26); test_int(p->y, 46); ecs_fini(world); } void Iter_reactive(ecs_iter_t *it) { ECS_COLUMN(it, Position, p, 1); Velocity *v = it->param; Mass *m = NULL; if (it->column_count >= 2) { v = ecs_column(it, Velocity, 2); test_assert(!ecs_is_owned(it, 2)); } probe_system(it); int i; for (i = 0; i < it->count; i ++) { p[i].x = v->x; p[i].y = v->y; if (m) { p[i].x = *m; p[i].y = *m; } } } void Dummy_1(ecs_iter_t *it) { } void Dummy_2(ecs_iter_t *it) { } void System_w_FromSystem_auto_add_tag() { ecs_world_t *world = ecs_init(); ECS_COMPONENT(world, Position); ECS_SYSTEM(world, Dummy_1, EcsOnUpdate, Position, SYSTEM:Hidden); ECS_SYSTEM(world, Dummy_2, 0, Position, SYSTEM:Hidden); test_assert( ecs_has_entity(world, Dummy_1, EcsHidden)); test_assert( ecs_has_entity(world, Dummy_2, EcsHidden)); ecs_fini(world); }
946149.c
//***************************************************************************** // // Lab5.c - user programs, File system, stream data onto disk // Jonathan Valvano, March 16, 2011, EE345M // You may implement Lab 5 without the oLED display //***************************************************************************** // PF1/IDX1 is user input select switch // PE1/PWM5 is user input down switch #include <stdio.h> #include <string.h> #include "inc/hw_types.h" //#include "serial.h" #include "adc.h" #include "os.h" #include "lm3s8962.h" #include "edisk.h" #include "efile.h" #include "UART.h" #include "shell.h" #define OS_AddPeriodicThread OS_Add_Periodic_Thread void simple_test(void); void write_test(void); void read_test(void); unsigned long NumCreated; // number of foreground threads created unsigned long NumSamples; // incremented every sample unsigned long DataLost; // data sent by Producer, but not received by Consumer int Running; // true while robot is running #define TIMESLICE 2*TIME_1MS // thread switch time in system time units #define GPIO_PF0 (*((volatile unsigned long *)0x40025004)) #define GPIO_PF1 (*((volatile unsigned long *)0x40025008)) #define GPIO_PF2 (*((volatile unsigned long *)0x40025010)) #define GPIO_PF3 (*((volatile unsigned long *)0x40025020)) #define GPIO_PG1 (*((volatile unsigned long *)0x40026008)) // PF1/IDX1 is user input select switch // PE1/PWM5 is user input down switch // PF0/PWM0 is debugging output on Systick // PF2/LED1 is debugging output // PF3/LED0 is debugging output // PG1/PWM1 is debugging output //******** Robot *************** // foreground thread, accepts data from producer // inputs: none // outputs: none void Robot(void){ unsigned long data; // ADC sample, 0 to 1023 unsigned long voltage; // in mV, 0 to 3000 unsigned long time; // in 10msec, 0 to 1000 unsigned long t=0; OS_ClearMsTime(); DataLost = 0; // new run with no lost data printf("Robot running..."); eFile_RedirectToFile("Robot"); printf("time(sec)\tdata(volts)\n\r"); do{ t++; time=OS_MsTime(); // 10ms resolution in this OS data = OS_Fifo_Get(); // 1000 Hz sampling get from producer voltage = (300*data)/1024; // in mV printf("%0u.%02u\t%0u.%03u\n\r",time/100,time%100,voltage/1000,voltage%1000); } while(time < 1000); // change this to mean 10 seconds eFile_EndRedirectToFile(); printf("done.\n\r"); Running = 0; // robot no longer running OS_Kill(); } //************ButtonPush************* // Called when Select Button pushed // background threads execute once and return void ButtonPush(void){ if(Running==0){ Running = 1; // prevents you from starting two robot threads NumCreated += OS_AddThread(&Robot,128,1); // start a 20 second run } } //************DownPush************* // Called when Down Button pushed // background threads execute once and return void DownPush(void){ } //******** Producer *************** // The Producer in this lab will be called from your ADC ISR // A timer runs at 1 kHz, started by your ADC_Collect // The timer triggers the ADC, creating the 1 kHz sampling // Your ADC ISR runs when ADC data is ready // Your ADC ISR calls this function with a 10-bit sample // sends data to the Robot, runs periodically at 1 kHz // inputs: none // outputs: none void Producer(unsigned short data){ if(Running){ if(OS_Fifo_Put(data)){ // send to Robot NumSamples++; } else{ DataLost++; } } } //******** IdleTask *************** // foreground thread, runs when no other work needed // never blocks, never sleeps, never dies // inputs: none // outputs: none unsigned long Idlecount=0; void IdleTask(void){ while(1) { Idlecount++; // debugging } } //******** Interpreter ************** // your intepreter from Lab 4 // foreground thread, accepts input from serial port, outputs to serial port // inputs: none // outputs: none extern void SH_Shell(void); // add the following commands, remove commands that do not make sense anymore // 1) format // 2) directory // 3) print file // 4) delete file // execute eFile_Init(); after periodic interrupts have started //*******************lab 5 main ********** int main2(void){ // lab 5 real main OS_Init(); // initialize, disable interrupts Running = 0; // robot not running DataLost = 0; // lost data between producer and consumer NumSamples = 0; //********initialize communication channels OS_Fifo_Init(MAX_FIFO_SIZE); // ***note*** 4 is not big enough***** ADC_Init(0); ADC_Collect(0, 1000, &Producer); // start ADC sampling, channel 0, 1000 Hz //*******attach background tasks*********** OS_AddButtonTask(&ButtonPush,2); OS_AddButtonTask(&DownPush,3); OS_AddPeriodicThread(disk_timerproc,10,5); NumCreated = 0 ; // create initial foreground threads NumCreated += OS_AddThread(&SH_Shell,128,2); NumCreated += OS_AddThread(&IdleTask,128,7); // runs when nothing useful to do OS_Launch(TIMESLICE); // doesn't return, interrupts enabled in here return 0; // this never executes } //*****************test programs************************* unsigned char buffer[512]; #define MAXBLOCKS 100 void diskError(char* errtype, unsigned long n){ printf(errtype); printf(" disk error %u\r\n",n); OS_Kill(); } void TestDisk(void){ DSTATUS result; unsigned short block; int i; unsigned long n; // simple test of eDisk printf("\n\rEE345M/EE380L, Lab 5 eDisk test\n\r"); result = eDisk_Init(0); // initialize disk if(result) diskError("eDisk_Init",result); printf("Writing blocks\n\r"); n = 1; // seed for(block = 0; block < MAXBLOCKS; block++){ for(i=0;i<512;i++){ n = (16807*n)%2147483647; // pseudo random sequence buffer[i] = 0xFF&n; } //GPIO_PF3 = 0x08; // PF3 high for 100 block writes if(eDisk_WriteBlock(buffer,block))diskError("eDisk_WriteBlock",block); // save to disk //GPIO_PF3 = 0x00; } printf("Reading blocks\n\r"); n = 1; // reseed, start over to get the same sequence for(block = 0; block < MAXBLOCKS; block++){ // GPIO_PF2 = 0x04; // PF2 high for one block read if(eDisk_ReadBlock(buffer,block))diskError("eDisk_ReadBlock",block); // read from disk // GPIO_PF2 = 0x00; for(i=0;i<512;i++){ n = (16807*n)%2147483647; // pseudo random sequence if(buffer[i] != (0xFF&n)){ printf("Read data not correct, block=%u, i=%u, expected %u, read %u\n\r",block,i,(0xFF&n),buffer[i]); OS_Kill(); } } } printf("Successful test of %u blocks\n\r",MAXBLOCKS); OS_Kill(); } void RunTest(void){ NumCreated += OS_AddThread(&TestDisk,128,1); } //******************* test main1 ********** // SYSTICK interrupts, period established by OS_Launch // Timer interrupts, period established by first call to OS_AddPeriodicThread int testmain(void){ // testmain1 OS_Init(); // initialize, disable interrupts //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10,0); // time out routines for disk OS_AddButtonTask(&RunTest,2); NumCreated = 0 ; // create initial foreground threads NumCreated += OS_AddThread(&TestDisk,128,1); NumCreated += OS_AddThread(&IdleTask,128,3); OS_Launch(10*TIME_1MS); // doesn't return, interrupts enabled in here return 0; // this never executes } void TestFile(void){ int i; char data; printf("\n\rEE345M/EE380L, Lab 5 eFile test\n\r"); // simple test of eFile //if(eFile_Init()) diskError("eFile_Init",0); if(eFile_Format()) diskError("eFile_Format",0); eFile_Directory(&printf); if(eFile_Create("file1", 0x20)) diskError("eFile_Create",0); if(eFile_WOpen("file1")) diskError("eFile_WOpen",0); for(i=0;i<1000;i++){ if(eFile_Write('a'+i%26)) diskError("eFile_Write",i); if(i%52==51){ if(eFile_Write('\n')) diskError("eFile_Write",i); if(eFile_Write('\r')) diskError("eFile_Write",i); } } if(eFile_WClose()) diskError("eFile_Close",0); eFile_Directory(&printf); if(eFile_ROpen("file1")) diskError("eFile_ROpen",0); for(i=0;i<1000;i++){ if(eFile_ReadNext(&data)) diskError("eFile_ReadNext",i); UART_OutChar(data); } if(eFile_Delete("file1")) diskError("eFile_Delete",0); eFile_Directory(&printf); printf("Successful test of creating a file\n\r"); // OS_Kill(); } void SD_Init(void) { eFile_Init(); OS_Kill(); } //******************* test main2 ********** // SYSTICK interrupts, period established by OS_Launch // Timer interrupts, period established by first call to OS_AddPeriodicThread int main(void){ OS_Init(); // initialize, disable interrupts // SH_Init(); //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10,0); // time out routines for disk NumCreated = 0 ; // create initial foreground threads //NumCreated += OS_AddThread(&TestFile,128,1); NumCreated += OS_AddThread(&IdleTask,128,6); NumCreated += OS_AddThread(&SD_Init, 128, 0); NumCreated += OS_AddThread(&SH_Shell, 128, 3); OS_Launch(10*TIME_1MS); // doesn't return, interrupts enabled in here return 0; // this never executes } // main program to measure the bandwidth of the SD card // measure the maximum rate at which you can continuously write to the SD card // output to unused GPIO pins int bandwidth_write_testmain(void) { OS_Init(); // initialize, disable interrupts //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10*TIME_1MS,0); // time out routines for disk // add threads for testing OS_AddThread(&write_test, 128, 0); // this thread adds SH_Shell when it's done OS_Launch(TIMESLICE); return 0; } // main program to measure the bandwidth of the SD card // measure the maximum rate at which you can continuously read from the SD card // output to unused GPIO pins int main1(void) { OS_Init(); // initialize, disable interrupts //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10,0); // time out routines for disk // add threads for testing OS_AddThread(&read_test, 128, 0); OS_Launch(TIMESLICE); return 0; } // main program to test the file system (eFile.c) int filesystem_testmain(void) { OS_Init(); // initialize, disable interrupts //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10*TIME_1MS,0); // time out routines for disk // TODO - add threads for testing OS_Launch(TIMESLICE); return 0; } // simple test main int simple_test_main(void) { OS_Init(); // initialize, disable interrupts UART_Init(); //*******attach background tasks*********** OS_AddPeriodicThread(&disk_timerproc,10,0); // time out routines for disk OS_AddThread(&TestFile, 128, 1); OS_Launch(TIMESLICE); return 0; } void simple_test(void) { char c; printf("\r\n\r\n"); printf("eFile_Init() returned: %d\r\n", eFile_Init()); printf("eFile_Format() returned: %d\r\n", eFile_Format()); printf("eFile_Create() returned: %d\r\n", eFile_Create("test", 0x20)); printf("eFile_WOpen() returned: %d\r\n", eFile_WOpen("test")); printf("eFile_Write() returned: %d\r\n", eFile_Write('x')); printf("eFile_WClose() returned: %d\r\n", eFile_WClose()); printf("eFile_ROpen() returned: %d\r\n", eFile_ROpen("test")); printf("eFile_ReadNext() returned: %d\r\n", eFile_ReadNext(&c)); printf("eFile_ReadNext() read: %c\r\n", c); printf("eFile_RClose() returned: %d\r\n", eFile_RClose()); while(1) { ; } } void write_test(void) { int i; unsigned int then, now; eFile_Init(); eFile_Format(); // format buffer with dummy data for(i = 0; i < 512; i++) { buffer[i] = 0xA5; } // possibly should just use OS_Time() then = OS_MsTime(); // write 10 blocks for(i = 0; i < 10; i++) { eDisk_WriteBlock(buffer, i); } now = OS_MsTime(); OS_AddThread(&SH_Shell, 128, 0); OS_Sleep(1000); OS_Suspend(); printf("Write test took %d ms", now - then); eFile_Format(); OS_Kill(); } void read_test(void) { int i; unsigned int then, now; eFile_Init(); eFile_Format(); then = OS_MsTime(); // read 10 blocks for(i = 0; i < 10; i++) { eDisk_ReadBlock(buffer, i); } now = OS_MsTime(); OS_AddThread(&SH_Shell, 128, 0); OS_Sleep(1000); OS_Suspend(); printf("Read test took %d ms", now - then); eFile_Format(); OS_Kill(); }
235709.c
/** @file HL_sys_vim.c * @brief VIM Driver Implementation File * @date 11-Dec-2018 * @version 04.07.01 * */ /* * Copyright (C) 2009-2018 Texas Instruments Incorporated - www.ti.com * * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * Neither the name of Texas Instruments Incorporated nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "HL_sys_vim.h" #include "HL_system.h" #include "HL_esm.h" /* USER CODE BEGIN (0) */ /* USER CODE END */ /* Vim Ram Definition */ /** @struct vimRam * @brief Vim Ram Definition * * This type is used to access the Vim Ram. */ /** @typedef vimRAM_t * @brief Vim Ram Type Definition * * This type is used to access the Vim Ram. */ typedef volatile struct vimRam { t_isrFuncPTR ISR[VIM_CHANNELS]; } vimRAM_t; #define vimRAM ((vimRAM_t *)0xFFF82000U) static const t_isrFuncPTR s_vim_init[128U] = { &phantomInterrupt, &esmHighInterrupt, /* Channel 0 */ &phantomInterrupt, /* Channel 1 */ &vPortPreemptiveTick, /* Channel 2 */ &phantomInterrupt, /* Channel 3 */ &phantomInterrupt, /* Channel 4 */ &phantomInterrupt, /* Channel 5 */ &phantomInterrupt, /* Channel 6 */ &phantomInterrupt, /* Channel 7 */ &phantomInterrupt, /* Channel 8 */ &gioHighLevelInterrupt, /* Channel 9 */ &phantomInterrupt, /* Channel 10 */ &phantomInterrupt, /* Channel 11 */ &phantomInterrupt, /* Channel 12 */ &phantomInterrupt, /* Channel 13 */ &phantomInterrupt, /* Channel 14 */ &phantomInterrupt, /* Channel 15 */ &phantomInterrupt, /* Channel 16 */ &phantomInterrupt, /* Channel 17 */ &phantomInterrupt, /* Channel 18 */ &phantomInterrupt, /* Channel 19 */ &phantomInterrupt, /* Channel 20 */ &vPortYeildWithinAPI, /* Channel 21 */ &phantomInterrupt, /* Channel 22 */ &phantomInterrupt, /* Channel 23 */ &phantomInterrupt, /* Channel 24 */ &phantomInterrupt, /* Channel 25 */ &phantomInterrupt, /* Channel 26 */ &phantomInterrupt, /* Channel 27 */ &phantomInterrupt, /* Channel 28 */ &phantomInterrupt, /* Channel 29 */ &phantomInterrupt, /* Channel 30 */ &phantomInterrupt, /* Channel 31 */ &phantomInterrupt, /* Channel 32 */ &phantomInterrupt, /* Channel 33 */ &phantomInterrupt, /* Channel 34 */ &phantomInterrupt, /* Channel 35 */ &phantomInterrupt, /* Channel 36 */ &phantomInterrupt, /* Channel 37 */ &phantomInterrupt, /* Channel 38 */ &phantomInterrupt, /* Channel 39 */ &phantomInterrupt, /* Channel 40 */ &phantomInterrupt, /* Channel 41 */ &phantomInterrupt, /* Channel 42 */ &phantomInterrupt, /* Channel 43 */ &phantomInterrupt, /* Channel 44 */ &phantomInterrupt, /* Channel 45 */ &phantomInterrupt, /* Channel 46 */ &phantomInterrupt, /* Channel 47 */ &phantomInterrupt, /* Channel 48 */ &phantomInterrupt, /* Channel 49 */ &phantomInterrupt, /* Channel 50 */ &phantomInterrupt, /* Channel 51 */ &phantomInterrupt, /* Channel 52 */ &phantomInterrupt, /* Channel 53 */ &phantomInterrupt, /* Channel 54 */ &phantomInterrupt, /* Channel 55 */ &phantomInterrupt, /* Channel 56 */ &phantomInterrupt, /* Channel 57 */ &phantomInterrupt, /* Channel 58 */ &phantomInterrupt, /* Channel 59 */ &phantomInterrupt, /* Channel 60 */ &phantomInterrupt, /* Channel 61 */ &phantomInterrupt, /* Channel 62 */ &het2HighLevelInterrupt, /* Channel 63 */ &phantomInterrupt, /* Channel 64 */ &phantomInterrupt, /* Channel 65 */ &phantomInterrupt, /* Channel 66 */ &phantomInterrupt, /* Channel 67 */ &phantomInterrupt, /* Channel 68 */ &phantomInterrupt, /* Channel 69 */ &phantomInterrupt, /* Channel 70 */ &phantomInterrupt, /* Channel 71 */ &phantomInterrupt, /* Channel 72 */ &het2LowLevelInterrupt, /* Channel 73 */ &phantomInterrupt, /* Channel 74 */ &phantomInterrupt, /* Channel 75 */ &phantomInterrupt, /* Channel 76 */ &EMACTxIntISR, /* Channel 77 */ &phantomInterrupt, /* Channel 78 */ &EMACRxIntISR, /* Channel 79 */ &phantomInterrupt, /* Channel 80 */ &phantomInterrupt, /* Channel 81 */ &phantomInterrupt, /* Channel 82 */ &phantomInterrupt, /* Channel 83 */ &phantomInterrupt, /* Channel 84 */ &phantomInterrupt, /* Channel 85 */ &phantomInterrupt, /* Channel 86 */ &phantomInterrupt, /* Channel 87 */ &phantomInterrupt, /* Channel 88 */ &phantomInterrupt, /* Channel 89 */ &phantomInterrupt, /* Channel 90 */ &phantomInterrupt, /* Channel 91 */ &phantomInterrupt, /* Channel 92 */ &phantomInterrupt, /* Channel 93 */ &phantomInterrupt, /* Channel 94 */ &phantomInterrupt, /* Channel 95 */ &phantomInterrupt, /* Channel 96 */ &phantomInterrupt, /* Channel 97 */ &phantomInterrupt, /* Channel 98 */ &phantomInterrupt, /* Channel 99 */ &phantomInterrupt, /* Channel 100 */ &phantomInterrupt, /* Channel 101 */ &phantomInterrupt, /* Channel 102 */ &phantomInterrupt, /* Channel 103 */ &phantomInterrupt, /* Channel 104 */ &phantomInterrupt, /* Channel 105 */ &phantomInterrupt, /* Channel 106 */ &phantomInterrupt, /* Channel 107 */ &phantomInterrupt, /* Channel 108 */ &phantomInterrupt, /* Channel 109 */ &phantomInterrupt, /* Channel 110 */ &phantomInterrupt, /* Channel 111 */ &phantomInterrupt, /* Channel 112 */ &phantomInterrupt, /* Channel 113 */ &phantomInterrupt, /* Channel 114 */ &phantomInterrupt, /* Channel 115 */ &phantomInterrupt, /* Channel 116 */ &phantomInterrupt, /* Channel 117 */ &phantomInterrupt, /* Channel 118 */ &phantomInterrupt, /* Channel 119 */ &phantomInterrupt, /* Channel 120 */ &phantomInterrupt, /* Channel 121 */ &phantomInterrupt, /* Channel 122 */ &phantomInterrupt, /* Channel 123 */ &phantomInterrupt, /* Channel 124 */ &phantomInterrupt, /* Channel 125 */ &phantomInterrupt, /* Channel 126 */ }; void vimECCErrorHandler(void); /* SourceId : VIM_SourceId_001 */ /* DesignId : VIM_DesignId_001 */ /* Requirements : HL_CONQ_VIM_SR2 */ /** @fn void vimInit(void) * @brief Initializes VIM module * * This function initializes VIM RAM and registers */ void vimInit(void) { /* USER CODE BEGIN (1) */ /* USER CODE END */ /* Enable ECC for VIM RAM */ /* Errata VIM#28 Workaround: Disable Single Bit error correction */ vimREG->ECCCTL = (uint32)((uint32)0xAU << 0U) | (uint32)((uint32)0x5U << 16U); /* Initialize VIM table */ { uint32 i; for (i = 0U; i < VIM_CHANNELS; i++) { vimRAM->ISR[i] = s_vim_init[i]; } } vimREG->FBVECADDR = (uint32)&vimECCErrorHandler; /* set IRQ/FIQ priorities */ vimREG->FIRQPR0 = (uint32)((uint32)SYS_FIQ << 0U) | (uint32)((uint32)SYS_FIQ << 1U) | (uint32)((uint32)SYS_IRQ << 2U) | (uint32)((uint32)SYS_IRQ << 3U) | (uint32)((uint32)SYS_IRQ << 4U) | (uint32)((uint32)SYS_IRQ << 5U) | (uint32)((uint32)SYS_IRQ << 6U) | (uint32)((uint32)SYS_IRQ << 7U) | (uint32)((uint32)SYS_IRQ << 8U) | (uint32)((uint32)SYS_IRQ << 9U) | (uint32)((uint32)SYS_IRQ << 10U) | (uint32)((uint32)SYS_IRQ << 11U) | (uint32)((uint32)SYS_IRQ << 12U) | (uint32)((uint32)SYS_IRQ << 13U) | (uint32)((uint32)SYS_IRQ << 14U) | (uint32)((uint32)SYS_IRQ << 15U) | (uint32)((uint32)SYS_IRQ << 16U) | (uint32)((uint32)SYS_IRQ << 17U) | (uint32)((uint32)SYS_IRQ << 18U) | (uint32)((uint32)SYS_IRQ << 19U) | (uint32)((uint32)SYS_IRQ << 20U) | (uint32)((uint32)SYS_IRQ << 21U) | (uint32)((uint32)SYS_IRQ << 22U) | (uint32)((uint32)SYS_IRQ << 23U) | (uint32)((uint32)SYS_IRQ << 24U) | (uint32)((uint32)SYS_IRQ << 25U) | (uint32)((uint32)SYS_IRQ << 26U) | (uint32)((uint32)SYS_IRQ << 27U) | (uint32)((uint32)SYS_IRQ << 28U) | (uint32)((uint32)SYS_IRQ << 29U) | (uint32)((uint32)SYS_IRQ << 30U) | (uint32)((uint32)SYS_IRQ << 31U); vimREG->FIRQPR1 = (uint32)((uint32)SYS_IRQ << 0U) | (uint32)((uint32)SYS_IRQ << 1U) | (uint32)((uint32)SYS_IRQ << 2U) | (uint32)((uint32)SYS_IRQ << 3U) | (uint32)((uint32)SYS_IRQ << 4U) | (uint32)((uint32)SYS_IRQ << 5U) | (uint32)((uint32)SYS_IRQ << 6U) | (uint32)((uint32)SYS_IRQ << 7U) | (uint32)((uint32)SYS_IRQ << 8U) | (uint32)((uint32)SYS_IRQ << 9U) | (uint32)((uint32)SYS_IRQ << 10U) | (uint32)((uint32)SYS_IRQ << 11U) | (uint32)((uint32)SYS_IRQ << 12U) | (uint32)((uint32)SYS_IRQ << 13U) | (uint32)((uint32)SYS_IRQ << 14U) | (uint32)((uint32)SYS_IRQ << 15U) | (uint32)((uint32)SYS_IRQ << 16U) | (uint32)((uint32)SYS_IRQ << 17U) | (uint32)((uint32)SYS_IRQ << 18U) | (uint32)((uint32)SYS_IRQ << 19U) | (uint32)((uint32)SYS_IRQ << 20U) | (uint32)((uint32)SYS_IRQ << 21U) | (uint32)((uint32)SYS_IRQ << 22U) | (uint32)((uint32)SYS_IRQ << 23U) | (uint32)((uint32)SYS_IRQ << 24U) | (uint32)((uint32)SYS_IRQ << 25U) | (uint32)((uint32)SYS_IRQ << 26U) | (uint32)((uint32)SYS_IRQ << 27U) | (uint32)((uint32)SYS_IRQ << 28U) | (uint32)((uint32)SYS_IRQ << 29U) | (uint32)((uint32)SYS_IRQ << 30U) | (uint32)((uint32)SYS_IRQ << 31U); vimREG->FIRQPR2 = (uint32)((uint32)SYS_IRQ << 0U) | (uint32)((uint32)SYS_IRQ << 1U) | (uint32)((uint32)SYS_IRQ << 2U) | (uint32)((uint32)SYS_IRQ << 3U) | (uint32)((uint32)SYS_IRQ << 4U) | (uint32)((uint32)SYS_IRQ << 5U) | (uint32)((uint32)SYS_IRQ << 6U) | (uint32)((uint32)SYS_IRQ << 7U) | (uint32)((uint32)SYS_IRQ << 8U) | (uint32)((uint32)SYS_IRQ << 9U) | (uint32)((uint32)SYS_IRQ << 10U) | (uint32)((uint32)SYS_IRQ << 11U) | (uint32)((uint32)SYS_IRQ << 12U) | (uint32)((uint32)SYS_IRQ << 13U) | (uint32)((uint32)SYS_IRQ << 14U) | (uint32)((uint32)SYS_IRQ << 15U) | (uint32)((uint32)SYS_IRQ << 16U) | (uint32)((uint32)SYS_IRQ << 17U) | (uint32)((uint32)SYS_IRQ << 18U) | (uint32)((uint32)SYS_IRQ << 19U) | (uint32)((uint32)SYS_IRQ << 20U) | (uint32)((uint32)SYS_IRQ << 21U) | (uint32)((uint32)SYS_IRQ << 22U) | (uint32)((uint32)SYS_IRQ << 23U) | (uint32)((uint32)SYS_IRQ << 24U) | (uint32)((uint32)SYS_IRQ << 25U) | (uint32)((uint32)SYS_IRQ << 26U) | (uint32)((uint32)SYS_IRQ << 27U) | (uint32)((uint32)SYS_IRQ << 28U) | (uint32)((uint32)SYS_IRQ << 29U) | (uint32)((uint32)SYS_IRQ << 30U) | (uint32)((uint32)SYS_IRQ << 31U); vimREG->FIRQPR3 = (uint32)((uint32)SYS_IRQ << 0U) | (uint32)((uint32)SYS_IRQ << 1U) | (uint32)((uint32)SYS_IRQ << 2U) | (uint32)((uint32)SYS_IRQ << 3U) | (uint32)((uint32)SYS_IRQ << 4U) | (uint32)((uint32)SYS_IRQ << 5U) | (uint32)((uint32)SYS_IRQ << 6U) | (uint32)((uint32)SYS_IRQ << 7U) | (uint32)((uint32)SYS_IRQ << 8U) | (uint32)((uint32)SYS_IRQ << 9U) | (uint32)((uint32)SYS_IRQ << 10U) | (uint32)((uint32)SYS_IRQ << 11U) | (uint32)((uint32)SYS_IRQ << 12U) | (uint32)((uint32)SYS_IRQ << 13U) | (uint32)((uint32)SYS_IRQ << 14U) | (uint32)((uint32)SYS_IRQ << 15U) | (uint32)((uint32)SYS_IRQ << 16U) | (uint32)((uint32)SYS_IRQ << 17U) | (uint32)((uint32)SYS_IRQ << 18U) | (uint32)((uint32)SYS_IRQ << 19U) | (uint32)((uint32)SYS_IRQ << 20U) | (uint32)((uint32)SYS_IRQ << 21U) | (uint32)((uint32)SYS_IRQ << 22U) | (uint32)((uint32)SYS_IRQ << 23U) | (uint32)((uint32)SYS_IRQ << 24U) | (uint32)((uint32)SYS_IRQ << 25U) | (uint32)((uint32)SYS_IRQ << 26U) | (uint32)((uint32)SYS_IRQ << 27U) | (uint32)((uint32)SYS_IRQ << 28U) | (uint32)((uint32)SYS_IRQ << 29U) | (uint32)((uint32)SYS_IRQ << 30U) | (uint32)((uint32)SYS_IRQ << 31U); /* enable interrupts */ vimREG->REQMASKSET0 = (uint32)((uint32)1U << 0U) | (uint32)((uint32)1U << 1U) | (uint32)((uint32)1U << 2U) | (uint32)((uint32)0U << 3U) | (uint32)((uint32)0U << 4U) | (uint32)((uint32)0U << 5U) | (uint32)((uint32)0U << 6U) | (uint32)((uint32)0U << 7U) | (uint32)((uint32)0U << 8U) | (uint32)((uint32)1U << 9U) | (uint32)((uint32)0U << 10U) | (uint32)((uint32)0U << 11U) | (uint32)((uint32)0U << 12U) | (uint32)((uint32)0U << 13U) | (uint32)((uint32)0U << 14U) | (uint32)((uint32)0U << 15U) | (uint32)((uint32)0U << 16U) | (uint32)((uint32)0U << 17U) | (uint32)((uint32)0U << 18U) | (uint32)((uint32)0U << 19U) | (uint32)((uint32)0U << 20U) | (uint32)((uint32)1U << 21U) | (uint32)((uint32)0U << 22U) | (uint32)((uint32)0U << 23U) | (uint32)((uint32)0U << 24U) | (uint32)((uint32)0U << 25U) | (uint32)((uint32)0U << 26U) | (uint32)((uint32)0U << 27U) | (uint32)((uint32)0U << 28U) | (uint32)((uint32)0U << 29U) | (uint32)((uint32)0U << 30U) | (uint32)((uint32)0U << 31U); vimREG->REQMASKSET1 = (uint32)((uint32)0U << 0U) | (uint32)((uint32)0U << 1U) | (uint32)((uint32)0U << 2U) | (uint32)((uint32)0U << 3U) | (uint32)((uint32)0U << 4U) | (uint32)((uint32)0U << 5U) | (uint32)((uint32)0U << 6U) | (uint32)((uint32)0U << 7U) | (uint32)((uint32)0U << 8U) | (uint32)((uint32)0U << 9U) | (uint32)((uint32)0U << 10U) | (uint32)((uint32)0U << 11U) | (uint32)((uint32)0U << 12U) | (uint32)((uint32)0U << 13U) | (uint32)((uint32)0U << 14U) | (uint32)((uint32)0U << 15U) | (uint32)((uint32)0U << 16U) | (uint32)((uint32)0U << 17U) | (uint32)((uint32)0U << 18U) | (uint32)((uint32)0U << 19U) | (uint32)((uint32)0U << 20U) | (uint32)((uint32)0U << 21U) | (uint32)((uint32)0U << 22U) | (uint32)((uint32)0U << 23U) | (uint32)((uint32)0U << 24U) | (uint32)((uint32)0U << 25U) | (uint32)((uint32)0U << 26U) | (uint32)((uint32)0U << 27U) | (uint32)((uint32)0U << 28U) | (uint32)((uint32)0U << 29U) | (uint32)((uint32)0U << 30U) | (uint32)((uint32)1U << 31U); vimREG->REQMASKSET2 = (uint32)((uint32)0U << 0U) | (uint32)((uint32)1U << 1U) | (uint32)((uint32)0U << 2U) | (uint32)((uint32)0U << 3U) | (uint32)((uint32)0U << 4U) | (uint32)((uint32)0U << 5U) | (uint32)((uint32)0U << 6U) | (uint32)((uint32)0U << 7U) | (uint32)((uint32)0U << 8U) | (uint32)((uint32)1U << 9U) | (uint32)((uint32)0U << 10U) | (uint32)((uint32)1U << 11U) | (uint32)((uint32)0U << 12U) | (uint32)((uint32)1U << 13U) | (uint32)((uint32)0U << 14U) | (uint32)((uint32)1U << 15U) | (uint32)((uint32)0U << 16U) | (uint32)((uint32)0U << 17U) | (uint32)((uint32)0U << 18U) | (uint32)((uint32)0U << 19U) | (uint32)((uint32)0U << 20U) | (uint32)((uint32)0U << 21U) | (uint32)((uint32)0U << 22U) | (uint32)((uint32)0U << 23U) | (uint32)((uint32)0U << 24U) | (uint32)((uint32)0U << 25U) | (uint32)((uint32)0U << 26U) | (uint32)((uint32)0U << 27U) | (uint32)((uint32)0U << 28U) | (uint32)((uint32)0U << 29U) | (uint32)((uint32)0U << 30U) | (uint32)((uint32)0U << 31U); vimREG->REQMASKSET3 = (uint32)((uint32)0U << 0U) | (uint32)((uint32)0U << 1U) | (uint32)((uint32)0U << 2U) | (uint32)((uint32)0U << 3U) | (uint32)((uint32)0U << 4U) | (uint32)((uint32)0U << 5U) | (uint32)((uint32)0U << 6U) | (uint32)((uint32)0U << 7U) | (uint32)((uint32)0U << 8U) | (uint32)((uint32)0U << 9U) | (uint32)((uint32)0U << 10U) | (uint32)((uint32)0U << 11U) | (uint32)((uint32)0U << 12U) | (uint32)((uint32)0U << 13U) | (uint32)((uint32)0U << 14U) | (uint32)((uint32)0U << 15U) | (uint32)((uint32)0U << 16U) | (uint32)((uint32)0U << 17U) | (uint32)((uint32)0U << 18U) | (uint32)((uint32)0U << 19U) | (uint32)((uint32)0U << 20U) | (uint32)((uint32)0U << 21U) | (uint32)((uint32)0U << 22U) | (uint32)((uint32)0U << 23U) | (uint32)((uint32)0U << 24U) | (uint32)((uint32)0U << 25U) | (uint32)((uint32)0U << 26U) | (uint32)((uint32)0U << 27U) | (uint32)((uint32)0U << 28U) | (uint32)((uint32)0U << 29U) | (uint32)((uint32)0U << 30U) | (uint32)((uint32)0U << 31U); /* Set Capture event sources */ vimREG->CAPEVT = ((uint32)((uint32)0U << 0U) |(uint32)((uint32)0U << 16U)); /* USER CODE BEGIN (2) */ /* USER CODE END */ } /* SourceId : VIM_SourceId_002 */ /* DesignId : VIM_DesignId_002 */ /* Requirements : HL_CONQ_VIM_SR5 */ /** @fn void vimChannelMap(uint32 request, uint32 channel, t_isrFuncPTR handler) * @brief Map selected interrupt request to the selected channel * * @param[in] request: Interrupt request number 2..95 * @param[in] channel: VIM Channel number 2..95 * @param[in] handler: Address of the interrupt handler * * This function will map selected interrupt request to the selected channel. * */ void vimChannelMap(uint32 request, uint32 channel, t_isrFuncPTR handler) { uint32 i,j; /* USER CODE BEGIN (3) */ /* USER CODE END */ i = channel >> 2U; /* Find the register to configure */ j = channel -(i<<2U); /* Find the offset of the type */ j = 3U-j; /* reverse the byte order */ j = j<<3U; /* find the bit location */ /*Mapping the required interrupt request to the required channel*/ vimREG->CHANCTRL[i] &= ~(uint32)((uint32)0xFFU << j); vimREG->CHANCTRL[i] |= (request << j); /*Updating VIMRAM*/ vimRAM->ISR[channel + 1U] = handler; /* USER CODE BEGIN (4) */ /* USER CODE END */ } /* SourceId : VIM_SourceId_003 */ /* DesignId : VIM_DesignId_003 */ /* Requirements : HL_CONQ_VIM_SR3 */ /** @fn void vimEnableInterrupt(uint32 channel, systemInterrupt_t inttype) * @brief Enable interrupt for the the selected channel * * @param[in] channel: VIM Channel number 2..95 * @param[in] inttype: Interrupt type * - SYS_IRQ: Selected channel will be enabled as IRQ * - SYS_FIQ: Selected channel will be enabled as FIQ * * This function will enable interrupt for the selected channel. * */ void vimEnableInterrupt(uint32 channel, systemInterrupt_t inttype) { /* USER CODE BEGIN (5) */ /* USER CODE END */ if (channel >= 96U) { if(inttype == SYS_IRQ) { vimREG->FIRQPR3 &= ~(uint32)((uint32)1U << (channel-96U)); } else { vimREG->FIRQPR3 |= ((uint32)1U << (channel-96U)); } vimREG->REQMASKSET3 = (uint32)1U << (channel-96U); } else if (channel >= 64U) { if(inttype == SYS_IRQ) { vimREG->FIRQPR2 &= ~(uint32)((uint32)1U << (channel-64U)); } else { vimREG->FIRQPR2 |= ((uint32)1U << (channel-64U)); } vimREG->REQMASKSET2 = (uint32)1U << (channel-64U); } else if (channel >= 32U) { if(inttype == SYS_IRQ) { vimREG->FIRQPR1 &= ~(uint32)((uint32)1U << (channel-32U)); } else { vimREG->FIRQPR1 |= ((uint32)1U << (channel-32U)); } vimREG->REQMASKSET1 = (uint32)1U << (channel-32U); } else if (channel >= 2U) { if(inttype == SYS_IRQ) { vimREG->FIRQPR0 &= ~(uint32)((uint32)1U << channel); } else { vimREG->FIRQPR0 |= ((uint32)1U << channel); } vimREG->REQMASKSET0 = (uint32)1U << channel; } else { /* Empty */ } /* USER CODE BEGIN (6) */ /* USER CODE END */ } /* SourceId : VIM_SourceId_004 */ /* DesignId : VIM_DesignId_004 */ /* Requirements : HL_CONQ_VIM_SR5 */ /** @fn void vimDisableInterrupt(uint32 channel) * @brief Disable interrupt for the the selected channel * * @param[in] channel: VIM Channel number 2..95 * * This function will disable interrupt for the selected channel. * */ void vimDisableInterrupt(uint32 channel) { /* USER CODE BEGIN (7) */ /* USER CODE END */ if (channel >= 96U) { vimREG->REQMASKCLR3 = (uint32)1U << (channel-96U); } else if (channel >= 64U) { vimREG->REQMASKCLR2 = (uint32)1U << (channel-64U); } else if (channel >=32U) { vimREG->REQMASKCLR1 = (uint32)1U << (channel-32U); } else if (channel >= 2U) { vimREG->REQMASKCLR0 = (uint32)1U << channel; } else { /* Empty */ } /* USER CODE BEGIN (8) */ /* USER CODE END */ } /* USER CODE BEGIN (9) */ /* USER CODE END */ /* SourceId : VIM_SourceId_005 */ /* DesignId : VIM_DesignId_005 */ /* Requirements : HL_CONQ_VIM_SR7 */ /** @fn void vimGetConfigValue(vim_config_reg_t *config_reg, config_value_type_t type) * @brief Get the initial or current values of the configuration registers * * @param[in] *config_reg: pointer to the struct to which the initial or current value of the configuration registers need to be stored * @param[in] type: whether initial or current value of the configuration registers need to be stored * - InitialValue: initial value of the configuration registers will be stored in the struct pointed by config_reg * - CurrentValue: initial value of the configuration registers will be stored in the struct pointed by config_reg * * This function will copy the initial or current value (depending on the parameter 'type') of the configuration * registers to the struct pointed by config_reg * */ void vimGetConfigValue(vim_config_reg_t *config_reg, config_value_type_t type) { if (type == InitialValue) { config_reg->CONFIG_FIRQPR0 = VIM_FIRQPR0_CONFIGVALUE; config_reg->CONFIG_FIRQPR1 = VIM_FIRQPR1_CONFIGVALUE; config_reg->CONFIG_FIRQPR2 = VIM_FIRQPR2_CONFIGVALUE; config_reg->CONFIG_FIRQPR3 = VIM_FIRQPR3_CONFIGVALUE; config_reg->CONFIG_REQMASKSET0 = VIM_REQMASKSET0_CONFIGVALUE; config_reg->CONFIG_REQMASKSET1 = VIM_REQMASKSET1_CONFIGVALUE; config_reg->CONFIG_REQMASKSET2 = VIM_REQMASKSET2_CONFIGVALUE; config_reg->CONFIG_REQMASKSET3 = VIM_REQMASKSET3_CONFIGVALUE; config_reg->CONFIG_WAKEMASKSET0 = VIM_WAKEMASKSET0_CONFIGVALUE; config_reg->CONFIG_WAKEMASKSET1 = VIM_WAKEMASKSET1_CONFIGVALUE; config_reg->CONFIG_WAKEMASKSET2 = VIM_WAKEMASKSET2_CONFIGVALUE; config_reg->CONFIG_WAKEMASKSET3 = VIM_WAKEMASKSET3_CONFIGVALUE; config_reg->CONFIG_CAPEVT = VIM_CAPEVT_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[0U] = VIM_CHANCTRL0_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[1U] = VIM_CHANCTRL1_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[2U] = VIM_CHANCTRL2_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[3U] = VIM_CHANCTRL3_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[4U] = VIM_CHANCTRL4_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[5U] = VIM_CHANCTRL5_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[6U] = VIM_CHANCTRL6_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[7U] = VIM_CHANCTRL7_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[8U] = VIM_CHANCTRL8_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[9U] = VIM_CHANCTRL9_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[10U] = VIM_CHANCTRL10_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[11U] = VIM_CHANCTRL11_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[12U] = VIM_CHANCTRL12_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[13U] = VIM_CHANCTRL13_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[14U] = VIM_CHANCTRL14_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[15U] = VIM_CHANCTRL15_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[16U] = VIM_CHANCTRL16_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[17U] = VIM_CHANCTRL17_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[18U] = VIM_CHANCTRL18_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[19U] = VIM_CHANCTRL19_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[20U] = VIM_CHANCTRL20_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[21U] = VIM_CHANCTRL21_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[22U] = VIM_CHANCTRL22_CONFIGVALUE; config_reg->CONFIG_CHANCTRL[23U] = VIM_CHANCTRL23_CONFIGVALUE; } else { /*SAFETYMCUSW 134 S MR:12.2 <APPROVED> "Register read back support" */ config_reg->CONFIG_FIRQPR0 = vimREG->FIRQPR0; config_reg->CONFIG_FIRQPR1 = vimREG->FIRQPR1; config_reg->CONFIG_FIRQPR2 = vimREG->FIRQPR2; config_reg->CONFIG_FIRQPR3 = vimREG->FIRQPR3; config_reg->CONFIG_REQMASKSET0 = vimREG->REQMASKSET0; config_reg->CONFIG_REQMASKSET1 = vimREG->REQMASKSET1; config_reg->CONFIG_REQMASKSET2 = vimREG->REQMASKSET2; config_reg->CONFIG_REQMASKSET3 = vimREG->REQMASKSET3; config_reg->CONFIG_WAKEMASKSET0 = vimREG->WAKEMASKSET0; config_reg->CONFIG_WAKEMASKSET1 = vimREG->WAKEMASKSET1; config_reg->CONFIG_WAKEMASKSET2 = vimREG->WAKEMASKSET2; config_reg->CONFIG_WAKEMASKSET3 = vimREG->WAKEMASKSET3; config_reg->CONFIG_CAPEVT = vimREG->CAPEVT; config_reg->CONFIG_CHANCTRL[0U] = vimREG->CHANCTRL[0U]; config_reg->CONFIG_CHANCTRL[1U] = vimREG->CHANCTRL[1U]; config_reg->CONFIG_CHANCTRL[2U] = vimREG->CHANCTRL[2U]; config_reg->CONFIG_CHANCTRL[3U] = vimREG->CHANCTRL[3U]; config_reg->CONFIG_CHANCTRL[4U] = vimREG->CHANCTRL[4U]; config_reg->CONFIG_CHANCTRL[5U] = vimREG->CHANCTRL[5U]; config_reg->CONFIG_CHANCTRL[6U] = vimREG->CHANCTRL[6U]; config_reg->CONFIG_CHANCTRL[7U] = vimREG->CHANCTRL[7U]; config_reg->CONFIG_CHANCTRL[8U] = vimREG->CHANCTRL[8U]; config_reg->CONFIG_CHANCTRL[9U] = vimREG->CHANCTRL[9U]; config_reg->CONFIG_CHANCTRL[10U] = vimREG->CHANCTRL[10U]; config_reg->CONFIG_CHANCTRL[11U] = vimREG->CHANCTRL[11U]; config_reg->CONFIG_CHANCTRL[12U] = vimREG->CHANCTRL[12U]; config_reg->CONFIG_CHANCTRL[13U] = vimREG->CHANCTRL[13U]; config_reg->CONFIG_CHANCTRL[14U] = vimREG->CHANCTRL[14U]; config_reg->CONFIG_CHANCTRL[15U] = vimREG->CHANCTRL[15U]; config_reg->CONFIG_CHANCTRL[16U] = vimREG->CHANCTRL[16U]; config_reg->CONFIG_CHANCTRL[17U] = vimREG->CHANCTRL[17U]; config_reg->CONFIG_CHANCTRL[18U] = vimREG->CHANCTRL[18U]; config_reg->CONFIG_CHANCTRL[19U] = vimREG->CHANCTRL[19U]; config_reg->CONFIG_CHANCTRL[20U] = vimREG->CHANCTRL[20U]; config_reg->CONFIG_CHANCTRL[21U] = vimREG->CHANCTRL[21U]; config_reg->CONFIG_CHANCTRL[22U] = vimREG->CHANCTRL[22U]; config_reg->CONFIG_CHANCTRL[23U] = vimREG->CHANCTRL[23U]; } } /* USER CODE BEGIN (10) */ /* USER CODE END */ #pragma CODE_STATE(vimECCErrorHandler, 32) #pragma INTERRUPT(vimECCErrorHandler, IRQ) #pragma WEAK(vimECCErrorHandler) /* SourceId : VIM_SourceId_006 */ /* DesignId : VIM_DesignId_006 */ /* Requirements : HL_CONQ_VIM_SR6 */ void vimECCErrorHandler(void) { uint32 vec; /* USER CODE BEGIN (11) */ /* USER CODE END */ /* Identify the corrupted address */ uint32 error_addr = vimREG->UERRADDR; /* Identify the channel number */ uint32 error_channel = ((error_addr & 0x3FFU) >> 2U); /* Correct the corrupted location */ vimRAM->ISR[error_channel] = s_vim_init[error_channel]; /* Clear Parity Error Flag */ vimREG->ECCSTAT = 1U; /* Disable and enable the highest priority pending channel */ if (vimREG->FIQINDEX != 0U) { vec = vimREG->FIQINDEX - 1U; } else { /*SAFETYMCUSW 134 S MR:12.2 <APPROVED> "Read 32 bit volatile register" */ vec = vimREG->IRQINDEX - 1U; } if(vec == 0U) { vimREG->INTREQ0 = 1U; vec = esmREG->IOFFHR - 1U; if (vec < 32U) { esmREG->SR1[0U] = (uint32)1U << vec; esmGroup1Notification(esmREG, vec); } else if (vec < 64U) { esmREG->SR1[1U] = (uint32)1U << (vec-32U); esmGroup2Notification(esmREG, (vec-32U)); } else if (vec < 96U) { esmREG->SR4[0U] = (uint32)1U << (vec-64U); esmGroup1Notification(esmREG, (vec-32U)); } else if ((vec >= 128U) && (vec < 160U)) { esmREG->SR7[0U] = (uint32)1U << (vec-128U); esmGroup2Notification(esmREG, (vec-96U)); } else { esmREG->SR7[0U] = 0xFFFFFFFFU; esmREG->SR4[1U] = 0xFFFFFFFFU; esmREG->SR4[0U] = 0xFFFFFFFFU; esmREG->SR1[1U] = 0xFFFFFFFFU; esmREG->SR1[0U] = 0xFFFFFFFFU; } } else if (vec < 32U) { vimREG->REQMASKCLR0 = (uint32)1U << vec; vimREG->REQMASKSET0 = (uint32)1U << vec; } else if (vec < 64U) { vimREG->REQMASKCLR1 = (uint32)1U << (vec-32U); vimREG->REQMASKSET1 = (uint32)1U << (vec-32U); } else if (vec < 96U) { vimREG->REQMASKCLR2 = (uint32)1U << (vec-64U); vimREG->REQMASKSET2 = (uint32)1U << (vec-64U); } else { vimREG->REQMASKCLR3 = (uint32)1U << (vec-96U); vimREG->REQMASKSET3 = (uint32)1U << (vec-96U); } /* USER CODE BEGIN (12) */ /* USER CODE END */ } /* USER CODE BEGIN (13) */ /* USER CODE END */
595840.c
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * * (C) 2003 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "mpi.h" #include <stdio.h> #include "mpitest.h" static char MTEST_Descrip[] = "A simple test of Comm_spawn, followed by intercomm merge"; int main( int argc, char *argv[] ) { int errs = 0, err; int rank, size, rsize, i; int np = 2; int errcodes[2]; MPI_Comm parentcomm, intercomm, intracomm, intracomm2, intracomm3; int isChild = 0; MPI_Status status; MTest_Init( &argc, &argv ); MPI_Comm_get_parent( &parentcomm ); if (parentcomm == MPI_COMM_NULL) { /* Create 2 more processes */ MPI_Comm_spawn( "./spawnintra", MPI_ARGV_NULL, np, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &intercomm, errcodes ); } else intercomm = parentcomm; /* We now have a valid intercomm */ MPI_Comm_remote_size( intercomm, &rsize ); MPI_Comm_size( intercomm, &size ); MPI_Comm_rank( intercomm, &rank ); if (parentcomm == MPI_COMM_NULL) { /* Master */ if (rsize != np) { errs++; printf( "Did not create %d processes (got %d)\n", np, rsize ); } if (rank == 0) { for (i=0; i<rsize; i++) { MPI_Send( &i, 1, MPI_INT, i, 0, intercomm ); } } } else { /* Child */ isChild = 1; if (size != np) { errs++; printf( "(Child) Did not create %d processes (got %d)\n", np, size ); } MPI_Recv( &i, 1, MPI_INT, 0, 0, intercomm, &status ); if (i != rank) { errs++; printf( "Unexpected rank on child %d (%d)\n", rank, i ); } } /* At this point, try to form the intracommunicator */ MPI_Intercomm_merge( intercomm, isChild, &intracomm ); /* Check on the intra comm */ { int icsize, icrank, wrank; MPI_Comm_size( intracomm, &icsize ); MPI_Comm_rank( intracomm, &icrank ); MPI_Comm_rank( MPI_COMM_WORLD, &wrank ); if (icsize != rsize + size) { errs++; printf( "Intracomm rank %d thinks size is %d, not %d\n", icrank, icsize, rsize + size ); } /* Make sure that the processes are ordered correctly */ if (isChild) { int psize; MPI_Comm_remote_size( parentcomm, &psize ); if (icrank != psize + wrank ) { errs++; printf( "Intracomm rank %d (from child) should have rank %d\n", icrank, psize + wrank ); } } else { if (icrank != wrank) { errs++; printf( "Intracomm rank %d (from parent) should have rank %d\n", icrank, wrank ); } } } /* At this point, try to form the intracommunicator, with the other processes first */ MPI_Intercomm_merge( intercomm, !isChild, &intracomm2 ); /* Check on the intra comm */ { int icsize, icrank, wrank; MPI_Comm_size( intracomm2, &icsize ); MPI_Comm_rank( intracomm2, &icrank ); MPI_Comm_rank( MPI_COMM_WORLD, &wrank ); if (icsize != rsize + size) { errs++; printf( "(2)Intracomm rank %d thinks size is %d, not %d\n", icrank, icsize, rsize + size ); } /* Make sure that the processes are ordered correctly */ if (isChild) { if (icrank != wrank ) { errs++; printf( "(2)Intracomm rank %d (from child) should have rank %d\n", icrank, wrank ); } } else { int csize; MPI_Comm_remote_size( intercomm, &csize ); if (icrank != wrank + csize) { errs++; printf( "(2)Intracomm rank %d (from parent) should have rank %d\n", icrank, wrank + csize ); } } } /* At this point, try to form the intracommunicator, with an arbitrary choice for the first group of processes */ MPI_Intercomm_merge( intercomm, 0, &intracomm3 ); /* Check on the intra comm */ { int icsize, icrank, wrank; MPI_Comm_size( intracomm3, &icsize ); MPI_Comm_rank( intracomm3, &icrank ); MPI_Comm_rank( MPI_COMM_WORLD, &wrank ); if (icsize != rsize + size) { errs++; printf( "(3)Intracomm rank %d thinks size is %d, not %d\n", icrank, icsize, rsize + size ); } /* Eventually, we should test that the processes are ordered correctly, by groups (must be one of the two cases above) */ } /* Update error count */ if (isChild) { /* Send the errs back to the master process */ MPI_Ssend( &errs, 1, MPI_INT, 0, 1, intercomm ); } else { if (rank == 0) { /* We could use intercomm reduce to get the errors from the children, but we'll use a simpler loop to make sure that we get valid data */ for (i=0; i<rsize; i++) { MPI_Recv( &err, 1, MPI_INT, i, 1, intercomm, MPI_STATUS_IGNORE ); errs += err; } } } /* It isn't necessary to free the intracomms, but it should not hurt */ MPI_Comm_free( &intracomm ); MPI_Comm_free( &intracomm2 ); MPI_Comm_free( &intracomm3 ); /* It isn't necessary to free the intercomm, but it should not hurt */ MPI_Comm_free( &intercomm ); /* Note that the MTest_Finalize get errs only over COMM_WORLD */ /* Note also that both the parent and child will generate "No Errors" if both call MTest_Finalize */ if (parentcomm == MPI_COMM_NULL) { MTest_Finalize( errs ); } MPI_Finalize(); return 0; }
673225.c
/****************************************************************************** * * Copyright (C) 2009 - 2014 Xilinx, Inc. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * Use of the Software is limited solely to applications: * (a) running on a Xilinx device, or * (b) that interact with a Xilinx device through a bus or interconnect. * * 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 * XILINX BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Except as contained in this notice, the name of the Xilinx shall not be used * in advertising or otherwise to promote the sale, use or other dealings in * this Software without prior written authorization from Xilinx. * ******************************************************************************/ /* * helloworld.c: simple test application * * This application configures UART 16550 to baud rate 9600. * PS7 UART (Zynq) is not initialized by this application, since * bootrom/bsp configures it to baud rate 115200 * * ------------------------------------------------ * | UART TYPE BAUD RATE | * ------------------------------------------------ * uartns550 9600 * uartlite Configurable only in HW design * ps7_uart 115200 (configured by bootrom/bsp) */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "platform.h" #include "xparameters.h" #include "fsl.h" #include "xtmrctr_l.h" #include "xil_printf.h" // Define the output of the MD5 algorithm (4 words of 32 bits - a single hash of 128) struct word128 { uint32_t A; uint32_t B; uint32_t C; uint32_t D; }; #define N 4 #define LEFTROTATE(x, c) (((x) << (c)) | ((x) >> (32 - (c)))) // computes the MD5 hash from the input struct word128 md5(unsigned char* initial_msg, unsigned long initial_len) { uint32_t h0, h1, h2, h3; // Message (to prepare) uint8_t *msg = NULL; // Note: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating // r specifies the per-round shift amounts uint32_t r[] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}; // Use binary integer part of the sines of integers (in radians) as constants// Initialize variables: uint32_t k[] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391}; h0 = 0x67452301; h1 = 0xefcdab89; h2 = 0x98badcfe; h3 = 0x10325476; // Pre-processing: adding a single 1 bit //append "1" bit to message /* Notice: the input bytes are considered as bits strings, where the first bit is the most significant bit of the byte.[37] */ // Pre-processing: padding with zeros //append "0" bit until message length in bit = 448 (mod 512) //append length mod (2 pow 64) to message uint32_t new_len = ((((initial_len + 8) / 64) + 1) * 64) - 8; msg = calloc(new_len + 64, 1); // also appends "0" bits // (we alloc also 64 extra bytes...) memcpy(msg, initial_msg, initial_len); msg[initial_len] = 128; // write the "1" bit uint32_t bits_len = 8*initial_len; // note, we append the len memcpy(msg + new_len, &bits_len, 4); // in bits at the end of the buffer // Process the message in successive 512-bit chunks: //for each 512-bit chunk of message: for(uint32_t offset = 0; offset < new_len; offset += (512/8)) { // break chunk into sixteen 32-bit words w[j], 0 <= j <= 15 uint32_t *w = (uint32_t *) (msg + offset); // Initialize hash value for this chunk: uint32_t a = h0; uint32_t b = h1; uint32_t c = h2; uint32_t d = h3; // Main loop: for(uint32_t i = 0; i < 64; i++) { uint32_t f, g; if (i < 16) { f = (b & c) | ((~b) & d); g = i; } else if (i < 32) { f = (d & b) | ((~d) & c); g = (5*i + 1) % 16; } else if (i < 48) { f = b ^ c ^ d; g = (3*i + 5) % 16; } else { f = c ^ (b | (~d)); g = (7*i) % 16; } uint32_t temp = d; d = c; c = b; b = b + LEFTROTATE((a + f + k[i] + w[g]), r[i]); a = temp; } // Add this chunks hash to result so far: h0 += a; h1 += b; h2 += c; h3 += d; } struct word128 w = {h0, h1, h2, h3}; // cleanup free(msg); return w; } // Send the words to the md5 function and combines the result void Md5Sw(struct word128 pDst, uint32_t* pSrc, unsigned int size) { uint32_t* p; for (p = pSrc; p < pSrc + size; p++) { struct word128 w = md5((unsigned char*)p, sizeof(*p)); uint8_t *p0, *p1, *p2, *p3; p0=(uint8_t *)&w.A; p1=(uint8_t *)&w.B; p2=(uint8_t *)&w.C; p3=(uint8_t *)&w.D; pDst.A = ((p0[0] << 24) | (p0[1] << 16) | (p0[2] << 8) | p0[3]); pDst.B = ((p1[0] << 24) | (p1[1] << 16) | (p1[2] << 8) | p1[3]); pDst.C = ((p2[0] << 24) | (p2[1] << 16) | (p2[2] << 8) | p2[3]); pDst.D = ((p3[0] << 24) | (p3[1] << 16) | (p3[2] << 8) | p3[3]); } } // Print the array void PrintDataArray(uint32_t* pData, uint32_t size) { uint32_t* p; xil_printf("\n\r["); for (p = pData; p < pData + size; p++) { xil_printf("%08x ", *p); } xil_printf("]"); } // Print the hash void PrintDataArray128(struct word128 pData, unsigned int size) { xil_printf("\n\r"); xil_printf("%08x%08x%08x%08x ", pData.A, pData.B, pData.C, pData.D); } void ResetPerformanceTimer() { XTmrCtr_Disable(XPAR_TMRCTR_0_BASEADDR, 0); XTmrCtr_SetLoadReg(XPAR_TMRCTR_0_BASEADDR, 0, 0x00000001); XTmrCtr_LoadTimerCounterReg(XPAR_TMRCTR_0_BASEADDR, 0); XTmrCtr_SetControlStatusReg(XPAR_TMRCTR_0_BASEADDR, 0, 0x00000000); } void RestartPerformanceTimer() { ResetPerformanceTimer(); XTmrCtr_Enable(XPAR_TMRCTR_0_BASEADDR, 0); } uint32_t GetPerformanceTimer() { return XTmrCtr_GetTimerCounterReg(XPAR_TMRCTR_0_BASEADDR, 0); } uint32_t StopAndGetPerformanceTimer() { XTmrCtr_Disable(XPAR_TMRCTR_0_BASEADDR, 0); return GetPerformanceTimer(); } int main() { uint32_t srcData[N]; struct word128 dstData; uint32_t timeElapsed; init_platform(); xil_printf("\n\rSoftware Only MD5 Demonstration\n\r"); RestartPerformanceTimer(); srand(0); for (int i = 0; i < N; i++) { srcData[i] = rand() + rand(); } timeElapsed = StopAndGetPerformanceTimer(); xil_printf("\n\rArray initialization time: %d microseconds\n\r", timeElapsed / (XPAR_CPU_M_AXI_DP_FREQ_HZ / 1000000)); PrintDataArray(srcData, N); xil_printf("\n\r"); // Software only RestartPerformanceTimer(); Md5Sw(dstData, srcData, N); timeElapsed = StopAndGetPerformanceTimer(); xil_printf("\n\rSoftware only MD5 time: %d microseconds", timeElapsed / (XPAR_CPU_M_AXI_DP_FREQ_HZ / 1000000)); PrintDataArray128(dstData, N); xil_printf("\n\r"); cleanup_platform(); return 0; }
654563.c
/****************************************************************************** * Demonstrate the use of high-resolution timers. Link with -lrt * * Glenn K. Lockwood October 2015 ******************************************************************************/ #include <stdio.h> #include <time.h> #include <math.h> #include <stdlib.h> #define ARRAY_SIZE 4 * 1024 * 1024 int main( int argc, char **argv ) { struct timespec t0, tf, dt; long stride; long i; double *array, value; if ( argc < 2 || !(stride = atol( argv[1] )) ) { fprintf( stderr, "Syntax: %s <stride>\n", argv[0] ); return 1; } if ( !(array = malloc( sizeof(*array) * ARRAY_SIZE * stride)) ) { perror( "malloc failed" ); return 1; } clock_gettime(CLOCK_MONOTONIC, &t0); /* * do some work here */ for (i = 0; i < ARRAY_SIZE; i++ ) array[i*stride] *= 3; /*value = array[i*stride] * 2.0e6;*/ clock_gettime(CLOCK_MONOTONIC, &tf); if ( (tf.tv_nsec - t0.tv_nsec) < 0 ) { dt.tv_sec = tf.tv_sec - t0.tv_sec - 1; dt.tv_nsec = 1000000000 + tf.tv_nsec - t0.tv_nsec; } else { dt.tv_sec = tf.tv_sec - t0.tv_sec; dt.tv_nsec = tf.tv_nsec - t0.tv_nsec; } printf( "%f sec in %ld steps with %ld-byte stride\n", dt.tv_sec + dt.tv_nsec / 1e9, i, stride*sizeof(*array) ); return 0; }
960587.c
--- prf_common_circular.c.orig 2021-06-15 11:37:41.598090000 +0200 +++ prf_common_circular.c 2021-06-15 11:41:44.322610000 +0200 @@ -322,7 +322,7 @@ #if defined(__linux__) #include <malloc.h> malloc_stats(); -#elif defined(__FreeBSD__) +#elif defined(__FreeBSD__) && !defined(__DragonFly__) #include <stdlib.h> #include <malloc_np.h> malloc_stats_print(NULL, NULL, "g");
981349.c
/***************************************************************************//** * # License * * The licensor of this software is Silicon Laboratories Inc. Your use of this * software is governed by the terms of Silicon Labs Master Software License * Agreement (MSLA) available at * www.silabs.com/about-us/legal/master-software-license-agreement. This * software is Third Party Software licensed by Silicon Labs from a third party * and is governed by the sections of the MSLA applicable to Third Party * Software and the additional terms set forth below. * ******************************************************************************/ /* * Diffie-Hellman-Merkle key exchange (client side) * * Copyright (C) 2006-2015, 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. * * This file is part of mbed TLS (https://tls.mbed.org) */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdio.h> #include <stdlib.h> #define mbedtls_printf printf #define mbedtls_time_t time_t #define MBEDTLS_EXIT_SUCCESS EXIT_SUCCESS #define MBEDTLS_EXIT_FAILURE EXIT_FAILURE #endif /* MBEDTLS_PLATFORM_C */ #if defined(MBEDTLS_AES_C) && defined(MBEDTLS_DHM_C) && \ defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_NET_C) && \ defined(MBEDTLS_RSA_C) && defined(MBEDTLS_SHA256_C) && \ defined(MBEDTLS_FS_IO) && defined(MBEDTLS_CTR_DRBG_C) && \ defined(MBEDTLS_SHA1_C) #include "mbedtls/net_sockets.h" #include "mbedtls/aes.h" #include "mbedtls/dhm.h" #include "mbedtls/rsa.h" #include "mbedtls/sha1.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include <stdio.h> #include <string.h> #endif #define SERVER_NAME "localhost" #define SERVER_PORT "11999" #if !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_DHM_C) || \ !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_NET_C) || \ !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_SHA256_C) || \ !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_CTR_DRBG_C) || \ !defined(MBEDTLS_SHA1_C) int main( void ) { mbedtls_printf("MBEDTLS_AES_C and/or MBEDTLS_DHM_C and/or MBEDTLS_ENTROPY_C " "and/or MBEDTLS_NET_C and/or MBEDTLS_RSA_C and/or " "MBEDTLS_SHA256_C and/or MBEDTLS_FS_IO and/or " "MBEDTLS_CTR_DRBG_C not defined.\n"); return( 0 ); } #else int main( void ) { FILE *f; int ret = 1; int exit_code = MBEDTLS_EXIT_FAILURE; size_t n, buflen; mbedtls_net_context server_fd; unsigned char *p, *end; unsigned char buf[2048]; unsigned char hash[32]; const char *pers = "dh_client"; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_rsa_context rsa; mbedtls_dhm_context dhm; mbedtls_aes_context aes; mbedtls_net_init( &server_fd ); mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, MBEDTLS_MD_SHA256 ); mbedtls_dhm_init( &dhm ); mbedtls_aes_init( &aes ); mbedtls_ctr_drbg_init( &ctr_drbg ); /* * 1. Setup the RNG */ mbedtls_printf( "\n . Seeding the random number generator" ); fflush( stdout ); mbedtls_entropy_init( &entropy ); if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *) pers, strlen( pers ) ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret ); goto exit; } /* * 2. Read the server's public RSA key */ mbedtls_printf( "\n . Reading public key from rsa_pub.txt" ); fflush( stdout ); if( ( f = fopen( "rsa_pub.txt", "rb" ) ) == NULL ) { mbedtls_printf( " failed\n ! Could not open rsa_pub.txt\n" \ " ! Please run rsa_genkey first\n\n" ); goto exit; } mbedtls_rsa_init( &rsa, MBEDTLS_RSA_PKCS_V15, 0 ); if( ( ret = mbedtls_mpi_read_file( &rsa.N, 16, f ) ) != 0 || ( ret = mbedtls_mpi_read_file( &rsa.E, 16, f ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_mpi_read_file returned %d\n\n", ret ); fclose( f ); goto exit; } rsa.len = ( mbedtls_mpi_bitlen( &rsa.N ) + 7 ) >> 3; fclose( f ); /* * 3. Initiate the connection */ mbedtls_printf( "\n . Connecting to tcp/%s/%s", SERVER_NAME, SERVER_PORT ); fflush( stdout ); if( ( ret = mbedtls_net_connect( &server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_net_connect returned %d\n\n", ret ); goto exit; } /* * 4a. First get the buffer length */ mbedtls_printf( "\n . Receiving the server's DH parameters" ); fflush( stdout ); memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, 2 ) ) != 2 ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } n = buflen = ( buf[0] << 8 ) | buf[1]; if( buflen < 1 || buflen > sizeof( buf ) ) { mbedtls_printf( " failed\n ! Got an invalid buffer length\n\n" ); goto exit; } /* * 4b. Get the DHM parameters: P, G and Ys = G^Xs mod P */ memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, n ) ) != (int) n ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } p = buf, end = buf + buflen; if( ( ret = mbedtls_dhm_read_params( &dhm, &p, end ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_read_params returned %d\n\n", ret ); goto exit; } if( dhm.len < 64 || dhm.len > 512 ) { mbedtls_printf( " failed\n ! Invalid DHM modulus size\n\n" ); goto exit; } /* * 5. Check that the server's RSA signature matches * the SHA-256 hash of (P,G,Ys) */ mbedtls_printf( "\n . Verifying the server's RSA signature" ); fflush( stdout ); p += 2; if( ( n = (size_t) ( end - p ) ) != rsa.len ) { mbedtls_printf( " failed\n ! Invalid RSA signature size\n\n" ); goto exit; } if( ( ret = mbedtls_sha1_ret( buf, (int)( p - 2 - buf ), hash ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_sha1_ret returned %d\n\n", ret ); goto exit; } if( ( ret = mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA256, 0, hash, p ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_rsa_pkcs1_verify returned %d\n\n", ret ); goto exit; } /* * 6. Send our public value: Yc = G ^ Xc mod P */ mbedtls_printf( "\n . Sending own public value to server" ); fflush( stdout ); n = dhm.len; if( ( ret = mbedtls_dhm_make_public( &dhm, (int) dhm.len, buf, n, mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_make_public returned %d\n\n", ret ); goto exit; } if( ( ret = mbedtls_net_send( &server_fd, buf, n ) ) != (int) n ) { mbedtls_printf( " failed\n ! mbedtls_net_send returned %d\n\n", ret ); goto exit; } /* * 7. Derive the shared secret: K = Ys ^ Xc mod P */ mbedtls_printf( "\n . Shared secret: " ); fflush( stdout ); if( ( ret = mbedtls_dhm_calc_secret( &dhm, buf, sizeof( buf ), &n, mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) { mbedtls_printf( " failed\n ! mbedtls_dhm_calc_secret returned %d\n\n", ret ); goto exit; } for( n = 0; n < 16; n++ ) mbedtls_printf( "%02x", buf[n] ); /* * 8. Setup the AES-256 decryption key * * This is an overly simplified example; best practice is * to hash the shared secret with a random value to derive * the keying material for the encryption/decryption keys, * IVs and MACs. */ mbedtls_printf( "...\n . Receiving and decrypting the ciphertext" ); fflush( stdout ); mbedtls_aes_setkey_dec( &aes, buf, 256 ); memset( buf, 0, sizeof( buf ) ); if( ( ret = mbedtls_net_recv( &server_fd, buf, 16 ) ) != 16 ) { mbedtls_printf( " failed\n ! mbedtls_net_recv returned %d\n\n", ret ); goto exit; } mbedtls_aes_crypt_ecb( &aes, MBEDTLS_AES_DECRYPT, buf, buf ); buf[16] = '\0'; mbedtls_printf( "\n . Plaintext is \"%s\"\n\n", (char *) buf ); exit_code = MBEDTLS_EXIT_SUCCESS; exit: mbedtls_net_free( &server_fd ); mbedtls_aes_free( &aes ); mbedtls_rsa_free( &rsa ); mbedtls_dhm_free( &dhm ); mbedtls_ctr_drbg_free( &ctr_drbg ); mbedtls_entropy_free( &entropy ); #if defined(_WIN32) mbedtls_printf( " + Press Enter to exit this program.\n" ); fflush( stdout ); getchar(); #endif return( exit_code ); } #endif /* MBEDTLS_AES_C && MBEDTLS_DHM_C && MBEDTLS_ENTROPY_C && MBEDTLS_NET_C && MBEDTLS_RSA_C && MBEDTLS_SHA256_C && MBEDTLS_FS_IO && MBEDTLS_CTR_DRBG_C */
414731.c
// Copyright (c) 2016, Intel Corporation. #ifdef BUILD_MODULE_BLE #ifndef QEMU_BUILD // Zephyr includes #include <zephyr.h> #include <string.h> #include <stdlib.h> #include <bluetooth/bluetooth.h> #include <bluetooth/hci.h> #include <bluetooth/conn.h> #include <bluetooth/uuid.h> #include <bluetooth/gatt.h> // ZJS includes #include "zjs_ble.h" #include "zjs_buffer.h" #include "zjs_callbacks.h" #include "zjs_event.h" #include "zjs_util.h" #define ZJS_BLE_UUID_LEN 36 #define ZJS_BLE_RESULT_SUCCESS 0x00 #define ZJS_BLE_RESULT_INVALID_OFFSET BT_ATT_ERR_INVALID_OFFSET #define ZJS_BLE_RESULT_ATTR_NOT_LONG BT_ATT_ERR_ATTRIBUTE_NOT_LONG #define ZJS_BLE_RESULT_INVALID_ATTRIBUTE_LENGTH BT_ATT_ERR_INVALID_ATTRIBUTE_LEN #define ZJS_BLE_RESULT_UNLIKELY_ERROR BT_ATT_ERR_UNLIKELY #define ZJS_BLE_TIMEOUT_TICKS 500 static struct k_sem ble_sem; typedef struct ble_handle { zjs_callback_id id; jerry_value_t js_callback; const void *buffer; uint16_t buffer_size; uint16_t offset; uint32_t error_code; } ble_handle_t; typedef struct ble_notify_handle { zjs_callback_id id; jerry_value_t js_callback; } ble_notify_handle_t; typedef struct ble_event_handle { zjs_callback_id id; jerry_value_t arg; } ble_event_handle_t; typedef struct zjs_ble_characteristic { int flags; jerry_value_t chrc_obj; struct bt_uuid *uuid; struct bt_gatt_attr *chrc_attr; jerry_value_t cud_value; ble_handle_t read_cb; ble_handle_t write_cb; ble_notify_handle_t subscribe_cb; ble_notify_handle_t unsubscribe_cb; ble_notify_handle_t notify_cb; struct zjs_ble_characteristic *next; } ble_characteristic_t; typedef struct zjs_ble_service { jerry_value_t service_obj; struct bt_uuid *uuid; ble_characteristic_t *characteristics; struct zjs_ble_service *next; } ble_service_t; typedef struct zjs_ble_connection { jerry_value_t ble_obj; struct bt_conn *default_conn; struct bt_gatt_ccc_cfg blvl_ccc_cfg[CONFIG_BLUETOOTH_MAX_PAIRED]; uint8_t simulate_blvl; ble_service_t *services; ble_event_handle_t ready_cb; ble_event_handle_t connected_cb; ble_event_handle_t disconnected_cb; } ble_connection_t; // global connection object static struct zjs_ble_connection *ble_conn = &(struct zjs_ble_connection) { .default_conn = NULL, .blvl_ccc_cfg = {}, .simulate_blvl = 0, .services = NULL, }; static struct bt_uuid *gatt_primary_service_uuid = BT_UUID_DECLARE_16(BT_UUID_GATT_PRIMARY_VAL); static struct bt_uuid *gatt_characteristic_uuid = BT_UUID_DECLARE_16(BT_UUID_GATT_CHRC_VAL); static struct bt_uuid *gatt_cud_uuid = BT_UUID_DECLARE_16(BT_UUID_GATT_CUD_VAL); static struct bt_uuid *gatt_ccc_uuid = BT_UUID_DECLARE_16(BT_UUID_GATT_CCC_VAL); struct bt_uuid* zjs_ble_new_uuid_16(uint16_t value) { struct bt_uuid_16 *uuid = zjs_malloc(sizeof(struct bt_uuid_16)); if (!uuid) { ERR_PRINT("zjs_ble_new_uuid_16: out of memory allocating struct bt_uuid_16\n"); return NULL; } memset(uuid, 0, sizeof(struct bt_uuid_16)); uuid->uuid.type = BT_UUID_TYPE_16; uuid->val = value; return (struct bt_uuid *) uuid; } static void zjs_ble_free_characteristics(ble_characteristic_t *chrc) { ble_characteristic_t *tmp; while (chrc != NULL) { tmp = chrc; chrc = chrc->next; jerry_release_value(tmp->chrc_obj); if (tmp->uuid) zjs_free(tmp->uuid); if (tmp->read_cb.id != -1) { zjs_remove_callback(tmp->read_cb.id); jerry_release_value(tmp->read_cb.js_callback); } if (tmp->write_cb.id != -1) { zjs_remove_callback(tmp->write_cb.id); jerry_release_value(tmp->write_cb.js_callback); } if (tmp->subscribe_cb.id != -1) { zjs_remove_callback(tmp->subscribe_cb.id); jerry_release_value(tmp->subscribe_cb.js_callback); } if (tmp->unsubscribe_cb.id != -1) { zjs_remove_callback(tmp->unsubscribe_cb.id); jerry_release_value(tmp->unsubscribe_cb.js_callback); } if (tmp->notify_cb.id != -1) { zjs_remove_callback(tmp->notify_cb.id); jerry_release_value(tmp->notify_cb.js_callback); } zjs_free(tmp); } } static void zjs_ble_free_services(ble_service_t *service) { ble_service_t *tmp; while (service != NULL) { tmp = service; service = service->next; jerry_release_value(tmp->service_obj); if (tmp->uuid) zjs_free(tmp->uuid); if (tmp->characteristics) zjs_ble_free_characteristics(tmp->characteristics); zjs_free(tmp); } } static jerry_value_t zjs_ble_read_callback_function(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc != 2 || !jerry_value_is_number(argv[0]) || !jerry_value_is_object(argv[1])) { k_sem_give(&ble_sem); return zjs_error("zjs_ble_read_attr_call_function_return: invalid arguments"); } uintptr_t ptr; if (jerry_get_object_native_handle(function_obj, &ptr)) { // store the return value in the read_cb struct struct zjs_ble_characteristic *chrc = (struct zjs_ble_characteristic*)ptr; chrc->read_cb.error_code = (uint32_t)jerry_get_number_value(argv[0]); zjs_buffer_t *buf = zjs_buffer_find(argv[1]); if (buf) { chrc->read_cb.buffer = buf->buffer; chrc->read_cb.buffer_size = buf->bufsize; } else { ERR_PRINT("zjs_ble_read_attr_call_function_return: buffer not found\n"); } } // unblock fiber k_sem_give(&ble_sem); return ZJS_UNDEFINED; } static void zjs_ble_read_c_callback(void *handle, void* argv) { ble_characteristic_t *chrc = (ble_characteristic_t *)handle; ble_handle_t *cb = &chrc->read_cb; jerry_value_t rval; jerry_value_t args[2]; jerry_value_t func_obj; args[0] = jerry_create_number(cb->offset); func_obj = jerry_create_external_function(zjs_ble_read_callback_function); jerry_set_object_native_handle(func_obj, (uintptr_t)handle, NULL); args[1] = func_obj; rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 2); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_read_c_callback: failed to call onReadRequest function\n"); } jerry_release_value(args[0]); jerry_release_value(args[1]); jerry_release_value(rval); } static ssize_t zjs_ble_read_attr_callback(struct bt_conn *conn, const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) { if (offset > len) { return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); } ble_characteristic_t *chrc = attr->user_data; if (!chrc) { ERR_PRINT("zjs_ble_read_attr_callback: characteristic not found\n"); return BT_GATT_ERR(BT_ATT_ERR_INVALID_HANDLE); } if (chrc->read_cb.id != -1) { // This is from the FIBER context, so we queue up the callback // to invoke js from task context chrc->read_cb.offset = offset; chrc->read_cb.buffer = NULL; chrc->read_cb.buffer_size = 0; chrc->read_cb.error_code = BT_ATT_ERR_NOT_SUPPORTED; zjs_signal_callback(chrc->read_cb.id, NULL, 0); // block until result is ready if (k_sem_take(&ble_sem, ZJS_BLE_TIMEOUT_TICKS)) { ERR_PRINT("zjs_ble_read_attr_callback: JS callback timed out\n"); return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY); } if (chrc->read_cb.error_code == ZJS_BLE_RESULT_SUCCESS) { if (chrc->read_cb.buffer && chrc->read_cb.buffer_size > 0) { // buffer should be pointing to the Buffer object that JS created // copy the bytes into the return buffer ptr memcpy(buf, chrc->read_cb.buffer, chrc->read_cb.buffer_size); return chrc->read_cb.buffer_size; } ERR_PRINT("zjs_ble_read_attr_callback: buffer is empty\n"); return BT_GATT_ERR(BT_ATT_ERR_NOT_SUPPORTED); } else { ERR_PRINT("zjs_ble_read_attr_callback: on read attr error %lu\n", chrc->read_cb.error_code); return BT_GATT_ERR(chrc->read_cb.error_code); } } DBG_PRINT("zjs_ble_read_attr_callback: js callback not available\n"); return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY); } static jerry_value_t zjs_ble_write_callback_function(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc != 1 || !jerry_value_is_number(argv[0])) { k_sem_give(&ble_sem); return zjs_error("zjs_ble_write_attr_call_function_return: invalid arguments"); } uintptr_t ptr; if (jerry_get_object_native_handle(function_obj, &ptr)) { // store the return value in the write_cb struct struct zjs_ble_characteristic *chrc = (struct zjs_ble_characteristic*)ptr; chrc->write_cb.error_code = (uint32_t)jerry_get_number_value(argv[0]); } // unblock fiber k_sem_give(&ble_sem); return ZJS_UNDEFINED; } static void zjs_ble_write_c_callback(void *handle, void* argv) { ble_characteristic_t *chrc = (ble_characteristic_t *)handle; ble_handle_t *cb = &chrc->write_cb; jerry_value_t rval; jerry_value_t args[4]; jerry_value_t func_obj; args[0] = jerry_create_null(); if (cb->buffer && cb->buffer_size > 0) { jerry_value_t buf_obj = zjs_buffer_create(cb->buffer_size); if (buf_obj) { zjs_buffer_t *buf = zjs_buffer_find(buf_obj); if (buf && buf->buffer && buf->bufsize == cb->buffer_size) { memcpy(buf->buffer, cb->buffer, cb->buffer_size); } jerry_release_value(args[0]); args[0] = buf_obj; } } args[1] = jerry_create_number(cb->offset); // TODO: support withoutResponse flag args[2] = jerry_create_boolean(false); func_obj = jerry_create_external_function(zjs_ble_write_callback_function); jerry_set_object_native_handle(func_obj, (uintptr_t)handle, NULL); args[3] = func_obj; rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 4); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_write_c_callback: failed to call onWriteRequest function\n"); } jerry_release_value(args[0]); jerry_release_value(args[1]); jerry_release_value(args[2]); jerry_release_value(args[3]); jerry_release_value(rval); } static ssize_t zjs_ble_write_attr_callback(struct bt_conn *conn, const struct bt_gatt_attr *attr, const void *buf, uint16_t len, uint16_t offset, uint8_t flags) { ble_characteristic_t *chrc = attr->user_data; if (!chrc) { ERR_PRINT("zjs_ble_write_attr_callback: characteristic not found\n"); return BT_GATT_ERR(BT_ATT_ERR_INVALID_HANDLE); } if (chrc->write_cb.id != -1) { // This is from the FIBER context, so we queue up the callback // to invoke js from task context chrc->write_cb.offset = offset; chrc->write_cb.buffer = (len > 0) ? buf : NULL; chrc->write_cb.buffer_size = len; chrc->write_cb.error_code = BT_ATT_ERR_NOT_SUPPORTED; zjs_signal_callback(chrc->write_cb.id, NULL, 0); // block until result is ready if (k_sem_take(&ble_sem, ZJS_BLE_TIMEOUT_TICKS)) { ERR_PRINT("zjs_ble_write_attr_callback: JS callback timed out\n"); return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY); } if (chrc->write_cb.error_code == ZJS_BLE_RESULT_SUCCESS) { return len; } else { return BT_GATT_ERR(chrc->write_cb.error_code); } } DBG_PRINT("zjs_ble_write_attr_callback: js callback not available\n"); return BT_GATT_ERR(BT_ATT_ERR_UNLIKELY); } static jerry_value_t zjs_ble_update_value_callback_function(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc != 1 || !jerry_value_is_object(argv[0])) { return zjs_error("zjs_ble_update_value_call_function: invalid arguments"); } // expects a Buffer object zjs_buffer_t *buf = zjs_buffer_find(argv[0]); if (buf) { if (ble_conn->default_conn) { uintptr_t ptr; if (jerry_get_object_native_handle(this, &ptr)) { ble_characteristic_t *chrc = (ble_characteristic_t *)ptr; if (chrc->chrc_attr) { bt_gatt_notify(ble_conn->default_conn, chrc->chrc_attr, buf->buffer, buf->bufsize); } } } return ZJS_UNDEFINED; } return zjs_error("updateValueCallback: buffer not found or empty"); } static void zjs_ble_subscribe_c_callback(void *handle, void* argv) { ble_characteristic_t *chrc = (ble_characteristic_t *)handle; ble_notify_handle_t *cb = &chrc->subscribe_cb; jerry_value_t rval; jerry_value_t args[2]; args[0] = jerry_create_number(20); // max payload size args[1] = jerry_create_external_function(zjs_ble_update_value_callback_function); rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, args, 2); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_subscribe_c_callback: failed to call onSubscribe function\n"); } jerry_release_value(args[0]); jerry_release_value(args[1]); jerry_release_value(rval); } static void zjs_ble_unsubscribe_c_callback(void *handle, void* argv) { ble_characteristic_t *chrc = (ble_characteristic_t *)handle; ble_notify_handle_t *cb = &chrc->unsubscribe_cb; jerry_value_t rval; rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, NULL, 0); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_unsubscribe_c_callback: failed to call onUnsubscribe function\n"); } jerry_release_value(rval); } static void zjs_ble_notify_c_callback(void *handle, void* argv) { ble_characteristic_t *chrc = (ble_characteristic_t *)handle; ble_notify_handle_t *cb = &chrc->notify_cb; jerry_value_t rval; rval = jerry_call_function(cb->js_callback, chrc->chrc_obj, NULL, 0); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_notify_c_callback: failed to call onNotify function\n"); } jerry_release_value(rval); } // Port this to javascript static void zjs_ble_blvl_ccc_cfg_changed(const struct bt_gatt_attr *attr, uint16_t value) { ble_conn->simulate_blvl = (value == BT_GATT_CCC_NOTIFY) ? 1 : 0; } static void zjs_ble_connected_c_callback(void *handle, void* argv) { // FIXME: get real bluetooth address jerry_value_t arg = jerry_create_string((jerry_char_t *)"AB:CD:DF:AB:CD:EF"); zjs_trigger_event(ble_conn->ble_obj, "accept", &arg, 1, NULL, NULL); DBG_PRINT("BLE event: accept\n"); } static void zjs_ble_connected(struct bt_conn *conn, uint8_t err) { if (err) { DBG_PRINT("zjs_ble_connected: Connection failed (err %u)\n", err); } else { DBG_PRINT("========== connected ==========\n"); ble_conn->default_conn = bt_conn_ref(conn); zjs_signal_callback(ble_conn->connected_cb.id, NULL, 0); } } static void zjs_ble_disconnected_c_callback(void *handle, void* argv) { // FIXME: get real bluetooth address jerry_value_t arg = jerry_create_string((jerry_char_t *)"AB:CD:DF:AB:CD:EF"); zjs_trigger_event(ble_conn->ble_obj, "disconnect", &arg, 1, NULL, NULL); DBG_PRINT("BLE event: disconnect\n"); } static void zjs_ble_disconnected(struct bt_conn *conn, uint8_t reason) { DBG_PRINT("========== Disconnected (reason %u) ==========\n", reason); if (ble_conn->default_conn) { bt_conn_unref(ble_conn->default_conn); ble_conn->default_conn = NULL; zjs_signal_callback(ble_conn->disconnected_cb.id, NULL, 0); } } static struct bt_conn_cb zjs_ble_conn_callbacks = { .connected = zjs_ble_connected, .disconnected = zjs_ble_disconnected, }; static void zjs_ble_auth_cancel(struct bt_conn *conn) { char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); DBG_PRINT("Pairing cancelled: %s\n", addr); } static struct bt_conn_auth_cb zjs_ble_auth_cb_display = { .cancel = zjs_ble_auth_cancel, }; static void zjs_ble_ready_c_callback(void *handle, void* argv) { jerry_value_t arg = jerry_create_string((jerry_char_t *)"poweredOn"); zjs_trigger_event(ble_conn->ble_obj, "stateChange", &arg, 1, NULL, NULL); DBG_PRINT("BLE event: stateChange - poweredOn"); } static void zjs_ble_bt_ready(int err) { DBG_PRINT("bt_ready() is called [err %d]\n", err); zjs_signal_callback(ble_conn->ready_cb.id, NULL, 0); } void zjs_ble_enable() { DBG_PRINT("Enabling the bluetooth, wait for bt_ready()...\n"); bt_enable(zjs_ble_bt_ready); // setup connection callbacks bt_conn_cb_register(&zjs_ble_conn_callbacks); bt_conn_auth_cb_register(&zjs_ble_auth_cb_display); } static jerry_value_t zjs_ble_disconnect(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (ble_conn->default_conn) { int error = bt_conn_disconnect(ble_conn->default_conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); if (error) { return zjs_error("zjs_ble_disconnect: disconnect failed"); } } return ZJS_UNDEFINED; } const int ZJS_SUCCESS = 0; const int ZJS_URL_TOO_LONG = 1; const int ZJS_ALLOC_FAILED = 2; const int ZJS_URL_SCHEME_ERROR = 3; static int zjs_encode_url_frame(jerry_value_t url, uint8_t **frame, int *size) { // requires: url is a URL string, frame points to a uint8_t *, url contains // only UTF-8 characters and hence no nil values // effects: allocates a new buffer that will fit an Eddystone URL frame // with a compressed version of the given url; returns it in // *frame and returns the size of the frame in bytes in *size, // and frame is then owned by the caller, to be freed later with // zjs_free // returns: 0 for success, 1 for URL too long, 2 for out of memory, 3 for // invalid url scheme/syntax (only http:// or https:// allowed) jerry_size_t sz = jerry_get_string_size(url); char buf[sz + 1]; int len = jerry_string_to_char_buffer(url, (jerry_char_t *)buf, sz); buf[len] = '\0'; // make sure it starts with http int offset = 0; if (strncmp(buf, "http", 4)) return ZJS_URL_SCHEME_ERROR; offset += 4; int scheme = 0; if (buf[offset] == 's') { scheme++; offset++; } // make sure scheme http/https is followed by :// if (strncmp(buf + offset, "://", 3)) return ZJS_URL_SCHEME_ERROR; offset += 3; if (strncmp(buf + offset, "www.", 4)) { scheme += 2; } else { offset += 4; } // FIXME: skipping the compression of .com, .com/, .org, etc for now len -= offset; if (len > 17) // max URL length specified by Eddystone spec return ZJS_URL_TOO_LONG; uint8_t *ptr = zjs_malloc(len + 5); if (!ptr) return ZJS_ALLOC_FAILED; ptr[0] = 0xaa; // Eddystone UUID ptr[1] = 0xfe; // Eddystone UUID ptr[2] = 0x10; // Eddystone-URL frame type ptr[3] = 0x00; // calibrated Tx power at 0m ptr[4] = scheme; // encoded URL scheme prefix strncpy(ptr + 5, buf + offset, len); *size = len + 5; *frame = ptr; return ZJS_SUCCESS; } static jerry_value_t zjs_ble_start_advertising(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { // arg 0 should be the device name to advertise, e.g. "Arduino101" // arg 1 should be an array of UUIDs (short, 4 hex chars) // arg 2 should be a short URL (typically registered with Google, I think) char name[80]; if (argc < 2 || !jerry_value_is_string(argv[0]) || !jerry_value_is_object(argv[1]) || (argc >= 3 && !jerry_value_is_string(argv[2]))) { return zjs_error("zjs_ble_adv_start: invalid arguments"); } jerry_value_t array = argv[1]; if (!jerry_value_is_array(array)) { return zjs_error("zjs_ble_adv_start: expected array"); } jerry_size_t sz = jerry_get_string_size(argv[0]); int len_name = jerry_string_to_char_buffer(argv[0], (jerry_char_t *) name, sz); name[len_name] = '\0'; struct bt_data sd[] = { BT_DATA(BT_DATA_NAME_COMPLETE, name, len_name), }; /* * Set Advertisement data. Based on the Eddystone specification: * https://github.com/google/eddystone/blob/master/protocol-specification.md * https://github.com/google/eddystone/tree/master/eddystone-url */ uint8_t *url_frame = NULL; int frame_size; if (argc >= 3) { if (zjs_encode_url_frame(argv[2], &url_frame, &frame_size)) { DBG_PRINT("zjs_ble_start_advertising: error encoding url frame, won't be advertised\n"); // TODO: Make use of error values and turn them into exceptions } } uint32_t arraylen = jerry_get_array_length(array); int records = arraylen; if (url_frame) records += 2; if (records == 0) { return zjs_error("zjs_ble_adv_start: nothing to advertise"); } const uint8_t url_adv[] = { 0xaa, 0xfe }; struct bt_data ad[records]; int index = 0; if (url_frame) { ad[0].type = BT_DATA_UUID16_ALL; ad[0].data_len = 2; ad[0].data = url_adv; ad[1].type = BT_DATA_SVC_DATA16; ad[1].data_len = frame_size; ad[1].data = url_frame; index = 2; } for (int i=0; i<arraylen; i++) { jerry_value_t uuid; uuid = jerry_get_property_by_index(array, i); if (!jerry_value_is_string(uuid)) { return zjs_error("zjs_ble_adv_start: invalid uuid argument type"); } jerry_size_t size = jerry_get_string_size(uuid); if (size != 4) { return zjs_error("zjs_ble_adv_start: unexpected uuid string length"); } char ubuf[4]; uint8_t bytes[2]; jerry_string_to_char_buffer(uuid, (jerry_char_t *)ubuf, 4); if (!zjs_hex_to_byte(ubuf + 2, &bytes[0]) || !zjs_hex_to_byte(ubuf, &bytes[1])) { return zjs_error("zjs_ble_adv_start: invalid character in uuid string"); } ad[index].type = BT_DATA_UUID16_ALL; ad[index].data_len = 2; ad[index].data = bytes; index++; } int err = bt_le_adv_start(BT_LE_ADV_CONN, ad, ARRAY_SIZE(ad), sd, ARRAY_SIZE(sd)); jerry_value_t error = err ? zjs_error("advertising failed") : jerry_create_null(); zjs_trigger_event(ble_conn->ble_obj, "advertisingStart", &error, 1, NULL, NULL); DBG_PRINT("BLE event: adveristingStart\n"); zjs_free(url_frame); return ZJS_UNDEFINED; } static jerry_value_t zjs_ble_stop_advertising(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { DBG_PRINT("zjs_ble_stop_advertising: stopAdvertising has been called\n"); return ZJS_UNDEFINED; } static bool zjs_ble_parse_characteristic(ble_characteristic_t *chrc) { char uuid[ZJS_BLE_UUID_LEN]; if (!chrc || !chrc->chrc_obj) return false; jerry_value_t chrc_obj = chrc->chrc_obj; if (!zjs_obj_get_string(chrc_obj, "uuid", uuid, ZJS_BLE_UUID_LEN)) { ERR_PRINT("zjs_ble_parse_characteristic: characteristic uuid doesn't exist\n"); return false; } chrc->uuid = zjs_ble_new_uuid_16(strtoul(uuid, NULL, 16)); jerry_value_t v_array = zjs_get_property(chrc_obj, "properties"); if (!jerry_value_is_array(v_array)) { ERR_PRINT("zjs_ble_parse_characteristic: properties is empty or not array\n"); return false; } for (int i=0; i<jerry_get_array_length(v_array); i++) { jerry_value_t v_property = jerry_get_property_by_index(v_array, i); if (!jerry_value_is_string(v_property)) { ERR_PRINT("zjs_ble_parse_characteristic: property is not string\n"); return false; } char name[20]; jerry_size_t sz; sz = jerry_get_string_size(v_property); int len = jerry_string_to_char_buffer(v_property, (jerry_char_t *) name, sz); name[len] = '\0'; if (!strcmp(name, "read")) { chrc->flags |= BT_GATT_CHRC_READ; } else if (!strcmp(name, "write")) { chrc->flags |= BT_GATT_CHRC_WRITE; } else if (!strcmp(name, "notify")) { chrc->flags |= BT_GATT_CHRC_NOTIFY; } } jerry_release_value(v_array); v_array = zjs_get_property(chrc_obj, "descriptors"); if (!jerry_value_is_undefined(v_array) && !jerry_value_is_null(v_array) && !jerry_value_is_array(v_array)) { ERR_PRINT("zjs_ble_parse_characteristic: descriptors is not array\n"); return false; } for (int i=0; i<jerry_get_array_length(v_array); i++) { jerry_value_t v_desc = jerry_get_property_by_index(v_array, i); if (!jerry_value_is_object(v_desc)) { ERR_PRINT("zjs_ble_parse_characteristic: not valid descriptor object\n"); return false; } char desc_uuid[ZJS_BLE_UUID_LEN]; if (!zjs_obj_get_string(v_desc, "uuid", desc_uuid, ZJS_BLE_UUID_LEN)) { ERR_PRINT("zjs_ble_parse_service: descriptor uuid doesn't exist\n"); return false; } if (strtoul(desc_uuid, NULL, 16) == BT_UUID_GATT_CUD_VAL) { // Support CUD only, ignore all other type of descriptors jerry_value_t v_value = zjs_get_property(v_desc, "value"); if (jerry_value_is_string(v_value)) { chrc->cud_value = jerry_acquire_value(v_value); } } } jerry_release_value(v_array); jerry_value_t v_func; v_func = zjs_get_property(chrc_obj, "onReadRequest"); if (jerry_value_is_function(v_func)) { chrc->read_cb.js_callback = jerry_acquire_value(v_func); chrc->read_cb.id = zjs_add_c_callback(chrc, zjs_ble_read_c_callback); } else { chrc->read_cb.id = -1; } v_func = zjs_get_property(chrc_obj, "onWriteRequest"); if (jerry_value_is_function(v_func)) { chrc->write_cb.js_callback = jerry_acquire_value(v_func); chrc->write_cb.id = zjs_add_c_callback(chrc, zjs_ble_write_c_callback); } else { chrc->write_cb.id = -1; } v_func = zjs_get_property(chrc_obj, "onSubscribe"); if (jerry_value_is_function(v_func)) { chrc->subscribe_cb.js_callback = jerry_acquire_value(v_func); chrc->subscribe_cb.id = zjs_add_c_callback(chrc, zjs_ble_subscribe_c_callback); // TODO: we need to monitor onSubscribe events from BLE driver eventually zjs_signal_callback(chrc->subscribe_cb.id, NULL, 0); } else { chrc->subscribe_cb.id = -1; } v_func = zjs_get_property(chrc_obj, "onUnsubscribe"); if (jerry_value_is_function(v_func)) { chrc->unsubscribe_cb.js_callback = jerry_acquire_value(v_func); chrc->unsubscribe_cb.id = zjs_add_c_callback(chrc, zjs_ble_unsubscribe_c_callback); } else { chrc->unsubscribe_cb.id = -1; } v_func = zjs_get_property(chrc_obj, "onNotify"); if (jerry_value_is_function(v_func)) { chrc->notify_cb.js_callback = jerry_acquire_value(v_func); chrc->notify_cb.id = zjs_add_c_callback(chrc, zjs_ble_notify_c_callback); } else { chrc->notify_cb.id = -1; } return true; } static bool zjs_ble_parse_service(ble_service_t *service) { char uuid[ZJS_BLE_UUID_LEN]; if (!service || !service->service_obj) return false; jerry_value_t service_obj = service->service_obj; if (!zjs_obj_get_string(service_obj, "uuid", uuid, ZJS_BLE_UUID_LEN)) { ERR_PRINT("zjs_ble_parse_service: service uuid doesn't exist\n"); return false; } service->uuid = zjs_ble_new_uuid_16(strtoul(uuid, NULL, 16)); jerry_value_t v_array = zjs_get_property(service_obj, "characteristics"); if (!jerry_value_is_array(v_array)) { ERR_PRINT("zjs_ble_parse_service: characteristics is empty or not array\n"); return false; } ble_characteristic_t *previous = NULL; for (int i=0; i<jerry_get_array_length(v_array); i++) { jerry_value_t v_chrc = jerry_get_property_by_index(v_array, i); if (!jerry_value_is_object(v_chrc)) { ERR_PRINT("zjs_ble_parse_characteristic: characteristic is not object\n"); return false; } ble_characteristic_t *chrc = zjs_malloc(sizeof(ble_characteristic_t)); if (!chrc) { ERR_PRINT("zjs_ble_parse_service: out of memory allocating ble_characteristic_t\n"); return false; } memset(chrc, 0, sizeof(ble_characteristic_t)); chrc->read_cb.id = chrc->write_cb.id = chrc->subscribe_cb.id = chrc->unsubscribe_cb.id = chrc->notify_cb.id = -1; chrc->chrc_obj = jerry_acquire_value(v_chrc); jerry_set_object_native_handle(chrc->chrc_obj, (uintptr_t)chrc, NULL); if (!zjs_ble_parse_characteristic(chrc)) { DBG_PRINT("failed to parse temp characteristic\n"); return false; } // append to the list if (!service->characteristics) { service->characteristics = chrc; previous = chrc; } else { previous->next = chrc; } } return true; } static bool zjs_ble_register_service(ble_service_t *service) { if (!service) { ERR_PRINT("zjs_ble_register_service: invalid ble_service\n"); return false; } // calculate the number of GATT attributes to allocate int entry_index = 0; int num_of_entries = 1; // 1 attribute for service uuid ble_characteristic_t *ch = service->characteristics; while (ch) { num_of_entries += 2; // 2 attributes for uuid and descriptor if (ch->cud_value) { num_of_entries++; // 1 attribute for cud } if ((ch->flags & BT_GATT_CHRC_NOTIFY) == BT_GATT_CHRC_NOTIFY) { num_of_entries++; // 1 attribute for ccc } ch = ch->next; } struct bt_gatt_attr *bt_attrs = zjs_malloc(sizeof(struct bt_gatt_attr) * num_of_entries); if (!bt_attrs) { ERR_PRINT("zjs_ble_register_service: out of memory allocating struct bt_gatt_attr\n"); return false; } // populate the array memset(bt_attrs, 0, sizeof(struct bt_gatt_attr) * num_of_entries); // GATT Primary Service bt_attrs[entry_index].uuid = gatt_primary_service_uuid; bt_attrs[entry_index].perm = BT_GATT_PERM_READ; bt_attrs[entry_index].read = bt_gatt_attr_read_service; bt_attrs[entry_index].user_data = service->uuid; entry_index++; ch = service->characteristics; while (ch) { // GATT Characteristic struct bt_gatt_chrc *chrc_user_data = zjs_malloc(sizeof(struct bt_gatt_chrc)); if (!chrc_user_data) { ERR_PRINT("zjs_ble_register_service: out of memory allocating struct bt_gatt_chrc\n"); return false; } memset(chrc_user_data, 0, sizeof(struct bt_gatt_chrc)); chrc_user_data->uuid = ch->uuid; chrc_user_data->properties = ch->flags; bt_attrs[entry_index].uuid = gatt_characteristic_uuid; bt_attrs[entry_index].perm = BT_GATT_PERM_READ; bt_attrs[entry_index].read = bt_gatt_attr_read_chrc; bt_attrs[entry_index].user_data = chrc_user_data; // TODO: handle multiple descriptors // DESCRIPTOR entry_index++; bt_attrs[entry_index].uuid = ch->uuid; if (ch->read_cb.id != -1) { bt_attrs[entry_index].perm |= BT_GATT_PERM_READ; } if (ch->write_cb.id != -1) { bt_attrs[entry_index].perm |= BT_GATT_PERM_WRITE; } bt_attrs[entry_index].read = zjs_ble_read_attr_callback; bt_attrs[entry_index].write = zjs_ble_write_attr_callback; bt_attrs[entry_index].user_data = ch; // hold references to the GATT attr for sending notification ch->chrc_attr = &bt_attrs[entry_index]; entry_index++; // CUD if (ch->cud_value) { jerry_size_t sz = jerry_get_string_size(ch->cud_value); char *cud_buffer = zjs_malloc(sz+1); if (!cud_buffer) { ERR_PRINT("zjs_ble_register_service: out of memory allocating cud buffer\n"); return false; } memset(cud_buffer, 0, sz+1); jerry_string_to_char_buffer(ch->cud_value, (jerry_char_t *)cud_buffer, sz); bt_attrs[entry_index].uuid = gatt_cud_uuid; bt_attrs[entry_index].perm = BT_GATT_PERM_READ; bt_attrs[entry_index].read = bt_gatt_attr_read_cud; bt_attrs[entry_index].user_data = cud_buffer; entry_index++; } // CCC if ((ch->flags & BT_GATT_CHRC_NOTIFY) == BT_GATT_CHRC_NOTIFY) { // add CCC only if notify flag is set struct _bt_gatt_ccc *ccc_user_data = zjs_malloc(sizeof(struct _bt_gatt_ccc)); if (!ccc_user_data) { ERR_PRINT("zjs_ble_register_service: out of memory allocating struct bt_gatt_ccc\n"); return false; } memset(ccc_user_data, 0, sizeof(struct _bt_gatt_ccc)); ccc_user_data->cfg = ble_conn->blvl_ccc_cfg; ccc_user_data->cfg_len = ARRAY_SIZE(ble_conn->blvl_ccc_cfg); ccc_user_data->cfg_changed = zjs_ble_blvl_ccc_cfg_changed; bt_attrs[entry_index].uuid = gatt_ccc_uuid; bt_attrs[entry_index].perm = BT_GATT_PERM_READ | BT_GATT_PERM_WRITE; bt_attrs[entry_index].read = bt_gatt_attr_read_ccc; bt_attrs[entry_index].write = bt_gatt_attr_write_ccc; bt_attrs[entry_index].user_data = ccc_user_data; entry_index++; } ch = ch->next; } if (entry_index != num_of_entries) { ERR_PRINT("zjs_ble_register_service: number of entries didn't match\n"); return false; } DBG_PRINT("Registered service: %d entries\n", entry_index); bt_gatt_register(bt_attrs, entry_index); return true; } static jerry_value_t zjs_ble_set_services(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { // arg 0 should be an array of services // arg 1 is optionally an callback function if (argc < 1 || !jerry_value_is_array(argv[0]) || (argc > 1 && !jerry_value_is_function(argv[1]))) { return zjs_error("zjs_ble_set_services: invalid arguments"); } // FIXME: currently hard-coded to work with demo // which has only 1 primary service and 2 characteristics // add support for multiple services jerry_value_t v_services = argv[0]; int array_size = jerry_get_array_length(v_services); if (array_size == 0) { return zjs_error("zjs_ble_set_services: services array is empty"); } // free existing services if (ble_conn->services) { zjs_ble_free_services(ble_conn->services); ble_conn->services = NULL; } bool success = true; ble_service_t *previous = NULL; for (int i = 0; i < array_size; i++) { jerry_value_t v_service = jerry_get_property_by_index(v_services, i); if (!jerry_value_is_object(v_service)) { return zjs_error("zjs_ble_set_services: service is not object"); } ble_service_t *service = zjs_malloc(sizeof(ble_service_t)); if (!service) { return zjs_error("zjs_ble_set_services: out of memory allocating ble_service_t"); } memset(service, 0, sizeof(ble_service_t)); service->service_obj = jerry_acquire_value(v_service); jerry_set_object_native_handle(service->service_obj, (uintptr_t)service, NULL); if (!zjs_ble_parse_service(service)) { return zjs_error("zjs_ble_set_services: failed to parse service"); } if (!zjs_ble_register_service(service)) { success = false; break; } // append to the list if (!ble_conn->services) { ble_conn->services = service; previous = service; } else { previous->next = service; } } if (argc > 1) { jerry_value_t arg; arg = success ? ZJS_UNDEFINED : jerry_create_string((jerry_char_t *)"failed to register services"); jerry_value_t rval = jerry_call_function(argv[1], ZJS_UNDEFINED, &arg, 1); if (jerry_value_has_error_flag(rval)) { DBG_PRINT("zjs_ble_set_services: failed to call callback function\n"); } } return ZJS_UNDEFINED; } static jerry_value_t zjs_ble_update_rssi(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { // Todo: get actual RSSI value from Zephyr Bluetooth driver jerry_value_t arg = jerry_create_number(-50); zjs_trigger_event(ble_conn->ble_obj, "rssiUpdate", &arg, 1, NULL, NULL); return ZJS_UNDEFINED; } // Constructor static jerry_value_t zjs_ble_primary_service(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc < 1 || !jerry_value_is_object(argv[0])) { return zjs_error("zjs_ble_primary_service: invalid arguments"); } return jerry_acquire_value(argv[0]); } // Constructor static jerry_value_t zjs_ble_characteristic(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc < 1 || !jerry_value_is_object(argv[0])) { return zjs_error("zjs_ble_characterstic: invalid arguments"); } jerry_value_t obj = jerry_acquire_value(argv[0]); jerry_value_t val; // error codes val = jerry_create_number(ZJS_BLE_RESULT_SUCCESS); zjs_set_property(obj, "RESULT_SUCCESS", val); jerry_release_value(val); val = jerry_create_number(ZJS_BLE_RESULT_INVALID_OFFSET); zjs_set_property(obj, "RESULT_INVALID_OFFSET", val); jerry_release_value(val); val = jerry_create_number(ZJS_BLE_RESULT_ATTR_NOT_LONG); zjs_set_property(obj, "RESULT_ATTR_NOT_LONG", val); jerry_release_value(val); val = jerry_create_number(ZJS_BLE_RESULT_INVALID_ATTRIBUTE_LENGTH); zjs_set_property(obj, "RESULT_INVALID_ATTRIBUTE_LENGTH", val); jerry_release_value(val); val = jerry_create_number(ZJS_BLE_RESULT_UNLIKELY_ERROR); zjs_set_property(obj, "RESULT_UNLIKELY_ERROR", val); jerry_release_value(val); return argv[0]; } // Constructor static jerry_value_t zjs_ble_descriptor(const jerry_value_t function_obj, const jerry_value_t this, const jerry_value_t argv[], const jerry_length_t argc) { if (argc < 1 || !jerry_value_is_object(argv[0])) { return zjs_error("zjs_ble_descriptor: invalid arguments"); } return jerry_acquire_value(argv[0]); } jerry_value_t zjs_ble_init() { k_sem_init(&ble_sem, 0, 1); // create global BLE object jerry_value_t ble_obj = jerry_create_object(); zjs_obj_add_function(ble_obj, zjs_ble_disconnect, "disconnect"); zjs_obj_add_function(ble_obj, zjs_ble_start_advertising, "startAdvertising"); zjs_obj_add_function(ble_obj, zjs_ble_stop_advertising, "stopAdvertising"); zjs_obj_add_function(ble_obj, zjs_ble_set_services, "setServices"); zjs_obj_add_function(ble_obj, zjs_ble_update_rssi, "updateRssi"); // register constructors zjs_obj_add_function(ble_obj, zjs_ble_primary_service, "PrimaryService"); zjs_obj_add_function(ble_obj, zjs_ble_characteristic, "Characteristic"); zjs_obj_add_function(ble_obj, zjs_ble_descriptor, "Descriptor"); // make it an event object zjs_make_event(ble_obj); // bt events are called from the FIBER context, since we can't call // zjs_trigger_event() directly, we need to register a c callback which // the C callback will call zjs_trigger_event() ble_conn->ready_cb.id = zjs_add_c_callback(ble_conn, zjs_ble_ready_c_callback); ble_conn->connected_cb.id = zjs_add_c_callback(ble_conn, zjs_ble_connected_c_callback); ble_conn->disconnected_cb.id = zjs_add_c_callback(ble_conn, zjs_ble_disconnected_c_callback); ble_conn->ble_obj = ble_obj; return ble_obj; } #endif // QEMU_BUILD #endif // BUILD_MODULE_BLE
433077.c
/* FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd. All rights reserved VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. This file is part of the FreeRTOS distribution. FreeRTOS is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. *************************************************************************** >>! NOTE: The modification to the GPL is included to allow you to !<< >>! distribute a combined work that includes FreeRTOS without being !<< >>! obliged to provide the source code for proprietary components !<< >>! outside of the FreeRTOS kernel. !<< *************************************************************************** FreeRTOS 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. Full license text is available on the following link: http://www.freertos.org/a00114.html *************************************************************************** * * * FreeRTOS provides completely free yet professionally developed, * * robust, strictly quality controlled, supported, and cross * * platform software that is more than just the market leader, it * * is the industry's de facto standard. * * * * Help yourself get started quickly while simultaneously helping * * to support the FreeRTOS project by purchasing a FreeRTOS * * tutorial book, reference manual, or both: * * http://www.FreeRTOS.org/Documentation * * * *************************************************************************** http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading the FAQ page "My application does not run, what could be wrong?". Have you defined configASSERT()? http://www.FreeRTOS.org/support - In return for receiving this top quality embedded software for free we request you assist our global community by participating in the support forum. http://www.FreeRTOS.org/training - Investing in training allows your team to be as productive as possible as early as possible. Now you can receive FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers Ltd, and the world's leading authority on the world's leading RTOS. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, including FreeRTOS+Trace - an indispensable productivity tool, a DOS compatible FAT file system, and our tiny thread aware UDP/IP stack. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS licenses offer ticketed support, indemnification and commercial middleware. http://www.SafeRTOS.com - High Integrity Systems also provide a safety engineered and independently SIL3 certified version for use in safety and mission critical applications that require provable dependability. 1 tab == 4 spaces! */ /*----------------------------------------------------------- * Implementation of functions defined in portable.h for the ARM CM0 port. *----------------------------------------------------------*/ /* Scheduler includes. */ #include "FreeRTOS01.h" #include "task01.h" /* Constants required to manipulate the NVIC. */ #define portNVIC_SYSTICK_CTRL ( ( volatile uint32_t *) 0xe000e010 ) #define portNVIC_SYSTICK_LOAD ( ( volatile uint32_t *) 0xe000e014 ) #define portNVIC_INT_CTRL ( ( volatile uint32_t *) 0xe000ed04 ) #define portNVIC_SYSPRI2 ( ( volatile uint32_t *) 0xe000ed20 ) #define portNVIC_SYSTICK_CLK 0x00000004 #define portNVIC_SYSTICK_INT 0x00000002 #define portNVIC_SYSTICK_ENABLE 0x00000001 #define portNVIC_PENDSVSET 0x10000000 #define portMIN_INTERRUPT_PRIORITY ( 255UL ) #define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL ) #define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL ) /* Constants required to set up the initial stack. */ #define portINITIAL_XPSR ( 0x01000000 ) /* Let the user override the pre-loading of the initial LR with the address of prvTaskExitError() in case it messes up unwinding of the stack in the debugger. */ #ifdef configTASK_RETURN_ADDRESS #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS #else #define portTASK_RETURN_ADDRESS prvTaskExitError #endif /* Each task maintains its own interrupt status in the critical nesting variable. */ static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; /* * Setup the timer to generate the tick interrupts. */ static void prvSetupTimerInterrupt( void ); /* * Exception handlers. */ void xPortPendSVHandler( void ) __attribute__ (( naked )); void xPortSysTickHandler( void ); void vPortSVCHandler( void ); /* * Start first task is a separate function so it can be tested in isolation. */ static void vPortStartFirstTask( void ) __attribute__ (( naked )); /* * Used to catch tasks that attempt to return from their implementing function. */ static void prvTaskExitError( void ); /*-----------------------------------------------------------*/ /* * See header file for description. */ StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) { /* Simulate the stack frame as it would be created by a context switch interrupt. */ pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ pxTopOfStack--; *pxTopOfStack = ( StackType_t ) pxCode; /* PC */ pxTopOfStack--; *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ pxTopOfStack -= 8; /* R11..R4. */ return pxTopOfStack; } /*-----------------------------------------------------------*/ static void prvTaskExitError( void ) { /* A function that implements a task must not exit or attempt to return to its caller as there is nothing to return to. If a task wants to exit it should instead call vTaskDelete( NULL ). Artificially force an assert() to be triggered if configASSERT() is defined, then stop here so application writers can catch the error. */ configASSERT( uxCriticalNesting == ~0UL ); portDISABLE_INTERRUPTS(); for( ;; ); } /*-----------------------------------------------------------*/ void vPortSVCHandler( void ) { /* This function is no longer used, but retained for backward compatibility. */ } /*-----------------------------------------------------------*/ void vPortStartFirstTask( void ) { /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector table offset register that can be used to locate the initial stack value. Not all M0 parts have the application vector table at address 0. */ __asm volatile( " ldr r2, pxCurrentTCBConst2 \n" /* Obtain location of pxCurrentTCB. */ " ldr r3, [r2] \n" " ldr r0, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */ " add r0, #32 \n" /* Discard everything up to r0. */ " msr psp, r0 \n" /* This is now the new top of stack to use in the task. */ " movs r0, #2 \n" /* Switch to the psp stack. */ " msr CONTROL, r0 \n" " isb \n" " pop {r0-r5} \n" /* Pop the registers that are saved automatically. */ " mov lr, r5 \n" /* lr is now in r5. */ " pop {r3} \n" /* Return address is now in r3. */ " pop {r2} \n" /* Pop and discard XPSR. */ " cpsie i \n" /* The first task has its context and interrupts can be enabled. */ " bx r3 \n" /* Finally, jump to the user defined task code. */ " \n" " .align 4 \n" "pxCurrentTCBConst2: .word pxCurrentTCB " ); } /*-----------------------------------------------------------*/ /* * See header file for description. */ BaseType_t xPortStartScheduler( void ) { /* Make PendSV, CallSV and SysTick the same priroity as the kernel. */ *(portNVIC_SYSPRI2) |= portNVIC_PENDSV_PRI; *(portNVIC_SYSPRI2) |= portNVIC_SYSTICK_PRI; /* Start the timer that generates the tick ISR. Interrupts are disabled here already. */ prvSetupTimerInterrupt(); /* Initialise the critical nesting count ready for the first task. */ uxCriticalNesting = 0; /* Start the first task. */ vPortStartFirstTask(); /* Should never get here as the tasks will now be executing! Call the task exit error function to prevent compiler warnings about a static function not being called in the case that the application writer overrides this functionality by defining configTASK_RETURN_ADDRESS. */ prvTaskExitError(); /* Should not get here! */ return 0; } /*-----------------------------------------------------------*/ void vPortEndScheduler( void ) { /* Not implemented in ports where there is nothing to return to. Artificially force an assert. */ configASSERT( uxCriticalNesting == 1000UL ); } /*-----------------------------------------------------------*/ void vPortYield( void ) { /* Set a PendSV to request a context switch. */ *( portNVIC_INT_CTRL ) = portNVIC_PENDSVSET; /* Barriers are normally not required but do ensure the code is completely within the specified behaviour for the architecture. */ __asm volatile( "dsb" ); __asm volatile( "isb" ); } /*-----------------------------------------------------------*/ void vPortEnterCritical( void ) { portDISABLE_INTERRUPTS(); uxCriticalNesting++; __asm volatile( "dsb" ); __asm volatile( "isb" ); } /*-----------------------------------------------------------*/ void vPortExitCritical( void ) { configASSERT( uxCriticalNesting ); uxCriticalNesting--; if( uxCriticalNesting == 0 ) { portENABLE_INTERRUPTS(); } } /*-----------------------------------------------------------*/ uint32_t ulSetInterruptMaskFromISR( void ) { __asm volatile( " mrs r0, PRIMASK \n" " cpsid i \n" " bx lr " ); /* To avoid compiler warnings. This line will never be reached. */ return 0; } /*-----------------------------------------------------------*/ void vClearInterruptMaskFromISR( uint32_t ulMask ) { __asm volatile( " msr PRIMASK, r0 \n" " bx lr " ); /* Just to avoid compiler warning. */ ( void ) ulMask; } /*-----------------------------------------------------------*/ void xPortPendSVHandler( void ) { /* This is a naked function. */ __asm volatile ( " mrs r0, psp \n" " \n" " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ " ldr r2, [r3] \n" " \n" " sub r0, r0, #32 \n" /* Make space for the remaining low registers. */ " str r0, [r2] \n" /* Save the new top of stack. */ " stmia r0!, {r4-r7} \n" /* Store the low registers that are not saved automatically. */ " mov r4, r8 \n" /* Store the high registers. */ " mov r5, r9 \n" " mov r6, r10 \n" " mov r7, r11 \n" " stmia r0!, {r4-r7} \n" " \n" " push {r3, r14} \n" " cpsid i \n" " bl vTaskSwitchContext \n" " cpsie i \n" " pop {r2, r3} \n" /* lr goes in r3. r2 now holds tcb pointer. */ " \n" " ldr r1, [r2] \n" " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ " add r0, r0, #16 \n" /* Move to the high registers. */ " ldmia r0!, {r4-r7} \n" /* Pop the high registers. */ " mov r8, r4 \n" " mov r9, r5 \n" " mov r10, r6 \n" " mov r11, r7 \n" " \n" " msr psp, r0 \n" /* Remember the new top of stack for the task. */ " \n" " sub r0, r0, #32 \n" /* Go back for the low registers that are not automatically restored. */ " ldmia r0!, {r4-r7} \n" /* Pop low registers. */ " \n" " bx r3 \n" " \n" " .align 4 \n" "pxCurrentTCBConst: .word pxCurrentTCB " ); } /*-----------------------------------------------------------*/ void xPortSysTickHandler( void ) { uint32_t ulPreviousMask; ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR(); { /* Increment the RTOS tick. */ if( xTaskIncrementTick() != pdFALSE ) { /* Pend a context switch. */ *(portNVIC_INT_CTRL) = portNVIC_PENDSVSET; } } portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask ); } /*-----------------------------------------------------------*/ /* * Setup the systick timer to generate the tick interrupts at the required * frequency. */ void prvSetupTimerInterrupt( void ) { /* Configure SysTick to interrupt at the requested rate. */ *(portNVIC_SYSTICK_LOAD) = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; *(portNVIC_SYSTICK_CTRL) = portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE; } /*-----------------------------------------------------------*/ #if configCHECK_FOR_STACK_OVERFLOW != 0 __WEAK void vApplicationStackOverflowHook( TaskHandle_t xTask, signed char *pcTaskName ) { (void)xTask; (void)pcTaskName; /* The stack space has been exceeded for a task, considering allocating more. */ taskDISABLE_INTERRUPTS(); CY_ASSERT(0U != 0U); for( ;; ) { } } #endif #if( configASSERT_DEFINED == 1 ) /* Constants required to check the validity of an interrupt priority. */ #define portFIRST_USER_INTERRUPT_NUMBER ( 16 ) #define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 ) #define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) ) #define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) #define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 ) #define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 ) #define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL ) #define portPRIGROUP_SHIFT ( 8UL ) static uint8_t ucMaxSysCallPriority = 0; static uint32_t ulMaxPRIGROUPValue = 0; static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16; void vPortValidateInterruptPriority( void ) { uint32_t ulCurrentInterrupt; uint8_t ucCurrentPriority; /* Obtain the number of the currently executing interrupt. */ __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) ); /* Is the interrupt number a user defined interrupt? */ if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ) { /* Look up the interrupt's priority. */ ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ]; /* The following assertion will fail if a service routine (ISR) for an interrupt that has been assigned a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API function. ISR safe FreeRTOS API functions must *only* be called from interrupts that have been assigned a priority at or below configMAX_SYSCALL_INTERRUPT_PRIORITY. Numerically low interrupt priority numbers represent logically high interrupt priorities, therefore the priority of the interrupt must be set to a value equal to or numerically *higher* than configMAX_SYSCALL_INTERRUPT_PRIORITY. Interrupts that use the FreeRTOS API must not be left at their default priority of zero as that is the highest possible priority, which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY, and therefore also guaranteed to be invalid. FreeRTOS maintains separate thread and ISR API functions to ensure interrupt entry is as fast and simple as possible. The following links provide detailed information: http://www.freertos.org/RTOS-Cortex-M3-M4.html http://www.freertos.org/FAQHelp.html */ configASSERT( ucCurrentPriority >= ucMaxSysCallPriority ); } /* Priority grouping: The interrupt controller (NVIC) allows the bits that define each interrupt's priority to be split between bits that define the interrupt's pre-emption priority bits and bits that define the interrupt's sub-priority. For simplicity all bits must be defined to be pre-emption priority bits. The following assertion will fail if this is not the case (if some bits represent a sub-priority). If the application only uses CMSIS libraries for interrupt configuration then the correct setting can be achieved on all Cortex-M devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the scheduler. Note however that some vendor specific peripheral libraries assume a non-zero priority group setting, in which cases using a value of zero will result in unpredicable behaviour. */ configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue ); } #endif /* configASSERT_DEFINED */
877736.c
#include <assert.h> int main(int argc, char** argv) { float x = 10.0; while(x>0) { x *= 0.1; } assert(x>=0.0); return 0; }
764094.c
#include "editor.h" void move_position_up(void) { if (pos.y > 0) pos.y--; if (pos.x) while (!buffer[pos.y][pos.x-1]) pos.x--; } void move_position_down(void) { if (pos.y < lines-1) pos.y++; if (pos.x) while (!buffer[pos.y][pos.x-1]) pos.x--; } void move_position_right(void) { if (buffer[pos.y][pos.x]) pos.x++; else if (pos.y < lines-1) do { pos.y++; pos.x = 0; } while (0); } void move_position_left(void) { if (pos.x > 0) pos.x--; else if (pos.y > 0) for (pos.y--; buffer[pos.y][pos.x]; pos.x++) ; } void check_position(void) { if (pos.x < 0) pos.x = 0; if (pos.y < 0) pos.y = 0; }
850070.c
// SPDX-License-Identifier: GPL-2.0+ /* Copyright (c) 2016-2017 Hisilicon Limited. */ #include "hclge_err.h" static const struct hclge_hw_error hclge_imp_tcm_ecc_int[] = { { .int_msk = BIT(0), .msg = "imp_itcm0_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "imp_itcm0_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "imp_itcm1_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "imp_itcm1_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "imp_itcm2_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "imp_itcm2_ecc_mbit_err" }, { .int_msk = BIT(6), .msg = "imp_itcm3_ecc_1bit_err" }, { .int_msk = BIT(7), .msg = "imp_itcm3_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "imp_dtcm0_mem0_ecc_1bit_err" }, { .int_msk = BIT(9), .msg = "imp_dtcm0_mem0_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "imp_dtcm0_mem1_ecc_1bit_err" }, { .int_msk = BIT(11), .msg = "imp_dtcm0_mem1_ecc_mbit_err" }, { .int_msk = BIT(12), .msg = "imp_dtcm1_mem0_ecc_1bit_err" }, { .int_msk = BIT(13), .msg = "imp_dtcm1_mem0_ecc_mbit_err" }, { .int_msk = BIT(14), .msg = "imp_dtcm1_mem1_ecc_1bit_err" }, { .int_msk = BIT(15), .msg = "imp_dtcm1_mem1_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_imp_itcm4_ecc_int[] = { { .int_msk = BIT(0), .msg = "imp_itcm4_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "imp_itcm4_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_cmdq_nic_mem_ecc_int[] = { { .int_msk = BIT(0), .msg = "cmdq_nic_rx_depth_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "cmdq_nic_rx_depth_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "cmdq_nic_tx_depth_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "cmdq_nic_tx_depth_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "cmdq_nic_rx_tail_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "cmdq_nic_rx_tail_ecc_mbit_err" }, { .int_msk = BIT(6), .msg = "cmdq_nic_tx_tail_ecc_1bit_err" }, { .int_msk = BIT(7), .msg = "cmdq_nic_tx_tail_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "cmdq_nic_rx_head_ecc_1bit_err" }, { .int_msk = BIT(9), .msg = "cmdq_nic_rx_head_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "cmdq_nic_tx_head_ecc_1bit_err" }, { .int_msk = BIT(11), .msg = "cmdq_nic_tx_head_ecc_mbit_err" }, { .int_msk = BIT(12), .msg = "cmdq_nic_rx_addr_ecc_1bit_err" }, { .int_msk = BIT(13), .msg = "cmdq_nic_rx_addr_ecc_mbit_err" }, { .int_msk = BIT(14), .msg = "cmdq_nic_tx_addr_ecc_1bit_err" }, { .int_msk = BIT(15), .msg = "cmdq_nic_tx_addr_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_cmdq_rocee_mem_ecc_int[] = { { .int_msk = BIT(0), .msg = "cmdq_rocee_rx_depth_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "cmdq_rocee_rx_depth_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "cmdq_rocee_tx_depth_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "cmdq_rocee_tx_depth_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "cmdq_rocee_rx_tail_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "cmdq_rocee_rx_tail_ecc_mbit_err" }, { .int_msk = BIT(6), .msg = "cmdq_rocee_tx_tail_ecc_1bit_err" }, { .int_msk = BIT(7), .msg = "cmdq_rocee_tx_tail_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "cmdq_rocee_rx_head_ecc_1bit_err" }, { .int_msk = BIT(9), .msg = "cmdq_rocee_rx_head_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "cmdq_rocee_tx_head_ecc_1bit_err" }, { .int_msk = BIT(11), .msg = "cmdq_rocee_tx_head_ecc_mbit_err" }, { .int_msk = BIT(12), .msg = "cmdq_rocee_rx_addr_ecc_1bit_err" }, { .int_msk = BIT(13), .msg = "cmdq_rocee_rx_addr_ecc_mbit_err" }, { .int_msk = BIT(14), .msg = "cmdq_rocee_tx_addr_ecc_1bit_err" }, { .int_msk = BIT(15), .msg = "cmdq_rocee_tx_addr_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_tqp_int_ecc_int[] = { { .int_msk = BIT(0), .msg = "tqp_int_cfg_even_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "tqp_int_cfg_odd_ecc_1bit_err" }, { .int_msk = BIT(2), .msg = "tqp_int_ctrl_even_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "tqp_int_ctrl_odd_ecc_1bit_err" }, { .int_msk = BIT(4), .msg = "tx_que_scan_int_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "rx_que_scan_int_ecc_1bit_err" }, { .int_msk = BIT(6), .msg = "tqp_int_cfg_even_ecc_mbit_err" }, { .int_msk = BIT(7), .msg = "tqp_int_cfg_odd_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "tqp_int_ctrl_even_ecc_mbit_err" }, { .int_msk = BIT(9), .msg = "tqp_int_ctrl_odd_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "tx_que_scan_int_ecc_mbit_err" }, { .int_msk = BIT(11), .msg = "rx_que_scan_int_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_igu_com_err_int[] = { { .int_msk = BIT(0), .msg = "igu_rx_buf0_ecc_mbit_err" }, { .int_msk = BIT(1), .msg = "igu_rx_buf0_ecc_1bit_err" }, { .int_msk = BIT(2), .msg = "igu_rx_buf1_ecc_mbit_err" }, { .int_msk = BIT(3), .msg = "igu_rx_buf1_ecc_1bit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_igu_egu_tnl_err_int[] = { { .int_msk = BIT(0), .msg = "rx_buf_overflow" }, { .int_msk = BIT(1), .msg = "rx_stp_fifo_overflow" }, { .int_msk = BIT(2), .msg = "rx_stp_fifo_undeflow" }, { .int_msk = BIT(3), .msg = "tx_buf_overflow" }, { .int_msk = BIT(4), .msg = "tx_buf_underrun" }, { .int_msk = BIT(5), .msg = "rx_stp_buf_overflow" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ncsi_err_int[] = { { .int_msk = BIT(0), .msg = "ncsi_tx_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "ncsi_tx_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ppp_mpf_int0[] = { { .int_msk = BIT(0), .msg = "vf_vlan_ad_mem_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "umv_mcast_group_mem_ecc_1bit_err" }, { .int_msk = BIT(2), .msg = "umv_key_mem0_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "umv_key_mem1_ecc_1bit_err" }, { .int_msk = BIT(4), .msg = "umv_key_mem2_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "umv_key_mem3_ecc_1bit_err" }, { .int_msk = BIT(6), .msg = "umv_ad_mem_ecc_1bit_err" }, { .int_msk = BIT(7), .msg = "rss_tc_mode_mem_ecc_1bit_err" }, { .int_msk = BIT(8), .msg = "rss_idt_mem0_ecc_1bit_err" }, { .int_msk = BIT(9), .msg = "rss_idt_mem1_ecc_1bit_err" }, { .int_msk = BIT(10), .msg = "rss_idt_mem2_ecc_1bit_err" }, { .int_msk = BIT(11), .msg = "rss_idt_mem3_ecc_1bit_err" }, { .int_msk = BIT(12), .msg = "rss_idt_mem4_ecc_1bit_err" }, { .int_msk = BIT(13), .msg = "rss_idt_mem5_ecc_1bit_err" }, { .int_msk = BIT(14), .msg = "rss_idt_mem6_ecc_1bit_err" }, { .int_msk = BIT(15), .msg = "rss_idt_mem7_ecc_1bit_err" }, { .int_msk = BIT(16), .msg = "rss_idt_mem8_ecc_1bit_err" }, { .int_msk = BIT(17), .msg = "rss_idt_mem9_ecc_1bit_err" }, { .int_msk = BIT(18), .msg = "rss_idt_mem10_ecc_1bit_err" }, { .int_msk = BIT(19), .msg = "rss_idt_mem11_ecc_1bit_err" }, { .int_msk = BIT(20), .msg = "rss_idt_mem12_ecc_1bit_err" }, { .int_msk = BIT(21), .msg = "rss_idt_mem13_ecc_1bit_err" }, { .int_msk = BIT(22), .msg = "rss_idt_mem14_ecc_1bit_err" }, { .int_msk = BIT(23), .msg = "rss_idt_mem15_ecc_1bit_err" }, { .int_msk = BIT(24), .msg = "port_vlan_mem_ecc_1bit_err" }, { .int_msk = BIT(25), .msg = "mcast_linear_table_mem_ecc_1bit_err" }, { .int_msk = BIT(26), .msg = "mcast_result_mem_ecc_1bit_err" }, { .int_msk = BIT(27), .msg = "flow_director_ad_mem0_ecc_1bit_err" }, { .int_msk = BIT(28), .msg = "flow_director_ad_mem1_ecc_1bit_err" }, { .int_msk = BIT(29), .msg = "rx_vlan_tag_memory_ecc_1bit_err" }, { .int_msk = BIT(30), .msg = "Tx_UP_mapping_config_mem_ecc_1bit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ppp_mpf_int1[] = { { .int_msk = BIT(0), .msg = "vf_vlan_ad_mem_ecc_mbit_err" }, { .int_msk = BIT(1), .msg = "umv_mcast_group_mem_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "umv_key_mem0_ecc_mbit_err" }, { .int_msk = BIT(3), .msg = "umv_key_mem1_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "umv_key_mem2_ecc_mbit_err" }, { .int_msk = BIT(5), .msg = "umv_key_mem3_ecc_mbit_err" }, { .int_msk = BIT(6), .msg = "umv_ad_mem_ecc_mbit_erre" }, { .int_msk = BIT(7), .msg = "rss_tc_mode_mem_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "rss_idt_mem0_ecc_mbit_err" }, { .int_msk = BIT(9), .msg = "rss_idt_mem1_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "rss_idt_mem2_ecc_mbit_err" }, { .int_msk = BIT(11), .msg = "rss_idt_mem3_ecc_mbit_err" }, { .int_msk = BIT(12), .msg = "rss_idt_mem4_ecc_mbit_err" }, { .int_msk = BIT(13), .msg = "rss_idt_mem5_ecc_mbit_err" }, { .int_msk = BIT(14), .msg = "rss_idt_mem6_ecc_mbit_err" }, { .int_msk = BIT(15), .msg = "rss_idt_mem7_ecc_mbit_err" }, { .int_msk = BIT(16), .msg = "rss_idt_mem8_ecc_mbit_err" }, { .int_msk = BIT(17), .msg = "rss_idt_mem9_ecc_mbit_err" }, { .int_msk = BIT(18), .msg = "rss_idt_mem10_ecc_m1bit_err" }, { .int_msk = BIT(19), .msg = "rss_idt_mem11_ecc_mbit_err" }, { .int_msk = BIT(20), .msg = "rss_idt_mem12_ecc_mbit_err" }, { .int_msk = BIT(21), .msg = "rss_idt_mem13_ecc_mbit_err" }, { .int_msk = BIT(22), .msg = "rss_idt_mem14_ecc_mbit_err" }, { .int_msk = BIT(23), .msg = "rss_idt_mem15_ecc_mbit_err" }, { .int_msk = BIT(24), .msg = "port_vlan_mem_ecc_mbit_err" }, { .int_msk = BIT(25), .msg = "mcast_linear_table_mem_ecc_mbit_err" }, { .int_msk = BIT(26), .msg = "mcast_result_mem_ecc_mbit_err" }, { .int_msk = BIT(27), .msg = "flow_director_ad_mem0_ecc_mbit_err" }, { .int_msk = BIT(28), .msg = "flow_director_ad_mem1_ecc_mbit_err" }, { .int_msk = BIT(29), .msg = "rx_vlan_tag_memory_ecc_mbit_err" }, { .int_msk = BIT(30), .msg = "Tx_UP_mapping_config_mem_ecc_mbit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ppp_pf_int[] = { { .int_msk = BIT(0), .msg = "Tx_vlan_tag_err" }, { .int_msk = BIT(1), .msg = "rss_list_tc_unassigned_queue_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ppp_mpf_int2[] = { { .int_msk = BIT(0), .msg = "hfs_fifo_mem_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "rslt_descr_fifo_mem_ecc_1bit_err" }, { .int_msk = BIT(2), .msg = "tx_vlan_tag_mem_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "FD_CN0_memory_ecc_1bit_err" }, { .int_msk = BIT(4), .msg = "FD_CN1_memory_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "GRO_AD_memory_ecc_1bit_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_ppp_mpf_int3[] = { { .int_msk = BIT(0), .msg = "hfs_fifo_mem_ecc_mbit_err" }, { .int_msk = BIT(1), .msg = "rslt_descr_fifo_mem_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "tx_vlan_tag_mem_ecc_mbit_err" }, { .int_msk = BIT(3), .msg = "FD_CN0_memory_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "FD_CN1_memory_ecc_mbit_err" }, { .int_msk = BIT(5), .msg = "GRO_AD_memory_ecc_mbit_err" }, { /* sentinel */ } }; struct hclge_tm_sch_ecc_info { const char *name; }; static const struct hclge_tm_sch_ecc_info hclge_tm_sch_ecc_err[7][15] = { { { .name = "QSET_QUEUE_CTRL:PRI_LEN TAB" }, { .name = "QSET_QUEUE_CTRL:SPA_LEN TAB" }, { .name = "QSET_QUEUE_CTRL:SPB_LEN TAB" }, { .name = "QSET_QUEUE_CTRL:WRRA_LEN TAB" }, { .name = "QSET_QUEUE_CTRL:WRRB_LEN TAB" }, { .name = "QSET_QUEUE_CTRL:SPA_HPTR TAB" }, { .name = "QSET_QUEUE_CTRL:SPB_HPTR TAB" }, { .name = "QSET_QUEUE_CTRL:WRRA_HPTR TAB" }, { .name = "QSET_QUEUE_CTRL:WRRB_HPTR TAB" }, { .name = "QSET_QUEUE_CTRL:QS_LINKLIST TAB" }, { .name = "QSET_QUEUE_CTRL:SPA_TPTR TAB" }, { .name = "QSET_QUEUE_CTRL:SPB_TPTR TAB" }, { .name = "QSET_QUEUE_CTRL:WRRA_TPTR TAB" }, { .name = "QSET_QUEUE_CTRL:WRRB_TPTR TAB" }, { .name = "QSET_QUEUE_CTRL:QS_DEFICITCNT TAB" }, }, { { .name = "ROCE_QUEUE_CTRL:QS_LEN TAB" }, { .name = "ROCE_QUEUE_CTRL:QS_TPTR TAB" }, { .name = "ROCE_QUEUE_CTRL:QS_HPTR TAB" }, { .name = "ROCE_QUEUE_CTRL:QLINKLIST TAB" }, { .name = "ROCE_QUEUE_CTRL:QCLEN TAB" }, }, { { .name = "NIC_QUEUE_CTRL:QS_LEN TAB" }, { .name = "NIC_QUEUE_CTRL:QS_TPTR TAB" }, { .name = "NIC_QUEUE_CTRL:QS_HPTR TAB" }, { .name = "NIC_QUEUE_CTRL:QLINKLIST TAB" }, { .name = "NIC_QUEUE_CTRL:QCLEN TAB" }, }, { { .name = "RAM_CFG_CTRL:CSHAP TAB" }, { .name = "RAM_CFG_CTRL:PSHAP TAB" }, }, { { .name = "SHAPER_CTRL:PSHAP TAB" }, }, { { .name = "MSCH_CTRL" }, }, { { .name = "TOP_CTRL" }, }, }; static const struct hclge_hw_error hclge_tm_sch_err_int[] = { { .int_msk = BIT(0), .msg = "tm_sch_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "tm_sch_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "tm_sch_port_shap_sub_fifo_wr_full_err" }, { .int_msk = BIT(3), .msg = "tm_sch_port_shap_sub_fifo_rd_empty_err" }, { .int_msk = BIT(4), .msg = "tm_sch_pg_pshap_sub_fifo_wr_full_err" }, { .int_msk = BIT(5), .msg = "tm_sch_pg_pshap_sub_fifo_rd_empty_err" }, { .int_msk = BIT(6), .msg = "tm_sch_pg_cshap_sub_fifo_wr_full_err" }, { .int_msk = BIT(7), .msg = "tm_sch_pg_cshap_sub_fifo_rd_empty_err" }, { .int_msk = BIT(8), .msg = "tm_sch_pri_pshap_sub_fifo_wr_full_err" }, { .int_msk = BIT(9), .msg = "tm_sch_pri_pshap_sub_fifo_rd_empty_err" }, { .int_msk = BIT(10), .msg = "tm_sch_pri_cshap_sub_fifo_wr_full_err" }, { .int_msk = BIT(11), .msg = "tm_sch_pri_cshap_sub_fifo_rd_empty_err" }, { .int_msk = BIT(12), .msg = "tm_sch_port_shap_offset_fifo_wr_full_err" }, { .int_msk = BIT(13), .msg = "tm_sch_port_shap_offset_fifo_rd_empty_err" }, { .int_msk = BIT(14), .msg = "tm_sch_pg_pshap_offset_fifo_wr_full_err" }, { .int_msk = BIT(15), .msg = "tm_sch_pg_pshap_offset_fifo_rd_empty_err" }, { .int_msk = BIT(16), .msg = "tm_sch_pg_cshap_offset_fifo_wr_full_err" }, { .int_msk = BIT(17), .msg = "tm_sch_pg_cshap_offset_fifo_rd_empty_err" }, { .int_msk = BIT(18), .msg = "tm_sch_pri_pshap_offset_fifo_wr_full_err" }, { .int_msk = BIT(19), .msg = "tm_sch_pri_pshap_offset_fifo_rd_empty_err" }, { .int_msk = BIT(20), .msg = "tm_sch_pri_cshap_offset_fifo_wr_full_err" }, { .int_msk = BIT(21), .msg = "tm_sch_pri_cshap_offset_fifo_rd_empty_err" }, { .int_msk = BIT(22), .msg = "tm_sch_rq_fifo_wr_full_err" }, { .int_msk = BIT(23), .msg = "tm_sch_rq_fifo_rd_empty_err" }, { .int_msk = BIT(24), .msg = "tm_sch_nq_fifo_wr_full_err" }, { .int_msk = BIT(25), .msg = "tm_sch_nq_fifo_rd_empty_err" }, { .int_msk = BIT(26), .msg = "tm_sch_roce_up_fifo_wr_full_err" }, { .int_msk = BIT(27), .msg = "tm_sch_roce_up_fifo_rd_empty_err" }, { .int_msk = BIT(28), .msg = "tm_sch_rcb_byte_fifo_wr_full_err" }, { .int_msk = BIT(29), .msg = "tm_sch_rcb_byte_fifo_rd_empty_err" }, { .int_msk = BIT(30), .msg = "tm_sch_ssu_byte_fifo_wr_full_err" }, { .int_msk = BIT(31), .msg = "tm_sch_ssu_byte_fifo_rd_empty_err" }, { /* sentinel */ } }; static const struct hclge_hw_error hclge_qcn_ecc_err_int[] = { { .int_msk = BIT(0), .msg = "qcn_byte_mem_ecc_1bit_err" }, { .int_msk = BIT(1), .msg = "qcn_byte_mem_ecc_mbit_err" }, { .int_msk = BIT(2), .msg = "qcn_time_mem_ecc_1bit_err" }, { .int_msk = BIT(3), .msg = "qcn_time_mem_ecc_mbit_err" }, { .int_msk = BIT(4), .msg = "qcn_fb_mem_ecc_1bit_err" }, { .int_msk = BIT(5), .msg = "qcn_fb_mem_ecc_mbit_err" }, { .int_msk = BIT(6), .msg = "qcn_link_mem_ecc_1bit_err" }, { .int_msk = BIT(7), .msg = "qcn_link_mem_ecc_mbit_err" }, { .int_msk = BIT(8), .msg = "qcn_rate_mem_ecc_1bit_err" }, { .int_msk = BIT(9), .msg = "qcn_rate_mem_ecc_mbit_err" }, { .int_msk = BIT(10), .msg = "qcn_tmplt_mem_ecc_1bit_err" }, { .int_msk = BIT(11), .msg = "qcn_tmplt_mem_ecc_mbit_err" }, { .int_msk = BIT(12), .msg = "qcn_shap_cfg_mem_ecc_1bit_err" }, { .int_msk = BIT(13), .msg = "qcn_shap_cfg_mem_ecc_mbit_err" }, { .int_msk = BIT(14), .msg = "qcn_gp0_barrel_mem_ecc_1bit_err" }, { .int_msk = BIT(15), .msg = "qcn_gp0_barrel_mem_ecc_mbit_err" }, { .int_msk = BIT(16), .msg = "qcn_gp1_barrel_mem_ecc_1bit_err" }, { .int_msk = BIT(17), .msg = "qcn_gp1_barrel_mem_ecc_mbit_err" }, { .int_msk = BIT(18), .msg = "qcn_gp2_barrel_mem_ecc_1bit_err" }, { .int_msk = BIT(19), .msg = "qcn_gp2_barrel_mem_ecc_mbit_err" }, { .int_msk = BIT(20), .msg = "qcn_gp3_barral_mem_ecc_1bit_err" }, { .int_msk = BIT(21), .msg = "qcn_gp3_barral_mem_ecc_mbit_err" }, { /* sentinel */ } }; static void hclge_log_error(struct device *dev, const struct hclge_hw_error *err_list, u32 err_sts) { const struct hclge_hw_error *err; int i = 0; while (err_list[i].msg) { err = &err_list[i]; if (!(err->int_msk & err_sts)) { i++; continue; } dev_warn(dev, "%s [error status=0x%x] found\n", err->msg, err_sts); i++; } } /* hclge_cmd_query_error: read the error information * @hdev: pointer to struct hclge_dev * @desc: descriptor for describing the command * @cmd: command opcode * @flag: flag for extended command structure * @w_num: offset for setting the read interrupt type. * @int_type: select which type of the interrupt for which the error * info will be read(RAS-CE/RAS-NFE/RAS-FE etc). * * This function query the error info from hw register/s using command */ static int hclge_cmd_query_error(struct hclge_dev *hdev, struct hclge_desc *desc, u32 cmd, u16 flag, u8 w_num, enum hclge_err_int_type int_type) { struct device *dev = &hdev->pdev->dev; int num = 1; int ret; hclge_cmd_setup_basic_desc(&desc[0], cmd, true); if (flag) { desc[0].flag |= cpu_to_le16(flag); hclge_cmd_setup_basic_desc(&desc[1], cmd, true); num = 2; } if (w_num) desc[0].data[w_num] = cpu_to_le32(int_type); ret = hclge_cmd_send(&hdev->hw, &desc[0], num); if (ret) dev_err(dev, "query error cmd failed (%d)\n", ret); return ret; } /* hclge_cmd_clear_error: clear the error status * @hdev: pointer to struct hclge_dev * @desc: descriptor for describing the command * @desc_src: prefilled descriptor from the previous command for reusing * @cmd: command opcode * @flag: flag for extended command structure * * This function clear the error status in the hw register/s using command */ static int hclge_cmd_clear_error(struct hclge_dev *hdev, struct hclge_desc *desc, struct hclge_desc *desc_src, u32 cmd, u16 flag) { struct device *dev = &hdev->pdev->dev; int num = 1; int ret, i; if (cmd) { hclge_cmd_setup_basic_desc(&desc[0], cmd, false); if (flag) { desc[0].flag |= cpu_to_le16(flag); hclge_cmd_setup_basic_desc(&desc[1], cmd, false); num = 2; } if (desc_src) { for (i = 0; i < 6; i++) { desc[0].data[i] = desc_src[0].data[i]; if (flag) desc[1].data[i] = desc_src[1].data[i]; } } } else { hclge_cmd_reuse_desc(&desc[0], false); if (flag) { desc[0].flag |= cpu_to_le16(flag); hclge_cmd_reuse_desc(&desc[1], false); num = 2; } } ret = hclge_cmd_send(&hdev->hw, &desc[0], num); if (ret) dev_err(dev, "clear error cmd failed (%d)\n", ret); return ret; } static int hclge_enable_common_error(struct hclge_dev *hdev, bool en) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc[2]; int ret; hclge_cmd_setup_basic_desc(&desc[0], HCLGE_COMMON_ECC_INT_CFG, false); desc[0].flag |= cpu_to_le16(HCLGE_CMD_FLAG_NEXT); hclge_cmd_setup_basic_desc(&desc[1], HCLGE_COMMON_ECC_INT_CFG, false); if (en) { /* enable COMMON error interrupts */ desc[0].data[0] = cpu_to_le32(HCLGE_IMP_TCM_ECC_ERR_INT_EN); desc[0].data[2] = cpu_to_le32(HCLGE_CMDQ_NIC_ECC_ERR_INT_EN | HCLGE_CMDQ_ROCEE_ECC_ERR_INT_EN); desc[0].data[3] = cpu_to_le32(HCLGE_IMP_RD_POISON_ERR_INT_EN); desc[0].data[4] = cpu_to_le32(HCLGE_TQP_ECC_ERR_INT_EN); desc[0].data[5] = cpu_to_le32(HCLGE_IMP_ITCM4_ECC_ERR_INT_EN); } else { /* disable COMMON error interrupts */ desc[0].data[0] = 0; desc[0].data[2] = 0; desc[0].data[3] = 0; desc[0].data[4] = 0; desc[0].data[5] = 0; } desc[1].data[0] = cpu_to_le32(HCLGE_IMP_TCM_ECC_ERR_INT_EN_MASK); desc[1].data[2] = cpu_to_le32(HCLGE_CMDQ_NIC_ECC_ERR_INT_EN_MASK | HCLGE_CMDQ_ROCEE_ECC_ERR_INT_EN_MASK); desc[1].data[3] = cpu_to_le32(HCLGE_IMP_RD_POISON_ERR_INT_EN_MASK); desc[1].data[4] = cpu_to_le32(HCLGE_TQP_ECC_ERR_INT_EN_MASK); desc[1].data[5] = cpu_to_le32(HCLGE_IMP_ITCM4_ECC_ERR_INT_EN_MASK); ret = hclge_cmd_send(&hdev->hw, &desc[0], 2); if (ret) dev_err(dev, "failed(%d) to enable/disable COMMON err interrupts\n", ret); return ret; } static int hclge_enable_ncsi_error(struct hclge_dev *hdev, bool en) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc; int ret; if (hdev->pdev->revision < 0x21) return 0; /* enable/disable NCSI error interrupts */ hclge_cmd_setup_basic_desc(&desc, HCLGE_NCSI_INT_EN, false); if (en) desc.data[0] = cpu_to_le32(HCLGE_NCSI_ERR_INT_EN); else desc.data[0] = 0; ret = hclge_cmd_send(&hdev->hw, &desc, 1); if (ret) dev_err(dev, "failed(%d) to enable/disable NCSI error interrupts\n", ret); return ret; } static int hclge_enable_igu_egu_error(struct hclge_dev *hdev, bool en) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc; int ret; /* enable/disable error interrupts */ hclge_cmd_setup_basic_desc(&desc, HCLGE_IGU_COMMON_INT_EN, false); if (en) desc.data[0] = cpu_to_le32(HCLGE_IGU_ERR_INT_EN); else desc.data[0] = 0; desc.data[1] = cpu_to_le32(HCLGE_IGU_ERR_INT_EN_MASK); ret = hclge_cmd_send(&hdev->hw, &desc, 1); if (ret) { dev_err(dev, "failed(%d) to enable/disable IGU common interrupts\n", ret); return ret; } hclge_cmd_setup_basic_desc(&desc, HCLGE_IGU_EGU_TNL_INT_EN, false); if (en) desc.data[0] = cpu_to_le32(HCLGE_IGU_TNL_ERR_INT_EN); else desc.data[0] = 0; desc.data[1] = cpu_to_le32(HCLGE_IGU_TNL_ERR_INT_EN_MASK); ret = hclge_cmd_send(&hdev->hw, &desc, 1); if (ret) { dev_err(dev, "failed(%d) to enable/disable IGU-EGU TNL interrupts\n", ret); return ret; } ret = hclge_enable_ncsi_error(hdev, en); if (ret) dev_err(dev, "fail(%d) to en/disable err int\n", ret); return ret; } static int hclge_enable_ppp_error_interrupt(struct hclge_dev *hdev, u32 cmd, bool en) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc[2]; int ret; /* enable/disable PPP error interrupts */ hclge_cmd_setup_basic_desc(&desc[0], cmd, false); desc[0].flag |= cpu_to_le16(HCLGE_CMD_FLAG_NEXT); hclge_cmd_setup_basic_desc(&desc[1], cmd, false); if (cmd == HCLGE_PPP_CMD0_INT_CMD) { if (en) { desc[0].data[0] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT0_EN); desc[0].data[1] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT1_EN); } else { desc[0].data[0] = 0; desc[0].data[1] = 0; } desc[1].data[0] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT0_EN_MASK); desc[1].data[1] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT1_EN_MASK); } else if (cmd == HCLGE_PPP_CMD1_INT_CMD) { if (en) { desc[0].data[0] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT2_EN); desc[0].data[1] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT3_EN); } else { desc[0].data[0] = 0; desc[0].data[1] = 0; } desc[1].data[0] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT2_EN_MASK); desc[1].data[1] = cpu_to_le32(HCLGE_PPP_MPF_ECC_ERR_INT3_EN_MASK); } ret = hclge_cmd_send(&hdev->hw, &desc[0], 2); if (ret) dev_err(dev, "failed(%d) to enable/disable PPP error interrupts\n", ret); return ret; } static int hclge_enable_ppp_error(struct hclge_dev *hdev, bool en) { struct device *dev = &hdev->pdev->dev; int ret; ret = hclge_enable_ppp_error_interrupt(hdev, HCLGE_PPP_CMD0_INT_CMD, en); if (ret) { dev_err(dev, "failed(%d) to enable/disable PPP error intr 0,1\n", ret); return ret; } ret = hclge_enable_ppp_error_interrupt(hdev, HCLGE_PPP_CMD1_INT_CMD, en); if (ret) dev_err(dev, "failed(%d) to enable/disable PPP error intr 2,3\n", ret); return ret; } int hclge_enable_tm_hw_error(struct hclge_dev *hdev, bool en) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc; int ret; /* enable TM SCH hw errors */ hclge_cmd_setup_basic_desc(&desc, HCLGE_TM_SCH_ECC_INT_EN, false); if (en) desc.data[0] = cpu_to_le32(HCLGE_TM_SCH_ECC_ERR_INT_EN); else desc.data[0] = 0; ret = hclge_cmd_send(&hdev->hw, &desc, 1); if (ret) { dev_err(dev, "failed(%d) to configure TM SCH errors\n", ret); return ret; } /* enable TM QCN hw errors */ ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_QCN_MEM_INT_CFG, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read TM QCN CFG status\n", ret); return ret; } hclge_cmd_reuse_desc(&desc, false); if (en) desc.data[1] = cpu_to_le32(HCLGE_TM_QCN_MEM_ERR_INT_EN); else desc.data[1] = 0; ret = hclge_cmd_send(&hdev->hw, &desc, 1); if (ret) dev_err(dev, "failed(%d) to configure TM QCN mem errors\n", ret); return ret; } static void hclge_process_common_error(struct hclge_dev *hdev, enum hclge_err_int_type type) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc[2]; u32 err_sts; int ret; /* read err sts */ ret = hclge_cmd_query_error(hdev, &desc[0], HCLGE_COMMON_ECC_INT_CFG, HCLGE_CMD_FLAG_NEXT, 0, 0); if (ret) { dev_err(dev, "failed(=%d) to query COMMON error interrupt status\n", ret); return; } /* log err */ err_sts = (le32_to_cpu(desc[0].data[0])) & HCLGE_IMP_TCM_ECC_INT_MASK; hclge_log_error(dev, &hclge_imp_tcm_ecc_int[0], err_sts); err_sts = (le32_to_cpu(desc[0].data[1])) & HCLGE_CMDQ_ECC_INT_MASK; hclge_log_error(dev, &hclge_cmdq_nic_mem_ecc_int[0], err_sts); err_sts = (le32_to_cpu(desc[0].data[1]) >> HCLGE_CMDQ_ROC_ECC_INT_SHIFT) & HCLGE_CMDQ_ECC_INT_MASK; hclge_log_error(dev, &hclge_cmdq_rocee_mem_ecc_int[0], err_sts); if ((le32_to_cpu(desc[0].data[3])) & BIT(0)) dev_warn(dev, "imp_rd_data_poison_err found\n"); err_sts = (le32_to_cpu(desc[0].data[3]) >> HCLGE_TQP_ECC_INT_SHIFT) & HCLGE_TQP_ECC_INT_MASK; hclge_log_error(dev, &hclge_tqp_int_ecc_int[0], err_sts); err_sts = (le32_to_cpu(desc[0].data[5])) & HCLGE_IMP_ITCM4_ECC_INT_MASK; hclge_log_error(dev, &hclge_imp_itcm4_ecc_int[0], err_sts); /* clear error interrupts */ desc[1].data[0] = cpu_to_le32(HCLGE_IMP_TCM_ECC_CLR_MASK); desc[1].data[1] = cpu_to_le32(HCLGE_CMDQ_NIC_ECC_CLR_MASK | HCLGE_CMDQ_ROCEE_ECC_CLR_MASK); desc[1].data[3] = cpu_to_le32(HCLGE_TQP_IMP_ERR_CLR_MASK); desc[1].data[5] = cpu_to_le32(HCLGE_IMP_ITCM4_ECC_CLR_MASK); ret = hclge_cmd_clear_error(hdev, &desc[0], NULL, 0, HCLGE_CMD_FLAG_NEXT); if (ret) dev_err(dev, "failed(%d) to clear COMMON error interrupt status\n", ret); } static void hclge_process_ncsi_error(struct hclge_dev *hdev, enum hclge_err_int_type type) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc_rd; struct hclge_desc desc_wr; u32 err_sts; int ret; if (hdev->pdev->revision < 0x21) return; /* read NCSI error status */ ret = hclge_cmd_query_error(hdev, &desc_rd, HCLGE_NCSI_INT_QUERY, 0, 1, HCLGE_NCSI_ERR_INT_TYPE); if (ret) { dev_err(dev, "failed(=%d) to query NCSI error interrupt status\n", ret); return; } /* log err */ err_sts = le32_to_cpu(desc_rd.data[0]); hclge_log_error(dev, &hclge_ncsi_err_int[0], err_sts); /* clear err int */ ret = hclge_cmd_clear_error(hdev, &desc_wr, &desc_rd, HCLGE_NCSI_INT_CLR, 0); if (ret) dev_err(dev, "failed(=%d) to clear NCSI interrupt status\n", ret); } static void hclge_process_igu_egu_error(struct hclge_dev *hdev, enum hclge_err_int_type int_type) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc_rd; struct hclge_desc desc_wr; u32 err_sts; int ret; /* read IGU common err sts */ ret = hclge_cmd_query_error(hdev, &desc_rd, HCLGE_IGU_COMMON_INT_QUERY, 0, 1, int_type); if (ret) { dev_err(dev, "failed(=%d) to query IGU common int status\n", ret); return; } /* log err */ err_sts = le32_to_cpu(desc_rd.data[0]) & HCLGE_IGU_COM_INT_MASK; hclge_log_error(dev, &hclge_igu_com_err_int[0], err_sts); /* clear err int */ ret = hclge_cmd_clear_error(hdev, &desc_wr, &desc_rd, HCLGE_IGU_COMMON_INT_CLR, 0); if (ret) { dev_err(dev, "failed(=%d) to clear IGU common int status\n", ret); return; } /* read IGU-EGU TNL err sts */ ret = hclge_cmd_query_error(hdev, &desc_rd, HCLGE_IGU_EGU_TNL_INT_QUERY, 0, 1, int_type); if (ret) { dev_err(dev, "failed(=%d) to query IGU-EGU TNL int status\n", ret); return; } /* log err */ err_sts = le32_to_cpu(desc_rd.data[0]) & HCLGE_IGU_EGU_TNL_INT_MASK; hclge_log_error(dev, &hclge_igu_egu_tnl_err_int[0], err_sts); /* clear err int */ ret = hclge_cmd_clear_error(hdev, &desc_wr, &desc_rd, HCLGE_IGU_EGU_TNL_INT_CLR, 0); if (ret) { dev_err(dev, "failed(=%d) to clear IGU-EGU TNL int status\n", ret); return; } hclge_process_ncsi_error(hdev, HCLGE_ERR_INT_RAS_NFE); } static int hclge_log_and_clear_ppp_error(struct hclge_dev *hdev, u32 cmd, enum hclge_err_int_type int_type) { enum hnae3_reset_type reset_level = HNAE3_NONE_RESET; struct device *dev = &hdev->pdev->dev; const struct hclge_hw_error *hw_err_lst1, *hw_err_lst2, *hw_err_lst3; struct hclge_desc desc[2]; u32 err_sts; int ret; /* read PPP INT sts */ ret = hclge_cmd_query_error(hdev, &desc[0], cmd, HCLGE_CMD_FLAG_NEXT, 5, int_type); if (ret) { dev_err(dev, "failed(=%d) to query PPP interrupt status\n", ret); return -EIO; } /* log error */ if (cmd == HCLGE_PPP_CMD0_INT_CMD) { hw_err_lst1 = &hclge_ppp_mpf_int0[0]; hw_err_lst2 = &hclge_ppp_mpf_int1[0]; hw_err_lst3 = &hclge_ppp_pf_int[0]; } else if (cmd == HCLGE_PPP_CMD1_INT_CMD) { hw_err_lst1 = &hclge_ppp_mpf_int2[0]; hw_err_lst2 = &hclge_ppp_mpf_int3[0]; } else { dev_err(dev, "invalid command(=%d)\n", cmd); return -EINVAL; } err_sts = le32_to_cpu(desc[0].data[2]); if (err_sts) { hclge_log_error(dev, hw_err_lst1, err_sts); reset_level = HNAE3_FUNC_RESET; } err_sts = le32_to_cpu(desc[0].data[3]); if (err_sts) { hclge_log_error(dev, hw_err_lst2, err_sts); reset_level = HNAE3_FUNC_RESET; } if (cmd == HCLGE_PPP_CMD0_INT_CMD) { err_sts = (le32_to_cpu(desc[0].data[4]) >> 8) & 0x3; if (err_sts) { hclge_log_error(dev, hw_err_lst3, err_sts); reset_level = HNAE3_FUNC_RESET; } } /* clear PPP INT */ ret = hclge_cmd_clear_error(hdev, &desc[0], NULL, 0, HCLGE_CMD_FLAG_NEXT); if (ret) { dev_err(dev, "failed(=%d) to clear PPP interrupt status\n", ret); return -EIO; } return 0; } static void hclge_process_ppp_error(struct hclge_dev *hdev, enum hclge_err_int_type int_type) { struct device *dev = &hdev->pdev->dev; int ret; /* read PPP INT0,1 sts */ ret = hclge_log_and_clear_ppp_error(hdev, HCLGE_PPP_CMD0_INT_CMD, int_type); if (ret < 0) { dev_err(dev, "failed(=%d) to clear PPP interrupt 0,1 status\n", ret); return; } /* read err PPP INT2,3 sts */ ret = hclge_log_and_clear_ppp_error(hdev, HCLGE_PPP_CMD1_INT_CMD, int_type); if (ret < 0) dev_err(dev, "failed(=%d) to clear PPP interrupt 2,3 status\n", ret); } static void hclge_process_tm_sch_error(struct hclge_dev *hdev) { struct device *dev = &hdev->pdev->dev; const struct hclge_tm_sch_ecc_info *tm_sch_ecc_info; struct hclge_desc desc; u32 ecc_info; u8 module_no; u8 ram_no; int ret; /* read TM scheduler errors */ ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_SCH_MBIT_ECC_INFO_CMD, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read SCH mbit ECC err info\n", ret); return; } ecc_info = le32_to_cpu(desc.data[0]); ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_SCH_ECC_ERR_RINT_CMD, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read SCH ECC err status\n", ret); return; } /* log TM scheduler errors */ if (le32_to_cpu(desc.data[0])) { hclge_log_error(dev, &hclge_tm_sch_err_int[0], le32_to_cpu(desc.data[0])); if (le32_to_cpu(desc.data[0]) & 0x2) { module_no = (ecc_info >> 20) & 0xF; ram_no = (ecc_info >> 16) & 0xF; tm_sch_ecc_info = &hclge_tm_sch_ecc_err[module_no][ram_no]; dev_warn(dev, "ecc err module:ram=%s\n", tm_sch_ecc_info->name); dev_warn(dev, "ecc memory address = 0x%x\n", ecc_info & 0xFFFF); } } /* clear TM scheduler errors */ ret = hclge_cmd_clear_error(hdev, &desc, NULL, 0, 0); if (ret) { dev_err(dev, "failed(%d) to clear TM SCH error status\n", ret); return; } ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_SCH_ECC_ERR_RINT_CE, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read SCH CE status\n", ret); return; } ret = hclge_cmd_clear_error(hdev, &desc, NULL, 0, 0); if (ret) { dev_err(dev, "failed(%d) to clear TM SCH CE status\n", ret); return; } ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_SCH_ECC_ERR_RINT_NFE, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read SCH NFE status\n", ret); return; } ret = hclge_cmd_clear_error(hdev, &desc, NULL, 0, 0); if (ret) { dev_err(dev, "failed(%d) to clear TM SCH NFE status\n", ret); return; } ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_SCH_ECC_ERR_RINT_FE, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read SCH FE status\n", ret); return; } ret = hclge_cmd_clear_error(hdev, &desc, NULL, 0, 0); if (ret) dev_err(dev, "failed(%d) to clear TM SCH FE status\n", ret); } static void hclge_process_tm_qcn_error(struct hclge_dev *hdev) { struct device *dev = &hdev->pdev->dev; struct hclge_desc desc; int ret; /* read QCN errors */ ret = hclge_cmd_query_error(hdev, &desc, HCLGE_TM_QCN_MEM_INT_INFO_CMD, 0, 0, 0); if (ret) { dev_err(dev, "failed(%d) to read QCN ECC err status\n", ret); return; } /* log QCN errors */ if (le32_to_cpu(desc.data[0])) hclge_log_error(dev, &hclge_qcn_ecc_err_int[0], le32_to_cpu(desc.data[0])); /* clear QCN errors */ ret = hclge_cmd_clear_error(hdev, &desc, NULL, 0, 0); if (ret) dev_err(dev, "failed(%d) to clear QCN error status\n", ret); } static void hclge_process_tm_error(struct hclge_dev *hdev, enum hclge_err_int_type type) { hclge_process_tm_sch_error(hdev); hclge_process_tm_qcn_error(hdev); } static const struct hclge_hw_blk hw_blk[] = { { .msk = BIT(0), .name = "IGU_EGU", .enable_error = hclge_enable_igu_egu_error, .process_error = hclge_process_igu_egu_error, }, { .msk = BIT(5), .name = "COMMON", .enable_error = hclge_enable_common_error, .process_error = hclge_process_common_error, }, { .msk = BIT(4), .name = "TM", .enable_error = hclge_enable_tm_hw_error, .process_error = hclge_process_tm_error, }, { .msk = BIT(1), .name = "PPP", .enable_error = hclge_enable_ppp_error, .process_error = hclge_process_ppp_error, }, { /* sentinel */ } }; int hclge_hw_error_set_state(struct hclge_dev *hdev, bool state) { struct device *dev = &hdev->pdev->dev; int ret = 0; int i = 0; while (hw_blk[i].name) { if (!hw_blk[i].enable_error) { i++; continue; } ret = hw_blk[i].enable_error(hdev, state); if (ret) { dev_err(dev, "fail(%d) to en/disable err int\n", ret); return ret; } i++; } return ret; } pci_ers_result_t hclge_process_ras_hw_error(struct hnae3_ae_dev *ae_dev) { struct hclge_dev *hdev = ae_dev->priv; struct device *dev = &hdev->pdev->dev; u32 sts, val; int i = 0; sts = hclge_read_dev(&hdev->hw, HCLGE_RAS_PF_OTHER_INT_STS_REG); /* Processing Non-fatal errors */ if (sts & HCLGE_RAS_REG_NFE_MASK) { val = (sts >> HCLGE_RAS_REG_NFE_SHIFT) & 0xFF; i = 0; while (hw_blk[i].name) { if (!(hw_blk[i].msk & val)) { i++; continue; } dev_warn(dev, "%s ras non-fatal error identified\n", hw_blk[i].name); if (hw_blk[i].process_error) hw_blk[i].process_error(hdev, HCLGE_ERR_INT_RAS_NFE); i++; } } return PCI_ERS_RESULT_NEED_RESET; }
503580.c
/* * Filter layer - format negotiation * copyright (c) 2007 Bobby Bingham * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avfilter.h" /** * Add all refs from a to ret and destroy a. */ static void merge_ref(AVFilterFormats *ret, AVFilterFormats *a) { int i; for(i = 0; i < a->refcount; i ++) { ret->refs[ret->refcount] = a->refs[i]; *ret->refs[ret->refcount++] = ret; } av_free(a->refs); av_free(a->formats); av_free(a); } AVFilterFormats *avfilter_merge_formats(AVFilterFormats *a, AVFilterFormats *b) { AVFilterFormats *ret; unsigned i, j, k = 0; ret = av_mallocz(sizeof(AVFilterFormats)); /* merge list of formats */ ret->formats = av_malloc(sizeof(*ret->formats) * FFMIN(a->format_count, b->format_count)); for(i = 0; i < a->format_count; i ++) for(j = 0; j < b->format_count; j ++) if(a->formats[i] == b->formats[j]) ret->formats[k++] = a->formats[i]; ret->format_count = k; /* check that there was at least one common format */ if(!ret->format_count) { av_free(ret->formats); av_free(ret); return NULL; } ret->refs = av_malloc(sizeof(AVFilterFormats**)*(a->refcount+b->refcount)); merge_ref(ret, a); merge_ref(ret, b); return ret; } AVFilterFormats *avfilter_make_format_list(int len, ...) { AVFilterFormats *ret; int i; va_list vl; ret = av_mallocz(sizeof(AVFilterFormats)); ret->formats = av_malloc(sizeof(*ret->formats) * len); ret->format_count = len; va_start(vl, len); for(i = 0; i < len; i ++) ret->formats[i] = va_arg(vl, int); va_end(vl); return ret; } AVFilterFormats *avfilter_all_colorspaces(void) { AVFilterFormats *ret; int i; ret = av_mallocz(sizeof(AVFilterFormats)); ret->formats = av_malloc(sizeof(*ret->formats) * PIX_FMT_NB); ret->format_count = PIX_FMT_NB; for(i = 0; i < PIX_FMT_NB; i ++) ret->formats[i] = i; return ret; } void avfilter_formats_ref(AVFilterFormats *f, AVFilterFormats **ref) { *ref = f; f->refs = av_realloc(f->refs, sizeof(AVFilterFormats**) * ++f->refcount); f->refs[f->refcount-1] = ref; } static int find_ref_index(AVFilterFormats **ref) { int i; for(i = 0; i < (*ref)->refcount; i ++) if((*ref)->refs[i] == ref) return i; return -1; } void avfilter_formats_unref(AVFilterFormats **ref) { int idx = find_ref_index(ref); if(idx >= 0) memmove((*ref)->refs + idx, (*ref)->refs + idx+1, sizeof(AVFilterFormats**) * ((*ref)->refcount-idx-1)); if(!--(*ref)->refcount) { av_free((*ref)->formats); av_free((*ref)->refs); av_free(*ref); } *ref = NULL; } void avfilter_formats_changeref(AVFilterFormats **oldref, AVFilterFormats **newref) { int idx = find_ref_index(oldref); if(idx >= 0) { (*oldref)->refs[idx] = newref; *newref = *oldref; *oldref = NULL; } }
183124.c
T_b("/*"); T_b("\n"); T_b(" "); T_b("* State-Event Matrix (SEM)"); T_b("\n"); T_b(" "); T_b("* Row index is object (MC enumerated) current state."); T_b("\n"); T_b(" "); T_b("* Row zero is the uninitialized state (e.g., for creation event transitions)."); T_b("\n"); T_b(" "); T_b("* Column index is (MC enumerated) state machine events."); T_b("\n"); T_b(" "); T_b("*/"); T_b("\n"); T_b("static const "); T_b(te_typemap->SEM_cell_name); T_b(" "); T_b(te_sm->SEMname); T_b("[ "); T_b(te_sm->num_states); T_b(" + 1 ][ "); T_b(num_events); T_b(" ] = {"); T_b("\n"); T_b(" "); T_b("/* row 0: uninitialized state (for creation events) */"); T_b("\n"); T_b(first_row); T_b(""); T_b(other_rows); T_b("\n"); T_b("};"); T_b("\n");
959005.c
char foo(void); char foo(void) { return 1; }
75678.c
#define R_NO_REMAP #include <R.h> #include <Rinternals.h> #include "libproj.h" #include "rproj-context.h" #include "rproj-proj.h" SEXP rproj_c_trans_matrix(SEXP pj_xptr, SEXP x_sexp, SEXP direction_sexp, SEXP verbose_sexp) { PJ* pj = rproj_pj_from_xptr(pj_xptr); PJ_CONTEXT* ctx = rproj_ctx_from_pj_xptr(pj_xptr); int direction = INTEGER(direction_sexp)[0]; int verbose = LOGICAL(verbose_sexp)[0]; int nrow = Rf_nrows(x_sexp); double* x = REAL(x_sexp); SEXP x_out_sexp = PROTECT(Rf_allocMatrix(REALSXP, nrow, 5)); double* x_out = REAL(x_out_sexp); int previous_log_level = PJ_LOG_ERROR; if (!verbose) { previous_log_level = proj_log_level(ctx, PJ_LOG_NONE); } PJ_COORD coord; for (int i = 0; i < nrow; i++) { for (int j = 0; j < 4; j++) { coord.v[j] = x[(j * nrow) + i]; } coord = proj_trans(pj, direction, coord); x_out[(4 * nrow) + i] = proj_errno(pj); for (int j = 0; j < 4; j++) { x_out[(j * nrow) + i] = coord.v[j]; } } if (!verbose) { proj_log_level(ctx, previous_log_level); } else { // if there was a logged error, the first one would have been // swallowed by the error logger SEXP ctx_xptr = R_ExternalPtrTag(pj_xptr); const char* logger_err = rproj_logger_error(ctx_xptr); if (logger_err != NULL) { REprintf("[first error was] %s\n", logger_err); } } UNPROTECT(1); return x_out_sexp; }
897270.c
/* * Microsemi Switchtec(tm) PCIe Management Library * Copyright (c) 2019, Microsemi Corporation * * 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. * */ /** * @file * @brief Switchtec core library functions for mfg operations */ /** * @defgroup mfg Manufacturing Functions * @brief Manufacturing-related API functions * * These are functions used during manufacturing process. These * includes functions that configure device security settings and * recover device from boot failures. * * Some of these functions modify device One-Time-Programming (OTP) memory, * so they should be used with great caution, and you should really * know what you are doing when calling these functions. FAILURE TO DO SO * COULD MAKE YOUR DEVICE UNBOOTABLE!! * * @{ */ #include "switchtec_priv.h" #include "switchtec/switchtec.h" #include "switchtec/mfg.h" #include "switchtec/errors.h" #include "switchtec/endian.h" #include "switchtec/mrpc.h" #include "switchtec/errors.h" #include <unistd.h> #include <errno.h> #include <stdio.h> #include <string.h> #include "lib/crc.h" #include "config.h" #ifdef __linux__ #if HAVE_LIBCRYPTO #include <openssl/pem.h> #endif #define SWITCHTEC_ACTV_IMG_ID_KMAN 1 #define SWITCHTEC_ACTV_IMG_ID_BL2 2 #define SWITCHTEC_ACTV_IMG_ID_CFG 3 #define SWITCHTEC_ACTV_IMG_ID_FW 4 #define SWITCHTEC_MB_MAX_ENTRIES 16 #define SWITCHTEC_ACTV_IDX_MAX_ENTRIES 32 #define SWITCHTEC_ACTV_IDX_SET_ENTRIES 4 #define SWITCHTEC_CLK_RATE_BITSHIFT 10 #define SWITCHTEC_CLK_RATE_BITMASK 0x0f #define SWITCHTEC_RC_TMO_BITSHIFT 14 #define SWITCHTEC_RC_TMO_BITMASK 0x0f #define SWITCHTEC_I2C_PORT_BITSHIFT 18 #define SWITCHTEC_I2C_PORT_BITMASK 0x0f #define SWITCHTEC_I2C_ADDR_BITSHIFT 22 #define SWITCHTEC_I2C_ADDR_BITMASK 0x7f #define SWITCHTEC_CMD_MAP_BITSHIFT 29 #define SWITCHTEC_CMD_MAP_BITMASK 0xfff #define SWITCHTEC_JTAG_LOCK_AFT_RST_BITMASK 0x40 #define SWITCHTEC_JTAG_LOCK_AFT_BL1_BITMASK 0x80 #define SWITCHTEC_JTAG_UNLOCK_BL1_BITMASK 0x0100 #define SWITCHTEC_JTAG_UNLOCK_AFT_BL1_BITMASK 0x0200 static int switchtec_mfg_cmd(struct switchtec_dev *dev, uint32_t cmd, const void *payload, size_t payload_len, void *resp, size_t resp_len); #if (HAVE_LIBCRYPTO && !HAVE_DECL_RSA_GET0_KEY) /** * openssl1.0 or older versions don't have this function, so copy * the code from openssl1.1 here */ static void RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d) { if (n != NULL) *n = r->n; if (e != NULL) *e = r->e; if (d != NULL) *d = r->d; } #endif /** * @brief Get secure boot configurations * @param[in] dev Switchtec device handle * @param[out] state Current secure boot settings * @return 0 on success, error code on failure */ int switchtec_security_config_get(struct switchtec_dev *dev, struct switchtec_security_cfg_state *state) { int ret; struct cfg_reply { uint32_t valid; uint32_t rsvd1; uint64_t cfg; uint32_t public_key_exponent; uint8_t rsvd2; uint8_t public_key_num; uint8_t public_key_ver; uint8_t rsvd3; uint8_t public_key[SWITCHTEC_KMSK_NUM][SWITCHTEC_KMSK_LEN]; uint8_t rsvd4[32]; } reply; ret = switchtec_mfg_cmd(dev, MRPC_SECURITY_CONFIG_GET, NULL, 0, &reply, sizeof(reply)); if (ret) return ret; reply.valid = le32toh(reply.valid); reply.cfg = le64toh(reply.cfg); reply.public_key_exponent = le32toh(reply.public_key_exponent); state->basic_setting_valid = !!(reply.valid & 0x01); state->public_key_exp_valid = !!(reply.valid & 0x02); state->public_key_num_valid = !!(reply.valid & 0x04); state->public_key_ver_valid = !!(reply.valid & 0x08); state->public_key_valid = !!(reply.valid & 0x10); state->debug_mode = reply.cfg & 0x03; state->secure_state = (reply.cfg>>2) & 0x03; state->jtag_lock_after_reset = !!(reply.cfg & 0x40); state->jtag_lock_after_bl1 = !!(reply.cfg & 0x80); state->jtag_bl1_unlock_allowed = !!(reply.cfg & 0x0100); state->jtag_post_bl1_unlock_allowed = !!(reply.cfg & 0x0200); state->spi_clk_rate = (reply.cfg >> SWITCHTEC_CLK_RATE_BITSHIFT) & 0x0f; if (state->spi_clk_rate == 0) state->spi_clk_rate = SWITCHTEC_SPI_RATE_25M; state->i2c_recovery_tmo = (reply.cfg >> SWITCHTEC_RC_TMO_BITSHIFT) & 0x0f; state->i2c_port = (reply.cfg >> SWITCHTEC_I2C_PORT_BITSHIFT) & 0xf; state->i2c_addr = (reply.cfg >> SWITCHTEC_I2C_ADDR_BITSHIFT) & 0x7f; state->i2c_cmd_map = (reply.cfg >> SWITCHTEC_CMD_MAP_BITSHIFT) & 0xfff; state->public_key_exponent = reply.public_key_exponent; state->public_key_num = reply.public_key_num; state->public_key_ver = reply.public_key_ver; memcpy(state->public_key, reply.public_key, SWITCHTEC_KMSK_NUM * SWITCHTEC_KMSK_LEN); return 0; } /** * @brief Retrieve mailbox entries * @param[in] dev Switchtec device handle * @param[in] fd File handle to write the log data * @return 0 on success, error code on failure */ int switchtec_mailbox_to_file(struct switchtec_dev *dev, int fd) { int ret; int num_to_read = htole32(SWITCHTEC_MB_MAX_ENTRIES); struct mb_reply { uint8_t num_returned; uint8_t num_remaining; uint8_t rsvd[2]; uint8_t data[SWITCHTEC_MB_MAX_ENTRIES * SWITCHTEC_MB_LOG_LEN]; } reply; do { ret = switchtec_mfg_cmd(dev, MRPC_MAILBOX_GET, &num_to_read, sizeof(int), &reply, sizeof(reply)); if (ret) return ret; reply.num_remaining = le32toh(reply.num_remaining); reply.num_returned = le32toh(reply.num_returned); ret = write(fd, reply.data, (reply.num_returned) * SWITCHTEC_MB_LOG_LEN); if (ret < 0) return ret; } while (reply.num_remaining > 0); return 0; } /** * @brief Set secure settings * @param[in] dev Switchtec device handle * @param[out] setting Secure boot settings * @return 0 on success, error code on failure */ int switchtec_security_config_set(struct switchtec_dev *dev, struct switchtec_security_cfg_set *setting) { int ret; struct setting_data { uint64_t cfg; uint32_t pub_key_exponent; uint8_t rsvd[4]; } sd; uint64_t ldata = 0; memset(&sd, 0, sizeof(sd)); sd.cfg |= setting->jtag_lock_after_reset? SWITCHTEC_JTAG_LOCK_AFT_RST_BITMASK : 0; sd.cfg |= setting->jtag_lock_after_bl1? SWITCHTEC_JTAG_LOCK_AFT_BL1_BITMASK : 0; sd.cfg |= setting->jtag_bl1_unlock_allowed? SWITCHTEC_JTAG_UNLOCK_BL1_BITMASK : 0; sd.cfg |= setting->jtag_post_bl1_unlock_allowed? SWITCHTEC_JTAG_UNLOCK_AFT_BL1_BITMASK : 0; sd.cfg |= (setting->spi_clk_rate & SWITCHTEC_CLK_RATE_BITMASK) << SWITCHTEC_CLK_RATE_BITSHIFT; sd.cfg |= (setting->i2c_recovery_tmo & SWITCHTEC_RC_TMO_BITMASK) << SWITCHTEC_RC_TMO_BITSHIFT; sd.cfg |= (setting->i2c_port & SWITCHTEC_I2C_PORT_BITMASK) << SWITCHTEC_I2C_PORT_BITSHIFT; sd.cfg |= (setting->i2c_addr & SWITCHTEC_I2C_ADDR_BITMASK) << SWITCHTEC_I2C_ADDR_BITSHIFT; ldata = setting->i2c_cmd_map & SWITCHTEC_CMD_MAP_BITMASK; ldata <<= SWITCHTEC_CMD_MAP_BITSHIFT; sd.cfg |= ldata; sd.cfg = htole64(sd.cfg); sd.pub_key_exponent = htole32(setting->public_key_exponent); ret = switchtec_mfg_cmd(dev, MRPC_SECURITY_CONFIG_SET, &sd, sizeof(sd), NULL, 0); return ret; } /** * @brief Get active image index * @param[in] dev Switchtec device handle * @param[out] index Active images indices * @return 0 on success, error code on failure */ int switchtec_active_image_index_get(struct switchtec_dev *dev, struct switchtec_active_index *index) { int ret; struct active_indices { uint8_t index[SWITCHTEC_ACTV_IDX_MAX_ENTRIES]; } reply; ret = switchtec_mfg_cmd(dev, MRPC_ACT_IMG_IDX_GET, NULL, 0, &reply, sizeof(reply)); if (ret) return ret; index->keyman = reply.index[SWITCHTEC_ACTV_IMG_ID_KMAN]; index->bl2 = reply.index[SWITCHTEC_ACTV_IMG_ID_BL2]; index->config = reply.index[SWITCHTEC_ACTV_IMG_ID_CFG]; index->firmware = reply.index[SWITCHTEC_ACTV_IMG_ID_FW]; return 0; } /** * @brief Set active image index * @param[in] dev Switchtec device handle * @param[in] index Active image indices * @return 0 on success, error code on failure */ int switchtec_active_image_index_set(struct switchtec_dev *dev, struct switchtec_active_index *index) { int ret; int i = 0; struct active_idx { uint32_t count; struct entry { uint8_t image_id; uint8_t index; } idx[SWITCHTEC_ACTV_IDX_SET_ENTRIES]; } set; memset(&set, 0, sizeof(set)); if (index->keyman != SWITCHTEC_ACTIVE_INDEX_NOT_SET) { set.idx[i].image_id = SWITCHTEC_ACTV_IMG_ID_KMAN; set.idx[i].index = index->keyman; i++; } if (index->bl2 != SWITCHTEC_ACTIVE_INDEX_NOT_SET) { set.idx[i].image_id = SWITCHTEC_ACTV_IMG_ID_BL2; set.idx[i].index = index->bl2; i++; } if (index->config != SWITCHTEC_ACTIVE_INDEX_NOT_SET) { set.idx[i].image_id = SWITCHTEC_ACTV_IMG_ID_CFG; set.idx[i].index = index->config; i++; } if (index->firmware != SWITCHTEC_ACTIVE_INDEX_NOT_SET) { set.idx[i].image_id = SWITCHTEC_ACTV_IMG_ID_FW; set.idx[i].index = index->firmware; i++; } if (i == 0) return 0; set.count = htole32(i); ret = switchtec_mfg_cmd(dev, MRPC_ACT_IMG_IDX_SET, &set, sizeof(set), NULL, 0); return ret; } /** * @brief Execute the transferred firmware * @param[in] dev Switchtec device handle * @param[in] recovery_mode Recovery mode in case of a boot failure * @return 0 on success, error code on failure */ int switchtec_fw_exec(struct switchtec_dev *dev, enum switchtec_bl2_recovery_mode recovery_mode) { struct fw_exec_struct { uint8_t subcmd; uint8_t recovery_mode; uint8_t rsvd[2]; } cmd; memset(&cmd, 0, sizeof(cmd)); cmd.subcmd = MRPC_FW_TX_EXEC; cmd.recovery_mode = recovery_mode; return switchtec_mfg_cmd(dev, MRPC_FW_TX, &cmd, sizeof(cmd), NULL, 0); } /** * @brief Resume device boot. * Note that after calling this function, the current * 'dev' pointer is no longer valid. Before making further * calls to switchtec library functions, be sure to close * this pointer and get a new one by calling switchtec_open(). * Also be sure to check the return value of switchtec_open() * for error, as the device might not be immediately * accessible after normal boot process. * @param[in] dev Switchtec device handle * @return 0 on success, error code on failure */ int switchtec_boot_resume(struct switchtec_dev *dev) { return switchtec_mfg_cmd(dev, MRPC_BOOTUP_RESUME, NULL, 0, NULL, 0); } /** * @brief Set device secure state * @param[in] dev Switchtec device handle * @param[in] state Secure state * @return 0 on success, error code on failure */ int switchtec_secure_state_set(struct switchtec_dev *dev, enum switchtec_secure_state state) { uint32_t data; if ((state != SWITCHTEC_INITIALIZED_UNSECURED) && (state != SWITCHTEC_INITIALIZED_SECURED)) { return ERR_PARAM_INVALID; } data = htole32(state); return switchtec_mfg_cmd(dev, MRPC_SECURE_STATE_SET, &data, sizeof(data), NULL, 0); } static int dbg_unlock_send_pubkey(struct switchtec_dev *dev, struct switchtec_pubkey *public_key) { struct public_key_cmd { uint8_t subcmd; uint8_t rsvd[3]; uint8_t pub_key[SWITCHTEC_PUB_KEY_LEN]; uint32_t pub_key_exp; } cmd = {}; cmd.subcmd = MRPC_DBG_UNLOCK_PKEY; memcpy(cmd.pub_key, public_key->pubkey, SWITCHTEC_PUB_KEY_LEN); cmd.pub_key_exp = htole32(public_key->pubkey_exp); return switchtec_mfg_cmd(dev, MRPC_DBG_UNLOCK, &cmd, sizeof(cmd), NULL, 0); } /** * @brief Unlock firmware debug features * @param[in] dev Switchtec device handle * @param[in] serial Device serial number * @param[in] ver_sec_unlock Secure unlock version * @param[in] public_key public key data * @param[in] signature Signature of data sent * @return 0 on success, error code on failure */ int switchtec_dbg_unlock(struct switchtec_dev *dev, uint32_t serial, uint32_t ver_sec_unlock, struct switchtec_pubkey *public_key, struct switchtec_signature *signature) { int ret; struct unlock_cmd { uint8_t subcmd; uint8_t rsvd[3]; uint32_t serial; uint32_t unlock_ver; uint8_t signature[SWITCHTEC_SIG_LEN]; } cmd = {}; ret = dbg_unlock_send_pubkey(dev, public_key); if (ret) return ret; cmd.subcmd = MRPC_DBG_UNLOCK_DATA; cmd.serial = htole32(serial); cmd.unlock_ver = htole32(ver_sec_unlock); memcpy(cmd.signature, signature->signature, SWITCHTEC_SIG_LEN); return switchtec_mfg_cmd(dev, MRPC_DBG_UNLOCK, &cmd, sizeof(cmd), NULL, 0); } /** * @brief Update firmware debug secure unlock version number * @param[in] dev Switchtec device handle * @param[in] serial Device serial number * @param[in] ver_sec_unlock New secure unlock version * @param[in] public_key public key data * @param[in] signature Signature of data sent * @return 0 on success, error code on failure */ int switchtec_dbg_unlock_version_update(struct switchtec_dev *dev, uint32_t serial, uint32_t ver_sec_unlock, struct switchtec_pubkey *public_key, struct switchtec_signature *signature) { int ret; struct update_cmd { uint8_t subcmd; uint8_t rsvd[3]; uint32_t serial; uint32_t unlock_ver; uint8_t signature[SWITCHTEC_SIG_LEN]; } cmd = {}; ret = dbg_unlock_send_pubkey(dev, public_key); if (ret) return ret; cmd.subcmd = MRPC_DBG_UNLOCK_UPDATE; cmd.serial = htole32(serial); cmd.unlock_ver = htole32(ver_sec_unlock); memcpy(cmd.signature, signature->signature, SWITCHTEC_SIG_LEN); return switchtec_mfg_cmd(dev, MRPC_DBG_UNLOCK, &cmd, sizeof(cmd), NULL, 0); } /** * @brief Read security settings from config file * @param[in] setting_file Security setting file * @param[out] set Security settings * @return 0 on success, error code on failure */ int switchtec_read_sec_cfg_file(FILE *setting_file, struct switchtec_security_cfg_set *set) { ssize_t rlen; char magic[4] = {'S', 'S', 'F', 'F'}; uint32_t crc; struct setting_file_header { uint8_t magic[4]; uint32_t version; uint32_t rsvd; uint32_t crc; }; struct setting_file_data { uint64_t cfg; uint32_t pub_key_exponent; uint8_t rsvd[36]; }; struct setting_file { struct setting_file_header header; struct setting_file_data data; } file_data; rlen = fread(&file_data, 1, sizeof(file_data), setting_file); if (rlen < sizeof(file_data)) return -EBADF; if (memcmp(file_data.header.magic, magic, sizeof(magic))) return -EBADF; crc = crc32((uint8_t*)&file_data.data, sizeof(file_data.data), 0, 1, 1); if (crc != le32toh(file_data.header.crc)) return -EBADF; memset(set, 0, sizeof(struct switchtec_security_cfg_set)); file_data.data.cfg = le64toh(file_data.data.cfg); set->jtag_lock_after_reset = !!(file_data.data.cfg & SWITCHTEC_JTAG_LOCK_AFT_RST_BITMASK); set->jtag_lock_after_bl1 = !!(file_data.data.cfg & SWITCHTEC_JTAG_LOCK_AFT_BL1_BITMASK); set->jtag_bl1_unlock_allowed = !!(file_data.data.cfg & SWITCHTEC_JTAG_UNLOCK_BL1_BITMASK); set->jtag_post_bl1_unlock_allowed = !!(file_data.data.cfg & SWITCHTEC_JTAG_UNLOCK_AFT_BL1_BITMASK); set->spi_clk_rate = (file_data.data.cfg >> SWITCHTEC_CLK_RATE_BITSHIFT) & SWITCHTEC_CLK_RATE_BITMASK; set->i2c_recovery_tmo = (file_data.data.cfg >> SWITCHTEC_RC_TMO_BITSHIFT) & SWITCHTEC_RC_TMO_BITMASK; set->i2c_port = (file_data.data.cfg >> SWITCHTEC_I2C_PORT_BITSHIFT) & SWITCHTEC_I2C_PORT_BITMASK; set->i2c_addr = (file_data.data.cfg >> SWITCHTEC_I2C_ADDR_BITSHIFT) & SWITCHTEC_I2C_ADDR_BITMASK; set->i2c_cmd_map = (file_data.data.cfg >> SWITCHTEC_CMD_MAP_BITSHIFT) & SWITCHTEC_CMD_MAP_BITMASK; set->public_key_exponent = le32toh(file_data.data.pub_key_exponent); return 0; } static int kmsk_set_send_pubkey(struct switchtec_dev *dev, struct switchtec_pubkey *public_key) { struct kmsk_pubk_cmd { uint8_t subcmd; uint8_t reserved[3]; uint8_t pub_key[SWITCHTEC_PUB_KEY_LEN]; uint32_t pub_key_exponent; } cmd = {}; cmd.subcmd = MRPC_KMSK_ENTRY_SET_PKEY; memcpy(cmd.pub_key, public_key->pubkey, SWITCHTEC_PUB_KEY_LEN); cmd.pub_key_exponent = htole32(public_key->pubkey_exp); return switchtec_mfg_cmd(dev, MRPC_KMSK_ENTRY_SET, &cmd, sizeof(cmd), NULL, 0); } static int kmsk_set_send_signature(struct switchtec_dev *dev, struct switchtec_signature *signature) { struct kmsk_signature_cmd { uint8_t subcmd; uint8_t reserved[3]; uint8_t signature[SWITCHTEC_SIG_LEN]; } cmd = {}; cmd.subcmd = MRPC_KMSK_ENTRY_SET_SIG; memcpy(cmd.signature, signature->signature, SWITCHTEC_SIG_LEN); return switchtec_mfg_cmd(dev, MRPC_KMSK_ENTRY_SET, &cmd, sizeof(cmd), NULL, 0); } static int kmsk_set_send_kmsk(struct switchtec_dev *dev, struct switchtec_kmsk *kmsk) { struct kmsk_kmsk_cmd { uint8_t subcmd; uint8_t num_entries; uint8_t reserved[2]; uint8_t kmsk[SWITCHTEC_KMSK_LEN]; } cmd = {}; cmd.subcmd = MRPC_KMSK_ENTRY_SET_KMSK; cmd.num_entries = 1; memcpy(cmd.kmsk, kmsk->kmsk, SWITCHTEC_KMSK_LEN); return switchtec_mfg_cmd(dev, MRPC_KMSK_ENTRY_SET, &cmd, sizeof(cmd), NULL, 0); } /** * @brief Set KMSK entry * KMSK stands for Key Manifest Secure Key. * It is a key used to verify Key Manifest * partition, which contains keys to verify * all other partitions. * @param[in] dev Switchtec device handle * @param[in] public_key Public key * @param[in] signature Signature * @param[in] kmsk KMSK entry data * @return 0 on success, error code on failure */ int switchtec_kmsk_set(struct switchtec_dev *dev, struct switchtec_pubkey *public_key, struct switchtec_signature *signature, struct switchtec_kmsk *kmsk) { int ret; if (public_key) { ret = kmsk_set_send_pubkey(dev, public_key); if (ret) return ret; } if (signature) { ret = kmsk_set_send_signature(dev, signature); if (ret) return ret; } return kmsk_set_send_kmsk(dev, kmsk); } #if HAVE_LIBCRYPTO /** * @brief Read public key from public key file * @param[in] pubk_file Public key file * @param[out] pubk Public key * @return 0 on success, error code on failure */ int switchtec_read_pubk_file(FILE *pubk_file, struct switchtec_pubkey *pubk) { RSA *RSAKey = NULL; const BIGNUM *modulus_bn; const BIGNUM *exponent_bn; uint32_t exponent_tmp = 0; RSAKey = PEM_read_RSA_PUBKEY(pubk_file, NULL, NULL, NULL); if (RSAKey == NULL) { fseek(pubk_file, 0L, SEEK_SET); RSAKey = PEM_read_RSAPrivateKey(pubk_file, NULL, NULL, NULL); if (RSAKey == NULL) return -1; } RSA_get0_key(RSAKey, &modulus_bn, &exponent_bn, NULL); BN_bn2bin(modulus_bn, pubk->pubkey); BN_bn2bin(exponent_bn, (uint8_t *)&exponent_tmp); pubk->pubkey_exp = be32toh(exponent_tmp); RSA_free(RSAKey); return 0; } #endif /** * @brief Read KMSK data from KMSK file * @param[in] kmsk_file KMSK file * @param[out] kmsk KMSK entry data * @return 0 on success, error code on failure */ int switchtec_read_kmsk_file(FILE *kmsk_file, struct switchtec_kmsk *kmsk) { ssize_t rlen; struct kmsk_struct { uint8_t magic[4]; uint32_t version; uint32_t reserved; uint32_t crc32; uint8_t kmsk[SWITCHTEC_KMSK_LEN]; } data; char magic[4] = {'K', 'M', 'S', 'K'}; uint32_t crc; rlen = fread(&data, 1, sizeof(data), kmsk_file); if (rlen < sizeof(data)) return -EBADF; if (memcmp(data.magic, magic, sizeof(magic))) return -EBADF; crc = crc32(data.kmsk, SWITCHTEC_KMSK_LEN, 0, 1, 1); if (crc != le32toh(data.crc32)) return -EBADF; memcpy(kmsk->kmsk, data.kmsk, SWITCHTEC_KMSK_LEN); return 0; } /** * @brief Read signature data from signature file * @param[in] sig_file Signature file * @param[out] signature Signature data * @return 0 on success, error code on failure */ int switchtec_read_signature_file(FILE *sig_file, struct switchtec_signature *signature) { ssize_t rlen; rlen = fread(signature->signature, 1, SWITCHTEC_SIG_LEN, sig_file); if (rlen < SWITCHTEC_SIG_LEN) return -EBADF; return 0; } /** * @brief Check if secure config already has a KMSK entry * KMSK stands for Key Manifest Secure Key. * It is a key used to verify Key Manifest * partition, which contains keys used to * verify all other partitions. * @param[in] state Secure config * @param[out] kmsk KMSK entry to check for * @return 0 on success, error code on failure */ int switchtec_security_state_has_kmsk(struct switchtec_security_cfg_state *state, struct switchtec_kmsk *kmsk) { int key_idx; for(key_idx = 0; key_idx < state->public_key_num; key_idx++) { if (memcmp(state->public_key[key_idx], kmsk->kmsk, SWITCHTEC_KMSK_LEN) == 0) return 1; } return 0; } #endif /* __linux__ */ static int switchtec_mfg_cmd(struct switchtec_dev *dev, uint32_t cmd, const void *payload, size_t payload_len, void *resp, size_t resp_len) { if (dev->ops->flags & SWITCHTEC_OPS_FLAG_NO_MFG) { errno = ERR_UART_NOT_SUPPORTED | SWITCHTEC_ERRNO_MRPC_FLAG_BIT; return -1; } return switchtec_cmd(dev, cmd, payload, payload_len, resp, resp_len); } /** * @brief Get serial number and security version * @param[in] dev Switchtec device handle * @param[out] info Serial number and security version info * @return 0 on success, error code on failure */ int switchtec_sn_ver_get(struct switchtec_dev *dev, struct switchtec_sn_ver_info *info) { int ret; ret = switchtec_mfg_cmd(dev, MRPC_SN_VER_GET, NULL, 0, info, sizeof(struct switchtec_sn_ver_info)); if (ret) return ret; info->chip_serial = le32toh(info->chip_serial); info->ver_bl2 = le32toh(info->ver_bl2); info->ver_km = le32toh(info->ver_km); info->ver_main = le32toh(info->ver_main); info->ver_sec_unlock = le32toh(info->ver_sec_unlock); return 0; } /**@}*/
502608.c
int XXX(int n){ if(n < 0){ return 0; } if(n==1 || n==0){ return 1; }else{ return XXX(n-1) + XXX(n-2); } }
163462.c
/* * librdkafka - Apache Kafka C library * * Copyright (c) 2012-2015, Magnus Edenhill * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "test.h" #if WITH_SOCKEM #include "rdkafka.h" #include <stdarg.h> /** * @name Verify #1985: * * Previously known topic transitions to UNKNOWN when metadata times out, * new messages are put on UA, when brokers come up again and metadata * is retrieved the UA messages must be produced. */ static rd_atomic32_t refuse_connect; /** * @brief Sockem connect, called from **internal librdkafka thread** through * librdkafka's connect_cb */ static int connect_cb (struct test *test, sockem_t *skm, const char *id) { if (rd_atomic32_get(&refuse_connect) > 0) return -1; else return 0; } static int is_fatal_cb (rd_kafka_t *rk, rd_kafka_resp_err_t err, const char *reason) { /* Ignore connectivity errors since we'll be bringing down * .. connectivity. * SASL auther will think a connection-down even in the auth * state means the broker doesn't support SASL PLAIN. */ TEST_SAY("is_fatal?: %s: %s\n", rd_kafka_err2str(err), reason); if (err == RD_KAFKA_RESP_ERR__TRANSPORT || err == RD_KAFKA_RESP_ERR__ALL_BROKERS_DOWN || err == RD_KAFKA_RESP_ERR__AUTHENTICATION || err == RD_KAFKA_RESP_ERR__TIMED_OUT) return 0; return 1; } static int msg_dr_cnt = 0; static int msg_dr_fail_cnt = 0; static void dr_msg_cb (rd_kafka_t *rk, const rd_kafka_message_t *rkmessage, void *opaque) { msg_dr_cnt++; TEST_SAYL(3, "Delivery for message %.*s: %s\n", (int)rkmessage->len, (const char *)rkmessage->payload, rd_kafka_err2name(rkmessage->err)); if (rkmessage->err) { TEST_FAIL_LATER("Expected message to succeed, got %s", rd_kafka_err2str(rkmessage->err)); msg_dr_fail_cnt++; } } int main_0088_produce_metadata_timeout (int argc, char **argv) { int64_t testid; rd_kafka_t *rk; rd_kafka_topic_t *rkt; const char *topic = test_mk_topic_name("0088_produce_metadata_timeout", 1); int msgcnt = 0; rd_kafka_conf_t *conf; testid = test_id_generate(); /* Create topic with single partition, for simplicity. */ test_create_topic(topic, 1, 1); test_conf_init(&conf, NULL, 15*60*2); // msgcnt * 2); rd_kafka_conf_set_dr_msg_cb(conf, dr_msg_cb); test_conf_set(conf, "metadata.max.age.ms", "10000"); test_conf_set(conf, "topic.metadata.refresh.interval.ms", "-1"); test_conf_set(conf, "linger.ms", "5000"); test_conf_set(conf, "batch.num.messages", "5"); test_socket_enable(conf); test_curr->connect_cb = connect_cb; test_curr->is_fatal_cb = is_fatal_cb; rk = test_create_handle(RD_KAFKA_PRODUCER, conf); rkt = rd_kafka_topic_new(rk, topic, NULL); /* Produce first set of messages and wait for delivery */ test_produce_msgs_nowait(rk, rkt, testid, RD_KAFKA_PARTITION_UA, msgcnt, 20, NULL, 0, &msgcnt); while (msg_dr_cnt < 5) rd_kafka_poll(rk, 1000); TEST_SAY(_C_YEL "Disconnecting sockets and " "refusing future connections\n"); rd_atomic32_set(&refuse_connect, 1); test_socket_close_all(test_curr, 1/*reinit*/); /* Wait for metadata timeout */ TEST_SAY("Waiting for metadata timeout\n"); rd_sleep(10+5); /* These messages will be put on the UA queue */ test_produce_msgs_nowait(rk, rkt, testid, RD_KAFKA_PARTITION_UA, msgcnt, 20, NULL, 0, &msgcnt); /* Restore the connection(s) when metadata has timed out. */ TEST_SAY(_C_YEL "Allowing connections\n"); rd_atomic32_set(&refuse_connect, 0); rd_sleep(3); test_produce_msgs_nowait(rk, rkt, testid, RD_KAFKA_PARTITION_UA, msgcnt, 20, NULL, 0, &msgcnt); test_flush(rk, 2*5*1000); /* linger.ms * 2 */ TEST_ASSERT(msg_dr_cnt == msgcnt, "expected %d, got %d", msgcnt, msg_dr_cnt); TEST_ASSERT(msg_dr_fail_cnt == 0, "expected %d dr failures, got %d", 0, msg_dr_fail_cnt); rd_kafka_topic_destroy(rkt); rd_kafka_destroy(rk); return 0; } #endif
144324.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE272_Least_Privilege_Violation__w32_wchar_t_CreateProcessAsUser_13.c Label Definition File: CWE272_Least_Privilege_Violation__w32.label.xml Template File: point-flaw-13.tmpl.c */ /* * @description * CWE: 272 Least Privilege Violation * Sinks: CreateProcessAsUser * GoodSink: Create a process using CreateProcessAsUserW() with quotes for the executable path * BadSink : Create a process using CreateProcessAsUserW() without quotes for the executable path * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) * * */ #include "std_testcase.h" #include <windows.h> #pragma comment(lib, "advapi32.lib") #ifndef OMITBAD void CWE272_Least_Privilege_Violation__w32_wchar_t_CreateProcessAsUser_13_bad() { if(GLOBAL_CONST_FIVE==5) { { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE pHandle = NULL; /* FLAW: The commandLine parameter to CreateProcessAsUser() contains a space in it and does not surround the executable path with quotes. A malicious executable could be run because of the way the function parses spaces. The process will attempt to run "Program.exe," if it exists, instead of the intended "GoodApp.exe" */ if(!CreateProcessAsUserW(pHandle, NULL, L"C:\\Program Files\\GoodApp arg1 arg2", NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi)) { printLine("CreateProcessAsUser failed"); RevertToSelf(); CloseHandle(pHandle); return; } else { printLine("CreateProcessAUser successful"); } /* Wait until child process exits. */ WaitForSingleObject(pi.hProcess, INFINITE); /* Close process and thread handles.*/ CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(pHandle); } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(GLOBAL_CONST_FIVE!=5) instead of if(GLOBAL_CONST_FIVE==5) */ static void good1() { if(GLOBAL_CONST_FIVE!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE pHandle = NULL; /* FIX: The commandLine parameter to CreateProcessAsUser() contains quotes surrounding the executable path. */ if(!CreateProcessAsUserW(pHandle, NULL, L"\"C:\\Program Files\\GoodApp\" arg1 arg2", NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi)) { printLine("CreateProcessAsUser failed"); RevertToSelf(); CloseHandle(pHandle); return; } else { printLine("CreateProcessAUser successful"); } /* Wait until child process exits. */ WaitForSingleObject(pi.hProcess, INFINITE); /* Close process and thread handles.*/ CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(pHandle); } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(GLOBAL_CONST_FIVE==5) { { STARTUPINFOW si; PROCESS_INFORMATION pi; HANDLE pHandle = NULL; /* FIX: The commandLine parameter to CreateProcessAsUser() contains quotes surrounding the executable path. */ if(!CreateProcessAsUserW(pHandle, NULL, L"\"C:\\Program Files\\GoodApp\" arg1 arg2", NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &si, &pi)) { printLine("CreateProcessAsUser failed"); RevertToSelf(); CloseHandle(pHandle); return; } else { printLine("CreateProcessAUser successful"); } /* Wait until child process exits. */ WaitForSingleObject(pi.hProcess, INFINITE); /* Close process and thread handles.*/ CloseHandle(pi.hProcess); CloseHandle(pi.hThread); CloseHandle(pHandle); } } } void CWE272_Least_Privilege_Violation__w32_wchar_t_CreateProcessAsUser_13_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE272_Least_Privilege_Violation__w32_wchar_t_CreateProcessAsUser_13_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE272_Least_Privilege_Violation__w32_wchar_t_CreateProcessAsUser_13_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
304176.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { int i = 0, aux = 0, tamDolares = 0, tamCentavos = 0; char dolares[20], centavos[5]; while(scanf("%s", dolares) != EOF) { scanf("%s", centavos); i = 0; aux = strlen(dolares) % 3; tamDolares = strlen(dolares); // guarda o tamanho da string dolares tamCentavos = strlen(centavos); // guarda o tamanho da string centavos if(aux == 0) aux = 3; printf("$"); while(i < tamDolares) { if(aux > 0) { printf("%c", dolares[i]); aux--; }else { printf(",%c", dolares[i]); aux = 2; } i++; } printf("."); if(tamCentavos == 1) { printf("0%c\n", centavos[0]); }else { printf("%c%c\n", centavos[0], centavos[1]); } } return 0; }
323630.c
#include <stdio.h> int main() { int a,i; printf("\nEnter a single digit integer:"); scanf("%d",&a); for(i=1;i<11;i++) { printf("\n%d x %d=%d",a,i,a*i); } return 0; }
483979.c
/* Unix SMB/CIFS implementation. RPC pipe client Copyright (C) Gerald Carter 2001-2005, Copyright (C) Tim Potter 2000-2002, Copyright (C) Andrew Tridgell 1994-2000, Copyright (C) Jean-Francois Micouleau 1999-2000. Copyright (C) Jeremy Allison 2005. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "includes.h" #include "../librpc/gen_ndr/cli_spoolss.h" /********************************************************************** convencience wrapper around rpccli_spoolss_OpenPrinterEx **********************************************************************/ WERROR rpccli_spoolss_openprinter_ex(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *printername, uint32_t access_desired, struct policy_handle *handle) { NTSTATUS status; WERROR werror; struct spoolss_DevmodeContainer devmode_ctr; union spoolss_UserLevel userlevel; struct spoolss_UserLevel1 level1; ZERO_STRUCT(devmode_ctr); level1.size = 28; level1.client = talloc_asprintf(mem_ctx, "\\\\%s", global_myname()); W_ERROR_HAVE_NO_MEMORY(level1.client); level1.user = cli->auth->user_name; level1.build = 1381; level1.major = 2; level1.minor = 0; level1.processor = 0; userlevel.level1 = &level1; status = rpccli_spoolss_OpenPrinterEx(cli, mem_ctx, printername, NULL, devmode_ctr, access_desired, 1, /* level */ userlevel, handle, &werror); if (!W_ERROR_IS_OK(werror)) { return werror; } if (!NT_STATUS_IS_OK(status)) { return ntstatus_to_werror(status); } return WERR_OK; } /********************************************************************** convencience wrapper around rpccli_spoolss_GetPrinterDriver **********************************************************************/ WERROR rpccli_spoolss_getprinterdriver(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, const char *architecture, uint32_t level, uint32_t offered, union spoolss_DriverInfo *info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_GetPrinterDriver(cli, mem_ctx, handle, architecture, level, (offered > 0) ? &buffer : NULL, offered, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_GetPrinterDriver(cli, mem_ctx, handle, architecture, level, &buffer, offered, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_GetPrinterDriver2 **********************************************************************/ WERROR rpccli_spoolss_getprinterdriver2(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, const char *architecture, uint32_t level, uint32_t offered, uint32_t client_major_version, uint32_t client_minor_version, union spoolss_DriverInfo *info, uint32_t *server_major_version, uint32_t *server_minor_version) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_GetPrinterDriver2(cli, mem_ctx, handle, architecture, level, (offered > 0) ? &buffer : NULL, offered, client_major_version, client_minor_version, info, &needed, server_major_version, server_minor_version, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_GetPrinterDriver2(cli, mem_ctx, handle, architecture, level, &buffer, offered, client_major_version, client_minor_version, info, &needed, server_major_version, server_minor_version, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_AddPrinterEx **********************************************************************/ WERROR rpccli_spoolss_addprinterex(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct spoolss_SetPrinterInfoCtr *info_ctr) { WERROR result; NTSTATUS status; struct spoolss_DevmodeContainer devmode_ctr; struct sec_desc_buf secdesc_ctr; struct spoolss_UserLevelCtr userlevel_ctr; struct spoolss_UserLevel1 level1; struct policy_handle handle; ZERO_STRUCT(devmode_ctr); ZERO_STRUCT(secdesc_ctr); level1.size = 28; level1.build = 1381; level1.major = 2; level1.minor = 0; level1.processor = 0; level1.client = talloc_asprintf(mem_ctx, "\\\\%s", global_myname()); W_ERROR_HAVE_NO_MEMORY(level1.client); level1.user = cli->auth->user_name; userlevel_ctr.level = 1; userlevel_ctr.user_info.level1 = &level1; status = rpccli_spoolss_AddPrinterEx(cli, mem_ctx, cli->srv_name_slash, info_ctr, &devmode_ctr, &secdesc_ctr, &userlevel_ctr, &handle, &result); return result; } /********************************************************************** convencience wrapper around rpccli_spoolss_GetPrinter **********************************************************************/ WERROR rpccli_spoolss_getprinter(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, uint32_t level, uint32_t offered, union spoolss_PrinterInfo *info) { NTSTATUS status; WERROR werror; DATA_BLOB buffer; uint32_t needed; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_GetPrinter(cli, mem_ctx, handle, level, (offered > 0) ? &buffer : NULL, offered, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_GetPrinter(cli, mem_ctx, handle, level, &buffer, offered, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_GetJob **********************************************************************/ WERROR rpccli_spoolss_getjob(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, uint32_t job_id, uint32_t level, uint32_t offered, union spoolss_JobInfo *info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_GetJob(cli, mem_ctx, handle, job_id, level, (offered > 0) ? &buffer : NULL, offered, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_GetJob(cli, mem_ctx, handle, job_id, level, &buffer, offered, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumForms **********************************************************************/ WERROR rpccli_spoolss_enumforms(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_FormInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumForms(cli, mem_ctx, handle, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumForms(cli, mem_ctx, handle, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrintProcessors **********************************************************************/ WERROR rpccli_spoolss_enumprintprocessors(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *servername, const char *environment, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_PrintProcessorInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumPrintProcessors(cli, mem_ctx, servername, environment, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumPrintProcessors(cli, mem_ctx, servername, environment, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrintProcDataTypes **********************************************************************/ WERROR rpccli_spoolss_enumprintprocessordatatypes(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *servername, const char *print_processor_name, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_PrintProcDataTypesInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumPrintProcDataTypes(cli, mem_ctx, servername, print_processor_name, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumPrintProcDataTypes(cli, mem_ctx, servername, print_processor_name, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPorts **********************************************************************/ WERROR rpccli_spoolss_enumports(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *servername, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_PortInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumPorts(cli, mem_ctx, servername, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumPorts(cli, mem_ctx, servername, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumMonitors **********************************************************************/ WERROR rpccli_spoolss_enummonitors(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *servername, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_MonitorInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumMonitors(cli, mem_ctx, servername, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumMonitors(cli, mem_ctx, servername, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumJobs **********************************************************************/ WERROR rpccli_spoolss_enumjobs(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, uint32_t firstjob, uint32_t numjobs, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_JobInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumJobs(cli, mem_ctx, handle, firstjob, numjobs, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumJobs(cli, mem_ctx, handle, firstjob, numjobs, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrinterDrivers **********************************************************************/ WERROR rpccli_spoolss_enumprinterdrivers(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, const char *server, const char *environment, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_DriverInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumPrinterDrivers(cli, mem_ctx, server, environment, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumPrinterDrivers(cli, mem_ctx, server, environment, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrinters **********************************************************************/ WERROR rpccli_spoolss_enumprinters(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, uint32_t flags, const char *server, uint32_t level, uint32_t offered, uint32_t *count, union spoolss_PrinterInfo **info) { NTSTATUS status; WERROR werror; uint32_t needed; DATA_BLOB buffer; if (offered > 0) { buffer = data_blob_talloc_zero(mem_ctx, offered); W_ERROR_HAVE_NO_MEMORY(buffer.data); } status = rpccli_spoolss_EnumPrinters(cli, mem_ctx, flags, server, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_INSUFFICIENT_BUFFER)) { offered = needed; buffer = data_blob_talloc_zero(mem_ctx, needed); W_ERROR_HAVE_NO_MEMORY(buffer.data); status = rpccli_spoolss_EnumPrinters(cli, mem_ctx, flags, server, level, (offered > 0) ? &buffer : NULL, offered, count, info, &needed, &werror); } return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_GetPrinterData **********************************************************************/ WERROR rpccli_spoolss_getprinterdata(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, const char *value_name, uint32_t offered, enum winreg_Type *type, uint32_t *needed_p, uint8_t **data_p) { NTSTATUS status; WERROR werror; uint32_t needed; uint8_t *data; data = talloc_zero_array(mem_ctx, uint8_t, offered); W_ERROR_HAVE_NO_MEMORY(data); status = rpccli_spoolss_GetPrinterData(cli, mem_ctx, handle, value_name, type, data, offered, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_MORE_DATA)) { offered = needed; data = talloc_zero_array(mem_ctx, uint8_t, offered); W_ERROR_HAVE_NO_MEMORY(data); status = rpccli_spoolss_GetPrinterData(cli, mem_ctx, handle, value_name, type, data, offered, &needed, &werror); } *data_p = data; *needed_p = needed; return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrinterKey **********************************************************************/ WERROR rpccli_spoolss_enumprinterkey(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, const char *key_name, const char ***key_buffer, uint32_t offered) { NTSTATUS status; WERROR werror; uint32_t needed; union spoolss_KeyNames _key_buffer; uint32_t _ndr_size; status = rpccli_spoolss_EnumPrinterKey(cli, mem_ctx, handle, key_name, &_ndr_size, &_key_buffer, offered, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_MORE_DATA)) { offered = needed; status = rpccli_spoolss_EnumPrinterKey(cli, mem_ctx, handle, key_name, &_ndr_size, &_key_buffer, offered, &needed, &werror); } *key_buffer = _key_buffer.string_array; return werror; } /********************************************************************** convencience wrapper around rpccli_spoolss_EnumPrinterDataEx **********************************************************************/ WERROR rpccli_spoolss_enumprinterdataex(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx, struct policy_handle *handle, const char *key_name, uint32_t offered, uint32_t *count, struct spoolss_PrinterEnumValues **info) { NTSTATUS status; WERROR werror; uint32_t needed; status = rpccli_spoolss_EnumPrinterDataEx(cli, mem_ctx, handle, key_name, offered, count, info, &needed, &werror); if (W_ERROR_EQUAL(werror, WERR_MORE_DATA)) { offered = needed; status = rpccli_spoolss_EnumPrinterDataEx(cli, mem_ctx, handle, key_name, offered, count, info, &needed, &werror); } return werror; }
770527.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include "../smalloc.h" #include "../flist.h" FILE *f_err; struct timeval *fio_tv = NULL; unsigned int fio_debug = 0; #define MAGIC1 0xa9b1c8d2 #define MAGIC2 0xf0a1e9b3 #define LOOPS 32 struct elem { unsigned int magic1; struct flist_head list; unsigned int magic2; }; FLIST_HEAD(list); static int do_rand_allocs(void) { unsigned int size, nr, rounds = 0; unsigned long total; struct elem *e; while (rounds++ < LOOPS) { #ifdef STEST_SEED srand(MAGIC1); #endif nr = total = 0; while (total < 128*1024*1024UL) { size = 8 * sizeof(struct elem) + (int) (999.0 * (rand() / (RAND_MAX + 1.0))); e = smalloc(size); if (!e) { printf("fail at %lu, size %u\n", total, size); break; } e->magic1 = MAGIC1; e->magic2 = MAGIC2; total += size; flist_add_tail(&e->list, &list); nr++; } printf("Got items: %u\n", nr); while (!flist_empty(&list)) { e = flist_entry(list.next, struct elem, list); assert(e->magic1 == MAGIC1); assert(e->magic2 == MAGIC2); flist_del(&e->list); sfree(e); } } return 0; } static int do_specific_alloc(unsigned long size) { void *ptr; ptr = smalloc(size); sfree(ptr); return 0; } int main(int argc, char *argv[]) { f_err = stderr; sinit(); do_rand_allocs(); /* smalloc bug, commit 271067a6 */ do_specific_alloc(671386584); scleanup(); return 0; } void __dprint(int type, const char *str, ...) { }
757261.c
/* Parse tree node implementation */ #include "Python.h" #include "node.h" #include "errcode.h" node * Ta3Node_New(int type) { node *n = (node *) PyObject_MALLOC(1 * sizeof(node)); if (n == NULL) return NULL; n->n_type = type; n->n_str = NULL; n->n_lineno = 0; n->n_nchildren = 0; n->n_child = NULL; return n; } /* See comments at XXXROUNDUP below. Returns -1 on overflow. */ static int fancy_roundup(int n) { /* Round up to the closest power of 2 >= n. */ int result = 256; assert(n > 128); while (result < n) { result <<= 1; if (result <= 0) return -1; } return result; } /* A gimmick to make massive numbers of reallocs quicker. The result is * a number >= the input. In Ta3Node_AddChild, it's used like so, when * we're about to add child number current_size + 1: * * if XXXROUNDUP(current_size) < XXXROUNDUP(current_size + 1): * allocate space for XXXROUNDUP(current_size + 1) total children * else: * we already have enough space * * Since a node starts out empty, we must have * * XXXROUNDUP(0) < XXXROUNDUP(1) * * so that we allocate space for the first child. One-child nodes are very * common (presumably that would change if we used a more abstract form * of syntax tree), so to avoid wasting memory it's desirable that * XXXROUNDUP(1) == 1. That in turn forces XXXROUNDUP(0) == 0. * * Else for 2 <= n <= 128, we round up to the closest multiple of 4. Why 4? * Rounding up to a multiple of an exact power of 2 is very efficient, and * most nodes with more than one child have <= 4 kids. * * Else we call fancy_roundup() to grow proportionately to n. We've got an * extreme case then (like test_longexp.py), and on many platforms doing * anything less than proportional growth leads to exorbitant runtime * (e.g., MacPython), or extreme fragmentation of user address space (e.g., * Win98). * * In a run of compileall across the 2.3a0 Lib directory, Andrew MacIntyre * reported that, with this scheme, 89% of PyObject_REALLOC calls in * Ta3Node_AddChild passed 1 for the size, and 9% passed 4. So this usually * wastes very little memory, but is very effective at sidestepping * platform-realloc disasters on vulnerable platforms. * * Note that this would be straightforward if a node stored its current * capacity. The code is tricky to avoid that. */ #define XXXROUNDUP(n) ((n) <= 1 ? (n) : \ (n) <= 128 ? (int)_Py_SIZE_ROUND_UP((n), 4) : \ fancy_roundup(n)) int Ta3Node_AddChild(node *n1, int type, char *str, int lineno, int col_offset) { const int nch = n1->n_nchildren; int current_capacity; int required_capacity; node *n; if (nch == INT_MAX || nch < 0) return E_OVERFLOW; current_capacity = XXXROUNDUP(nch); required_capacity = XXXROUNDUP(nch + 1); if (current_capacity < 0 || required_capacity < 0) return E_OVERFLOW; if (current_capacity < required_capacity) { if ((size_t)required_capacity > SIZE_MAX / sizeof(node)) { return E_NOMEM; } n = n1->n_child; n = (node *) PyObject_REALLOC(n, required_capacity * sizeof(node)); if (n == NULL) return E_NOMEM; n1->n_child = n; } n = &n1->n_child[n1->n_nchildren++]; n->n_type = type; n->n_str = str; n->n_lineno = lineno; n->n_col_offset = col_offset; n->n_nchildren = 0; n->n_child = NULL; return 0; } /* Forward */ static void freechildren(node *); static Py_ssize_t sizeofchildren(node *n); void Ta3Node_Free(node *n) { if (n != NULL) { freechildren(n); PyObject_FREE(n); } } Py_ssize_t _Ta3Node_SizeOf(node *n) { Py_ssize_t res = 0; if (n != NULL) res = sizeof(node) + sizeofchildren(n); return res; } static void freechildren(node *n) { int i; for (i = NCH(n); --i >= 0; ) freechildren(CHILD(n, i)); if (n->n_child != NULL) PyObject_FREE(n->n_child); if (STR(n) != NULL) PyObject_FREE(STR(n)); } static Py_ssize_t sizeofchildren(node *n) { Py_ssize_t res = 0; int i; for (i = NCH(n); --i >= 0; ) res += sizeofchildren(CHILD(n, i)); if (n->n_child != NULL) /* allocated size of n->n_child array */ res += XXXROUNDUP(NCH(n)) * sizeof(node); if (STR(n) != NULL) res += strlen(STR(n)) + 1; return res; }
863285.c
/* * FAT.c * FAT32 FAT (File Allocation Table) Implementation * * ARM-based K70F120M microcontroller board * for educational purposes only * CSCI E-92 Spring 2021, Professor James L. Frankel, Harvard Extension School * * Written by James L. Frankel ([email protected]) * * Copyright (c) 2021 James L. Frankel. All rights reserved. * * Last updated: 2:14 PM 16-Mar-2021 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "microSD.h" #include "FAT.h" #include "bootSector.h" #include "breakpoint.h" uint32_t FAT_sector_valid; uint32_t FAT_in_mem_0_origin_sector; uint32_t FAT_sector[512/4]; static int FAT_endiannessDetermined = 0; /* FAT_endian will indicate if the *computer* is little or big endian; The format of data in FAT32 file structures is always little endian */ static enum endianness { endian_little, endian_big } FAT_endian; /* This module implements a single sector write-through FAT cache */ static void determineEndianness(void); static void read_FAT(uint32_t rca, uint8_t *data, uint32_t sector); static void write_FAT(uint32_t rca, uint8_t *data, uint32_t sector); static void determineEndianness(void) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; union union_32 { uint32_t uint32; uint8_t uint8[4]; } union_32; union_32.uint8[0] = 0; union_32.uint8[1] = 1; union_32.uint8[2] = 2; union_32.uint8[3] = 3; if(union_32.uint32 == 0x03020100) { FAT_endian = endian_little; } else { FAT_endian = endian_big; } if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "Computer is %s endian\n", (FAT_endian == endian_little) ? "little" : "big"); CONSOLE_PUTS(output_buffer); } } uint32_t read_FAT_entry(uint32_t rca, uint32_t cluster) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; uint32_t FAT_0_origin_sector_for_cluster_num = cluster/(bytes_per_sector/4); uint32_t FAT_entry_offset_in_sector = cluster%(bytes_per_sector/4); uint32_t FAT_sector_to_access = FAT_0_origin_sector_for_cluster_num+first_FAT_sector; if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "Reading FAT entry for cluster %lu\n", cluster); CONSOLE_PUTS(output_buffer); } if(!FAT_sector_valid) { if(FAT_DEBUG) CONSOLE_PUTS("No FAT sector is currently in memory\n"); /* no FAT sector is currently in memory; read the needed sector */ read_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access); FAT_in_mem_0_origin_sector = FAT_0_origin_sector_for_cluster_num; FAT_sector_valid = 1; } else if(FAT_0_origin_sector_for_cluster_num == FAT_in_mem_0_origin_sector) { /* FAT sector we need is currently in memory; just return needed entry */ if(FAT_DEBUG) CONSOLE_PUTS("Correct FAT sector is currently in memory\n"); } else { /* A FAT sector is in memory, but not the one we need; read the needed sector */ if(FAT_DEBUG) CONSOLE_PUTS("Incorrect FAT sector is currently in memory\n"); read_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access); FAT_in_mem_0_origin_sector = FAT_0_origin_sector_for_cluster_num; } if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "The FAT entry for cluster %lu is %lu (0x%08lX)\n", cluster, FAT_sector[FAT_entry_offset_in_sector], FAT_sector[FAT_entry_offset_in_sector]); CONSOLE_PUTS(output_buffer); } return FAT_sector[FAT_entry_offset_in_sector] & FAT_ENTRY_MASK; } void write_FAT_entry(uint32_t rca, uint32_t cluster, uint32_t nextCluster) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; uint32_t FAT_0_origin_sector_for_cluster_num = cluster/(bytes_per_sector/4); uint32_t FAT_entry_offset_in_sector = cluster%(bytes_per_sector/4); uint32_t FAT_sector_to_access = FAT_0_origin_sector_for_cluster_num+first_FAT_sector; if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "Writing FAT entry for cluster %lu to be %lu\n", cluster, nextCluster); CONSOLE_PUTS(output_buffer); } if(!FAT_sector_valid) { if(FAT_DEBUG) CONSOLE_PUTS("No FAT sector is currently in memory\n"); /* no FAT sector is currently in memory; read the needed sector */ read_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access); FAT_in_mem_0_origin_sector = FAT_0_origin_sector_for_cluster_num; FAT_sector_valid = 1; } else if(FAT_0_origin_sector_for_cluster_num == FAT_in_mem_0_origin_sector) { /* FAT sector we need is currently in memory; just return needed entry */ if(FAT_DEBUG) CONSOLE_PUTS("Correct FAT sector is currently in memory\n"); } else { /* A FAT sector is in memory, but not the one we need; read the needed sector */ if(FAT_DEBUG) CONSOLE_PUTS("Incorrect FAT sector is currently in memory\n"); read_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access); FAT_in_mem_0_origin_sector = FAT_0_origin_sector_for_cluster_num; } if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "The previous FAT entry for cluster %lu is %lu (0x%08lX)\n", cluster, FAT_sector[FAT_entry_offset_in_sector], FAT_sector[FAT_entry_offset_in_sector]); CONSOLE_PUTS(output_buffer); } /* change the selected FAT entry to be nextCluster */ /* we're allowed to change only the low-order 28 bits; the high-order 4 bits must maintain their previous value */ FAT_sector[FAT_entry_offset_in_sector] = (FAT_sector[FAT_entry_offset_in_sector] & ~FAT_ENTRY_MASK) | (nextCluster & FAT_ENTRY_MASK); /* write the modified FAT sector to the main FAT in the file system */ write_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access); /* write the modified FAT sector to the copy FAT in the file system */ write_FAT(rca, (uint8_t *)FAT_sector, FAT_sector_to_access+sectors_per_FAT); return; } void invalidate_FAT_by_sector(uint32_t sector_address) { if(sector_address == (FAT_in_mem_0_origin_sector+first_FAT_sector)) { FAT_sector_valid = 0; } } static void read_FAT(uint32_t rca, uint8_t *data, uint32_t sector) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; struct sdhc_card_status card_status; if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "Reading FAT sector %lu\n", sector); CONSOLE_PUTS(output_buffer); } if(!FAT_endiannessDetermined) { determineEndianness(); FAT_endiannessDetermined = 1; } /* computer is little endian, we can read directly into memory */ if(SDHC_SUCCESS != sdhc_read_single_block(rca, sector, &card_status, data)) { __BKPT(); } if(FAT_endian == endian_big) { /* if computer is big endian, we need to reverse the bytes in each 32-bit word */ int i; uint8_t MSByte, NextToMSByte; for(i = 0; i < 512; i += 4) { MSByte = data[i]; NextToMSByte = data[i+1]; data[i] = data[i+3]; data[i+1] = data[i+2]; data[i+2] = NextToMSByte; data[i+3] = MSByte; } } } static void write_FAT(uint32_t rca, uint8_t *data, uint32_t sector) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; struct sdhc_card_status card_status; if(FAT_DEBUG) { snprintf(output_buffer, sizeof(output_buffer), "Writing FAT sector %lu\n", sector); CONSOLE_PUTS(output_buffer); } if(!FAT_endiannessDetermined) { determineEndianness(); FAT_endiannessDetermined = 1; } if(FAT_endian == endian_big) { /* if computer is big endian, we need to reverse the bytes in each 32-bit word before writing it to the FAT file structure */ int i; uint8_t MSByte, NextToMSByte; for(i = 0; i < 512; i += 4) { MSByte = data[i]; NextToMSByte = data[i+1]; data[i] = data[i+3]; data[i+1] = data[i+2]; data[i+2] = NextToMSByte; data[i+3] = MSByte; } } /* now that the FAT sector is in little endian byte order, we can write directly from memory */ if(SDHC_SUCCESS != sdhc_write_single_block(rca, sector, &card_status, data)) { __BKPT(); } if(FAT_endian == endian_big) { /* unfortunately, if computer is big endian, we now need to re-reverse the bytes in each 32-bit word */ int i; uint8_t MSByte, NextToMSByte; for(i = 0; i < 512; i += 4) { MSByte = data[i]; NextToMSByte = data[i+1]; data[i] = data[i+3]; data[i+1] = data[i+2]; data[i+2] = NextToMSByte; data[i+3] = MSByte; } } } int FAT_copy_verify(uint32_t rca) { char output_buffer[FAT_OUTPUT_BUFFER_SIZE]; uint32_t main_FAT_sector_number, copy_FAT_sector_number, i; struct sdhc_card_status card_status; uint8_t main_FAT_data[512], copy_FAT_data[512]; int compare_equal; compare_equal = 1; main_FAT_sector_number = first_FAT_sector; copy_FAT_sector_number = first_FAT_sector+sectors_per_FAT; for(i = 0; i < sectors_per_FAT; i++) { if(SDHC_SUCCESS != sdhc_read_single_block(rca, main_FAT_sector_number, &card_status, main_FAT_data)) { __BKPT(); } if(SDHC_SUCCESS != sdhc_read_single_block(rca, copy_FAT_sector_number, &card_status, copy_FAT_data)) { __BKPT(); } if(memcmp(main_FAT_data, copy_FAT_data, bytes_per_sector) != 0) { compare_equal = 0; if(FAT_INFORMATIVE_PRINTF) { snprintf(output_buffer, sizeof(output_buffer), "Sector #%lu of main FAT and sector #%lu of copy FAT are not the same\n", main_FAT_sector_number, copy_FAT_sector_number); CONSOLE_PUTS(output_buffer); } } main_FAT_sector_number++; copy_FAT_sector_number++; } return compare_equal; }
60043.c
/* * ieframe - Internet Explorer main frame window * * Copyright 2006 Mike McCormack (for CodeWeavers) * Copyright 2006 Jacek Caban (for CodeWeavers) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #define COBJMACROS #include <stdarg.h> #include "ieframe.h" #include "resource.h" #include "winuser.h" #include "wingdi.h" #include "winnls.h" #include "ole2.h" #include "exdisp.h" #include "oleidl.h" #include "mshtmcid.h" #include "shellapi.h" #include "winreg.h" #include "shlwapi.h" #include "intshcut.h" #include "ddeml.h" #include "wine/debug.h" WINE_DEFAULT_DEBUG_CHANNEL(ieframe); #define IDI_APPICON 1 #define WM_UPDATEADDRBAR (WM_APP+1) static const WCHAR szIEWinFrame[] = { 'I','E','F','r','a','m','e',0 }; /* Windows uses "Microsoft Internet Explorer" */ static const WCHAR wszWineInternetExplorer[] = {'W','i','n','e',' ','I','n','t','e','r','n','e','t',' ','E','x','p','l','o','r','e','r',0}; static LONG obj_cnt; static DWORD dde_inst; static HSZ ddestr_iexplore, ddestr_openurl; static struct list ie_list = LIST_INIT(ie_list); HRESULT update_ie_statustext(InternetExplorer* This, LPCWSTR text) { if(!SendMessageW(This->status_hwnd, SB_SETTEXTW, MAKEWORD(SB_SIMPLEID, 0), (LPARAM)text)) return E_FAIL; return S_OK; } static void adjust_ie_docobj_rect(HWND frame, RECT* rc) { HWND hwndRebar = GetDlgItem(frame, IDC_BROWSE_REBAR); HWND hwndStatus = GetDlgItem(frame, IDC_BROWSE_STATUSBAR); INT barHeight = SendMessageW(hwndRebar, RB_GETBARHEIGHT, 0, 0); rc->top += barHeight; rc->bottom -= barHeight; if(IsWindowVisible(hwndStatus)) { RECT statusrc; GetClientRect(hwndStatus, &statusrc); rc->bottom -= statusrc.bottom - statusrc.top; } } static HMENU get_tb_menu(HMENU menu) { HMENU menu_view = GetSubMenu(menu, 1); return GetSubMenu(menu_view, 0); } static HMENU get_fav_menu(HMENU menu) { return GetSubMenu(menu, 2); } static LPWSTR get_fav_url_from_id(HMENU menu, UINT id) { MENUITEMINFOW item; item.cbSize = sizeof(item); item.fMask = MIIM_DATA; if(!GetMenuItemInfoW(menu, id, FALSE, &item)) return NULL; return (LPWSTR)item.dwItemData; } static void free_fav_menu_data(HMENU menu) { LPWSTR url; int i; for(i = 0; (url = get_fav_url_from_id(menu, ID_BROWSE_GOTOFAV_FIRST + i)); i++) heap_free( url ); } static int get_menu_item_count(HMENU menu) { MENUITEMINFOW item; int count = 0; int i; item.cbSize = sizeof(item); item.fMask = MIIM_DATA | MIIM_SUBMENU; for(i = 0; GetMenuItemInfoW(menu, i, TRUE, &item); i++) { if(item.hSubMenu) count += get_menu_item_count(item.hSubMenu); else count++; } return count; } static void add_fav_to_menu(HMENU favmenu, HMENU menu, LPWSTR title, LPCWSTR url) { MENUITEMINFOW item; /* Subtract the number of standard elements in the Favorites menu */ int favcount = get_menu_item_count(favmenu) - 2; LPWSTR urlbuf; if(favcount > (ID_BROWSE_GOTOFAV_MAX - ID_BROWSE_GOTOFAV_FIRST)) { FIXME("Add support for more than %d Favorites\n", favcount); return; } urlbuf = heap_alloc((lstrlenW(url) + 1) * sizeof(WCHAR)); if(!urlbuf) return; lstrcpyW(urlbuf, url); item.cbSize = sizeof(item); item.fMask = MIIM_FTYPE | MIIM_STRING | MIIM_DATA | MIIM_ID; item.fType = MFT_STRING; item.dwTypeData = title; item.wID = ID_BROWSE_GOTOFAV_FIRST + favcount; item.dwItemData = (ULONG_PTR)urlbuf; InsertMenuItemW(menu, -1, TRUE, &item); } static void add_favs_to_menu(HMENU favmenu, HMENU menu, LPCWSTR dir) { WCHAR path[MAX_PATH*2]; const WCHAR search[] = {'*',0}; WCHAR* filename; HANDLE findhandle; WIN32_FIND_DATAW finddata; IUniformResourceLocatorW* urlobj; IPersistFile* urlfile = NULL; HRESULT res; lstrcpyW(path, dir); PathAppendW(path, search); findhandle = FindFirstFileW(path, &finddata); if(findhandle == INVALID_HANDLE_VALUE) return; res = CoCreateInstance(&CLSID_InternetShortcut, NULL, CLSCTX_INPROC_SERVER, &IID_IUniformResourceLocatorW, (PVOID*)&urlobj); if(SUCCEEDED(res)) res = IUnknown_QueryInterface((IUnknown*)urlobj, &IID_IPersistFile, (PVOID*)&urlfile); if(SUCCEEDED(res)) { filename = path + lstrlenW(path) - lstrlenW(search); do { lstrcpyW(filename, finddata.cFileName); if(finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { MENUITEMINFOW item; const WCHAR ignore1[] = {'.','.',0}; const WCHAR ignore2[] = {'.',0}; if(!lstrcmpW(filename, ignore1) || !lstrcmpW(filename, ignore2)) continue; item.cbSize = sizeof(item); item.fMask = MIIM_STRING | MIIM_SUBMENU; item.dwTypeData = filename; item.hSubMenu = CreatePopupMenu(); InsertMenuItemW(menu, -1, TRUE, &item); add_favs_to_menu(favmenu, item.hSubMenu, path); } else { WCHAR* fileext; WCHAR* url = NULL; const WCHAR urlext[] = {'.','u','r','l',0}; if(lstrcmpiW(PathFindExtensionW(filename), urlext)) continue; if(FAILED(IPersistFile_Load(urlfile, path, 0))) continue; urlobj->lpVtbl->GetURL(urlobj, &url); if(!url) continue; fileext = filename + lstrlenW(filename) - lstrlenW(urlext); *fileext = 0; add_fav_to_menu(favmenu, menu, filename, url); } } while(FindNextFileW(findhandle, &finddata)); } if(urlfile) IPersistFile_Release(urlfile); if(urlobj) IUnknown_Release((IUnknown*)urlobj); FindClose(findhandle); } static void add_tbs_to_menu(HMENU menu) { HUSKEY toolbar_handle; WCHAR toolbar_key[] = {'S','o','f','t','w','a','r','e','\\', 'M','i','c','r','o','s','o','f','t','\\', 'I','n','t','e','r','n','e','t',' ', 'E','x','p','l','o','r','e','r','\\', 'T','o','o','l','b','a','r',0}; if(SHRegOpenUSKeyW(toolbar_key, KEY_READ, NULL, &toolbar_handle, TRUE) == ERROR_SUCCESS) { HUSKEY classes_handle; WCHAR classes_key[] = {'S','o','f','t','w','a','r','e','\\', 'C','l','a','s','s','e','s','\\','C','L','S','I','D',0}; WCHAR guid[39]; DWORD value_len = sizeof(guid)/sizeof(guid[0]); int i; if(SHRegOpenUSKeyW(classes_key, KEY_READ, NULL, &classes_handle, TRUE) != ERROR_SUCCESS) { SHRegCloseUSKey(toolbar_handle); ERR("Failed to open key %s\n", debugstr_w(classes_key)); return; } for(i = 0; SHRegEnumUSValueW(toolbar_handle, i, guid, &value_len, NULL, NULL, NULL, SHREGENUM_HKLM) == ERROR_SUCCESS; i++) { WCHAR tb_name[100]; DWORD tb_name_len = sizeof(tb_name)/sizeof(tb_name[0]); HUSKEY tb_class_handle; MENUITEMINFOW item; LSTATUS ret; value_len = sizeof(guid)/sizeof(guid[0]); if(lstrlenW(guid) != 38) { TRACE("Found invalid IE toolbar entry: %s\n", debugstr_w(guid)); continue; } if(SHRegOpenUSKeyW(guid, KEY_READ, classes_handle, &tb_class_handle, TRUE) != ERROR_SUCCESS) { ERR("Failed to get class info for %s\n", debugstr_w(guid)); continue; } ret = SHRegQueryUSValueW(tb_class_handle, NULL, NULL, tb_name, &tb_name_len, TRUE, NULL, 0); SHRegCloseUSKey(tb_class_handle); if(ret != ERROR_SUCCESS) { ERR("Failed to get toolbar name for %s\n", debugstr_w(guid)); continue; } item.cbSize = sizeof(item); item.fMask = MIIM_STRING; item.dwTypeData = tb_name; InsertMenuItemW(menu, GetMenuItemCount(menu), TRUE, &item); } SHRegCloseUSKey(classes_handle); SHRegCloseUSKey(toolbar_handle); } } static HMENU create_ie_menu(void) { HMENU menu = LoadMenuW(ieframe_instance, MAKEINTRESOURCEW(IDR_BROWSE_MAIN_MENU)); HMENU favmenu = get_fav_menu(menu); WCHAR path[MAX_PATH]; add_tbs_to_menu(get_tb_menu(menu)); if(SHGetFolderPathW(NULL, CSIDL_COMMON_FAVORITES, NULL, SHGFP_TYPE_CURRENT, path) == S_OK) add_favs_to_menu(favmenu, favmenu, path); if(SHGetFolderPathW(NULL, CSIDL_FAVORITES, NULL, SHGFP_TYPE_CURRENT, path) == S_OK) add_favs_to_menu(favmenu, favmenu, path); return menu; } static void ie_navigate(InternetExplorer* This, LPCWSTR url) { VARIANT variant; V_VT(&variant) = VT_BSTR; V_BSTR(&variant) = SysAllocString(url); IWebBrowser2_Navigate2(&This->IWebBrowser2_iface, &variant, NULL, NULL, NULL, NULL); SysFreeString(V_BSTR(&variant)); } static INT_PTR CALLBACK ie_dialog_open_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { static InternetExplorer* This; switch(msg) { case WM_INITDIALOG: This = (InternetExplorer*)lparam; EnableWindow(GetDlgItem(hwnd, IDOK), FALSE); return TRUE; case WM_COMMAND: switch(LOWORD(wparam)) { case IDC_BROWSE_OPEN_URL: { HWND hwndurl = GetDlgItem(hwnd, IDC_BROWSE_OPEN_URL); int len = GetWindowTextLengthW(hwndurl); EnableWindow(GetDlgItem(hwnd, IDOK), len != 0); break; } case IDOK: { HWND hwndurl = GetDlgItem(hwnd, IDC_BROWSE_OPEN_URL); int len = GetWindowTextLengthW(hwndurl); if(len) { VARIANT url; V_VT(&url) = VT_BSTR; V_BSTR(&url) = SysAllocStringLen(NULL, len); GetWindowTextW(hwndurl, V_BSTR(&url), len + 1); IWebBrowser2_Navigate2(&This->IWebBrowser2_iface, &url, NULL, NULL, NULL, NULL); SysFreeString(V_BSTR(&url)); } } /* fall through */ case IDCANCEL: EndDialog(hwnd, wparam); return TRUE; } } return FALSE; } static void ie_dialog_about(HWND hwnd) { HICON icon = LoadImageW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDI_APPICON), IMAGE_ICON, 48, 48, LR_SHARED); ShellAboutW(hwnd, wszWineInternetExplorer, NULL, icon); DestroyIcon(icon); } static void add_tb_separator(HWND hwnd) { TBBUTTON btn; ZeroMemory(&btn, sizeof(btn)); btn.iBitmap = 3; btn.fsStyle = BTNS_SEP; SendMessageW(hwnd, TB_ADDBUTTONSW, 1, (LPARAM)&btn); } static void add_tb_button(HWND hwnd, int bmp, int cmd, int strId) { TBBUTTON btn; WCHAR buf[30]; LoadStringW(ieframe_instance, strId, buf, sizeof(buf)/sizeof(buf[0])); btn.iBitmap = bmp; btn.idCommand = cmd; btn.fsState = TBSTATE_ENABLED; btn.fsStyle = BTNS_SHOWTEXT; btn.dwData = 0; btn.iString = (INT_PTR)buf; SendMessageW(hwnd, TB_ADDBUTTONSW, 1, (LPARAM)&btn); } static void create_rebar(HWND hwnd) { HWND hwndRebar; HWND hwndAddress; HWND hwndToolbar; REBARINFO rebarinf; REBARBANDINFOW bandinf; WCHAR addr[40]; HIMAGELIST imagelist; SIZE toolbar_size; LoadStringW(ieframe_instance, IDS_ADDRESS, addr, sizeof(addr)/sizeof(addr[0])); hwndRebar = CreateWindowExW(WS_EX_TOOLWINDOW, REBARCLASSNAMEW, NULL, WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|RBS_VARHEIGHT|CCS_TOP|CCS_NODIVIDER, 0, 0, 0, 0, hwnd, (HMENU)IDC_BROWSE_REBAR, ieframe_instance, NULL); rebarinf.cbSize = sizeof(rebarinf); rebarinf.fMask = 0; rebarinf.himl = NULL; SendMessageW(hwndRebar, RB_SETBARINFO, 0, (LPARAM)&rebarinf); hwndToolbar = CreateWindowExW(TBSTYLE_EX_MIXEDBUTTONS, TOOLBARCLASSNAMEW, NULL, TBSTYLE_FLAT | WS_CHILD | WS_VISIBLE | CCS_NORESIZE, 0, 0, 0, 0, hwndRebar, (HMENU)IDC_BROWSE_TOOLBAR, ieframe_instance, NULL); imagelist = ImageList_LoadImageW(ieframe_instance, MAKEINTRESOURCEW(IDB_IETOOLBAR), 32, 0, CLR_NONE, IMAGE_BITMAP, LR_CREATEDIBSECTION); SendMessageW(hwndToolbar, TB_SETIMAGELIST, 0, (LPARAM)imagelist); SendMessageW(hwndToolbar, TB_BUTTONSTRUCTSIZE, sizeof(TBBUTTON), 0); add_tb_button(hwndToolbar, 0, ID_BROWSE_BACK, IDS_TB_BACK); add_tb_button(hwndToolbar, 1, ID_BROWSE_FORWARD, IDS_TB_FORWARD); add_tb_button(hwndToolbar, 2, ID_BROWSE_STOP, IDS_TB_STOP); add_tb_button(hwndToolbar, 3, ID_BROWSE_REFRESH, IDS_TB_REFRESH); add_tb_button(hwndToolbar, 4, ID_BROWSE_HOME, IDS_TB_HOME); add_tb_separator(hwndToolbar); add_tb_button(hwndToolbar, 5, ID_BROWSE_PRINT, IDS_TB_PRINT); SendMessageW(hwndToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(55,50)); SendMessageW(hwndToolbar, TB_GETMAXSIZE, 0, (LPARAM)&toolbar_size); bandinf.cbSize = sizeof(bandinf); bandinf.fMask = RBBIM_STYLE | RBBIM_CHILD | RBBIM_CHILDSIZE; bandinf.fStyle = RBBS_CHILDEDGE; bandinf.cxMinChild = toolbar_size.cx; bandinf.cyMinChild = toolbar_size.cy+2; bandinf.hwndChild = hwndToolbar; SendMessageW(hwndRebar, RB_INSERTBANDW, -1, (LPARAM)&bandinf); hwndAddress = CreateWindowExW(0, WC_COMBOBOXEXW, NULL, WS_BORDER|WS_CHILD|WS_VISIBLE|CBS_DROPDOWN, 0, 0, 100,20,hwndRebar, (HMENU)IDC_BROWSE_ADDRESSBAR, ieframe_instance, NULL); bandinf.fMask |= RBBIM_TEXT; bandinf.fStyle = RBBS_CHILDEDGE | RBBS_BREAK; bandinf.lpText = addr; bandinf.cxMinChild = 100; bandinf.cyMinChild = 20; bandinf.hwndChild = hwndAddress; SendMessageW(hwndRebar, RB_INSERTBANDW, -1, (LPARAM)&bandinf); } static LRESULT iewnd_OnCreate(HWND hwnd, LPCREATESTRUCTW lpcs) { InternetExplorer* This = (InternetExplorer*)lpcs->lpCreateParams; SetWindowLongPtrW(hwnd, 0, (LONG_PTR) lpcs->lpCreateParams); This->menu = create_ie_menu(); This->status_hwnd = CreateStatusWindowW(WS_VISIBLE|WS_CHILD|SBT_NOBORDERS|CCS_NODIVIDER, NULL, hwnd, IDC_BROWSE_STATUSBAR); SendMessageW(This->status_hwnd, SB_SIMPLE, TRUE, 0); create_rebar(hwnd); return 0; } static LRESULT iewnd_OnSize(InternetExplorer *This, INT width, INT height) { HWND hwndRebar = GetDlgItem(This->frame_hwnd, IDC_BROWSE_REBAR); INT barHeight = SendMessageW(hwndRebar, RB_GETBARHEIGHT, 0, 0); RECT docarea = {0, 0, width, height}; SendMessageW(This->status_hwnd, WM_SIZE, 0, 0); adjust_ie_docobj_rect(This->frame_hwnd, &docarea); if(This->doc_host.hwnd) SetWindowPos(This->doc_host.hwnd, NULL, docarea.left, docarea.top, docarea.right, docarea.bottom, SWP_NOZORDER | SWP_NOACTIVATE); SetWindowPos(hwndRebar, NULL, 0, 0, width, barHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } static LRESULT iewnd_OnNotify(InternetExplorer *This, WPARAM wparam, LPARAM lparam) { NMHDR* hdr = (NMHDR*)lparam; if(hdr->idFrom == IDC_BROWSE_ADDRESSBAR && hdr->code == CBEN_ENDEDITW) { NMCBEENDEDITW* info = (NMCBEENDEDITW*)lparam; if(info->fChanged && info->iWhy == CBENF_RETURN) { VARIANT vt; V_VT(&vt) = VT_BSTR; V_BSTR(&vt) = SysAllocString(info->szText); IWebBrowser2_Navigate2(&This->IWebBrowser2_iface, &vt, NULL, NULL, NULL, NULL); SysFreeString(V_BSTR(&vt)); return 0; } } if(hdr->idFrom == IDC_BROWSE_REBAR && hdr->code == RBN_HEIGHTCHANGE) { RECT docarea; GetClientRect(This->frame_hwnd, &docarea); adjust_ie_docobj_rect(This->frame_hwnd, &docarea); if(This->doc_host.hwnd) SetWindowPos(This->doc_host.hwnd, NULL, docarea.left, docarea.top, docarea.right, docarea.bottom, SWP_NOZORDER | SWP_NOACTIVATE); } return 0; } static LRESULT iewnd_OnDestroy(InternetExplorer *This) { HWND hwndRebar = GetDlgItem(This->frame_hwnd, IDC_BROWSE_REBAR); HWND hwndToolbar = GetDlgItem(hwndRebar, IDC_BROWSE_TOOLBAR); HIMAGELIST list = (HIMAGELIST)SendMessageW(hwndToolbar, TB_GETIMAGELIST, 0, 0); TRACE("%p\n", This); free_fav_menu_data(get_fav_menu(This->menu)); ImageList_Destroy(list); This->frame_hwnd = NULL; return 0; } static LRESULT iewnd_OnCommand(InternetExplorer *This, HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch(LOWORD(wparam)) { case ID_BROWSE_OPEN: DialogBoxParamW(ieframe_instance, MAKEINTRESOURCEW(IDD_BROWSE_OPEN), hwnd, ie_dialog_open_proc, (LPARAM)This); break; case ID_BROWSE_PRINT: if(This->doc_host.document) { IOleCommandTarget* target; if(FAILED(IUnknown_QueryInterface(This->doc_host.document, &IID_IOleCommandTarget, (LPVOID*)&target))) break; IOleCommandTarget_Exec(target, &CGID_MSHTML, IDM_PRINT, OLECMDEXECOPT_DODEFAULT, NULL, NULL); IOleCommandTarget_Release(target); } break; case ID_BROWSE_HOME: IWebBrowser2_GoHome(&This->IWebBrowser2_iface); break; case ID_BROWSE_BACK: IWebBrowser2_GoBack(&This->IWebBrowser2_iface); break; case ID_BROWSE_FORWARD: IWebBrowser2_GoForward(&This->IWebBrowser2_iface); break; case ID_BROWSE_STOP: IWebBrowser2_Stop(&This->IWebBrowser2_iface); break; case ID_BROWSE_REFRESH: IWebBrowser2_Refresh(&This->IWebBrowser2_iface); break; case ID_BROWSE_ABOUT: ie_dialog_about(hwnd); break; case ID_BROWSE_QUIT: ShowWindow(hwnd, SW_HIDE); break; default: if(LOWORD(wparam) >= ID_BROWSE_GOTOFAV_FIRST && LOWORD(wparam) <= ID_BROWSE_GOTOFAV_MAX) { LPCWSTR url = get_fav_url_from_id(get_fav_menu(This->menu), LOWORD(wparam)); if(url) ie_navigate(This, url); } return DefWindowProcW(hwnd, msg, wparam, lparam); } return 0; } static LRESULT update_addrbar(InternetExplorer *This, LPARAM lparam) { HWND hwndRebar = GetDlgItem(This->frame_hwnd, IDC_BROWSE_REBAR); HWND hwndAddress = GetDlgItem(hwndRebar, IDC_BROWSE_ADDRESSBAR); HWND hwndEdit = (HWND)SendMessageW(hwndAddress, CBEM_GETEDITCONTROL, 0, 0); LPCWSTR url = (LPCWSTR)lparam; SendMessageW(hwndEdit, WM_SETTEXT, 0, (LPARAM)url); return 0; } static LRESULT WINAPI ie_window_proc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { InternetExplorer *This = (InternetExplorer*) GetWindowLongPtrW(hwnd, 0); switch (msg) { case WM_CREATE: return iewnd_OnCreate(hwnd, (LPCREATESTRUCTW)lparam); case WM_CLOSE: TRACE("WM_CLOSE\n"); ShowWindow(hwnd, SW_HIDE); return 0; case WM_SHOWWINDOW: TRACE("WM_SHOWWINDOW %lx\n", wparam); if(wparam) { IWebBrowser2_AddRef(&This->IWebBrowser2_iface); InterlockedIncrement(&This->extern_ref); }else { release_extern_ref(This, TRUE); IWebBrowser2_Release(&This->IWebBrowser2_iface); } break; case WM_DESTROY: return iewnd_OnDestroy(This); case WM_SIZE: return iewnd_OnSize(This, LOWORD(lparam), HIWORD(lparam)); case WM_COMMAND: return iewnd_OnCommand(This, hwnd, msg, wparam, lparam); case WM_NOTIFY: return iewnd_OnNotify(This, wparam, lparam); case WM_DOCHOSTTASK: return process_dochost_tasks(&This->doc_host); case WM_UPDATEADDRBAR: return update_addrbar(This, lparam); } return DefWindowProcW(hwnd, msg, wparam, lparam); } void register_iewindow_class(void) { WNDCLASSEXW wc; memset(&wc, 0, sizeof wc); wc.cbSize = sizeof(wc); wc.style = 0; wc.lpfnWndProc = ie_window_proc; wc.cbClsExtra = 0; wc.cbWndExtra = sizeof(InternetExplorer*); wc.hInstance = ieframe_instance; wc.hIcon = LoadIconW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDI_APPICON)); wc.hIconSm = LoadImageW(GetModuleHandleW(0), MAKEINTRESOURCEW(IDI_APPICON), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED); wc.hCursor = LoadCursorW(0, MAKEINTRESOURCEW(IDC_ARROW)); wc.hbrBackground = 0; wc.lpszClassName = szIEWinFrame; wc.lpszMenuName = NULL; RegisterClassExW(&wc); } void unregister_iewindow_class(void) { UnregisterClassW(szIEWinFrame, ieframe_instance); } static void create_frame_hwnd(InternetExplorer *This) { This->frame_hwnd = CreateWindowExW( WS_EX_WINDOWEDGE, szIEWinFrame, wszWineInternetExplorer, WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL /* FIXME */, ieframe_instance, This); This->doc_host.frame_hwnd = This->frame_hwnd; create_doc_view_hwnd(&This->doc_host); } static inline InternetExplorer *impl_from_DocHost(DocHost *iface) { return CONTAINING_RECORD(iface, InternetExplorer, doc_host); } static ULONG IEDocHost_addref(DocHost *iface) { InternetExplorer *This = impl_from_DocHost(iface); return IWebBrowser2_AddRef(&This->IWebBrowser2_iface); } static ULONG IEDocHost_release(DocHost *iface) { InternetExplorer *This = impl_from_DocHost(iface); return IWebBrowser2_Release(&This->IWebBrowser2_iface); } static void WINAPI DocHostContainer_GetDocObjRect(DocHost* This, RECT* rc) { GetClientRect(This->frame_hwnd, rc); adjust_ie_docobj_rect(This->frame_hwnd, rc); } static HRESULT WINAPI DocHostContainer_SetStatusText(DocHost *iface, LPCWSTR text) { InternetExplorer *This = impl_from_DocHost(iface); return update_ie_statustext(This, text); } static void WINAPI DocHostContainer_SetURL(DocHost* iface, LPCWSTR url) { InternetExplorer *This = impl_from_DocHost(iface); This->nohome = FALSE; SendMessageW(This->frame_hwnd, WM_UPDATEADDRBAR, 0, (LPARAM)url); } static HRESULT DocHostContainer_exec(DocHost* This, const GUID *cmd_group, DWORD cmdid, DWORD execopt, VARIANT *in, VARIANT *out) { return E_NOTIMPL; } static const IDocHostContainerVtbl DocHostContainerVtbl = { IEDocHost_addref, IEDocHost_release, DocHostContainer_GetDocObjRect, DocHostContainer_SetStatusText, DocHostContainer_SetURL, DocHostContainer_exec }; static HRESULT create_ie(InternetExplorer **ret_obj) { InternetExplorer *ret; ret = heap_alloc_zero(sizeof(InternetExplorer)); if(!ret) return E_OUTOFMEMORY; ret->ref = 1; DocHost_Init(&ret->doc_host, &ret->IWebBrowser2_iface, &DocHostContainerVtbl); InternetExplorer_WebBrowser_Init(ret); HlinkFrame_Init(&ret->hlink_frame, (IUnknown*)&ret->IWebBrowser2_iface, &ret->doc_host); create_frame_hwnd(ret); InterlockedIncrement(&obj_cnt); list_add_tail(&ie_list, &ret->entry); *ret_obj = ret; return S_OK; } HRESULT WINAPI InternetExplorer_Create(IClassFactory *iface, IUnknown *pOuter, REFIID riid, void **ppv) { InternetExplorer *ret; HRESULT hres; TRACE("(%p %s %p)\n", pOuter, debugstr_guid(riid), ppv); hres = create_ie(&ret); if(FAILED(hres)) return hres; hres = IWebBrowser2_QueryInterface(&ret->IWebBrowser2_iface, riid, ppv); IWebBrowser2_Release(&ret->IWebBrowser2_iface); if(FAILED(hres)) return hres; return S_OK; } void released_obj(void) { if(!InterlockedDecrement(&obj_cnt)) PostQuitMessage(0); } static BOOL create_ie_window(const WCHAR *cmdline) { InternetExplorer *ie; HRESULT hres; hres = create_ie(&ie); if(FAILED(hres)) return FALSE; IWebBrowser2_put_Visible(&ie->IWebBrowser2_iface, VARIANT_TRUE); IWebBrowser2_put_MenuBar(&ie->IWebBrowser2_iface, VARIANT_TRUE); if(!*cmdline) { IWebBrowser2_GoHome(&ie->IWebBrowser2_iface); }else { VARIANT var_url; int cmdlen; static const WCHAR nohomeW[] = {'-','n','o','h','o','m','e'}; while(*cmdline == ' ' || *cmdline == '\t') cmdline++; cmdlen = strlenW(cmdline); if(cmdlen > 2 && cmdline[0] == '"' && cmdline[cmdlen-1] == '"') { cmdline++; cmdlen -= 2; } if(cmdlen == sizeof(nohomeW)/sizeof(*nohomeW) && !memcmp(cmdline, nohomeW, sizeof(nohomeW))) { ie->nohome = TRUE; }else { V_VT(&var_url) = VT_BSTR; V_BSTR(&var_url) = SysAllocStringLen(cmdline, cmdlen); /* navigate to the first page */ IWebBrowser2_Navigate2(&ie->IWebBrowser2_iface, &var_url, NULL, NULL, NULL, NULL); SysFreeString(V_BSTR(&var_url)); } } IWebBrowser2_Release(&ie->IWebBrowser2_iface); return TRUE; } static HDDEDATA open_dde_url(WCHAR *dde_url) { InternetExplorer *ie = NULL, *iter; WCHAR *url, *url_end; VARIANT urlv; HRESULT hres; TRACE("%s\n", debugstr_w(dde_url)); url = dde_url; if(*url == '"') { url++; url_end = strchrW(url, '"'); if(!url_end) { FIXME("missing string terminator\n"); return 0; } *url_end = 0; }else { url_end = strchrW(url, ','); if(url_end) *url_end = 0; else url_end = url + strlenW(url); } LIST_FOR_EACH_ENTRY(iter, &ie_list, InternetExplorer, entry) { if(iter->nohome) { IWebBrowser2_AddRef(&iter->IWebBrowser2_iface); ie = iter; break; } } if(!ie) { hres = create_ie(&ie); if(FAILED(hres)) return 0; } IWebBrowser2_put_Visible(&ie->IWebBrowser2_iface, VARIANT_TRUE); IWebBrowser2_put_MenuBar(&ie->IWebBrowser2_iface, VARIANT_TRUE); V_VT(&urlv) = VT_BSTR; V_BSTR(&urlv) = SysAllocStringLen(url, url_end-url); if(!V_BSTR(&urlv)) { IWebBrowser2_Release(&ie->IWebBrowser2_iface); return 0; } hres = IWebBrowser2_Navigate2(&ie->IWebBrowser2_iface, &urlv, NULL, NULL, NULL, NULL); if(FAILED(hres)) return 0; IWebBrowser2_Release(&ie->IWebBrowser2_iface); return ULongToHandle(DDE_FACK); } static HDDEDATA WINAPI dde_proc(UINT type, UINT uFmt, HCONV hConv, HSZ hsz1, HSZ hsz2, HDDEDATA data, ULONG_PTR dwData1, ULONG_PTR dwData2) { switch(type) { case XTYP_CONNECT: TRACE("XTYP_CONNECT %p\n", hsz1); return ULongToHandle(!DdeCmpStringHandles(hsz1, ddestr_openurl)); case XTYP_EXECUTE: { WCHAR *url; DWORD size; HDDEDATA ret; TRACE("XTYP_EXECUTE %p\n", data); size = DdeGetData(data, NULL, 0, 0); if(!size) { WARN("size = 0\n"); break; } url = heap_alloc(size); if(!url) break; if(DdeGetData(data, (BYTE*)url, size, 0) != size) { ERR("error during read\n"); heap_free(url); break; } ret = open_dde_url(url); heap_free(url); return ret; } case XTYP_REQUEST: FIXME("XTYP_REQUEST\n"); break; default: TRACE("type %d\n", type); } return NULL; } static void init_dde(void) { UINT res; static const WCHAR iexploreW[] = {'I','E','x','p','l','o','r','e',0}; static const WCHAR openurlW[] = {'W','W','W','_','O','p','e','n','U','R','L',0}; res = DdeInitializeW(&dde_inst, dde_proc, CBF_SKIP_ALLNOTIFICATIONS | CBF_FAIL_ADVISES | CBF_FAIL_POKES, 0); if(res != DMLERR_NO_ERROR) { WARN("DdeInitialize failed: %u\n", res); return; } ddestr_iexplore = DdeCreateStringHandleW(dde_inst, iexploreW, CP_WINUNICODE); if(!ddestr_iexplore) WARN("Failed to create string handle: %u\n", DdeGetLastError(dde_inst)); ddestr_openurl = DdeCreateStringHandleW(dde_inst, openurlW, CP_WINUNICODE); if(!ddestr_openurl) WARN("Failed to create string handle: %u\n", DdeGetLastError(dde_inst)); if(!DdeNameService(dde_inst, ddestr_iexplore, 0, DNS_REGISTER)) WARN("DdeNameService failed\n"); } static void release_dde(void) { if(ddestr_iexplore) DdeNameService(dde_inst, ddestr_iexplore, 0, DNS_UNREGISTER); if(ddestr_openurl) DdeFreeStringHandle(dde_inst, ddestr_openurl); if(ddestr_iexplore) DdeFreeStringHandle(dde_inst, ddestr_iexplore); DdeUninitialize(dde_inst); } /****************************************************************** * IEWinMain (ieframe.101) * * Only returns on error. */ DWORD WINAPI IEWinMain(const WCHAR *cmdline, int nShowWindow) { MSG msg; HRESULT hres; static const WCHAR embeddingW[] = {'-','e','m','b','e','d','d','i','n','g',0}; TRACE("%s %d\n", debugstr_w(cmdline), nShowWindow); CoInitialize(NULL); hres = register_class_object(TRUE); if(FAILED(hres)) { CoUninitialize(); ExitProcess(1); } init_dde(); if(strcmpiW(cmdline, embeddingW)) { if(!create_ie_window(cmdline)) { CoUninitialize(); ExitProcess(1); } } /* run the message loop for this thread */ while (GetMessageW(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessageW(&msg); } register_class_object(FALSE); release_dde(); CoUninitialize(); ExitProcess(0); return 0; }
517033.c
/*- * Copyright (c) 1980, 1993 * The Regents of the University of California. All rights reserved. * * %sccs.include.proprietary.c% */ #ifndef lint static char sccsid[] = "@(#)linemod.c 8.1 (Berkeley) 06/04/93"; #endif /* not lint */ #include "hp2648.h" linemod( line ) char *line; { putchar('Z'); handshake(); putchar(ESC); putchar(GRAPHIC); putchar(MODE); if ( *(line) == 's' ) { if ( *(++line) == 'o' ) { /* * solid mode 1 */ putchar( '1' ); putchar( 'b' ); goto done; } else if ( *(line) == 'h' ) { /* * shortdashed mode 4 */ putchar( '6' ); putchar( 'b' ); goto done; } } else if ( *(line) == 'd' ) { if ( *(++line) == 'o' && *(++line) == 't' ) { if ( *(++line) == 't' ) { /* * dotted mode 2 */ putchar( '7' ); putchar( 'b' ); goto done; } else if ( *(line) == 'd' ) { /* * dotdashed mode 3 */ putchar( '8' ); putchar( 'b' ); goto done; } } } else if ( *(line) == 'l' ) { /* * longdashed mode 5 */ putchar( '5' ); putchar( 'b' ); goto done; } putchar( '1' ); /* default to solid */ putchar( 'b' ); /* default to solid */ done: putchar( 'Z' ); handshake(); putchar(ESC); putchar(GRAPHIC); putchar(PLOT); putchar(BINARY); buffcount = 4; return; }
218738.c
/* Copyright 2013-2014. The Regents of the University of California. * Copyright 2015-2016. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2016 Martin Uecker <[email protected]> * 2014 Jonathan Tamir <[email protected]> */ #include <complex.h> #include <stdbool.h> #include "num/multind.h" #include "num/init.h" #include "misc/resize.h" #include "misc/mmio.h" #include "misc/misc.h" #include "misc/opts.h" #ifndef DIMS #define DIMS 16 #endif #ifndef CFL_SIZE #define CFL_SIZE sizeof(complex float) #endif static const char help_str[] = "Resizes an array along dimensions to sizes by truncating or zero-padding. Please see doc/resize.txt for examples."; int main_resize(int argc, char* argv[argc]) { long count = 0; unsigned int* dims = NULL; unsigned int* sizes = NULL; const char* in_file = NULL; const char* out_file = NULL; struct arg_s args[] = { ARG_TUPLE(true, &count, 2, { OPT_UINT, sizeof(*dims), &dims, "dim" }, { OPT_UINT, sizeof(*sizes), &sizes, "size" }), ARG_INFILE(true, &in_file, "input"), ARG_OUTFILE(true, &out_file, "output"), }; bool center = false; const struct opt_s opts[] = { OPT_SET('c', &center, "center"), }; cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts); num_init(); unsigned int N = DIMS; long in_dims[N]; long out_dims[N]; void* in_data = load_cfl(in_file, N, in_dims); md_copy_dims(N, out_dims, in_dims); for (int i = 0; i < count; i++) { unsigned int dim = dims[i]; unsigned int size = sizes[i]; assert(dim < N); assert(size >= 1); out_dims[dim] = size; } void* out_data = create_cfl(out_file, N, out_dims); (center ? md_resize_center : md_resize)(N, out_dims, out_data, in_dims, in_data, CFL_SIZE); unmap_cfl(N, in_dims, in_data); unmap_cfl(N, out_dims, out_data); xfree(dims); xfree(sizes); return 0; }
530775.c
/*------------------------------------------------------------------------- * * initsplan.c * Target list, qualification, joininfo initialization routines * * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/optimizer/plan/initsplan.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "catalog/pg_type.h" #include "nodes/nodeFuncs.h" #include "optimizer/clauses.h" #include "optimizer/joininfo.h" #include "optimizer/pathnode.h" #include "optimizer/paths.h" #include "optimizer/placeholder.h" #include "optimizer/planmain.h" #include "optimizer/planner.h" #include "optimizer/prep.h" #include "optimizer/restrictinfo.h" #include "optimizer/var.h" #include "parser/analyze.h" #include "rewrite/rewriteManip.h" #include "utils/lsyscache.h" /* These parameters are set by GUC */ int from_collapse_limit; int join_collapse_limit; /* Elements of the postponed_qual_list used during deconstruct_recurse */ typedef struct PostponedQual { Node *qual; /* a qual clause waiting to be processed */ Relids relids; /* the set of baserels it references */ } PostponedQual; static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex); static void add_lateral_info(PlannerInfo *root, Relids lhs, Relids rhs); static List *deconstruct_recurse(PlannerInfo *root, Node *jtnode, bool below_outer_join, Relids *qualscope, Relids *inner_join_rels, List **postponed_qual_list); static SpecialJoinInfo *make_outerjoininfo(PlannerInfo *root, Relids left_rels, Relids right_rels, Relids inner_join_rels, JoinType jointype, List *clause); static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, bool is_deduced, bool below_outer_join, JoinType jointype, Relids qualscope, Relids ojscope, Relids outerjoin_nonnullable, Relids deduced_nullable_relids, List **postponed_qual_list); static bool check_outerjoin_delay(PlannerInfo *root, Relids *relids_p, Relids *nullable_relids_p, bool is_pushed_down); static bool check_equivalence_delay(PlannerInfo *root, RestrictInfo *restrictinfo); static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause); static void check_mergejoinable(RestrictInfo *restrictinfo); static void check_hashjoinable(RestrictInfo *restrictinfo); /***************************************************************************** * * JOIN TREES * *****************************************************************************/ /* * add_base_rels_to_query * * Scan the query's jointree and create baserel RelOptInfos for all * the base relations (ie, table, subquery, and function RTEs) * appearing in the jointree. * * The initial invocation must pass root->parse->jointree as the value of * jtnode. Internally, the function recurses through the jointree. * * At the end of this process, there should be one baserel RelOptInfo for * every non-join RTE that is used in the query. Therefore, this routine * is the only place that should call build_simple_rel with reloptkind * RELOPT_BASEREL. (Note: build_simple_rel recurses internally to build * "other rel" RelOptInfos for the members of any appendrels we find here.) */ void add_base_rels_to_query(PlannerInfo *root, Node *jtnode) { if (jtnode == NULL) return; if (IsA(jtnode, RangeTblRef)) { int varno = ((RangeTblRef *) jtnode)->rtindex; (void) build_simple_rel(root, varno, RELOPT_BASEREL); } else if (IsA(jtnode, FromExpr)) { FromExpr *f = (FromExpr *) jtnode; ListCell *l; foreach(l, f->fromlist) add_base_rels_to_query(root, lfirst(l)); } else if (IsA(jtnode, JoinExpr)) { JoinExpr *j = (JoinExpr *) jtnode; add_base_rels_to_query(root, j->larg); add_base_rels_to_query(root, j->rarg); } else elog(ERROR, "unrecognized node type: %d", (int) nodeTag(jtnode)); } /***************************************************************************** * * TARGET LISTS * *****************************************************************************/ /* * build_base_rel_tlists * Add targetlist entries for each var needed in the query's final tlist * to the appropriate base relations. * * We mark such vars as needed by "relation 0" to ensure that they will * propagate up through all join plan steps. */ void build_base_rel_tlists(PlannerInfo *root, List *final_tlist) { List *tlist_vars = pull_var_clause((Node *) final_tlist, PVC_RECURSE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS); if (tlist_vars != NIL) { add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0), true); list_free(tlist_vars); } } /* * add_vars_to_targetlist * For each variable appearing in the list, add it to the owning * relation's targetlist if not already present, and mark the variable * as being needed for the indicated join (or for final output if * where_needed includes "relation 0"). * * The list may also contain PlaceHolderVars. These don't necessarily * have a single owning relation; we keep their attr_needed info in * root->placeholder_list instead. If create_new_ph is true, it's OK * to create new PlaceHolderInfos; otherwise, the PlaceHolderInfos must * already exist, and we should only update their ph_needed. (This should * be true before deconstruct_jointree begins, and false after that.) */ void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed, bool create_new_ph) { ListCell *temp; Assert(!bms_is_empty(where_needed)); foreach(temp, vars) { Node *node = (Node *) lfirst(temp); if (IsA(node, Var)) { Var *var = (Var *) node; RelOptInfo *rel = find_base_rel(root, var->varno); int attno = var->varattno; if (bms_is_subset(where_needed, rel->relids)) continue; Assert(attno >= rel->min_attr && attno <= rel->max_attr); attno -= rel->min_attr; if (rel->attr_needed[attno] == NULL) { /* Variable not yet requested, so add to reltargetlist */ /* XXX is copyObject necessary here? */ rel->reltargetlist = lappend(rel->reltargetlist, copyObject(var)); } rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno], where_needed); } else if (IsA(node, PlaceHolderVar)) { PlaceHolderVar *phv = (PlaceHolderVar *) node; PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, create_new_ph); phinfo->ph_needed = bms_add_members(phinfo->ph_needed, where_needed); } else elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node)); } } /***************************************************************************** * * LATERAL REFERENCES * *****************************************************************************/ /* * find_lateral_references * For each LATERAL subquery, extract all its references to Vars and * PlaceHolderVars of the current query level, and make sure those values * will be available for evaluation of the subquery. * * While later planning steps ensure that the Var/PHV source rels are on the * outside of nestloops relative to the LATERAL subquery, we also need to * ensure that the Vars/PHVs propagate up to the nestloop join level; this * means setting suitable where_needed values for them. * * Note that this only deals with lateral references in unflattened LATERAL * subqueries. When we flatten a LATERAL subquery, its lateral references * become plain Vars in the parent query, but they may have to be wrapped in * PlaceHolderVars if they need to be forced NULL by outer joins that don't * also null the LATERAL subquery. That's all handled elsewhere. * * This has to run before deconstruct_jointree, since it might result in * creation of PlaceHolderInfos. */ void find_lateral_references(PlannerInfo *root) { Index rti; /* We need do nothing if the query contains no LATERAL RTEs */ if (!root->hasLateralRTEs) return; /* * Examine all baserels (the rel array has been set up by now). */ for (rti = 1; rti < root->simple_rel_array_size; rti++) { RelOptInfo *brel = root->simple_rel_array[rti]; /* there may be empty slots corresponding to non-baserel RTEs */ if (brel == NULL) continue; Assert(brel->relid == rti); /* sanity check on array */ /* * This bit is less obvious than it might look. We ignore appendrel * otherrels and consider only their parent baserels. In a case where * a LATERAL-containing UNION ALL subquery was pulled up, it is the * otherrel that is actually going to be in the plan. However, we * want to mark all its lateral references as needed by the parent, * because it is the parent's relid that will be used for join * planning purposes. And the parent's RTE will contain all the * lateral references we need to know, since the pulled-up member is * nothing but a copy of parts of the original RTE's subquery. We * could visit the parent's children instead and transform their * references back to the parent's relid, but it would be much more * complicated for no real gain. (Important here is that the child * members have not yet received any processing beyond being pulled * up.) Similarly, in appendrels created by inheritance expansion, * it's sufficient to look at the parent relation. */ /* ignore RTEs that are "other rels" */ if (brel->reloptkind != RELOPT_BASEREL) continue; extract_lateral_references(root, brel, rti); } } static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex) { RangeTblEntry *rte = root->simple_rte_array[rtindex]; List *vars; List *newvars; Relids where_needed; ListCell *lc; /* No cross-references are possible if it's not LATERAL */ if (!rte->lateral) return; /* Fetch the appropriate variables */ if (rte->rtekind == RTE_SUBQUERY) vars = pull_vars_of_level((Node *) rte->subquery, 1); else if (rte->rtekind == RTE_FUNCTION) vars = pull_vars_of_level(rte->funcexpr, 0); else if (rte->rtekind == RTE_VALUES) vars = pull_vars_of_level((Node *) rte->values_lists, 0); else { Assert(false); return; /* keep compiler quiet */ } if (vars == NIL) return; /* nothing to do */ /* Copy each Var (or PlaceHolderVar) and adjust it to match our level */ newvars = NIL; foreach(lc, vars) { Node *node = (Node *) lfirst(lc); node = copyObject(node); if (IsA(node, Var)) { Var *var = (Var *) node; /* Adjustment is easy since it's just one node */ var->varlevelsup = 0; } else if (IsA(node, PlaceHolderVar)) { PlaceHolderVar *phv = (PlaceHolderVar *) node; int levelsup = phv->phlevelsup; /* Have to work harder to adjust the contained expression too */ if (levelsup != 0) IncrementVarSublevelsUp(node, -levelsup, 0); /* * If we pulled the PHV out of a subquery RTE, its expression * needs to be preprocessed. subquery_planner() already did this * for level-zero PHVs in function and values RTEs, though. */ if (levelsup > 0) phv->phexpr = preprocess_phv_expression(root, phv->phexpr); } else Assert(false); newvars = lappend(newvars, node); } list_free(vars); /* * We mark the Vars as being "needed" at the LATERAL RTE. This is a bit * of a cheat: a more formal approach would be to mark each one as needed * at the join of the LATERAL RTE with its source RTE. But it will work, * and it's much less tedious than computing a separate where_needed for * each Var. */ where_needed = bms_make_singleton(rtindex); /* * Push Vars into their source relations' targetlists, and PHVs into * root->placeholder_list. */ add_vars_to_targetlist(root, newvars, where_needed, true); /* Remember the lateral references for create_lateral_join_info */ brel->lateral_vars = newvars; } /* * create_lateral_join_info * For each unflattened LATERAL subquery, create LateralJoinInfo(s) and add * them to root->lateral_info_list, and fill in the per-rel lateral_relids * and lateral_referencers sets. Also generate LateralJoinInfo(s) to * represent any lateral references within PlaceHolderVars (this part deals * with the effects of flattened LATERAL subqueries). * * This has to run after deconstruct_jointree, because we need to know the * final ph_eval_at values for PlaceHolderVars. */ void create_lateral_join_info(PlannerInfo *root) { Index rti; ListCell *lc; /* We need do nothing if the query contains no LATERAL RTEs */ if (!root->hasLateralRTEs) return; /* * Examine all baserels (the rel array has been set up by now). */ for (rti = 1; rti < root->simple_rel_array_size; rti++) { RelOptInfo *brel = root->simple_rel_array[rti]; Relids lateral_relids; /* there may be empty slots corresponding to non-baserel RTEs */ if (brel == NULL) continue; Assert(brel->relid == rti); /* sanity check on array */ /* ignore RTEs that are "other rels" */ if (brel->reloptkind != RELOPT_BASEREL) continue; lateral_relids = NULL; /* consider each laterally-referenced Var or PHV */ foreach(lc, brel->lateral_vars) { Node *node = (Node *) lfirst(lc); if (IsA(node, Var)) { Var *var = (Var *) node; add_lateral_info(root, bms_make_singleton(var->varno), brel->relids); lateral_relids = bms_add_member(lateral_relids, var->varno); } else if (IsA(node, PlaceHolderVar)) { PlaceHolderVar *phv = (PlaceHolderVar *) node; PlaceHolderInfo *phinfo = find_placeholder_info(root, phv, false); add_lateral_info(root, phinfo->ph_eval_at, brel->relids); lateral_relids = bms_add_members(lateral_relids, phinfo->ph_eval_at); } else Assert(false); } /* We now know all the relids needed for lateral refs in this rel */ if (bms_is_empty(lateral_relids)) continue; /* ensure lateral_relids is NULL if empty */ brel->lateral_relids = lateral_relids; } /* * Now check for lateral references within PlaceHolderVars, and make * LateralJoinInfos describing each such reference. Unlike references in * unflattened LATERAL RTEs, the referencing location could be a join. */ foreach(lc, root->placeholder_list) { PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc); Relids eval_at = phinfo->ph_eval_at; if (phinfo->ph_lateral != NULL) { List *vars = pull_var_clause((Node *) phinfo->ph_var->phexpr, PVC_RECURSE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS); ListCell *lc2; foreach(lc2, vars) { Node *node = (Node *) lfirst(lc2); if (IsA(node, Var)) { Var *var = (Var *) node; if (!bms_is_member(var->varno, eval_at)) add_lateral_info(root, bms_make_singleton(var->varno), eval_at); } else if (IsA(node, PlaceHolderVar)) { PlaceHolderVar *other_phv = (PlaceHolderVar *) node; PlaceHolderInfo *other_phi; other_phi = find_placeholder_info(root, other_phv, false); if (!bms_is_subset(other_phi->ph_eval_at, eval_at)) add_lateral_info(root, other_phi->ph_eval_at, eval_at); } else Assert(false); } list_free(vars); } } /* If we found no lateral references, we're done. */ if (root->lateral_info_list == NIL) return; /* * Now that we've identified all lateral references, make a second pass in * which we mark each baserel with the set of relids of rels that * reference it laterally (essentially, the inverse mapping of * lateral_relids). We'll need this for join_clause_is_movable_to(). * * Also, propagate lateral_relids and lateral_referencers from appendrel * parent rels to their child rels. We intentionally give each child rel * the same minimum parameterization, even though it's quite possible that * some don't reference all the lateral rels. This is because any append * path for the parent will have to have the same parameterization for * every child anyway, and there's no value in forcing extra * reparameterize_path() calls. Similarly, a lateral reference to the * parent prevents use of otherwise-movable join rels for each child. */ for (rti = 1; rti < root->simple_rel_array_size; rti++) { RelOptInfo *brel = root->simple_rel_array[rti]; Relids lateral_referencers; if (brel == NULL) continue; if (brel->reloptkind != RELOPT_BASEREL) continue; /* Compute lateral_referencers using the finished lateral_info_list */ lateral_referencers = NULL; foreach(lc, root->lateral_info_list) { LateralJoinInfo *ljinfo = (LateralJoinInfo *) lfirst(lc); if (bms_is_member(brel->relid, ljinfo->lateral_lhs)) lateral_referencers = bms_add_members(lateral_referencers, ljinfo->lateral_rhs); } brel->lateral_referencers = lateral_referencers; /* * If it's an appendrel parent, copy its lateral_relids and * lateral_referencers to each child rel. */ if (root->simple_rte_array[rti]->inh) { foreach(lc, root->append_rel_list) { AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc); RelOptInfo *childrel; if (appinfo->parent_relid != rti) continue; childrel = root->simple_rel_array[appinfo->child_relid]; Assert(childrel->reloptkind == RELOPT_OTHER_MEMBER_REL); Assert(childrel->lateral_relids == NULL); childrel->lateral_relids = brel->lateral_relids; Assert(childrel->lateral_referencers == NULL); childrel->lateral_referencers = brel->lateral_referencers; } } } } /* * add_lateral_info * Add a LateralJoinInfo to root->lateral_info_list, if needed * * We suppress redundant list entries. The passed Relids are copied if saved. */ static void add_lateral_info(PlannerInfo *root, Relids lhs, Relids rhs) { LateralJoinInfo *ljinfo; ListCell *lc; /* Sanity-check the input */ Assert(!bms_is_empty(lhs)); Assert(!bms_is_empty(rhs)); Assert(!bms_overlap(lhs, rhs)); /* * The input is redundant if it has the same RHS and an LHS that is a * subset of an existing entry's. If an existing entry has the same RHS * and an LHS that is a subset of the new one, it's redundant, but we * don't trouble to get rid of it. The only case that is really worth * worrying about is identical entries, and we handle that well enough * with this simple logic. */ foreach(lc, root->lateral_info_list) { ljinfo = (LateralJoinInfo *) lfirst(lc); if (bms_equal(rhs, ljinfo->lateral_rhs) && bms_is_subset(lhs, ljinfo->lateral_lhs)) return; } /* Not there, so make a new entry */ ljinfo = makeNode(LateralJoinInfo); ljinfo->lateral_lhs = bms_copy(lhs); ljinfo->lateral_rhs = bms_copy(rhs); root->lateral_info_list = lappend(root->lateral_info_list, ljinfo); } /***************************************************************************** * * JOIN TREE PROCESSING * *****************************************************************************/ /* * deconstruct_jointree * Recursively scan the query's join tree for WHERE and JOIN/ON qual * clauses, and add these to the appropriate restrictinfo and joininfo * lists belonging to base RelOptInfos. Also, add SpecialJoinInfo nodes * to root->join_info_list for any outer joins appearing in the query tree. * Return a "joinlist" data structure showing the join order decisions * that need to be made by make_one_rel(). * * The "joinlist" result is a list of items that are either RangeTblRef * jointree nodes or sub-joinlists. All the items at the same level of * joinlist must be joined in an order to be determined by make_one_rel() * (note that legal orders may be constrained by SpecialJoinInfo nodes). * A sub-joinlist represents a subproblem to be planned separately. Currently * sub-joinlists arise only from FULL OUTER JOIN or when collapsing of * subproblems is stopped by join_collapse_limit or from_collapse_limit. * * NOTE: when dealing with inner joins, it is appropriate to let a qual clause * be evaluated at the lowest level where all the variables it mentions are * available. However, we cannot push a qual down into the nullable side(s) * of an outer join since the qual might eliminate matching rows and cause a * NULL row to be incorrectly emitted by the join. Therefore, we artificially * OR the minimum-relids of such an outer join into the required_relids of * clauses appearing above it. This forces those clauses to be delayed until * application of the outer join (or maybe even higher in the join tree). */ List * deconstruct_jointree(PlannerInfo *root) { List *result; Relids qualscope; Relids inner_join_rels; List *postponed_qual_list = NIL; /* Start recursion at top of jointree */ Assert(root->parse->jointree != NULL && IsA(root->parse->jointree, FromExpr)); /* this is filled as we scan the jointree */ root->nullable_baserels = NULL; result = deconstruct_recurse(root, (Node *) root->parse->jointree, false, &qualscope, &inner_join_rels, &postponed_qual_list); /* Shouldn't be any leftover quals */ Assert(postponed_qual_list == NIL); return result; } /* * deconstruct_recurse * One recursion level of deconstruct_jointree processing. * * Inputs: * jtnode is the jointree node to examine * below_outer_join is TRUE if this node is within the nullable side of a * higher-level outer join * Outputs: * *qualscope gets the set of base Relids syntactically included in this * jointree node (do not modify or free this, as it may also be pointed * to by RestrictInfo and SpecialJoinInfo nodes) * *inner_join_rels gets the set of base Relids syntactically included in * inner joins appearing at or below this jointree node (do not modify * or free this, either) * *postponed_qual_list is a list of PostponedQual structs, which we can * add quals to if they turn out to belong to a higher join level * Return value is the appropriate joinlist for this jointree node * * In addition, entries will be added to root->join_info_list for outer joins. */ static List * deconstruct_recurse(PlannerInfo *root, Node *jtnode, bool below_outer_join, Relids *qualscope, Relids *inner_join_rels, List **postponed_qual_list) { List *joinlist; if (jtnode == NULL) { *qualscope = NULL; *inner_join_rels = NULL; return NIL; } if (IsA(jtnode, RangeTblRef)) { int varno = ((RangeTblRef *) jtnode)->rtindex; /* No quals to deal with, just return correct result */ *qualscope = bms_make_singleton(varno); /* A single baserel does not create an inner join */ *inner_join_rels = NULL; joinlist = list_make1(jtnode); } else if (IsA(jtnode, FromExpr)) { FromExpr *f = (FromExpr *) jtnode; List *child_postponed_quals = NIL; int remaining; ListCell *l; /* * First, recurse to handle child joins. We collapse subproblems into * a single joinlist whenever the resulting joinlist wouldn't exceed * from_collapse_limit members. Also, always collapse one-element * subproblems, since that won't lengthen the joinlist anyway. */ *qualscope = NULL; *inner_join_rels = NULL; joinlist = NIL; remaining = list_length(f->fromlist); foreach(l, f->fromlist) { Relids sub_qualscope; List *sub_joinlist; int sub_members; sub_joinlist = deconstruct_recurse(root, lfirst(l), below_outer_join, &sub_qualscope, inner_join_rels, &child_postponed_quals); *qualscope = bms_add_members(*qualscope, sub_qualscope); sub_members = list_length(sub_joinlist); remaining--; if (sub_members <= 1 || list_length(joinlist) + sub_members + remaining <= from_collapse_limit) joinlist = list_concat(joinlist, sub_joinlist); else joinlist = lappend(joinlist, sub_joinlist); } /* * A FROM with more than one list element is an inner join subsuming * all below it, so we should report inner_join_rels = qualscope. If * there was exactly one element, we should (and already did) report * whatever its inner_join_rels were. If there were no elements (is * that possible?) the initialization before the loop fixed it. */ if (list_length(f->fromlist) > 1) *inner_join_rels = *qualscope; /* * Try to process any quals postponed by children. If they need * further postponement, add them to my output postponed_qual_list. */ foreach(l, child_postponed_quals) { PostponedQual *pq = (PostponedQual *) lfirst(l); if (bms_is_subset(pq->relids, *qualscope)) distribute_qual_to_rels(root, pq->qual, false, below_outer_join, JOIN_INNER, *qualscope, NULL, NULL, NULL, NULL); else *postponed_qual_list = lappend(*postponed_qual_list, pq); } /* * Now process the top-level quals. */ foreach(l, (List *) f->quals) { Node *qual = (Node *) lfirst(l); distribute_qual_to_rels(root, qual, false, below_outer_join, JOIN_INNER, *qualscope, NULL, NULL, NULL, postponed_qual_list); } } else if (IsA(jtnode, JoinExpr)) { JoinExpr *j = (JoinExpr *) jtnode; List *child_postponed_quals = NIL; Relids leftids, rightids, left_inners, right_inners, nonnullable_rels, nullable_rels, ojscope; List *leftjoinlist, *rightjoinlist; SpecialJoinInfo *sjinfo; ListCell *l; /* * Order of operations here is subtle and critical. First we recurse * to handle sub-JOINs. Their join quals will be placed without * regard for whether this level is an outer join, which is correct. * Then we place our own join quals, which are restricted by lower * outer joins in any case, and are forced to this level if this is an * outer join and they mention the outer side. Finally, if this is an * outer join, we create a join_info_list entry for the join. This * will prevent quals above us in the join tree that use those rels * from being pushed down below this level. (It's okay for upper * quals to be pushed down to the outer side, however.) */ switch (j->jointype) { case JOIN_INNER: leftjoinlist = deconstruct_recurse(root, j->larg, below_outer_join, &leftids, &left_inners, &child_postponed_quals); rightjoinlist = deconstruct_recurse(root, j->rarg, below_outer_join, &rightids, &right_inners, &child_postponed_quals); *qualscope = bms_union(leftids, rightids); *inner_join_rels = *qualscope; /* Inner join adds no restrictions for quals */ nonnullable_rels = NULL; /* and it doesn't force anything to null, either */ nullable_rels = NULL; break; case JOIN_LEFT: case JOIN_ANTI: leftjoinlist = deconstruct_recurse(root, j->larg, below_outer_join, &leftids, &left_inners, &child_postponed_quals); rightjoinlist = deconstruct_recurse(root, j->rarg, true, &rightids, &right_inners, &child_postponed_quals); *qualscope = bms_union(leftids, rightids); *inner_join_rels = bms_union(left_inners, right_inners); nonnullable_rels = leftids; nullable_rels = rightids; break; case JOIN_SEMI: leftjoinlist = deconstruct_recurse(root, j->larg, below_outer_join, &leftids, &left_inners, &child_postponed_quals); rightjoinlist = deconstruct_recurse(root, j->rarg, below_outer_join, &rightids, &right_inners, &child_postponed_quals); *qualscope = bms_union(leftids, rightids); *inner_join_rels = bms_union(left_inners, right_inners); /* Semi join adds no restrictions for quals */ nonnullable_rels = NULL; /* * Theoretically, a semijoin would null the RHS; but since the * RHS can't be accessed above the join, this is immaterial * and we needn't account for it. */ nullable_rels = NULL; break; case JOIN_FULL: leftjoinlist = deconstruct_recurse(root, j->larg, true, &leftids, &left_inners, &child_postponed_quals); rightjoinlist = deconstruct_recurse(root, j->rarg, true, &rightids, &right_inners, &child_postponed_quals); *qualscope = bms_union(leftids, rightids); *inner_join_rels = bms_union(left_inners, right_inners); /* each side is both outer and inner */ nonnullable_rels = *qualscope; nullable_rels = *qualscope; break; default: /* JOIN_RIGHT was eliminated during reduce_outer_joins() */ elog(ERROR, "unrecognized join type: %d", (int) j->jointype); nonnullable_rels = NULL; /* keep compiler quiet */ nullable_rels = NULL; leftjoinlist = rightjoinlist = NIL; break; } /* Report all rels that will be nulled anywhere in the jointree */ root->nullable_baserels = bms_add_members(root->nullable_baserels, nullable_rels); /* * For an OJ, form the SpecialJoinInfo now, because we need the OJ's * semantic scope (ojscope) to pass to distribute_qual_to_rels. But * we mustn't add it to join_info_list just yet, because we don't want * distribute_qual_to_rels to think it is an outer join below us. * * Semijoins are a bit of a hybrid: we build a SpecialJoinInfo, but we * want ojscope = NULL for distribute_qual_to_rels. */ if (j->jointype != JOIN_INNER) { sjinfo = make_outerjoininfo(root, leftids, rightids, *inner_join_rels, j->jointype, (List *) j->quals); if (j->jointype == JOIN_SEMI) ojscope = NULL; else ojscope = bms_union(sjinfo->min_lefthand, sjinfo->min_righthand); } else { sjinfo = NULL; ojscope = NULL; } /* * Try to process any quals postponed by children. If they need * further postponement, add them to my output postponed_qual_list. */ foreach(l, child_postponed_quals) { PostponedQual *pq = (PostponedQual *) lfirst(l); if (bms_is_subset(pq->relids, *qualscope)) distribute_qual_to_rels(root, pq->qual, false, below_outer_join, j->jointype, *qualscope, ojscope, nonnullable_rels, NULL, NULL); else { /* * We should not be postponing any quals past an outer join. * If this Assert fires, pull_up_subqueries() messed up. */ Assert(j->jointype == JOIN_INNER); *postponed_qual_list = lappend(*postponed_qual_list, pq); } } /* Process the JOIN's qual clauses */ foreach(l, (List *) j->quals) { Node *qual = (Node *) lfirst(l); distribute_qual_to_rels(root, qual, false, below_outer_join, j->jointype, *qualscope, ojscope, nonnullable_rels, NULL, postponed_qual_list); } /* Now we can add the SpecialJoinInfo to join_info_list */ if (sjinfo) { root->join_info_list = lappend(root->join_info_list, sjinfo); /* Each time we do that, recheck placeholder eval levels */ update_placeholder_eval_levels(root, sjinfo); } /* * Finally, compute the output joinlist. We fold subproblems together * except at a FULL JOIN or where join_collapse_limit would be * exceeded. */ if (j->jointype == JOIN_FULL) { /* force the join order exactly at this node */ joinlist = list_make1(list_make2(leftjoinlist, rightjoinlist)); } else if (list_length(leftjoinlist) + list_length(rightjoinlist) <= join_collapse_limit) { /* OK to combine subproblems */ joinlist = list_concat(leftjoinlist, rightjoinlist); } else { /* can't combine, but needn't force join order above here */ Node *leftpart, *rightpart; /* avoid creating useless 1-element sublists */ if (list_length(leftjoinlist) == 1) leftpart = (Node *) linitial(leftjoinlist); else leftpart = (Node *) leftjoinlist; if (list_length(rightjoinlist) == 1) rightpart = (Node *) linitial(rightjoinlist); else rightpart = (Node *) rightjoinlist; joinlist = list_make2(leftpart, rightpart); } } else { elog(ERROR, "unrecognized node type: %d", (int) nodeTag(jtnode)); joinlist = NIL; /* keep compiler quiet */ } return joinlist; } /* * make_outerjoininfo * Build a SpecialJoinInfo for the current outer join * * Inputs: * left_rels: the base Relids syntactically on outer side of join * right_rels: the base Relids syntactically on inner side of join * inner_join_rels: base Relids participating in inner joins below this one * jointype: what it says (must always be LEFT, FULL, SEMI, or ANTI) * clause: the outer join's join condition (in implicit-AND format) * * The node should eventually be appended to root->join_info_list, but we * do not do that here. * * Note: we assume that this function is invoked bottom-up, so that * root->join_info_list already contains entries for all outer joins that are * syntactically below this one. */ static SpecialJoinInfo * make_outerjoininfo(PlannerInfo *root, Relids left_rels, Relids right_rels, Relids inner_join_rels, JoinType jointype, List *clause) { SpecialJoinInfo *sjinfo = makeNode(SpecialJoinInfo); Relids clause_relids; Relids strict_relids; Relids min_lefthand; Relids min_righthand; ListCell *l; /* * We should not see RIGHT JOIN here because left/right were switched * earlier */ Assert(jointype != JOIN_INNER); Assert(jointype != JOIN_RIGHT); /* * Presently the executor cannot support FOR [KEY] UPDATE/SHARE marking of * rels appearing on the nullable side of an outer join. (It's somewhat * unclear what that would mean, anyway: what should we mark when a result * row is generated from no element of the nullable relation?) So, * complain if any nullable rel is FOR [KEY] UPDATE/SHARE. * * You might be wondering why this test isn't made far upstream in the * parser. It's because the parser hasn't got enough info --- consider * FOR UPDATE applied to a view. Only after rewriting and flattening do * we know whether the view contains an outer join. * * We use the original RowMarkClause list here; the PlanRowMark list would * list everything. */ foreach(l, root->parse->rowMarks) { RowMarkClause *rc = (RowMarkClause *) lfirst(l); if (bms_is_member(rc->rti, right_rels) || (jointype == JOIN_FULL && bms_is_member(rc->rti, left_rels))) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), /*------ translator: %s is a SQL row locking clause such as FOR UPDATE */ errmsg("%s cannot be applied to the nullable side of an outer join", LCS_asString(rc->strength)))); } sjinfo->syn_lefthand = left_rels; sjinfo->syn_righthand = right_rels; sjinfo->jointype = jointype; /* this always starts out false */ sjinfo->delay_upper_joins = false; sjinfo->join_quals = clause; /* If it's a full join, no need to be very smart */ if (jointype == JOIN_FULL) { sjinfo->min_lefthand = bms_copy(left_rels); sjinfo->min_righthand = bms_copy(right_rels); sjinfo->lhs_strict = false; /* don't care about this */ return sjinfo; } /* * Retrieve all relids mentioned within the join clause. */ clause_relids = pull_varnos((Node *) clause); /* * For which relids is the clause strict, ie, it cannot succeed if the * rel's columns are all NULL? */ strict_relids = find_nonnullable_rels((Node *) clause); /* Remember whether the clause is strict for any LHS relations */ sjinfo->lhs_strict = bms_overlap(strict_relids, left_rels); /* * Required LHS always includes the LHS rels mentioned in the clause. We * may have to add more rels based on lower outer joins; see below. */ min_lefthand = bms_intersect(clause_relids, left_rels); /* * Similarly for required RHS. But here, we must also include any lower * inner joins, to ensure we don't try to commute with any of them. */ min_righthand = bms_int_members(bms_union(clause_relids, inner_join_rels), right_rels); foreach(l, root->join_info_list) { SpecialJoinInfo *otherinfo = (SpecialJoinInfo *) lfirst(l); /* ignore full joins --- other mechanisms preserve their ordering */ if (otherinfo->jointype == JOIN_FULL) continue; /* * For a lower OJ in our LHS, if our join condition uses the lower * join's RHS and is not strict for that rel, we must preserve the * ordering of the two OJs, so add lower OJ's full syntactic relset to * min_lefthand. (We must use its full syntactic relset, not just its * min_lefthand + min_righthand. This is because there might be other * OJs below this one that this one can commute with, but we cannot * commute with them if we don't with this one.) Also, if the current * join is a semijoin or antijoin, we must preserve ordering * regardless of strictness. * * Note: I believe we have to insist on being strict for at least one * rel in the lower OJ's min_righthand, not its whole syn_righthand. */ if (bms_overlap(left_rels, otherinfo->syn_righthand)) { if (bms_overlap(clause_relids, otherinfo->syn_righthand) && (jointype == JOIN_SEMI || jointype == JOIN_ANTI || !bms_overlap(strict_relids, otherinfo->min_righthand))) { min_lefthand = bms_add_members(min_lefthand, otherinfo->syn_lefthand); min_lefthand = bms_add_members(min_lefthand, otherinfo->syn_righthand); } } /* * For a lower OJ in our RHS, if our join condition does not use the * lower join's RHS and the lower OJ's join condition is strict, we * can interchange the ordering of the two OJs; otherwise we must add * lower OJ's full syntactic relset to min_righthand. Here, we must * preserve ordering anyway if either the current join is a semijoin, * or the lower OJ is either a semijoin or an antijoin. * * Here, we have to consider that "our join condition" includes any * clauses that syntactically appeared above the lower OJ and below * ours; those are equivalent to degenerate clauses in our OJ and must * be treated as such. Such clauses obviously can't reference our * LHS, and they must be non-strict for the lower OJ's RHS (else * reduce_outer_joins would have reduced the lower OJ to a plain * join). Hence the other ways in which we handle clauses within our * join condition are not affected by them. The net effect is * therefore sufficiently represented by the delay_upper_joins flag * saved for us by check_outerjoin_delay. */ if (bms_overlap(right_rels, otherinfo->syn_righthand)) { if (bms_overlap(clause_relids, otherinfo->syn_righthand) || jointype == JOIN_SEMI || otherinfo->jointype == JOIN_SEMI || otherinfo->jointype == JOIN_ANTI || !otherinfo->lhs_strict || otherinfo->delay_upper_joins) { min_righthand = bms_add_members(min_righthand, otherinfo->syn_lefthand); min_righthand = bms_add_members(min_righthand, otherinfo->syn_righthand); } } } /* * Examine PlaceHolderVars. If a PHV is supposed to be evaluated within * this join's nullable side, then ensure that min_righthand contains the * full eval_at set of the PHV. This ensures that the PHV actually can be * evaluated within the RHS. Note that this works only because we should * already have determined the final eval_at level for any PHV * syntactically within this join. */ foreach(l, root->placeholder_list) { PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(l); Relids ph_syn_level = phinfo->ph_var->phrels; /* Ignore placeholder if it didn't syntactically come from RHS */ if (!bms_is_subset(ph_syn_level, right_rels)) continue; /* Else, prevent join from being formed before we eval the PHV */ min_righthand = bms_add_members(min_righthand, phinfo->ph_eval_at); } /* * If we found nothing to put in min_lefthand, punt and make it the full * LHS, to avoid having an empty min_lefthand which will confuse later * processing. (We don't try to be smart about such cases, just correct.) * Likewise for min_righthand. */ if (bms_is_empty(min_lefthand)) min_lefthand = bms_copy(left_rels); if (bms_is_empty(min_righthand)) min_righthand = bms_copy(right_rels); /* Now they'd better be nonempty */ Assert(!bms_is_empty(min_lefthand)); Assert(!bms_is_empty(min_righthand)); /* Shouldn't overlap either */ Assert(!bms_overlap(min_lefthand, min_righthand)); sjinfo->min_lefthand = min_lefthand; sjinfo->min_righthand = min_righthand; return sjinfo; } /***************************************************************************** * * QUALIFICATIONS * *****************************************************************************/ /* * distribute_qual_to_rels * Add clause information to either the baserestrictinfo or joininfo list * (depending on whether the clause is a join) of each base relation * mentioned in the clause. A RestrictInfo node is created and added to * the appropriate list for each rel. Alternatively, if the clause uses a * mergejoinable operator and is not delayed by outer-join rules, enter * the left- and right-side expressions into the query's list of * EquivalenceClasses. Alternatively, if the clause needs to be treated * as belonging to a higher join level, just add it to postponed_qual_list. * * 'clause': the qual clause to be distributed * 'is_deduced': TRUE if the qual came from implied-equality deduction * 'below_outer_join': TRUE if the qual is from a JOIN/ON that is below the * nullable side of a higher-level outer join * 'jointype': type of join the qual is from (JOIN_INNER for a WHERE clause) * 'qualscope': set of baserels the qual's syntactic scope covers * 'ojscope': NULL if not an outer-join qual, else the minimum set of baserels * needed to form this join * 'outerjoin_nonnullable': NULL if not an outer-join qual, else the set of * baserels appearing on the outer (nonnullable) side of the join * (for FULL JOIN this includes both sides of the join, and must in fact * equal qualscope) * 'deduced_nullable_relids': if is_deduced is TRUE, the nullable relids to * impute to the clause; otherwise NULL * 'postponed_qual_list': list of PostponedQual structs, which we can add * this qual to if it turns out to belong to a higher join level. * Can be NULL if caller knows postponement is impossible. * * 'qualscope' identifies what level of JOIN the qual came from syntactically. * 'ojscope' is needed if we decide to force the qual up to the outer-join * level, which will be ojscope not necessarily qualscope. * * In normal use (when is_deduced is FALSE), at the time this is called, * root->join_info_list must contain entries for all and only those special * joins that are syntactically below this qual. But when is_deduced is TRUE, * we are adding new deduced clauses after completion of deconstruct_jointree, * so it cannot be assumed that root->join_info_list has anything to do with * qual placement. */ static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, bool is_deduced, bool below_outer_join, JoinType jointype, Relids qualscope, Relids ojscope, Relids outerjoin_nonnullable, Relids deduced_nullable_relids, List **postponed_qual_list) { Relids relids; bool is_pushed_down; bool outerjoin_delayed; bool pseudoconstant = false; bool maybe_equivalence; bool maybe_outer_join; Relids nullable_relids; RestrictInfo *restrictinfo; /* * Retrieve all relids mentioned within the clause. */ relids = pull_varnos(clause); /* * In ordinary SQL, a WHERE or JOIN/ON clause can't reference any rels * that aren't within its syntactic scope; however, if we pulled up a * LATERAL subquery then we might find such references in quals that have * been pulled up. We need to treat such quals as belonging to the join * level that includes every rel they reference. Although we could make * pull_up_subqueries() place such quals correctly to begin with, it's * easier to handle it here. When we find a clause that contains Vars * outside its syntactic scope, we add it to the postponed-quals list, and * process it once we've recursed back up to the appropriate join level. */ if (!bms_is_subset(relids, qualscope)) { PostponedQual *pq = (PostponedQual *) palloc(sizeof(PostponedQual)); Assert(root->hasLateralRTEs); /* shouldn't happen otherwise */ Assert(jointype == JOIN_INNER); /* mustn't postpone past outer join */ Assert(!is_deduced); /* shouldn't be deduced, either */ pq->qual = clause; pq->relids = relids; *postponed_qual_list = lappend(*postponed_qual_list, pq); return; } /* * If it's an outer-join clause, also check that relids is a subset of * ojscope. (This should not fail if the syntactic scope check passed.) */ if (ojscope && !bms_is_subset(relids, ojscope)) elog(ERROR, "JOIN qualification cannot refer to other relations"); /* * If the clause is variable-free, our normal heuristic for pushing it * down to just the mentioned rels doesn't work, because there are none. * * If the clause is an outer-join clause, we must force it to the OJ's * semantic level to preserve semantics. * * Otherwise, when the clause contains volatile functions, we force it to * be evaluated at its original syntactic level. This preserves the * expected semantics. * * When the clause contains no volatile functions either, it is actually a * pseudoconstant clause that will not change value during any one * execution of the plan, and hence can be used as a one-time qual in a * gating Result plan node. We put such a clause into the regular * RestrictInfo lists for the moment, but eventually createplan.c will * pull it out and make a gating Result node immediately above whatever * plan node the pseudoconstant clause is assigned to. It's usually best * to put a gating node as high in the plan tree as possible. If we are * not below an outer join, we can actually push the pseudoconstant qual * all the way to the top of the tree. If we are below an outer join, we * leave the qual at its original syntactic level (we could push it up to * just below the outer join, but that seems more complex than it's * worth). */ if (bms_is_empty(relids)) { if (ojscope) { /* clause is attached to outer join, eval it there */ relids = bms_copy(ojscope); /* mustn't use as gating qual, so don't mark pseudoconstant */ } else { /* eval at original syntactic level */ relids = bms_copy(qualscope); if (!contain_volatile_functions(clause)) { /* mark as gating qual */ pseudoconstant = true; /* tell createplan.c to check for gating quals */ root->hasPseudoConstantQuals = true; /* if not below outer join, push it to top of tree */ if (!below_outer_join) { relids = get_relids_in_jointree((Node *) root->parse->jointree, false); qualscope = bms_copy(relids); } } } } /*---------- * Check to see if clause application must be delayed by outer-join * considerations. * * A word about is_pushed_down: we mark the qual as "pushed down" if * it is (potentially) applicable at a level different from its original * syntactic level. This flag is used to distinguish OUTER JOIN ON quals * from other quals pushed down to the same joinrel. The rules are: * WHERE quals and INNER JOIN quals: is_pushed_down = true. * Non-degenerate OUTER JOIN quals: is_pushed_down = false. * Degenerate OUTER JOIN quals: is_pushed_down = true. * A "degenerate" OUTER JOIN qual is one that doesn't mention the * non-nullable side, and hence can be pushed down into the nullable side * without changing the join result. It is correct to treat it as a * regular filter condition at the level where it is evaluated. * * Note: it is not immediately obvious that a simple boolean is enough * for this: if for some reason we were to attach a degenerate qual to * its original join level, it would need to be treated as an outer join * qual there. However, this cannot happen, because all the rels the * clause mentions must be in the outer join's min_righthand, therefore * the join it needs must be formed before the outer join; and we always * attach quals to the lowest level where they can be evaluated. But * if we were ever to re-introduce a mechanism for delaying evaluation * of "expensive" quals, this area would need work. *---------- */ if (is_deduced) { /* * If the qual came from implied-equality deduction, it should not be * outerjoin-delayed, else deducer blew it. But we can't check this * because the join_info_list may now contain OJs above where the qual * belongs. For the same reason, we must rely on caller to supply the * correct nullable_relids set. */ Assert(!ojscope); is_pushed_down = true; outerjoin_delayed = false; nullable_relids = deduced_nullable_relids; /* Don't feed it back for more deductions */ maybe_equivalence = false; maybe_outer_join = false; } else if (bms_overlap(relids, outerjoin_nonnullable)) { /* * The qual is attached to an outer join and mentions (some of the) * rels on the nonnullable side, so it's not degenerate. * * We can't use such a clause to deduce equivalence (the left and * right sides might be unequal above the join because one of them has * gone to NULL) ... but we might be able to use it for more limited * deductions, if it is mergejoinable. So consider adding it to the * lists of set-aside outer-join clauses. */ is_pushed_down = false; maybe_equivalence = false; maybe_outer_join = true; /* Check to see if must be delayed by lower outer join */ outerjoin_delayed = check_outerjoin_delay(root, &relids, &nullable_relids, false); /* * Now force the qual to be evaluated exactly at the level of joining * corresponding to the outer join. We cannot let it get pushed down * into the nonnullable side, since then we'd produce no output rows, * rather than the intended single null-extended row, for any * nonnullable-side rows failing the qual. * * (Do this step after calling check_outerjoin_delay, because that * trashes relids.) */ Assert(ojscope); relids = ojscope; Assert(!pseudoconstant); } else { /* * Normal qual clause or degenerate outer-join clause. Either way, we * can mark it as pushed-down. */ is_pushed_down = true; /* Check to see if must be delayed by lower outer join */ outerjoin_delayed = check_outerjoin_delay(root, &relids, &nullable_relids, true); if (outerjoin_delayed) { /* Should still be a subset of current scope ... */ Assert(root->hasLateralRTEs || bms_is_subset(relids, qualscope)); Assert(ojscope == NULL || bms_is_subset(relids, ojscope)); /* * Because application of the qual will be delayed by outer join, * we mustn't assume its vars are equal everywhere. */ maybe_equivalence = false; /* * It's possible that this is an IS NULL clause that's redundant * with a lower antijoin; if so we can just discard it. We need * not test in any of the other cases, because this will only be * possible for pushed-down, delayed clauses. */ if (check_redundant_nullability_qual(root, clause)) return; } else { /* * Qual is not delayed by any lower outer-join restriction, so we * can consider feeding it to the equivalence machinery. However, * if it's itself within an outer-join clause, treat it as though * it appeared below that outer join (note that we can only get * here when the clause references only nullable-side rels). */ maybe_equivalence = true; if (outerjoin_nonnullable != NULL) below_outer_join = true; } /* * Since it doesn't mention the LHS, it's certainly not useful as a * set-aside OJ clause, even if it's in an OJ. */ maybe_outer_join = false; } /* * Build the RestrictInfo node itself. */ restrictinfo = make_restrictinfo((Expr *) clause, is_pushed_down, outerjoin_delayed, pseudoconstant, relids, outerjoin_nonnullable, nullable_relids); /* * If it's a join clause (either naturally, or because delayed by * outer-join rules), add vars used in the clause to targetlists of their * relations, so that they will be emitted by the plan nodes that scan * those relations (else they won't be available at the join node!). * * Note: if the clause gets absorbed into an EquivalenceClass then this * may be unnecessary, but for now we have to do it to cover the case * where the EC becomes ec_broken and we end up reinserting the original * clauses into the plan. */ if (bms_membership(relids) == BMS_MULTIPLE) { List *vars = pull_var_clause(clause, PVC_RECURSE_AGGREGATES, PVC_INCLUDE_PLACEHOLDERS); add_vars_to_targetlist(root, vars, relids, false); list_free(vars); } /* * We check "mergejoinability" of every clause, not only join clauses, * because we want to know about equivalences between vars of the same * relation, or between vars and consts. */ check_mergejoinable(restrictinfo); /* * If it is a true equivalence clause, send it to the EquivalenceClass * machinery. We do *not* attach it directly to any restriction or join * lists. The EC code will propagate it to the appropriate places later. * * If the clause has a mergejoinable operator and is not * outerjoin-delayed, yet isn't an equivalence because it is an outer-join * clause, the EC code may yet be able to do something with it. We add it * to appropriate lists for further consideration later. Specifically: * * If it is a left or right outer-join qualification that relates the two * sides of the outer join (no funny business like leftvar1 = leftvar2 + * rightvar), we add it to root->left_join_clauses or * root->right_join_clauses according to which side the nonnullable * variable appears on. * * If it is a full outer-join qualification, we add it to * root->full_join_clauses. (Ideally we'd discard cases that aren't * leftvar = rightvar, as we do for left/right joins, but this routine * doesn't have the info needed to do that; and the current usage of the * full_join_clauses list doesn't require that, so it's not currently * worth complicating this routine's API to make it possible.) * * If none of the above hold, pass it off to * distribute_restrictinfo_to_rels(). * * In all cases, it's important to initialize the left_ec and right_ec * fields of a mergejoinable clause, so that all possibly mergejoinable * expressions have representations in EquivalenceClasses. If * process_equivalence is successful, it will take care of that; * otherwise, we have to call initialize_mergeclause_eclasses to do it. */ if (restrictinfo->mergeopfamilies) { if (maybe_equivalence) { if (check_equivalence_delay(root, restrictinfo) && process_equivalence(root, restrictinfo, below_outer_join)) return; /* EC rejected it, so set left_ec/right_ec the hard way ... */ initialize_mergeclause_eclasses(root, restrictinfo); /* ... and fall through to distribute_restrictinfo_to_rels */ } else if (maybe_outer_join && restrictinfo->can_join) { /* we need to set up left_ec/right_ec the hard way */ initialize_mergeclause_eclasses(root, restrictinfo); /* now see if it should go to any outer-join lists */ if (bms_is_subset(restrictinfo->left_relids, outerjoin_nonnullable) && !bms_overlap(restrictinfo->right_relids, outerjoin_nonnullable)) { /* we have outervar = innervar */ root->left_join_clauses = lappend(root->left_join_clauses, restrictinfo); return; } if (bms_is_subset(restrictinfo->right_relids, outerjoin_nonnullable) && !bms_overlap(restrictinfo->left_relids, outerjoin_nonnullable)) { /* we have innervar = outervar */ root->right_join_clauses = lappend(root->right_join_clauses, restrictinfo); return; } if (jointype == JOIN_FULL) { /* FULL JOIN (above tests cannot match in this case) */ root->full_join_clauses = lappend(root->full_join_clauses, restrictinfo); return; } /* nope, so fall through to distribute_restrictinfo_to_rels */ } else { /* we still need to set up left_ec/right_ec */ initialize_mergeclause_eclasses(root, restrictinfo); } } /* No EC special case applies, so push it into the clause lists */ distribute_restrictinfo_to_rels(root, restrictinfo); } /* * check_outerjoin_delay * Detect whether a qual referencing the given relids must be delayed * in application due to the presence of a lower outer join, and/or * may force extra delay of higher-level outer joins. * * If the qual must be delayed, add relids to *relids_p to reflect the lowest * safe level for evaluating the qual, and return TRUE. Any extra delay for * higher-level joins is reflected by setting delay_upper_joins to TRUE in * SpecialJoinInfo structs. We also compute nullable_relids, the set of * referenced relids that are nullable by lower outer joins (note that this * can be nonempty even for a non-delayed qual). * * For an is_pushed_down qual, we can evaluate the qual as soon as (1) we have * all the rels it mentions, and (2) we are at or above any outer joins that * can null any of these rels and are below the syntactic location of the * given qual. We must enforce (2) because pushing down such a clause below * the OJ might cause the OJ to emit null-extended rows that should not have * been formed, or that should have been rejected by the clause. (This is * only an issue for non-strict quals, since if we can prove a qual mentioning * only nullable rels is strict, we'd have reduced the outer join to an inner * join in reduce_outer_joins().) * * To enforce (2), scan the join_info_list and merge the required-relid sets of * any such OJs into the clause's own reference list. At the time we are * called, the join_info_list contains only outer joins below this qual. We * have to repeat the scan until no new relids get added; this ensures that * the qual is suitably delayed regardless of the order in which OJs get * executed. As an example, if we have one OJ with LHS=A, RHS=B, and one with * LHS=B, RHS=C, it is implied that these can be done in either order; if the * B/C join is done first then the join to A can null C, so a qual actually * mentioning only C cannot be applied below the join to A. * * For a non-pushed-down qual, this isn't going to determine where we place the * qual, but we need to determine outerjoin_delayed and nullable_relids anyway * for use later in the planning process. * * Lastly, a pushed-down qual that references the nullable side of any current * join_info_list member and has to be evaluated above that OJ (because its * required relids overlap the LHS too) causes that OJ's delay_upper_joins * flag to be set TRUE. This will prevent any higher-level OJs from * being interchanged with that OJ, which would result in not having any * correct place to evaluate the qual. (The case we care about here is a * sub-select WHERE clause within the RHS of some outer join. The WHERE * clause must effectively be treated as a degenerate clause of that outer * join's condition. Rather than trying to match such clauses with joins * directly, we set delay_upper_joins here, and when the upper outer join * is processed by make_outerjoininfo, it will refrain from allowing the * two OJs to commute.) */ static bool check_outerjoin_delay(PlannerInfo *root, Relids *relids_p, /* in/out parameter */ Relids *nullable_relids_p, /* output parameter */ bool is_pushed_down) { Relids relids; Relids nullable_relids; bool outerjoin_delayed; bool found_some; /* fast path if no special joins */ if (root->join_info_list == NIL) { *nullable_relids_p = NULL; return false; } /* must copy relids because we need the original value at the end */ relids = bms_copy(*relids_p); nullable_relids = NULL; outerjoin_delayed = false; do { ListCell *l; found_some = false; foreach(l, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(l); /* do we reference any nullable rels of this OJ? */ if (bms_overlap(relids, sjinfo->min_righthand) || (sjinfo->jointype == JOIN_FULL && bms_overlap(relids, sjinfo->min_lefthand))) { /* yes; have we included all its rels in relids? */ if (!bms_is_subset(sjinfo->min_lefthand, relids) || !bms_is_subset(sjinfo->min_righthand, relids)) { /* no, so add them in */ relids = bms_add_members(relids, sjinfo->min_lefthand); relids = bms_add_members(relids, sjinfo->min_righthand); outerjoin_delayed = true; /* we'll need another iteration */ found_some = true; } /* track all the nullable rels of relevant OJs */ nullable_relids = bms_add_members(nullable_relids, sjinfo->min_righthand); if (sjinfo->jointype == JOIN_FULL) nullable_relids = bms_add_members(nullable_relids, sjinfo->min_lefthand); /* set delay_upper_joins if needed */ if (is_pushed_down && sjinfo->jointype != JOIN_FULL && bms_overlap(relids, sjinfo->min_lefthand)) sjinfo->delay_upper_joins = true; } } } while (found_some); /* identify just the actually-referenced nullable rels */ nullable_relids = bms_int_members(nullable_relids, *relids_p); /* replace *relids_p, and return nullable_relids */ bms_free(*relids_p); *relids_p = relids; *nullable_relids_p = nullable_relids; return outerjoin_delayed; } /* * check_equivalence_delay * Detect whether a potential equivalence clause is rendered unsafe * by outer-join-delay considerations. Return TRUE if it's safe. * * The initial tests in distribute_qual_to_rels will consider a mergejoinable * clause to be a potential equivalence clause if it is not outerjoin_delayed. * But since the point of equivalence processing is that we will recombine the * two sides of the clause with others, we have to check that each side * satisfies the not-outerjoin_delayed condition on its own; otherwise it might * not be safe to evaluate everywhere we could place a derived equivalence * condition. */ static bool check_equivalence_delay(PlannerInfo *root, RestrictInfo *restrictinfo) { Relids relids; Relids nullable_relids; /* fast path if no special joins */ if (root->join_info_list == NIL) return true; /* must copy restrictinfo's relids to avoid changing it */ relids = bms_copy(restrictinfo->left_relids); /* check left side does not need delay */ if (check_outerjoin_delay(root, &relids, &nullable_relids, true)) return false; /* and similarly for the right side */ relids = bms_copy(restrictinfo->right_relids); if (check_outerjoin_delay(root, &relids, &nullable_relids, true)) return false; return true; } /* * check_redundant_nullability_qual * Check to see if the qual is an IS NULL qual that is redundant with * a lower JOIN_ANTI join. * * We want to suppress redundant IS NULL quals, not so much to save cycles * as to avoid generating bogus selectivity estimates for them. So if * redundancy is detected here, distribute_qual_to_rels() just throws away * the qual. */ static bool check_redundant_nullability_qual(PlannerInfo *root, Node *clause) { Var *forced_null_var; Index forced_null_rel; ListCell *lc; /* Check for IS NULL, and identify the Var forced to NULL */ forced_null_var = find_forced_null_var(clause); if (forced_null_var == NULL) return false; forced_null_rel = forced_null_var->varno; /* * If the Var comes from the nullable side of a lower antijoin, the IS * NULL condition is necessarily true. */ foreach(lc, root->join_info_list) { SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc); if (sjinfo->jointype == JOIN_ANTI && bms_is_member(forced_null_rel, sjinfo->syn_righthand)) return true; } return false; } /* * distribute_restrictinfo_to_rels * Push a completed RestrictInfo into the proper restriction or join * clause list(s). * * This is the last step of distribute_qual_to_rels() for ordinary qual * clauses. Clauses that are interesting for equivalence-class processing * are diverted to the EC machinery, but may ultimately get fed back here. */ void distribute_restrictinfo_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo) { Relids relids = restrictinfo->required_relids; RelOptInfo *rel; switch (bms_membership(relids)) { case BMS_SINGLETON: /* * There is only one relation participating in the clause, so it * is a restriction clause for that relation. */ rel = find_base_rel(root, bms_singleton_member(relids)); /* Add clause to rel's restriction list */ rel->baserestrictinfo = lappend(rel->baserestrictinfo, restrictinfo); break; case BMS_MULTIPLE: /* * The clause is a join clause, since there is more than one rel * in its relid set. */ /* * Check for hashjoinable operators. (We don't bother setting the * hashjoin info except in true join clauses.) */ check_hashjoinable(restrictinfo); /* * Add clause to the join lists of all the relevant relations. */ add_join_clause_to_rels(root, restrictinfo, relids); break; default: /* * clause references no rels, and therefore we have no place to * attach it. Shouldn't get here if callers are working properly. */ elog(ERROR, "cannot cope with variable-free clause"); break; } } /* * process_implied_equality * Create a restrictinfo item that says "item1 op item2", and push it * into the appropriate lists. (In practice opno is always a btree * equality operator.) * * "qualscope" is the nominal syntactic level to impute to the restrictinfo. * This must contain at least all the rels used in the expressions, but it * is used only to set the qual application level when both exprs are * variable-free. Otherwise the qual is applied at the lowest join level * that provides all its variables. * * "nullable_relids" is the set of relids used in the expressions that are * potentially nullable below the expressions. (This has to be supplied by * caller because this function is used after deconstruct_jointree, so we * don't have knowledge of where the clause items came from.) * * "both_const" indicates whether both items are known pseudo-constant; * in this case it is worth applying eval_const_expressions() in case we * can produce constant TRUE or constant FALSE. (Otherwise it's not, * because the expressions went through eval_const_expressions already.) * * Note: this function will copy item1 and item2, but it is caller's * responsibility to make sure that the Relids parameters are fresh copies * not shared with other uses. * * This is currently used only when an EquivalenceClass is found to * contain pseudoconstants. See path/pathkeys.c for more details. */ void process_implied_equality(PlannerInfo *root, Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids, bool below_outer_join, bool both_const) { Expr *clause; /* * Build the new clause. Copy to ensure it shares no substructure with * original (this is necessary in case there are subselects in there...) */ clause = make_opclause(opno, BOOLOID, /* opresulttype */ false, /* opretset */ (Expr *) copyObject(item1), (Expr *) copyObject(item2), InvalidOid, collation); /* If both constant, try to reduce to a boolean constant. */ if (both_const) { clause = (Expr *) eval_const_expressions(root, (Node *) clause); /* If we produced const TRUE, just drop the clause */ if (clause && IsA(clause, Const)) { Const *cclause = (Const *) clause; Assert(cclause->consttype == BOOLOID); if (!cclause->constisnull && DatumGetBool(cclause->constvalue)) return; } } /* * Push the new clause into all the appropriate restrictinfo lists. */ distribute_qual_to_rels(root, (Node *) clause, true, below_outer_join, JOIN_INNER, qualscope, NULL, NULL, nullable_relids, NULL); } /* * build_implied_join_equality --- build a RestrictInfo for a derived equality * * This overlaps the functionality of process_implied_equality(), but we * must return the RestrictInfo, not push it into the joininfo tree. * * Note: this function will copy item1 and item2, but it is caller's * responsibility to make sure that the Relids parameters are fresh copies * not shared with other uses. * * Note: we do not do initialize_mergeclause_eclasses() here. It is * caller's responsibility that left_ec/right_ec be set as necessary. */ RestrictInfo * build_implied_join_equality(Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids) { RestrictInfo *restrictinfo; Expr *clause; /* * Build the new clause. Copy to ensure it shares no substructure with * original (this is necessary in case there are subselects in there...) */ clause = make_opclause(opno, BOOLOID, /* opresulttype */ false, /* opretset */ (Expr *) copyObject(item1), (Expr *) copyObject(item2), InvalidOid, collation); /* * Build the RestrictInfo node itself. */ restrictinfo = make_restrictinfo(clause, true, /* is_pushed_down */ false, /* outerjoin_delayed */ false, /* pseudoconstant */ qualscope, /* required_relids */ NULL, /* outer_relids */ nullable_relids); /* nullable_relids */ /* Set mergejoinability/hashjoinability flags */ check_mergejoinable(restrictinfo); check_hashjoinable(restrictinfo); return restrictinfo; } /***************************************************************************** * * CHECKS FOR MERGEJOINABLE AND HASHJOINABLE CLAUSES * *****************************************************************************/ /* * check_mergejoinable * If the restrictinfo's clause is mergejoinable, set the mergejoin * info fields in the restrictinfo. * * Currently, we support mergejoin for binary opclauses where * the operator is a mergejoinable operator. The arguments can be * anything --- as long as there are no volatile functions in them. */ static void check_mergejoinable(RestrictInfo *restrictinfo) { Expr *clause = restrictinfo->clause; Oid opno; Node *leftarg; if (restrictinfo->pseudoconstant) return; if (!is_opclause(clause)) return; if (list_length(((OpExpr *) clause)->args) != 2) return; opno = ((OpExpr *) clause)->opno; leftarg = linitial(((OpExpr *) clause)->args); if (op_mergejoinable(opno, exprType(leftarg)) && !contain_volatile_functions((Node *) clause)) restrictinfo->mergeopfamilies = get_mergejoin_opfamilies(opno); /* * Note: op_mergejoinable is just a hint; if we fail to find the operator * in any btree opfamilies, mergeopfamilies remains NIL and so the clause * is not treated as mergejoinable. */ } /* * check_hashjoinable * If the restrictinfo's clause is hashjoinable, set the hashjoin * info fields in the restrictinfo. * * Currently, we support hashjoin for binary opclauses where * the operator is a hashjoinable operator. The arguments can be * anything --- as long as there are no volatile functions in them. */ static void check_hashjoinable(RestrictInfo *restrictinfo) { Expr *clause = restrictinfo->clause; Oid opno; Node *leftarg; if (restrictinfo->pseudoconstant) return; if (!is_opclause(clause)) return; if (list_length(((OpExpr *) clause)->args) != 2) return; opno = ((OpExpr *) clause)->opno; leftarg = linitial(((OpExpr *) clause)->args); if (op_hashjoinable(opno, exprType(leftarg)) && !contain_volatile_functions((Node *) clause)) restrictinfo->hashjoinoperator = opno; }
47705.c
/** ****************************************************************************** * @file usbd_hid.c * @author MCD Application Team * @version V2.2.0 * @date 13-June-2014 * @brief This file provides the HID core functions. * * @verbatim * * =================================================================== * HID Class Description * =================================================================== * This module manages the HID class V1.11 following the "Device Class Definition * for Human Interface Devices (HID) Version 1.11 Jun 27, 2001". * This driver implements the following aspects of the specification: * - The Boot Interface Subclass * - Usage Page : Generic Desktop * - Usage : Vendor * - Collection : Application * * @note In HS mode and when the DMA is used, all variables and data structures * dealing with the DMA during the transaction process should be 32-bit aligned. * * * @endverbatim * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ #include "os.h" /* Includes ------------------------------------------------------------------*/ #include "usbd_hid.h" #include "usbd_ctlreq.h" #include "usbd_core.h" #include "usbd_conf.h" #include "usbd_def.h" #include "os_io_seproxyhal.h" /** @addtogroup STM32_USB_DEVICE_LIBRARY * @{ */ /** @defgroup USBD_HID * @brief usbd core module * @{ */ /** @defgroup USBD_HID_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup USBD_HID_Private_Defines * @{ */ /** * @} */ /** @defgroup USBD_HID_Private_Macros * @{ */ /** * @} */ /** @defgroup USBD_HID_Private_FunctionPrototypes * @{ */ /** * @} */ /** @defgroup USBD_HID_Private_Variables * @{ */ #define HID_EPIN_ADDR 0x82 #define HID_EPIN_SIZE 0x40 #define HID_EPOUT_ADDR 0x02 #define HID_EPOUT_SIZE 0x40 #define USBD_LANGID_STRING 0x409 #define USBD_VID 0x2C97 #if TARGET_ID == 0x31000002 // blue #define USBD_PID 0x0000 const uint8_t const USBD_PRODUCT_FS_STRING[] = { 4*2+2, USB_DESC_TYPE_STRING, 'B', 0, 'l', 0, 'u', 0, 'e', 0, }; #elif TARGET_ID == 0x31100002 // nano s #define USBD_PID 0x0001 const uint8_t const USBD_PRODUCT_FS_STRING[] = { 6*2+2, USB_DESC_TYPE_STRING, 'N', 0, 'a', 0, 'n', 0, 'o', 0, ' ', 0, 'S', 0, }; #elif TARGET_ID == 0x31200002 // aramis #define USBD_PID 0x0002 const uint8_t const USBD_PRODUCT_FS_STRING[] = { 6*2+2, USB_DESC_TYPE_STRING, 'A', 0, 'r', 0, 'a', 0, 'm', 0, 'i', 0, 's', 0, }; #else #error unknown TARGET_ID #endif /* USB Standard Device Descriptor */ static const uint8_t const USBD_LangIDDesc[]= { USB_LEN_LANGID_STR_DESC, USB_DESC_TYPE_STRING, LOBYTE(USBD_LANGID_STRING), HIBYTE(USBD_LANGID_STRING), }; static const uint8_t const USB_SERIAL_STRING[] = { 4*2+2, USB_DESC_TYPE_STRING, '0', 0, '0', 0, '0', 0, '1', 0, }; static const uint8_t const USBD_MANUFACTURER_STRING[] = { 6*2+2, USB_DESC_TYPE_STRING, 'L', 0, 'e', 0, 'd', 0, 'g', 0, 'e', 0, 'r', 0, }; #define USBD_INTERFACE_FS_STRING USBD_PRODUCT_FS_STRING #define USBD_CONFIGURATION_FS_STRING USBD_PRODUCT_FS_STRING const uint8_t const HID_ReportDesc[] = { 0x06, 0xA0, 0xFF, // Usage page (vendor defined) 0x09, 0x01, // Usage ID (vendor defined) 0xA1, 0x01, // Collection (application) // The Input report 0x09, 0x03, // Usage ID - vendor defined 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x75, 0x08, // Report Size (8 bits) 0x95, HID_EPIN_SIZE, // Report Count (64 fields) 0x81, 0x08, // Input (Data, Variable, Absolute) // The Output report 0x09, 0x04, // Usage ID - vendor defined 0x15, 0x00, // Logical Minimum (0) 0x26, 0xFF, 0x00, // Logical Maximum (255) 0x75, 0x08, // Report Size (8 bits) 0x95, HID_EPOUT_SIZE, // Report Count (64 fields) 0x91, 0x08, // Output (Data, Variable, Absolute) 0xC0 }; /* USB HID device Configuration Descriptor */ static __ALIGN_BEGIN const uint8_t const USBD_CfgDesc[] __ALIGN_END = { 0x09, /* bLength: Configuration Descriptor size */ USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */ 0x29, /* wTotalLength: Bytes returned */ 0x00, 0x01, /*bNumInterfaces: 1 interface*/ 0x01, /*bConfigurationValue: Configuration value*/ USBD_IDX_PRODUCT_STR, /*iConfiguration: Index of string descriptor describing the configuration*/ 0xC0, /*bmAttributes: bus powered */ 0x32, /*MaxPower 100 mA: this current is used for detecting Vbus*/ /************** Descriptor of CUSTOM HID interface ****************/ /* 09 */ 0x09, /*bLength: Interface Descriptor size*/ USB_DESC_TYPE_INTERFACE,/*bDescriptorType: Interface descriptor type*/ 0x00, /*bInterfaceNumber: Number of Interface*/ 0x00, /*bAlternateSetting: Alternate setting*/ 0x02, /*bNumEndpoints*/ 0x03, /*bInterfaceClass: HID*/ 0x00, /*bInterfaceSubClass : 1=BOOT, 0=no boot*/ 0x00, /*nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse*/ USBD_IDX_PRODUCT_STR, /*iInterface: Index of string descriptor*/ /******************** Descriptor of HID *************************/ /* 18 */ 0x09, /*bLength: HID Descriptor size*/ HID_DESCRIPTOR_TYPE, /*bDescriptorType: HID*/ 0x11, /*bHIDUSTOM_HID: HID Class Spec release number*/ 0x01, 0x00, /*bCountryCode: Hardware target country*/ 0x01, /*bNumDescriptors: Number of HID class descriptors to follow*/ 0x22, /*bDescriptorType*/ sizeof(HID_ReportDesc),/*wItemLength: Total length of Report descriptor*/ 0x00, /******************** Descriptor of Custom HID endpoints ********************/ /* 27 */ 0x07, /*bLength: Endpoint Descriptor size*/ USB_DESC_TYPE_ENDPOINT, /*bDescriptorType:*/ HID_EPIN_ADDR, /*bEndpointAddress: Endpoint Address (IN)*/ 0x03, /*bmAttributes: Interrupt endpoint*/ HID_EPIN_SIZE, /*wMaxPacketSize: 2 Byte max */ 0x00, 0x01, /*bInterval: Polling Interval (20 ms)*/ /* 34 */ 0x07, /* bLength: Endpoint Descriptor size */ USB_DESC_TYPE_ENDPOINT, /* bDescriptorType: */ HID_EPOUT_ADDR, /*bEndpointAddress: Endpoint Address (OUT)*/ 0x03, /* bmAttributes: Interrupt endpoint */ HID_EPOUT_SIZE, /* wMaxPacketSize: 2 Bytes max */ 0x00, 0x01, /* bInterval: Polling Interval (20 ms) */ /* 41 */ } ; /* USB HID device Configuration Descriptor */ __ALIGN_BEGIN const uint8_t const USBD_HID_Desc[] __ALIGN_END = { /* 18 */ 0x09, /*bLength: HID Descriptor size*/ HID_DESCRIPTOR_TYPE, /*bDescriptorType: HID*/ 0x11, /*bHIDUSTOM_HID: HID Class Spec release number*/ 0x01, 0x00, /*bCountryCode: Hardware target country*/ 0x01, /*bNumDescriptors: Number of HID class descriptors to follow*/ 0x22, /*bDescriptorType*/ sizeof(HID_ReportDesc),/*wItemLength: Total length of Report descriptor*/ 0x00, }; /* USB Standard Device Descriptor */ static __ALIGN_BEGIN const uint8_t const USBD_DeviceQualifierDesc[] __ALIGN_END = { USB_LEN_DEV_QUALIFIER_DESC, USB_DESC_TYPE_DEVICE_QUALIFIER, 0x00, 0x02, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00, }; /* USB Standard Device Descriptor */ const uint8_t const USBD_DeviceDesc[]= { 0x12, /* bLength */ USB_DESC_TYPE_DEVICE, /* bDescriptorType */ 0x00, /* bcdUSB */ 0x02, 0x00, /* bDeviceClass */ 0x00, /* bDeviceSubClass */ 0x00, /* bDeviceProtocol */ USB_MAX_EP0_SIZE, /* bMaxPacketSize */ LOBYTE(USBD_VID), /* idVendor */ HIBYTE(USBD_VID), /* idVendor */ LOBYTE(USBD_PID), /* idVendor */ HIBYTE(USBD_PID), /* idVendor */ 0x00, /* bcdDevice rel. 2.00 */ 0x02, USBD_IDX_MFC_STR, /* Index of manufacturer string */ USBD_IDX_PRODUCT_STR, /* Index of product string */ USBD_IDX_SERIAL_STR, /* Index of serial number string */ USBD_MAX_NUM_CONFIGURATION /* bNumConfigurations */ }; /* USB_DeviceDescriptor */ /** * @brief Returns the device descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_DeviceDesc); return (uint8_t*)USBD_DeviceDesc; } /** * @brief Returns the LangID string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_LangIDDesc); return (uint8_t*)USBD_LangIDDesc; } /** * @brief Returns the product string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_PRODUCT_FS_STRING); return (uint8_t*)USBD_PRODUCT_FS_STRING; } /** * @brief Returns the manufacturer string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_MANUFACTURER_STRING); return (uint8_t*)USBD_MANUFACTURER_STRING; } /** * @brief Returns the serial number string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USB_SERIAL_STRING); return (uint8_t*)USB_SERIAL_STRING; } /** * @brief Returns the configuration string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_CONFIGURATION_FS_STRING); return (uint8_t*)USBD_CONFIGURATION_FS_STRING; } /** * @brief Returns the interface string descriptor. * @param speed: Current device speed * @param length: Pointer to data length variable * @retval Pointer to descriptor buffer */ static uint8_t *USBD_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) { UNUSED(speed); *length = sizeof(USBD_INTERFACE_FS_STRING); return (uint8_t*)USBD_INTERFACE_FS_STRING; } /** * @brief DeviceQualifierDescriptor * return Device Qualifier descriptor * @param length : pointer data length * @retval pointer to descriptor buffer */ static uint8_t *USBD_GetDeviceQualifierDesc_impl (uint16_t *length) { *length = sizeof (USBD_DeviceQualifierDesc); return (uint8_t*)USBD_DeviceQualifierDesc; } /** * @brief USBD_CUSTOM_HID_GetCfgDesc * return configuration descriptor * @param speed : current device speed * @param length : pointer data length * @retval pointer to descriptor buffer */ static uint8_t *USBD_GetCfgDesc_impl (uint16_t *length) { *length = sizeof (USBD_CfgDesc); return (uint8_t*)USBD_CfgDesc; } uint8_t* USBD_HID_GetHidDescriptor_impl(uint16_t* len) { *len = sizeof(USBD_HID_Desc); return (uint8_t*)USBD_HID_Desc; } uint8_t* USBD_HID_GetReportDescriptor_impl(uint16_t* len) { *len = sizeof(HID_ReportDesc); return (uint8_t*)HID_ReportDesc; } /** * @} */ /** * @brief USBD_HID_DataOut * handle data OUT Stage * @param pdev: device instance * @param epnum: endpoint index * @retval status * * This function is the default behavior for our implementation when data are sent over the out hid endpoint */ extern volatile unsigned short G_io_apdu_length; uint8_t USBD_HID_DataOut_impl (USBD_HandleTypeDef *pdev, uint8_t epnum, uint8_t* buffer) { UNUSED(epnum); // prepare receiving the next chunk (masked time) USBD_LL_PrepareReceive(pdev, HID_EPOUT_ADDR , HID_EPOUT_SIZE); // avoid troubles when an apdu has not been replied yet if (G_io_apdu_media == IO_APDU_MEDIA_NONE) { // add to the hid transport switch(io_usb_hid_receive(io_usb_send_apdu_data, buffer, io_seproxyhal_get_ep_rx_size(HID_EPOUT_ADDR))) { default: break; case IO_USB_APDU_RECEIVED: G_io_apdu_media = IO_APDU_MEDIA_USB_HID; // for application code G_io_apdu_state = APDU_USB_HID; // for next call to io_exchange G_io_apdu_length = G_io_usb_hid_total_length; break; } } return USBD_OK; } /** @defgroup USBD_HID_Private_Functions * @{ */ // note: how core lib usb calls the hid class static const USBD_DescriptorsTypeDef const HID_Desc = { USBD_DeviceDescriptor, USBD_LangIDStrDescriptor, USBD_ManufacturerStrDescriptor, USBD_ProductStrDescriptor, USBD_SerialStrDescriptor, USBD_ConfigStrDescriptor, USBD_InterfaceStrDescriptor, NULL, }; static const USBD_ClassTypeDef const USBD_HID = { USBD_HID_Init, USBD_HID_DeInit, USBD_HID_Setup, NULL, /*EP0_TxSent*/ NULL, /*EP0_RxReady*/ /* STATUS STAGE IN */ NULL, /*DataIn*/ USBD_HID_DataOut_impl, /*DataOut*/ NULL, /*SOF */ NULL, NULL, USBD_GetCfgDesc_impl, USBD_GetCfgDesc_impl, USBD_GetCfgDesc_impl, USBD_GetDeviceQualifierDesc_impl, }; void USB_power(unsigned char enabled) { os_memset(&USBD_Device, 0, sizeof(USBD_Device)); if (enabled) { os_memset(&USBD_Device, 0, sizeof(USBD_Device)); /* Init Device Library */ USBD_Init(&USBD_Device, (USBD_DescriptorsTypeDef*)&HID_Desc, 0); /* Register the HID class */ USBD_RegisterClass(&USBD_Device, (USBD_ClassTypeDef*)&USBD_HID); /* Start Device Process */ USBD_Start(&USBD_Device); } else { USBD_DeInit(&USBD_Device); } } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
439700.c
/* * debug_editor.c : An editor that writes the operations it does to stderr. * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== */ #include "svn_io.h" #include "private/svn_delta_private.h" struct edit_baton { const svn_delta_editor_t *wrapped_editor; void *wrapped_edit_baton; int indent_level; svn_stream_t *out; const char *prefix; }; struct dir_baton { void *edit_baton; void *wrapped_dir_baton; }; struct file_baton { void *edit_baton; void *wrapped_file_baton; }; static svn_error_t * write_indent(struct edit_baton *eb, apr_pool_t *pool) { int i; SVN_ERR(svn_stream_puts(eb->out, eb->prefix)); for (i = 0; i < eb->indent_level; ++i) SVN_ERR(svn_stream_puts(eb->out, " ")); return SVN_NO_ERROR; } static svn_error_t * set_target_revision(void *edit_baton, svn_revnum_t target_revision, apr_pool_t *pool) { struct edit_baton *eb = edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "set_target_revision : %ld\n", target_revision)); return eb->wrapped_editor->set_target_revision(eb->wrapped_edit_baton, target_revision, pool); } static svn_error_t * open_root(void *edit_baton, svn_revnum_t base_revision, apr_pool_t *pool, void **root_baton) { struct edit_baton *eb = edit_baton; struct dir_baton *dir_baton = apr_palloc(pool, sizeof(*dir_baton)); SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "open_root : %ld\n", base_revision)); eb->indent_level++; SVN_ERR(eb->wrapped_editor->open_root(eb->wrapped_edit_baton, base_revision, pool, &dir_baton->wrapped_dir_baton)); dir_baton->edit_baton = edit_baton; *root_baton = dir_baton; return SVN_NO_ERROR; } static svn_error_t * delete_entry(const char *path, svn_revnum_t base_revision, void *parent_baton, apr_pool_t *pool) { struct dir_baton *pb = parent_baton; struct edit_baton *eb = pb->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "delete_entry : %s:%ld\n", path, base_revision)); return eb->wrapped_editor->delete_entry(path, base_revision, pb->wrapped_dir_baton, pool); } static svn_error_t * add_directory(const char *path, void *parent_baton, const char *copyfrom_path, svn_revnum_t copyfrom_revision, apr_pool_t *pool, void **child_baton) { struct dir_baton *pb = parent_baton; struct edit_baton *eb = pb->edit_baton; struct dir_baton *b = apr_palloc(pool, sizeof(*b)); SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "add_directory : '%s' [from '%s':%ld]\n", path, copyfrom_path, copyfrom_revision)); eb->indent_level++; SVN_ERR(eb->wrapped_editor->add_directory(path, pb->wrapped_dir_baton, copyfrom_path, copyfrom_revision, pool, &b->wrapped_dir_baton)); b->edit_baton = eb; *child_baton = b; return SVN_NO_ERROR; } static svn_error_t * open_directory(const char *path, void *parent_baton, svn_revnum_t base_revision, apr_pool_t *pool, void **child_baton) { struct dir_baton *pb = parent_baton; struct edit_baton *eb = pb->edit_baton; struct dir_baton *db = apr_palloc(pool, sizeof(*db)); SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "open_directory : '%s':%ld\n", path, base_revision)); eb->indent_level++; SVN_ERR(eb->wrapped_editor->open_directory(path, pb->wrapped_dir_baton, base_revision, pool, &db->wrapped_dir_baton)); db->edit_baton = eb; *child_baton = db; return SVN_NO_ERROR; } static svn_error_t * add_file(const char *path, void *parent_baton, const char *copyfrom_path, svn_revnum_t copyfrom_revision, apr_pool_t *pool, void **file_baton) { struct dir_baton *pb = parent_baton; struct edit_baton *eb = pb->edit_baton; struct file_baton *fb = apr_palloc(pool, sizeof(*fb)); SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "add_file : '%s' [from '%s':%ld]\n", path, copyfrom_path, copyfrom_revision)); eb->indent_level++; SVN_ERR(eb->wrapped_editor->add_file(path, pb->wrapped_dir_baton, copyfrom_path, copyfrom_revision, pool, &fb->wrapped_file_baton)); fb->edit_baton = eb; *file_baton = fb; return SVN_NO_ERROR; } static svn_error_t * open_file(const char *path, void *parent_baton, svn_revnum_t base_revision, apr_pool_t *pool, void **file_baton) { struct dir_baton *pb = parent_baton; struct edit_baton *eb = pb->edit_baton; struct file_baton *fb = apr_palloc(pool, sizeof(*fb)); SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "open_file : '%s':%ld\n", path, base_revision)); eb->indent_level++; SVN_ERR(eb->wrapped_editor->open_file(path, pb->wrapped_dir_baton, base_revision, pool, &fb->wrapped_file_baton)); fb->edit_baton = eb; *file_baton = fb; return SVN_NO_ERROR; } static svn_error_t * apply_textdelta(void *file_baton, const char *base_checksum, apr_pool_t *pool, svn_txdelta_window_handler_t *handler, void **handler_baton) { struct file_baton *fb = file_baton; struct edit_baton *eb = fb->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "apply_textdelta : %s\n", base_checksum)); SVN_ERR(eb->wrapped_editor->apply_textdelta(fb->wrapped_file_baton, base_checksum, pool, handler, handler_baton)); return SVN_NO_ERROR; } static svn_error_t * close_file(void *file_baton, const char *text_checksum, apr_pool_t *pool) { struct file_baton *fb = file_baton; struct edit_baton *eb = fb->edit_baton; eb->indent_level--; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "close_file : %s\n", text_checksum)); SVN_ERR(eb->wrapped_editor->close_file(fb->wrapped_file_baton, text_checksum, pool)); return SVN_NO_ERROR; } static svn_error_t * absent_file(const char *path, void *file_baton, apr_pool_t *pool) { struct file_baton *fb = file_baton; struct edit_baton *eb = fb->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "absent_file : %s\n", path)); SVN_ERR(eb->wrapped_editor->absent_file(path, fb->wrapped_file_baton, pool)); return SVN_NO_ERROR; } static svn_error_t * close_directory(void *dir_baton, apr_pool_t *pool) { struct dir_baton *db = dir_baton; struct edit_baton *eb = db->edit_baton; eb->indent_level--; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "close_directory\n")); SVN_ERR(eb->wrapped_editor->close_directory(db->wrapped_dir_baton, pool)); return SVN_NO_ERROR; } static svn_error_t * absent_directory(const char *path, void *dir_baton, apr_pool_t *pool) { struct dir_baton *db = dir_baton; struct edit_baton *eb = db->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "absent_directory : %s\n", path)); SVN_ERR(eb->wrapped_editor->absent_directory(path, db->wrapped_dir_baton, pool)); return SVN_NO_ERROR; } static svn_error_t * change_file_prop(void *file_baton, const char *name, const svn_string_t *value, apr_pool_t *pool) { struct file_baton *fb = file_baton; struct edit_baton *eb = fb->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "change_file_prop : %s -> %s\n", name, value ? value->data : "<deleted>")); SVN_ERR(eb->wrapped_editor->change_file_prop(fb->wrapped_file_baton, name, value, pool)); return SVN_NO_ERROR; } static svn_error_t * change_dir_prop(void *dir_baton, const char *name, const svn_string_t *value, apr_pool_t *pool) { struct dir_baton *db = dir_baton; struct edit_baton *eb = db->edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "change_dir_prop : %s -> %s\n", name, value ? value->data : "<deleted>")); SVN_ERR(eb->wrapped_editor->change_dir_prop(db->wrapped_dir_baton, name, value, pool)); return SVN_NO_ERROR; } static svn_error_t * close_edit(void *edit_baton, apr_pool_t *pool) { struct edit_baton *eb = edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "close_edit\n")); SVN_ERR(eb->wrapped_editor->close_edit(eb->wrapped_edit_baton, pool)); return SVN_NO_ERROR; } static svn_error_t * abort_edit(void *edit_baton, apr_pool_t *pool) { struct edit_baton *eb = edit_baton; SVN_ERR(write_indent(eb, pool)); SVN_ERR(svn_stream_printf(eb->out, pool, "abort_edit\n")); SVN_ERR(eb->wrapped_editor->abort_edit(eb->wrapped_edit_baton, pool)); return SVN_NO_ERROR; } svn_error_t * svn_delta__get_debug_editor(const svn_delta_editor_t **editor, void **edit_baton, const svn_delta_editor_t *wrapped_editor, void *wrapped_edit_baton, const char *prefix, apr_pool_t *pool) { svn_delta_editor_t *tree_editor = apr_palloc(pool, sizeof(*tree_editor)); struct edit_baton *eb = apr_palloc(pool, sizeof(*eb)); apr_file_t *errfp; svn_stream_t *out; apr_status_t apr_err = apr_file_open_stdout(&errfp, pool); if (apr_err) return svn_error_wrap_apr(apr_err, "Problem opening stderr"); out = svn_stream_from_aprfile2(errfp, TRUE, pool); tree_editor->set_target_revision = set_target_revision; tree_editor->open_root = open_root; tree_editor->delete_entry = delete_entry; tree_editor->add_directory = add_directory; tree_editor->open_directory = open_directory; tree_editor->change_dir_prop = change_dir_prop; tree_editor->close_directory = close_directory; tree_editor->absent_directory = absent_directory; tree_editor->add_file = add_file; tree_editor->open_file = open_file; tree_editor->apply_textdelta = apply_textdelta; tree_editor->change_file_prop = change_file_prop; tree_editor->close_file = close_file; tree_editor->absent_file = absent_file; tree_editor->close_edit = close_edit; tree_editor->abort_edit = abort_edit; eb->wrapped_editor = wrapped_editor; eb->wrapped_edit_baton = wrapped_edit_baton; eb->out = out; eb->indent_level = 0; /* This is DBG_FLAG from ../libsvn_subr/debug.c */ eb->prefix = apr_pstrcat(pool, "DBG: ", prefix, SVN_VA_NULL); *editor = tree_editor; *edit_baton = eb; return SVN_NO_ERROR; }
197497.c
// 2019-2 Programming Report 1 // Problem #4 #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> int main() { float a, b; char operand; int success; // printf("2개의 실수를 입력하세요. :"); printf("Enter 2 real numbers: "); do { success = scanf("%f %f", &a, &b); if (success == 0) { // printf("오류: 입력은 2개의 실수여야 합니다.\n"); printf("Error: Input type should be 2 real numbers.\n\n"); // 입력 버퍼 클리어 scanf("%*[^\n]"); // printf("2개의 실수를 입력하세요. :"); printf("Enter 2 real numbers: "); } } while (!success); // printf("연산 종류를 입력하세요. :"); printf("Enter operand (+ - * /): "); do { success = scanf(" %c", &operand); if (operand != '+' && operand != '-' && operand != '*' && operand != '/') { success = 0; } if (success == 0) { // printf("오류: 입력은 연산자 문자여야 합니다.\n"); printf("Error: Input type should be operand character (+ - * /).\n\n"); // 입력 버퍼 클리어 scanf("%*[^\n]"); // printf("연산 종류를 입력하세요. :"); printf("Enter operand (+ - * /): "); } } while (!success); printf("\n"); printf("%.2f %c %.2f = ", a, operand, b); switch (operand) { case '+': printf("%.2f", a + b); break; case '-': printf("%.2f", a - b); break; case '*': printf("%.2f", a * b); break; case '/': printf("%.2f", a / b); break; } printf("\n"); return 0; }
399849.c
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice 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 "uv.h" #include "internal.h" #include "spinlock.h" #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <termios.h> #include <errno.h> #include <sys/ioctl.h> #if defined(__MVS__) && !defined(IMAXBEL) #define IMAXBEL 0 #endif static int orig_termios_fd = -1; static struct termios orig_termios; static uv_spinlock_t termios_spinlock = UV_SPINLOCK_INITIALIZER; static int uv__tty_is_slave(const int fd) { int result; #if defined(__linux__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) int dummy; result = ioctl(fd, TIOCGPTN, &dummy) != 0; #elif defined(__APPLE__) char dummy[256]; result = ioctl(fd, TIOCPTYGNAME, &dummy) != 0; #elif defined(__NetBSD__) /* * NetBSD as an extension returns with ptsname(3) and ptsname_r(3) the slave * device name for both descriptors, the master one and slave one. * * Implement function to compare major device number with pts devices. * * The major numbers are machine-dependent, on NetBSD/amd64 they are * respectively: * - master tty: ptc - major 6 * - slave tty: pts - major 5 */ struct stat sb; /* Lookup device's major for the pts driver and cache it. */ static devmajor_t pts = NODEVMAJOR; if (pts == NODEVMAJOR) { pts = getdevmajor("pts", S_IFCHR); if (pts == NODEVMAJOR) abort(); } /* Lookup stat structure behind the file descriptor. */ if (fstat(fd, &sb) != 0) abort(); /* Assert character device. */ if (!S_ISCHR(sb.st_mode)) abort(); /* Assert valid major. */ if (major(sb.st_rdev) == NODEVMAJOR) abort(); result = (pts == major(sb.st_rdev)); #else /* Fallback to ptsname */ result = ptsname(fd) == NULL; #endif return result; } int uv_tty_init(uv_loop_t* loop, uv_tty_t* tty, int fd, int readable) { uv_handle_type type; int flags; int newfd; int r; int saved_flags; char path[256]; /* File descriptors that refer to files cannot be monitored with epoll. * That restriction also applies to character devices like /dev/random * (but obviously not /dev/tty.) */ type = uv_guess_handle(fd); if (type == UV_FILE || type == UV_UNKNOWN_HANDLE) return UV_EINVAL; flags = 0; newfd = -1; /* Reopen the file descriptor when it refers to a tty. This lets us put the * tty in non-blocking mode without affecting other processes that share it * with us. * * Example: `node | cat` - if we put our fd 0 in non-blocking mode, it also * affects fd 1 of `cat` because both file descriptors refer to the same * struct file in the kernel. When we reopen our fd 0, it points to a * different struct file, hence changing its properties doesn't affect * other processes. */ if (type == UV_TTY) { /* Reopening a pty in master mode won't work either because the reopened * pty will be in slave mode (*BSD) or reopening will allocate a new * master/slave pair (Linux). Therefore check if the fd points to a * slave device. */ if (uv__tty_is_slave(fd) && ttyname_r(fd, path, sizeof(path)) == 0) r = uv__open_cloexec(path, O_RDWR); else r = -1; if (r < 0) { /* fallback to using blocking writes */ if (!readable) flags |= UV_STREAM_BLOCKING; goto skip; } newfd = r; r = uv__dup2_cloexec(newfd, fd); if (r < 0 && r != UV_EINVAL) { /* EINVAL means newfd == fd which could conceivably happen if another * thread called close(fd) between our calls to isatty() and open(). * That's a rather unlikely event but let's handle it anyway. */ uv__close(newfd); return r; } fd = newfd; } #if defined(__APPLE__) /* Save the fd flags in case we need to restore them due to an error. */ do saved_flags = fcntl(fd, F_GETFL); while (saved_flags == -1 && errno == EINTR); if (saved_flags == -1) { if (newfd != -1) uv__close(newfd); return UV__ERR(errno); } #endif /* Pacify the compiler. */ (void) &saved_flags; skip: uv__stream_init(loop, (uv_stream_t*) tty, UV_TTY); /* If anything fails beyond this point we need to remove the handle from * the handle queue, since it was added by uv__handle_init in uv_stream_init. */ if (!(flags & UV_STREAM_BLOCKING)) uv__nonblock(fd, 1); #if defined(__APPLE__) r = uv__stream_try_select((uv_stream_t*) tty, &fd); if (r) { int rc = r; if (newfd != -1) uv__close(newfd); QUEUE_REMOVE(&tty->handle_queue); do r = fcntl(fd, F_SETFL, saved_flags); while (r == -1 && errno == EINTR); return rc; } #endif if (readable) flags |= UV_STREAM_READABLE; else flags |= UV_STREAM_WRITABLE; uv__stream_open((uv_stream_t*) tty, fd, flags); tty->mode = UV_TTY_MODE_NORMAL; return 0; } static void uv__tty_make_raw(struct termios* tio) { assert(tio != NULL); #if defined __sun || defined __MVS__ /* * This implementation of cfmakeraw for Solaris and derivatives is taken from * http://www.perkin.org.uk/posts/solaris-portability-cfmakeraw.html. */ tio->c_iflag &= ~(IMAXBEL | IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); tio->c_oflag &= ~OPOST; tio->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); tio->c_cflag &= ~(CSIZE | PARENB); tio->c_cflag |= CS8; #else cfmakeraw(tio); #endif /* #ifdef __sun */ } int uv_tty_set_mode(uv_tty_t* tty, uv_tty_mode_t mode) { struct termios tmp; int fd; if (tty->mode == (int) mode) return 0; fd = uv__stream_fd(tty); if (tty->mode == UV_TTY_MODE_NORMAL && mode != UV_TTY_MODE_NORMAL) { if (tcgetattr(fd, &tty->orig_termios)) return UV__ERR(errno); /* This is used for uv_tty_reset_mode() */ uv_spinlock_lock(&termios_spinlock); if (orig_termios_fd == -1) { orig_termios = tty->orig_termios; orig_termios_fd = fd; } uv_spinlock_unlock(&termios_spinlock); } tmp = tty->orig_termios; switch (mode) { case UV_TTY_MODE_NORMAL: break; case UV_TTY_MODE_RAW: tmp.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); tmp.c_oflag |= (ONLCR); tmp.c_cflag |= (CS8); tmp.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); tmp.c_cc[VMIN] = 1; tmp.c_cc[VTIME] = 0; break; case UV_TTY_MODE_IO: uv__tty_make_raw(&tmp); break; } /* Apply changes after draining */ if (tcsetattr(fd, TCSADRAIN, &tmp)) return UV__ERR(errno); tty->mode = mode; return 0; } int uv_tty_get_winsize(uv_tty_t* tty, int* width, int* height) { struct winsize ws; int err; do err = ioctl(uv__stream_fd(tty), TIOCGWINSZ, &ws); while (err == -1 && errno == EINTR); if (err == -1) return UV__ERR(errno); *width = ws.ws_col; *height = ws.ws_row; return 0; } uv_handle_type uv_guess_handle(uv_file file) { struct sockaddr sa; struct stat s; socklen_t len; int type; if (file < 0) return UV_UNKNOWN_HANDLE; if (isatty(file)) return UV_TTY; if (fstat(file, &s)) return UV_UNKNOWN_HANDLE; if (S_ISREG(s.st_mode)) return UV_FILE; if (S_ISCHR(s.st_mode)) return UV_FILE; /* XXX UV_NAMED_PIPE? */ if (S_ISFIFO(s.st_mode)) return UV_NAMED_PIPE; if (!S_ISSOCK(s.st_mode)) return UV_UNKNOWN_HANDLE; len = sizeof(type); if (getsockopt(file, SOL_SOCKET, SO_TYPE, &type, &len)) return UV_UNKNOWN_HANDLE; len = sizeof(sa); if (getsockname(file, &sa, &len)) return UV_UNKNOWN_HANDLE; if (type == SOCK_DGRAM) if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6) return UV_UDP; if (type == SOCK_STREAM) { #if defined(_AIX) || defined(__DragonFly__) /* on AIX/DragonFly the getsockname call returns an empty sa structure * for sockets of type AF_UNIX. For all other types it will * return a properly filled in structure. */ if (len == 0) return UV_NAMED_PIPE; #endif /* defined(_AIX) || defined(__DragonFly__) */ if (sa.sa_family == AF_INET || sa.sa_family == AF_INET6) return UV_TCP; if (sa.sa_family == AF_UNIX) return UV_NAMED_PIPE; } return UV_UNKNOWN_HANDLE; } /* This function is async signal-safe, meaning that it's safe to call from * inside a signal handler _unless_ execution was inside uv_tty_set_mode()'s * critical section when the signal was raised. */ int uv_tty_reset_mode(void) { int saved_errno; int err; saved_errno = errno; if (!uv_spinlock_trylock(&termios_spinlock)) return UV_EBUSY; /* In uv_tty_set_mode(). */ err = 0; if (orig_termios_fd != -1) if (tcsetattr(orig_termios_fd, TCSANOW, &orig_termios)) err = UV__ERR(errno); uv_spinlock_unlock(&termios_spinlock); errno = saved_errno; return err; }
679552.c
/* * Gamepad daemon device * * Authors: * Antti Partanen <[email protected]> */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <linux/uinput.h> #include <libe/log.h> #include <libe/linkedlist.h> #include "gdd.h" static struct gdd *gdd_first; static struct gdd *gdd_last; int gdd_init(void) { return 0; } void gdd_quit(void) { } struct gdd *gdd_create(uint32_t id, uint8_t type) { struct gdd *gdd; struct uinput_setup usetup; int fd; for (gdd = gdd_first; gdd; gdd = gdd->next) { if (gdd->id == id) { return gdd; } } fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK); ERROR_IF_R(fd < 0, NULL, "failed to create new uinput device"); /* enable the device */ ioctl(fd, UI_SET_EVBIT, EV_KEY); ioctl(fd, UI_SET_KEYBIT, BTN_A); ioctl(fd, UI_SET_KEYBIT, BTN_B); ioctl(fd, UI_SET_KEYBIT, BTN_SELECT); ioctl(fd, UI_SET_KEYBIT, BTN_START); ioctl(fd, UI_SET_KEYBIT, BTN_DPAD_UP); ioctl(fd, UI_SET_KEYBIT, BTN_DPAD_DOWN); ioctl(fd, UI_SET_KEYBIT, BTN_DPAD_LEFT); ioctl(fd, UI_SET_KEYBIT, BTN_DPAD_RIGHT); /* setup and create */ memset(&usetup, 0, sizeof(usetup)); usetup.id.bustype = BUS_USB; usetup.id.vendor = 0x7777; usetup.id.product = 0x7777; strcpy(usetup.name, "Duge's gamepad"); ioctl(fd, UI_DEV_SETUP, &usetup); ioctl(fd, UI_DEV_CREATE); /* allocate device and fill data */ SALLOC(gdd, NULL); gdd->id = id; gdd->fd = fd; LL_APP(gdd_first, gdd_last, gdd); return gdd; } void gdd_destroy(struct gdd *gdd) { if (gdd) { ioctl(gdd->fd, UI_DEV_DESTROY); close(gdd->fd); free(gdd); } } int gdd_set_buttons(struct gdd *gdd, uint16_t buttons) { struct input_event ie; ie.time.tv_sec = 0; ie.time.tv_usec = 0; for (int i = 0; i < 8; i++) { ie.type = EV_KEY; ie.code = 0; ie.value = buttons & (1 << i) ? 1 : 0; switch (i) { case 0: ie.code = BTN_A; break; case 1: ie.code = BTN_B; break; case 2: ie.code = BTN_SELECT; break; case 3: ie.code = BTN_START; break; case 4: ie.code = BTN_DPAD_UP; break; case 5: ie.code = BTN_DPAD_DOWN; break; case 6: ie.code = BTN_DPAD_LEFT; break; case 7: ie.code = BTN_DPAD_RIGHT; break; } ERROR_IF(write(gdd->fd, &ie, sizeof(ie)) < 1, "write failed"); } ie.type = EV_SYN; ie.code = SYN_REPORT; ie.value = 0; ERROR_IF(write(gdd->fd, &ie, sizeof(ie)) < 1, "write failed"); return 0; }
176259.c
/* * Copyright (C) 2019 HAW Hamburg * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. * */ /** * @ingroup sys_auto_init_saul * @{ * * @file * @brief Auto initialization of AD7746 * * @author Leandro Lanzieri <[email protected]> * * @} */ #ifdef MODULE_AD7746 #include "assert.h" #include "log.h" #include "saul_reg.h" #include "ad7746.h" #include "ad7746_params.h" /** * @brief Define the number of configured sensors */ #define AD7746_NUM ARRAY_SIZE(ad7746_params) /** * @brief Allocate memory for the device descriptors. */ static ad7746_t ad7746_devs[AD7746_NUM]; /** * @brief Memory for the SAUL registry entries. Each device provides * 3 SAUL entries (capacitance, temperature and voltage) */ static saul_reg_t saul_entries[AD7746_NUM * 3]; /** * @brief Define the number of saul info */ #define AD7746_INFO_NUM ARRAY_SIZE(ad7746_saul_info) /** * @brief Reference the driver structs * @{ */ extern saul_driver_t ad7746_saul_driver_cap; extern saul_driver_t ad7746_saul_driver_temp; extern saul_driver_t ad7746_saul_driver_volt; /** @} */ void auto_init_ad7746(void) { assert(AD7746_INFO_NUM == AD7746_NUM); for (unsigned i = 0; i < AD7746_NUM; i++) { LOG_DEBUG("[auto_init_saul] initializing ad7746 #%d\n", i); if (ad7746_init(&ad7746_devs[i], &ad7746_params[i]) < 0) { LOG_ERROR("[auto_init_saul] error initializing ad7746 #%d\n", i); continue; } /* add capacitance driver */ saul_entries[i].dev = &(ad7746_devs[i]); saul_entries[i].name = ad7746_saul_info[i].name; saul_entries[i].driver = &ad7746_saul_driver_cap; saul_reg_add(&(saul_entries[i])); /* add temperature driver */ saul_entries[i + 1].dev = &(ad7746_devs[i]); saul_entries[i + 1].name = ad7746_saul_info[i].name; saul_entries[i + 1].driver = &ad7746_saul_driver_temp; saul_reg_add(&(saul_entries[i + 1])); /* add voltage driver */ saul_entries[i + 2].dev = &(ad7746_devs[i]); saul_entries[i + 2].name = ad7746_saul_info[i].name; saul_entries[i + 2].driver = &ad7746_saul_driver_volt; saul_reg_add(&(saul_entries[i + 2])); } } #else typedef int dont_be_pedantic; #endif /* MODULE_AD7746 */
790061.c
#include<stdio.h> int main() { printf("Hello, World!"); return 0; }
80505.c
/****************************************************************************** * * Copyright(c) 2007 - 2011 Realtek Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA * * ******************************************************************************/ #define _RTW_STA_MGT_C_ #include <drv_conf.h> #include <osdep_service.h> #include <drv_types.h> #include <recv_osdep.h> #include <xmit_osdep.h> #include <mlme_osdep.h> #if defined (PLATFORM_LINUX) && defined (PLATFORM_WINDOWS) #error "Shall be Linux or Windows, but not both!\n" #endif #include <sta_info.h> void _rtw_init_stainfo(struct sta_info *psta) { _func_enter_; _rtw_memset((u8 *)psta, 0, sizeof (struct sta_info)); _rtw_spinlock_init(&psta->lock); _rtw_init_listhead(&psta->list); _rtw_init_listhead(&psta->hash_list); //_rtw_init_listhead(&psta->asoc_list); //_rtw_init_listhead(&psta->sleep_list); //_rtw_init_listhead(&psta->wakeup_list); _rtw_init_queue(&psta->sleep_q); psta->sleepq_len = 0; _rtw_init_sta_xmit_priv(&psta->sta_xmitpriv); _rtw_init_sta_recv_priv(&psta->sta_recvpriv); #ifdef CONFIG_AP_MODE _rtw_init_listhead(&psta->asoc_list); _rtw_init_listhead(&psta->auth_list); psta->expire_to = 0; psta->flags = 0; psta->capability = 0; psta->bpairwise_key_installed = _FALSE; #ifdef CONFIG_NATIVEAP_MLME psta->nonerp_set = 0; psta->no_short_slot_time_set = 0; psta->no_short_preamble_set = 0; psta->no_ht_gf_set = 0; psta->no_ht_set = 0; psta->ht_20mhz_set = 0; #endif #ifdef CONFIG_TX_MCAST2UNI psta->under_exist_checking = 0; #endif // CONFIG_TX_MCAST2UNI #endif // CONFIG_AP_MODE _func_exit_; } u32 _rtw_init_sta_priv(struct sta_priv *pstapriv) { struct sta_info *psta; s32 i; _func_enter_; pstapriv->pallocated_stainfo_buf = rtw_zvmalloc (sizeof(struct sta_info) * NUM_STA+ 4); if(!pstapriv->pallocated_stainfo_buf) return _FAIL; pstapriv->pstainfo_buf = pstapriv->pallocated_stainfo_buf + 4 - ((SIZE_PTR)(pstapriv->pallocated_stainfo_buf ) & 3); _rtw_init_queue(&pstapriv->free_sta_queue); _rtw_spinlock_init(&pstapriv->sta_hash_lock); //_rtw_init_queue(&pstapriv->asoc_q); pstapriv->asoc_sta_count = 0; _rtw_init_queue(&pstapriv->sleep_q); _rtw_init_queue(&pstapriv->wakeup_q); psta = (struct sta_info *)(pstapriv->pstainfo_buf); for(i = 0; i < NUM_STA; i++) { _rtw_init_stainfo(psta); _rtw_init_listhead(&(pstapriv->sta_hash[i])); rtw_list_insert_tail(&psta->list, get_list_head(&pstapriv->free_sta_queue)); psta++; } #ifdef CONFIG_AP_MODE pstapriv->sta_dz_bitmap = 0; pstapriv->tim_bitmap = 0; _rtw_init_listhead(&pstapriv->asoc_list); _rtw_init_listhead(&pstapriv->auth_list); _rtw_spinlock_init(&pstapriv->asoc_list_lock); _rtw_spinlock_init(&pstapriv->auth_list_lock); pstapriv->auth_to = 3; // 3*2 = 6 sec pstapriv->assoc_to = 3; //pstapriv->expire_to = 900;// 900*2 = 1800 sec = 30 min, expire after no any traffic. //pstapriv->expire_to = 30;// 30*2 = 60 sec = 1 min, expire after no any traffic. pstapriv->expire_to = 60;// 60*2 = 120 sec = 2 min, expire after no any traffic. pstapriv->max_num_sta = NUM_STA; #endif _func_exit_; return _SUCCESS; } void _rtw_free_sta_xmit_priv_lock(struct sta_xmit_priv *psta_xmitpriv) { _func_enter_; _rtw_spinlock_free(&psta_xmitpriv->lock); _rtw_spinlock_free(&(psta_xmitpriv->be_q.sta_pending.lock)); _rtw_spinlock_free(&(psta_xmitpriv->bk_q.sta_pending.lock)); _rtw_spinlock_free(&(psta_xmitpriv->vi_q.sta_pending.lock)); _rtw_spinlock_free(&(psta_xmitpriv->vo_q.sta_pending.lock)); _func_exit_; } static void _rtw_free_sta_recv_priv_lock(struct sta_recv_priv *psta_recvpriv) { _func_enter_; _rtw_spinlock_free(&psta_recvpriv->lock); _rtw_spinlock_free(&(psta_recvpriv->defrag_q.lock)); _func_exit_; } void rtw_mfree_stainfo(struct sta_info *psta) { _func_enter_; if(&psta->lock != NULL) _rtw_spinlock_free(&psta->lock); _rtw_free_sta_xmit_priv_lock(&psta->sta_xmitpriv); _rtw_free_sta_recv_priv_lock(&psta->sta_recvpriv); _func_exit_; } // this function is used to free the memory of lock || sema for all stainfos void rtw_mfree_all_stainfo(struct sta_priv *pstapriv ) { _irqL irqL; _list *plist, *phead; struct sta_info *psta = NULL; _func_enter_; _enter_critical_bh(&pstapriv->sta_hash_lock, &irqL); phead = get_list_head(&pstapriv->free_sta_queue); plist = get_next(phead); while ((rtw_end_of_queue_search(phead, plist)) == _FALSE) { psta = LIST_CONTAINOR(plist, struct sta_info ,list); plist = get_next(plist); rtw_mfree_stainfo(psta); } _exit_critical_bh(&pstapriv->sta_hash_lock, &irqL); _func_exit_; } void rtw_mfree_sta_priv_lock(struct sta_priv *pstapriv) { rtw_mfree_all_stainfo(pstapriv); //be done before free sta_hash_lock _rtw_spinlock_free(&pstapriv->free_sta_queue.lock); _rtw_spinlock_free(&pstapriv->sta_hash_lock); _rtw_spinlock_free(&pstapriv->wakeup_q.lock); _rtw_spinlock_free(&pstapriv->sleep_q.lock); #ifdef CONFIG_AP_MODE _rtw_spinlock_free(&pstapriv->asoc_list_lock); _rtw_spinlock_free(&pstapriv->auth_list_lock); #endif } u32 _rtw_free_sta_priv(struct sta_priv *pstapriv) { _func_enter_; if(pstapriv){ rtw_mfree_sta_priv_lock(pstapriv); if(pstapriv->pallocated_stainfo_buf) { rtw_vmfree(pstapriv->pallocated_stainfo_buf, sizeof(struct sta_info)*NUM_STA+4); } } _func_exit_; return _SUCCESS; } //struct sta_info *rtw_alloc_stainfo(_queue *pfree_sta_queue, unsigned char *hwaddr) struct sta_info *rtw_alloc_stainfo(struct sta_priv *pstapriv, u8 *hwaddr) { _irqL irqL, irqL2; uint tmp_aid; s32 index; _list *phash_list; struct sta_info *psta; _queue *pfree_sta_queue; struct recv_reorder_ctrl *preorder_ctrl; int i = 0; u16 wRxSeqInitialValue = 0xffff; _func_enter_; pfree_sta_queue = &pstapriv->free_sta_queue; _enter_critical_bh(&(pfree_sta_queue->lock), &irqL); if (_rtw_queue_empty(pfree_sta_queue) == _TRUE) { _exit_critical_bh(&(pfree_sta_queue->lock), &irqL); psta = NULL; } else { psta = LIST_CONTAINOR(get_next(&pfree_sta_queue->queue), struct sta_info, list); rtw_list_delete(&(psta->list)); _exit_critical_bh(&(pfree_sta_queue->lock), &irqL); tmp_aid = psta->aid; _rtw_init_stainfo(psta); _rtw_memcpy(psta->hwaddr, hwaddr, ETH_ALEN); index = wifi_mac_hash(hwaddr); RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_info_,("rtw_alloc_stainfo: index = %x", index)); if(index >= NUM_STA){ RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_err_,("ERROR=> rtw_alloc_stainfo: index >= NUM_STA")); psta= NULL; goto exit; } phash_list = &(pstapriv->sta_hash[index]); _enter_critical_bh(&(pstapriv->sta_hash_lock), &irqL2); rtw_list_insert_tail(&psta->hash_list, phash_list); pstapriv->asoc_sta_count ++ ; _exit_critical_bh(&(pstapriv->sta_hash_lock), &irqL2); // Commented by Albert 2009/08/13 // For the SMC router, the sequence number of first packet of WPS handshake will be 0. // In this case, this packet will be dropped by recv_decache function if we use the 0x00 as the default value for tid_rxseq variable. // So, we initialize the tid_rxseq variable as the 0xffff. for( i = 0; i < 16; i++ ) { _rtw_memcpy( &psta->sta_recvpriv.rxcache.tid_rxseq[ i ], &wRxSeqInitialValue, 2 ); } RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_info_,("alloc number_%d stainfo with hwaddr = %x %x %x %x %x %x \n", pstapriv->asoc_sta_count , hwaddr[0], hwaddr[1], hwaddr[2],hwaddr[3],hwaddr[4],hwaddr[5])); init_addba_retry_timer(pstapriv->padapter, psta); #ifdef CONFIG_TDLS psta->padapter = pstapriv->padapter; init_TPK_timer(pstapriv->padapter, psta); init_ch_switch_timer(pstapriv->padapter, psta); init_base_ch_timer(pstapriv->padapter, psta); init_off_ch_timer(pstapriv->padapter, psta); init_handshake_timer(pstapriv->padapter, psta); init_tdls_alive_timer(pstapriv->padapter, psta); #endif //for A-MPDU Rx reordering buffer control for(i=0; i < 16 ; i++) { preorder_ctrl = &psta->recvreorder_ctrl[i]; preorder_ctrl->padapter = pstapriv->padapter; preorder_ctrl->enable = _FALSE; preorder_ctrl->indicate_seq = 0xffff; #ifdef DBG_RX_SEQ DBG_871X("DBG_RX_SEQ %s:%d IndicateSeq: %d\n", __FUNCTION__, __LINE__, preorder_ctrl->indicate_seq); #endif preorder_ctrl->wend_b= 0xffff; //preorder_ctrl->wsize_b = (NR_RECVBUFF-2); preorder_ctrl->wsize_b = 64;//64; _rtw_init_queue(&preorder_ctrl->pending_recvframe_queue); rtw_init_recv_timer(preorder_ctrl); } //init for DM psta->rssi_stat.UndecoratedSmoothedPWDB = (-1); psta->rssi_stat.UndecoratedSmoothedCCK = (-1); } exit: _func_exit_; return psta; } // using pstapriv->sta_hash_lock to protect u32 rtw_free_stainfo(_adapter *padapter , struct sta_info *psta) { int i; _irqL irqL0; _queue *pfree_sta_queue; struct recv_reorder_ctrl *preorder_ctrl; struct sta_xmit_priv *pstaxmitpriv; struct xmit_priv *pxmitpriv= &padapter->xmitpriv; struct sta_priv *pstapriv = &padapter->stapriv; _func_enter_; if (psta == NULL) goto exit; pfree_sta_queue = &pstapriv->free_sta_queue; pstaxmitpriv = &psta->sta_xmitpriv; //rtw_list_delete(&psta->sleep_list); //rtw_list_delete(&psta->wakeup_list); _enter_critical_bh(&pxmitpriv->lock, &irqL0); rtw_free_xmitframe_queue(pxmitpriv, &psta->sleep_q); psta->sleepq_len = 0; //_enter_critical_bh(&(pxmitpriv->vo_pending.lock), &irqL0); rtw_free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->vo_q.sta_pending); rtw_list_delete(&(pstaxmitpriv->vo_q.tx_pending)); //_exit_critical_bh(&(pxmitpriv->vo_pending.lock), &irqL0); //_enter_critical_bh(&(pxmitpriv->vi_pending.lock), &irqL0); rtw_free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->vi_q.sta_pending); rtw_list_delete(&(pstaxmitpriv->vi_q.tx_pending)); //_exit_critical_bh(&(pxmitpriv->vi_pending.lock), &irqL0); //_enter_critical_bh(&(pxmitpriv->bk_pending.lock), &irqL0); rtw_free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->bk_q.sta_pending); rtw_list_delete(&(pstaxmitpriv->bk_q.tx_pending)); //_exit_critical_bh(&(pxmitpriv->bk_pending.lock), &irqL0); //_enter_critical_bh(&(pxmitpriv->be_pending.lock), &irqL0); rtw_free_xmitframe_queue( pxmitpriv, &pstaxmitpriv->be_q.sta_pending); rtw_list_delete(&(pstaxmitpriv->be_q.tx_pending)); //_exit_critical_bh(&(pxmitpriv->be_pending.lock), &irqL0); _exit_critical_bh(&pxmitpriv->lock, &irqL0); rtw_list_delete(&psta->hash_list); RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_err_,("\n free number_%d stainfo with hwaddr = 0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x 0x%.2x \n",pstapriv->asoc_sta_count , psta->hwaddr[0], psta->hwaddr[1], psta->hwaddr[2],psta->hwaddr[3],psta->hwaddr[4],psta->hwaddr[5])); pstapriv->asoc_sta_count --; // re-init sta_info; 20061114 _rtw_init_sta_xmit_priv(&psta->sta_xmitpriv); _rtw_init_sta_recv_priv(&psta->sta_recvpriv); _cancel_timer_ex(&psta->addba_retry_timer); #ifdef CONFIG_TDLS _cancel_timer_ex(&psta->TPK_timer); _cancel_timer_ex(&psta->option_timer); _cancel_timer_ex(&psta->base_ch_timer); _cancel_timer_ex(&psta->off_ch_timer); _cancel_timer_ex(&psta->alive_timer1); _cancel_timer_ex(&psta->alive_timer2); #endif //for A-MPDU Rx reordering buffer control, cancel reordering_ctrl_timer for(i=0; i < 16 ; i++) { _irqL irqL; _list *phead, *plist; union recv_frame *prframe; _queue *ppending_recvframe_queue; _queue *pfree_recv_queue = &padapter->recvpriv.free_recv_queue; preorder_ctrl = &psta->recvreorder_ctrl[i]; _cancel_timer_ex(&preorder_ctrl->reordering_ctrl_timer); ppending_recvframe_queue = &preorder_ctrl->pending_recvframe_queue; _enter_critical_bh(&ppending_recvframe_queue->lock, &irqL); phead = get_list_head(ppending_recvframe_queue); plist = get_next(phead); while(!rtw_is_list_empty(phead)) { prframe = LIST_CONTAINOR(plist, union recv_frame, u); plist = get_next(plist); rtw_list_delete(&(prframe->u.hdr.list)); rtw_free_recvframe(prframe, pfree_recv_queue); } _exit_critical_bh(&ppending_recvframe_queue->lock, &irqL); } #ifdef CONFIG_AP_MODE /* _enter_critical_bh(&pstapriv->asoc_list_lock, &irqL0); rtw_list_delete(&psta->asoc_list); _exit_critical_bh(&pstapriv->asoc_list_lock, &irqL0); */ _enter_critical_bh(&pstapriv->auth_list_lock, &irqL0); rtw_list_delete(&psta->auth_list); _exit_critical_bh(&pstapriv->auth_list_lock, &irqL0); psta->expire_to = 0; psta->sleepq_ac_len = 0; psta->qos_info = 0; psta->max_sp_len = 0; psta->uapsd_bk = 0; psta->uapsd_be = 0; psta->uapsd_vi = 0; psta->uapsd_vo = 0; psta->has_legacy_ac = 0; #ifdef CONFIG_NATIVEAP_MLME pstapriv->sta_dz_bitmap &=~BIT(psta->aid); pstapriv->tim_bitmap &=~BIT(psta->aid); //rtw_indicate_sta_disassoc_event(padapter, psta); if (pstapriv->sta_aid[psta->aid - 1] == psta) { pstapriv->sta_aid[psta->aid - 1] = NULL; psta->aid = 0; } #endif // CONFIG_NATIVEAP_MLME #ifdef CONFIG_TX_MCAST2UNI psta->under_exist_checking = 0; #endif // CONFIG_TX_MCAST2UNI #endif // CONFIG_AP_MODE _enter_critical_bh(&(pfree_sta_queue->lock), &irqL0); rtw_list_insert_tail(&psta->list, get_list_head(pfree_sta_queue)); _exit_critical_bh(&(pfree_sta_queue->lock), &irqL0); exit: _func_exit_; return _SUCCESS; } // free all stainfo which in sta_hash[all] void rtw_free_all_stainfo(_adapter *padapter) { _irqL irqL; _list *plist, *phead; s32 index; struct sta_info *psta = NULL; struct sta_priv *pstapriv = &padapter->stapriv; struct sta_info* pbcmc_stainfo =rtw_get_bcmc_stainfo( padapter); _func_enter_; if(pstapriv->asoc_sta_count==1) goto exit; _enter_critical_bh(&pstapriv->sta_hash_lock, &irqL); for(index=0; index< NUM_STA; index++) { phead = &(pstapriv->sta_hash[index]); plist = get_next(phead); while ((rtw_end_of_queue_search(phead, plist)) == _FALSE) { psta = LIST_CONTAINOR(plist, struct sta_info ,hash_list); plist = get_next(plist); if(pbcmc_stainfo!=psta) rtw_free_stainfo(padapter , psta); } } _exit_critical_bh(&pstapriv->sta_hash_lock, &irqL); exit: _func_exit_; } /* any station allocated can be searched by hash list */ struct sta_info *rtw_get_stainfo(struct sta_priv *pstapriv, u8 *hwaddr) { _irqL irqL; _list *plist, *phead; struct sta_info *psta = NULL; u32 index; u8 *addr; u8 bc_addr[ETH_ALEN] = {0xff,0xff,0xff,0xff,0xff,0xff}; _func_enter_; if(hwaddr==NULL) return NULL; if(IS_MCAST(hwaddr)) { addr = bc_addr; } else { addr = hwaddr; } index = wifi_mac_hash(addr); _enter_critical_bh(&pstapriv->sta_hash_lock, &irqL); phead = &(pstapriv->sta_hash[index]); plist = get_next(phead); while ((rtw_end_of_queue_search(phead, plist)) == _FALSE) { psta = LIST_CONTAINOR(plist, struct sta_info, hash_list); if ((_rtw_memcmp(psta->hwaddr, addr, ETH_ALEN))== _TRUE) { // if found the matched address break; } psta=NULL; plist = get_next(plist); } _exit_critical_bh(&pstapriv->sta_hash_lock, &irqL); _func_exit_; return psta; } u32 rtw_init_bcmc_stainfo(_adapter* padapter) { struct sta_info *psta; struct tx_servq *ptxservq; u32 res=_SUCCESS; NDIS_802_11_MAC_ADDRESS bcast_addr= {0xff,0xff,0xff,0xff,0xff,0xff}; struct sta_priv *pstapriv = &padapter->stapriv; //_queue *pstapending = &padapter->xmitpriv.bm_pending; _func_enter_; psta = rtw_alloc_stainfo(pstapriv, bcast_addr); if(psta==NULL){ res=_FAIL; RT_TRACE(_module_rtl871x_sta_mgt_c_,_drv_err_,("rtw_alloc_stainfo fail")); goto exit; } // default broadcast & multicast use macid 1 psta->mac_id = 1; ptxservq= &(psta->sta_xmitpriv.be_q); /* _enter_critical(&pstapending->lock, &irqL0); if (rtw_is_list_empty(&ptxservq->tx_pending)) rtw_list_insert_tail(&ptxservq->tx_pending, get_list_head(pstapending)); _exit_critical(&pstapending->lock, &irqL0); */ exit: _func_exit_; return _SUCCESS; } struct sta_info* rtw_get_bcmc_stainfo(_adapter* padapter) { struct sta_info *psta; struct sta_priv *pstapriv = &padapter->stapriv; u8 bc_addr[ETH_ALEN] = {0xff,0xff,0xff,0xff,0xff,0xff}; _func_enter_; psta = rtw_get_stainfo(pstapriv, bc_addr); _func_exit_; return psta; } u8 rtw_access_ctrl(struct wlan_acl_pool* pacl_list, u8 * mac_addr) { return _TRUE; }
150697.c
/* Copyright 2020 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <device.h> #include <drivers/cros_bbram.h> #include <drivers/cros_system.h> #include <logging/log.h> #include "bbram.h" #include "common.h" #include "cros_version.h" #include "system.h" #include "watchdog.h" #define BBRAM_REGION_PD0 DT_PATH(named_bbram_regions, pd0) #define BBRAM_REGION_PD1 DT_PATH(named_bbram_regions, pd1) #define BBRAM_REGION_PD2 DT_PATH(named_bbram_regions, pd2) #define BBRAM_REGION_TRY_SLOT DT_PATH(named_bbram_regions, try_slot) LOG_MODULE_REGISTER(shim_system, LOG_LEVEL_ERR); STATIC_IF_NOT(CONFIG_ZTEST) const struct device *bbram_dev; STATIC_IF_NOT(CONFIG_ZTEST) const struct device *sys_dev; #if DT_NODE_EXISTS(DT_NODELABEL(bbram)) static int system_init(const struct device *unused) { ARG_UNUSED(unused); bbram_dev = device_get_binding(DT_LABEL(DT_NODELABEL(bbram))); return 0; } SYS_INIT(system_init, PRE_KERNEL_1, 50); #endif /* Map idx to a bbram offset/size, or return -1 on invalid idx */ static int bbram_lookup(enum system_bbram_idx idx, int *offset_out, int *size_out) { switch (idx) { case SYSTEM_BBRAM_IDX_PD0: *offset_out = DT_PROP(BBRAM_REGION_PD0, offset); *size_out = DT_PROP(BBRAM_REGION_PD0, size); break; case SYSTEM_BBRAM_IDX_PD1: *offset_out = DT_PROP(BBRAM_REGION_PD1, offset); *size_out = DT_PROP(BBRAM_REGION_PD1, size); break; case SYSTEM_BBRAM_IDX_PD2: *offset_out = DT_PROP(BBRAM_REGION_PD2, offset); *size_out = DT_PROP(BBRAM_REGION_PD2, size); break; case SYSTEM_BBRAM_IDX_TRY_SLOT: *offset_out = DT_PROP(BBRAM_REGION_TRY_SLOT, offset); *size_out = DT_PROP(BBRAM_REGION_TRY_SLOT, size); break; default: return EC_ERROR_INVAL; } return EC_SUCCESS; } int system_get_bbram(enum system_bbram_idx idx, uint8_t *value) { int offset, size, rc; if (bbram_dev == NULL) return EC_ERROR_INVAL; rc = bbram_lookup(idx, &offset, &size); if (rc) return rc; rc = cros_bbram_read(bbram_dev, offset, size, value); return rc ? EC_ERROR_INVAL : EC_SUCCESS; } void system_hibernate(uint32_t seconds, uint32_t microseconds) { const struct device *sys_dev = device_get_binding("CROS_SYSTEM"); int err; /* Flush console before hibernating */ cflush(); if (board_hibernate) board_hibernate(); /* Save 'wake-up from hibernate' reset flag */ chip_save_reset_flags(chip_read_reset_flags() | EC_RESET_FLAG_HIBERNATE); err = cros_system_hibernate(sys_dev, seconds, microseconds); if (err < 0) { LOG_ERR("hibernate failed %d", err); return; } /* should never reach this point */ while (1) continue; } const char *system_get_chip_vendor(void) { const struct device *sys_dev = device_get_binding("CROS_SYSTEM"); return cros_system_chip_vendor(sys_dev); } const char *system_get_chip_name(void) { const struct device *sys_dev = device_get_binding("CROS_SYSTEM"); return cros_system_chip_name(sys_dev); } const char *system_get_chip_revision(void) { const struct device *sys_dev = device_get_binding("CROS_SYSTEM"); return cros_system_chip_revision(sys_dev); } void system_reset(int flags) { int err; uint32_t save_flags; if (!sys_dev) LOG_ERR("sys_dev get binding failed"); /* Disable interrupts to avoid task swaps during reboot */ interrupt_disable_all(); /* Get flags to be saved in BBRAM */ system_encode_save_flags(flags, &save_flags); /* Store flags to battery backed RAM. */ chip_save_reset_flags(save_flags); /* If WAIT_EXT is set, then allow 10 seconds for external reset */ if (flags & SYSTEM_RESET_WAIT_EXT) { int i; /* Wait 10 seconds for external reset */ for (i = 0; i < 1000; i++) { watchdog_reload(); udelay(10000); } } err = cros_system_soc_reset(sys_dev); if (err < 0) LOG_ERR("soc reset failed"); /* should never return */ while (1) continue; } static int check_reset_cause(void) { uint32_t chip_flags = 0; /* used to write back to the BBRAM */ uint32_t system_flags = chip_read_reset_flags(); /* system reset flag */ int chip_reset_cause = 0; /* chip-level reset cause */ chip_reset_cause = cros_system_get_reset_cause(sys_dev); if (chip_reset_cause < 0) return -1; /* * TODO(b/182876692): Implement CONFIG_POWER_BUTTON_INIT_IDLE & * CONFIG_BOARD_FORCE_RESET_PIN. */ switch (chip_reset_cause) { case POWERUP: system_flags |= EC_RESET_FLAG_POWER_ON; /* * Power-on restart, so set a flag and save it for the next * imminent reset. Later code will check for this flag and wait * for the second reset. Waking from PSL hibernate is power-on * for EC but not for H1, so do not wait for the second reset. */ if (IS_ENABLED(CONFIG_BOARD_RESET_AFTER_POWER_ON) && ((system_flags & EC_RESET_FLAG_HIBERNATE) == 0)) { system_flags |= EC_RESET_FLAG_INITIAL_PWR; chip_flags |= EC_RESET_FLAG_INITIAL_PWR; } break; case VCC1_RST_PIN: /* * If configured, check the saved flags to see whether the * previous restart was a power-on, in which case treat this * restart as a power-on as well. This is to workaround the fact * that the H1 will reset the EC at power up. */ if (IS_ENABLED(CONFIG_BOARD_RESET_AFTER_POWER_ON)) { if (system_flags & EC_RESET_FLAG_INITIAL_PWR) { /* * The previous restart was a power-on so treat * this restart as that, and clear the flag so * later code will not wait for the second * reset. */ system_flags = (system_flags & ~EC_RESET_FLAG_INITIAL_PWR) | EC_RESET_FLAG_POWER_ON; } else { /* * No previous reset flag, so this is a * subsequent restart i.e any restarts after the * second restart caused by the H1. */ system_flags |= EC_RESET_FLAG_RESET_PIN; } } else { system_flags |= EC_RESET_FLAG_RESET_PIN; } break; case DEBUG_RST: system_flags |= EC_RESET_FLAG_SOFT; break; case WATCHDOG_RST: /* * Don't set EC_RESET_FLAG_WATCHDOG flag if watchdog is issued * by system_reset or hibernate in order to distinguish reset * cause is panic reason or not. */ if (!(system_flags & (EC_RESET_FLAG_SOFT | EC_RESET_FLAG_HARD | EC_RESET_FLAG_HIBERNATE))) system_flags |= EC_RESET_FLAG_WATCHDOG; break; } /* Clear & set the reset flags for the following reset. */ chip_save_reset_flags(chip_flags); /* Set the system reset flags. */ system_set_reset_flags(system_flags); return 0; } static int system_preinitialize(const struct device *unused) { ARG_UNUSED(unused); sys_dev = device_get_binding("CROS_SYSTEM"); if (!sys_dev) { /* * TODO(b/183022804): This should not happen in normal * operation. Check whether the error check can be change to * build-time error, or at least a fatal run-time error. */ LOG_ERR("sys_dev gets binding failed"); return -1; } /* check the reset cause */ if (check_reset_cause() != 0) { LOG_ERR("check the reset cause failed"); return -1; } /* * For some boards on power-on, the EC is reset by the H1 after * power-on, so the EC sees 2 resets. This config enables the EC to save * a flag on the first power-up restart, and then wait for the second * reset before any other setup is done (such as GPIOs, timers, UART * etc.) On the second reset, the saved flag is used to detect the * previous power-on, and treat the second reset as a power-on instead * of a reset. */ if (IS_ENABLED(CONFIG_BOARD_RESET_AFTER_POWER_ON) && system_get_reset_flags() & EC_RESET_FLAG_INITIAL_PWR) { /* TODO(b/182875520): Change to use 2 second delay. */ while (1) continue; } return 0; } #if (!defined(CONFIG_ZTEST)) SYS_INIT(system_preinitialize, PRE_KERNEL_1, CONFIG_PLATFORM_EC_SYSTEM_PRE_INIT_PRIORITY); #endif
636856.c
/* Copyright 2021 Gravitational, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "vmlinux.h" #include <linux/limits.h> #include <bpf/bpf_helpers.h> /* most used helpers: SEC, __always_inline, etc */ #include <bpf/bpf_core_read.h> /* for BPF CO-RE helpers */ #include <bpf/bpf_tracing.h> /* for getting kprobe arguments */ #include "helpers.h" // Maximum number of in-flight open syscalls supported #define INFLIGHT_MAX 8192 // Size, in bytes, of the ring buffer used to report // audit events to userspace. This is the default, // the userspace can adjust this value based on config. #define EVENTS_BUF_SIZE (4096*128) char LICENSE[] SEC("license") = "Dual BSD/GPL"; struct val_t { u64 pid; const char *fname; int flags; }; struct data_t { u64 cgroup; u64 pid; int ret; char comm[TASK_COMM_LEN]; char fname[NAME_MAX]; int flags; }; BPF_HASH(infotmp, u64, struct val_t, INFLIGHT_MAX); // open_events ring buffer BPF_RING_BUF(open_events, EVENTS_BUF_SIZE); BPF_COUNTER(lost); static int enter_open(const char *filename, int flags) { struct val_t val = {}; u64 id = bpf_get_current_pid_tgid(); val.pid = id >> 32; val.fname = filename; val.flags = flags; bpf_map_update_elem(&infotmp, &id, &val, 0); return 0; } static int exit_open(int ret) { u64 id = bpf_get_current_pid_tgid(); struct val_t *valp; struct data_t data = {}; valp = bpf_map_lookup_elem(&infotmp, &id); if (valp == 0) { // Missed entry. return 0; } if (bpf_get_current_comm(&data.comm, sizeof(data.comm)) != 0) { data.comm[0] = '\0'; } bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)valp->fname); data.pid = valp->pid; data.flags = valp->flags; data.ret = ret; data.cgroup = bpf_get_current_cgroup_id(); if (bpf_ringbuf_output(&open_events, &data, sizeof(data), 0) != 0) INCR_COUNTER(lost); bpf_map_delete_elem(&infotmp, &id); return 0; } SEC("tp/syscalls/sys_enter_creat") int tracepoint__syscalls__sys_enter_creat(struct trace_event_raw_sys_enter *tp) { const char *filename = (const char*) tp->args[0]; return enter_open(filename, 0); } SEC("tp/syscalls/sys_exit_creat") int tracepoint__syscalls__sys_exit_creat(struct trace_event_raw_sys_exit *tp) { return exit_open(tp->ret); } SEC("tp/syscalls/sys_enter_open") int tracepoint__syscalls__sys_enter_open(struct trace_event_raw_sys_enter *tp) { const char *filename = (const char*) tp->args[0]; int flags = tp->args[1]; return enter_open(filename, flags); }; SEC("tp/syscalls/sys_exit_open") int tracepoint__syscalls__sys_exit_open(struct trace_event_raw_sys_exit *tp) { return exit_open(tp->ret); } SEC("tp/syscalls/sys_enter_openat") int tracepoint__syscalls__sys_enter_openat(struct trace_event_raw_sys_enter *tp) { const char *filename = (const char*) tp->args[1]; int flags = tp->args[2]; return enter_open(filename, flags); }; SEC("tp/syscalls/sys_exit_openat") int tracepoint__syscalls__sys_exit_openat(struct trace_event_raw_sys_exit *tp) { return exit_open(tp->ret); } SEC("tp/syscalls/sys_enter_openat2") int tracepoint__syscalls__sys_enter_openat2(struct trace_event_raw_sys_enter *tp) { const char *filename = (const char*) tp->args[1]; struct open_how *how = (struct open_how *) tp->args[2]; return enter_open(filename, BPF_CORE_READ(how, flags)); }; SEC("tp/syscalls/sys_exit_openat2") int tracepoint__syscalls__sys_exit_openat2(struct trace_event_raw_sys_exit *tp) { return exit_open(tp->ret); }
337383.c
/* * Copyright (c) 2013 Mellanox Technologies, Inc. * All rights reserved. * Copyright (c) 2013 Cisco Systems, Inc. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "oshmem_config.h" #include "oshmem/shmem/fortran/bindings.h" #include "oshmem/include/shmem.h" #include "oshmem/shmem/shmem_api_logger.h" #include "oshmem/runtime/runtime.h" #include "oshmem/mca/spml/spml.h" #include "ompi/datatype/ompi_datatype.h" #include "stdio.h" #if OSHMEM_PROFILING #include "oshmem/shmem/fortran/profile/pbindings.h" SHMEM_GENERATE_WEAK_BINDINGS(SHMEM_IPUT128, shmem_iput128) #include "oshmem/shmem/fortran/profile/defines.h" #endif SHMEM_GENERATE_FORTRAN_BINDINGS_SUB (void, SHMEM_IPUT128, shmem_iput128_, shmem_iput128__, shmem_iput128_f, (FORTRAN_POINTER_T target, FORTRAN_POINTER_T source, MPI_Fint *tst, MPI_Fint *sst, MPI_Fint *len, MPI_Fint *pe), (target,source,tst,sst,len,pe) ) void shmem_iput128_f(FORTRAN_POINTER_T target, FORTRAN_POINTER_T source, MPI_Fint *tst, MPI_Fint *sst, MPI_Fint *len, MPI_Fint *pe) { int i; int length = OMPI_FINT_2_INT(*len); int tst_c = OMPI_FINT_2_INT(*tst); int sst_c = OMPI_FINT_2_INT(*sst); for (i=0; i<length; i++) { MCA_SPML_CALL(put((uint8_t *)FPTR_2_VOID_PTR(target) + i * tst_c * 16, 16, (uint8_t *)FPTR_2_VOID_PTR(source) + i * sst_c * 16, OMPI_FINT_2_INT(*pe))); } }
699014.c
/* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <stdio.h> #include "internal/cryptlib.h" int EVP_PKEY_encrypt_old(unsigned char* ek, const unsigned char* key, int key_len, EVP_PKEY* pubk) { int ret = 0; #ifndef OPENSSL_NO_RSA if (EVP_PKEY_id(pubk) != EVP_PKEY_RSA) { #endif EVPerr(EVP_F_EVP_PKEY_ENCRYPT_OLD, EVP_R_PUBLIC_KEY_NOT_RSA); #ifndef OPENSSL_NO_RSA goto err; } ret = RSA_public_encrypt(key_len, key, ek, EVP_PKEY_get0_RSA(pubk), RSA_PKCS1_PADDING); err: #endif return ret; }
438488.c
/* ** my_getnbr_base.c for libmy in /home/pereni_j/libmy/src ** ** Made by joseph pereniguez ** Login <[email protected]> ** ** Started on Tue Jun 16 10:37:49 2015 joseph pereniguez ** Last update Tue Jun 16 16:27:48 2015 joseph pereniguez */ #include "../include/my.h" int my_getnbr_base(char *str, char *base) { char *start; int result; int len; int i; if (str[0] == '\0' || base[0] == '\0') return (0); start = my_find_first_digit(str, base); result = my_get_digit_weight(*start, base); start += 1; len = my_strlen(base); i = 0; while (start[i] != '\0' && my_is_valid_digit(start[i], base)) { result = result * len + my_get_digit_weight(start[i], base); i += 1; } if (str[0] == '-') result = -result; return (result); }
207674.c
#include<stdio.h> #include<stdlib.h> struct listNode{ int data; struct listNode *next; }; int singlyListLength(struct listNode *head){ int count; struct listNode *current=head; while(current!=NULL){ count++; current=current->next; } return count; } void insertInSinglyLinkedList(struct listNode **head, int data, int pos){ int k=1; struct listNode *q,*p; struct listNode *newNode=(struct listNode*)malloc(sizeof(struct listNode)); if(!newNode){ printf("Memory Error\n"); return; } newNode->data=data; p=*head; if(pos==1 || p==NULL){ newNode->next=*head; *head=newNode; } else{ while(p!=NULL && (k<pos)){ k++; q=p; p=p->next; } newNode->next=q->next; q->next=newNode; } } void deleteNodeFromLinkedList(struct listNode **head, int pos){ int k=1; struct listNode *p,*q; p=*head; if(*head==NULL){ printf("List Empty\n"); return; } else if(pos==1){ *head=(*head)->next; free(p); } else{ while(p!=NULL && k<pos){ k++; q=p; p=p->next; } if(p==NULL){ printf("Position does not exist\n"); } else{ q->next=p->next; free(p); } } } void printSLList(struct listNode *head){ while(head!=NULL){ printf("%d ",head->data); head=head->next; } printf("\n"); } int SinglyLinkedList_test(){ struct listNode *head=NULL; insertInSinglyLinkedList(&head,5,5); insertInSinglyLinkedList(&head,2,5); printf("Elements in List:%d\n",singlyListLength(head)); printSLList(head); deleteNodeFromLinkedList(&head,1); printSLList(head); return 0; }
220132.c
#include "cache.h" #include "object.h" #include "blob.h" #include "tree.h" #include "tree-walk.h" #include "commit.h" #include "tag.h" #include "fsck.h" #include "refs.h" #include "utf8.h" #include "sha1-array.h" #include "hashmap.h" #include "submodule-config.h" struct oidhash_entry { struct hashmap_entry ent; unsigned char sha1[20]; }; static int oidhash_hashcmp(const void *va, const void *vb, const void *vkey) { const struct oidhash_entry *a = va, *b = vb; const unsigned char *key = vkey; return hashcmp(a->sha1, key ? key : b->sha1); } static struct hashmap gitmodules_found; static struct hashmap gitmodules_done; static void oidhash_insert(struct hashmap *h, const unsigned char *sha1) { struct oidhash_entry *e; if (!h->tablesize) hashmap_init(h, oidhash_hashcmp, 0); e = xmalloc(sizeof(*e)); hashmap_entry_init(&e->ent, sha1hash(sha1)); hashcpy(e->sha1, sha1); hashmap_add(h, e); } static int oidhash_contains(struct hashmap *h, const unsigned char *sha1) { return h->tablesize && !!hashmap_get_from_hash(h, sha1hash(sha1), sha1); } #define FSCK_FATAL -1 #define FSCK_INFO -2 #define FOREACH_MSG_ID(FUNC) \ /* fatal errors */ \ FUNC(NUL_IN_HEADER, FATAL) \ FUNC(UNTERMINATED_HEADER, FATAL) \ /* errors */ \ FUNC(BAD_DATE, ERROR) \ FUNC(BAD_DATE_OVERFLOW, ERROR) \ FUNC(BAD_EMAIL, ERROR) \ FUNC(BAD_NAME, ERROR) \ FUNC(BAD_OBJECT_SHA1, ERROR) \ FUNC(BAD_PARENT_SHA1, ERROR) \ FUNC(BAD_TAG_OBJECT, ERROR) \ FUNC(BAD_TIMEZONE, ERROR) \ FUNC(BAD_TREE, ERROR) \ FUNC(BAD_TREE_SHA1, ERROR) \ FUNC(BAD_TYPE, ERROR) \ FUNC(DUPLICATE_ENTRIES, ERROR) \ FUNC(MISSING_AUTHOR, ERROR) \ FUNC(MISSING_COMMITTER, ERROR) \ FUNC(MISSING_EMAIL, ERROR) \ FUNC(MISSING_GRAFT, ERROR) \ FUNC(MISSING_NAME_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_OBJECT, ERROR) \ FUNC(MISSING_PARENT, ERROR) \ FUNC(MISSING_SPACE_BEFORE_DATE, ERROR) \ FUNC(MISSING_SPACE_BEFORE_EMAIL, ERROR) \ FUNC(MISSING_TAG, ERROR) \ FUNC(MISSING_TAG_ENTRY, ERROR) \ FUNC(MISSING_TAG_OBJECT, ERROR) \ FUNC(MISSING_TREE, ERROR) \ FUNC(MISSING_TREE_OBJECT, ERROR) \ FUNC(MISSING_TYPE, ERROR) \ FUNC(MISSING_TYPE_ENTRY, ERROR) \ FUNC(MULTIPLE_AUTHORS, ERROR) \ FUNC(TAG_OBJECT_NOT_TAG, ERROR) \ FUNC(TREE_NOT_SORTED, ERROR) \ FUNC(UNKNOWN_TYPE, ERROR) \ FUNC(ZERO_PADDED_DATE, ERROR) \ FUNC(GITMODULES_MISSING, ERROR) \ FUNC(GITMODULES_BLOB, ERROR) \ FUNC(GITMODULES_PARSE, ERROR) \ FUNC(GITMODULES_NAME, ERROR) \ FUNC(GITMODULES_SYMLINK, ERROR) \ FUNC(GITMODULES_URL, ERROR) \ /* warnings */ \ FUNC(BAD_FILEMODE, WARN) \ FUNC(EMPTY_NAME, WARN) \ FUNC(FULL_PATHNAME, WARN) \ FUNC(HAS_DOT, WARN) \ FUNC(HAS_DOTDOT, WARN) \ FUNC(HAS_DOTGIT, WARN) \ FUNC(NULL_SHA1, WARN) \ FUNC(ZERO_PADDED_FILEMODE, WARN) \ /* infos (reported as warnings, but ignored by default) */ \ FUNC(BAD_TAG_NAME, INFO) \ FUNC(MISSING_TAGGER_ENTRY, INFO) #define MSG_ID(id, msg_type) FSCK_MSG_##id, enum fsck_msg_id { FOREACH_MSG_ID(MSG_ID) FSCK_MSG_MAX }; #undef MSG_ID #define STR(x) #x #define MSG_ID(id, msg_type) { STR(id), NULL, FSCK_##msg_type }, static struct { const char *id_string; const char *downcased; int msg_type; } msg_id_info[FSCK_MSG_MAX + 1] = { FOREACH_MSG_ID(MSG_ID) { NULL, NULL, -1 } }; #undef MSG_ID static int parse_msg_id(const char *text) { int i; if (!msg_id_info[0].downcased) { /* convert id_string to lower case, without underscores. */ for (i = 0; i < FSCK_MSG_MAX; i++) { const char *p = msg_id_info[i].id_string; int len = strlen(p); char *q = xmalloc(len); msg_id_info[i].downcased = q; while (*p) if (*p == '_') p++; else *(q)++ = tolower(*(p)++); *q = '\0'; } } for (i = 0; i < FSCK_MSG_MAX; i++) if (!strcmp(text, msg_id_info[i].downcased)) return i; return -1; } static int fsck_msg_type(enum fsck_msg_id msg_id, struct fsck_options *options) { int msg_type; assert(msg_id >= 0 && msg_id < FSCK_MSG_MAX); if (options->msg_type) msg_type = options->msg_type[msg_id]; else { msg_type = msg_id_info[msg_id].msg_type; if (options->strict && msg_type == FSCK_WARN) msg_type = FSCK_ERROR; } return msg_type; } static void init_skiplist(struct fsck_options *options, const char *path) { static struct sha1_array skiplist = SHA1_ARRAY_INIT; int sorted, fd; char buffer[41]; unsigned char sha1[20]; if (options->skiplist) sorted = options->skiplist->sorted; else { sorted = 1; options->skiplist = &skiplist; } fd = open(path, O_RDONLY); if (fd < 0) die("Could not open skip list: %s", path); for (;;) { int result = read_in_full(fd, buffer, sizeof(buffer)); if (result < 0) die_errno("Could not read '%s'", path); if (!result) break; if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') die("Invalid SHA-1: %s", buffer); sha1_array_append(&skiplist, sha1); if (sorted && skiplist.nr > 1 && hashcmp(skiplist.sha1[skiplist.nr - 2], sha1) > 0) sorted = 0; } close(fd); if (sorted) skiplist.sorted = 1; } static int parse_msg_type(const char *str) { if (!strcmp(str, "error")) return FSCK_ERROR; else if (!strcmp(str, "warn")) return FSCK_WARN; else if (!strcmp(str, "ignore")) return FSCK_IGNORE; else die("Unknown fsck message type: '%s'", str); } int is_valid_msg_type(const char *msg_id, const char *msg_type) { if (parse_msg_id(msg_id) < 0) return 0; parse_msg_type(msg_type); return 1; } void fsck_set_msg_type(struct fsck_options *options, const char *msg_id, const char *msg_type) { int id = parse_msg_id(msg_id), type; if (id < 0) die("Unhandled message id: %s", msg_id); type = parse_msg_type(msg_type); if (type != FSCK_ERROR && msg_id_info[id].msg_type == FSCK_FATAL) die("Cannot demote %s to %s", msg_id, msg_type); if (!options->msg_type) { int i; int *msg_type; ALLOC_ARRAY(msg_type, FSCK_MSG_MAX); for (i = 0; i < FSCK_MSG_MAX; i++) msg_type[i] = fsck_msg_type(i, options); options->msg_type = msg_type; } options->msg_type[id] = type; } void fsck_set_msg_types(struct fsck_options *options, const char *values) { char *buf = xstrdup(values), *to_free = buf; int done = 0; while (!done) { int len = strcspn(buf, " ,|"), equal; done = !buf[len]; if (!len) { buf++; continue; } buf[len] = '\0'; for (equal = 0; equal < len && buf[equal] != '=' && buf[equal] != ':'; equal++) buf[equal] = tolower(buf[equal]); buf[equal] = '\0'; if (!strcmp(buf, "skiplist")) { if (equal == len) die("skiplist requires a path"); init_skiplist(options, buf + equal + 1); buf += len + 1; continue; } if (equal == len) die("Missing '=': '%s'", buf); fsck_set_msg_type(options, buf, buf + equal + 1); buf += len + 1; } free(to_free); } static void append_msg_id(struct strbuf *sb, const char *msg_id) { for (;;) { char c = *(msg_id)++; if (!c) break; if (c != '_') strbuf_addch(sb, tolower(c)); else { assert(*msg_id); strbuf_addch(sb, *(msg_id)++); } } strbuf_addstr(sb, ": "); } __attribute__((format (printf, 4, 5))) static int report(struct fsck_options *options, struct object *object, enum fsck_msg_id id, const char *fmt, ...) { va_list ap; struct strbuf sb = STRBUF_INIT; int msg_type = fsck_msg_type(id, options), result; if (msg_type == FSCK_IGNORE) return 0; if (options->skiplist && object && sha1_array_lookup(options->skiplist, object->oid.hash) >= 0) return 0; if (msg_type == FSCK_FATAL) msg_type = FSCK_ERROR; else if (msg_type == FSCK_INFO) msg_type = FSCK_WARN; append_msg_id(&sb, msg_id_info[id].id_string); va_start(ap, fmt); strbuf_vaddf(&sb, fmt, ap); result = options->error_func(object, msg_type, sb.buf); strbuf_release(&sb); va_end(ap); return result; } static int fsck_walk_tree(struct tree *tree, void *data, struct fsck_options *options) { struct tree_desc desc; struct name_entry entry; int res = 0; if (parse_tree(tree)) return -1; init_tree_desc(&desc, tree->buffer, tree->size); while (tree_entry(&desc, &entry)) { int result; if (S_ISGITLINK(entry.mode)) continue; if (S_ISDIR(entry.mode)) result = options->walk(&lookup_tree(entry.sha1)->object, OBJ_TREE, data, options); else if (S_ISREG(entry.mode) || S_ISLNK(entry.mode)) result = options->walk(&lookup_blob(entry.sha1)->object, OBJ_BLOB, data, options); else { result = error("in tree %s: entry %s has bad mode %.6o", oid_to_hex(&tree->object.oid), entry.path, entry.mode); } if (result < 0) return result; if (!res) res = result; } return res; } static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_options *options) { struct commit_list *parents; int res; int result; if (parse_commit(commit)) return -1; result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options); if (result < 0) return result; res = result; parents = commit->parents; while (parents) { result = options->walk((struct object *)parents->item, OBJ_COMMIT, data, options); if (result < 0) return result; if (!res) res = result; parents = parents->next; } return res; } static int fsck_walk_tag(struct tag *tag, void *data, struct fsck_options *options) { if (parse_tag(tag)) return -1; return options->walk(tag->tagged, OBJ_ANY, data, options); } int fsck_walk(struct object *obj, void *data, struct fsck_options *options) { if (!obj) return -1; switch (obj->type) { case OBJ_BLOB: return 0; case OBJ_TREE: return fsck_walk_tree((struct tree *)obj, data, options); case OBJ_COMMIT: return fsck_walk_commit((struct commit *)obj, data, options); case OBJ_TAG: return fsck_walk_tag((struct tag *)obj, data, options); default: error("Unknown object type for %s", oid_to_hex(&obj->oid)); return -1; } } /* * The entries in a tree are ordered in the _path_ order, * which means that a directory entry is ordered by adding * a slash to the end of it. * * So a directory called "a" is ordered _after_ a file * called "a.c", because "a/" sorts after "a.c". */ #define TREE_UNORDERED (-1) #define TREE_HAS_DUPS (-2) static int verify_ordered(unsigned mode1, const char *name1, unsigned mode2, const char *name2) { int len1 = strlen(name1); int len2 = strlen(name2); int len = len1 < len2 ? len1 : len2; unsigned char c1, c2; int cmp; cmp = memcmp(name1, name2, len); if (cmp < 0) return 0; if (cmp > 0) return TREE_UNORDERED; /* * Ok, the first <len> characters are the same. * Now we need to order the next one, but turn * a '\0' into a '/' for a directory entry. */ c1 = name1[len]; c2 = name2[len]; if (!c1 && !c2) /* * git-write-tree used to write out a nonsense tree that has * entries with the same name, one blob and one tree. Make * sure we do not have duplicate entries. */ return TREE_HAS_DUPS; if (!c1 && S_ISDIR(mode1)) c1 = '/'; if (!c2 && S_ISDIR(mode2)) c2 = '/'; return c1 < c2 ? 0 : TREE_UNORDERED; } static int fsck_tree(struct tree *item, struct fsck_options *options) { int retval = 0; int has_null_sha1 = 0; int has_full_path = 0; int has_empty_name = 0; int has_dot = 0; int has_dotdot = 0; int has_dotgit = 0; int has_zero_pad = 0; int has_bad_modes = 0; int has_dup_entries = 0; int not_properly_sorted = 0; struct tree_desc desc; unsigned o_mode; const char *o_name; init_tree_desc(&desc, item->buffer, item->size); o_mode = 0; o_name = NULL; while (desc.size) { unsigned mode; const char *name; const unsigned char *sha1; sha1 = tree_entry_extract(&desc, &name, &mode); has_null_sha1 |= is_null_sha1(sha1); has_full_path |= !!strchr(name, '/'); has_empty_name |= !*name; has_dot |= !strcmp(name, "."); has_dotdot |= !strcmp(name, ".."); has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name); has_zero_pad |= *(char *)desc.buffer == '0'; if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) { if (!S_ISLNK(mode)) oidhash_insert(&gitmodules_found, sha1); else retval += report(options, &item->object, FSCK_MSG_GITMODULES_SYMLINK, ".gitmodules is a symbolic link"); } update_tree_entry(&desc); switch (mode) { /* * Standard modes.. */ case S_IFREG | 0755: case S_IFREG | 0644: case S_IFLNK: case S_IFDIR: case S_IFGITLINK: break; /* * This is nonstandard, but we had a few of these * early on when we honored the full set of mode * bits.. */ case S_IFREG | 0664: if (!options->strict) break; default: has_bad_modes = 1; } if (o_name) { switch (verify_ordered(o_mode, o_name, mode, name)) { case TREE_UNORDERED: not_properly_sorted = 1; break; case TREE_HAS_DUPS: has_dup_entries = 1; break; default: break; } } o_mode = mode; o_name = name; } if (has_null_sha1) retval += report(options, &item->object, FSCK_MSG_NULL_SHA1, "contains entries pointing to null sha1"); if (has_full_path) retval += report(options, &item->object, FSCK_MSG_FULL_PATHNAME, "contains full pathnames"); if (has_empty_name) retval += report(options, &item->object, FSCK_MSG_EMPTY_NAME, "contains empty pathname"); if (has_dot) retval += report(options, &item->object, FSCK_MSG_HAS_DOT, "contains '.'"); if (has_dotdot) retval += report(options, &item->object, FSCK_MSG_HAS_DOTDOT, "contains '..'"); if (has_dotgit) retval += report(options, &item->object, FSCK_MSG_HAS_DOTGIT, "contains '.git'"); if (has_zero_pad) retval += report(options, &item->object, FSCK_MSG_ZERO_PADDED_FILEMODE, "contains zero-padded file modes"); if (has_bad_modes) retval += report(options, &item->object, FSCK_MSG_BAD_FILEMODE, "contains bad file modes"); if (has_dup_entries) retval += report(options, &item->object, FSCK_MSG_DUPLICATE_ENTRIES, "contains duplicate file entries"); if (not_properly_sorted) retval += report(options, &item->object, FSCK_MSG_TREE_NOT_SORTED, "not properly sorted"); return retval; } static int verify_headers(const void *data, unsigned long size, struct object *obj, struct fsck_options *options) { const char *buffer = (const char *)data; unsigned long i; for (i = 0; i < size; i++) { switch (buffer[i]) { case '\0': return report(options, obj, FSCK_MSG_NUL_IN_HEADER, "unterminated header: NUL at offset %ld", i); case '\n': if (i + 1 < size && buffer[i + 1] == '\n') return 0; } } /* * We did not find double-LF that separates the header * and the body. Not having a body is not a crime but * we do want to see the terminating LF for the last header * line. */ if (size && buffer[size - 1] == '\n') return 0; return report(options, obj, FSCK_MSG_UNTERMINATED_HEADER, "unterminated header"); } static int fsck_ident(const char **ident, struct object *obj, struct fsck_options *options) { const char *p = *ident; char *end; *ident = strchrnul(*ident, '\n'); if (**ident == '\n') (*ident)++; if (*p == '<') return report(options, obj, FSCK_MSG_MISSING_NAME_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p += strcspn(p, "<>\n"); if (*p == '>') return report(options, obj, FSCK_MSG_BAD_NAME, "invalid author/committer line - bad name"); if (*p != '<') return report(options, obj, FSCK_MSG_MISSING_EMAIL, "invalid author/committer line - missing email"); if (p[-1] != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_EMAIL, "invalid author/committer line - missing space before email"); p++; p += strcspn(p, "<>\n"); if (*p != '>') return report(options, obj, FSCK_MSG_BAD_EMAIL, "invalid author/committer line - bad email"); p++; if (*p != ' ') return report(options, obj, FSCK_MSG_MISSING_SPACE_BEFORE_DATE, "invalid author/committer line - missing space before date"); p++; if (*p == '0' && p[1] != ' ') return report(options, obj, FSCK_MSG_ZERO_PADDED_DATE, "invalid author/committer line - zero-padded date"); if (date_overflows(strtoul(p, &end, 10))) return report(options, obj, FSCK_MSG_BAD_DATE_OVERFLOW, "invalid author/committer line - date causes integer overflow"); if ((end == p || *end != ' ')) return report(options, obj, FSCK_MSG_BAD_DATE, "invalid author/committer line - bad date"); p = end + 1; if ((*p != '+' && *p != '-') || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3]) || !isdigit(p[4]) || (p[5] != '\n')) return report(options, obj, FSCK_MSG_BAD_TIMEZONE, "invalid author/committer line - bad time zone"); p += 6; return 0; } static int fsck_commit_buffer(struct commit *commit, const char *buffer, unsigned long size, struct fsck_options *options) { unsigned char tree_sha1[20], sha1[20]; struct commit_graft *graft; unsigned parent_count, parent_line_count = 0, author_count; int err; if (verify_headers(buffer, size, &commit->object, options)) return -1; if (!skip_prefix(buffer, "tree ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line"); if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1"); if (err) return err; } buffer += 41; while (skip_prefix(buffer, "parent ", &buffer)) { if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1"); if (err) return err; } buffer += 41; parent_line_count++; } graft = lookup_commit_graft(commit->object.oid.hash); parent_count = commit_list_count(commit->parents); if (graft) { if (graft->nr_parent == -1 && !parent_count) ; /* shallow commit */ else if (graft->nr_parent != parent_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_GRAFT, "graft objects missing"); if (err) return err; } } else { if (parent_count != parent_line_count) { err = report(options, &commit->object, FSCK_MSG_MISSING_PARENT, "parent objects missing"); if (err) return err; } } author_count = 0; while (skip_prefix(buffer, "author ", &buffer)) { author_count++; err = fsck_ident(&buffer, &commit->object, options); if (err) return err; } if (author_count < 1) err = report(options, &commit->object, FSCK_MSG_MISSING_AUTHOR, "invalid format - expected 'author' line"); else if (author_count > 1) err = report(options, &commit->object, FSCK_MSG_MULTIPLE_AUTHORS, "invalid format - multiple 'author' lines"); if (err) return err; if (!skip_prefix(buffer, "committer ", &buffer)) return report(options, &commit->object, FSCK_MSG_MISSING_COMMITTER, "invalid format - expected 'committer' line"); err = fsck_ident(&buffer, &commit->object, options); if (err) return err; if (!commit->tree) return report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1)); return 0; } static int fsck_commit(struct commit *commit, const char *data, unsigned long size, struct fsck_options *options) { const char *buffer = data ? data : get_commit_buffer(commit, &size); int ret = fsck_commit_buffer(commit, buffer, size, options); if (!data) unuse_commit_buffer(commit, buffer); return ret; } static int fsck_tag_buffer(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { unsigned char sha1[20]; int ret = 0; const char *buffer; char *to_free = NULL, *eol; struct strbuf sb = STRBUF_INIT; if (data) buffer = data; else { enum object_type type; buffer = to_free = read_sha1_file(tag->object.oid.hash, &type, &size); if (!buffer) return report(options, &tag->object, FSCK_MSG_MISSING_TAG_OBJECT, "cannot read tag object"); if (type != OBJ_TAG) { ret = report(options, &tag->object, FSCK_MSG_TAG_OBJECT_NOT_TAG, "expected tag got %s", typename(type)); goto done; } } ret = verify_headers(buffer, size, &tag->object, options); if (ret) goto done; if (!skip_prefix(buffer, "object ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line"); goto done; } if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') { ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1"); if (ret) goto done; } buffer += 41; if (!skip_prefix(buffer, "type ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE, "invalid format - unexpected end after 'type' line"); goto done; } if (type_from_string_gently(buffer, eol - buffer, 1) < 0) ret = report(options, &tag->object, FSCK_MSG_BAD_TYPE, "invalid 'type' value"); if (ret) goto done; buffer = eol + 1; if (!skip_prefix(buffer, "tag ", &buffer)) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG_ENTRY, "invalid format - expected 'tag' line"); goto done; } eol = strchr(buffer, '\n'); if (!eol) { ret = report(options, &tag->object, FSCK_MSG_MISSING_TAG, "invalid format - unexpected end after 'type' line"); goto done; } strbuf_addf(&sb, "refs/tags/%.*s", (int)(eol - buffer), buffer); if (check_refname_format(sb.buf, 0)) { ret = report(options, &tag->object, FSCK_MSG_BAD_TAG_NAME, "invalid 'tag' name: %.*s", (int)(eol - buffer), buffer); if (ret) goto done; } buffer = eol + 1; if (!skip_prefix(buffer, "tagger ", &buffer)) { /* early tags do not contain 'tagger' lines; warn only */ ret = report(options, &tag->object, FSCK_MSG_MISSING_TAGGER_ENTRY, "invalid format - expected 'tagger' line"); if (ret) goto done; } else ret = fsck_ident(&buffer, &tag->object, options); done: strbuf_release(&sb); free(to_free); return ret; } static int fsck_tag(struct tag *tag, const char *data, unsigned long size, struct fsck_options *options) { struct object *tagged = tag->tagged; if (!tagged) return report(options, &tag->object, FSCK_MSG_BAD_TAG_OBJECT, "could not load tagged object"); return fsck_tag_buffer(tag, data, size, options); } struct fsck_gitmodules_data { struct object *obj; struct fsck_options *options; int ret; }; static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata) { struct fsck_gitmodules_data *data = vdata; const char *subsection, *key; int subsection_len; char *name; if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 || !subsection) return 0; name = xmemdupz(subsection, subsection_len); if (check_submodule_name(name) < 0) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_NAME, "disallowed submodule name: %s", name); if (!strcmp(key, "url") && value && looks_like_command_line_option(value)) data->ret |= report(data->options, data->obj, FSCK_MSG_GITMODULES_URL, "disallowed submodule url: %s", value); free(name); return 0; } static int fsck_blob(struct blob *blob, const char *buf, unsigned long size, struct fsck_options *options) { struct fsck_gitmodules_data data; if (!oidhash_contains(&gitmodules_found, blob->object.oid.hash)) return 0; oidhash_insert(&gitmodules_done, blob->object.oid.hash); if (!buf) { /* * A missing buffer here is a sign that the caller found the * blob too gigantic to load into memory. Let's just consider * that an error. */ return report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, ".gitmodules too large to parse"); } data.obj = &blob->object; data.options = options; data.ret = 0; if (git_config_from_buf(fsck_gitmodules_fn, ".gitmodules", buf, size, &data)) data.ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_PARSE, "could not parse gitmodules blob"); return data.ret; } int fsck_object(struct object *obj, void *data, unsigned long size, struct fsck_options *options) { if (!obj) return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck"); if (obj->type == OBJ_BLOB) return fsck_blob((struct blob *)obj, data, size, options); if (obj->type == OBJ_TREE) return fsck_tree((struct tree *) obj, options); if (obj->type == OBJ_COMMIT) return fsck_commit((struct commit *) obj, (const char *) data, size, options); if (obj->type == OBJ_TAG) return fsck_tag((struct tag *) obj, (const char *) data, size, options); return report(options, obj, FSCK_MSG_UNKNOWN_TYPE, "unknown type '%d' (internal fsck error)", obj->type); } int fsck_error_function(struct object *obj, int msg_type, const char *message) { if (msg_type == FSCK_WARN) { warning("object %s: %s", oid_to_hex(&obj->oid), message); return 0; } error("object %s: %s", oid_to_hex(&obj->oid), message); return 1; } int fsck_finish(struct fsck_options *options) { int ret = 0; struct hashmap_iter iter; const struct oidhash_entry *e; hashmap_iter_init(&gitmodules_found, &iter); while ((e = hashmap_iter_next(&iter))) { const unsigned char *sha1 = e->sha1; struct blob *blob; enum object_type type; unsigned long size; char *buf; if (oidhash_contains(&gitmodules_done, sha1)) continue; blob = lookup_blob(sha1); if (!blob) { ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); continue; } buf = read_sha1_file(sha1, &type, &size); if (!buf) { ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_MISSING, "unable to read .gitmodules blob"); continue; } if (type == OBJ_BLOB) ret |= fsck_blob(blob, buf, size, options); else ret |= report(options, &blob->object, FSCK_MSG_GITMODULES_BLOB, "non-blob found at .gitmodules"); free(buf); } hashmap_free(&gitmodules_found, 1); hashmap_free(&gitmodules_done, 1); return ret; }
58649.c
#include <common.h> const TSpriteInterlaced weapon_slash_large_0_0 = { {0x1F,0x7B,0xFF,0xFF,0xFF,0xFF,0x3F,0x3F,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00, 0xF8,0xBE,0xFF,0xBB,0xBF,0xFF,0xE7,0xF6,0xFE,0xFC,0xDC,0x00,0x00,0x00,0x00,0x00,}, {0x00,0x01,0x26,0x10,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x80,0x10,0xFC,0x9A,0xBE,0xEE,0xE4,0x44,0x28,0x08,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x07,0x1A,0x7F,0x98,0x22,0x0F,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0xE0,0xB8,0xC6,0xBB,0x2C,0xDA,0xA0,0xF4,0x20,0x88,0x00,0x00,0x00,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_0_1 = { {0x7F,0x7F,0x3F,0x3F,0x3F,0x3F,0x07,0x03,0x07,0x07,0x07,0x00,0x00,0x00,0x00,0x00, 0xF0,0xFC,0xFE,0xEE,0xDF,0x9F,0xF9,0xFF,0xFF,0xFF,0xFC,0x70,0x70,0x00,0x00,0x00,}, {0x0E,0x04,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0xC0,0x20,0x5C,0x8C,0xF8,0xEE,0x8E,0x08,0x20,0x00,0x00,0x00,0x00,0x00,}, {0x2D,0x06,0x12,0x00,0x17,0x03,0x00,0x01,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00, 0xC0,0x60,0xB8,0x2C,0x44,0x9A,0xE9,0x1F,0xC8,0x60,0x00,0x20,0x00,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_0_2 = { {0x01,0x03,0x07,0x07,0x07,0x03,0x01,0x03,0x0F,0x0E,0x0F,0x03,0x01,0x01,0x00,0x00, 0xF0,0xFC,0xFE,0xFE,0xFF,0xFB,0xEB,0xCF,0xFF,0xFF,0xFB,0xFF,0xFF,0xFF,0x00,0x00,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00, 0x40,0x00,0x00,0x30,0x0C,0x18,0x68,0xCE,0xFE,0x5E,0x58,0x1C,0xA0,0x00,0x00,0x00,}, {0x00,0x01,0x00,0x03,0x01,0x00,0x00,0x00,0x01,0x06,0x01,0x00,0x00,0x00,0x00,0x00, 0x40,0x60,0x28,0x3C,0x94,0x9A,0x4A,0xCB,0x39,0xEF,0xDA,0x0E,0xAA,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_0_3 = { {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x03,0x07,0x07,0x07,0x01,0x00, 0x1C,0x3E,0xFE,0xFF,0xFF,0xFD,0xFF,0xFF,0xFF,0xE5,0xFF,0xBF,0x3F,0xF7,0xFE,0x7C,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x03,0x00,0x00,0x00, 0x00,0x00,0x04,0x08,0x00,0x04,0x14,0x22,0x7D,0xE4,0x74,0x1E,0x3C,0xF4,0x38,0x00,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x01,0x00,0x02,0x00,0x00,0x00, 0x08,0x04,0x14,0x4E,0x2E,0x25,0x77,0x25,0xEF,0xA5,0xDB,0xAA,0x3A,0x94,0x2C,0x08,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_1_0 = { {0x0F,0x3F,0x79,0x7F,0xFC,0xFE,0xFF,0xFF,0xFF,0x7D,0x38,0x00,0x00,0x00,0x00,0x00, 0xFC,0xFC,0xDC,0xFC,0xFC,0xFC,0xFC,0xFC,0xBC,0xF0,0xE0,0xE0,0x00,0x00,0x00,0x00,}, {0x00,0x01,0x09,0x0F,0x14,0x12,0x83,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xC0,0xD0,0xF0,0xF0,0x88,0xE0,0x88,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x01,0x07,0x18,0x37,0x1C,0x70,0xC3,0x0D,0x58,0x10,0x00,0x00,0x00,0x00,0x00,0x00, 0xC0,0x78,0x50,0xF8,0xA0,0xC8,0x60,0x68,0xA0,0x40,0x40,0x00,0x00,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_1_3 = { {0x00,0x00,0x00,0x00,0x00,0x07,0x07,0x07,0x07,0x1F,0x1F,0x1F,0x07,0x07,0x03,0x03, 0x01,0x03,0x3F,0x3F,0x3F,0x7F,0xFF,0xFF,0xFF,0xDF,0xCF,0xF7,0xFE,0xBE,0xBC,0xF0,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x03,0x01,0x01,0x00, 0x00,0x00,0x00,0x00,0x01,0x03,0x01,0x30,0xE4,0xD4,0xC8,0x50,0xF0,0xB0,0x80,0x00,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x01,0x03,0x0A,0x00,0x01,0x00,0x00,0x00, 0x00,0x00,0x01,0x14,0x01,0x13,0x36,0xB1,0x65,0x53,0x4E,0xA4,0xEC,0x98,0xA0,0xC0,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_2_0 = { {0x0F,0x3D,0x7D,0x7F,0xEF,0xF3,0xFB,0xFF,0xFF,0xFF,0xFE,0xFC,0xFC,0xFC,0xC0,0x80, 0xC0,0xC0,0xE0,0xE0,0xF8,0xF8,0xF8,0xE0,0xE0,0xE0,0xE0,0x00,0x00,0x00,0x00,0x00,}, {0x00,0x01,0x0D,0x0F,0x0A,0x13,0x2B,0x27,0x0C,0x80,0xC0,0x80,0x00,0x00,0x00,0x00, 0x00,0x80,0x80,0xC0,0x00,0x20,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x03,0x05,0x19,0x37,0x25,0x72,0xCA,0xA6,0x8D,0x6C,0xC8,0x80,0x28,0x80,0x00,0x00, 0x00,0x00,0x00,0x80,0x00,0x50,0xC0,0x80,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_2_3 = { {0x00,0x00,0x00,0x00,0x07,0x07,0x0F,0x3D,0x3F,0x3F,0x3F,0x3F,0x3F,0x3B,0x3F,0x3F, 0x00,0x00,0x00,0x00,0x00,0x1C,0xBE,0xFF,0xFF,0xFF,0x7F,0x3F,0xFF,0x9E,0xFC,0xF0,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x11,0x07,0x11,0x0F,0x0F,0x0B,0x03,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0xC1,0x48,0x28,0xF0,0x90,0x80,0x00,}, {0x00,0x00,0x00,0x00,0x00,0x02,0x02,0x05,0x16,0x06,0x13,0x05,0x1F,0x0A,0x1E,0x03, 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x1A,0xB0,0xC3,0x0E,0x38,0xEC,0x18,0xE0,0x80,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_3_0 = { {0x3E,0x7F,0x6F,0xFC,0xFD,0xFF,0xA7,0xFF,0xFF,0xFF,0xBF,0xFF,0xFF,0x7F,0x7C,0x38, 0x00,0x80,0xE0,0xE0,0xE0,0xC0,0xE0,0xE0,0xE0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x00,0x1C,0x2F,0x3C,0x78,0x2E,0x27,0xBE,0x44,0x28,0x20,0x00,0x10,0x20,0x00,0x00, 0x00,0x00,0x00,0xC0,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x10,0x34,0x29,0x5C,0x55,0xDB,0xA5,0xF7,0xA4,0xEE,0xA4,0x74,0x72,0x28,0x20,0x10, 0x00,0x00,0x00,0x40,0x00,0x80,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_3_1 = { {0x00,0x00,0xFF,0xFF,0xFF,0xDF,0xFF,0xFF,0xF3,0xD7,0xDF,0xFF,0x7F,0x7F,0x3F,0x07, 0x00,0x00,0x80,0x80,0xC0,0xF0,0x70,0xF0,0xC0,0x80,0xC0,0xE0,0xE0,0xE0,0xC0,0xC0,}, {0x00,0x00,0x00,0x05,0x38,0x1A,0x7A,0x7F,0x73,0x16,0x18,0x30,0x0C,0x00,0x00,0x02, 0x00,0x00,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,}, {0x00,0x00,0x00,0x55,0x70,0x5B,0xF7,0x9C,0xD3,0x52,0x59,0x29,0x3C,0x14,0x06,0x02, 0x00,0x00,0x00,0x00,0x00,0x80,0x60,0x80,0x00,0x00,0x00,0x80,0xC0,0x00,0x80,0x00,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_3_2 = { {0x00,0x00,0x00,0x0E,0x0E,0x3F,0xFF,0xFF,0xFF,0x9F,0xF9,0xFB,0x77,0x7F,0x3F,0x0F, 0x00,0x00,0x00,0x00,0x00,0xE0,0xE0,0xE0,0xC0,0xE0,0xFC,0xFC,0xFC,0xFC,0xFE,0xFE,}, {0x00,0x00,0x00,0x00,0x00,0x04,0x10,0x71,0x77,0x1F,0x31,0x3A,0x04,0x03,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x00,0x00,0x20,0x70,}, {0x00,0x00,0x00,0x00,0x04,0x00,0x06,0x13,0xF8,0x97,0x59,0x22,0x34,0x1D,0x06,0x03, 0x00,0x00,0x00,0x00,0x00,0x00,0x40,0x00,0x80,0x00,0xC0,0xE8,0x00,0x48,0x60,0xB4,}, 9, 14}; const TSpriteInterlaced weapon_slash_large_3_3 = { {0x00,0x00,0x00,0x00,0x00,0x3B,0x3F,0x7F,0x6F,0xE7,0xFF,0xFD,0xDD,0xFF,0x7D,0x1F, 0x00,0x00,0x00,0x00,0x00,0x80,0x80,0x80,0xFC,0xFC,0xFE,0xFF,0xFF,0xFF,0xDE,0xF8,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x14,0x22,0x27,0x77,0x7D,0x59,0x3F,0x08,0x01, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x80,0x40,0x08,0x64,0x80,0x00,}, {0x00,0x00,0x00,0x00,0x00,0x00,0x11,0x04,0x2F,0x05,0x5B,0x34,0xDD,0x63,0x1D,0x07, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0xF0,0x44,0x19,0xFE,0x58,0xE0,}, 9, 14};
994572.c
/* Copyright (c) 2008, 2009 The Board of Trustees of The Leland Stanford * Junior University * * We are making the OpenFlow specification and associated documentation * (Software) available for public use and benefit with the expectation * that others will use, modify and enhance the Software and contribute * those enhancements back to the community. However, since we would * like to make the Software available for broadest use, with as few * restrictions as possible permission is hereby granted, free of * charge, to any person obtaining a copy of this Software to deal in * the Software under the copyrights 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. * * The name and trademarks of copyright holder(s) may NOT be used in * advertising or publicity pertaining to the Software or any * derivatives without specific, written prior permission. */ #include <config.h> #include "vconn-provider.h" #include <assert.h> #include <errno.h> #include <inttypes.h> #include <netinet/in.h> #include <poll.h> #include <stdlib.h> #include <string.h> #include "dynamic-string.h" #include "ofp.h" #include "ofpbuf.h" #include "openflow/openflow.h" #include "poll-loop.h" #include "random.h" #include "util.h" #include "oflib/ofl.h" #include "oflib/ofl-messages.h" #include "oflib-exp/ofl-exp.h" #define LOG_MODULE VLM_vconn #include "vlog.h" /* State of an active vconn.*/ enum vconn_state { /* This is the ordinary progression of states. */ VCS_CONNECTING, /* Underlying vconn is not connected. */ VCS_SEND_HELLO, /* Waiting to send OFPT_HELLO message. */ VCS_RECV_HELLO, /* Waiting to receive OFPT_HELLO message. */ VCS_CONNECTED, /* Connection established. */ /* These states are entered only when something goes wrong. */ VCS_SEND_ERROR, /* Sending OFPT_ERROR message. */ VCS_DISCONNECTED /* Connection failed or connection closed. */ }; static struct ofl_exp_msg ofl_exp_msg = {.pack = ofl_exp_msg_pack, .unpack = ofl_exp_msg_unpack, .free = ofl_exp_msg_free, .to_string = ofl_exp_msg_to_string}; static struct ofl_exp_act ofl_exp_act = {.pack = OFDPA_ofl_exp_action_pack, .unpack = OFDPA_ofl_exp_action_unpack, .free = OFDPA_ofl_exp_action_free, .ofp_len = OFDPA_ofl_exp_action_ofp_len, .to_string = OFDPA_ofl_exp_action_to_string}; static struct ofl_exp ofl_exp = {.act = &ofl_exp_act, .inst = NULL, .match = NULL, .stats = NULL, .msg = &ofl_exp_msg}; static struct vconn_class *vconn_classes[] = { &tcp_vconn_class, &unix_vconn_class, #ifdef HAVE_NETLINK &netlink_vconn_class, #endif #ifdef HAVE_OPENSSL &ssl_vconn_class, #endif }; static struct pvconn_class *pvconn_classes[] = { &ptcp_pvconn_class, &punix_pvconn_class, #ifdef HAVE_OPENSSL &pssl_pvconn_class, #endif }; /* High rate limit because most of the rate-limiting here is individual * OpenFlow messages going over the vconn. If those are enabled then we * really need to see them. */ static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(600, 600); static int do_recv(struct vconn *, struct ofpbuf **); static int do_send(struct vconn *, struct ofpbuf *); /* Check the validity of the vconn class structures. */ static void check_vconn_classes(void) { #ifndef NDEBUG size_t i; for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) { struct vconn_class *class = vconn_classes[i]; assert(class->name != NULL); assert(class->open != NULL); if (class->close || class->recv || class->send || class->wait) { assert(class->close != NULL); assert(class->recv != NULL); assert(class->send != NULL); assert(class->wait != NULL); } else { /* This class delegates to another one. */ } } for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) { struct pvconn_class *class = pvconn_classes[i]; assert(class->name != NULL); assert(class->listen != NULL); if (class->close || class->accept || class->wait) { assert(class->close != NULL); assert(class->accept != NULL); assert(class->wait != NULL); } else { /* This class delegates to another one. */ } } #endif } /* Prints information on active (if 'active') and passive (if 'passive') * connection methods supported by the vconn. If 'bootstrap' is true, also * advertises options to bootstrap the CA certificate. */ void vconn_usage(bool active, bool passive, bool bootstrap UNUSED) { /* Really this should be implemented via callbacks into the vconn * providers, but that seems too heavy-weight to bother with at the * moment. */ printf("\n"); if (active) { printf("Active OpenFlow connection methods:\n"); printf(" tcp:HOST[:PORT] " "PORT (default: %d) on remote TCP HOST\n", OFP_TCP_PORT); #ifdef HAVE_OPENSSL printf(" ssl:HOST[:PORT] " "SSL PORT (default: %d) on remote HOST\n", OFP_SSL_PORT); #endif printf(" unix:FILE Unix domain socket named FILE\n"); printf(" fd:N File descriptor N\n"); } if (passive) { printf("Passive OpenFlow connection methods:\n"); printf(" ptcp:[PORT] " "listen to TCP PORT (default: %d)\n", OFP_TCP_PORT); #ifdef HAVE_OPENSSL printf(" pssl:[PORT] " "listen for SSL on PORT (default: %d)\n", OFP_SSL_PORT); #endif printf(" punix:FILE " "listen on Unix domain socket FILE\n"); } #ifdef HAVE_OPENSSL printf("PKI configuration (required to use SSL):\n" " -p, --private-key=FILE file with private key\n" " -c, --certificate=FILE file with certificate for private key\n" " -C, --ca-cert=FILE file with peer CA certificate\n"); if (bootstrap) { printf(" --bootstrap-ca-cert=FILE file with peer CA certificate " "to read or create\n"); } #endif } /* Attempts to connect to an OpenFlow device. 'name' is a connection name in * the form "TYPE:ARGS", where TYPE is an active vconn class's name and ARGS * are vconn class-specific. * * The vconn will automatically negotiate an OpenFlow protocol version * acceptable to both peers on the connection. The version negotiated will be * no lower than 'min_version' and no higher than OFP_VERSION. * * Returns 0 if successful, otherwise a positive errno value. If successful, * stores a pointer to the new connection in '*vconnp', otherwise a null * pointer. */ int vconn_open(const char *name, int min_version, struct vconn **vconnp) { size_t prefix_len; size_t i; check_vconn_classes(); *vconnp = NULL; prefix_len = strcspn(name, ":"); if (prefix_len == strlen(name)) { return EAFNOSUPPORT; } for (i = 0; i < ARRAY_SIZE(vconn_classes); i++) { struct vconn_class *class = vconn_classes[i]; if (strlen(class->name) == prefix_len && !memcmp(class->name, name, prefix_len)) { struct vconn *vconn; char *suffix_copy = xstrdup(name + prefix_len + 1); int retval = class->open(name, suffix_copy, &vconn); free(suffix_copy); if (!retval) { assert(vconn->state != VCS_CONNECTING || vconn->class->connect); vconn->min_version = min_version; *vconnp = vconn; } return retval; } } return EAFNOSUPPORT; } int vconn_open_block(const char *name, int min_version, struct vconn **vconnp) { struct vconn *vconn; int error; error = vconn_open(name, min_version, &vconn); while (error == EAGAIN) { vconn_connect_wait(vconn); poll_block(); error = vconn_connect(vconn,NULL,false); assert(error != EINPROGRESS); } if (error) { vconn_close(vconn); *vconnp = NULL; } else { *vconnp = vconn; } return error; } /* Closes 'vconn'. */ void vconn_close(struct vconn *vconn) { if (vconn != NULL) { char *name = vconn->name; (vconn->class->close)(vconn); free(name); } } /* Returns the name of 'vconn', that is, the string passed to vconn_open(). */ const char * vconn_get_name(const struct vconn *vconn) { return vconn->name; } /* Returns the IP address of the peer, or 0 if the peer is not connected over * an IP-based protocol or if its IP address is not yet known. */ uint32_t vconn_get_ip(const struct vconn *vconn) { return vconn->ip; } /* Returns true if, when 'vconn' is closed, it is possible to try to reconnect * to it using the name that was originally used. This is ordinarily the case. * * Returns false if reconnecting under the same name will never work in the way * that you would expect. This is the case if 'vconn' represents a "fd:N" type * vconn; one can never connect to such a vconn more than once, because closing * it closes the file descriptor. */ bool vconn_is_reconnectable(const struct vconn *vconn) { return vconn->reconnectable; } static void vcs_connecting(struct vconn *vconn) { int retval = (vconn->class->connect)(vconn); assert(retval != EINPROGRESS); if (!retval) { vconn->state = VCS_SEND_HELLO; } else if (retval != EAGAIN) { vconn->state = VCS_DISCONNECTED; vconn->error = retval; } } static void vcs_send_hello(struct vconn *vconn,struct ofl_hello_elem_versionbitmap *map,bool is_map) { struct ofpbuf *b; int retval; make_openflow(sizeof(struct ofp_header), OFPT_HELLO, &b,map,is_map); retval = do_send(vconn, b); if (!retval) { ++vconn->ofps_sent.ofps_total; ++vconn->ofps_sent.ofps_hello; vconn->state = VCS_RECV_HELLO; } else { ofpbuf_delete(b); if (retval != EAGAIN) { vconn->state = VCS_DISCONNECTED; vconn->error = retval; } } } static void vcs_recv_hello(struct vconn *vconn) { struct ofpbuf *b; int retval; retval = do_recv(vconn, &b); if (!retval) { struct ofp_header *oh = b->data; if (oh->type == OFPT_HELLO) { if (b->size > sizeof *oh) { struct ds msg = DS_EMPTY_INITIALIZER; ds_put_format(&msg, "%s: extra-long hello:\n", vconn->name); ds_put_hex_dump(&msg, b->data, b->size, 0, true); VLOG_WARN_RL(LOG_MODULE, &rl, "%s", ds_cstr(&msg)); ds_destroy(&msg); } vconn->version = MIN(OFP_VERSION, oh->version); if (vconn->version < vconn->min_version) { VLOG_WARN_RL(LOG_MODULE, &rl, "%s: version negotiation failed: we support " "versions 0x%02x to 0x%02x inclusive but peer " "supports no later than version 0x%02"PRIx8, vconn->name, vconn->min_version, OFP_VERSION, oh->version); vconn->state = VCS_SEND_ERROR; } else { VLOG_DBG(LOG_MODULE, "%s: negotiated OpenFlow version 0x%02x " "(we support versions 0x%02x to 0x%02x inclusive, " "peer no later than version 0x%02"PRIx8")", vconn->name, vconn->version, vconn->min_version, OFP_VERSION, oh->version); vconn->state = VCS_CONNECTED; } ++vconn->ofps_rcvd.ofps_total; ++vconn->ofps_rcvd.ofps_hello; ofpbuf_delete(b); return; } else { struct ofl_msg_header *msg; char *str; if (!ofl_msg_unpack(b->data, b->size, &msg, NULL/*xid*/, &ofl_exp)) { str = ofl_msg_to_string(msg, &ofl_exp); ofl_msg_free(msg, &ofl_exp); } else { struct ds string = DS_EMPTY_INITIALIZER; ds_put_cstr(&string, "\n"); ds_put_hex_dump(&string, b->data, MIN(b->size, 1024), 0, false); str = ds_cstr(&string); } VLOG_WARN_RL(LOG_MODULE, &rl, "%s: received message while expecting hello: %s", vconn->name, str); free(str); retval = EPROTO; ofpbuf_delete(b); } } if (retval != EAGAIN) { vconn->state = VCS_DISCONNECTED; vconn->error = retval; } } static void vcs_send_error(struct vconn *vconn) { struct ofp_error_msg *error; struct ofpbuf *b; char s[128]; int retval; snprintf(s, sizeof s, "We support versions 0x%02x to 0x%02x inclusive but " "you support no later than version 0x%02"PRIx8".", vconn->min_version, OFP_VERSION, vconn->version); error = make_openflow(sizeof *error, OFPT_ERROR, &b,NULL,false); error->type = htons(OFPET_HELLO_FAILED); error->code = htons(OFPHFC_INCOMPATIBLE); ofpbuf_put(b, s, strlen(s)); update_openflow_length(b); retval = do_send(vconn, b); if (retval) { ++vconn->ofps_sent.ofps_total; ++vconn->ofps_sent.ofps_error; ++vconn->ofps_sent.ofps_error_type.hello_fail; ++vconn->ofps_sent.ofps_error_code.hf_incompat; ofpbuf_delete(b); } if (retval != EAGAIN) { vconn->state = VCS_DISCONNECTED; vconn->error = retval ? retval : EPROTO; } } /* Tries to complete the connection on 'vconn', which must be an active * vconn. If 'vconn''s connection is complete, returns 0 if the connection * was successful or a positive errno value if it failed. If the * connection is still in progress, returns EAGAIN. */ int vconn_connect(struct vconn *vconn,struct ofl_hello_elem_versionbitmap *map,bool is_map) { enum vconn_state last_state; assert(vconn->min_version >= 0); do { last_state = vconn->state; switch (vconn->state) { case VCS_CONNECTING: vcs_connecting(vconn); break; case VCS_SEND_HELLO: vcs_send_hello(vconn,map,is_map); break; case VCS_RECV_HELLO: vcs_recv_hello(vconn); break; case VCS_CONNECTED: return 0; case VCS_SEND_ERROR: vcs_send_error(vconn); break; case VCS_DISCONNECTED: return vconn->error; default: NOT_REACHED(); } } while (vconn->state != last_state); return EAGAIN; } /* Tries to receive an OpenFlow message from 'vconn', which must be an active * vconn. If successful, stores the received message into '*msgp' and returns * 0. The caller is responsible for destroying the message with * ofpbuf_delete(). On failure, returns a positive errno value and stores a * null pointer into '*msgp'. On normal connection close, returns EOF. * * vconn_recv will not block waiting for a packet to arrive. If no packets * have been received, it returns EAGAIN immediately. */ int vconn_recv(struct vconn *vconn, struct ofpbuf **msgp) { int retval = vconn_connect(vconn,NULL,false); if (!retval) { retval = do_recv(vconn, msgp); } return retval; } static int do_recv(struct vconn *vconn, struct ofpbuf **msgp) { int retval; again: retval = (vconn->class->recv)(vconn, msgp); if (!retval) { struct ofp_header *oh; if (VLOG_IS_DBG_ENABLED(LOG_MODULE)) { struct ofl_msg_header *msg; char *str; if (!ofl_msg_unpack((*msgp)->data, (*msgp)->size, &msg, NULL/*xid*/, &ofl_exp)) { str = ofl_msg_to_string(msg, &ofl_exp); ofl_msg_free(msg, &ofl_exp); } else { struct ds string = DS_EMPTY_INITIALIZER; ds_put_cstr(&string, "\n"); ds_put_hex_dump(&string, (*msgp)->data, MIN((*msgp)->size, 1024), 0, false); str = ds_cstr(&string); } VLOG_DBG_RL(LOG_MODULE, &rl, "%s: received: %s", vconn->name, str); free(str); } oh = ofpbuf_at_assert(*msgp, 0, sizeof *oh); if (oh->version != vconn->version && oh->type != OFPT_HELLO && oh->type != OFPT_ERROR && oh->type != OFPT_ECHO_REQUEST && oh->type != OFPT_ECHO_REPLY && oh->type != OFPT_EXPERIMENTER) { if (vconn->version < 0) { if (oh->type == OFPT_PACKET_IN || oh->type == OFPT_FLOW_REMOVED || oh->type == OFPT_PORT_STATUS) { /* The kernel datapath is stateless and doesn't really * support version negotiation, so it can end up sending * these asynchronous message before version negotiation * is complete. Just ignore them. * * (After we move OFPT_PORT_STATUS messages from the kernel * into secchan, we won't get those here, since secchan * does proper version negotiation.) */ ofpbuf_delete(*msgp); goto again; } VLOG_ERR_RL(LOG_MODULE, &rl, "%s: received OpenFlow message type %"PRIu8" " "before version negotiation complete", vconn->name, oh->type); } else { VLOG_ERR_RL(LOG_MODULE, &rl, "%s: received OpenFlow version 0x%02"PRIx8" " "!= expected %02x", vconn->name, oh->version, vconn->version); } ofpbuf_delete(*msgp); retval = EPROTO; } } if (retval) { *msgp = NULL; } return retval; } /* Tries to queue 'msg' for transmission on 'vconn', which must be an active * vconn. If successful, returns 0, in which case ownership of 'msg' is * transferred to the vconn. Success does not guarantee that 'msg' has been or * ever will be delivered to the peer, only that it has been queued for * transmission. * * Returns a positive errno value on failure, in which case the caller * retains ownership of 'msg'. * * vconn_send will not block. If 'msg' cannot be immediately accepted for * transmission, it returns EAGAIN immediately. */ int vconn_send(struct vconn *vconn, struct ofpbuf *msg,struct ofl_hello_elem_versionbitmap *map,bool is_map) { int retval = vconn_connect(vconn,map,is_map); if (!retval) { retval = do_send(vconn, msg); } return retval; } static int do_send(struct vconn *vconn, struct ofpbuf *buf) { int retval; assert(buf->size >= sizeof(struct ofp_header)); // assert(((struct ofp_header *) buf->data)->length == htons(buf->size)); if (!VLOG_IS_DBG_ENABLED(LOG_MODULE)) { retval = (vconn->class->send)(vconn, buf); } else { struct ofl_msg_header *msg; char *str; if (!ofl_msg_unpack(buf->data, buf->size, &msg, NULL/*xid*/, &ofl_exp)) { str = ofl_msg_to_string(msg, &ofl_exp); ofl_msg_free(msg, &ofl_exp); } else { struct ds string = DS_EMPTY_INITIALIZER; ds_put_cstr(&string, "\n"); ds_put_hex_dump(&string, buf->data, MIN(buf->size, 1024), 0, false); str = ds_cstr(&string); } retval = (vconn->class->send)(vconn, buf); if (retval != EAGAIN) { VLOG_DBG_RL(LOG_MODULE, &rl, "%s: sent (%s): %s", vconn->name, strerror(retval), str); } free(str); } return retval; } /* Same as vconn_send, except that it waits until 'msg' can be transmitted. */ int vconn_send_block(struct vconn *vconn, struct ofpbuf *msg , struct ofl_hello_elem_versionbitmap *map ,bool is_map) { int retval; while ((retval = vconn_send(vconn, msg,map,is_map)) == EAGAIN) { vconn_send_wait(vconn); poll_block(); } return retval; } /* Same as vconn_recv, except that it waits until a message is received. */ int vconn_recv_block(struct vconn *vconn, struct ofpbuf **msgp) { int retval; while ((retval = vconn_recv(vconn, msgp)) == EAGAIN) { vconn_recv_wait(vconn); poll_block(); } return retval; } /* Waits until a message with a transaction ID matching 'xid' is recived on * 'vconn'. Returns 0 if successful, in which case the reply is stored in * '*replyp' for the caller to examine and free. Otherwise returns a positive * errno value, or EOF, and sets '*replyp' to null. * * 'request' is always destroyed, regardless of the return value. */ int vconn_recv_xid(struct vconn *vconn, uint32_t xid, struct ofpbuf **replyp) { for (;;) { uint32_t recv_xid; uint16_t reply_flag; uint8_t type; struct ofpbuf *reply; int error; error = vconn_recv_block(vconn, &reply); if (error) { *replyp = NULL; return error; } /* Multipart messages TODO: It's only getting the last message. Should return an array of multiparted messages*/ type = ((struct ofp_header*) reply->data)->type; if (type == OFPT_MULTIPART_REPLY || type == OFPT_MULTIPART_REQUEST){ reply_flag = ((struct ofp_multipart_reply *) reply->data)->flags; while(ntohs(reply_flag) == OFPMPF_REPLY_MORE){ error = vconn_recv_block(vconn, &reply); reply_flag = ((struct ofp_multipart_reply *) reply->data)->flags; } } recv_xid = ((struct ofp_header *) reply->data)->xid; if (xid == recv_xid) { *replyp = reply; return 0; } VLOG_DBG_RL(LOG_MODULE, &rl, "%s: received reply with xid %08"PRIx32" != expected " "%08"PRIx32, vconn->name, recv_xid, xid); ofpbuf_delete(reply); } } /* Sends 'request' to 'vconn' and blocks until it receives a reply with a * matching transaction ID. Returns 0 if successful, in which case the reply * is stored in '*replyp' for the caller to examine and free. Otherwise * returns a positive errno value, or EOF, and sets '*replyp' to null. * * 'request' is always destroyed, regardless of the return value. */ int vconn_transact(struct vconn *vconn, struct ofpbuf *request, struct ofpbuf **replyp ,struct ofl_hello_elem_versionbitmap *map,bool is_map) { uint32_t send_xid = ((struct ofp_header *) request->data)->xid; int error; *replyp = NULL; error = vconn_send_block(vconn, request ,map,is_map); if (error) { ofpbuf_delete(request); } return error ? error : vconn_recv_xid(vconn, send_xid, replyp); } void vconn_wait(struct vconn *vconn, enum vconn_wait_type wait) { assert(wait == WAIT_CONNECT || wait == WAIT_RECV || wait == WAIT_SEND); switch (vconn->state) { case VCS_CONNECTING: wait = WAIT_CONNECT; break; case VCS_SEND_HELLO: case VCS_SEND_ERROR: wait = WAIT_SEND; break; case VCS_RECV_HELLO: wait = WAIT_RECV; break; case VCS_CONNECTED: break; case VCS_DISCONNECTED: poll_immediate_wake(); return; } (vconn->class->wait)(vconn, wait); } void vconn_connect_wait(struct vconn *vconn) { vconn_wait(vconn, WAIT_CONNECT); } void vconn_recv_wait(struct vconn *vconn) { vconn_wait(vconn, WAIT_RECV); } void vconn_send_wait(struct vconn *vconn) { vconn_wait(vconn, WAIT_SEND); } /* Attempts to start listening for OpenFlow connections. 'name' is a * connection name in the form "TYPE:ARGS", where TYPE is an passive vconn * class's name and ARGS are vconn class-specific. * * Returns 0 if successful, otherwise a positive errno value. If successful, * stores a pointer to the new connection in '*pvconnp', otherwise a null * pointer. */ int pvconn_open(const char *name, struct pvconn **pvconnp) { size_t prefix_len; size_t i; check_vconn_classes(); *pvconnp = NULL; prefix_len = strcspn(name, ":"); if (prefix_len == strlen(name)) { return EAFNOSUPPORT; } for (i = 0; i < ARRAY_SIZE(pvconn_classes); i++) { struct pvconn_class *class = pvconn_classes[i]; if (strlen(class->name) == prefix_len && !memcmp(class->name, name, prefix_len)) { char *suffix_copy = xstrdup(name + prefix_len + 1); int retval = class->listen(name, suffix_copy, pvconnp); free(suffix_copy); if (retval) { *pvconnp = NULL; } return retval; } } return EAFNOSUPPORT; } /* Closes 'pvconn'. */ void pvconn_close(struct pvconn *pvconn) { if (pvconn != NULL) { char *name = pvconn->name; (pvconn->class->close)(pvconn); free(name); } } /* Tries to accept a new connection on 'pvconn'. If successful, stores the new * connection in '*new_vconn' and returns 0. Otherwise, returns a positive * errno value. * * The new vconn will automatically negotiate an OpenFlow protocol version * acceptable to both peers on the connection. The version negotiated will be * no lower than 'min_version' and no higher than OFP_VERSION. * * pvconn_accept() will not block waiting for a connection. If no connection * is ready to be accepted, it returns EAGAIN immediately. */ int pvconn_accept(struct pvconn *pvconn, int min_version, struct vconn **new_vconn) { int retval = (pvconn->class->accept)(pvconn, new_vconn); if (retval) { *new_vconn = NULL; } else { assert((*new_vconn)->state != VCS_CONNECTING || (*new_vconn)->class->connect); (*new_vconn)->min_version = min_version; } return retval; } void pvconn_wait(struct pvconn *pvconn) { (pvconn->class->wait)(pvconn); } void vconn_init(struct vconn *vconn, struct vconn_class *class, int connect_status, uint32_t ip, const char *name, bool reconnectable) { vconn->class = class; vconn->state = (connect_status == EAGAIN ? VCS_CONNECTING : !connect_status ? VCS_SEND_HELLO : VCS_DISCONNECTED); vconn->error = connect_status; vconn->version = -1; vconn->min_version = -1; vconn->ip = ip; vconn->name = xstrdup(name); vconn->reconnectable = reconnectable; memset(&vconn->ofps_rcvd, 0, sizeof(vconn->ofps_rcvd)); memset(&vconn->ofps_sent, 0, sizeof(vconn->ofps_sent)); } void pvconn_init(struct pvconn *pvconn, struct pvconn_class *class, const char *name) { pvconn->class = class; pvconn->name = xstrdup(name); }
329147.c
/* Global Descriptor Table setup * * In this file, "limit" refers to the higest address accessible, and * "base" refers to the base address, the lowest address accessible */ #include <stddef.h> #include <stdint.h> #include "gdt.h" typedef struct GDT_entry { uint16_t limit_low; // 16 LSB of the limit uint16_t base_low; // 16 LSB of the base uint8_t base_mid; // Next 8 bits of the base uint8_t access; // Access flags uint8_t gran; // Granularity uint8_t base_high; // 8 MSB of the base } __attribute__((packed)) GDT_entry; typedef struct GDT_ptr { uint16_t limit; // 16 MSB of all limits uint32_t base; // Address of the first GDT_entry } __attribute__((packed)) GDT_ptr; extern void flush_gdt(uint32_t gdt); #define NUM_GDT_ENTRIES 5 static GDT_entry gdt_entries[NUM_GDT_ENTRIES]; static GDT_ptr gdt; static void set_gdt_entry(size_t i, uint32_t base, uint32_t limit, uint8_t access, uint8_t gran) { gdt_entries[i].base_low = base & 0xFFFF; gdt_entries[i].base_mid = (base >> 16) & 0xFF; gdt_entries[i].base_high = base >> 24; gdt_entries[i].limit_low = limit & 0xFFFF; gdt_entries[i].gran = (limit >> 16) & 0xF; gdt_entries[i].gran |= gran & 0xF0; gdt_entries[i].access = access; } void init_gdt() { gdt.limit = (sizeof(GDT_entry) * NUM_GDT_ENTRIES) - 1; gdt.base = (uintptr_t)&gdt_entries; set_gdt_entry(0, 0, 0, 0, 0); // Null segment set_gdt_entry(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); // Code segment set_gdt_entry(2, 0, 0xFFFFFFFF, 0x92, 0xCF); // Data segment set_gdt_entry(3, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User mode code segment set_gdt_entry(4, 0, 0xFFFFFFFF, 0xF2, 0xCF); // User mode data segment flush_gdt((uintptr_t)&gdt); }
386905.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 Scott Shawcroft for Adafruit Industries * * 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 <stdint.h> #include <string.h> #include "extmod/vfs_fat.h" #include "py/gc.h" #include "py/mperrno.h" #include "py/runtime.h" #include "common-hal/audioio/AudioOut.h" #include "shared-bindings/audioio/AudioOut.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "supervisor/shared/translate.h" #include "atmel_start_pins.h" #include "hal/include/hal_gpio.h" #include "hpl/gclk/hpl_gclk_base.h" #include "peripheral_clk_config.h" #ifdef SAMD21 #include "hpl/pm/hpl_pm_base.h" #endif #include "audio_dma.h" #include "timer_handler.h" #include "samd/dma.h" #include "samd/events.h" #include "samd/pins.h" #include "samd/timers.h" #ifdef SAMD21 static void ramp_value(uint16_t start, uint16_t end) { start = DAC->DATA.reg; int32_t diff = (int32_t) end - start; int32_t step = 49; int32_t steps = diff / step; if (diff < 0) { steps = -steps; step = -step; } for (int32_t i = 0; i < steps; i++) { uint32_t value = start + step * i; DAC->DATA.reg = value; DAC->DATABUF.reg = value; common_hal_mcu_delay_us(50); RUN_BACKGROUND_TASKS; } } #endif #ifdef SAMD51 static void ramp_value(uint16_t start, uint16_t end) { int32_t diff = (int32_t) end - start; int32_t step = 49; int32_t steps = diff / step; if (diff < 0) { steps = -steps; step = -step; } for (int32_t i = 0; i < steps; i++) { uint16_t value = start + step * i; DAC->DATA[0].reg = value; DAC->DATABUF[0].reg = value; DAC->DATA[1].reg = value; DAC->DATABUF[1].reg = value; common_hal_mcu_delay_us(50); RUN_BACKGROUND_TASKS; } } #endif void audioout_reset(void) { #if defined(SAMD21) && !defined(PIN_PA02) return; #endif #ifdef SAMD21 while (DAC->STATUS.reg & DAC_STATUS_SYNCBUSY) {} #endif #ifdef SAMD51 while (DAC->SYNCBUSY.reg & DAC_SYNCBUSY_SWRST) {} #endif if (DAC->CTRLA.bit.ENABLE) { ramp_value(0x8000, 0); } DAC->CTRLA.reg |= DAC_CTRLA_SWRST; // TODO(tannewt): Turn off the DAC clocks to save power. } void common_hal_audioio_audioout_construct(audioio_audioout_obj_t* self, const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t quiescent_value) { #ifdef SAMD51 bool dac_clock_enabled = hri_mclk_get_APBDMASK_DAC_bit(MCLK); #endif #ifdef SAMD21 bool dac_clock_enabled = PM->APBCMASK.bit.DAC_; #endif // Only support exclusive use of the DAC. if (dac_clock_enabled && DAC->CTRLA.bit.ENABLE == 1) { mp_raise_RuntimeError(translate("DAC already in use")); } #ifdef SAMD21 if (right_channel != NULL) { mp_raise_ValueError(translate("Right channel unsupported")); } if (left_channel != &pin_PA02) { mp_raise_ValueError(translate("Invalid pin")); } assert_pin_free(left_channel); claim_pin(left_channel); #endif #ifdef SAMD51 self->right_channel = NULL; if (left_channel != &pin_PA02 && left_channel != &pin_PA05) { mp_raise_ValueError(translate("Invalid pin for left channel")); } assert_pin_free(left_channel); if (right_channel != NULL && right_channel != &pin_PA02 && right_channel != &pin_PA05) { mp_raise_ValueError(translate("Invalid pin for right channel")); } if (right_channel == left_channel) { mp_raise_ValueError(translate("Cannot output both channels on the same pin")); } claim_pin(left_channel); if (right_channel != NULL) { claim_pin(right_channel); self->right_channel = right_channel; audio_dma_init(&self->right_dma); } #endif self->left_channel = left_channel; audio_dma_init(&self->left_dma); #ifdef SAMD51 hri_mclk_set_APBDMASK_DAC_bit(MCLK); #endif #ifdef SAMD21 _pm_enable_bus_clock(PM_BUS_APBC, DAC); #endif // SAMD51: This clock should be <= 12 MHz, per datasheet section 47.6.3. // SAMD21: This clock is 48mhz despite the datasheet saying it must only be <= 350kHz, per // datasheet table 37-6. It's incorrect because the max output rate is 350ksps and is only // achieved when the GCLK is more than 8mhz. _gclk_enable_channel(DAC_GCLK_ID, CONF_GCLK_DAC_SRC); DAC->CTRLA.bit.SWRST = 1; while (DAC->CTRLA.bit.SWRST == 1) {} // Make sure there are no outstanding access errors. (Reading DATA can cause this.) #ifdef SAMD51 PAC->INTFLAGD.reg = PAC_INTFLAGD_DAC; #endif bool channel0_enabled = true; #ifdef SAMD51 channel0_enabled = self->left_channel == &pin_PA02 || self->right_channel == &pin_PA02; bool channel1_enabled = self->left_channel == &pin_PA05 || self->right_channel == &pin_PA05; #endif if (channel0_enabled) { #ifdef SAMD21 DAC->EVCTRL.reg |= DAC_EVCTRL_STARTEI; // We disable the voltage pump because we always run at 3.3v. DAC->CTRLB.reg = DAC_CTRLB_REFSEL_AVCC | DAC_CTRLB_LEFTADJ | DAC_CTRLB_EOEN | DAC_CTRLB_VPD; #endif #ifdef SAMD51 DAC->EVCTRL.reg |= DAC_EVCTRL_STARTEI0; DAC->DACCTRL[0].reg = DAC_DACCTRL_CCTRL_CC1M | DAC_DACCTRL_ENABLE | DAC_DACCTRL_LEFTADJ; DAC->CTRLB.reg = DAC_CTRLB_REFSEL_VREFPU; #endif } #ifdef SAMD51 if (channel1_enabled) { DAC->EVCTRL.reg |= DAC_EVCTRL_STARTEI1; DAC->DACCTRL[1].reg = DAC_DACCTRL_CCTRL_CC1M | DAC_DACCTRL_ENABLE | DAC_DACCTRL_LEFTADJ; DAC->CTRLB.reg = DAC_CTRLB_REFSEL_VREFPU; } #endif // Re-enable the DAC DAC->CTRLA.bit.ENABLE = 1; #ifdef SAMD21 while (DAC->STATUS.bit.SYNCBUSY == 1) {} #endif #ifdef SAMD51 while (DAC->SYNCBUSY.bit.ENABLE == 1) {} while (channel0_enabled && DAC->STATUS.bit.READY0 == 0) {} while (channel1_enabled && DAC->STATUS.bit.READY1 == 0) {} #endif // Use a timer to coordinate when DAC conversions occur. Tc *t = NULL; uint8_t tc_index = TC_INST_NUM; for (uint8_t i = TC_INST_NUM; i > 0; i--) { if (tc_insts[i - 1]->COUNT16.CTRLA.bit.ENABLE == 0) { t = tc_insts[i - 1]; tc_index = i - 1; break; } } if (t == NULL) { common_hal_audioio_audioout_deinit(self); mp_raise_RuntimeError(translate("All timers in use")); return; } self->tc_index = tc_index; // Use the 48mhz clocks on both the SAMD21 and 51 because we will be going much slower. uint8_t tc_gclk = 0; #ifdef SAMD51 tc_gclk = 1; #endif set_timer_handler(true, tc_index, TC_HANDLER_NO_INTERRUPT); turn_on_clocks(true, tc_index, tc_gclk); // Don't bother setting the period. We set it before you playback anything. tc_set_enable(t, false); tc_reset(t); #ifdef SAMD51 t->COUNT16.WAVE.reg = TC_WAVE_WAVEGEN_MFRQ; #endif #ifdef SAMD21 t->COUNT16.CTRLA.bit.WAVEGEN = TC_CTRLA_WAVEGEN_MFRQ_Val; #endif t->COUNT16.EVCTRL.reg = TC_EVCTRL_OVFEO; tc_set_enable(t, true); t->COUNT16.CTRLBSET.reg = TC_CTRLBSET_CMD_STOP; // Connect the timer overflow event, which happens at the target frequency, // to the DAC conversion trigger(s). #ifdef SAMD21 #define FIRST_TC_GEN_ID EVSYS_ID_GEN_TC3_OVF #endif #ifdef SAMD51 #define FIRST_TC_GEN_ID EVSYS_ID_GEN_TC0_OVF #endif uint8_t tc_gen_id = FIRST_TC_GEN_ID + 3 * tc_index; turn_on_event_system(); // Find a free event channel. We start at the highest channels because we only need and async // path. uint8_t channel = find_async_event_channel(); if (channel >= EVSYS_CHANNELS) { mp_raise_RuntimeError(translate("All event channels in use")); } #ifdef SAMD51 connect_event_user_to_channel(EVSYS_ID_USER_DAC_START_1, channel); if (right_channel != NULL) { gpio_set_pin_function(self->right_channel->number, GPIO_PIN_FUNCTION_B); } #define EVSYS_ID_USER_DAC_START EVSYS_ID_USER_DAC_START_0 #endif connect_event_user_to_channel(EVSYS_ID_USER_DAC_START, channel); gpio_set_pin_function(self->left_channel->number, GPIO_PIN_FUNCTION_B); init_async_event_channel(channel, tc_gen_id); self->tc_to_dac_event_channel = channel; // Ramp the DAC up. self->quiescent_value = quiescent_value; ramp_value(0, quiescent_value); // Leave the DMA setup to playback. } bool common_hal_audioio_audioout_deinited(audioio_audioout_obj_t* self) { return self->left_channel == mp_const_none; } void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t* self) { if (common_hal_audioio_audioout_deinited(self)) { return; } if (common_hal_audioio_audioout_get_playing(self)) { common_hal_audioio_audioout_stop(self); } // Ramp the DAC down. ramp_value(self->quiescent_value, 0); DAC->CTRLA.bit.ENABLE = 0; #ifdef SAMD21 while (DAC->STATUS.bit.SYNCBUSY == 1) {} #endif #ifdef SAMD51 while (DAC->SYNCBUSY.bit.ENABLE == 1) {} #endif disable_event_channel(self->tc_to_dac_event_channel); tc_set_enable(tc_insts[self->tc_index], false); reset_pin_number(self->left_channel->number); self->left_channel = mp_const_none; #ifdef SAMD51 reset_pin_number(self->right_channel->number); self->right_channel = mp_const_none; #endif } static void set_timer_frequency(Tc* timer, uint32_t frequency) { uint32_t system_clock = 48000000; uint32_t new_top; uint8_t new_divisor; for (new_divisor = 0; new_divisor < 8; new_divisor++) { new_top = (system_clock / prescaler[new_divisor] / frequency) - 1; if (new_top < (1u << 16)) { break; } } uint8_t old_divisor = timer->COUNT16.CTRLA.bit.PRESCALER; if (new_divisor != old_divisor) { tc_set_enable(timer, false); timer->COUNT16.CTRLA.bit.PRESCALER = new_divisor; tc_set_enable(timer, true); } tc_wait_for_sync(timer); timer->COUNT16.CC[0].reg = new_top; tc_wait_for_sync(timer); } void common_hal_audioio_audioout_play(audioio_audioout_obj_t* self, mp_obj_t sample, bool loop) { if (common_hal_audioio_audioout_get_playing(self)) { common_hal_audioio_audioout_stop(self); } audio_dma_result result = AUDIO_DMA_OK; uint32_t sample_rate = audiosample_sample_rate(sample); #ifdef SAMD21 uint32_t max_sample_rate = 350000; #endif #ifdef SAMD51 uint32_t max_sample_rate = 1000000; #endif if (sample_rate > max_sample_rate) { mp_raise_ValueError_varg(translate("Sample rate too high. It must be less than %d"), max_sample_rate); } #ifdef SAMD21 result = audio_dma_setup_playback(&self->left_dma, sample, loop, true, 0, false /* output unsigned */, (uint32_t) &DAC->DATABUF.reg, DAC_DMAC_ID_EMPTY); #endif #ifdef SAMD51 uint32_t left_channel_reg = (uint32_t) &DAC->DATABUF[0].reg; uint8_t left_channel_trigger = DAC_DMAC_ID_EMPTY_0; uint32_t right_channel_reg = 0; uint8_t right_channel_trigger = 0; if (self->left_channel == &pin_PA05) { left_channel_reg = (uint32_t) &DAC->DATABUF[1].reg; left_channel_trigger = DAC_DMAC_ID_EMPTY_1; } else if (self->right_channel == &pin_PA05) { right_channel_reg = (uint32_t) &DAC->DATABUF[1].reg; right_channel_trigger = DAC_DMAC_ID_EMPTY_1; } if (self->right_channel == &pin_PA02) { right_channel_reg = (uint32_t) &DAC->DATABUF[0].reg; right_channel_trigger = DAC_DMAC_ID_EMPTY_0; } result = audio_dma_setup_playback(&self->left_dma, sample, loop, true, 0, false /* output unsigned */, left_channel_reg, left_channel_trigger); if (right_channel_reg != 0 && result == AUDIO_DMA_OK) { result = audio_dma_setup_playback(&self->right_dma, sample, loop, true, 1, false /* output unsigned */, right_channel_reg, right_channel_trigger); } #endif if (result != AUDIO_DMA_OK) { audio_dma_stop(&self->left_dma); #ifdef SAMD51 audio_dma_stop(&self->right_dma); #endif if (result == AUDIO_DMA_DMA_BUSY) { mp_raise_RuntimeError(translate("No DMA channel found")); } else if (result == AUDIO_DMA_MEMORY_ERROR) { mp_raise_RuntimeError(translate("Unable to allocate buffers for signed conversion")); } } Tc* timer = tc_insts[self->tc_index]; set_timer_frequency(timer, audiosample_sample_rate(sample)); timer->COUNT16.CTRLBSET.reg = TC_CTRLBSET_CMD_RETRIGGER; while (timer->COUNT16.STATUS.bit.STOP == 1) {} self->playing = true; } void common_hal_audioio_audioout_pause(audioio_audioout_obj_t* self) { audio_dma_pause(&self->left_dma); #ifdef SAMD51 audio_dma_pause(&self->right_dma); #endif } void common_hal_audioio_audioout_resume(audioio_audioout_obj_t* self) { // Clear any overrun/underrun errors #ifdef SAMD21 DAC->INTFLAG.reg = DAC_INTFLAG_UNDERRUN; #endif #ifdef SAMD51 DAC->INTFLAG.reg = DAC_INTFLAG_UNDERRUN0 | DAC_INTFLAG_UNDERRUN1; #endif audio_dma_resume(&self->left_dma); #ifdef SAMD51 audio_dma_resume(&self->right_dma); #endif } bool common_hal_audioio_audioout_get_paused(audioio_audioout_obj_t* self) { return audio_dma_get_paused(&self->left_dma); } void common_hal_audioio_audioout_stop(audioio_audioout_obj_t* self) { Tc* timer = tc_insts[self->tc_index]; timer->COUNT16.CTRLBSET.reg = TC_CTRLBSET_CMD_STOP; audio_dma_stop(&self->left_dma); #ifdef SAMD51 audio_dma_stop(&self->right_dma); #endif // Ramp the DAC to default. The start is ignored when the current value can be readback. // Otherwise, we just set it immediately. ramp_value(self->quiescent_value, self->quiescent_value); } bool common_hal_audioio_audioout_get_playing(audioio_audioout_obj_t* self) { bool now_playing = audio_dma_get_playing(&self->left_dma); if (self->playing && !now_playing) { common_hal_audioio_audioout_stop(self); } return now_playing; }
169315.c
/* Support for printing Fortran values for GDB, the GNU debugger. Copyright (C) 1993-2020 Free Software Foundation, Inc. Contributed by Motorola. Adapted from the C definitions by Farooq Butt ([email protected]), additionally worked over by Stan Shebs. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "defs.h" #include "symtab.h" #include "gdbtypes.h" #include "expression.h" #include "value.h" #include "valprint.h" #include "language.h" #include "f-lang.h" #include "frame.h" #include "gdbcore.h" #include "command.h" #include "block.h" #include "dictionary.h" #include "cli/cli-style.h" #include "gdbarch.h" static void f77_get_dynamic_length_of_aggregate (struct type *); int f77_array_offset_tbl[MAX_FORTRAN_DIMS + 1][2]; /* Array which holds offsets to be applied to get a row's elements for a given array. Array also holds the size of each subarray. */ LONGEST f77_get_lowerbound (struct type *type) { if (type->bounds ()->low.kind () == PROP_UNDEFINED) error (_("Lower bound may not be '*' in F77")); return type->bounds ()->low.const_val (); } LONGEST f77_get_upperbound (struct type *type) { if (type->bounds ()->high.kind () == PROP_UNDEFINED) { /* We have an assumed size array on our hands. Assume that upper_bound == lower_bound so that we show at least 1 element. If the user wants to see more elements, let him manually ask for 'em and we'll subscript the array and show him. */ return f77_get_lowerbound (type); } return type->bounds ()->high.const_val (); } /* Obtain F77 adjustable array dimensions. */ static void f77_get_dynamic_length_of_aggregate (struct type *type) { int upper_bound = -1; int lower_bound = 1; /* Recursively go all the way down into a possibly multi-dimensional F77 array and get the bounds. For simple arrays, this is pretty easy but when the bounds are dynamic, we must be very careful to add up all the lengths correctly. Not doing this right will lead to horrendous-looking arrays in parameter lists. This function also works for strings which behave very similarly to arrays. */ if (TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_ARRAY || TYPE_TARGET_TYPE (type)->code () == TYPE_CODE_STRING) f77_get_dynamic_length_of_aggregate (TYPE_TARGET_TYPE (type)); /* Recursion ends here, start setting up lengths. */ lower_bound = f77_get_lowerbound (type); upper_bound = f77_get_upperbound (type); /* Patch in a valid length value. */ TYPE_LENGTH (type) = (upper_bound - lower_bound + 1) * TYPE_LENGTH (check_typedef (TYPE_TARGET_TYPE (type))); } /* Actual function which prints out F77 arrays, Valaddr == address in the superior. Address == the address in the inferior. */ static void f77_print_array_1 (int nss, int ndimensions, struct type *type, const gdb_byte *valaddr, int embedded_offset, CORE_ADDR address, struct ui_file *stream, int recurse, const struct value *val, const struct value_print_options *options, int *elts) { struct type *range_type = check_typedef (type)->index_type (); CORE_ADDR addr = address + embedded_offset; LONGEST lowerbound, upperbound; LONGEST i; get_discrete_bounds (range_type, &lowerbound, &upperbound); if (nss != ndimensions) { struct gdbarch *gdbarch = get_type_arch (type); size_t dim_size = type_length_units (TYPE_TARGET_TYPE (type)); int unit_size = gdbarch_addressable_memory_unit_size (gdbarch); size_t byte_stride = type->bit_stride () / (unit_size * 8); if (byte_stride == 0) byte_stride = dim_size; size_t offs = 0; for (i = lowerbound; (i < upperbound + 1 && (*elts) < options->print_max); i++) { struct value *subarray = value_from_contents_and_address (TYPE_TARGET_TYPE (type), value_contents_for_printing_const (val) + offs, addr + offs); fprintf_filtered (stream, "( "); f77_print_array_1 (nss + 1, ndimensions, value_type (subarray), value_contents_for_printing (subarray), value_embedded_offset (subarray), value_address (subarray), stream, recurse, subarray, options, elts); offs += byte_stride; fprintf_filtered (stream, ") "); } if (*elts >= options->print_max && i < upperbound) fprintf_filtered (stream, "..."); } else { for (i = lowerbound; i < upperbound + 1 && (*elts) < options->print_max; i++, (*elts)++) { struct value *elt = value_subscript ((struct value *)val, i); common_val_print (elt, stream, recurse, options, current_language); if (i != upperbound) fprintf_filtered (stream, ", "); if ((*elts == options->print_max - 1) && (i != upperbound)) fprintf_filtered (stream, "..."); } } } /* This function gets called to print an F77 array, we set up some stuff and then immediately call f77_print_array_1(). */ static void f77_print_array (struct type *type, const gdb_byte *valaddr, int embedded_offset, CORE_ADDR address, struct ui_file *stream, int recurse, const struct value *val, const struct value_print_options *options) { int ndimensions; int elts = 0; ndimensions = calc_f77_array_dims (type); if (ndimensions > MAX_FORTRAN_DIMS || ndimensions < 0) error (_("\ Type node corrupt! F77 arrays cannot have %d subscripts (%d Max)"), ndimensions, MAX_FORTRAN_DIMS); f77_print_array_1 (1, ndimensions, type, valaddr, embedded_offset, address, stream, recurse, val, options, &elts); } /* Decorations for Fortran. */ static const struct generic_val_print_decorations f_decorations = { "(", ",", ")", ".TRUE.", ".FALSE.", "void", "{", "}" }; /* See f-lang.h. */ void f_value_print_inner (struct value *val, struct ui_file *stream, int recurse, const struct value_print_options *options) { struct type *type = check_typedef (value_type (val)); struct gdbarch *gdbarch = get_type_arch (type); int printed_field = 0; /* Number of fields printed. */ struct type *elttype; CORE_ADDR addr; int index; const gdb_byte *valaddr = value_contents_for_printing (val); const CORE_ADDR address = value_address (val); switch (type->code ()) { case TYPE_CODE_STRING: f77_get_dynamic_length_of_aggregate (type); LA_PRINT_STRING (stream, builtin_type (gdbarch)->builtin_char, valaddr, TYPE_LENGTH (type), NULL, 0, options); break; case TYPE_CODE_ARRAY: if (TYPE_TARGET_TYPE (type)->code () != TYPE_CODE_CHAR) { fprintf_filtered (stream, "("); f77_print_array (type, valaddr, 0, address, stream, recurse, val, options); fprintf_filtered (stream, ")"); } else { struct type *ch_type = TYPE_TARGET_TYPE (type); f77_get_dynamic_length_of_aggregate (type); LA_PRINT_STRING (stream, ch_type, valaddr, TYPE_LENGTH (type) / TYPE_LENGTH (ch_type), NULL, 0, options); } break; case TYPE_CODE_PTR: if (options->format && options->format != 's') { value_print_scalar_formatted (val, options, 0, stream); break; } else { int want_space = 0; addr = unpack_pointer (type, valaddr); elttype = check_typedef (TYPE_TARGET_TYPE (type)); if (elttype->code () == TYPE_CODE_FUNC) { /* Try to print what function it points to. */ print_function_pointer_address (options, gdbarch, addr, stream); return; } if (options->symbol_print) want_space = print_address_demangle (options, gdbarch, addr, stream, demangle); else if (options->addressprint && options->format != 's') { fputs_filtered (paddress (gdbarch, addr), stream); want_space = 1; } /* For a pointer to char or unsigned char, also print the string pointed to, unless pointer is null. */ if (TYPE_LENGTH (elttype) == 1 && elttype->code () == TYPE_CODE_INT && (options->format == 0 || options->format == 's') && addr != 0) { if (want_space) fputs_filtered (" ", stream); val_print_string (TYPE_TARGET_TYPE (type), NULL, addr, -1, stream, options); } return; } break; case TYPE_CODE_INT: if (options->format || options->output_format) { struct value_print_options opts = *options; opts.format = (options->format ? options->format : options->output_format); value_print_scalar_formatted (val, &opts, 0, stream); } else value_print_scalar_formatted (val, options, 0, stream); break; case TYPE_CODE_STRUCT: case TYPE_CODE_UNION: /* Starting from the Fortran 90 standard, Fortran supports derived types. */ fprintf_filtered (stream, "( "); for (index = 0; index < type->num_fields (); index++) { struct value *field = value_field (val, index); struct type *field_type = check_typedef (type->field (index).type ()); if (field_type->code () != TYPE_CODE_FUNC) { const char *field_name; if (printed_field > 0) fputs_filtered (", ", stream); field_name = TYPE_FIELD_NAME (type, index); if (field_name != NULL) { fputs_styled (field_name, variable_name_style.style (), stream); fputs_filtered (" = ", stream); } common_val_print (field, stream, recurse + 1, options, current_language); ++printed_field; } } fprintf_filtered (stream, " )"); break; case TYPE_CODE_BOOL: if (options->format || options->output_format) { struct value_print_options opts = *options; opts.format = (options->format ? options->format : options->output_format); value_print_scalar_formatted (val, &opts, 0, stream); } else { LONGEST longval = value_as_long (val); /* The Fortran standard doesn't specify how logical types are represented. Different compilers use different non zero values to represent logical true. */ if (longval == 0) fputs_filtered (f_decorations.false_name, stream); else fputs_filtered (f_decorations.true_name, stream); } break; case TYPE_CODE_REF: case TYPE_CODE_FUNC: case TYPE_CODE_FLAGS: case TYPE_CODE_FLT: case TYPE_CODE_VOID: case TYPE_CODE_ERROR: case TYPE_CODE_RANGE: case TYPE_CODE_UNDEF: case TYPE_CODE_COMPLEX: case TYPE_CODE_CHAR: default: generic_value_print (val, stream, recurse, options, &f_decorations); break; } } static void info_common_command_for_block (const struct block *block, const char *comname, int *any_printed) { struct block_iterator iter; struct symbol *sym; struct value_print_options opts; get_user_print_options (&opts); ALL_BLOCK_SYMBOLS (block, iter, sym) if (SYMBOL_DOMAIN (sym) == COMMON_BLOCK_DOMAIN) { const struct common_block *common = SYMBOL_VALUE_COMMON_BLOCK (sym); size_t index; gdb_assert (SYMBOL_CLASS (sym) == LOC_COMMON_BLOCK); if (comname && (!sym->linkage_name () || strcmp (comname, sym->linkage_name ()) != 0)) continue; if (*any_printed) putchar_filtered ('\n'); else *any_printed = 1; if (sym->print_name ()) printf_filtered (_("Contents of F77 COMMON block '%s':\n"), sym->print_name ()); else printf_filtered (_("Contents of blank COMMON block:\n")); for (index = 0; index < common->n_entries; index++) { struct value *val = NULL; printf_filtered ("%s = ", common->contents[index]->print_name ()); try { val = value_of_variable (common->contents[index], block); value_print (val, gdb_stdout, &opts); } catch (const gdb_exception_error &except) { fprintf_styled (gdb_stdout, metadata_style.style (), "<error reading variable: %s>", except.what ()); } putchar_filtered ('\n'); } } } /* This function is used to print out the values in a given COMMON block. It will always use the most local common block of the given name. */ static void info_common_command (const char *comname, int from_tty) { struct frame_info *fi; const struct block *block; int values_printed = 0; /* We have been told to display the contents of F77 COMMON block supposedly visible in this function. Let us first make sure that it is visible and if so, let us display its contents. */ fi = get_selected_frame (_("No frame selected")); /* The following is generally ripped off from stack.c's routine print_frame_info(). */ block = get_frame_block (fi, 0); if (block == NULL) { printf_filtered (_("No symbol table info available.\n")); return; } while (block) { info_common_command_for_block (block, comname, &values_printed); /* After handling the function's top-level block, stop. Don't continue to its superblock, the block of per-file symbols. */ if (BLOCK_FUNCTION (block)) break; block = BLOCK_SUPERBLOCK (block); } if (!values_printed) { if (comname) printf_filtered (_("No common block '%s'.\n"), comname); else printf_filtered (_("No common blocks.\n")); } } void _initialize_f_valprint (); void _initialize_f_valprint () { add_info ("common", info_common_command, _("Print out the values contained in a Fortran COMMON block.")); }
641358.c
#include "gridstore.h" #include <stdlib.h> #include <stdio.h> void main(int argc, char *argv[]){ /* 変数 */ GSGridStore *store; GSContainer *container; GSResult ret; int i; // コンテナ作成用 GSContainerInfo info0 = GS_CONTAINER_INFO_INITIALIZER; GSColumnInfo columnInfo = GS_COLUMN_INFO_INITIALIZER; GSColumnInfo columnInfoList[3]; // カラム数3 // コンテナ情報取得用 GSContainerInfo info = GS_CONTAINER_INFO_INITIALIZER; GSBool exist; // エラー処理用 size_t stackSize; GSResult errorCode; GSChar errMsgBuf1[1024], errMsgBuf2[1024]; // エラーメッセージを格納するバッファ //=============================================== // クラスタに接続する //=============================================== // 接続情報を指定する (マルチキャスト方式) const GSPropertyEntry props[] = { { "notificationAddress", "239.0.0.1" }, { "notificationPort", "31999" }, { "clusterName", "myCluster" }, { "database", "public" }, { "user", "admin" }, { "password", "admin" }, //{ "applicationName", "SampleC" } }; /* // 接続情報を指定する (固定リスト方式) const GSPropertyEntry props[] = { { "notificationMember", "192.168.10.110:10001" }, { "clusterName", "myCluster" }, { "database", "public" }, { "user", "admin" }, { "password", "admin" }, { "applicationName", "SampleC" } }; */ const size_t propCount = sizeof(props) / sizeof(*props); // GridStoreインスタンスを取得する ret = gsGetGridStore(gsGetDefaultFactory(), props, propCount, &store); if ( !GS_SUCCEEDED(ret) ){ fprintf(stderr, "ERROR gsGetGridStore\n"); goto LABEL_ERROR; } // コンテナ作成や取得などの操作を行うと、クラスタに接続される ret = gsGetContainerGeneral(store, "containerName", &container); if ( !GS_SUCCEEDED(ret) ){ fprintf(stderr, "ERROR gsGetContainerGeneral\n"); goto LABEL_ERROR; } gsCloseContainer(&container, GS_TRUE); printf("Connect to Cluster\n"); //=============================================== // データ準備 (コンテナ作成) //=============================================== { // コンテナ情報を設定する info0.type = GS_CONTAINER_COLLECTION; info0.rowKeyAssigned = GS_TRUE; columnInfo.name = "id"; columnInfo.type = GS_TYPE_INTEGER; columnInfoList[0] = columnInfo; columnInfo.name = "productName"; columnInfo.type = GS_TYPE_STRING; columnInfoList[1] = columnInfo; columnInfo.name = "count"; columnInfo.type = GS_TYPE_INTEGER; columnInfoList[2] = columnInfo; info0.columnCount = sizeof(columnInfoList) / sizeof(*columnInfoList); info0.columnInfoList = columnInfoList; // コレクションを作成する ret = gsPutCollectionGeneral(store, "SampleC_Info", &info0, GS_FALSE, &container); if ( !GS_SUCCEEDED(ret) ){ fprintf(stderr, "ERROR gsPutCollectionGeneral\n"); goto LABEL_ERROR; } printf("Sample data generation: Create Collection name=SampleC_Info\n"); gsCloseContainer(&container, GS_TRUE); } //=============================================== // コンテナ情報を取得する //=============================================== // (1)コンテナ情報を取得する ret = gsGetContainerInfo(store, "SampleC_Info", &info, &exist); if ( !GS_SUCCEEDED(ret) ){ fprintf(stderr, "ERROR gsGetContainerInfo\n"); goto LABEL_ERROR; } if ( !exist ){ printf("Container not found\n"); goto LABEL_ERROR; } // (2)コンテナ情報を表示する printf("Get ContainerInfo: \n name=%s\n", info.name); if ( info.type == GS_CONTAINER_COLLECTION ){ printf(" type=Collection\n"); } else { printf(" type=TimeSeries\n"); } printf(" rowKeyAssigned=%d\n", info.rowKeyAssigned); printf(" columnCount=%d\n", info.columnCount); for ( i = 0; i < info.columnCount; i++ ){ printf(" column (%s, %d)\n", info.columnInfoList[i].name, info.columnInfoList[i].type); } //=============================================== // 終了処理 //=============================================== // リソースを解放する gsCloseGridStore(&store, GS_TRUE); printf("success!\n"); return; LABEL_ERROR: //=============================================== // エラー処理 //=============================================== // エラーコードとエラーメッセージを出力する stackSize = gsGetErrorStackSize(store); for ( i = 0; i < stackSize; i++ ){ errorCode = gsGetErrorCode(store, i); gsFormatErrorMessage(store, i, errMsgBuf1, sizeof(errMsgBuf1)); gsFormatErrorLocation(store, i, errMsgBuf2, sizeof(errMsgBuf2)); fprintf(stderr, "[%d] %s (%s)\n", errorCode, errMsgBuf1, errMsgBuf2); } // リソースを解放する gsCloseGridStore(&store, GS_TRUE); return; }
974034.c
#include <rtthread.h> #include <stdio.h> #include <math.h> #include <dfs_posix.h> #include "drv_heap.h" #include "drv_display.h" #include "image_info.h" #include "display.h" /* ************************************************************************************************** * * Macro define * ************************************************************************************************** */ /* display win layers */ #define ANIMATION_RGB888_WIN 1 #define ANI_MAX_XRES 320 #define ANI_MAX_YRES 385 /* display region define */ #define ANI_REGION_X 0 #define ANI_REGION_Y 0 #define ANI_FB_W 320 /* aligned 2 (32bit) */ #define ANI_FB_H 385 /* aligned 2 */ #define ANI_FB_PIXELS 24 /* Command define */ #define CMD_REFR_ANI (0x01UL << 0) /* Event define */ #define EVENT_REFR_UPDATE (0x01UL << 0) #define EVENT_REFR_DONE (0x01UL << 1) #define ANI_UPDATE_TICKS ((RT_TICK_PER_SECOND / 1000) * 33) /* ************************************************************************************************** * * Declaration * ************************************************************************************************** */ #define ANI_RES_FILE_NUM 6 /* ************************************************************************************************** * * Global static struct & data define * ************************************************************************************************** */ struct global_ani_data { rt_display_data_t disp; rt_event_t disp_event; rt_uint32_t cmd; rt_timer_t ani_timer; rt_uint8_t *fb; rt_uint32_t fblen; rt_uint32_t res_id; }; static struct global_ani_data *g_ani_data = RT_NULL; /* ************************************************************************************************** * * Animation display * ************************************************************************************************** */ /** * Animation timer callback. */ static void app_animation_timer(void *parameter) { struct global_ani_data *ani_data = (struct global_ani_data *)parameter; ani_data->cmd |= CMD_REFR_ANI; rt_event_send(ani_data->disp_event, EVENT_REFR_UPDATE); } /** * Animation dmeo init. */ static rt_err_t app_animation_init(struct global_ani_data *ani_data) { ani_data->fblen = ANI_FB_W * ANI_FB_H * (ANI_FB_PIXELS / 8); ani_data->fb = (rt_uint8_t *)rt_malloc_psram(ani_data->fblen); RT_ASSERT(ani_data->fb != RT_NULL); rt_memset((void *)ani_data->fb, 0, ani_data->fblen); ani_data->ani_timer = rt_timer_create("appAniTimer", app_animation_timer, (void *)ani_data, ANI_UPDATE_TICKS, RT_TIMER_FLAG_PERIODIC); RT_ASSERT(ani_data->ani_timer != RT_NULL); rt_timer_start(ani_data->ani_timer); ani_data->cmd |= CMD_REFR_ANI; rt_event_send(ani_data->disp_event, EVENT_REFR_UPDATE); return RT_EOK; } /** * Animation demo deinit. */ static void app_animation_deinit(struct global_ani_data *ani_data) { rt_err_t ret; rt_timer_stop(ani_data->ani_timer); ret = rt_timer_delete(ani_data->ani_timer); RT_ASSERT(ret == RT_EOK); rt_free_psram((void *)ani_data->fb); } /** * Animation refresh. */ static rt_err_t app_animation_refresh(struct global_ani_data *ani_data, struct rt_display_config *wincfg) { struct rt_device_graphic_info *info = &ani_data->disp->info; char fname[256]; wincfg->winId = ANIMATION_RGB888_WIN; wincfg->format = RTGRAPHIC_PIXEL_FORMAT_RGB888; wincfg->lut = RT_NULL; wincfg->lutsize = 0; wincfg->fb = ani_data->fb; wincfg->fblen = ani_data->fblen; wincfg->w = ANI_FB_W; wincfg->h = ANI_FB_H; wincfg->x = ANI_REGION_X + ((info->width - wincfg->w) / 2); wincfg->y = ANI_REGION_Y + ((info->height - wincfg->h) / 2); wincfg->ylast = wincfg->y; RT_ASSERT(((wincfg->w * ANI_FB_PIXELS) % 32) == 0); //RT_ASSERT(((wincfg->y % 2) == 0) && ((wincfg->h % 2) == 0)); RT_ASSERT((wincfg->x + wincfg->w) <= info->width); RT_ASSERT((wincfg->y + wincfg->h) <= info->height); RT_ASSERT(wincfg->fblen <= ani_data->fblen); if (++ani_data->res_id >= ANI_RES_FILE_NUM) { ani_data->res_id = 0; } // read data from file rt_memset(fname, 0, sizeof(fname)); snprintf(fname, sizeof(fname), "/Animation2Res/oximetry_%03d.dta", (int)ani_data->res_id); //rt_kprintf("app_animation_refresh: %s\n", fname); int fd = open(fname, O_RDONLY, 0); if (fd < 0) { rt_kprintf("file open error --> %s\n", fname); } else { rt_uint32_t len = read(fd, wincfg->fb, wincfg->fblen); if (len != wincfg->fblen) { rt_kprintf("file read error --> %s, req = %d, read = %d\n", fname, wincfg->fblen, len); } close(fd); } return RT_EOK; } /* ************************************************************************************************** * * Animation demo init & thread * ************************************************************************************************** */ /** * display refresh request: request send data to LCD pannel. */ static rt_err_t app_animation_refr_done(void) { return (rt_event_send(g_ani_data->disp_event, EVENT_REFR_DONE)); } static rt_err_t app_animation_refr_request(struct rt_display_mq_t *disp_mq) { rt_err_t ret; //request refresh display data to Pannel disp_mq->disp_finish = app_animation_refr_done; ret = rt_mq_send(g_ani_data->disp->disp_mq, disp_mq, sizeof(struct rt_display_mq_t)); RT_ASSERT(ret == RT_EOK); //wait refresh done rt_uint32_t event; ret = rt_event_recv(g_ani_data->disp_event, EVENT_REFR_DONE, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &event); RT_ASSERT(ret == RT_EOK); return RT_EOK; } /** * Animation display task. */ static rt_err_t app_animation_refr_tasks(struct global_ani_data *ani_data) { rt_err_t ret; struct rt_display_mq_t disp_mq; rt_memset(&disp_mq, 0, sizeof(struct rt_display_mq_t)); disp_mq.win[0].zpos = WIN_TOP_LAYER; if ((ani_data->cmd & CMD_REFR_ANI) == CMD_REFR_ANI) { ani_data->cmd &= ~CMD_REFR_ANI; ret = app_animation_refresh(ani_data, &disp_mq.win[0]); RT_ASSERT(ret == RT_EOK); disp_mq.cfgsta |= (0x01 << 0); } if (disp_mq.cfgsta) { app_animation_refr_request(&disp_mq); } if (ani_data->cmd != 0) { //rt_event_send(ani_data->disp_event, EVENT_REFR_UPDATE); } return RT_EOK; } /** * Animation demo thread */ static void app_animation_thread(void *p) { rt_err_t ret; uint32_t event; struct global_ani_data *ani_data; g_ani_data = ani_data = (struct global_ani_data *)rt_malloc(sizeof(struct global_ani_data)); RT_ASSERT(ani_data != RT_NULL); rt_memset((void *)ani_data, 0, sizeof(struct global_ani_data)); ani_data->disp = rt_display_get_disp(); RT_ASSERT(ani_data->disp != RT_NULL); //check required pannel size struct rt_device_graphic_info *info = &ani_data->disp->info; if ((info->width < ANI_MAX_XRES) || (info->height < ANI_MAX_YRES)) { rt_kprintf("Error: the pannel size(%dx%d) is less than required size(%dx%d)!\n", info->width, info->height, ANI_MAX_XRES, ANI_MAX_YRES); RT_ASSERT(!(info->width < ANI_MAX_XRES)); RT_ASSERT(!(info->height < ANI_MAX_YRES)); } ret = rt_display_screen_clear(); RT_ASSERT(ret == RT_EOK); ani_data->disp_event = rt_event_create("display_event", RT_IPC_FLAG_FIFO); RT_ASSERT(ani_data->disp_event != RT_NULL); ret = app_animation_init(ani_data); RT_ASSERT(ret == RT_EOK); while (1) { ret = rt_event_recv(ani_data->disp_event, EVENT_REFR_UPDATE, RT_EVENT_FLAG_OR | RT_EVENT_FLAG_CLEAR, RT_WAITING_FOREVER, &event); if (ret != RT_EOK) { /* Reserved... */ } if (event & EVENT_REFR_UPDATE) { ret = app_animation_refr_tasks(ani_data); RT_ASSERT(ret == RT_EOK); } } /* Thread deinit */ app_animation_deinit(ani_data); rt_event_delete(ani_data->disp_event); rt_free(ani_data); } /** * Animation demo init */ int app_animation_thread_init(void) { rt_thread_t thread; thread = rt_thread_create("appAnimation", app_animation_thread, RT_NULL, 2048, 5, 10); RT_ASSERT(thread != RT_NULL); rt_thread_startup(thread); return RT_EOK; } INIT_APP_EXPORT(app_animation_thread_init);
667796.c
// we put main() in a seperate file so that the linker will ignore it // if we link the libpi-fake.a library against something that has a main() #include "fake-pi.h" int main(int argc, char *argv[]) { fake_init(); // extension: run in a subprocess to isolate // errors. output("calling pi code\n"); notmain(); output("pi exited cleanly\n"); trace("%d calls to random\n", fake_random_calls()); return 0; }
953772.c
/* * WPA Supplicant / dbus-based control interface * Copyright (c) 2006, Dan Williams <[email protected]> and Red Hat, Inc. * Copyright (c) 2009-2010, Witold Sowa <[email protected]> * Copyright (c) 2009, Jouni Malinen <[email protected]> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include "common.h" #include "common/ieee802_11_defs.h" #include "wps/wps.h" #include "../config.h" #include "../wpa_supplicant_i.h" #include "../bss.h" #include "../wpas_glue.h" #include "dbus_new_helpers.h" #include "dbus_dict_helpers.h" #include "dbus_new.h" #include "dbus_new_handlers.h" #include "dbus_common_i.h" #include "dbus_new_handlers_p2p.h" #include "p2p/p2p.h" #include "../p2p_supplicant.h" #ifdef CONFIG_AP /* until needed by something else */ /* * NameOwnerChanged handling * * Some services we provide allow an application to register for * a signal that it needs. While it can also unregister, we must * be prepared for the case where the application simply crashes * and thus doesn't clean up properly. The way to handle this in * DBus is to register for the NameOwnerChanged signal which will * signal an owner change to NULL if the peer closes the socket * for whatever reason. * * Handle this signal via a filter function whenever necessary. * The code below also handles refcounting in case in the future * there will be multiple instances of this subscription scheme. */ static const char wpas_dbus_noc_filter_str[] = "interface=org.freedesktop.DBus,member=NameOwnerChanged"; static DBusHandlerResult noc_filter(DBusConnection *conn, DBusMessage *message, void *data) { struct wpas_dbus_priv *priv = data; if (dbus_message_get_type(message) != DBUS_MESSAGE_TYPE_SIGNAL) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) { const char *name; const char *prev_owner; const char *new_owner; DBusError derr; struct wpa_supplicant *wpa_s; dbus_error_init(&derr); if (!dbus_message_get_args(message, &derr, DBUS_TYPE_STRING, &name, DBUS_TYPE_STRING, &prev_owner, DBUS_TYPE_STRING, &new_owner, DBUS_TYPE_INVALID)) { /* Ignore this error */ dbus_error_free(&derr); return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } for (wpa_s = priv->global->ifaces; wpa_s; wpa_s = wpa_s->next) { if (wpa_s->preq_notify_peer != NULL && os_strcmp(name, wpa_s->preq_notify_peer) == 0 && (new_owner == NULL || os_strlen(new_owner) == 0)) { /* probe request owner disconnected */ os_free(wpa_s->preq_notify_peer); wpa_s->preq_notify_peer = NULL; wpas_dbus_unsubscribe_noc(priv); } } } return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } void wpas_dbus_subscribe_noc(struct wpas_dbus_priv *priv) { priv->dbus_noc_refcnt++; if (priv->dbus_noc_refcnt > 1) return; if (!dbus_connection_add_filter(priv->con, noc_filter, priv, NULL)) { wpa_printf(MSG_ERROR, "dbus: failed to add filter"); return; } dbus_bus_add_match(priv->con, wpas_dbus_noc_filter_str, NULL); } void wpas_dbus_unsubscribe_noc(struct wpas_dbus_priv *priv) { priv->dbus_noc_refcnt--; if (priv->dbus_noc_refcnt > 0) return; dbus_bus_remove_match(priv->con, wpas_dbus_noc_filter_str, NULL); dbus_connection_remove_filter(priv->con, noc_filter, priv); } #endif /* CONFIG_AP */ /** * wpas_dbus_signal_interface - Send a interface related event signal * @wpa_s: %wpa_supplicant network interface data * @sig_name: signal name - InterfaceAdded or InterfaceRemoved * @properties: Whether to add second argument with object properties * * Notify listeners about event related with interface */ static void wpas_dbus_signal_interface(struct wpa_supplicant *wpa_s, const char *sig_name, int properties) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(WPAS_DBUS_NEW_PATH, WPAS_DBUS_NEW_INTERFACE, sig_name); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &wpa_s->dbus_new_path)) goto err; if (properties) { if (!wpa_dbus_get_object_properties( iface, wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, &iter)) goto err; } dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_interface_added - Send a interface created signal * @wpa_s: %wpa_supplicant network interface data * * Notify listeners about creating new interface */ static void wpas_dbus_signal_interface_added(struct wpa_supplicant *wpa_s) { wpas_dbus_signal_interface(wpa_s, "InterfaceAdded", TRUE); } /** * wpas_dbus_signal_interface_removed - Send a interface removed signal * @wpa_s: %wpa_supplicant network interface data * * Notify listeners about removing interface */ static void wpas_dbus_signal_interface_removed(struct wpa_supplicant *wpa_s) { wpas_dbus_signal_interface(wpa_s, "InterfaceRemoved", FALSE); } /** * wpas_dbus_signal_scan_done - send scan done signal * @wpa_s: %wpa_supplicant network interface data * @success: indicates if scanning succeed or failed * * Notify listeners about finishing a scan */ void wpas_dbus_signal_scan_done(struct wpa_supplicant *wpa_s, int success) { struct wpas_dbus_priv *iface; DBusMessage *msg; dbus_bool_t succ; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, "ScanDone"); if (msg == NULL) return; succ = success ? TRUE : FALSE; if (dbus_message_append_args(msg, DBUS_TYPE_BOOLEAN, &succ, DBUS_TYPE_INVALID)) dbus_connection_send(iface->con, msg, NULL); else wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_blob - Send a BSS related event signal * @wpa_s: %wpa_supplicant network interface data * @bss_obj_path: BSS object path * @sig_name: signal name - BSSAdded or BSSRemoved * @properties: Whether to add second argument with object properties * * Notify listeners about event related with BSS */ static void wpas_dbus_signal_bss(struct wpa_supplicant *wpa_s, const char *bss_obj_path, const char *sig_name, int properties) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, sig_name); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &bss_obj_path)) goto err; if (properties) { if (!wpa_dbus_get_object_properties(iface, bss_obj_path, WPAS_DBUS_NEW_IFACE_BSS, &iter)) goto err; } dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_bss_added - Send a BSS added signal * @wpa_s: %wpa_supplicant network interface data * @bss_obj_path: new BSS object path * * Notify listeners about adding new BSS */ static void wpas_dbus_signal_bss_added(struct wpa_supplicant *wpa_s, const char *bss_obj_path) { wpas_dbus_signal_bss(wpa_s, bss_obj_path, "BSSAdded", TRUE); } /** * wpas_dbus_signal_bss_removed - Send a BSS removed signal * @wpa_s: %wpa_supplicant network interface data * @bss_obj_path: BSS object path * * Notify listeners about removing BSS */ static void wpas_dbus_signal_bss_removed(struct wpa_supplicant *wpa_s, const char *bss_obj_path) { wpas_dbus_signal_bss(wpa_s, bss_obj_path, "BSSRemoved", FALSE); } /** * wpas_dbus_signal_blob - Send a blob related event signal * @wpa_s: %wpa_supplicant network interface data * @name: blob name * @sig_name: signal name - BlobAdded or BlobRemoved * * Notify listeners about event related with blob */ static void wpas_dbus_signal_blob(struct wpa_supplicant *wpa_s, const char *name, const char *sig_name) { struct wpas_dbus_priv *iface; DBusMessage *msg; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, sig_name); if (msg == NULL) return; if (dbus_message_append_args(msg, DBUS_TYPE_STRING, &name, DBUS_TYPE_INVALID)) dbus_connection_send(iface->con, msg, NULL); else wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_blob_added - Send a blob added signal * @wpa_s: %wpa_supplicant network interface data * @name: blob name * * Notify listeners about adding a new blob */ void wpas_dbus_signal_blob_added(struct wpa_supplicant *wpa_s, const char *name) { wpas_dbus_signal_blob(wpa_s, name, "BlobAdded"); } /** * wpas_dbus_signal_blob_removed - Send a blob removed signal * @wpa_s: %wpa_supplicant network interface data * @name: blob name * * Notify listeners about removing blob */ void wpas_dbus_signal_blob_removed(struct wpa_supplicant *wpa_s, const char *name) { wpas_dbus_signal_blob(wpa_s, name, "BlobRemoved"); } /** * wpas_dbus_signal_network - Send a network related event signal * @wpa_s: %wpa_supplicant network interface data * @id: new network id * @sig_name: signal name - NetworkAdded, NetworkRemoved or NetworkSelected * @properties: determines if add second argument with object properties * * Notify listeners about event related with configured network */ static void wpas_dbus_signal_network(struct wpa_supplicant *wpa_s, int id, const char *sig_name, int properties) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char net_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; os_snprintf(net_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_NETWORKS_PART "/%u", wpa_s->dbus_new_path, id); msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, sig_name); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); path = net_obj_path; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto err; if (properties) { if (!wpa_dbus_get_object_properties( iface, net_obj_path, WPAS_DBUS_NEW_IFACE_NETWORK, &iter)) goto err; } dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_network_added - Send a network added signal * @wpa_s: %wpa_supplicant network interface data * @id: new network id * * Notify listeners about adding new network */ static void wpas_dbus_signal_network_added(struct wpa_supplicant *wpa_s, int id) { wpas_dbus_signal_network(wpa_s, id, "NetworkAdded", TRUE); } /** * wpas_dbus_signal_network_removed - Send a network removed signal * @wpa_s: %wpa_supplicant network interface data * @id: network id * * Notify listeners about removing a network */ static void wpas_dbus_signal_network_removed(struct wpa_supplicant *wpa_s, int id) { wpas_dbus_signal_network(wpa_s, id, "NetworkRemoved", FALSE); } /** * wpas_dbus_signal_network_selected - Send a network selected signal * @wpa_s: %wpa_supplicant network interface data * @id: network id * * Notify listeners about selecting a network */ void wpas_dbus_signal_network_selected(struct wpa_supplicant *wpa_s, int id) { wpas_dbus_signal_network(wpa_s, id, "NetworkSelected", FALSE); } /** * wpas_dbus_signal_network_request - Indicate that additional information * (EAP password, etc.) is required to complete the association to this SSID * @wpa_s: %wpa_supplicant network interface data * @rtype: The specific additional information required * @default_text: Optional description of required information * * Request additional information or passwords to complete an association * request. */ void wpas_dbus_signal_network_request(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid, enum wpa_ctrl_req_type rtype, const char *default_txt) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char net_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; const char *field, *txt = NULL, *net_ptr; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; field = wpa_supplicant_ctrl_req_to_string(rtype, default_txt, &txt); if (field == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, "NetworkRequest"); if (msg == NULL) return; os_snprintf(net_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_NETWORKS_PART "/%u", wpa_s->dbus_new_path, ssid->id); net_ptr = &net_obj_path[0]; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &net_ptr)) goto err; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &field)) goto err; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &txt)) goto err; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_network_enabled_changed - Signals Enabled property changes * @wpa_s: %wpa_supplicant network interface data * @ssid: configured network which Enabled property has changed * * Sends PropertyChanged signals containing new value of Enabled property * for specified network */ void wpas_dbus_signal_network_enabled_changed(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid) { char path[WPAS_DBUS_OBJECT_PATH_MAX]; os_snprintf(path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_NETWORKS_PART "/%d", wpa_s->dbus_new_path, ssid->id); wpa_dbus_mark_property_changed(wpa_s->global->dbus, path, WPAS_DBUS_NEW_IFACE_NETWORK, "Enabled"); } #ifdef CONFIG_WPS /** * wpas_dbus_signal_wps_event_success - Signals Success WPS event * @wpa_s: %wpa_supplicant network interface data * * Sends Event dbus signal with name "success" and empty dict as arguments */ void wpas_dbus_signal_wps_event_success(struct wpa_supplicant *wpa_s) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char *key = "success"; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_WPS, "Event"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key) || !wpa_dbus_dict_open_write(&iter, &dict_iter) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); else dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); } /** * wpas_dbus_signal_wps_event_fail - Signals Fail WPS event * @wpa_s: %wpa_supplicant network interface data * * Sends Event dbus signal with name "fail" and dictionary containing * "msg field with fail message number (int32) as arguments */ void wpas_dbus_signal_wps_event_fail(struct wpa_supplicant *wpa_s, struct wps_event_fail *fail) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char *key = "fail"; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_WPS, "Event"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key) || !wpa_dbus_dict_open_write(&iter, &dict_iter) || !wpa_dbus_dict_append_int32(&dict_iter, "msg", fail->msg) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); else dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); } /** * wpas_dbus_signal_wps_event_m2d - Signals M2D WPS event * @wpa_s: %wpa_supplicant network interface data * * Sends Event dbus signal with name "m2d" and dictionary containing * fields of wps_event_m2d structure. */ void wpas_dbus_signal_wps_event_m2d(struct wpa_supplicant *wpa_s, struct wps_event_m2d *m2d) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char *key = "m2d"; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_WPS, "Event"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key) || !wpa_dbus_dict_open_write(&iter, &dict_iter) || !wpa_dbus_dict_append_uint16(&dict_iter, "config_methods", m2d->config_methods) || !wpa_dbus_dict_append_byte_array(&dict_iter, "manufacturer", (const char *) m2d->manufacturer, m2d->manufacturer_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "model_name", (const char *) m2d->model_name, m2d->model_name_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "model_number", (const char *) m2d->model_number, m2d->model_number_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "serial_number", (const char *) m2d->serial_number, m2d->serial_number_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "dev_name", (const char *) m2d->dev_name, m2d->dev_name_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "primary_dev_type", (const char *) m2d->primary_dev_type, 8) || !wpa_dbus_dict_append_uint16(&dict_iter, "config_error", m2d->config_error) || !wpa_dbus_dict_append_uint16(&dict_iter, "dev_password_id", m2d->dev_password_id) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); else dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); } /** * wpas_dbus_signal_wps_cred - Signals new credentials * @wpa_s: %wpa_supplicant network interface data * * Sends signal with credentials in directory argument */ void wpas_dbus_signal_wps_cred(struct wpa_supplicant *wpa_s, const struct wps_credential *cred) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char *auth_type[5]; /* we have five possible authentication types */ int at_num = 0; char *encr_type[3]; /* we have three possible encryption types */ int et_num = 0; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_WPS, "Credentials"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto nomem; if (cred->auth_type & WPS_AUTH_OPEN) auth_type[at_num++] = "open"; if (cred->auth_type & WPS_AUTH_WPAPSK) auth_type[at_num++] = "wpa-psk"; if (cred->auth_type & WPS_AUTH_WPA) auth_type[at_num++] = "wpa-eap"; if (cred->auth_type & WPS_AUTH_WPA2) auth_type[at_num++] = "wpa2-eap"; if (cred->auth_type & WPS_AUTH_WPA2PSK) auth_type[at_num++] = "wpa2-psk"; if (cred->encr_type & WPS_ENCR_NONE) encr_type[et_num++] = "none"; if (cred->encr_type & WPS_ENCR_TKIP) encr_type[et_num++] = "tkip"; if (cred->encr_type & WPS_ENCR_AES) encr_type[et_num++] = "aes"; if (wpa_s->current_ssid) { if (!wpa_dbus_dict_append_byte_array( &dict_iter, "BSSID", (const char *) wpa_s->current_ssid->bssid, ETH_ALEN)) goto nomem; } if (!wpa_dbus_dict_append_byte_array(&dict_iter, "SSID", (const char *) cred->ssid, cred->ssid_len) || !wpa_dbus_dict_append_string_array(&dict_iter, "AuthType", (const char **) auth_type, at_num) || !wpa_dbus_dict_append_string_array(&dict_iter, "EncrType", (const char **) encr_type, et_num) || !wpa_dbus_dict_append_byte_array(&dict_iter, "Key", (const char *) cred->key, cred->key_len) || !wpa_dbus_dict_append_uint32(&dict_iter, "KeyIndex", cred->key_idx) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) goto nomem; dbus_connection_send(iface->con, msg, NULL); nomem: dbus_message_unref(msg); } #endif /* CONFIG_WPS */ void wpas_dbus_signal_certification(struct wpa_supplicant *wpa_s, int depth, const char *subject, const char *cert_hash, const struct wpabuf *cert) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter, dict_iter; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, "Certification"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto nomem; if (!wpa_dbus_dict_append_uint32(&dict_iter, "depth", depth) || !wpa_dbus_dict_append_string(&dict_iter, "subject", subject)) goto nomem; if (cert_hash && !wpa_dbus_dict_append_string(&dict_iter, "cert_hash", cert_hash)) goto nomem; if (cert && !wpa_dbus_dict_append_byte_array(&dict_iter, "cert", wpabuf_head(cert), wpabuf_len(cert))) goto nomem; if (!wpa_dbus_dict_close_write(&iter, &dict_iter)) goto nomem; dbus_connection_send(iface->con, msg, NULL); nomem: dbus_message_unref(msg); } void wpas_dbus_signal_eap_status(struct wpa_supplicant *wpa_s, const char *status, const char *parameter) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, "EAP"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &status) || !dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &parameter)) goto nomem; dbus_connection_send(iface->con, msg, NULL); nomem: dbus_message_unref(msg); } /** * wpas_dbus_signal_sta - Send a station related event signal * @wpa_s: %wpa_supplicant network interface data * @sta: station mac address * @sig_name: signal name - StaAuthorized or StaDeauthorized * * Notify listeners about event related with station */ static void wpas_dbus_signal_sta(struct wpa_supplicant *wpa_s, const u8 *sta, const char *sig_name) { struct wpas_dbus_priv *iface; DBusMessage *msg; char sta_mac[WPAS_DBUS_OBJECT_PATH_MAX]; char *dev_mac; os_snprintf(sta_mac, WPAS_DBUS_OBJECT_PATH_MAX, MACSTR, MAC2STR(sta)); dev_mac = sta_mac; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, sig_name); if (msg == NULL) return; if (dbus_message_append_args(msg, DBUS_TYPE_STRING, &dev_mac, DBUS_TYPE_INVALID)) dbus_connection_send(iface->con, msg, NULL); else wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); wpa_printf(MSG_DEBUG, "dbus: Station MAC address '%s' '%s'", sta_mac, sig_name); } /** * wpas_dbus_signal_sta_authorized - Send a STA authorized signal * @wpa_s: %wpa_supplicant network interface data * @sta: station mac address * * Notify listeners a new station has been authorized */ void wpas_dbus_signal_sta_authorized(struct wpa_supplicant *wpa_s, const u8 *sta) { wpas_dbus_signal_sta(wpa_s, sta, "StaAuthorized"); } /** * wpas_dbus_signal_sta_deauthorized - Send a STA deauthorized signal * @wpa_s: %wpa_supplicant network interface data * @sta: station mac address * * Notify listeners a station has been deauthorized */ void wpas_dbus_signal_sta_deauthorized(struct wpa_supplicant *wpa_s, const u8 *sta) { wpas_dbus_signal_sta(wpa_s, sta, "StaDeauthorized"); } #ifdef CONFIG_P2P /** * wpas_dbus_signal_p2p_group_removed - Signals P2P group was removed * @wpa_s: %wpa_supplicant network interface data * @role: role of this device (client or GO) * Sends signal with i/f name and role as string arguments */ void wpas_dbus_signal_p2p_group_removed(struct wpa_supplicant *wpa_s, const char *role) { int error = 1; DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; if (!wpa_s->dbus_groupobj_path) return; msg = dbus_message_new_signal(wpa_s->parent->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "GroupFinished"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto nomem; if (!wpa_dbus_dict_append_object_path(&dict_iter, "interface_object", wpa_s->dbus_new_path)) goto nomem; if (!wpa_dbus_dict_append_string(&dict_iter, "role", role)) goto nomem; if (!wpa_dbus_dict_append_object_path(&dict_iter, "group_object", wpa_s->dbus_groupobj_path) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) goto nomem; error = 0; dbus_connection_send(iface->con, msg, NULL); nomem: if (error > 0) wpa_printf(MSG_ERROR, "dbus: Failed to construct GroupFinished"); dbus_message_unref(msg); } /** * wpas_dbus_signal_p2p_provision_discovery - Signals various PD events * * @dev_addr - who sent the request or responded to our request. * @request - Will be 1 if request, 0 for response. * @status - valid only in case of response * @config_methods - wps config methods * @generated_pin - pin to be displayed in case of WPS_CONFIG_DISPLAY method * * Sends following provision discovery related events: * ProvisionDiscoveryRequestDisplayPin * ProvisionDiscoveryResponseDisplayPin * ProvisionDiscoveryRequestEnterPin * ProvisionDiscoveryResponseEnterPin * ProvisionDiscoveryPBCRequest * ProvisionDiscoveryPBCResponse * * TODO:: * ProvisionDiscoveryFailure (timeout case) */ void wpas_dbus_signal_p2p_provision_discovery(struct wpa_supplicant *wpa_s, const u8 *dev_addr, int request, enum p2p_prov_disc_status status, u16 config_methods, unsigned int generated_pin) { DBusMessage *msg; DBusMessageIter iter; struct wpas_dbus_priv *iface; char *_signal; int add_pin = 0; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; int error_ret = 1; char pin[9], *p_pin = NULL; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; if (request || !status) { if (config_methods & WPS_CONFIG_DISPLAY) _signal = request ? "ProvisionDiscoveryRequestDisplayPin" : "ProvisionDiscoveryResponseEnterPin"; else if (config_methods & WPS_CONFIG_KEYPAD) _signal = request ? "ProvisionDiscoveryRequestEnterPin" : "ProvisionDiscoveryResponseDisplayPin"; else if (config_methods & WPS_CONFIG_PUSHBUTTON) _signal = request ? "ProvisionDiscoveryPBCRequest" : "ProvisionDiscoveryPBCResponse"; else return; /* Unknown or un-supported method */ } else if (!request && status) /* Explicit check for failure response */ _signal = "ProvisionDiscoveryFailure"; add_pin = ((request && (config_methods & WPS_CONFIG_DISPLAY)) || (!request && !status && (config_methods & WPS_CONFIG_KEYPAD))); if (add_pin) { os_snprintf(pin, sizeof(pin), "%08d", generated_pin); p_pin = pin; } msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, _signal); if (msg == NULL) return; /* Check if this is a known peer */ if (!p2p_peer_known(wpa_s->global->p2p, dev_addr)) goto error; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(dev_addr)); path = peer_obj_path; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto error; if (!request && status) /* Attach status to ProvisionDiscoveryFailure */ error_ret = !dbus_message_iter_append_basic(&iter, DBUS_TYPE_INT32, &status); else error_ret = (add_pin && !dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &p_pin)); error: if (!error_ret) dbus_connection_send(iface->con, msg, NULL); else wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } void wpas_dbus_signal_p2p_go_neg_req(struct wpa_supplicant *wpa_s, const u8 *src, u16 dev_passwd_id) { DBusMessage *msg; DBusMessageIter iter; struct wpas_dbus_priv *iface; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(src)); path = peer_obj_path; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "GONegotiationRequest"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path) || !dbus_message_iter_append_basic(&iter, DBUS_TYPE_UINT16, &dev_passwd_id)) wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); else dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); } static int wpas_dbus_get_group_obj_path(struct wpa_supplicant *wpa_s, const struct wpa_ssid *ssid, char *group_obj_path) { char group_name[3]; if (os_memcmp(ssid->ssid, P2P_WILDCARD_SSID, P2P_WILDCARD_SSID_LEN)) return -1; os_memcpy(group_name, ssid->ssid + P2P_WILDCARD_SSID_LEN, 2); group_name[2] = '\0'; os_snprintf(group_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_GROUPS_PART "/%s", wpa_s->dbus_new_path, group_name); return 0; } struct group_changed_data { struct wpa_supplicant *wpa_s; struct p2p_peer_info *info; }; static int match_group_where_peer_is_client(struct p2p_group *group, void *user_data) { struct group_changed_data *data = user_data; const struct p2p_group_config *cfg; struct wpa_supplicant *wpa_s_go; if (!p2p_group_is_client_connected(group, data->info->p2p_device_addr)) return 1; cfg = p2p_group_get_config(group); wpa_s_go = wpas_get_p2p_go_iface(data->wpa_s, cfg->ssid, cfg->ssid_len); if (wpa_s_go != NULL && wpa_s_go == data->wpa_s) { wpas_dbus_signal_peer_groups_changed( data->wpa_s->parent, data->info->p2p_device_addr); return 0; } return 1; } static void signal_peer_groups_changed(struct p2p_peer_info *info, void *user_data) { struct group_changed_data *data = user_data; struct wpa_supplicant *wpa_s_go; wpa_s_go = wpas_get_p2p_client_iface(data->wpa_s, info->p2p_device_addr); if (wpa_s_go != NULL && wpa_s_go == data->wpa_s) { wpas_dbus_signal_peer_groups_changed(data->wpa_s->parent, info->p2p_device_addr); return; } data->info = info; p2p_loop_on_all_groups(data->wpa_s->global->p2p, match_group_where_peer_is_client, data); data->info = NULL; } static void peer_groups_changed(struct wpa_supplicant *wpa_s) { struct group_changed_data data; os_memset(&data, 0, sizeof(data)); data.wpa_s = wpa_s; p2p_loop_on_known_peers(wpa_s->global->p2p, signal_peer_groups_changed, &data); } /** * wpas_dbus_signal_p2p_group_started - Signals P2P group has * started. Emitted when a group is successfully started * irrespective of the role (client/GO) of the current device * * @wpa_s: %wpa_supplicant network interface data * @ssid: SSID object * @client: this device is P2P client * @network_id: network id of the group started, use instead of ssid->id * to account for persistent groups */ void wpas_dbus_signal_p2p_group_started(struct wpa_supplicant *wpa_s, const struct wpa_ssid *ssid, int client, int network_id) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; iface = wpa_s->parent->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; if (wpa_s->dbus_groupobj_path == NULL) return; /* New interface has been created for this group */ msg = dbus_message_new_signal(wpa_s->parent->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "GroupStarted"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto nomem; /* * In case the device supports creating a separate interface the * DBus client will need to know the object path for the interface * object this group was created on, so include it here. */ if (!wpa_dbus_dict_append_object_path(&dict_iter, "interface_object", wpa_s->dbus_new_path)) goto nomem; if (!wpa_dbus_dict_append_string(&dict_iter, "role", client ? "client" : "GO")) goto nomem; if (!wpa_dbus_dict_append_object_path(&dict_iter, "group_object", wpa_s->dbus_groupobj_path) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) goto nomem; dbus_connection_send(iface->con, msg, NULL); if (client) peer_groups_changed(wpa_s); nomem: dbus_message_unref(msg); } /** * * Method to emit GONegotiation Success or Failure signals based * on status. * @status: Status of the GO neg request. 0 for success, other for errors. */ void wpas_dbus_signal_p2p_go_neg_resp(struct wpa_supplicant *wpa_s, struct p2p_go_neg_results *res) { DBusMessage *msg; DBusMessageIter iter, dict_iter; DBusMessageIter iter_dict_entry, iter_dict_val, iter_dict_array; struct wpas_dbus_priv *iface; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; dbus_int32_t freqs[P2P_MAX_CHANNELS]; dbus_int32_t *f_array = freqs; iface = wpa_s->global->dbus; os_memset(freqs, 0, sizeof(freqs)); /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(res->peer_device_addr)); path = peer_obj_path; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, res->status ? "GONegotiationFailure" : "GONegotiationSuccess"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto err; if (!wpa_dbus_dict_append_object_path(&dict_iter, "peer_object", path) || !wpa_dbus_dict_append_int32(&dict_iter, "status", res->status)) goto err; if (!res->status) { int i = 0; int freq_list_num = 0; if (res->role_go) { if (!wpa_dbus_dict_append_byte_array( &dict_iter, "passphrase", (const char *) res->passphrase, sizeof(res->passphrase))) goto err; } if (!wpa_dbus_dict_append_string(&dict_iter, "role_go", res->role_go ? "GO" : "client") || !wpa_dbus_dict_append_int32(&dict_iter, "frequency", res->freq) || !wpa_dbus_dict_append_byte_array(&dict_iter, "ssid", (const char *) res->ssid, res->ssid_len) || !wpa_dbus_dict_append_byte_array(&dict_iter, "peer_device_addr", (const char *) res->peer_device_addr, ETH_ALEN) || !wpa_dbus_dict_append_byte_array(&dict_iter, "peer_interface_addr", (const char *) res->peer_interface_addr, ETH_ALEN) || !wpa_dbus_dict_append_string(&dict_iter, "wps_method", p2p_wps_method_text( res->wps_method))) goto err; for (i = 0; i < P2P_MAX_CHANNELS; i++) { if (res->freq_list[i]) { freqs[i] = res->freq_list[i]; freq_list_num++; } } if (!wpa_dbus_dict_begin_array(&dict_iter, "frequency_list", DBUS_TYPE_INT32_AS_STRING, &iter_dict_entry, &iter_dict_val, &iter_dict_array)) goto err; if (!dbus_message_iter_append_fixed_array(&iter_dict_array, DBUS_TYPE_INT32, &f_array, freq_list_num)) goto err; if (!wpa_dbus_dict_end_array(&dict_iter, &iter_dict_entry, &iter_dict_val, &iter_dict_array)) goto err; if (!wpa_dbus_dict_append_int32(&dict_iter, "persistent_group", res->persistent_group) || !wpa_dbus_dict_append_uint32(&dict_iter, "peer_config_timeout", res->peer_config_timeout)) goto err; } if (!wpa_dbus_dict_close_write(&iter, &dict_iter)) goto err; dbus_connection_send(iface->con, msg, NULL); err: dbus_message_unref(msg); } /** * * Method to emit Invitation Result signal based on status and * bssid * @status: Status of the Invite request. 0 for success, other * for errors * @bssid : Basic Service Set Identifier */ void wpas_dbus_signal_p2p_invitation_result(struct wpa_supplicant *wpa_s, int status, const u8 *bssid) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; wpa_printf(MSG_DEBUG, "%s", __func__); iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "InvitationResult"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto nomem; if (!wpa_dbus_dict_append_int32(&dict_iter, "status", status)) goto nomem; if (bssid) { if (!wpa_dbus_dict_append_byte_array(&dict_iter, "BSSID", (const char *) bssid, ETH_ALEN)) goto nomem; } if (!wpa_dbus_dict_close_write(&iter, &dict_iter)) goto nomem; dbus_connection_send(iface->con, msg, NULL); nomem: dbus_message_unref(msg); } /** * * Method to emit a signal for a peer joining the group. * The signal will carry path to the group member object * constructed using p2p i/f addr used for connecting. * * @wpa_s: %wpa_supplicant network interface data * @peer_addr: P2P Device Address of the peer joining the group */ void wpas_dbus_signal_p2p_peer_joined(struct wpa_supplicant *wpa_s, const u8 *peer_addr) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; if (!wpa_s->dbus_groupobj_path) return; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->parent->dbus_new_path, MAC2STR(peer_addr)); msg = dbus_message_new_signal(wpa_s->dbus_groupobj_path, WPAS_DBUS_NEW_IFACE_P2P_GROUP, "PeerJoined"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); path = peer_obj_path; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto err; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); wpas_dbus_signal_peer_groups_changed(wpa_s->parent, peer_addr); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * * Method to emit a signal for a peer disconnecting the group. * The signal will carry path to the group member object * constructed using the P2P Device Address of the peer. * * @wpa_s: %wpa_supplicant network interface data * @peer_addr: P2P Device Address of the peer joining the group */ void wpas_dbus_signal_p2p_peer_disconnected(struct wpa_supplicant *wpa_s, const u8 *peer_addr) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; if (!wpa_s->dbus_groupobj_path) return; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_groupobj_path, MAC2STR(peer_addr)); msg = dbus_message_new_signal(wpa_s->dbus_groupobj_path, WPAS_DBUS_NEW_IFACE_P2P_GROUP, "PeerDisconnected"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); path = peer_obj_path; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto err; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); wpas_dbus_signal_peer_groups_changed(wpa_s->parent, peer_addr); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct PeerDisconnected " "signal"); dbus_message_unref(msg); } /** * * Method to emit a signal for a service discovery request. * The signal will carry station address, frequency, dialog token, * update indicator and it tlvs * * @wpa_s: %wpa_supplicant network interface data * @sa: station addr (p2p i/f) of the peer * @dialog_token: service discovery request dialog token * @update_indic: service discovery request update indicator * @tlvs: service discovery request genrated byte array of tlvs * @tlvs_len: service discovery request tlvs length */ void wpas_dbus_signal_p2p_sd_request(struct wpa_supplicant *wpa_s, int freq, const u8 *sa, u8 dialog_token, u16 update_indic, const u8 *tlvs, size_t tlvs_len) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "ServiceDiscoveryRequest"); if (msg == NULL) return; /* Check if this is a known peer */ if (!p2p_peer_known(wpa_s->global->p2p, sa)) goto error; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(sa)); path = peer_obj_path; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto error; if (!wpa_dbus_dict_append_object_path(&dict_iter, "peer_object", path) || !wpa_dbus_dict_append_int32(&dict_iter, "frequency", freq) || !wpa_dbus_dict_append_int32(&dict_iter, "dialog_token", dialog_token) || !wpa_dbus_dict_append_uint16(&dict_iter, "update_indicator", update_indic) || !wpa_dbus_dict_append_byte_array(&dict_iter, "tlvs", (const char *) tlvs, tlvs_len) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) goto error; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; error: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * * Method to emit a signal for a service discovery response. * The signal will carry station address, update indicator and it * tlvs * * @wpa_s: %wpa_supplicant network interface data * @sa: station addr (p2p i/f) of the peer * @update_indic: service discovery request update indicator * @tlvs: service discovery request genrated byte array of tlvs * @tlvs_len: service discovery request tlvs length */ void wpas_dbus_signal_p2p_sd_response(struct wpa_supplicant *wpa_s, const u8 *sa, u16 update_indic, const u8 *tlvs, size_t tlvs_len) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "ServiceDiscoveryResponse"); if (msg == NULL) return; /* Check if this is a known peer */ if (!p2p_peer_known(wpa_s->global->p2p, sa)) goto error; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(sa)); path = peer_obj_path; dbus_message_iter_init_append(msg, &iter); if (!wpa_dbus_dict_open_write(&iter, &dict_iter)) goto error; if (!wpa_dbus_dict_append_object_path(&dict_iter, "peer_object", path) || !wpa_dbus_dict_append_uint16(&dict_iter, "update_indicator", update_indic) || !wpa_dbus_dict_append_byte_array(&dict_iter, "tlvs", (const char *) tlvs, tlvs_len) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) goto error; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; error: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_persistent_group - Send a persistent group related * event signal * @wpa_s: %wpa_supplicant network interface data * @id: new persistent group id * @sig_name: signal name - PersistentGroupAdded, PersistentGroupRemoved * @properties: determines if add second argument with object properties * * Notify listeners about an event related to persistent groups. */ static void wpas_dbus_signal_persistent_group(struct wpa_supplicant *wpa_s, int id, const char *sig_name, int properties) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char pgrp_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; os_snprintf(pgrp_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_PERSISTENT_GROUPS_PART "/%u", wpa_s->dbus_new_path, id); msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, sig_name); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); path = pgrp_obj_path; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto err; if (properties) { if (!wpa_dbus_get_object_properties( iface, pgrp_obj_path, WPAS_DBUS_NEW_IFACE_PERSISTENT_GROUP, &iter)) goto err; } dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_persistent_group_added - Send a persistent_group * added signal * @wpa_s: %wpa_supplicant network interface data * @id: new persistent group id * * Notify listeners about addition of a new persistent group. */ static void wpas_dbus_signal_persistent_group_added( struct wpa_supplicant *wpa_s, int id) { wpas_dbus_signal_persistent_group(wpa_s, id, "PersistentGroupAdded", TRUE); } /** * wpas_dbus_signal_persistent_group_removed - Send a persistent_group * removed signal * @wpa_s: %wpa_supplicant network interface data * @id: persistent group id * * Notify listeners about removal of a persistent group. */ static void wpas_dbus_signal_persistent_group_removed( struct wpa_supplicant *wpa_s, int id) { wpas_dbus_signal_persistent_group(wpa_s, id, "PersistentGroupRemoved", FALSE); } /** * wpas_dbus_signal_p2p_wps_failed - Signals WpsFailed event * @wpa_s: %wpa_supplicant network interface data * * Sends Event dbus signal with name "fail" and dictionary containing * "msg" field with fail message number (int32) as arguments */ void wpas_dbus_signal_p2p_wps_failed(struct wpa_supplicant *wpa_s, struct wps_event_fail *fail) { DBusMessage *msg; DBusMessageIter iter, dict_iter; struct wpas_dbus_priv *iface; char *key = "fail"; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; msg = dbus_message_new_signal(wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "WpsFailed"); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &key) || !wpa_dbus_dict_open_write(&iter, &dict_iter) || !wpa_dbus_dict_append_int32(&dict_iter, "msg", fail->msg) || !wpa_dbus_dict_append_int16(&dict_iter, "config_error", fail->config_error) || !wpa_dbus_dict_close_write(&iter, &dict_iter)) wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); else dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); } #endif /*CONFIG_P2P*/ /** * wpas_dbus_signal_prop_changed - Signals change of property * @wpa_s: %wpa_supplicant network interface data * @property: indicates which property has changed * * Sends PropertyChanged signals with path, interface and arguments * depending on which property has changed. */ void wpas_dbus_signal_prop_changed(struct wpa_supplicant *wpa_s, enum wpas_dbus_prop property) { char *prop; dbus_bool_t flush; if (wpa_s->dbus_new_path == NULL) return; /* Skip signal since D-Bus setup is not yet ready */ flush = FALSE; switch (property) { case WPAS_DBUS_PROP_AP_SCAN: prop = "ApScan"; break; case WPAS_DBUS_PROP_SCANNING: prop = "Scanning"; break; case WPAS_DBUS_PROP_STATE: prop = "State"; break; case WPAS_DBUS_PROP_CURRENT_BSS: prop = "CurrentBSS"; break; case WPAS_DBUS_PROP_CURRENT_NETWORK: prop = "CurrentNetwork"; break; case WPAS_DBUS_PROP_BSSS: prop = "BSSs"; break; case WPAS_DBUS_PROP_CURRENT_AUTH_MODE: prop = "CurrentAuthMode"; break; case WPAS_DBUS_PROP_DISCONNECT_REASON: prop = "DisconnectReason"; flush = TRUE; break; default: wpa_printf(MSG_ERROR, "dbus: %s: Unknown Property value %d", __func__, property); return; } wpa_dbus_mark_property_changed(wpa_s->global->dbus, wpa_s->dbus_new_path, WPAS_DBUS_NEW_IFACE_INTERFACE, prop); if (flush) { wpa_dbus_flush_object_changed_properties( wpa_s->global->dbus->con, wpa_s->dbus_new_path); } } /** * wpas_dbus_bss_signal_prop_changed - Signals change of BSS property * @wpa_s: %wpa_supplicant network interface data * @property: indicates which property has changed * @id: unique BSS identifier * * Sends PropertyChanged signals with path, interface, and arguments depending * on which property has changed. */ void wpas_dbus_bss_signal_prop_changed(struct wpa_supplicant *wpa_s, enum wpas_dbus_bss_prop property, unsigned int id) { char path[WPAS_DBUS_OBJECT_PATH_MAX]; char *prop; switch (property) { case WPAS_DBUS_BSS_PROP_SIGNAL: prop = "Signal"; break; case WPAS_DBUS_BSS_PROP_FREQ: prop = "Frequency"; break; case WPAS_DBUS_BSS_PROP_MODE: prop = "Mode"; break; case WPAS_DBUS_BSS_PROP_PRIVACY: prop = "Privacy"; break; case WPAS_DBUS_BSS_PROP_RATES: prop = "Rates"; break; case WPAS_DBUS_BSS_PROP_WPA: prop = "WPA"; break; case WPAS_DBUS_BSS_PROP_RSN: prop = "RSN"; break; case WPAS_DBUS_BSS_PROP_WPS: prop = "WPS"; break; case WPAS_DBUS_BSS_PROP_IES: prop = "IEs"; break; default: wpa_printf(MSG_ERROR, "dbus: %s: Unknown Property value %d", __func__, property); return; } os_snprintf(path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_BSSIDS_PART "/%u", wpa_s->dbus_new_path, id); wpa_dbus_mark_property_changed(wpa_s->global->dbus, path, WPAS_DBUS_NEW_IFACE_BSS, prop); } /** * wpas_dbus_signal_debug_level_changed - Signals change of debug param * @global: wpa_global structure * * Sends PropertyChanged signals informing that debug level has changed. */ void wpas_dbus_signal_debug_level_changed(struct wpa_global *global) { wpa_dbus_mark_property_changed(global->dbus, WPAS_DBUS_NEW_PATH, WPAS_DBUS_NEW_INTERFACE, "DebugLevel"); } /** * wpas_dbus_signal_debug_timestamp_changed - Signals change of debug param * @global: wpa_global structure * * Sends PropertyChanged signals informing that debug timestamp has changed. */ void wpas_dbus_signal_debug_timestamp_changed(struct wpa_global *global) { wpa_dbus_mark_property_changed(global->dbus, WPAS_DBUS_NEW_PATH, WPAS_DBUS_NEW_INTERFACE, "DebugTimestamp"); } /** * wpas_dbus_signal_debug_show_keys_changed - Signals change of debug param * @global: wpa_global structure * * Sends PropertyChanged signals informing that debug show_keys has changed. */ void wpas_dbus_signal_debug_show_keys_changed(struct wpa_global *global) { wpa_dbus_mark_property_changed(global->dbus, WPAS_DBUS_NEW_PATH, WPAS_DBUS_NEW_INTERFACE, "DebugShowKeys"); } static void wpas_dbus_register(struct wpa_dbus_object_desc *obj_desc, void *priv, WPADBusArgumentFreeFunction priv_free, const struct wpa_dbus_method_desc *methods, const struct wpa_dbus_property_desc *properties, const struct wpa_dbus_signal_desc *signals) { int n; obj_desc->user_data = priv; obj_desc->user_data_free_func = priv_free; obj_desc->methods = methods; obj_desc->properties = properties; obj_desc->signals = signals; for (n = 0; properties && properties->dbus_property; properties++) n++; obj_desc->prop_changed_flags = os_zalloc(n); if (!obj_desc->prop_changed_flags) wpa_printf(MSG_DEBUG, "dbus: %s: can't register handlers", __func__); } static const struct wpa_dbus_method_desc wpas_dbus_global_methods[] = { { "CreateInterface", WPAS_DBUS_NEW_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_create_interface, { { "args", "a{sv}", ARG_IN }, { "path", "o", ARG_OUT }, END_ARGS } }, { "RemoveInterface", WPAS_DBUS_NEW_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_remove_interface, { { "path", "o", ARG_IN }, END_ARGS } }, { "GetInterface", WPAS_DBUS_NEW_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_get_interface, { { "ifname", "s", ARG_IN }, { "path", "o", ARG_OUT }, END_ARGS } }, { NULL, NULL, NULL, { END_ARGS } } }; static const struct wpa_dbus_property_desc wpas_dbus_global_properties[] = { { "DebugLevel", WPAS_DBUS_NEW_INTERFACE, "s", wpas_dbus_getter_debug_level, wpas_dbus_setter_debug_level }, { "DebugTimestamp", WPAS_DBUS_NEW_INTERFACE, "b", wpas_dbus_getter_debug_timestamp, wpas_dbus_setter_debug_timestamp }, { "DebugShowKeys", WPAS_DBUS_NEW_INTERFACE, "b", wpas_dbus_getter_debug_show_keys, wpas_dbus_setter_debug_show_keys }, { "Interfaces", WPAS_DBUS_NEW_INTERFACE, "ao", wpas_dbus_getter_interfaces, NULL }, { "EapMethods", WPAS_DBUS_NEW_INTERFACE, "as", wpas_dbus_getter_eap_methods, NULL }, { "Capabilities", WPAS_DBUS_NEW_INTERFACE, "as", wpas_dbus_getter_global_capabilities, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_global_signals[] = { { "InterfaceAdded", WPAS_DBUS_NEW_INTERFACE, { { "path", "o", ARG_OUT }, { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "InterfaceRemoved", WPAS_DBUS_NEW_INTERFACE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "NetworkRequest", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, { "field", "s", ARG_OUT }, { "text", "s", ARG_OUT }, END_ARGS } }, /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_INTERFACE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; /** * wpas_dbus_ctrl_iface_init - Initialize dbus control interface * @global: Pointer to global data from wpa_supplicant_init() * Returns: 0 on success or -1 on failure * * Initialize the dbus control interface for wpa_supplicantand and start * receiving commands from external programs over the bus. */ int wpas_dbus_ctrl_iface_init(struct wpas_dbus_priv *priv) { struct wpa_dbus_object_desc *obj_desc; int ret; obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); return -1; } wpas_dbus_register(obj_desc, priv->global, NULL, wpas_dbus_global_methods, wpas_dbus_global_properties, wpas_dbus_global_signals); wpa_printf(MSG_DEBUG, "dbus: Register D-Bus object '%s'", WPAS_DBUS_NEW_PATH); ret = wpa_dbus_ctrl_iface_init(priv, WPAS_DBUS_NEW_PATH, WPAS_DBUS_NEW_SERVICE, obj_desc); if (ret < 0) free_dbus_object_desc(obj_desc); else priv->dbus_new_initialized = 1; return ret; } /** * wpas_dbus_ctrl_iface_deinit - Deinitialize dbus ctrl interface for * wpa_supplicant * @iface: Pointer to dbus private data from wpas_dbus_init() * * Deinitialize the dbus control interface that was initialized with * wpas_dbus_ctrl_iface_init(). */ void wpas_dbus_ctrl_iface_deinit(struct wpas_dbus_priv *iface) { if (!iface->dbus_new_initialized) return; wpa_printf(MSG_DEBUG, "dbus: Unregister D-Bus object '%s'", WPAS_DBUS_NEW_PATH); dbus_connection_unregister_object_path(iface->con, WPAS_DBUS_NEW_PATH); } static void wpa_dbus_free(void *ptr) { os_free(ptr); } static const struct wpa_dbus_property_desc wpas_dbus_network_properties[] = { { "Properties", WPAS_DBUS_NEW_IFACE_NETWORK, "a{sv}", wpas_dbus_getter_network_properties, wpas_dbus_setter_network_properties }, { "Enabled", WPAS_DBUS_NEW_IFACE_NETWORK, "b", wpas_dbus_getter_enabled, wpas_dbus_setter_enabled }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_network_signals[] = { /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_IFACE_NETWORK, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; /** * wpas_dbus_register_network - Register a configured network with dbus * @wpa_s: wpa_supplicant interface structure * @ssid: network configuration data * Returns: 0 on success, -1 on failure * * Registers network representing object with dbus */ int wpas_dbus_register_network(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid) { struct wpas_dbus_priv *ctrl_iface; struct wpa_dbus_object_desc *obj_desc; struct network_handler_args *arg; char net_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; #ifdef CONFIG_P2P /* * If it is a persistent group register it as such. * This is to handle cases where an interface is being initialized * with a list of networks read from config. */ if (network_is_persistent_group(ssid)) return wpas_dbus_register_persistent_group(wpa_s, ssid); #endif /* CONFIG_P2P */ /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(net_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_NETWORKS_PART "/%u", wpa_s->dbus_new_path, ssid->id); wpa_printf(MSG_DEBUG, "dbus: Register network object '%s'", net_obj_path); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); goto err; } /* allocate memory for handlers arguments */ arg = os_zalloc(sizeof(struct network_handler_args)); if (!arg) { wpa_printf(MSG_ERROR, "Not enough memory " "to create arguments for method"); goto err; } arg->wpa_s = wpa_s; arg->ssid = ssid; wpas_dbus_register(obj_desc, arg, wpa_dbus_free, NULL, wpas_dbus_network_properties, wpas_dbus_network_signals); if (wpa_dbus_register_object_per_iface(ctrl_iface, net_obj_path, wpa_s->ifname, obj_desc)) goto err; wpas_dbus_signal_network_added(wpa_s, ssid->id); return 0; err: free_dbus_object_desc(obj_desc); return -1; } /** * wpas_dbus_unregister_network - Unregister a configured network from dbus * @wpa_s: wpa_supplicant interface structure * @nid: network id * Returns: 0 on success, -1 on failure * * Unregisters network representing object from dbus */ int wpas_dbus_unregister_network(struct wpa_supplicant *wpa_s, int nid) { struct wpas_dbus_priv *ctrl_iface; char net_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; int ret; #ifdef CONFIG_P2P struct wpa_ssid *ssid; ssid = wpa_config_get_network(wpa_s->conf, nid); /* If it is a persistent group unregister it as such */ if (ssid && network_is_persistent_group(ssid)) return wpas_dbus_unregister_persistent_group(wpa_s, nid); #endif /* CONFIG_P2P */ /* Do nothing if the control interface is not turned on */ if (wpa_s->global == NULL || wpa_s->dbus_new_path == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(net_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_NETWORKS_PART "/%u", wpa_s->dbus_new_path, nid); wpa_printf(MSG_DEBUG, "dbus: Unregister network object '%s'", net_obj_path); ret = wpa_dbus_unregister_object_per_iface(ctrl_iface, net_obj_path); if (!ret) wpas_dbus_signal_network_removed(wpa_s, nid); return ret; } static const struct wpa_dbus_property_desc wpas_dbus_bss_properties[] = { { "SSID", WPAS_DBUS_NEW_IFACE_BSS, "ay", wpas_dbus_getter_bss_ssid, NULL }, { "BSSID", WPAS_DBUS_NEW_IFACE_BSS, "ay", wpas_dbus_getter_bss_bssid, NULL }, { "Privacy", WPAS_DBUS_NEW_IFACE_BSS, "b", wpas_dbus_getter_bss_privacy, NULL }, { "Mode", WPAS_DBUS_NEW_IFACE_BSS, "s", wpas_dbus_getter_bss_mode, NULL }, { "Signal", WPAS_DBUS_NEW_IFACE_BSS, "n", wpas_dbus_getter_bss_signal, NULL }, { "Frequency", WPAS_DBUS_NEW_IFACE_BSS, "q", wpas_dbus_getter_bss_frequency, NULL }, { "Rates", WPAS_DBUS_NEW_IFACE_BSS, "au", wpas_dbus_getter_bss_rates, NULL }, { "WPA", WPAS_DBUS_NEW_IFACE_BSS, "a{sv}", wpas_dbus_getter_bss_wpa, NULL }, { "RSN", WPAS_DBUS_NEW_IFACE_BSS, "a{sv}", wpas_dbus_getter_bss_rsn, NULL }, { "WPS", WPAS_DBUS_NEW_IFACE_BSS, "a{sv}", wpas_dbus_getter_bss_wps, NULL }, { "IEs", WPAS_DBUS_NEW_IFACE_BSS, "ay", wpas_dbus_getter_bss_ies, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_bss_signals[] = { /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_IFACE_BSS, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; /** * wpas_dbus_unregister_bss - Unregister a scanned BSS from dbus * @wpa_s: wpa_supplicant interface structure * @bssid: scanned network bssid * @id: unique BSS identifier * Returns: 0 on success, -1 on failure * * Unregisters BSS representing object from dbus */ int wpas_dbus_unregister_bss(struct wpa_supplicant *wpa_s, u8 bssid[ETH_ALEN], unsigned int id) { struct wpas_dbus_priv *ctrl_iface; char bss_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(bss_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_BSSIDS_PART "/%u", wpa_s->dbus_new_path, id); wpa_printf(MSG_DEBUG, "dbus: Unregister BSS object '%s'", bss_obj_path); if (wpa_dbus_unregister_object_per_iface(ctrl_iface, bss_obj_path)) { wpa_printf(MSG_ERROR, "dbus: Cannot unregister BSS object %s", bss_obj_path); return -1; } wpas_dbus_signal_bss_removed(wpa_s, bss_obj_path); wpas_dbus_signal_prop_changed(wpa_s, WPAS_DBUS_PROP_BSSS); return 0; } /** * wpas_dbus_register_bss - Register a scanned BSS with dbus * @wpa_s: wpa_supplicant interface structure * @bssid: scanned network bssid * @id: unique BSS identifier * Returns: 0 on success, -1 on failure * * Registers BSS representing object with dbus */ int wpas_dbus_register_bss(struct wpa_supplicant *wpa_s, u8 bssid[ETH_ALEN], unsigned int id) { struct wpas_dbus_priv *ctrl_iface; struct wpa_dbus_object_desc *obj_desc; char bss_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; struct bss_handler_args *arg; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(bss_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_BSSIDS_PART "/%u", wpa_s->dbus_new_path, id); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); goto err; } arg = os_zalloc(sizeof(struct bss_handler_args)); if (!arg) { wpa_printf(MSG_ERROR, "Not enough memory " "to create arguments for handler"); goto err; } arg->wpa_s = wpa_s; arg->id = id; wpas_dbus_register(obj_desc, arg, wpa_dbus_free, NULL, wpas_dbus_bss_properties, wpas_dbus_bss_signals); wpa_printf(MSG_DEBUG, "dbus: Register BSS object '%s'", bss_obj_path); if (wpa_dbus_register_object_per_iface(ctrl_iface, bss_obj_path, wpa_s->ifname, obj_desc)) { wpa_printf(MSG_ERROR, "Cannot register BSSID dbus object %s.", bss_obj_path); goto err; } wpas_dbus_signal_bss_added(wpa_s, bss_obj_path); wpas_dbus_signal_prop_changed(wpa_s, WPAS_DBUS_PROP_BSSS); return 0; err: free_dbus_object_desc(obj_desc); return -1; } static const struct wpa_dbus_method_desc wpas_dbus_interface_methods[] = { { "Scan", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_scan, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "Disconnect", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_disconnect, { END_ARGS } }, { "AddNetwork", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_add_network, { { "args", "a{sv}", ARG_IN }, { "path", "o", ARG_OUT }, END_ARGS } }, { "Reassociate", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_reassociate, { END_ARGS } }, { "Reattach", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_reattach, { END_ARGS } }, { "RemoveNetwork", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_remove_network, { { "path", "o", ARG_IN }, END_ARGS } }, { "RemoveAllNetworks", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_remove_all_networks, { END_ARGS } }, { "SelectNetwork", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_select_network, { { "path", "o", ARG_IN }, END_ARGS } }, { "NetworkReply", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_network_reply, { { "path", "o", ARG_IN }, { "field", "s", ARG_IN }, { "value", "s", ARG_IN }, END_ARGS } }, #ifndef CONFIG_NO_CONFIG_BLOBS { "AddBlob", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_add_blob, { { "name", "s", ARG_IN }, { "data", "ay", ARG_IN }, END_ARGS } }, { "GetBlob", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_get_blob, { { "name", "s", ARG_IN }, { "data", "ay", ARG_OUT }, END_ARGS } }, { "RemoveBlob", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_remove_blob, { { "name", "s", ARG_IN }, END_ARGS } }, #endif /* CONFIG_NO_CONFIG_BLOBS */ { "SetPKCS11EngineAndModulePath", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_set_pkcs11_engine_and_module_path, { { "pkcs11_engine_path", "s", ARG_IN }, { "pkcs11_module_path", "s", ARG_IN }, END_ARGS } }, #ifdef CONFIG_WPS { "Start", WPAS_DBUS_NEW_IFACE_WPS, (WPADBusMethodHandler) &wpas_dbus_handler_wps_start, { { "args", "a{sv}", ARG_IN }, { "output", "a{sv}", ARG_OUT }, END_ARGS } }, #endif /* CONFIG_WPS */ #ifdef CONFIG_P2P { "Find", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_find, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "StopFind", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_stop_find, { END_ARGS } }, { "Listen", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_listen, { { "timeout", "i", ARG_IN }, END_ARGS } }, { "ExtendedListen", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_extendedlisten, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "PresenceRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_presence_request, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "ProvisionDiscoveryRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_prov_disc_req, { { "peer", "o", ARG_IN }, { "config_method", "s", ARG_IN }, END_ARGS } }, { "Connect", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_connect, { { "args", "a{sv}", ARG_IN }, { "generated_pin", "s", ARG_OUT }, END_ARGS } }, { "GroupAdd", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_group_add, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "Invite", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_invite, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "Disconnect", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_disconnect, { END_ARGS } }, { "RejectPeer", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_rejectpeer, { { "peer", "o", ARG_IN }, END_ARGS } }, { "Flush", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_flush, { END_ARGS } }, { "AddService", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_add_service, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "DeleteService", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_delete_service, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "FlushService", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_flush_service, { END_ARGS } }, { "ServiceDiscoveryRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_service_sd_req, { { "args", "a{sv}", ARG_IN }, { "ref", "t", ARG_OUT }, END_ARGS } }, { "ServiceDiscoveryResponse", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_service_sd_res, { { "args", "a{sv}", ARG_IN }, END_ARGS } }, { "ServiceDiscoveryCancelRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_service_sd_cancel_req, { { "args", "t", ARG_IN }, END_ARGS } }, { "ServiceUpdate", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_service_update, { END_ARGS } }, { "ServiceDiscoveryExternal", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler)wpas_dbus_handler_p2p_serv_disc_external, { { "arg", "i", ARG_IN }, END_ARGS } }, { "AddPersistentGroup", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler) wpas_dbus_handler_add_persistent_group, { { "args", "a{sv}", ARG_IN }, { "path", "o", ARG_OUT }, END_ARGS } }, { "RemovePersistentGroup", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler) wpas_dbus_handler_remove_persistent_group, { { "path", "o", ARG_IN }, END_ARGS } }, { "RemoveAllPersistentGroups", WPAS_DBUS_NEW_IFACE_P2PDEVICE, (WPADBusMethodHandler) wpas_dbus_handler_remove_all_persistent_groups, { END_ARGS } }, #endif /* CONFIG_P2P */ { "FlushBSS", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_flush_bss, { { "age", "u", ARG_IN }, END_ARGS } }, #ifdef CONFIG_AP { "SubscribeProbeReq", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_subscribe_preq, { END_ARGS } }, { "UnsubscribeProbeReq", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_unsubscribe_preq, { END_ARGS } }, #endif /* CONFIG_AP */ { "EAPLogoff", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_eap_logoff, { END_ARGS } }, { "EAPLogon", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_eap_logon, { END_ARGS } }, #ifdef CONFIG_AUTOSCAN { "AutoScan", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) &wpas_dbus_handler_autoscan, { { "arg", "s", ARG_IN }, END_ARGS } }, #endif /* CONFIG_AUTOSCAN */ #ifdef CONFIG_TDLS { "TDLSDiscover", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_tdls_discover, { { "peer_address", "s", ARG_IN }, END_ARGS } }, { "TDLSSetup", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_tdls_setup, { { "peer_address", "s", ARG_IN }, END_ARGS } }, { "TDLSStatus", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_tdls_status, { { "peer_address", "s", ARG_IN }, { "status", "s", ARG_OUT }, END_ARGS } }, { "TDLSTeardown", WPAS_DBUS_NEW_IFACE_INTERFACE, (WPADBusMethodHandler) wpas_dbus_handler_tdls_teardown, { { "peer_address", "s", ARG_IN }, END_ARGS } }, #endif /* CONFIG_TDLS */ { NULL, NULL, NULL, { END_ARGS } } }; static const struct wpa_dbus_property_desc wpas_dbus_interface_properties[] = { { "Capabilities", WPAS_DBUS_NEW_IFACE_INTERFACE, "a{sv}", wpas_dbus_getter_capabilities, NULL }, { "State", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_state, NULL }, { "Scanning", WPAS_DBUS_NEW_IFACE_INTERFACE, "b", wpas_dbus_getter_scanning, NULL }, { "ApScan", WPAS_DBUS_NEW_IFACE_INTERFACE, "u", wpas_dbus_getter_ap_scan, wpas_dbus_setter_ap_scan }, { "BSSExpireAge", WPAS_DBUS_NEW_IFACE_INTERFACE, "u", wpas_dbus_getter_bss_expire_age, wpas_dbus_setter_bss_expire_age }, { "BSSExpireCount", WPAS_DBUS_NEW_IFACE_INTERFACE, "u", wpas_dbus_getter_bss_expire_count, wpas_dbus_setter_bss_expire_count }, { "Country", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_country, wpas_dbus_setter_country }, { "Ifname", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_ifname, NULL }, { "Driver", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_driver, NULL }, { "BridgeIfname", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_bridge_ifname, NULL }, { "CurrentBSS", WPAS_DBUS_NEW_IFACE_INTERFACE, "o", wpas_dbus_getter_current_bss, NULL }, { "CurrentNetwork", WPAS_DBUS_NEW_IFACE_INTERFACE, "o", wpas_dbus_getter_current_network, NULL }, { "CurrentAuthMode", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_current_auth_mode, NULL }, { "Blobs", WPAS_DBUS_NEW_IFACE_INTERFACE, "a{say}", wpas_dbus_getter_blobs, NULL }, { "BSSs", WPAS_DBUS_NEW_IFACE_INTERFACE, "ao", wpas_dbus_getter_bsss, NULL }, { "Networks", WPAS_DBUS_NEW_IFACE_INTERFACE, "ao", wpas_dbus_getter_networks, NULL }, { "FastReauth", WPAS_DBUS_NEW_IFACE_INTERFACE, "b", wpas_dbus_getter_fast_reauth, wpas_dbus_setter_fast_reauth }, { "ScanInterval", WPAS_DBUS_NEW_IFACE_INTERFACE, "i", wpas_dbus_getter_scan_interval, wpas_dbus_setter_scan_interval }, { "PKCS11EnginePath", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_pkcs11_engine_path, NULL }, { "PKCS11ModulePath", WPAS_DBUS_NEW_IFACE_INTERFACE, "s", wpas_dbus_getter_pkcs11_module_path, NULL }, #ifdef CONFIG_WPS { "ProcessCredentials", WPAS_DBUS_NEW_IFACE_WPS, "b", wpas_dbus_getter_process_credentials, wpas_dbus_setter_process_credentials }, #endif /* CONFIG_WPS */ #ifdef CONFIG_P2P { "P2PDeviceConfig", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "a{sv}", wpas_dbus_getter_p2p_device_config, wpas_dbus_setter_p2p_device_config }, { "Peers", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "ao", wpas_dbus_getter_p2p_peers, NULL }, { "Role", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "s", wpas_dbus_getter_p2p_role, NULL }, { "Group", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "o", wpas_dbus_getter_p2p_group, NULL }, { "PeerGO", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "o", wpas_dbus_getter_p2p_peergo, NULL }, { "PersistentGroups", WPAS_DBUS_NEW_IFACE_P2PDEVICE, "ao", wpas_dbus_getter_persistent_groups, NULL }, #endif /* CONFIG_P2P */ { "DisconnectReason", WPAS_DBUS_NEW_IFACE_INTERFACE, "i", wpas_dbus_getter_disconnect_reason, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_interface_signals[] = { { "ScanDone", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "success", "b", ARG_OUT }, END_ARGS } }, { "BSSAdded", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "BSSRemoved", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "BlobAdded", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "name", "s", ARG_OUT }, END_ARGS } }, { "BlobRemoved", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "name", "s", ARG_OUT }, END_ARGS } }, { "NetworkAdded", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "NetworkRemoved", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "NetworkSelected", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "path", "o", ARG_OUT }, END_ARGS } }, /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, #ifdef CONFIG_WPS { "Event", WPAS_DBUS_NEW_IFACE_WPS, { { "name", "s", ARG_OUT }, { "args", "a{sv}", ARG_OUT }, END_ARGS } }, { "Credentials", WPAS_DBUS_NEW_IFACE_WPS, { { "credentials", "a{sv}", ARG_OUT }, END_ARGS } }, /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_IFACE_WPS, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, #endif /* CONFIG_WPS */ #ifdef CONFIG_P2P { "P2PStateChanged", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "states", "a{ss}", ARG_OUT }, END_ARGS } }, { "DeviceFound", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "DeviceLost", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryRequestDisplayPin", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, { "pin", "s", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryResponseDisplayPin", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, { "pin", "s", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryRequestEnterPin", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryResponseEnterPin", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryPBCRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryPBCResponse", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, END_ARGS } }, { "ProvisionDiscoveryFailure", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "peer_object", "o", ARG_OUT }, { "status", "i", ARG_OUT }, END_ARGS } }, { "GroupStarted", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "GONegotiationSuccess", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "GONegotiationFailure", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "GONegotiationRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "path", "o", ARG_OUT }, { "dev_passwd_id", "i", ARG_OUT }, END_ARGS } }, { "InvitationResult", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "invite_result", "a{sv}", ARG_OUT }, END_ARGS } }, { "GroupFinished", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "ServiceDiscoveryRequest", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "sd_request", "a{sv}", ARG_OUT }, END_ARGS } }, { "ServiceDiscoveryResponse", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "sd_response", "a{sv}", ARG_OUT }, END_ARGS } }, { "PersistentGroupAdded", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "path", "o", ARG_OUT }, { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { "PersistentGroupRemoved", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "path", "o", ARG_OUT }, END_ARGS } }, { "WpsFailed", WPAS_DBUS_NEW_IFACE_P2PDEVICE, { { "name", "s", ARG_OUT }, { "args", "a{sv}", ARG_OUT }, END_ARGS } }, #endif /* CONFIG_P2P */ #ifdef CONFIG_AP { "ProbeRequest", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "args", "a{sv}", ARG_OUT }, END_ARGS } }, #endif /* CONFIG_AP */ { "Certification", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "certification", "a{sv}", ARG_OUT }, END_ARGS } }, { "EAP", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "status", "s", ARG_OUT }, { "parameter", "s", ARG_OUT }, END_ARGS } }, { "StaAuthorized", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "name", "s", ARG_OUT }, END_ARGS } }, { "StaDeauthorized", WPAS_DBUS_NEW_IFACE_INTERFACE, { { "name", "s", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; int wpas_dbus_register_interface(struct wpa_supplicant *wpa_s) { struct wpa_dbus_object_desc *obj_desc = NULL; struct wpas_dbus_priv *ctrl_iface = wpa_s->global->dbus; int next; /* Do nothing if the control interface is not turned on */ if (ctrl_iface == NULL) return 0; /* Create and set the interface's object path */ wpa_s->dbus_new_path = os_zalloc(WPAS_DBUS_OBJECT_PATH_MAX); if (wpa_s->dbus_new_path == NULL) return -1; next = ctrl_iface->next_objid++; os_snprintf(wpa_s->dbus_new_path, WPAS_DBUS_OBJECT_PATH_MAX, WPAS_DBUS_NEW_PATH_INTERFACES "/%u", next); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); goto err; } wpas_dbus_register(obj_desc, wpa_s, NULL, wpas_dbus_interface_methods, wpas_dbus_interface_properties, wpas_dbus_interface_signals); wpa_printf(MSG_DEBUG, "dbus: Register interface object '%s'", wpa_s->dbus_new_path); if (wpa_dbus_register_object_per_iface(ctrl_iface, wpa_s->dbus_new_path, wpa_s->ifname, obj_desc)) goto err; wpas_dbus_signal_interface_added(wpa_s); return 0; err: os_free(wpa_s->dbus_new_path); wpa_s->dbus_new_path = NULL; free_dbus_object_desc(obj_desc); return -1; } int wpas_dbus_unregister_interface(struct wpa_supplicant *wpa_s) { struct wpas_dbus_priv *ctrl_iface; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; wpa_printf(MSG_DEBUG, "dbus: Unregister interface object '%s'", wpa_s->dbus_new_path); #ifdef CONFIG_AP if (wpa_s->preq_notify_peer) { wpas_dbus_unsubscribe_noc(ctrl_iface); os_free(wpa_s->preq_notify_peer); wpa_s->preq_notify_peer = NULL; } #endif /* CONFIG_AP */ if (wpa_dbus_unregister_object_per_iface(ctrl_iface, wpa_s->dbus_new_path)) return -1; wpas_dbus_signal_interface_removed(wpa_s); os_free(wpa_s->dbus_new_path); wpa_s->dbus_new_path = NULL; return 0; } #ifdef CONFIG_P2P static const struct wpa_dbus_property_desc wpas_dbus_p2p_peer_properties[] = { { "DeviceName", WPAS_DBUS_NEW_IFACE_P2P_PEER, "s", wpas_dbus_getter_p2p_peer_device_name, NULL }, { "PrimaryDeviceType", WPAS_DBUS_NEW_IFACE_P2P_PEER, "ay", wpas_dbus_getter_p2p_peer_primary_device_type, NULL }, { "config_method", WPAS_DBUS_NEW_IFACE_P2P_PEER, "q", wpas_dbus_getter_p2p_peer_config_method, NULL }, { "level", WPAS_DBUS_NEW_IFACE_P2P_PEER, "i", wpas_dbus_getter_p2p_peer_level, NULL }, { "devicecapability", WPAS_DBUS_NEW_IFACE_P2P_PEER, "y", wpas_dbus_getter_p2p_peer_device_capability, NULL }, { "groupcapability", WPAS_DBUS_NEW_IFACE_P2P_PEER, "y", wpas_dbus_getter_p2p_peer_group_capability, NULL }, { "SecondaryDeviceTypes", WPAS_DBUS_NEW_IFACE_P2P_PEER, "aay", wpas_dbus_getter_p2p_peer_secondary_device_types, NULL }, { "VendorExtension", WPAS_DBUS_NEW_IFACE_P2P_PEER, "aay", wpas_dbus_getter_p2p_peer_vendor_extension, NULL }, { "IEs", WPAS_DBUS_NEW_IFACE_P2P_PEER, "ay", wpas_dbus_getter_p2p_peer_ies, NULL }, { "DeviceAddress", WPAS_DBUS_NEW_IFACE_P2P_PEER, "ay", wpas_dbus_getter_p2p_peer_device_address, NULL }, { "Groups", WPAS_DBUS_NEW_IFACE_P2P_PEER, "ao", wpas_dbus_getter_p2p_peer_groups, NULL }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_p2p_peer_signals[] = { /* Deprecated: use org.freedesktop.DBus.Properties.PropertiesChanged */ { "PropertiesChanged", WPAS_DBUS_NEW_IFACE_P2P_PEER, { { "properties", "a{sv}", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; /** * wpas_dbus_signal_peer - Send a peer related event signal * @wpa_s: %wpa_supplicant network interface data * @dev: peer device object * @interface: name of the interface emitting this signal. * In case of peer objects, it would be emitted by either * the "interface object" or by "peer objects" * @sig_name: signal name - DeviceFound * * Notify listeners about event related with newly found p2p peer device */ static void wpas_dbus_signal_peer(struct wpa_supplicant *wpa_s, const u8 *dev_addr, const char *interface, const char *sig_name) { struct wpas_dbus_priv *iface; DBusMessage *msg; DBusMessageIter iter; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX], *path; iface = wpa_s->global->dbus; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(dev_addr)); msg = dbus_message_new_signal(wpa_s->dbus_new_path, interface, sig_name); if (msg == NULL) return; dbus_message_iter_init_append(msg, &iter); path = peer_obj_path; if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_OBJECT_PATH, &path)) goto err; dbus_connection_send(iface->con, msg, NULL); dbus_message_unref(msg); return; err: wpa_printf(MSG_ERROR, "dbus: Failed to construct signal"); dbus_message_unref(msg); } /** * wpas_dbus_signal_peer_found - Send a peer found signal * @wpa_s: %wpa_supplicant network interface data * @dev: peer device object * * Notify listeners about find a p2p peer device found */ void wpas_dbus_signal_peer_device_found(struct wpa_supplicant *wpa_s, const u8 *dev_addr) { wpas_dbus_signal_peer(wpa_s, dev_addr, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "DeviceFound"); } /** * wpas_dbus_signal_peer_lost - Send a peer lost signal * @wpa_s: %wpa_supplicant network interface data * @dev: peer device object * * Notify listeners about lost a p2p peer device */ void wpas_dbus_signal_peer_device_lost(struct wpa_supplicant *wpa_s, const u8 *dev_addr) { wpas_dbus_signal_peer(wpa_s, dev_addr, WPAS_DBUS_NEW_IFACE_P2PDEVICE, "DeviceLost"); } /** * wpas_dbus_register_peer - Register a discovered peer object with dbus * @wpa_s: wpa_supplicant interface structure * @ssid: network configuration data * Returns: 0 on success, -1 on failure * * Registers network representing object with dbus */ int wpas_dbus_register_peer(struct wpa_supplicant *wpa_s, const u8 *dev_addr) { struct wpas_dbus_priv *ctrl_iface; struct wpa_dbus_object_desc *obj_desc; struct peer_handler_args *arg; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(dev_addr)); wpa_printf(MSG_INFO, "dbus: Register peer object '%s'", peer_obj_path); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); goto err; } /* allocate memory for handlers arguments */ arg = os_zalloc(sizeof(struct peer_handler_args)); if (!arg) { wpa_printf(MSG_ERROR, "Not enough memory " "to create arguments for method"); goto err; } arg->wpa_s = wpa_s; os_memcpy(arg->p2p_device_addr, dev_addr, ETH_ALEN); wpas_dbus_register(obj_desc, arg, wpa_dbus_free, NULL, wpas_dbus_p2p_peer_properties, wpas_dbus_p2p_peer_signals); if (wpa_dbus_register_object_per_iface(ctrl_iface, peer_obj_path, wpa_s->ifname, obj_desc)) goto err; return 0; err: free_dbus_object_desc(obj_desc); return -1; } /** * wpas_dbus_unregister_peer - Unregister a peer object with dbus * @wpa_s: wpa_supplicant interface structure * @dev_addr: p2p device addr * Returns: 0 on success, -1 on failure * * Registers network representing object with dbus */ int wpas_dbus_unregister_peer(struct wpa_supplicant *wpa_s, const u8 *dev_addr) { struct wpas_dbus_priv *ctrl_iface; char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; int ret; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL || wpa_s->dbus_new_path == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(dev_addr)); wpa_printf(MSG_INFO, "dbus: Unregister peer object '%s'", peer_obj_path); ret = wpa_dbus_unregister_object_per_iface(ctrl_iface, peer_obj_path); return ret; } void wpas_dbus_signal_peer_groups_changed(struct wpa_supplicant *wpa_s, const u8 *dev_addr) { char peer_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; os_snprintf(peer_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_P2P_PEERS_PART "/" COMPACT_MACSTR, wpa_s->dbus_new_path, MAC2STR(dev_addr)); wpa_dbus_mark_property_changed(wpa_s->global->dbus, peer_obj_path, WPAS_DBUS_NEW_IFACE_P2P_PEER, "Groups"); } static const struct wpa_dbus_property_desc wpas_dbus_p2p_group_properties[] = { { "Members", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "ao", wpas_dbus_getter_p2p_group_members, NULL }, { "Group", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "o", wpas_dbus_getter_p2p_group, NULL }, { "Role", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "s", wpas_dbus_getter_p2p_role, NULL }, { "SSID", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "ay", wpas_dbus_getter_p2p_group_ssid, NULL }, { "BSSID", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "ay", wpas_dbus_getter_p2p_group_bssid, NULL }, { "Frequency", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "q", wpas_dbus_getter_p2p_group_frequency, NULL }, { "Passphrase", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "s", wpas_dbus_getter_p2p_group_passphrase, NULL }, { "PSK", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "ay", wpas_dbus_getter_p2p_group_psk, NULL }, { "WPSVendorExtensions", WPAS_DBUS_NEW_IFACE_P2P_GROUP, "aay", wpas_dbus_getter_p2p_group_vendor_ext, wpas_dbus_setter_p2p_group_vendor_ext }, { NULL, NULL, NULL, NULL, NULL } }; static const struct wpa_dbus_signal_desc wpas_dbus_p2p_group_signals[] = { { "PeerJoined", WPAS_DBUS_NEW_IFACE_P2P_GROUP, { { "peer", "o", ARG_OUT }, END_ARGS } }, { "PeerDisconnected", WPAS_DBUS_NEW_IFACE_P2P_GROUP, { { "peer", "o", ARG_OUT }, END_ARGS } }, { NULL, NULL, { END_ARGS } } }; /** * wpas_dbus_register_p2p_group - Register a p2p group object with dbus * @wpa_s: wpa_supplicant interface structure * @ssid: SSID struct * Returns: 0 on success, -1 on failure * * Registers p2p group representing object with dbus */ void wpas_dbus_register_p2p_group(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid) { struct wpas_dbus_priv *ctrl_iface; struct wpa_dbus_object_desc *obj_desc; char group_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return; if (wpa_s->dbus_groupobj_path) { wpa_printf(MSG_INFO, "%s: Group object '%s' already exists", __func__, wpa_s->dbus_groupobj_path); return; } if (wpas_dbus_get_group_obj_path(wpa_s, ssid, group_obj_path) < 0) return; wpa_s->dbus_groupobj_path = os_strdup(group_obj_path); if (wpa_s->dbus_groupobj_path == NULL) return; wpa_printf(MSG_INFO, "dbus: Register group object '%s'", group_obj_path); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "Not enough memory " "to create object description"); goto err; } wpas_dbus_register(obj_desc, wpa_s, NULL, NULL, wpas_dbus_p2p_group_properties, wpas_dbus_p2p_group_signals); if (wpa_dbus_register_object_per_iface(ctrl_iface, group_obj_path, wpa_s->ifname, obj_desc)) goto err; return; err: if (wpa_s->dbus_groupobj_path) { os_free(wpa_s->dbus_groupobj_path); wpa_s->dbus_groupobj_path = NULL; } free_dbus_object_desc(obj_desc); } /** * wpas_dbus_unregister_p2p_group - Unregister a p2p group object from dbus * @wpa_s: wpa_supplicant interface structure * @ssid: network name of the p2p group started */ void wpas_dbus_unregister_p2p_group(struct wpa_supplicant *wpa_s, const struct wpa_ssid *ssid) { struct wpas_dbus_priv *ctrl_iface; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return; if (!wpa_s->dbus_groupobj_path) { wpa_printf(MSG_DEBUG, "%s: Group object '%s' already unregistered", __func__, wpa_s->dbus_groupobj_path); return; } peer_groups_changed(wpa_s); wpa_printf(MSG_DEBUG, "dbus: Unregister group object '%s'", wpa_s->dbus_groupobj_path); wpa_dbus_unregister_object_per_iface(ctrl_iface, wpa_s->dbus_groupobj_path); os_free(wpa_s->dbus_groupobj_path); wpa_s->dbus_groupobj_path = NULL; } static const struct wpa_dbus_property_desc wpas_dbus_persistent_group_properties[] = { { "Properties", WPAS_DBUS_NEW_IFACE_PERSISTENT_GROUP, "a{sv}", wpas_dbus_getter_persistent_group_properties, wpas_dbus_setter_persistent_group_properties }, { NULL, NULL, NULL, NULL, NULL } }; /* No signals intended for persistent group objects */ /** * wpas_dbus_register_persistent_group - Register a configured(saved) * persistent group with dbus * @wpa_s: wpa_supplicant interface structure * @ssid: persistent group (still represented as a network within wpa) * configuration data * Returns: 0 on success, -1 on failure * * Registers a persistent group representing object with dbus. */ int wpas_dbus_register_persistent_group(struct wpa_supplicant *wpa_s, struct wpa_ssid *ssid) { struct wpas_dbus_priv *ctrl_iface; struct wpa_dbus_object_desc *obj_desc; struct network_handler_args *arg; char pgrp_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; /* Make sure ssid is a persistent group */ if (ssid->disabled != 2 && !ssid->p2p_persistent_group) return -1; /* should we return w/o complaining? */ ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; /* * Intentionally not coming up with different numbering scheme * for persistent groups. */ os_snprintf(pgrp_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_PERSISTENT_GROUPS_PART "/%u", wpa_s->dbus_new_path, ssid->id); wpa_printf(MSG_DEBUG, "dbus: Register persistent group object '%s'", pgrp_obj_path); obj_desc = os_zalloc(sizeof(struct wpa_dbus_object_desc)); if (!obj_desc) { wpa_printf(MSG_ERROR, "dbus: Not enough memory to create " "object description"); goto err; } /* * Reusing the same context structure as that for networks * since these are represented using same data structure. */ /* allocate memory for handlers arguments */ arg = os_zalloc(sizeof(struct network_handler_args)); if (!arg) { wpa_printf(MSG_ERROR, "dbus: Not enough memory to create " "arguments for method"); goto err; } arg->wpa_s = wpa_s; arg->ssid = ssid; wpas_dbus_register(obj_desc, arg, wpa_dbus_free, NULL, wpas_dbus_persistent_group_properties, NULL); if (wpa_dbus_register_object_per_iface(ctrl_iface, pgrp_obj_path, wpa_s->ifname, obj_desc)) goto err; wpas_dbus_signal_persistent_group_added(wpa_s, ssid->id); return 0; err: free_dbus_object_desc(obj_desc); return -1; } /** * wpas_dbus_unregister_persistent_group - Unregister a persistent_group * from dbus * @wpa_s: wpa_supplicant interface structure * @nid: network id * Returns: 0 on success, -1 on failure * * Unregisters persistent group representing object from dbus * * NOTE: There is a slight issue with the semantics here. While the * implementation simply means the persistent group is unloaded from memory, * it should not get interpreted as the group is actually being erased/removed * from persistent storage as well. */ int wpas_dbus_unregister_persistent_group(struct wpa_supplicant *wpa_s, int nid) { struct wpas_dbus_priv *ctrl_iface; char pgrp_obj_path[WPAS_DBUS_OBJECT_PATH_MAX]; int ret; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL || wpa_s->dbus_new_path == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; os_snprintf(pgrp_obj_path, WPAS_DBUS_OBJECT_PATH_MAX, "%s/" WPAS_DBUS_NEW_PERSISTENT_GROUPS_PART "/%u", wpa_s->dbus_new_path, nid); wpa_printf(MSG_DEBUG, "dbus: Unregister persistent group object '%s'", pgrp_obj_path); ret = wpa_dbus_unregister_object_per_iface(ctrl_iface, pgrp_obj_path); if (!ret) wpas_dbus_signal_persistent_group_removed(wpa_s, nid); return ret; } #endif /* CONFIG_P2P */
686158.c
/* * * Copyright (c) 2013, The Linux Foundation. All rights reserved. * Not a Contribution. * * Copyright 2012 The Android Open Source Project * * 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. * */ /****************************************************************************** * * Filename: hw_ar3k.c * * Description: Contains controller-specific functions, like * firmware patch download * low power mode operations * ******************************************************************************/ #ifdef __cplusplus extern "C" { #endif #define LOG_TAG "bt_vendor" #include "bt_hci_bdroid.h" #include "bt_vendor_qcom.h" #include "hci_uart.h" #include "hw_ar3k.h" #include <ctype.h> #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/uio.h> #include <termios.h> #include <time.h> #include <unistd.h> #include <cutils/properties.h> #include <utils/Log.h> /****************************************************************************** ** Variables ******************************************************************************/ int cbstat = 0; #define PATCH_LOC_STRING_LEN 8 char ARbyte[3]; char ARptr[MAX_PATCH_CMD + 1]; int byte_cnt; int patch_count = 0; char patch_loc[PATCH_LOC_STRING_LEN + 1]; int PSCounter=0; uint32_t dev_type = 0; uint32_t rom_version = 0; uint32_t build_version = 0; char patch_file[PATH_MAX]; char ps_file[PATH_MAX]; FILE *stream; int tag_count=0; /* for friendly debugging outpout string */ static char *lpm_mode[] = { "UNKNOWN", "disabled", "enabled" }; static char *lpm_state[] = { "UNKNOWN", "de-asserted", "asserted" }; static uint8_t upio_state[UPIO_MAX_COUNT]; struct ps_cfg_entry ps_list[MAX_TAGS]; #define PS_EVENT_LEN 100 #ifdef __cplusplus } #endif /***************************************************************************** ** Functions *****************************************************************************/ int is_bt_soc_ath() { int ret = 0; char bt_soc_type[PROPERTY_VALUE_MAX]; ret = property_get("qcom.bluetooth.soc", bt_soc_type, NULL); if (ret != 0) { ALOGI("qcom.bluetooth.soc set to %s\n", bt_soc_type); if (!strncasecmp(bt_soc_type, "ath3k", sizeof("ath3k"))) return 1; } else { ALOGI("qcom.bluetooth.soc not set, so using default.\n"); } return 0; } /* * Send HCI command and wait for command complete event. * The event buffer has to be freed by the caller. */ static int send_hci_cmd_sync(int dev, uint8_t *cmd, int len, uint8_t **event) { int err; uint8_t *hci_event; uint8_t pkt_type = HCI_COMMAND_PKT; if (len == 0) return len; if (write(dev, &pkt_type, 1) != 1) return -EILSEQ; if (write(dev, (unsigned char *)cmd, len) != len) return -EILSEQ; hci_event = (uint8_t *)malloc(PS_EVENT_LEN); if (!hci_event) return -ENOMEM; err = read_hci_event(dev, (unsigned char *)hci_event, PS_EVENT_LEN); if (err > 0) { *event = hci_event; } else { free(hci_event); return -EILSEQ; } return len; } static void convert_bdaddr(char *str_bdaddr, char *bdaddr) { char bdbyte[3]; char *str_byte = str_bdaddr; int i, j; int colon_present = 0; if (strstr(str_bdaddr, ":")) colon_present = 1; bdbyte[2] = '\0'; /* Reverse the BDADDR to LSB first */ for (i = 0, j = 5; i < 6; i++, j--) { bdbyte[0] = str_byte[0]; bdbyte[1] = str_byte[1]; bdaddr[j] = strtol(bdbyte, NULL, 16); if (colon_present == 1) str_byte += 3; else str_byte += 2; } } static int uart_speed(int s) { switch (s) { case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; case 230400: return B230400; case 460800: return B460800; case 500000: return B500000; case 576000: return B576000; case 921600: return B921600; case 1000000: return B1000000; case 1152000: return B1152000; case 1500000: return B1500000; case 2000000: return B2000000; #ifdef B2500000 case 2500000: return B2500000; #endif #ifdef B3000000 case 3000000: return B3000000; #endif #ifdef B3500000 case 3500000: return B3500000; #endif #ifdef B4000000 case 4000000: return B4000000; #endif default: return B57600; } } int set_speed(int fd, struct termios *ti, int speed) { if (cfsetospeed(ti, uart_speed(speed)) < 0) return -errno; if (cfsetispeed(ti, uart_speed(speed)) < 0) return -errno; if (tcsetattr(fd, TCSANOW, ti) < 0) return -errno; return 0; } static void load_hci_ps_hdr(uint8_t *cmd, uint8_t ps_op, int len, int index) { hci_command_hdr *ch = (void *)cmd; ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, HCI_PS_CMD_OCF)); ch->plen = len + PS_HDR_LEN; cmd += HCI_COMMAND_HDR_SIZE; cmd[0] = ps_op; cmd[1] = index; cmd[2] = index >> 8; cmd[3] = len; } static int read_ps_event(uint8_t *event, uint16_t ocf) { hci_event_hdr *eh; uint16_t opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, ocf)); event++; eh = (void *)event; event += HCI_EVENT_HDR_SIZE; if (eh->evt == EVT_CMD_COMPLETE) { evt_cmd_complete *cc = (void *)event; event += EVT_CMD_COMPLETE_SIZE; if (cc->opcode == opcode && event[0] == HCI_EV_SUCCESS) return 0; else return -EILSEQ; } return -EILSEQ; } #define PS_WRITE 1 #define PS_RESET 2 #define WRITE_PATCH 8 #define ENABLE_PATCH 11 #define HCI_PS_CMD_HDR_LEN 7 static int write_cmd(int fd, uint8_t *buffer, int len) { uint8_t *event; int err; err = send_hci_cmd_sync(fd, buffer, len, &event); if (err < 0) return err; err = read_ps_event(event, HCI_PS_CMD_OCF); free(event); return err; } #define PS_RESET_PARAM_LEN 6 #define PS_RESET_CMD_LEN (HCI_PS_CMD_HDR_LEN + PS_RESET_PARAM_LEN) #define PS_ID_MASK 0xFF /* Sends PS commands using vendor specficic HCI commands */ static int write_ps_cmd(int fd, uint8_t opcode, uint32_t ps_param) { uint8_t cmd[HCI_MAX_CMD_SIZE]; uint32_t i; switch (opcode) { case ENABLE_PATCH: load_hci_ps_hdr(cmd, opcode, 0, 0x00); if (write_cmd(fd, cmd, HCI_PS_CMD_HDR_LEN) < 0) return -EILSEQ; break; case PS_RESET: load_hci_ps_hdr(cmd, opcode, PS_RESET_PARAM_LEN, 0x00); cmd[7] = 0x00; cmd[PS_RESET_CMD_LEN - 2] = ps_param & PS_ID_MASK; cmd[PS_RESET_CMD_LEN - 1] = (ps_param >> 8) & PS_ID_MASK; if (write_cmd(fd, cmd, PS_RESET_CMD_LEN) < 0) return -EILSEQ; break; case PS_WRITE: for (i = 0; i < ps_param; i++) { load_hci_ps_hdr(cmd, opcode, ps_list[i].len, ps_list[i].id); memcpy(&cmd[HCI_PS_CMD_HDR_LEN], ps_list[i].data, ps_list[i].len); if (write_cmd(fd, cmd, ps_list[i].len + HCI_PS_CMD_HDR_LEN) < 0) return -EILSEQ; } break; } return 0; } #define PS_ASIC_FILE "PS_ASIC.pst" #define PS_FPGA_FILE "PS_FPGA.pst" #define MAXPATHLEN 4096 static void get_ps_file_name(uint32_t devtype, uint32_t rom_version,char *path) { char *filename; if (devtype == 0xdeadc0de) filename = PS_ASIC_FILE; else filename = PS_FPGA_FILE; snprintf(path, MAXPATHLEN, "%s%x/%s", FW_PATH, rom_version, filename); } #define PATCH_FILE "RamPatch.txt" #define FPGA_ROM_VERSION 0x99999999 #define ROM_DEV_TYPE 0xdeadc0de static void get_patch_file_name(uint32_t dev_type, uint32_t rom_version, uint32_t build_version, char *path) { if (rom_version == FPGA_ROM_VERSION && dev_type != ROM_DEV_TYPE &&dev_type != 0 && build_version == 1) path[0] = '\0'; else snprintf(path, MAXPATHLEN, "%s%x/%s", FW_PATH, rom_version, PATCH_FILE); } static int set_cntrlr_baud(int fd, int speed) { int baud; struct timespec tm = { 0, 500000}; unsigned char cmd[MAX_CMD_LEN], rsp[HCI_MAX_EVENT_SIZE]; unsigned char *ptr = cmd + 1; hci_command_hdr *ch = (void *)ptr; cmd[0] = HCI_COMMAND_PKT; /* set controller baud rate to user specified value */ ptr = cmd + 1; ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, HCI_CHG_BAUD_CMD_OCF)); ch->plen = 2; ptr += HCI_COMMAND_HDR_SIZE; baud = speed/100; ptr[0] = (char)baud; ptr[1] = (char)(baud >> 8); if (write(fd, cmd, WRITE_BAUD_CMD_LEN) != WRITE_BAUD_CMD_LEN) { ALOGI("Failed to write change baud rate command"); return -ETIMEDOUT; } nanosleep(&tm, NULL); if (read_hci_event(fd, rsp, sizeof(rsp)) < 0) return -ETIMEDOUT; return 0; } #define PS_UNDEF 0 #define PS_ID 1 #define PS_LEN 2 #define PS_DATA 3 #define PS_MAX_LEN 500 #define LINE_SIZE_MAX (PS_MAX_LEN * 2) #define ENTRY_PER_LINE 16 #define __check_comment(buf) (((buf)[0] == '/') && ((buf)[1] == '/')) #define __skip_space(str) while (*(str) == ' ') ((str)++) #define __is_delim(ch) ((ch) == ':') #define MAX_PREAMBLE_LEN 4 /* Parse PS entry preamble of format [X:X] for main type and subtype */ static int get_ps_type(char *ptr, int index, char *type, char *sub_type) { int i; int delim = false; if (index > MAX_PREAMBLE_LEN) return -EILSEQ; for (i = 1; i < index; i++) { if (__is_delim(ptr[i])) { delim = true; continue; } if (isalpha(ptr[i])) { if (delim == false) (*type) = toupper(ptr[i]); else (*sub_type) = toupper(ptr[i]); } } return 0; } #define ARRAY 'A' #define STRING 'S' #define DECIMAL 'D' #define BINARY 'B' #define PS_HEX 0 #define PS_DEC 1 static int get_input_format(char *buf, struct ps_entry_type *format) { char *ptr = NULL; char type = '\0'; char sub_type = '\0'; format->type = PS_HEX; format->array = true; if (strstr(buf, "[") != buf) return 0; ptr = strstr(buf, "]"); if (!ptr) return -EILSEQ; if (get_ps_type(buf, ptr - buf, &type, &sub_type) < 0) return -EILSEQ; /* Check is data type is of array */ if (type == ARRAY || sub_type == ARRAY) format->array = true; if (type == STRING || sub_type == STRING) format->array = false; if (type == DECIMAL || type == BINARY) format->type = PS_DEC; else format->type = PS_HEX; return 0; } #define UNDEFINED 0xFFFF static unsigned int read_data_in_section(char *buf, struct ps_entry_type type) { char *ptr = buf; if (!buf) return UNDEFINED; if (buf == strstr(buf, "[")) { ptr = strstr(buf, "]"); if (!ptr) return UNDEFINED; ptr++; } if (type.type == PS_HEX && type.array != true) return strtol(ptr, NULL, 16); return UNDEFINED; } /* Read PS entries as string, convert and add to Hex array */ static void update_tag_data(struct ps_cfg_entry *tag, struct tag_info *info, const char *ptr) { char buf[3]; buf[2] = '\0'; strlcpy(buf, &ptr[info->char_cnt],sizeof(buf)); tag->data[info->byte_count] = strtol(buf, NULL, 16); info->char_cnt += 3; info->byte_count++; strlcpy(buf, &ptr[info->char_cnt], sizeof(buf)); tag->data[info->byte_count] = strtol(buf, NULL, 16); info->char_cnt += 3; info->byte_count++; } static inline int update_char_count(const char *buf) { char *end_ptr; if (strstr(buf, "[") == buf) { end_ptr = strstr(buf, "]"); if (!end_ptr) return 0; else return(end_ptr - buf) + 1; } return 0; } #define PS_HEX 0 #define PS_DEC 1 static int ath_parse_ps(FILE *stream) { char buf[LINE_SIZE_MAX + 1]; char *ptr; uint8_t tag_cnt = 0; int16_t byte_count = 0; struct ps_entry_type format; struct tag_info status = { 0, 0, 0, 0}; do { int read_count; struct ps_cfg_entry *tag; ptr = fgets(buf, LINE_SIZE_MAX, stream); if (!ptr) break; __skip_space(ptr); if (__check_comment(ptr)) continue; /* Lines with a '#' will be followed by new PS entry */ if (ptr == strstr(ptr, "#")) { if (status.section != PS_UNDEF) { return -EILSEQ; } else { status.section = PS_ID; continue; } } tag = &ps_list[tag_cnt]; switch (status.section) { case PS_ID: if (get_input_format(ptr, &format) < 0) return -EILSEQ; tag->id = read_data_in_section(ptr, format); status.section = PS_LEN; break; case PS_LEN: if (get_input_format(ptr, &format) < 0) return -EILSEQ; byte_count = read_data_in_section(ptr, format); if (byte_count > PS_MAX_LEN) return -EILSEQ; tag->len = byte_count; tag->data = (uint8_t *)malloc(byte_count); status.section = PS_DATA; status.line_count = 0; break; case PS_DATA: if (status.line_count == 0) if (get_input_format(ptr, &format) < 0) return -EILSEQ; __skip_space(ptr); status.char_cnt = update_char_count(ptr); read_count = (byte_count > ENTRY_PER_LINE) ? ENTRY_PER_LINE : byte_count; if (format.type == PS_HEX && format.array == true) { while (read_count > 0) { update_tag_data(tag, &status, ptr); read_count -= 2; } if (byte_count > ENTRY_PER_LINE) byte_count -= ENTRY_PER_LINE; else byte_count = 0; } status.line_count++; if (byte_count == 0) memset(&status, 0x00, sizeof(struct tag_info)); if (status.section == PS_UNDEF) tag_cnt++; if (tag_cnt == MAX_TAGS) return -EILSEQ; break; } } while (ptr); return tag_cnt; } #define PS_RAM_SIZE 2048 static int ps_config_download(int fd, int tag_count) { if (write_ps_cmd(fd, PS_RESET, PS_RAM_SIZE) < 0) return -1; if (tag_count > 0) if (write_ps_cmd(fd, PS_WRITE, tag_count) < 0) return -1; return 0; } static int write_bdaddr(int pConfig, char *bdaddr) { uint8_t *event; int err; uint8_t cmd[13]; uint8_t *ptr = cmd; hci_command_hdr *ch = (void *)cmd; memset(cmd, 0, sizeof(cmd)); ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, HCI_PS_CMD_OCF)); ch->plen = 10; ptr += HCI_COMMAND_HDR_SIZE; ptr[0] = 0x01; ptr[1] = 0x01; ptr[2] = 0x00; ptr[3] = 0x06; convert_bdaddr(bdaddr, (char *)&ptr[4]); err = send_hci_cmd_sync(pConfig, cmd, sizeof(cmd), &event); if (err < 0) return err; err = read_ps_event(event, HCI_PS_CMD_OCF); free(event); return err; } static void write_bdaddr_from_file(int rom_version, int fd) { FILE *stream; char bdaddr[PATH_MAX]; char bdaddr_file[PATH_MAX]; snprintf(bdaddr_file, MAXPATHLEN, "%s%x/%s", FW_PATH, rom_version, BDADDR_FILE); stream = fopen(bdaddr_file, "r"); if (!stream) return; if (fgets(bdaddr, PATH_MAX - 1, stream)) write_bdaddr(fd, bdaddr); fclose(stream); } #define HCI_EVT_CMD_CMPL_OPCODE 3 #define HCI_EVT_CMD_CMPL_STATUS_RET_BYTE 5 void baswap(bdaddr_t *dst, const bdaddr_t *src) { register unsigned char *d = (unsigned char *) dst; register const unsigned char *s = (const unsigned char *) src; register int i; for (i = 0; i < 6; i++) d[i] = s[5-i]; } int str2ba(const char *str, bdaddr_t *ba) { uint8_t b[6]; const char *ptr = str; int i; for (i = 0; i < 6; i++) { b[i] = (uint8_t) strtol(ptr, NULL, 16); ptr = strchr(ptr, ':'); if (i != 5 && !ptr) ptr = ":00:00:00:00:00"; ptr++; } baswap(ba, (bdaddr_t *) b); return 0; } #define DEV_REGISTER 0x4FFC #define GET_DEV_TYPE_OCF 0x05 static int get_device_type(int dev, uint32_t *code) { uint8_t cmd[8] = {0}; uint8_t *event; uint32_t reg; int err; uint8_t *ptr = cmd; hci_command_hdr *ch = (void *)cmd; ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, GET_DEV_TYPE_OCF)); ch->plen = 5; ptr += HCI_COMMAND_HDR_SIZE; ptr[0] = (uint8_t)DEV_REGISTER; ptr[1] = (uint8_t)DEV_REGISTER >> 8; ptr[2] = (uint8_t)DEV_REGISTER >> 16; ptr[3] = (uint8_t)DEV_REGISTER >> 24; ptr[4] = 0x04; err = send_hci_cmd_sync(dev, cmd, sizeof(cmd), &event); if (err < 0) return err; err = read_ps_event(event, GET_DEV_TYPE_OCF); if (err < 0) goto cleanup; reg = event[10]; reg = (reg << 8) | event[9]; reg = (reg << 8) | event[8]; reg = (reg << 8) | event[7]; *code = reg; cleanup: free(event); return err; } #define GET_VERSION_OCF 0x1E static int read_ath3k_version(int pConfig, uint32_t *rom_version, uint32_t *build_version) { uint8_t cmd[3] = {0}; uint8_t *event; int err; int status; hci_command_hdr *ch = (void *)cmd; ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, GET_VERSION_OCF)); ch->plen = 0; err = send_hci_cmd_sync(pConfig, cmd, sizeof(cmd), &event); if (err < 0) return err; err = read_ps_event(event, GET_VERSION_OCF); if (err < 0) goto cleanup; status = event[10]; status = (status << 8) | event[9]; status = (status << 8) | event[8]; status = (status << 8) | event[7]; *rom_version = status; status = event[14]; status = (status << 8) | event[13]; status = (status << 8) | event[12]; status = (status << 8) | event[11]; *build_version = status; cleanup: free(event); return err; } #define VERIFY_CRC 9 #define PS_REGION 1 #define PATCH_REGION 2 static int get_ath3k_crc(int dev) { uint8_t cmd[7] = {0}; uint8_t *event; int err; load_hci_ps_hdr(cmd, VERIFY_CRC, 0, PS_REGION | PATCH_REGION); err = send_hci_cmd_sync(dev, cmd, sizeof(cmd), &event); if (err < 0) return err; /* Send error code if CRC check patched */ if (read_ps_event(event, HCI_PS_CMD_OCF) >= 0) err = -EILSEQ; free(event); return err; } #define SET_PATCH_RAM_ID 0x0D #define SET_PATCH_RAM_CMD_SIZE 11 #define ADDRESS_LEN 4 static int set_patch_ram(int dev, char *patch_loc, int len) { int err; uint8_t cmd[20] = {0}; int i, j; char loc_byte[3]; uint8_t *event; uint8_t *loc_ptr = &cmd[7]; if (!patch_loc) return -1; loc_byte[2] = '\0'; load_hci_ps_hdr(cmd, SET_PATCH_RAM_ID, ADDRESS_LEN, 0); for (i = 0, j = 3; i < 4; i++, j--) { loc_byte[0] = patch_loc[0]; loc_byte[1] = patch_loc[1]; loc_ptr[j] = strtol(loc_byte, NULL, 16); patch_loc += 2; } err = send_hci_cmd_sync(dev, cmd, SET_PATCH_RAM_CMD_SIZE, &event); if (err < 0) return err; err = read_ps_event(event, HCI_PS_CMD_OCF); free(event); return err; } #define PATCH_LOC_KEY "DA:" #define PATCH_LOC_STRING_LEN 8 static int ps_patch_download(int fd, FILE *stream) { char byte[3]; char ptr[MAX_PATCH_CMD + 1]; int byte_cnt; int patch_count = 0; char patch_loc[PATCH_LOC_STRING_LEN + 1]; byte[2] = '\0'; while (fgets(ptr, MAX_PATCH_CMD, stream)) { if (strlen(ptr) <= 1) continue; else if (strstr(ptr, PATCH_LOC_KEY) == ptr) { strlcpy(patch_loc, &ptr[sizeof(PATCH_LOC_KEY) - 1], PATCH_LOC_STRING_LEN); if (set_patch_ram(fd, patch_loc, sizeof(patch_loc)) < 0) return -1; } else if (isxdigit(ptr[0])) break; else return -1; } byte_cnt = strtol(ptr, NULL, 16); while (byte_cnt > 0) { int i; uint8_t cmd[HCI_MAX_CMD_SIZE] = {0}; struct patch_entry patch; if (byte_cnt > MAX_PATCH_CMD) patch.len = MAX_PATCH_CMD; else patch.len = byte_cnt; for (i = 0; i < patch.len; i++) { if (!fgets(byte, 3, stream)) return -1; patch.data[i] = strtoul(byte, NULL, 16); } load_hci_ps_hdr(cmd, WRITE_PATCH, patch.len, patch_count); memcpy(&cmd[HCI_PS_CMD_HDR_LEN], patch.data, patch.len); if (write_cmd(fd, cmd, patch.len + HCI_PS_CMD_HDR_LEN) < 0) return -1; patch_count++; byte_cnt = byte_cnt - MAX_PATCH_CMD; } if (write_ps_cmd(fd, ENABLE_PATCH, 0) < 0) return -1; return patch_count; } static int ath_ps_download(int fd) { int err = 0; int tag_count; int patch_count = 0; uint32_t rom_version = 0; uint32_t build_version = 0; uint32_t dev_type = 0; char patch_file[PATH_MAX]; char ps_file[PATH_MAX]; FILE *stream; /* * Verfiy firmware version. depending on it select the PS * config file to download. */ if (get_device_type(fd, &dev_type) < 0) { err = -EILSEQ; goto download_cmplete; } if (read_ath3k_version(fd, &rom_version, &build_version) < 0) { err = -EILSEQ; goto download_cmplete; } /* Do not download configuration if CRC passes */ if (get_ath3k_crc(fd) < 0) { err = 0; goto download_cmplete; } get_ps_file_name(dev_type, rom_version, ps_file); get_patch_file_name(dev_type, rom_version, build_version, patch_file); stream = fopen(ps_file, "r"); if (!stream) { ALOGI("firmware file open error:%s, ver:%x\n",ps_file, rom_version); if (rom_version == 0x1020201) err = 0; else err = -EILSEQ; goto download_cmplete; } tag_count = ath_parse_ps(stream); fclose(stream); if (tag_count < 0) { err = -EILSEQ; goto download_cmplete; } /* * It is not necessary that Patch file be available, * continue with PS Operations if patch file is not available. */ if (patch_file[0] == '\0') err = 0; stream = fopen(patch_file, "r"); if (!stream) err = 0; else { patch_count = ps_patch_download(fd, stream); fclose(stream); if (patch_count < 0) { err = -EILSEQ; goto download_cmplete; } } err = ps_config_download(fd, tag_count); download_cmplete: if (!err) write_bdaddr_from_file(rom_version, fd); return err; } int ath3k_init(int fd, int speed, int init_speed, char *bdaddr, struct termios *ti) { ALOGI(" %s ", __FUNCTION__); int r; int err = 0; struct timespec tm = { 0, 500000}; unsigned char cmd[MAX_CMD_LEN] = {0}; unsigned char rsp[HCI_MAX_EVENT_SIZE]; unsigned char *ptr = cmd + 1; hci_command_hdr *ch = (void *)ptr; int flags = 0; if (ioctl(fd, TIOCMGET, &flags) < 0) { ALOGI("TIOCMGET failed in init\n"); return -1; } flags |= TIOCM_RTS; if (ioctl(fd, TIOCMSET, &flags) < 0) { ALOGI("TIOCMSET failed in init: HW Flow-on error\n"); return -1; } /* set both controller and host baud rate to maximum possible value */ err = set_cntrlr_baud(fd, speed); ALOGI("set_cntrlr_baud : ret:%d \n", err); if (err < 0) return err; err = set_speed(fd, ti, speed); if (err < 0) { ALOGI("Can't set required baud rate"); return err; } /* Download PS and patch */ r = ath_ps_download(fd); if (r < 0) { ALOGI("Failed to Download configuration"); err = -ETIMEDOUT; goto failed; } ALOGI("ath_ps_download is done\n"); cmd[0] = HCI_COMMAND_PKT; /* Write BDADDR */ if (bdaddr) { ch->opcode = htobs(cmd_opcode_pack(HCI_VENDOR_CMD_OGF, HCI_PS_CMD_OCF)); ch->plen = 10; ptr += HCI_COMMAND_HDR_SIZE; ptr[0] = 0x01; ptr[1] = 0x01; ptr[2] = 0x00; ptr[3] = 0x06; str2ba(bdaddr, (bdaddr_t *)(ptr + 4)); if (write(fd, cmd, WRITE_BDADDR_CMD_LEN) != WRITE_BDADDR_CMD_LEN) { ALOGI("Failed to write BD_ADDR command\n"); err = -ETIMEDOUT; goto failed; } if (read_hci_event(fd, rsp, sizeof(rsp)) < 0) { ALOGI("Failed to set BD_ADDR\n"); err = -ETIMEDOUT; goto failed; } } /* Send HCI Reset */ cmd[1] = 0x03; cmd[2] = 0x0C; cmd[3] = 0x00; r = write(fd, cmd, 4); if (r != 4) { err = -ETIMEDOUT; goto failed; } nanosleep(&tm, NULL); if (read_hci_event(fd, rsp, sizeof(rsp)) < 0) { err = -ETIMEDOUT; goto failed; } ALOGI("HCI Reset is done\n"); err = set_cntrlr_baud(fd, speed); if (err < 0) ALOGI("set_cntrlr_baud0:%d,%d\n", speed, err); failed: if (err < 0) { set_cntrlr_baud(fd, init_speed); set_speed(fd, ti, init_speed); } return err; } #define BTPROTO_HCI 1 /* Open HCI device. * Returns device descriptor (dd). */ int hci_open_dev(int dev_id) { struct sockaddr_hci a; int dd, err; /* Create HCI socket */ dd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI); if (dd < 0) return dd; /* Bind socket to the HCI device */ memset(&a, 0, sizeof(a)); a.hci_family = AF_BLUETOOTH; a.hci_dev = dev_id; if (bind(dd, (struct sockaddr *) &a, sizeof(a)) < 0) goto failed; return dd; failed: err = errno; close(dd); errno = err; return -1; } int hci_close_dev(int dd) { return close(dd); } /* HCI functions that require open device * dd - Device descriptor returned by hci_open_dev. */ int hci_send_cmd(int dd, uint16_t ogf, uint16_t ocf, uint8_t plen, void *param) { uint8_t type = HCI_COMMAND_PKT; hci_command_hdr hc; struct iovec iv[3]; int ivn; hc.opcode = htobs(cmd_opcode_pack(ogf, ocf)); hc.plen= plen; iv[0].iov_base = &type; iv[0].iov_len = 1; iv[1].iov_base = &hc; iv[1].iov_len = HCI_COMMAND_HDR_SIZE; ivn = 2; if (plen) { iv[2].iov_base = param; iv[2].iov_len = plen; ivn = 3; } while (writev(dd, iv, ivn) < 0) { if (errno == EAGAIN || errno == EINTR) continue; return -1; } return 0; } #define HCI_SLEEP_CMD_OCF 0x04 #define TIOCSETD 0x5423 #define HCIUARTSETFLAGS _IOW('U', 204, int) #define HCIUARTSETPROTO _IOW('U', 200, int) #define HCIUARTGETDEVICE _IOW('U', 202, int) /* * Atheros AR300x specific initialization post callback */ int ath3k_post(int fd, int pm) { int dev_id, dd; struct timespec tm = { 0, 50000}; sleep(1); dev_id = ioctl(fd, HCIUARTGETDEVICE, 0); if (dev_id < 0) { perror("cannot get device id"); return dev_id; } dd = hci_open_dev(dev_id); if (dd < 0) { perror("HCI device open failed"); return dd; } if (ioctl(dd, HCIDEVUP, dev_id) < 0 && errno != EALREADY) { perror("hci down:Power management Disabled"); hci_close_dev(dd); return -1; } /* send vendor specific command with Sleep feature Enabled */ if (hci_send_cmd(dd, OGF_VENDOR_CMD, HCI_SLEEP_CMD_OCF, 1, &pm) < 0) perror("PM command failed, power management Disabled"); nanosleep(&tm, NULL); hci_close_dev(dd); return 0; } #define FLOW_CTL 0x0001 #define ENABLE_PM 1 #define DISABLE_PM 0 /* Initialize UART driver */ static int init_uart(char *dev, struct uart_t *u, int send_break, int raw) { ALOGI(" %s ", __FUNCTION__); struct termios ti; int i, fd; unsigned long flags = 0; if (raw) flags |= 1 << HCI_UART_RAW_DEVICE; fd = open(dev, O_RDWR | O_NOCTTY); if (fd < 0) { ALOGI("Can't open serial port"); return -1; } tcflush(fd, TCIOFLUSH); if (tcgetattr(fd, &ti) < 0) { ALOGI("Can't get port settings: %d\n", errno); return -1; } cfmakeraw(&ti); ti.c_cflag |= CLOCAL; if (u->flags & FLOW_CTL) ti.c_cflag |= CRTSCTS; else ti.c_cflag &= ~CRTSCTS; if (tcsetattr(fd, TCSANOW, &ti) < 0) { ALOGI("Can't set port settings"); return -1; } if (set_speed(fd, &ti, u->init_speed) < 0) { ALOGI("Can't set initial baud rate"); return -1; } tcflush(fd, TCIOFLUSH); if (send_break) { tcsendbreak(fd, 0); usleep(500000); } ath3k_init(fd,u->speed,u->init_speed,u->bdaddr, &ti); ALOGI("Device setup complete\n"); tcflush(fd, TCIOFLUSH); // Set actual baudrate /* if (set_speed(fd, &ti, u->speed) < 0) { perror("Can't set baud rate"); return -1; } i = N_HCI; if (ioctl(fd, TIOCSETD, &i) < 0) { perror("Can't set line discipline"); return -1; } if (flags && ioctl(fd, HCIUARTSETFLAGS, flags) < 0) { perror("Can't set UART flags"); return -1; } if (ioctl(fd, HCIUARTSETPROTO, u->proto) < 0) { perror("Can't set device"); return -1; } #if !defined(SW_BOARD_HAVE_BLUETOOTH_RTK) ath3k_post(fd, u->pm); #endif */ return fd; } int hw_config_ath3k(char *port_name) { ALOGI(" %s ", __FUNCTION__); PSCounter=0; struct sigaction sa; struct uart_t u ; int n=0,send_break=0,raw=0; memset(&u, 0, sizeof(u)); u.speed =3000000; u.init_speed =115200; u.flags |= FLOW_CTL; u.pm = DISABLE_PM; n = init_uart(port_name, &u, send_break, raw); if (n < 0) { ALOGI("Can't initialize device"); } return n; } void lpm_set_ar3k(uint8_t pio, uint8_t action, uint8_t polarity) { int rc; int fd = -1; char buffer; ALOGI("lpm mode: %d action: %d", pio, action); switch (pio) { case UPIO_LPM_MODE: if (upio_state[UPIO_LPM_MODE] == action) { ALOGI("LPM is %s already", lpm_mode[action]); return; } fd = open(VENDOR_LPM_PROC_NODE, O_WRONLY); if (fd < 0) { ALOGE("upio_set : open(%s) for write failed: %s (%d)", VENDOR_LPM_PROC_NODE, strerror(errno), errno); return; } if (action == UPIO_ASSERT) { buffer = '1'; } else { buffer = '0'; } if (write(fd, &buffer, 1) < 0) { ALOGE("upio_set : write(%s) failed: %s (%d)", VENDOR_LPM_PROC_NODE, strerror(errno),errno); } else { upio_state[UPIO_LPM_MODE] = action; ALOGI("LPM is set to %s", lpm_mode[action]); } if (fd >= 0) close(fd); break; case UPIO_BT_WAKE: /* UPIO_DEASSERT should be allowed because in Rx case assert occur * from the remote side where as deassert will be initiated from Host */ if ((action == UPIO_ASSERT) && (upio_state[UPIO_BT_WAKE] == action)) { ALOGI("BT_WAKE is %s already", lpm_state[action]); return; } if (action == UPIO_DEASSERT) buffer = '0'; else buffer = '1'; fd = open(VENDOR_BTWRITE_PROC_NODE, O_WRONLY); if (fd < 0) { ALOGE("upio_set : open(%s) for write failed: %s (%d)", VENDOR_BTWRITE_PROC_NODE, strerror(errno), errno); return; } if (write(fd, &buffer, 1) < 0) { ALOGE("upio_set : write(%s) failed: %s (%d)", VENDOR_BTWRITE_PROC_NODE, strerror(errno),errno); } else { upio_state[UPIO_BT_WAKE] = action; ALOGI("BT_WAKE is set to %s", lpm_state[action]); } ALOGI("proc btwrite assertion"); if (fd >= 0) close(fd); break; case UPIO_HOST_WAKE: ALOGI("upio_set: UPIO_HOST_WAKE"); break; } }
189653.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE252_Unchecked_Return_Value__wchar_t_puts_13.c Label Definition File: CWE252_Unchecked_Return_Value.string.label.xml Template File: point-flaw-13.tmpl.c */ /* * @description * CWE: 252 Unchecked Return Value * Sinks: puts * GoodSink: Check if putws() fails * BadSink : Do not check if _putws() fails * Flow Variant: 13 Control flow: if(global_const_five==5) and if(global_const_five!=5) * * */ #include "std_testcase.h" #ifndef OMITBAD void CWE252_Unchecked_Return_Value__wchar_t_puts_13_bad() { if(global_const_five==5) { { /* FLAW: Do not check the return value */ _putws(L"string"); } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { /* FIX: check the return value */ if (_putws(L"string") == WEOF) { printLine("puts failed!"); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(global_const_five!=5) instead of if(global_const_five==5) */ static void good1() { if(global_const_five!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { /* FLAW: Do not check the return value */ _putws(L"string"); } } else { { /* FIX: check the return value */ if (_putws(L"string") == WEOF) { printLine("puts failed!"); } } } } /* good2() reverses the bodies in the if statement */ static void good2() { if(global_const_five==5) { { /* FIX: check the return value */ if (_putws(L"string") == WEOF) { printLine("puts failed!"); } } } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ { /* FLAW: Do not check the return value */ _putws(L"string"); } } } void CWE252_Unchecked_Return_Value__wchar_t_puts_13_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE252_Unchecked_Return_Value__wchar_t_puts_13_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE252_Unchecked_Return_Value__wchar_t_puts_13_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
400282.c
/* * $Id: info_delete.c 2 2000-04-12 16:19:07Z joachim $ * * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "mpioimpl.h" #ifdef HAVE_WEAK_SYMBOLS #if defined(HAVE_PRAGMA_WEAK) #pragma weak MPI_Info_delete = PMPI_Info_delete #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #pragma _HP_SECONDARY_DEF PMPI_Info_delete MPI_Info_delete #elif defined(HAVE_PRAGMA_CRI_DUP) #pragma _CRI duplicate MPI_Info_delete as PMPI_Info_delete /* end of weak pragmas */ #endif /* Include mapping from MPI->PMPI */ #define __MPIO_BUILD_PROFILING #include "mpioprof.h" #endif /*@ MPI_Info_delete - Deletes a (key,value) pair from info Input Parameters: . info - info object (handle) . key - key (string) .N fortran @*/ int MPI_Info_delete(MPI_Info info, char *key) { MPI_Info prev, curr; int done; if ((info <= (MPI_Info) 0) || (info->cookie != MPIR_INFO_COOKIE)) { printf("MPI_Info_delete: Invalid info object\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if (key <= (char *) 0) { printf("MPI_Info_delete: key is an invalid address\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if (strlen(key) > MPI_MAX_INFO_KEY) { printf("MPI_Info_delete: key is longer than MPI_MAX_INFO_KEY\n"); MPI_Abort(MPI_COMM_WORLD, 1); } if (!strlen(key)) { printf("MPI_Info_delete: key is a null string\n"); MPI_Abort(MPI_COMM_WORLD, 1); } prev = info; curr = info->next; done = 0; while (curr) { if (!strcmp(curr->key, key)) { free(curr->key); /* not ADIOI_Free, because it was strdup'ed */ free(curr->value); prev->next = curr->next; ADIOI_Free(curr); done = 1; break; } prev = curr; curr = curr->next; } if (!done) { printf("MPI_Info_delete: key not defined in info\n"); MPI_Abort(MPI_COMM_WORLD, 1); } return MPI_SUCCESS; }
101957.c
/***************************************************************************//** * \file EzI2C_SPI_UART_INT.c * \version 3.20 * * \brief * This file provides the source code to the Interrupt Service Routine for * the SCB Component in SPI and UART modes. * * Note: * ******************************************************************************** * \copyright * Copyright 2013-2016, Cypress Semiconductor Corporation. All rights reserved. * You may use this file only in accordance with the license, terms, conditions, * disclaimers, and limitations in the end user license agreement accompanying * the software package with which this file was provided. *******************************************************************************/ #include "EzI2C_PVT.h" #include "EzI2C_SPI_UART_PVT.h" #if (EzI2C_SCB_IRQ_INTERNAL) /******************************************************************************* * Function Name: EzI2C_SPI_UART_ISR ****************************************************************************//** * * Handles the Interrupt Service Routine for the SCB SPI or UART modes. * *******************************************************************************/ CY_ISR(EzI2C_SPI_UART_ISR) { #if (EzI2C_INTERNAL_RX_SW_BUFFER_CONST) uint32 locHead; #endif /* (EzI2C_INTERNAL_RX_SW_BUFFER_CONST) */ #if (EzI2C_INTERNAL_TX_SW_BUFFER_CONST) uint32 locTail; #endif /* (EzI2C_INTERNAL_TX_SW_BUFFER_CONST) */ #ifdef EzI2C_SPI_UART_ISR_ENTRY_CALLBACK EzI2C_SPI_UART_ISR_EntryCallback(); #endif /* EzI2C_SPI_UART_ISR_ENTRY_CALLBACK */ if (NULL != EzI2C_customIntrHandler) { EzI2C_customIntrHandler(); } #if(EzI2C_CHECK_SPI_WAKE_ENABLE) { /* Clear SPI wakeup source */ EzI2C_ClearSpiExtClkInterruptSource(EzI2C_INTR_SPI_EC_WAKE_UP); } #endif #if (EzI2C_CHECK_RX_SW_BUFFER) { if (EzI2C_CHECK_INTR_RX_MASKED(EzI2C_INTR_RX_NOT_EMPTY)) { do { /* Move local head index */ locHead = (EzI2C_rxBufferHead + 1u); /* Adjust local head index */ if (EzI2C_INTERNAL_RX_BUFFER_SIZE == locHead) { locHead = 0u; } if (locHead == EzI2C_rxBufferTail) { #if (EzI2C_CHECK_UART_RTS_CONTROL_FLOW) { /* There is no space in the software buffer - disable the * RX Not Empty interrupt source. The data elements are * still being received into the RX FIFO until the RTS signal * stops the transmitter. After the data element is read from the * buffer, the RX Not Empty interrupt source is enabled to * move the next data element in the software buffer. */ EzI2C_INTR_RX_MASK_REG &= ~EzI2C_INTR_RX_NOT_EMPTY; break; } #else { /* Overflow: through away received data element */ (void) EzI2C_RX_FIFO_RD_REG; EzI2C_rxBufferOverflow = (uint8) EzI2C_INTR_RX_OVERFLOW; } #endif } else { /* Store received data */ EzI2C_PutWordInRxBuffer(locHead, EzI2C_RX_FIFO_RD_REG); /* Move head index */ EzI2C_rxBufferHead = locHead; } } while(0u != EzI2C_GET_RX_FIFO_ENTRIES); EzI2C_ClearRxInterruptSource(EzI2C_INTR_RX_NOT_EMPTY); } } #endif #if (EzI2C_CHECK_TX_SW_BUFFER) { if (EzI2C_CHECK_INTR_TX_MASKED(EzI2C_INTR_TX_NOT_FULL)) { do { /* Check for room in TX software buffer */ if (EzI2C_txBufferHead != EzI2C_txBufferTail) { /* Move local tail index */ locTail = (EzI2C_txBufferTail + 1u); /* Adjust local tail index */ if (EzI2C_TX_BUFFER_SIZE == locTail) { locTail = 0u; } /* Put data into TX FIFO */ EzI2C_TX_FIFO_WR_REG = EzI2C_GetWordFromTxBuffer(locTail); /* Move tail index */ EzI2C_txBufferTail = locTail; } else { /* TX software buffer is empty: complete transfer */ EzI2C_DISABLE_INTR_TX(EzI2C_INTR_TX_NOT_FULL); break; } } while (EzI2C_SPI_UART_FIFO_SIZE != EzI2C_GET_TX_FIFO_ENTRIES); EzI2C_ClearTxInterruptSource(EzI2C_INTR_TX_NOT_FULL); } } #endif #ifdef EzI2C_SPI_UART_ISR_EXIT_CALLBACK EzI2C_SPI_UART_ISR_ExitCallback(); #endif /* EzI2C_SPI_UART_ISR_EXIT_CALLBACK */ } #endif /* (EzI2C_SCB_IRQ_INTERNAL) */ /* [] END OF FILE */
365298.c
/* $NetBSD: race.c,v 1.4 2014/12/10 04:37:55 christos Exp $ */ #ifndef lint static char *rcsid = "Id: race.c,v 1.1 2003/06/04 00:26:07 marka Exp "; #endif /* * Copyright (c) 2000,2001,2002 Japan Network Information Center. * All rights reserved. * * By using this file, you agree to the terms and conditions set forth bellow. * * LICENSE TERMS AND CONDITIONS * * The following License Terms and Conditions apply, unless a different * license is obtained from Japan Network Information Center ("JPNIC"), * a Japanese association, Kokusai-Kougyou-Kanda Bldg 6F, 2-3-4 Uchi-Kanda, * Chiyoda-ku, Tokyo 101-0047, Japan. * * 1. Use, Modification and Redistribution (including distribution of any * modified or derived work) in source and/or binary forms is permitted * under this License Terms and Conditions. * * 2. Redistribution of source code must retain the copyright notices as they * appear in each source code file, this License Terms and Conditions. * * 3. Redistribution in binary form must reproduce the Copyright Notice, * this License Terms and Conditions, in the documentation and/or other * materials provided with the distribution. For the purposes of binary * distribution the "Copyright Notice" refers to the following language: * "Copyright (c) 2000-2002 Japan Network Information Center. All rights reserved." * * 4. The name of JPNIC may not be used to endorse or promote products * derived from this Software without specific prior written approval of * JPNIC. * * 5. Disclaimer/Limitation of Liability: THIS SOFTWARE IS PROVIDED BY JPNIC * "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 JPNIC 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 DAMAGES. */ #include <config.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <idn/result.h> #include <idn/assert.h> #include <idn/logmacro.h> #include <idn/converter.h> #include <idn/ucs4.h> #include <idn/debug.h> #include <idn/race.h> #include <idn/util.h> #ifndef IDN_RACE_PREFIX #define IDN_RACE_PREFIX "bq--" #endif #define RACE_2OCTET_MODE 0xd8 #define RACE_ESCAPE 0xff #define RACE_ESCAPE_2ND 0x99 #define RACE_BUF_SIZE 128 /* more than enough */ /* * Unicode surrogate pair. */ #define IS_SURROGATE_HIGH(v) (0xd800 <= (v) && (v) <= 0xdbff) #define IS_SURROGATE_LOW(v) (0xdc00 <= (v) && (v) <= 0xdfff) #define SURROGATE_HIGH(v) (SURROGATE_H_OFF + (((v) - 0x10000) >> 10)) #define SURROGATE_LOW(v) (SURROGATE_L_OFF + ((v) & 0x3ff)) #define SURROGATE_BASE 0x10000 #define SURROGATE_H_OFF 0xd800 #define SURROGATE_L_OFF 0xdc00 #define COMBINE_SURROGATE(h, l) \ (SURROGATE_BASE + (((h)-SURROGATE_H_OFF)<<10) + ((l)-SURROGATE_L_OFF)) /* * Compression type. */ enum { compress_one, /* all characters are in a single row */ compress_two, /* row 0 and another row */ compress_none /* nope */ }; static idn_result_t race_decode_decompress(const char *from, unsigned short *buf, size_t buflen); static idn_result_t race_compress_encode(const unsigned short *p, int compress_mode, char *to, size_t tolen); static int get_compress_mode(unsigned short *p); idn_result_t idn__race_decode(idn_converter_t ctx, void *privdata, const char *from, unsigned long *to, size_t tolen) { unsigned short *buf = NULL; size_t prefixlen = strlen(IDN_RACE_PREFIX); size_t fromlen; size_t buflen; idn_result_t r; assert(ctx != NULL); TRACE(("idn__race_decode(from=\"%s\", tolen=%d)\n", idn__debug_xstring(from, 50), (int)tolen)); if (!idn__util_asciihaveaceprefix(from, IDN_RACE_PREFIX)) { if (*from == '\0') { r = idn_ucs4_utf8toucs4(from, to, tolen); goto ret; } r = idn_invalid_encoding; goto ret; } from += prefixlen; fromlen = strlen(from); /* * Allocate sufficient buffer. */ buflen = fromlen + 1; buf = malloc(sizeof(*buf) * buflen); if (buf == NULL) { r = idn_nomemory; goto ret; } /* * Decode base32 and decompress. */ r = race_decode_decompress(from, buf, buflen); if (r != idn_success) goto ret; /* * Now 'buf' points the decompressed string, which must contain * UTF-16 characters. */ /* * Convert to UCS4. */ r = idn_ucs4_utf16toucs4(buf, to, tolen); if (r != idn_success) goto ret; ret: free(buf); if (r == idn_success) { TRACE(("idn__race_decode(): succcess (to=\"%s\")\n", idn__debug_ucs4xstring(to, 50))); } else { TRACE(("idn__race_decode(): %s\n", idn_result_tostring(r))); } return (r); } static idn_result_t race_decode_decompress(const char *from, unsigned short *buf, size_t buflen) { unsigned short *p = buf; unsigned int bitbuf = 0; int bitlen = 0; int i, j; size_t len; while (*from != '\0') { int c = *from++; int x; if ('a' <= c && c <= 'z') x = c - 'a'; else if ('A' <= c && c <= 'Z') x = c - 'A'; else if ('2' <= c && c <= '7') x = c - '2' + 26; else return (idn_invalid_encoding); bitbuf = (bitbuf << 5) + x; bitlen += 5; if (bitlen >= 8) { *p++ = (bitbuf >> (bitlen - 8)) & 0xff; bitlen -= 8; } } len = p - buf; /* * Now 'buf' holds the decoded string. */ /* * Decompress. */ if (buf[0] == RACE_2OCTET_MODE) { if ((len - 1) % 2 != 0) return (idn_invalid_encoding); for (i = 1, j = 0; i < len; i += 2, j++) buf[j] = (buf[i] << 8) + buf[i + 1]; len = j; } else { unsigned short c = buf[0] << 8; /* higher octet */ for (i = 1, j = 0; i < len; j++) { if (buf[i] == RACE_ESCAPE) { if (i + 1 >= len) return (idn_invalid_encoding); else if (buf[i + 1] == RACE_ESCAPE_2ND) buf[j] = c | 0xff; else buf[j] = buf[i + 1]; i += 2; } else if (buf[i] == 0x99 && c == 0x00) { /* * The RACE specification says this is error. */ return (idn_invalid_encoding); } else { buf[j] = c | buf[i++]; } } len = j; } buf[len] = '\0'; return (idn_success); } idn_result_t idn__race_encode(idn_converter_t ctx, void *privdata, const unsigned long *from, char *to, size_t tolen) { char *to_org = to; unsigned short *p, *buf = NULL; size_t prefixlen = strlen(IDN_RACE_PREFIX); size_t buflen; size_t fromlen; idn_result_t r; int compress_mode; assert(ctx != NULL); TRACE(("idn__race_encode(from=\"%s\", tolen=%d)\n", idn__debug_ucs4xstring(from, 50), (int)tolen)); if (*from == '\0') { r = idn_ucs4_ucs4toutf8(from, to, tolen); goto ret; } else if (idn__util_ucs4haveaceprefix(from, IDN_RACE_PREFIX)) { r = idn_prohibited; goto ret; } if (tolen < prefixlen) { r = idn_buffer_overflow; goto ret; } memcpy(to, IDN_RACE_PREFIX, prefixlen); to += prefixlen; tolen -= prefixlen; fromlen = idn_ucs4_strlen(from); buflen = fromlen * 2 + 2; /* * Convert to UTF-16. * Preserve space for a character at the top of the buffer. */ for (;;) { unsigned short *new_buf; new_buf = realloc(buf, sizeof(*buf) * buflen); if (new_buf == NULL) { r = idn_nomemory; goto ret; } buf = new_buf; r = idn_ucs4_ucs4toutf16(from, buf + 1, buflen - 1); if (r == idn_success) break; else if (r != idn_buffer_overflow) goto ret; buflen = fromlen * 2 + 2; } p = buf + 1; /* * Now 'p' contains UTF-16 encoded string. */ /* * Check U+0099. * RACE doesn't permit U+0099 in an input string. */ for (p = buf + 1; *p != '\0'; p++) { if (*p == 0x0099) { r = idn_invalid_encoding; goto ret; } } /* * Compress, encode in base-32 and output. */ compress_mode = get_compress_mode(buf + 1); r = race_compress_encode(buf, compress_mode, to, tolen); ret: free(buf); if (r == idn_success) { TRACE(("idn__race_encode(): succcess (to=\"%s\")\n", idn__debug_xstring(to_org, 50))); } else { TRACE(("idn__race_encode(): %s\n", idn_result_tostring(r))); } return (r); } static idn_result_t race_compress_encode(const unsigned short *p, int compress_mode, char *to, size_t tolen) { unsigned long bitbuf = *p++; /* bit stream buffer */ int bitlen = 8; /* # of bits in 'bitbuf' */ while (*p != '\0' || bitlen > 0) { unsigned int c = *p; if (c == '\0') { /* End of data. Flush. */ bitbuf <<= (5 - bitlen); bitlen = 5; } else if (compress_mode == compress_none) { /* Push 16 bit data. */ bitbuf = (bitbuf << 16) | c; bitlen += 16; p++; } else {/* compress_mode == compress_one/compress_two */ /* Push 8 or 16 bit data. */ if (compress_mode == compress_two && (c & 0xff00) == 0) { /* Upper octet is zero (and not U1). */ bitbuf = (bitbuf << 16) | 0xff00 | c; bitlen += 16; } else if ((c & 0xff) == 0xff) { /* Lower octet is 0xff. */ bitbuf = (bitbuf << 16) | (RACE_ESCAPE << 8) | RACE_ESCAPE_2ND; bitlen += 16; } else { /* Just output lower octet. */ bitbuf = (bitbuf << 8) | (c & 0xff); bitlen += 8; } p++; } /* * Output bits in 'bitbuf' in 5-bit unit. */ while (bitlen >= 5) { int x; /* Get top 5 bits. */ x = (bitbuf >> (bitlen - 5)) & 0x1f; bitlen -= 5; /* Encode. */ if (x < 26) x += 'a'; else x = (x - 26) + '2'; if (tolen < 1) return (idn_buffer_overflow); *to++ = x; tolen--; } } if (tolen <= 0) return (idn_buffer_overflow); *to = '\0'; return (idn_success); } static int get_compress_mode(unsigned short *p) { int zero = 0; unsigned int upper = 0; unsigned short *modepos = p - 1; while (*p != '\0') { unsigned int hi = *p++ & 0xff00; if (hi == 0) { zero++; } else if (hi == upper) { ; } else if (upper == 0) { upper = hi; } else { *modepos = RACE_2OCTET_MODE; return (compress_none); } } *modepos = upper >> 8; if (upper > 0 && zero > 0) return (compress_two); else return (compress_one); }
996821.c
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. */ /* based on https://github.com/brainhub/SHA3IUF (public domain) */ #include "tomcrypt.h" #ifdef LTC_SHA3 const struct ltc_hash_descriptor sha3_224_desc = { "sha3-224", /* name of hash */ 17, /* internal ID */ 28, /* Size of digest in octets */ 128, /* Input block size in octets */ { 2,16,840,1,101,3,4,2,7 }, /* ASN.1 OID */ 9, /* Length OID */ &sha3_224_init, &sha3_process, &sha3_done, &sha3_224_test, NULL }; const struct ltc_hash_descriptor sha3_256_desc = { "sha3-256", /* name of hash */ 18, /* internal ID */ 32, /* Size of digest in octets */ 128, /* Input block size in octets */ { 2,16,840,1,101,3,4,2,8 }, /* ASN.1 OID */ 9, /* Length OID */ &sha3_256_init, &sha3_process, &sha3_done, &sha3_256_test, NULL }; const struct ltc_hash_descriptor sha3_384_desc = { "sha3-384", /* name of hash */ 19, /* internal ID */ 48, /* Size of digest in octets */ 128, /* Input block size in octets */ { 2,16,840,1,101,3,4,2,9 }, /* ASN.1 OID */ 9, /* Length OID */ &sha3_384_init, &sha3_process, &sha3_done, &sha3_384_test, NULL }; const struct ltc_hash_descriptor sha3_512_desc = { "sha3-512", /* name of hash */ 20, /* internal ID */ 64, /* Size of digest in octets */ 128, /* Input block size in octets */ { 2,16,840,1,101,3,4,2,10 }, /* ASN.1 OID */ 9, /* Length OID */ &sha3_512_init, &sha3_process, &sha3_done, &sha3_512_test, NULL }; #define SHA3_KECCAK_SPONGE_WORDS 25 /* 1600 bits > 200 bytes > 25 x ulong64 */ #define SHA3_KECCAK_ROUNDS 24 static const ulong64 keccakf_rndc[24] = { CONST64(0x0000000000000001), CONST64(0x0000000000008082), CONST64(0x800000000000808a), CONST64(0x8000000080008000), CONST64(0x000000000000808b), CONST64(0x0000000080000001), CONST64(0x8000000080008081), CONST64(0x8000000000008009), CONST64(0x000000000000008a), CONST64(0x0000000000000088), CONST64(0x0000000080008009), CONST64(0x000000008000000a), CONST64(0x000000008000808b), CONST64(0x800000000000008b), CONST64(0x8000000000008089), CONST64(0x8000000000008003), CONST64(0x8000000000008002), CONST64(0x8000000000000080), CONST64(0x000000000000800a), CONST64(0x800000008000000a), CONST64(0x8000000080008081), CONST64(0x8000000000008080), CONST64(0x0000000080000001), CONST64(0x8000000080008008) }; static const unsigned keccakf_rotc[24] = { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44 }; static const unsigned keccakf_piln[24] = { 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1 }; static void keccakf(ulong64 s[25]) { int i, j, round; ulong64 t, bc[5]; for(round = 0; round < SHA3_KECCAK_ROUNDS; round++) { /* Theta */ for(i = 0; i < 5; i++) bc[i] = s[i] ^ s[i + 5] ^ s[i + 10] ^ s[i + 15] ^ s[i + 20]; for(i = 0; i < 5; i++) { t = bc[(i + 4) % 5] ^ ROL64(bc[(i + 1) % 5], 1); for(j = 0; j < 25; j += 5) s[j + i] ^= t; } /* Rho Pi */ t = s[1]; for(i = 0; i < 24; i++) { j = keccakf_piln[i]; bc[0] = s[j]; s[j] = ROL64(t, keccakf_rotc[i]); t = bc[0]; } /* Chi */ for(j = 0; j < 25; j += 5) { for(i = 0; i < 5; i++) bc[i] = s[j + i]; for(i = 0; i < 5; i++) s[j + i] ^= (~bc[(i + 1) % 5]) & bc[(i + 2) % 5]; } /* Iota */ s[0] ^= keccakf_rndc[round]; } } /* Public Inteface */ int sha3_224_init(hash_state *md) { LTC_ARGCHK(md != NULL); XMEMSET(&md->sha3, 0, sizeof(md->sha3)); md->sha3.capacity_words = 2 * 224 / (8 * sizeof(ulong64)); return CRYPT_OK; } int sha3_256_init(hash_state *md) { LTC_ARGCHK(md != NULL); XMEMSET(&md->sha3, 0, sizeof(md->sha3)); md->sha3.capacity_words = 2 * 256 / (8 * sizeof(ulong64)); return CRYPT_OK; } int sha3_384_init(hash_state *md) { LTC_ARGCHK(md != NULL); XMEMSET(&md->sha3, 0, sizeof(md->sha3)); md->sha3.capacity_words = 2 * 384 / (8 * sizeof(ulong64)); return CRYPT_OK; } int sha3_512_init(hash_state *md) { LTC_ARGCHK(md != NULL); XMEMSET(&md->sha3, 0, sizeof(md->sha3)); md->sha3.capacity_words = 2 * 512 / (8 * sizeof(ulong64)); return CRYPT_OK; } int sha3_shake_init(hash_state *md, int num) { LTC_ARGCHK(md != NULL); if (num != 128 && num != 256) return CRYPT_INVALID_ARG; XMEMSET(&md->sha3, 0, sizeof(md->sha3)); md->sha3.capacity_words = (unsigned short)(2 * num / (8 * sizeof(ulong64))); return CRYPT_OK; } int sha3_process(hash_state *md, const unsigned char *in, unsigned long inlen) { /* 0...7 -- how much is needed to have a word */ unsigned old_tail = (8 - md->sha3.byte_index) & 7; unsigned long words; unsigned tail; unsigned long i; if (inlen == 0) return CRYPT_OK; /* nothing to do */ LTC_ARGCHK(md != NULL); LTC_ARGCHK(in != NULL); if(inlen < old_tail) { /* have no complete word or haven't started the word yet */ while (inlen--) md->sha3.saved |= (ulong64) (*(in++)) << ((md->sha3.byte_index++) * 8); return CRYPT_OK; } if(old_tail) { /* will have one word to process */ inlen -= old_tail; while (old_tail--) md->sha3.saved |= (ulong64) (*(in++)) << ((md->sha3.byte_index++) * 8); /* now ready to add saved to the sponge */ md->sha3.s[md->sha3.word_index] ^= md->sha3.saved; md->sha3.byte_index = 0; md->sha3.saved = 0; if(++md->sha3.word_index == (SHA3_KECCAK_SPONGE_WORDS - md->sha3.capacity_words)) { keccakf(md->sha3.s); md->sha3.word_index = 0; } } /* now work in full words directly from input */ words = inlen / sizeof(ulong64); tail = inlen - words * sizeof(ulong64); for(i = 0; i < words; i++, in += sizeof(ulong64)) { ulong64 t; LOAD64L(t, in); md->sha3.s[md->sha3.word_index] ^= t; if(++md->sha3.word_index == (SHA3_KECCAK_SPONGE_WORDS - md->sha3.capacity_words)) { keccakf(md->sha3.s); md->sha3.word_index = 0; } } /* finally, save the partial word */ while (tail--) { md->sha3.saved |= (ulong64) (*(in++)) << ((md->sha3.byte_index++) * 8); } return CRYPT_OK; } int sha3_done(hash_state *md, unsigned char *hash) { unsigned i; LTC_ARGCHK(md != NULL); LTC_ARGCHK(hash != NULL); md->sha3.s[md->sha3.word_index] ^= (md->sha3.saved ^ (CONST64(0x06) << (md->sha3.byte_index * 8))); md->sha3.s[SHA3_KECCAK_SPONGE_WORDS - md->sha3.capacity_words - 1] ^= CONST64(0x8000000000000000); keccakf(md->sha3.s); /* store sha3.s[] as little-endian bytes into sha3.sb */ for(i = 0; i < SHA3_KECCAK_SPONGE_WORDS; i++) { STORE64L(md->sha3.s[i], md->sha3.sb + i * 8); } XMEMCPY(hash, md->sha3.sb, md->sha3.capacity_words * 4); return CRYPT_OK; } int sha3_shake_done(hash_state *md, unsigned char *out, unsigned long outlen) { /* IMPORTANT NOTE: sha3_shake_done can be called many times */ unsigned long idx; unsigned i; if (outlen == 0) return CRYPT_OK; /* nothing to do */ LTC_ARGCHK(md != NULL); LTC_ARGCHK(out != NULL); if (!md->sha3.xof_flag) { /* shake_xof operation must be done only once */ md->sha3.s[md->sha3.word_index] ^= (md->sha3.saved ^ (CONST64(0x1F) << (md->sha3.byte_index * 8))); md->sha3.s[SHA3_KECCAK_SPONGE_WORDS - md->sha3.capacity_words - 1] ^= CONST64(0x8000000000000000); keccakf(md->sha3.s); /* store sha3.s[] as little-endian bytes into sha3.sb */ for(i = 0; i < SHA3_KECCAK_SPONGE_WORDS; i++) { STORE64L(md->sha3.s[i], md->sha3.sb + i * 8); } md->sha3.byte_index = 0; md->sha3.xof_flag = 1; } for (idx = 0; idx < outlen; idx++) { if(md->sha3.byte_index >= (SHA3_KECCAK_SPONGE_WORDS - md->sha3.capacity_words) * 8) { keccakf(md->sha3.s); /* store sha3.s[] as little-endian bytes into sha3.sb */ for(i = 0; i < SHA3_KECCAK_SPONGE_WORDS; i++) { STORE64L(md->sha3.s[i], md->sha3.sb + i * 8); } md->sha3.byte_index = 0; } out[idx] = md->sha3.sb[md->sha3.byte_index++]; } return CRYPT_OK; } int sha3_shake_memory(int num, const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen) { hash_state md; int err; LTC_ARGCHK(in != NULL); LTC_ARGCHK(out != NULL); LTC_ARGCHK(outlen != NULL); if ((err = sha3_shake_init(&md, num)) != CRYPT_OK) return err; if ((err = sha3_shake_process(&md, in, inlen)) != CRYPT_OK) return err; if ((err = sha3_shake_done(&md, out, *outlen)) != CRYPT_OK) return err; return CRYPT_OK; } #endif
939063.c
#include <windows.h> #include <stdio.h> #define MIN_STR_LEN 4 // FindStr takes a buffer cwith the loaded file, and its size // It then prints all null terminiated ASCII range strings void FindString(char* buffer, DWORD bufferSize){ char asciiMin = 32; char asciiMax = 126; // //your solution here! } // Loads The file contents, calculates the size, then calls FindStr void MyStrings (char * fileName){ //GetFileSize DWORD fileSize; char* buffer; // //your solution here! } int main(int argc, char* argv[]){ if(argc != 2){ printf("Usage: %s <filename>\n", argv[0]); return 0; } MyStrings(argv[1]); }
384456.c
/* * FreeRTOS V202112.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice 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. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" /* Xilinx includes. */ #include "xscutimer.h" #include "xscugic.h" #define XSCUTIMER_CLOCK_HZ ( XPAR_CPU_CORTEXA9_0_CPU_CLK_FREQ_HZ / 2UL ) static XScuTimer xTimer; XScuGic xInterruptController; /* Interrupt controller instance */ /* * The application must provide a function that configures a peripheral to * create the FreeRTOS tick interrupt, then define configSETUP_TICK_INTERRUPT() * in FreeRTOSConfig.h to call the function. This file contains a function * that is suitable for use on the Zynq SoC. */ void vConfigureTickInterrupt( void ) { BaseType_t xStatus; extern void FreeRTOS_Tick_Handler( void ); XScuTimer_Config *pxTimerConfig; XScuGic_Config *pxGICConfig; const uint8_t ucRisingEdge = 3; /* This function is called with the IRQ interrupt disabled, and the IRQ interrupt should be left disabled. It is enabled automatically when the scheduler is started. */ /* Ensure XScuGic_CfgInitialize() has been called. In this demo it has already been called from prvSetupHardware() in main(). */ pxGICConfig = XScuGic_LookupConfig( XPAR_SCUGIC_SINGLE_DEVICE_ID ); xStatus = XScuGic_CfgInitialize( &xInterruptController, pxGICConfig, pxGICConfig->CpuBaseAddress ); configASSERT( xStatus == XST_SUCCESS ); ( void ) xStatus; /* Remove compiler warning if configASSERT() is not defined. */ /* The priority must be the lowest possible. */ XScuGic_SetPriorityTriggerType( &xInterruptController, XPAR_SCUTIMER_INTR, portLOWEST_USABLE_INTERRUPT_PRIORITY << portPRIORITY_SHIFT, ucRisingEdge ); /* Install the FreeRTOS tick handler. */ xStatus = XScuGic_Connect( &xInterruptController, XPAR_SCUTIMER_INTR, (Xil_ExceptionHandler) FreeRTOS_Tick_Handler, ( void * ) &xTimer ); configASSERT( xStatus == XST_SUCCESS ); ( void ) xStatus; /* Remove compiler warning if configASSERT() is not defined. */ /* Initialise the timer. */ pxTimerConfig = XScuTimer_LookupConfig( XPAR_SCUTIMER_DEVICE_ID ); xStatus = XScuTimer_CfgInitialize( &xTimer, pxTimerConfig, pxTimerConfig->BaseAddr ); configASSERT( xStatus == XST_SUCCESS ); ( void ) xStatus; /* Remove compiler warning if configASSERT() is not defined. */ /* Enable Auto reload mode. */ XScuTimer_EnableAutoReload( &xTimer ); /* Ensure there is no prescale. */ XScuTimer_SetPrescaler( &xTimer, 0 ); /* Load the timer counter register. */ XScuTimer_LoadTimer( &xTimer, XSCUTIMER_CLOCK_HZ / configTICK_RATE_HZ ); /* Start the timer counter and then wait for it to timeout a number of times. */ XScuTimer_Start( &xTimer ); /* Enable the interrupt for the xTimer in the interrupt controller. */ XScuGic_Enable( &xInterruptController, XPAR_SCUTIMER_INTR ); /* Enable the interrupt in the xTimer itself. */ vClearTickInterrupt(); XScuTimer_EnableInterrupt( &xTimer ); } /*-----------------------------------------------------------*/ void vClearTickInterrupt( void ) { XScuTimer_ClearInterruptStatus( &xTimer ); } /*-----------------------------------------------------------*/ /* This is the callback function which is called by the FreeRTOS Cortex-A port layer in response to an interrupt. If the function is called vApplicationFPUSafeIRQHandler() then it is called after the floating point registers have been saved. If the function is called vApplicationIRQHandler() then it will be called without first having saved the FPU registers. See http://www.freertos.org/Using-FreeRTOS-on-Cortex-A-Embedded-Processors.html for more information */ void vApplicationFPUSafeIRQHandler( uint32_t ulICCIAR ) { extern const XScuGic_Config XScuGic_ConfigTable[]; static const XScuGic_VectorTableEntry *pxVectorTable = XScuGic_ConfigTable[ XPAR_SCUGIC_SINGLE_DEVICE_ID ].HandlerTable; uint32_t ulInterruptID; const XScuGic_VectorTableEntry *pxVectorEntry; /* Re-enable interrupts. */ __asm ( "cpsie i" ); /* The ID of the interrupt is obtained by bitwise anding the ICCIAR value with 0x3FF. */ ulInterruptID = ulICCIAR & 0x3FFUL; if( ulInterruptID < XSCUGIC_MAX_NUM_INTR_INPUTS ) { /* Call the function installed in the array of installed handler functions. */ pxVectorEntry = &( pxVectorTable[ ulInterruptID ] ); pxVectorEntry->Handler( pxVectorEntry->CallBackRef ); } }
830016.c
/* * Copyright (C) 2017 Vabishchevich Nikolay <[email protected]> * * This file is part of libass. * * 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. */ #include "image.h" #include "../libass/ass.h" #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <string.h> #define FFMAX(a,b) ((a) > (b) ? (a) : (b)) #define FFMIN(a,b) ((a) > (b) ? (b) : (a)) static void blend_image(Image8 *frame, int32_t x0, int32_t y0, const ASS_Image *img) { int32_t x1 = img->dst_x, x_min = FFMAX(x0, x1); int32_t y1 = img->dst_y, y_min = FFMAX(y0, y1); x0 = x_min - x0; x1 = x_min - x1; y0 = y_min - y0; y1 = y_min - y1; int32_t w = FFMIN(x0 + frame->width, x1 + img->w); int32_t h = FFMIN(y0 + frame->height, y1 + img->h); if (w <= 0 || h <= 0) return; uint8_t r = img->color >> 24; uint8_t g = img->color >> 16; uint8_t b = img->color >> 8; uint8_t a = img->color >> 0; int32_t mul = 129 * (255 - a); const int32_t offs = (int32_t) 1 << 22; int32_t stride = 4 * frame->width; uint8_t *dst = frame->buffer + y0 * stride + 4 * x0; const uint8_t *src = img->bitmap + y1 * img->stride + x1; for (int32_t y = 0; y < h; y++) { for (int32_t x = 0; x < w; x++) { int32_t k = src[x] * mul; dst[4 * x + 0] -= ((dst[4 * x + 0] - r) * k + offs) >> 23; dst[4 * x + 1] -= ((dst[4 * x + 1] - g) * k + offs) >> 23; dst[4 * x + 2] -= ((dst[4 * x + 2] - b) * k + offs) >> 23; dst[4 * x + 3] -= ((dst[4 * x + 3] - 0) * k + offs) >> 23; } dst += stride; src += img->stride; } } static void blend_all(Image8 *frame, int32_t x0, int32_t y0, const ASS_Image *img) { uint8_t *dst = frame->buffer; size_t size = (size_t) frame->width * frame->height; for (size_t i = 0; i < size; i++) { dst[0] = dst[1] = dst[2] = 0; dst[3] = 255; dst += 4; } for (; img; img = img->next) blend_image(frame, x0, y0, img); } inline static uint16_t abs_diff(uint16_t a, uint16_t b) { return a > b ? a - b : b - a; } inline static uint16_t abs_diff4(const uint16_t a[4], const uint16_t b[4]) { uint16_t res = 0; for (int k = 0; k < 4; k++) { uint16_t diff = abs_diff(a[k], b[k]); res = FFMAX(res, diff); } return res; } // Calculate error visibility scale according to formula: // max_pixel_value / 255 + max(max_side_gradient / 4, max_diagonal_gradient / 8). static void calc_grad(const Image16 *target, uint16_t *grad) { const int base = 257; const int border = base + 65535 / 4; int32_t w = target->width; int32_t h = target->height; int32_t stride = 4 * target->width; for (int32_t x = 0; x < w; x++) *grad++ = border; const uint16_t *tg = target->buffer + stride + 4; for (int32_t y = 1; y < h - 1; y++) { *grad++ = border; for (int32_t x = 1; x < w - 1; x++) { uint16_t g[8]; g[0] = abs_diff4(tg, tg - 4) / 4; g[1] = abs_diff4(tg, tg + 4) / 4; g[2] = abs_diff4(tg, tg - stride) / 4; g[3] = abs_diff4(tg, tg + stride) / 4; g[4] = abs_diff4(tg, tg - stride - 4) / 8; g[5] = abs_diff4(tg, tg - stride + 4) / 8; g[6] = abs_diff4(tg, tg + stride - 4) / 8; g[7] = abs_diff4(tg, tg + stride + 4) / 8; uint16_t gg = g[0]; for (int k = 1; k < 8; k++) gg = FFMAX(gg, g[k]); *grad++ = base + gg; tg += 4; } *grad++ = border; tg += 8; } for (int32_t x = 0; x < w; x++) *grad++ = border; } static int compare1(const Image16 *target, const uint16_t *grad, const ASS_Image *img, const char *path, double *result) { Image8 frame; frame.width = target->width; frame.height = target->height; size_t size = (size_t) frame.width * frame.height; frame.buffer = malloc(4 * size); if (!frame.buffer) return 0; blend_all(&frame, 0, 0, img); double max_err = 0; const uint8_t *ptr = frame.buffer; const uint16_t *tg = target->buffer; for (size_t i = 0; i < size; i++) { uint16_t cmp[4]; for (int k = 0; k < 4; k++) cmp[k] = 257u * ptr[k]; double err = (double) abs_diff4(cmp, tg) / *grad++; if (max_err < err) max_err = err; ptr += 4; tg += 4; } int flag = path && !write_png8(path, &frame) ? -1 : 1; free(frame.buffer); *result = max_err; return flag; } static int compare(const Image16 *target, const uint16_t *grad, const ASS_Image *img, const char *path, double *result, int scale) { if (scale == 1) return compare1(target, grad, img, path, result); int scale2 = scale * scale; Image16 frame; frame.width = target->width; frame.height = target->height; size_t size = (size_t) frame.width * frame.height; frame.buffer = malloc(8 * size); if (!frame.buffer) return 0; Image8 temp; temp.width = scale * target->width; temp.height = scale * target->height; temp.buffer = malloc(4 * scale2 * size); if (!temp.buffer) { free(frame.buffer); return 0; } blend_all(&temp, 0, 0, img); uint16_t *dst = frame.buffer; const uint8_t *src = temp.buffer; int32_t stride = 4 * temp.width; const uint32_t offs = ((uint32_t) 1 << 18) - 1; uint32_t mul = ((uint32_t) 257 << 19) / scale2; for (int32_t y = 0; y < frame.height; y++) { for (int32_t x = 0; x < frame.width; x++) { uint16_t res[4] = {0}; const uint8_t *ptr = src; for (int i = 0; i < scale; i++) { for (int j = 0; j < scale; j++) for (int k = 0; k < 4; k++) res[k] += ptr[4 * j + k]; ptr += stride; } for (int k = 0; k < 4; k++) // equivalent to (257 * res[k] + (scale2 - 1) / 2) / scale2; *dst++ = (res[k] * (uint64_t) mul + offs) >> 19; src += 4 * scale; } src += (scale - 1) * stride; } free(temp.buffer); double max_err = 0; const uint16_t *ptr = frame.buffer; const uint16_t *tg = target->buffer; for (size_t i = 0; i < size; i++) { double err = (double) abs_diff4(ptr, tg) / *grad++; if (max_err < err) max_err = err; ptr += 4; tg += 4; } int flag = path && !write_png16(path, &frame) ? -1 : 1; free(frame.buffer); *result = max_err; return flag; } static bool load_font(ASS_Library *lib, const char *dir, const char *file) { char path[4096]; snprintf(path, sizeof(path), "%s/%s", dir, file); FILE *fp = fopen(path, "rb"); if (!fp) return false; if (fseek(fp, 0, SEEK_END) == -1) { fclose(fp); return false; } long size = ftell(fp); if (size <= 0 || size > (1l << 30)) { fclose(fp); return false; } rewind(fp); char *buf = malloc(size); if (!buf) { fclose(fp); return false; } long pos = 0; while (pos < size) { size_t n = fread(buf + pos, 1, size - pos, fp); if (!n) { free(buf); fclose(fp); return false; } pos += n; } fclose(fp); printf("Loading font '%s'.\n", file); ass_add_font(lib, (char *) file, buf, size); free(buf); return true; } static ASS_Track *load_track(ASS_Library *lib, const char *dir, const char *file) { char path[4096]; snprintf(path, sizeof(path), "%s/%s.ass", dir, file); ASS_Track *track = ass_read_file(lib, path, NULL); if (!track) { printf("Cannot load subtitle file '%s.ass'!\n", file); return NULL; } printf("Processing '%s.ass':\n", file); return track; } static bool out_of_memory() { printf("Not enough memory!\n"); return false; } static bool process_image(ASS_Renderer *renderer, ASS_Track *track, const char *input, const char *output, const char *file, int64_t time, int scale) { uint64_t tm = time; unsigned msec = tm % 1000; tm /= 1000; unsigned sec = tm % 60; tm /= 60; unsigned min = tm % 60; tm /= 60; printf(" Time %u:%02u:%02u.%03u - ", (unsigned) tm, min, sec, msec); char path[4096]; snprintf(path, sizeof(path), "%s/%s", input, file); Image16 target; if (!read_png(path, &target)) { printf("PNG reading failed!\n"); return false; } uint16_t *grad = malloc(2 * target.width * target.height); if (!grad) { free(target.buffer); return out_of_memory(); } calc_grad(&target, grad); ass_set_frame_size(renderer, scale * target.width, scale * target.height); ASS_Image *img = ass_render_frame(renderer, track, time, NULL); const char *out_file = NULL; if (output) { snprintf(path, sizeof(path), "%s/%s", output, file); out_file = path; } double max_err; int res = compare(&target, grad, img, out_file, &max_err, scale); free(target.buffer); free(grad); if (!res) return out_of_memory(); bool flag = max_err < 4; printf("%.3f %s\n", max_err, flag ? (max_err < 2 ? "OK" : "BAD") : "FAIL"); if (res < 0) printf("Cannot write PNG to file '%s'!\n", path); return flag; } typedef struct { char *name; int64_t time; } Item; typedef struct { size_t n_items, max_items; Item *items; } ItemList; static bool init_items(ItemList *list) { int n = 256; list->n_items = list->max_items = 0; list->items = malloc(n * sizeof(Item)); if (!list->items) return out_of_memory(); list->max_items = n; return true; } static bool add_item(ItemList *list) { if (list->n_items < list->max_items) return true; int n = 2 * list->max_items; Item *next = realloc(list->items, n * sizeof(Item)); if (!next) return out_of_memory(); list->max_items = n; list->items = next; return true; } static void delete_items(ItemList *list) { for (size_t i = 0; i < list->n_items; i++) free(list->items[i].name); free(list->items); } static int item_compare(const void *ptr1, const void *ptr2) { const Item *e1 = ptr1, *e2 = ptr2; int cmp = strcmp(e1->name, e2->name); if (cmp) return cmp; if (e1->time > e2->time) return +1; if (e1->time < e2->time) return -1; return 0; } static bool add_sub_item(ItemList *list, const char *file, int len) { if (!add_item(list)) return false; Item *item = &list->items[list->n_items]; item->name = strndup(file, len); if (!item->name) return out_of_memory(); item->time = -1; list->n_items++; return true; } static bool add_img_item(ItemList *list, const char *file, int len) { // Parse image name: // <subtitle_name>-<time_in_msec>.png int pos = len, first = len; while (true) { if (!pos--) return true; if (file[pos] == '-') break; if (file[pos] < '0' || file[pos] > '9') return true; if (file[pos] != '0') first = pos; } if (pos + 1 == len || first + 15 < len) return true; if (!add_item(list)) return false; Item *item = &list->items[list->n_items]; item->name = strdup(file); if (!item->name) return out_of_memory(); item->name[pos] = '\0'; item->time = 0; for (int i = first; i < len; i++) item->time = 10 * item->time + (file[i] - '0'); list->n_items++; return true; } static int print_usage(const char *program) { const char *fmt = "Usage: %s [-i] <input-dir> [-o <output-dir>] [-s <scale:1-8>]\n"; printf(fmt, program); return 1; } void msg_callback(int level, const char *fmt, va_list va, void *data) { if (level > 3) return; printf("libass: "); vprintf(fmt, va); printf("\n"); } int main(int argc, char *argv[]) { enum { INPUT, OUTPUT, SCALE }; int pos[3] = {0}; for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { if (pos[INPUT]) return print_usage(argv[0]); pos[INPUT] = i; continue; } int index; switch (argv[i][1]) { case 'i': index = INPUT; break; case 'o': index = OUTPUT; break; case 's': index = SCALE; break; default: return print_usage(argv[0]); } if (argv[i][2] || ++i >= argc || pos[index]) return print_usage(argv[0]); pos[index] = i; } if (!pos[INPUT]) return print_usage(argv[0]); int scale = 1; if (pos[SCALE]) { const char *arg = argv[pos[SCALE]]; if (arg[0] < '1' || arg[0] > '8' || arg[1]) { printf("Invalid scale value, should be 1-8!\n"); return 1; } scale = arg[0] - '0'; } const char *input = argv[pos[INPUT]]; DIR *dir = opendir(input); if (!dir) { printf("Cannot open input directory '%s'!\n", input); return 1; } const char *output = NULL; if (pos[OUTPUT]) { output = argv[pos[OUTPUT]]; struct stat st; if (stat(output, &st)) { if (mkdir(output, 0755)) { printf("Cannot create output directory '%s'!\n", output); closedir(dir); return 1; } } else if (!(st.st_mode & S_IFDIR)) { printf("Invalid output directory '%s'!\n", output); closedir(dir); return 1; } } ASS_Library *lib = ass_library_init(); if (!lib) { printf("ass_library_init failed!\n"); closedir(dir); return 1; } ass_set_message_cb(lib, msg_callback, NULL); ItemList list; if (!init_items(&list)) { ass_library_done(lib); closedir(dir); return 1; } while (true) { struct dirent *file = readdir(dir); if (!file) break; const char *name = file->d_name; if (name[0] == '.') continue; const char *ext = strrchr(name + 1, '.'); if (!ext) continue; if (!strcmp(ext, ".png")) { if (add_img_item(&list, name, ext - name)) continue; } else if (!strcmp(ext, ".ass")) { if (add_sub_item(&list, name, ext - name)) continue; } else if (!strcmp(ext, ".ttf") || !strcmp(ext, ".otf") || !strcmp(ext, ".pfb")) { if (load_font(lib, input, name)) continue; printf("Cannot load font '%s'!\n", name); } else { continue; } delete_items(&list); ass_library_done(lib); closedir(dir); return 1; } closedir(dir); ASS_Renderer *renderer = ass_renderer_init(lib); if (!renderer) { printf("ass_renderer_init failed!\n"); delete_items(&list); ass_library_done(lib); return 1; } ass_set_fonts(renderer, NULL, NULL, ASS_FONTPROVIDER_NONE, NULL, 0); int prefix; const char *prev = ""; ASS_Track *track = NULL; unsigned total = 0, good = 0; qsort(list.items, list.n_items, sizeof(Item), item_compare); for (size_t i = 0; i < list.n_items; i++) { if (strcmp(prev, list.items[i].name)) { if (track) ass_free_track(track); prev = list.items[i].name; prefix = strlen(prev); if (list.items[i].time < 0) track = load_track(lib, input, prev); else { printf("Missing subtitle file '%s.ass'!\n", prev); track = NULL; total++; } continue; } total++; if (!track) continue; char *name = list.items[i].name; name[prefix] = '-'; // restore initial filename if (process_image(renderer, track, input, output, name, list.items[i].time, scale)) good++; } if (track) ass_free_track(track); delete_items(&list); ass_renderer_done(renderer); ass_library_done(lib); if (good < total) { printf("Only %u of %u images have passed test\n", good, total); return 1; } printf("All %u images have passed test\n", total); return 0; }
817750.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/engineerr.h> #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA ENGINE_str_functs[] = { {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DIGEST_UPDATE, 0), "digest_update"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_CTRL, 0), "dynamic_ctrl"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_GET_DATA_CTX, 0), "dynamic_get_data_ctx"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_LOAD, 0), "dynamic_load"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_DYNAMIC_SET_DATA_CTX, 0), "dynamic_set_data_ctx"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_ADD, 0), "ENGINE_add"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_BY_ID, 0), "ENGINE_by_id"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CMD_IS_EXECUTABLE, 0), "ENGINE_cmd_is_executable"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL, 0), "ENGINE_ctrl"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL_CMD, 0), "ENGINE_ctrl_cmd"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_CTRL_CMD_STRING, 0), "ENGINE_ctrl_cmd_string"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_FINISH, 0), "ENGINE_finish"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_CIPHER, 0), "ENGINE_get_cipher"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_DIGEST, 0), "ENGINE_get_digest"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_FIRST, 0), "ENGINE_get_first"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_LAST, 0), "ENGINE_get_last"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_NEXT, 0), "ENGINE_get_next"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PKEY_ASN1_METH, 0), "ENGINE_get_pkey_asn1_meth"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PKEY_METH, 0), "ENGINE_get_pkey_meth"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_GET_PREV, 0), "ENGINE_get_prev"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_INIT, 0), "ENGINE_init"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LIST_ADD, 0), "engine_list_add"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LIST_REMOVE, 0), "engine_list_remove"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_PRIVATE_KEY, 0), "ENGINE_load_private_key"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_PUBLIC_KEY, 0), "ENGINE_load_public_key"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT, 0), "ENGINE_load_ssl_client_cert"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_NEW, 0), "ENGINE_new"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR, 0), "ENGINE_pkey_asn1_find_str"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_REMOVE, 0), "ENGINE_remove"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_DEFAULT_STRING, 0), "ENGINE_set_default_string"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_ID, 0), "ENGINE_set_id"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_SET_NAME, 0), "ENGINE_set_name"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_TABLE_REGISTER, 0), "engine_table_register"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_UNLOCKED_FINISH, 0), "engine_unlocked_finish"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_ENGINE_UP_REF, 0), "ENGINE_up_ref"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_CLEANUP_ITEM, 0), "int_cleanup_item"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_CTRL_HELPER, 0), "int_ctrl_helper"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_ENGINE_CONFIGURE, 0), "int_engine_configure"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_INT_ENGINE_MODULE_INIT, 0), "int_engine_module_init"}, {ERR_PACK(ERR_LIB_ENGINE, ENGINE_F_OSSL_HMAC_INIT, 0), "ossl_hmac_init"}, {0, NULL} }; static const ERR_STRING_DATA ENGINE_str_reasons[] = { {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ALREADY_LOADED), "already loaded"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER), "argument is not a number"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CMD_NOT_EXECUTABLE), "cmd not executable"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_INPUT), "command takes input"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_COMMAND_TAKES_NO_INPUT), "command takes no input"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CONFLICTING_ENGINE_ID), "conflicting engine id"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED), "ctrl command not implemented"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_FAILURE), "DSO failure"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_DSO_NOT_FOUND), "dso not found"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINES_SECTION_ERROR), "engines section error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_CONFIGURATION_ERROR), "engine configuration error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_IS_NOT_IN_LIST), "engine is not in the list"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ENGINE_SECTION_ERROR), "engine section error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PRIVATE_KEY), "failed loading private key"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FAILED_LOADING_PUBLIC_KEY), "failed loading public key"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_FINISH_FAILED), "finish failed"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_ID_OR_NAME_MISSING), "'id' or 'name' missing"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INIT_FAILED), "init failed"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INTERNAL_LIST_ERROR), "internal list error"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_ARGUMENT), "invalid argument"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NAME), "invalid cmd name"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_CMD_NUMBER), "invalid cmd number"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_INIT_VALUE), "invalid init value"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_INVALID_STRING), "invalid string"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_INITIALISED), "not initialised"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NOT_LOADED), "not loaded"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_CONTROL_FUNCTION), "no control function"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_INDEX), "no index"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_LOAD_FUNCTION), "no load function"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_REFERENCE), "no reference"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_NO_SUCH_ENGINE), "no such engine"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_CIPHER), "unimplemented cipher"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_DIGEST), "unimplemented digest"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD), "unimplemented public key method"}, {ERR_PACK(ERR_LIB_ENGINE, 0, ENGINE_R_VERSION_INCOMPATIBILITY), "version incompatibility"}, {0, NULL} }; #endif int ERR_load_ENGINE_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_func_error_string(ENGINE_str_functs[0].error) == NULL) { ERR_load_strings_const(ENGINE_str_functs); ERR_load_strings_const(ENGINE_str_reasons); } #endif return 1; }
582328.c
#include <hre/config.h> #include <stdlib.h> #include <assert.h> #include <aterm2.h> #include <hre/user.h> #include <vset-lib/vdom_object.h> static void WarningHandler(const char *format, va_list args) { FILE* f=log_get_stream(info); if (f) { fprintf(f,"%s: ",get_label()); ATvfprintf(f, format, args); fprintf(f,"\n"); } } static void ErrorHandler(const char *format, va_list args) { FILE* f=log_get_stream(error); if (f) { fprintf(f,"%s: ",get_label()); ATvfprintf(f, format, args); fprintf(f,"\n"); } Abort("ATerror"); } static void atermdd_popt(poptContext con, enum poptCallbackReason reason, const struct poptOption * opt, const char * arg, void * data){ (void)con;(void)opt;(void)arg;(void)data; switch(reason){ case POPT_CALLBACK_REASON_PRE: break; case POPT_CALLBACK_REASON_POST: { char*argv[]={"xxx",NULL}; if (HREglobal()!=NULL) { // work around for the case when HRE is not yet initialised ATinit(1, argv, (ATerm*) HREstackBottom()); ATsetWarningHandler(WarningHandler); ATsetErrorHandler(ErrorHandler); } return; } case POPT_CALLBACK_REASON_OPTION: break; } Abort("unexpected call to atermdd_popt"); } struct poptOption atermdd_options[]= { { NULL, 0 , POPT_ARG_CALLBACK|POPT_CBFLAG_POST|POPT_CBFLAG_SKIPOPTION , (void*)atermdd_popt , 0 , NULL , NULL }, POPT_TABLEEND }; struct vector_domain { struct vector_domain_shared shared; }; struct vector_set { vdom_t dom; ATerm set; int p_len; int proj[]; }; struct vector_relation { vdom_t dom; expand_cb expand; void *expand_ctx; ATerm rel; int p_len; int proj[]; }; static ATerm emptyset=NULL; static AFun cons; static AFun zip,min,sum,intersect,pi,reach,inv_reach,match,match3,rel_prod; static ATerm atom; static ATerm Atom=NULL; static ATerm Empty=NULL; static ATermTable global_ct=NULL; static ATermTable global_rc=NULL; // Used in saturation - relational product static ATermTable global_sc=NULL; // Used in saturation - saturation results static ATermTable global_uc=NULL; // Used in saturation - union results #define ATcmp ATcompare //define ATcmp(t1,t2) (((long)t1)-((long)t2)) #define HASH_INIT 1024 #define HASH_LOAD 75 static void set_reset_ct(){ if (global_ct!=NULL) { ATtableDestroy(global_ct); } global_ct=ATtableCreate(HASH_INIT,HASH_LOAD); } static void set_init() { ATprotect(&emptyset); ATprotect(&atom); emptyset=ATparse("VSET_E"); atom=ATparse("VSET_A"); cons=ATmakeAFun("VSET_C",3,ATfalse); ATprotectAFun(cons); zip=ATmakeAFun("VSET_ZIP",2,ATfalse); ATprotectAFun(zip); min=ATmakeAFun("VSET_MINUS",2,ATfalse); ATprotectAFun(min); sum=ATmakeAFun("VSET_UNION",2,ATfalse); ATprotectAFun(sum); intersect=ATmakeAFun("VSET_INTERSECT",2,ATfalse); ATprotectAFun(intersect); match=ATmakeAFun("VSET_MATCH",1,ATfalse); ATprotectAFun(match); match3=ATmakeAFun("VSET_MATCH3",3,ATfalse); ATprotectAFun(match3); pi=ATmakeAFun("VSET_PI",1,ATfalse); ATprotectAFun(pi); reach=ATmakeAFun("VSET_REACH",2,ATfalse); ATprotectAFun(reach); inv_reach=ATmakeAFun("VSET_INV_REACH",2,ATfalse); ATprotectAFun(inv_reach); rel_prod = ATmakeAFun("VSET_REL_PROD", 4, ATfalse); ATprotectAFun(rel_prod); // used for vector_set_tree: Empty=ATparse("VSET_E"); ATprotect(&Empty); Atom=ATparse("VSET_A"); ATprotect(&Atom); set_reset_ct(); } static vset_t set_create_both(vdom_t dom,int k,int* proj){ int l = (k < 0)?0:k; vset_t set=(vset_t)RTmalloc(sizeof(struct vector_set)+sizeof(int[l])); set->dom=dom; set->set=emptyset; ATprotect(&set->set); set->p_len=k; for(int i=0;i<k;i++) set->proj[i]=proj[i]; return set; } static void set_destroy_both(vset_t set) { ATunprotect(&set->set); set->p_len = 0; RTfree(set); } static vrel_t rel_create_both(vdom_t dom,int k,int* proj){ assert(k >= 0); vrel_t rel=(vrel_t)RTmalloc(sizeof(struct vector_relation)+sizeof(int[k])); rel->dom=dom; rel->rel=emptyset; ATprotect(&rel->rel); rel->p_len=k; for(int i=0;i<k;i++) rel->proj[i]=proj[i]; return rel; } static int set_is_empty_both(vset_t set){ return ATisEqual(set->set,emptyset); } static int set_equal_both(vset_t set1,vset_t set2){ return ATisEqual(set1->set,set2->set); } static void set_clear_both(vset_t set){ set->set=emptyset; } static void set_copy_both(vset_t dst,vset_t src){ assert(dst->p_len == src->p_len); dst->set=src->set; } // these are used for counting: static ATermIndexedSet count_is; static long node_count; static bn_int_t *elem_count; static long elem_size; static long count_set_t2(ATerm set){ ATbool new; long idx, idx_0, idx_1, idx_2; idx=ATindexedSetPut(count_is,(ATerm)set,&new); if(new){ node_count++; if (idx>=elem_size){ long elem_size_old=elem_size; elem_size=elem_size+(elem_size>>1); elem_count=RTrealloc(elem_count,elem_size*sizeof(bn_int_t)); //ATwarning("resize %d %d %x",idx,elem_size,elem_count); for(int i=elem_size_old;i<elem_size;i++) bn_init(&elem_count[i]); } idx_0=count_set_t2(ATgetArgument(set,0)); idx_1=count_set_t2(ATgetArgument(set,1)); idx_2=count_set_t2(ATgetArgument(set,2)); bn_add(&elem_count[idx_0],&elem_count[idx],&elem_count[idx]); bn_add(&elem_count[idx_1],&elem_count[idx],&elem_count[idx]); bn_add(&elem_count[idx_2],&elem_count[idx],&elem_count[idx]); return idx; } else return idx; } static void set_count_t(ATerm set, long *nodes, bn_int_t *elements) { long idx; count_is=ATindexedSetCreate(HASH_INIT,HASH_LOAD); elem_size=HASH_INIT; elem_count=RTmalloc(elem_size*sizeof(bn_int_t)); for(int i=0;i<elem_size;i++) bn_init(&elem_count[i]); node_count=2; // atom and emptyset idx=ATindexedSetPut(count_is,Empty,NULL); assert(idx<elem_size); bn_set_digit(&elem_count[idx],0); idx=ATindexedSetPut(count_is,Atom,NULL); assert(idx<elem_size); bn_set_digit(&elem_count[idx],1); idx=count_set_t2(set); if (elements != NULL) bn_init_copy(elements,&elem_count[idx]); ATindexedSetDestroy(count_is); for(int i=0;i<elem_size;i++) bn_clear(&elem_count[i]); RTfree(elem_count); if (set == Atom || set == Empty) node_count = 1; if (nodes != NULL) *nodes=node_count; } static void set_count_tree(vset_t set,long *nodes,bn_int_t *elements){ set_count_t(set->set,nodes,elements); } static void rel_count_tree(vrel_t rel,long *nodes,bn_int_t *elements){ set_count_t(rel->rel,nodes,elements); } static long count_set_2(ATerm set){ ATbool new; long idx, idx_1, idx_2; idx=ATindexedSetPut(count_is,(ATerm)set,&new); if(new){ node_count++; if (idx>=elem_size){ long elem_size_old=elem_size; elem_size=elem_size+(elem_size>>1); elem_count=RTrealloc(elem_count,elem_size*sizeof(bn_int_t)); //ATwarning("resize %d %d %x",idx,elem_size,elem_count); for(int i=elem_size_old;i<elem_size;i++) bn_init(&elem_count[i]); } idx_1=count_set_2(ATgetArgument(set,1)); idx_2=count_set_2(ATgetArgument(set,2)); bn_add(&elem_count[idx_1],&elem_count[idx_2],&elem_count[idx]); return idx; } else return idx; } static void count_set(ATerm set, long *nodes, bn_int_t *elements) { long idx; count_is=ATindexedSetCreate(HASH_INIT,HASH_LOAD); elem_size=HASH_INIT; elem_count=RTmalloc(elem_size*sizeof(bn_int_t)); for(int i=0;i<elem_size;i++) bn_init(&elem_count[i]); node_count=2; // atom and emptyset idx=ATindexedSetPut(count_is,(ATerm)emptyset,NULL); assert(idx<elem_size); bn_set_digit(&elem_count[idx],0); idx=ATindexedSetPut(count_is,(ATerm)atom,NULL); assert(idx<elem_size); bn_set_digit(&elem_count[idx],1); idx=count_set_2(set); bn_init_copy(elements,&elem_count[idx]); ATindexedSetDestroy(count_is); for(int i=0;i<elem_size;i++) bn_clear(&elem_count[i]); RTfree(elem_count); if (set == atom || set == emptyset) node_count = 1; *nodes=node_count; } static void set_count_list(vset_t set,long *nodes,bn_int_t *elements){ count_set(set->set,nodes,elements); } static void rel_count_list(vrel_t rel,long *nodes,bn_int_t *elements){ count_set(rel->rel,nodes,elements); } static ATbool set_member(ATerm set,ATerm *a){ if (set==emptyset) return ATfalse; else if (set==atom) return ATtrue; else { int c = ATcmp(a[0],ATgetArgument(set,0)); if (c==0) return set_member(ATgetArgument(set,1),a+1); else if (c>0) return set_member(ATgetArgument(set,2),a); else return ATfalse; } } static inline ATerm Cons(ATerm e,ATerm es,ATerm tl) { return (ATerm)ATmakeAppl3(cons,e,es,tl); } static ATerm MakeCons(ATerm e,ATerm es,ATerm tl){ if (ATisEqual(es,emptyset)) return tl; return Cons(e,es,tl); } static ATerm MCons(ATerm down,ATerm left,ATerm right) { // used for tree if (ATisEqual(down,Empty) && ATisEqual(left,Empty) && ATisEqual(right,Empty)) return Empty; return Cons(down,left,right); } static inline ATerm Down(ATerm e) { return ATgetArgument(e,0); } static inline ATerm Left(ATerm e) { return ATgetArgument(e,1); } static inline ATerm Right(ATerm e) { return ATgetArgument(e,2); } static ATerm singleton(ATerm *a,int len){ ATerm set=atom; for (int i=len-1;i>=0;i--) set=Cons(a[i],set,emptyset); return set; } static ATerm set_add(ATerm set,ATerm *a,int len){ if (set==emptyset) return singleton(a,len); else if (set==atom) return atom; else { ATerm x=ATgetArgument(set,0); int c = ATcmp(a[0],x); if (c<0) return Cons(a[0],singleton(a+1,len-1),set); else { ATerm set1 = ATgetArgument(set,1); ATerm set2 = ATgetArgument(set,2); if (c==0) return Cons(x,set_add(set1,a+1,len-1),set2); else return Cons(x,set1,set_add(set2,a,len)); } } } static void set_add_list(vset_t set,const int* e){ int N=(set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm vec[N]; for(int i=0;i<N;i++) vec[i]=(ATerm)ATmakeInt(e[i]); set->set=set_add(set->set,vec,N); } static void rel_add_list(vrel_t rel,const int* src, const int* dst){ int N=(rel->p_len < 0)?rel->dom->shared.size:rel->p_len; ATerm vec[2*N]; for(int i=0;i<N;i++) { vec[i+i]=(ATerm)ATmakeInt(src[i]); vec[i+i+1]=(ATerm)ATmakeInt(dst[i]); } rel->rel=set_add(rel->rel,vec,2*N); } static int set_member_list(vset_t set,const int* e){ int N=(set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm vec[N]; for(int i=0;i<N;i++) vec[i]=(ATerm)ATmakeInt(e[i]); return set_member(set->set,vec); } static ATbool set_member_tree_2(ATerm set,const int *a); static ATerm singleton_tree(const int *a,int len); static ATerm set_add_tree_2(ATerm set, const int *a,int len,ATbool *new); static void rel_add_tree(vrel_t rel,const int* src, const int* dst){ int N=(rel->p_len < 0)?rel->dom->shared.size:rel->p_len; int vec[2*N]; for(int i=0;i<N;i++) { vec[i+i]=src[i]; vec[i+i+1]=dst[i]; } rel->rel=set_add_tree_2(rel->rel,vec,2*N,NULL); } static ATbool set_member_tree_2(ATerm set, const int *a) { for (;;) { if (set==Empty) return ATfalse; else if (set==Atom) return ATtrue; else { int x=a++[0]+1; while (x!=1) { int odd = x & 0x0001; x = x>>1; if (odd) set = Right(set); else set = Left(set); if (set==Empty) return ATfalse; } } set = Down(set); } } static ATerm singleton2(int x, const int *a, int len) { if (x==1) return Cons(singleton_tree(a,len-1),Empty,Empty); else { int odd = x & 0x0001; x = x>>1; if (odd) return Cons(Empty,Empty,singleton2(x,a,len)); else return Cons(Empty,singleton2(x,a,len),Empty); } } static ATerm singleton_tree(const int *a,int len){ if (len==0) return Atom; else return singleton2(a[0]+1,a+1,len); // only values >0 can be stored } static ATerm set_add2(ATerm set,int x, const int *a,int len,ATbool *new){ if (set==Empty) { if (new) *new=ATtrue; return singleton2(x,a,len); } else if (x==1) return Cons(set_add_tree_2(Down(set),a,len-1,new),Left(set),Right(set)); else { int odd = x & 0x0001; x = x>>1; if (odd) return Cons(Down(set),Left(set),set_add2(Right(set),x,a,len,new)); else return Cons(Down(set),set_add2(Left(set),x,a,len,new),Right(set)); } } static ATerm set_add_tree_2(ATerm set,const int *a,int len,ATbool *new){ if (set==Atom) { if (new) *new=ATfalse; return Atom; } else if (set==Empty) { if (new) *new=ATtrue; return singleton_tree(a,len); } else return set_add2(set,a[0]+1,a+1,len,new); } void set_add_tree(vset_t set,const int* e){ int N=(set->p_len < 0)?set->dom->shared.size:set->p_len; // ATbool new; set->set=set_add_tree_2(set->set,e,N,NULL); } int set_member_tree(vset_t set,const int* e){ return set_member_tree_2(set->set,e); } union enum_context { // Used by set_enum and enum_wrap functions: struct { vset_element_cb cb; void *context; } enum_cb; // Used by set_example and enum_first functions: int *enum_elem; }; static int vset_enum_wrap(ATerm *a, int len, union enum_context *ctx) { int vec[len]; for(int i = 0; i < len; i++) vec[i] = ATgetInt((ATermInt)a[i]); ctx->enum_cb.cb(ctx->enum_cb.context, vec); return 0; } static int vset_enum_first(ATerm *a, int len, union enum_context *ctx) { for(int i = 0; i < len; i++) ctx->enum_elem[i] = ATgetInt((ATermInt)a[i]); return 1; } static int set_enum_2(ATerm set, ATerm *a, int len, int (*callback)(ATerm*, int, union enum_context*), int ofs, union enum_context *ctx) { int tmp; while(ATgetAFun(set) == cons){ if (ofs < len) { a[ofs] = ATgetArgument(set, 0); tmp = set_enum_2(ATgetArgument(set, 1), a, len, callback, ofs + 1, ctx); if (tmp) return tmp; } set = ATgetArgument(set, 2); } if (ATisEqual(set, atom)) { return callback(a, ofs, ctx); } return 0; } static void set_enum_list(vset_t set, vset_element_cb cb, void* context) { union enum_context ctx = {.enum_cb = {cb, context}}; int N = (set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm vec[N]; set_enum_2(set->set, vec, N, vset_enum_wrap, 0, &ctx); } static void set_example_list(vset_t set, int *e) { union enum_context ctx = {.enum_elem = e}; int N = (set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm vec[N]; set_enum_2(set->set, vec, N, vset_enum_first, 0, &ctx); } static int vset_enum_wrap_tree(int *a, int len, union enum_context *ctx) { (void)len; ctx->enum_cb.cb(ctx->enum_cb.context, a); return 0; } static int vset_enum_tree_first(int *a, int len, union enum_context *ctx) { for (int i = 0; i < len; i++) ctx->enum_elem[i] = a[i]; return 1; } static int set_enum_t2(ATerm set, int *a, int len, int (*callback)(int*, int, union enum_context*), int ofs, int shift, int cur, union enum_context *ctx) { int tmp; if (set == Atom) return callback(a, ofs, ctx); else if (set == Empty) return 0; else { if (ofs < len) { a[ofs] = shift + cur - 1; // Recall that 0 cannot be stored tmp = set_enum_t2(Down(set), a, len, callback, ofs + 1, 1, 0, ctx); if (tmp) return tmp; } set_enum_t2(Left(set), a, len, callback, ofs, shift<<1, cur, ctx); set_enum_t2(Right(set), a, len, callback, ofs, shift<<1, shift|cur, ctx); return 0; } } static void set_enum_tree(vset_t set, vset_element_cb cb, void* context) { union enum_context ctx = {.enum_cb = {cb, context}}; int N = (set->p_len < 0)?set->dom->shared.size:set->p_len; int vec[N]; set_enum_t2(set->set, vec, N, vset_enum_wrap_tree, 0, 1, 0, &ctx); } static void set_example_tree(vset_t set, int *e) { union enum_context ctx = {.enum_elem = e}; int N = (set->p_len < 0)?set->dom->shared.size:set->p_len; int vec[N]; set_enum_t2(set->set,vec,N,vset_enum_tree_first, 0, 1, 0, &ctx); } static vset_element_cb match_cb; static void* match_context; static int vset_match_wrap(ATerm *a,int len){ int vec[len]; for(int i=0;i<len;i++) vec[i]=ATgetInt((ATermInt)a[i]); match_cb(match_context,vec); return 0; } /* return < 0 : error, 0 no matches, >0 matches found */ static int set_enum_match_2(ATermIndexedSet dead,ATerm set,ATerm *a,int len,ATerm*pattern,int *proj,int p_len, int (*callback)(ATerm *,int),int ofs ){ int tmp; if (ATindexedSetGetIndex(dead,set)>=0) return 0; if (ATgetAFun(set)==cons){ int live=0; if (ofs<len){ if (p_len && proj[0]==ofs){ ATerm el=ATgetArgument(set,0); if (ATisEqual(pattern[0],el)){ a[ofs]=el; tmp=set_enum_match_2(dead,ATgetArgument(set,1),a,len,pattern+1,proj+1,p_len-1,callback,ofs+1); if (tmp<0) return tmp; if (tmp) live=1; } } else { a[ofs]=ATgetArgument(set,0); tmp=set_enum_match_2(dead,ATgetArgument(set,1),a,len,pattern,proj,p_len,callback,ofs+1); if (tmp<0) return tmp; if(tmp) live=1; } } if(ofs<=len){ tmp=set_enum_match_2(dead,ATgetArgument(set,2),a,len,pattern,proj,p_len,callback,ofs); if(tmp<0) return tmp; if(tmp) live=1; } if (!live){ ATindexedSetPut(dead,set,NULL); } return live; } if (ATisEqual(set,atom)&&ofs==len) { return callback(a,ofs)?-1:1; } else { ATindexedSetPut(dead,set,NULL); return 0; } } static void set_enum_match_list(vset_t set,int p_len,int* proj,int*match,vset_element_cb cb,void* context){ int N=(set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm vec[N]; ATerm pattern[p_len]; for(int i=0;i<p_len;i++) pattern[i]=(ATerm)ATmakeInt(match[i]); match_cb=cb; match_context=context; ATermIndexedSet dead_branches=ATindexedSetCreate(HASH_INIT,HASH_LOAD); set_enum_match_2(dead_branches,set->set,vec,N,pattern,proj,p_len,vset_match_wrap,0); ATindexedSetDestroy(dead_branches); } /* return NULL : error, or matched vset */ static ATerm set_copy_match_2(ATerm set, int len, ATerm*pattern, int *proj, int p_len, int ofs) { ATerm key, res, tmp = emptyset; // lookup in cache key = (ATerm)ATmakeAppl1(match,set); res = ATtableGet(global_ct,key); if (res) return res; res = emptyset; if (ATgetAFun(set) == cons) { ATerm el=ATgetArgument(set,0); if (ofs<len) { // if still matching and this offset matches, // compare the aterm and return it if it matches if (p_len && proj[0]==ofs) { // does it match? if (ATisEqual(pattern[0],el)) { // try to match the next element, return the result tmp=set_copy_match_2(ATgetArgument(set,1),len,pattern+1, proj+1, p_len-1,ofs+1); } // not matching anymore or the offset doesn't match } else { tmp=set_copy_match_2(ATgetArgument(set,1),len,pattern, proj, p_len,ofs+1); } } // test matches in second argument if (ofs<=len) { res=set_copy_match_2(ATgetArgument(set,2),len,pattern, proj, p_len,ofs); } // combine results res = MakeCons(el, tmp, res); } else { if (ATisEqual(set,atom) && ofs==len) { res=set; } else { res=emptyset; } } ATtablePut(global_ct,key,res); return res; } static void set_copy_match_list(vset_t dst,vset_t src,int p_len,int* proj,int*match) { int N=(src->p_len < 0)?src->dom->shared.size:src->p_len; ATerm pattern[p_len]; for(int i=0;i<p_len;i++) pattern[i]=(ATerm)ATmakeInt(match[i]); dst->set = set_copy_match_2(src->set,N,pattern,proj,p_len,0); ATtableReset(global_ct); } static ATerm set_union_2(ATerm s1, ATerm s2,char lookup) { if (s1==atom) return atom; else if (s1==emptyset) return s2; else if (s2==emptyset) return s1; else if (s1==s2) return s1; else { ATerm key=NULL,res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(sum,s1,s2); res = ATtableGet(global_ct,key); if (res) return res; } { // either not looked up, or not found in cache: compute ATerm x = ATgetArgument(s1,0); ATerm y = ATgetArgument(s2,0); int c = ATcmp(x,y); if (c==0) res=Cons(x, set_union_2(ATgetArgument(s1,1),ATgetArgument(s2,1),1), set_union_2(ATgetArgument(s1,2),ATgetArgument(s2,2),0)); else if (c<0) res=Cons(x, ATgetArgument(s1,1), set_union_2(ATgetArgument(s1,2),s2,0)); else res = Cons(y, ATgetArgument(s2,1), set_union_2(s1,ATgetArgument(s2,2),0)); if (lookup) ATtablePut(global_ct,key,res); return res; } } } static void set_union_list(vset_t dst,vset_t src){ assert(dst->p_len == src->p_len); dst->set=set_union_2(dst->set,src->set,0); ATtableReset(global_ct); } static ATerm set_intersect_2(ATerm s1, ATerm s2,char lookup) { if (s1==atom && s2==atom) return atom; else if (s1==emptyset) return emptyset; else if (s2==emptyset) return emptyset; else { ATerm key=NULL,res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(intersect,s1,s2); res = ATtableGet(global_ct,key); if (res) return res; } { // either not looked up, or not found in cache: compute ATerm x = ATgetArgument(s1,0); ATerm y = ATgetArgument(s2,0); int c = ATcmp(x,y); if (c==0) res=MakeCons(x, set_intersect_2(ATgetArgument(s1,1),ATgetArgument(s2,1),1), set_intersect_2(ATgetArgument(s1,2),ATgetArgument(s2,2),1)); // x < y else if (c<0) res=set_intersect_2(ATgetArgument(s1,2),s2,1); else res = set_intersect_2(s1, ATgetArgument(s2,2),1); if (lookup) ATtablePut(global_ct,key,res); return res; } } } static void set_intersect_list(vset_t dst,vset_t src){ assert(dst->p_len == src->p_len); dst->set=set_intersect_2(dst->set,src->set,0); ATtableReset(global_ct); } static ATerm set_minus_2(ATerm a,ATerm b, char lookup) { if (b==emptyset) return a; else if (a==emptyset) return emptyset; else if (b==atom) return emptyset; else if (a==b) return emptyset; else { ATerm key=NULL, res=NULL; if (lookup) { key=(ATerm)ATmakeAppl2(min,a,b); res=ATtableGet(global_ct,key); if (res) return res; } { // not looked up, or not found in cache. ATerm x=ATgetArgument(a,0); ATerm y= ATgetArgument(b,0); int c=ATcmp(x,y); if (c==0) res=MakeCons(x,set_minus_2(ATgetArgument(a,1),ATgetArgument(b,1),1), set_minus_2(ATgetArgument(a,2),ATgetArgument(b,2),0)); else if (c<0) res=Cons(x,ATgetArgument(a,1), set_minus_2(ATgetArgument(a,2),b,0)); else res=(ATerm)set_minus_2(a,ATgetArgument(b,2),0); if (lookup) ATtablePut(global_ct,key,res); return res; } } } static void set_minus_list(vset_t dst,vset_t src){ assert(dst->p_len == src->p_len); dst->set=set_minus_2(dst->set,src->set,0); ATtableReset(global_ct); } static void set_zip_2(ATerm in1,ATerm in2,ATerm *out1,ATerm *out2, char lookup){ if (in1==atom) {*out1=atom; *out2=emptyset; return;} else if (in1==emptyset) {*out1=*out2=in2; return;} else if (in2==emptyset) {*out1=in1; *out2=in2; return;} else if (in1==in2) {*out1=in1,*out2=emptyset; return;} else { ATerm key=NULL, res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(zip,in1,in2); res=ATtableGet(global_ct,key); if (res) { *out1=ATgetArgument(res,0); *out2=ATgetArgument(res,1); return; } } { // not looked up, or not found in cache: compute int c=ATcmp(ATgetArgument(in1,0),ATgetArgument(in2,0)); if(c<0) { ATerm t1=NULL,t2=NULL; set_zip_2(ATgetArgument(in1,2),in2,&t1,&t2,0); *out1=Cons(ATgetArgument(in1,0),ATgetArgument(in1,1),t1); *out2=t2; } else if (c>0) { ATerm t1=NULL,t2=NULL; set_zip_2(in1,ATgetArgument(in2,2),&t1,&t2,0); *out1=Cons(ATgetArgument(in2,0),ATgetArgument(in2,1),t1); *out2=Cons(ATgetArgument(in2,0),ATgetArgument(in2,1),t2); } else { ATerm t1=NULL,t2=NULL,t3=NULL,t4=NULL; set_zip_2(ATgetArgument(in1,1),ATgetArgument(in2,1),&t1,&t2,1); set_zip_2(ATgetArgument(in1,2),ATgetArgument(in2,2),&t3,&t4,0); *out1=Cons(ATgetArgument(in1,0),t1,t3); *out2=MakeCons(ATgetArgument(in1,0),t2,t4); } if (lookup) ATtablePut(global_ct,key,(ATerm)ATmakeAppl2(zip,*out1,*out2)); } } } static void set_zip_list(vset_t dst,vset_t src){ set_zip_2(dst->set,src->set,&dst->set,&src->set,0); ATtableReset(global_ct); } static ATerm set_project_2(ATerm set,int ofs,int *proj,int len,char lookup) { // WARNING: cache results may never be reused from different toplevel calls to project!! if (set==emptyset) return emptyset; else if (len==0) return atom; else { ATerm key=NULL, res=NULL; if (lookup) { key=(ATerm)ATmakeAppl1(pi,set); res=ATtableGet(global_ct,key); if (res) return res; } { // not looked up, or not found in cache: compute if (ofs==proj[0]) // check: projection of non-empty set is always nonempty... res = Cons(ATgetArgument(set,0), set_project_2(ATgetArgument(set,1),ofs+1,proj+1,len-1,1), set_project_2(ATgetArgument(set,2),ofs,proj,len,0)); else for (res=emptyset;set!=emptyset;set=ATgetArgument(set,2)) res=set_union_2(res,set_project_2(ATgetArgument(set,1),ofs+1,proj,len,1),1); if (lookup) ATtablePut(global_ct,key,res); return res; } } } static void set_project_list(vset_t dst,vset_t src){ assert(dst->p_len >= 0 && src->p_len < 0); dst->set=set_project_2(src->set,0,dst->proj,dst->p_len,0); ATtableReset(global_ct); } static ATerm set_reach_2(ATerm set,ATerm trans,int *proj,int p_len,int ofs, char lookup); static ATerm copy_level(ATerm set,ATerm trans,int *proj,int p_len,int ofs){ if (set==emptyset) return emptyset; else return MakeCons(ATgetArgument(set,0), set_reach_2(ATgetArgument(set,1),trans,proj,p_len,ofs+1,1), copy_level(ATgetArgument(set,2),trans,proj,p_len,ofs)); } static ATerm trans_level(ATerm set,ATerm trans,int *proj,int p_len,int ofs){ if (trans==emptyset) return emptyset; else return MakeCons(ATgetArgument(trans,0), set_reach_2(set,ATgetArgument(trans,1),proj+1,p_len-1,ofs+1,1), trans_level(set,ATgetArgument(trans,2),proj,p_len,ofs)); } static ATerm apply_reach(ATerm set,ATerm trans,int *proj,int p_len,int ofs){ int c; ATerm res=emptyset; while ((ATgetAFun(set)==cons)&&(ATgetAFun(trans)==cons)){ c=ATcmp(ATgetArgument(set,0),ATgetArgument(trans,0)); if (c<0) set=ATgetArgument(set,2); else if (c>0) trans=ATgetArgument(trans,2); else { res=set_union_2(res, trans_level(ATgetArgument(set,1), ATgetArgument(trans,1),proj,p_len,ofs),0); set=ATgetArgument(set,2); trans=ATgetArgument(trans,2); } } return res; } static ATerm set_reach_2(ATerm set,ATerm trans,int *proj,int p_len,int ofs, char lookup){ // WARNING: cache results may never be reused from different toplevel calls to project!! // TO CHECK: why add 'trans' to cache? Just caching set should probably work as well if (set == emptyset || trans == emptyset) return emptyset; else if (p_len==0) return set; else { ATerm key=NULL, res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(reach,set,trans); res=ATtableGet(global_ct,key); if (res) return res; } { if (proj[0]==ofs) res = apply_reach(set,trans,proj,p_len,ofs); else res = copy_level(set,trans,proj,p_len,ofs); if (lookup) ATtablePut(global_ct,key,res); return res; } } } void set_next_list(vset_t dst,vset_t src,vrel_t rel){ assert(dst->p_len < 0 && src->p_len < 0); dst->set=set_reach_2(src->set,rel->rel,rel->proj,rel->p_len,0,0); ATtableReset(global_ct); } static ATerm set_inv_reach(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup); static ATerm copy_level_inv(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (set==emptyset) { return emptyset; } else { return MakeCons(ATgetArgument(set, 0), set_inv_reach(ATgetArgument(set, 1), trans, proj, p_len, ofs + 1, 1), copy_level_inv(ATgetArgument(set, 2), trans, proj, p_len, ofs) ); } } static ATerm trans_level_inv(ATerm trans_src, ATerm set, ATerm trans, int *proj, int p_len, int ofs) { int c; ATerm res = emptyset; while ((ATgetAFun(trans)==cons) && ATgetAFun(set)==cons) { // compare 2nd argument c = ATcmp(ATgetArgument(set,0), ATgetArgument(trans,0)); if (c < 0) { set = ATgetArgument(set, 2); } else if (c > 0) { trans=ATgetArgument(trans,2); } else { // equal, match rest and return //ATprintf("match, %t -> %t\n", trans_src, ATgetArgument(trans, 0)); ATerm tail = set_inv_reach(ATgetArgument(set, 1), ATgetArgument(trans, 1), proj + 1, p_len - 1, ofs+1, 1); res = set_union_2(res, MakeCons(trans_src, tail, emptyset), 0); set=ATgetArgument(set,2); trans=ATgetArgument(trans,2); } } return res; } static ATerm apply_inv_reach(ATerm set, ATerm trans, int *proj, int p_len, int ofs){ ATerm res=emptyset; for(;(ATgetAFun(trans)==cons);) { res = set_union_2( res, trans_level_inv(ATgetArgument(trans, 0), set, ATgetArgument(trans,1), proj, p_len, ofs), 0); trans = ATgetArgument(trans, 2); } return res; } static ATerm set_inv_reach(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup) { if (set == emptyset || trans == emptyset) { return emptyset; } if (p_len == 0) { return set; } else { ATerm key = NULL, res = NULL; if (lookup) { // do lookup key = (ATerm)ATmakeAppl2(inv_reach, set, trans); res = ATtableGet(global_ct, key); if (res) return res; } if (proj[0] == ofs) { // apply the relation backwards res = apply_inv_reach(set, trans, proj, p_len, ofs); } else { // copy, nothing in projection res = copy_level_inv(set, trans, proj, p_len, ofs); } if (lookup) { // put in cache ATtablePut(global_ct, key, res); } return res; } } void set_prev_list(vset_t dst, vset_t src, vrel_t rel, vset_t univ) { assert(dst->p_len < 0 && src->p_len < 0); dst->set=set_inv_reach(src->set, rel->rel, rel->proj, rel->p_len, 0, 0); ATtableReset(global_ct); set_intersect_list(dst, univ); } #if 0 union Atom _ = Atom union Empty s = s union s Empty = s union (Cons dstdown dstleft dstright) (Cons srcdown srcleft srcright) = Cons (union dstdown srcdown) (union dstleft srcleft) (union dstright srcright) #endif static ATerm set_union_tree_2(ATerm s1, ATerm s2, char lookup) { if (s1==Atom) return Atom; else if (s1==Empty) return s2; else if (s2==Empty) return s1; else { ATerm key=NULL,res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(sum,s1,s2); res = ATtableGet(global_ct,key); if (res) return res; } // either not looked up, or not found in cache: compute res = Cons( set_union_tree_2(Down(s1), Down(s2), 1), set_union_tree_2(Left(s1), Left(s2), 1), set_union_tree_2(Right(s1), Right(s2), 1) ); if (lookup) ATtablePut(global_ct,key,res); return res; } } static void set_union_tree(vset_t dst, vset_t src) { assert(dst->p_len == src->p_len); dst->set=set_union_tree_2(dst->set,src->set,0); ATtableReset(global_ct); } #if 0 intersect Atom Atom = Atom intersect Empty _ = Empty intersect _ Empty = Empty intersect (Cons dstdown dstleft dstright) (Cons srcdown srcleft srcright) = Cons (intersect dstdown srcdown) (intersect dstleft srcleft) (intersect dstright srcright) #endif static ATerm set_intersect_tree_2(ATerm s1, ATerm s2) { if (s1==Atom && s2==Atom) return Atom; else if (s1==Empty) return Empty; else if (s2==Empty) return Empty; else { ATerm key=NULL,res=NULL; key = (ATerm)ATmakeAppl2(intersect,s1,s2); res = ATtableGet(global_ct,key); if (res) return res; // either not looked up, or not found in cache: compute res = MCons( set_intersect_tree_2(Down(s1), Down(s2)), set_intersect_tree_2(Left(s1), Left(s2)), set_intersect_tree_2(Right(s1), Right(s2)) ); ATtablePut(global_ct,key,res); return res; } } static void set_intersect_tree(vset_t dst, vset_t src) { assert(dst->p_len == src->p_len); dst->set=set_intersect_tree_2(dst->set,src->set); ATtableReset(global_ct); } #if 0 project Empty _ _ = Empty project _ _ [] = Atom project (Cons x s t) i (j:l) | i == j = Cons (project x (i+1) (l)) (project s i (j:l)) (project t i (j:l)) project (Cons x s t) i (j:l) | i < j = union (project x (i+1) (j:l)) (union (project s i (j:l)) (project t i (j:l)) ) #endif static ATerm set_project_tree_2(ATerm set,int ofs,int *proj,int len,char lookup) { // WARNING: cache results may never be reused from different toplevel calls to project!! if (set==Empty) return Empty; else if (len==0) return Atom; else { ATerm key=NULL, res=NULL; if (lookup) { key=(ATerm)ATmakeAppl1(pi,set); res=ATtableGet(global_ct,key); if (res) return res; } // not looked up, or not found in cache: compute if (ofs==proj[0]) { // check: projection of non-empty set is always nonempty... res = Cons(set_project_tree_2(Down(set) , ofs+1, proj+1, len-1, 1), set_project_tree_2(Left(set) , ofs , proj , len , 1), set_project_tree_2(Right(set), ofs , proj , len , 1)); } else { res = set_union_tree_2( set_project_tree_2(Down(set), ofs+1, proj, len, 1), set_union_tree_2( set_project_tree_2(Left(set) , ofs, proj, len, 1), set_project_tree_2(Right(set), ofs, proj, len, 1), 1 ), 1); } if (lookup) ATtablePut(global_ct,key,res); return res; } } static void set_project_tree(vset_t dst,vset_t src){ assert(dst->p_len >= 0 && src->p_len < 0); dst->set=set_project_tree_2(src->set,0,dst->proj,dst->p_len,0); ATtableReset(global_ct); } #if 0 minus s Empty = s minus Empty s = Empty minus _ Atom = Empty minus (Cons dstdown dstleft dstright) (Cons srcdown srcleft srcright) = mcons (minus dstdown srcdown) (minus dstleft srcleft) (minus dstright srcright) #endif static ATerm set_minus_tree_2(ATerm a, ATerm b, char lookup) { if (b==Empty) return a; else if (a==Empty) return Empty; else if (b==Atom) return Empty; else { ATerm key=NULL, res=NULL; if (lookup) { key=(ATerm)ATmakeAppl2(min,a,b); res=ATtableGet(global_ct,key); if (res) return res; } // not looked up, or not found in cache. res = MCons( set_minus_tree_2(Down(a) ,Down(b) ,1), set_minus_tree_2(Left(a) ,Left(b) ,1), set_minus_tree_2(Right(a),Right(b),1) ); if (lookup) ATtablePut(global_ct,key,res); return res; } } static void set_minus_tree(vset_t dst,vset_t src){ assert(dst->p_len == src->p_len); dst->set=set_minus_tree_2(dst->set,src->set,0); ATtableReset(global_ct); } #if 0 tzip (Atom, _) = (Atom, Empty) tzip (s, Empty) = (s, Empty) tzip (Empty, s) = (s, s) tzip (Cons x s1 s2, Cons y t1 t2) = (Cons u u1 v1, mcons v u2 v2) where (u,v) = tzip (x,y); (u1,u2) = tzip (s1,t1); (v1,v2) = tzip (s2,t2); #endif static void set_zip_tree_2(ATerm in1, ATerm in2, ATerm *out1, ATerm *out2, char lookup){ if (in1==Atom) { *out1=Atom; *out2=Empty; return; } else if (in1==Empty) { *out1=*out2=in2; return; } else if (in2==Empty) { *out1=in1; *out2=in2; return; } else { ATerm key=NULL, res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(zip,in1,in2); res=ATtableGet(global_ct,key); if (res) { *out1=ATgetArgument(res,0); *out2=ATgetArgument(res,1); return; } } // not looked up, or not found in cache: compute ATerm u , m; set_zip_tree_2(Down(in1), Down(in2),&u,&m,1); ATerm u1,m1; set_zip_tree_2(Left(in1), Left(in2),&u1,&m1,1); ATerm u2,m2; set_zip_tree_2(Right(in1), Right(in2),&u2,&m2,1); *out1=Cons(u,u1,u2); *out2=MCons(m,m1,m2); if (lookup) ATtablePut(global_ct,key,(ATerm)ATmakeAppl2(zip,*out1,*out2)); } } static void set_zip_tree(vset_t dst,vset_t src){ set_zip_tree_2(dst->set,src->set,&dst->set,&src->set,0); ATtableReset(global_ct); } static ATerm set_reach_tree_2(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup); #if 0 copy Empty _ _ _ = Empty copy (Cons down left right) rel i (j:k) = mcons (next down rel (i+1) (j:k)) (copy left rel i (j:k)) (copy right rel i (j:k)) #endif static ATerm copy_level_next_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (set==Empty) { return Empty; } else { return MCons(set_reach_tree_2( Down(set) , trans, proj, p_len, ofs+1, 1), copy_level_next_tree(Left(set) , trans, proj, p_len, ofs), copy_level_next_tree(Right(set), trans, proj, p_len, ofs)); } } #if 0 trans src Atom i (j:k) = Atom trans src Empty i (j:k) = Empty trans src (Cons down left right) i (j:k) = mcons (next src down (i+1) k) (trans src left i (j:k)) (trans src right i (j:k)) #endif static ATerm trans_level_next_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (trans==Atom || trans==Empty) { return trans; } else { return MCons(set_reach_tree_2( set , Down(trans) , proj+1, p_len-1, ofs+1, 1), trans_level_next_tree(set , Left(trans) , proj , p_len , ofs), trans_level_next_tree(set , Right(trans), proj , p_len , ofs)); } } #if 0 apply Empty _ _ _ = Empty apply _ Empty _ _ = Empty -- not matched apply (Cons x y z) (Cons u v w) i proj = union (trans x u i proj) (union (apply y v i proj) (apply z w i proj)) #endif static ATerm apply_reach_next_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (set==Empty) { return Empty; } if (trans==Empty) { return Empty; } return set_union_tree_2( trans_level_next_tree(Down(set), Down(trans), proj, p_len, ofs), set_union_tree_2( set_reach_tree_2(Left(set), Left(trans), proj, p_len, ofs, 1), set_reach_tree_2(Right(set), Right(trans), proj, p_len, ofs, 1), 1), 1); } #if 0 next Empty _ _ _ = Empty -- nothing left in src set next _ Empty _ _ = Empty -- nothing left in relation next src rel i [] = src next src rel i (j:k) | i == j = apply src rel i (j:k) next src rel i (j:k) | i < j = copy src rel i (j:k) #endif static ATerm set_reach_tree_2(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup) { if (set==Empty) { return Empty; } if (trans==Empty) { return Empty; } if (p_len==0) { return set; } else { ATerm key=NULL, res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(reach,set,trans); res=ATtableGet(global_ct,key); if (res) return res; } if (proj[0]==ofs) { res = apply_reach_next_tree(set,trans,proj,p_len,ofs); } else { res = copy_level_next_tree(set,trans,proj,p_len,ofs); } if (lookup) ATtablePut(global_ct,key,res); return res; } } void set_next_tree(vset_t dst,vset_t src,vrel_t rel){ assert(dst->p_len < 0 && src->p_len < 0); dst->set=set_reach_tree_2(src->set, rel->rel, rel->proj, rel->p_len, 0, 0); ATtableReset(global_ct); } static ATerm set_prev_tree_2(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup); #if 0 pcopy Empty _ _ _ = Empty pcopy (Cons down left right) rel i (j:k) = mcons (prev down rel (i+1) (j:k)) (pcopy left rel i (j:k)) (pcopy right rel i (j:k)) #endif static ATerm copy_level_prev_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (set==Empty) { return Empty; } else { return MCons(set_prev_tree_2( Down(set) , trans, proj, p_len, ofs+1, 1), copy_level_prev_tree(Left(set) , trans, proj, p_len, ofs), copy_level_prev_tree(Right(set), trans, proj, p_len, ofs)); } } #if 0 match Empty _ _ _ = Empty match _ Empty _ _ = Empty match (Cons x y z) (Cons u v w) i (j:k) = union (prev x u (i+1) k) (union (match y v i (j:k)) (match z w i (j:k))) #endif static ATerm match_prev_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (set==Empty) return Empty; if (trans==Empty) return Empty; return set_union_tree_2( set_prev_tree_2(Down(set), Down(trans), proj+1, p_len-1, ofs+1, 1), set_union_tree_2( match_prev_tree(Left(set) , Left(trans) , proj, p_len, ofs), match_prev_tree(Right(set), Right(trans), proj, p_len, ofs), 1), 1); } #if 0 merge src Empty _ _= Empty merge src (Cons u v w) i proj = mcons (match src u i proj) (merge src v i proj) (merge src w i proj) #endif static ATerm merge_prev_tree(ATerm set, ATerm trans, int *proj, int p_len, int ofs) { if (trans==Empty) { return Empty; } return MCons( match_prev_tree(set, Down(trans) , proj, p_len, ofs), merge_prev_tree(set, Left(trans) , proj, p_len, ofs), merge_prev_tree(set, Right(trans), proj, p_len, ofs) ); } #if 0 prev Empty _ _ _ = Empty prev _ Empty _ _ = Empty prev src rel i [] = src prev src rel i (j:k) | i == j = merge src rel i (j:k) prev src rel i (j:k) | i < j = pcopy src rel i (j:k) #endif static ATerm set_prev_tree_2(ATerm set, ATerm trans, int *proj, int p_len, int ofs, char lookup) { if (set==Empty) { return Empty; } if (trans==Empty) { return Empty; } if (p_len==0) { return set; } else { ATerm key=NULL, res=NULL; if (lookup) { key = (ATerm)ATmakeAppl2(inv_reach,set,trans); res=ATtableGet(global_ct,key); if (res) return res; } if (proj[0]==ofs) { res = merge_prev_tree(set,trans,proj,p_len,ofs); } else { res = copy_level_prev_tree(set,trans,proj,p_len,ofs); } if (lookup) ATtablePut(global_ct,key,res); return res; } } void set_prev_tree(vset_t dst,vset_t src,vrel_t rel,vset_t univ){ assert(dst->p_len < 0 && src->p_len < 0); dst->set=set_prev_tree_2(src->set, rel->rel, rel->proj, rel->p_len, 0, 0); ATtableReset(global_ct); set_intersect_list(dst,univ); } static void reorder() {} static ATerm set_copy_match_tree_2(ATerm set, int len,int *matchv, int *proj, int p_len, int ofs, int shift, int cur) { ATerm key, res; // lookup in cache key = (ATerm)ATmakeAppl3(match3,set, (ATerm)ATmakeInt(p_len), (ATerm)ATmakeInt(shift+cur-1)); res = ATtableGet(global_ct,key); if (res) return res; res = Empty; if (ATgetAFun(set) == cons) { // should always be true, check anyway if (ofs<=len) { // if still matching and this offset matches, // compare the match to the computed current-1 if (p_len && proj[0]==ofs) { // does it match? if (matchv[0] == shift+cur-1) { // remember: can't store zero, thus -1 // try to match the next element, return the result res = MCons( set_copy_match_tree_2(Down(set), len, matchv+1, proj+1, p_len-1, ofs+1, 1, 0), Empty, Empty ); } else { res = MCons( Empty, set_copy_match_tree_2(Left(set), len, matchv, proj, p_len, ofs, shift<<1, cur), set_copy_match_tree_2(Right(set), len, matchv, proj, p_len, ofs, shift<<1, shift|cur) ); } // not matching anymore or the offset doesn't match } else { res = MCons( set_copy_match_tree_2(Down(set), len, matchv, proj, p_len, ofs+1, 1, 0), set_copy_match_tree_2(Left(set), len, matchv, proj, p_len, ofs, shift<<1, cur), set_copy_match_tree_2(Right(set), len, matchv, proj, p_len, ofs, shift<<1, shift|cur) ); } } } else { if (ATisEqual(set,Atom) && ofs>=len) { res=set; } else { res=Empty; } } ATtablePut(global_ct,key,res); return res; } static void set_copy_match_tree(vset_t dst,vset_t src, int p_len,int* proj,int*match){ assert(dst->p_len == src->p_len); int N=(src->p_len < 0)?src->dom->shared.size:src->p_len; if (p_len == 0) { dst->set = src->set; } else { dst->set = set_copy_match_tree_2(src->set,N,match,proj,p_len,0, 1, 0); ATtableReset(global_ct); } } static void set_enum_match_tree(vset_t set, int p_len, int *proj, int *match, vset_element_cb cb, void *context) { int N = (set->p_len < 0)?set->dom->shared.size:set->p_len; ATerm match_set; if (p_len == 0) { match_set = set->set; } else { match_set = set_copy_match_tree_2(set->set, N, match, proj, p_len, 0, 1, 0); ATtableReset(global_ct); } union enum_context ctx = {.enum_cb = {cb, context}}; int vec[N]; set_enum_t2(match_set, vec, N, vset_enum_wrap_tree, 0, 1, 0, &ctx); } // Structure for storing transition groups at top levels. typedef struct { int tg_len; int *top_groups; } top_groups_info; static vrel_t *rel_set; static vset_t *proj_set; static top_groups_info *top_groups; static ATerm saturate(int level, ATerm set); static ATerm sat_rel_prod(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp); // Initialize a global memoization table static ATermTable reset_table(ATermTable table) { ATermTable new_table = table; if (new_table != NULL) ATtableDestroy(new_table); return ATtableCreate(HASH_INIT, HASH_LOAD); } static ATerm set_union_sat(ATerm s1, ATerm s2, int lookup) { if (s1 == atom) return atom; if (s1 == emptyset) return s2; if (s2 == emptyset) return s1; if (s1 == s2) return s1; ATerm key = NULL, res = NULL; if (lookup) { key = (ATerm)ATmakeAppl2(sum, s1, s2); res = ATtableGet(global_uc, key); if (res) return res; } // not looked up or not found in cache: compute ATerm x = ATgetArgument(s1, 0); ATerm y = ATgetArgument(s2, 0); int c = ATcmp(x, y); if (c==0) res=Cons(x, set_union_sat(ATgetArgument(s1,1),ATgetArgument(s2,1),1), set_union_sat(ATgetArgument(s1,2),ATgetArgument(s2,2),0)); else if (c<0) res=Cons(x, ATgetArgument(s1,1), set_union_sat(ATgetArgument(s1,2),s2,0)); else res = Cons(y, ATgetArgument(s2,1), set_union_sat(s1,ATgetArgument(s2,2),0)); if (lookup) ATtablePut(global_uc, key, res); return res; } static ATerm copy_level_sat(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp) { if (set==emptyset) return emptyset; else return MakeCons(ATgetArgument(set, 0), sat_rel_prod(ATgetArgument(set, 1), trans, proj, p_len, ofs + 1, grp), copy_level_sat(ATgetArgument(set, 2), trans, proj, p_len, ofs, grp)); } static ATerm trans_level_sat(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp) { if (trans == emptyset) return emptyset; else return MakeCons(ATgetArgument(trans, 0), sat_rel_prod(set, ATgetArgument(trans, 1), proj + 1, p_len-1, ofs + 1, grp), trans_level_sat(set, ATgetArgument(trans, 2), proj, p_len, ofs, grp)); } static ATerm apply_rel_prod(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp) { ATerm res = emptyset; while((ATgetAFun(set) == cons) && (ATgetAFun(trans) == cons)) { int c = ATcmp(ATgetArgument(set, 0), ATgetArgument(trans, 0)); if (c < 0) set = ATgetArgument(set, 2); else if (c > 0) trans = ATgetArgument(trans, 2); else { res = set_union_sat(res, trans_level_sat(ATgetArgument(set,1), ATgetArgument(trans,1), proj, p_len, ofs, grp), 0); set = ATgetArgument(set,2); trans = ATgetArgument(trans,2); } } return res; } // Get memoized rel_prod value static inline ATerm get_rel_prod_value(int lvl, int grp, ATerm set, ATerm trans) { ATerm lvlNode = (ATerm) ATmakeInt(lvl); ATerm grpNode = (ATerm) ATmakeInt(grp); ATerm key = (ATerm) ATmakeAppl4(rel_prod, lvlNode, grpNode, set, trans); return ATtableGet(global_rc, key); } // Memoize rel_prod value static inline void put_rel_prod_value(int lvl, int grp, ATerm set, ATerm trans, ATerm value) { ATerm lvlNode = (ATerm) ATmakeInt(lvl); ATerm grpNode = (ATerm) ATmakeInt(grp); ATerm key = (ATerm) ATmakeAppl4(rel_prod, lvlNode, grpNode, set, trans); ATtablePut(global_rc, key, value); } static ATerm sat_rel_prod(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp) { if (p_len == 0) return set; else { ATerm res = get_rel_prod_value(ofs, grp, set, trans); if (res) return res; if (proj[0] == ofs) res = apply_rel_prod(set,trans,proj,p_len,ofs,grp); else res = copy_level_sat(set,trans,proj,p_len,ofs,grp); res = saturate(ofs, res); put_rel_prod_value(ofs, grp, set, trans, res); return res; } } static ATerm apply_rel_fixpoint(ATerm set, ATerm trans, int *proj, int p_len, int ofs, int grp) { ATerm res=set; while((ATgetAFun(set) == cons) && (ATgetAFun(trans) == cons)) { int c = ATcmp(ATgetArgument(set, 0), ATgetArgument(trans, 0)); if (c < 0) set = ATgetArgument(set, 2); else if (c > 0) trans = ATgetArgument(trans, 2); else { ATerm new_res = res; ATerm trans_value = ATgetArgument(trans, 0); ATerm res_value = ATgetArgument(res, 0); while (!ATisEqual(res_value, trans_value)) { new_res = ATgetArgument(new_res, 2); res_value = ATgetArgument(new_res, 0); } res = set_union_sat(res, trans_level_sat(ATgetArgument(new_res, 1), ATgetArgument(trans, 1), proj, p_len, ofs, grp), 0); set = ATgetArgument(set,2); trans = ATgetArgument(trans,2); } } return res; } // Start fixpoint calculations on the MDD at a given level for transition groups // whose top is at that level. Continue performing fixpoint calculations until // the MDD does not change anymore. static ATerm sat_fixpoint(int level, ATerm set) { if (ATisEqual(set, emptyset) || ATisEqual(set, atom)) return set; top_groups_info groups_info = top_groups[level]; ATerm old_set = emptyset; ATerm new_set = set; while (!ATisEqual(old_set, new_set)) { old_set = new_set; for (int i = 0; i < groups_info.tg_len; i++) { int grp = groups_info.top_groups[i]; // Update transition relations if (rel_set[grp]->expand != NULL) { proj_set[grp]->set = set_project_2(new_set, level, proj_set[grp]->proj, proj_set[grp]->p_len, 0); rel_set[grp]->expand(rel_set[grp], proj_set[grp], rel_set[grp]->expand_ctx); proj_set[grp]->set = emptyset; ATtableReset(global_ct); } new_set = apply_rel_fixpoint(new_set, rel_set[grp]->rel, rel_set[grp]->proj, rel_set[grp]->p_len, level, grp); } } return new_set; } // Traverse the local state values of an MDD node recursively: // - Base case: end of MDD node is reached OR MDD node is atom node. // - Induction: construct a new MDD node with the link to next entry of the // MDD node handled recursively static ATerm saturate_level(int level, ATerm node_set) { if (ATisEqual(node_set, emptyset) || ATisEqual(node_set, atom)) return node_set; ATerm sat_set = saturate(level + 1, ATgetArgument(node_set, 1)); ATerm new_node_set = saturate_level(level, ATgetArgument(node_set, 2)); return MakeCons(ATgetArgument(node_set, 0), sat_set, new_node_set); } // Saturation process for the MDD at a given level static ATerm saturate(int level, ATerm set) { ATerm new_set = ATtableGet(global_sc, set); if (new_set) return new_set; new_set = saturate_level(level, set); new_set = sat_fixpoint(level, new_set); ATtablePut(global_sc, set, new_set); return new_set; } // Perform fixpoint calculations using the "General Basic Saturation" algorithm static void set_least_fixpoint_list(vset_t dst, vset_t src, vrel_t rels[], int rel_count) { // Only implemented if not projected assert(src->p_len < 0 && dst->p_len < 0); // Initialize global hash tables. global_ct = reset_table(global_ct); global_sc = reset_table(global_sc); global_rc = reset_table(global_rc); global_uc = reset_table(global_uc); // Initialize partitioned transition relations and expansions. rel_set = rels; // Initialize top_groups_info array // This stores transition groups per topmost level int init_state_len = src->dom->shared.size; top_groups = RTmalloc(sizeof(top_groups_info[init_state_len])); proj_set = RTmalloc(sizeof(vset_t[rel_count])); for (int lvl = 0; lvl < init_state_len; lvl++) { top_groups[lvl].top_groups = RTmalloc(sizeof(int[rel_count])); top_groups[lvl].tg_len = 0; } for (int grp = 0; grp < rel_count; grp++) { proj_set[grp] = set_create_both(rels[grp]->dom, rels[grp]->p_len, rels[grp]->proj); if (rels[grp]->p_len == 0) continue; int top_lvl = rels[grp]->proj[0]; top_groups[top_lvl].top_groups[top_groups[top_lvl].tg_len] = grp; top_groups[top_lvl].tg_len++; } // Saturation on initial state set dst->set = saturate(0, src->set); // Clean-up for (int grp = 0; grp < rel_count; grp++) { if (rels[grp]->p_len == 0 && rels[grp]->expand != NULL) { proj_set[grp]->set = set_project_2(dst->set, 0, NULL, 0, 0); rel_set[grp]->expand(rel_set[grp], proj_set[grp], rel_set[grp]->expand_ctx); ATtableReset(global_ct); } vset_destroy(proj_set[grp]); } for (int lvl = 0; lvl < init_state_len; lvl++) RTfree(top_groups[lvl].top_groups); rel_set = NULL; RTfree(proj_set); RTfree(top_groups); ATtableReset(global_ct); ATtableReset(global_sc); ATtableReset(global_rc); ATtableReset(global_uc); } vdom_t vdom_create_tree(int n){ Warning(info,"Creating an AtermDD tree domain."); vdom_t dom=(vdom_t)RTmalloc(sizeof(struct vector_domain)); vdom_init_shared(dom,n); if (!emptyset) set_init(); dom->shared.set_create=set_create_both; dom->shared.set_add=set_add_tree; dom->shared.set_member=set_member_tree; dom->shared.set_is_empty=set_is_empty_both; dom->shared.set_equal=set_equal_both; dom->shared.set_clear=set_clear_both; dom->shared.set_copy=set_copy_both; dom->shared.set_enum=set_enum_tree; dom->shared.set_enum_match=set_enum_match_tree; dom->shared.set_copy_match=set_copy_match_tree; dom->shared.set_example=set_example_tree; dom->shared.set_count=set_count_tree; dom->shared.rel_count=rel_count_tree; dom->shared.set_union=set_union_tree; dom->shared.set_intersect=set_intersect_tree; dom->shared.set_minus=set_minus_tree; dom->shared.set_zip=set_zip_tree; dom->shared.set_project=set_project_tree; dom->shared.rel_create=rel_create_both; // initializes with emptyset instead of empty? wrong? -> all both functions mix this.. dom->shared.rel_add=rel_add_tree; dom->shared.set_next=set_next_tree; dom->shared.set_prev=set_prev_tree; dom->shared.reorder=reorder; dom->shared.set_destroy=set_destroy_both; return dom; } vdom_t vdom_create_list(int n){ Warning(info,"Creating an AtermDD list domain."); vdom_t dom=RT_NEW(struct vector_domain); vdom_init_shared(dom,n); if (!emptyset) set_init(); dom->shared.set_create=set_create_both; dom->shared.set_add=set_add_list; dom->shared.set_member=set_member_list; dom->shared.set_is_empty=set_is_empty_both; dom->shared.set_equal=set_equal_both; dom->shared.set_clear=set_clear_both; dom->shared.set_copy=set_copy_both; dom->shared.set_enum=set_enum_list; dom->shared.set_enum_match=set_enum_match_list; dom->shared.set_copy_match=set_copy_match_list; dom->shared.set_example=set_example_list; dom->shared.set_count=set_count_list; dom->shared.rel_count=rel_count_list; dom->shared.set_union=set_union_list; dom->shared.set_intersect=set_intersect_list; dom->shared.set_minus=set_minus_list; dom->shared.set_zip=set_zip_list; dom->shared.set_project=set_project_list; dom->shared.rel_create=rel_create_both; dom->shared.rel_add=rel_add_list; dom->shared.set_next=set_next_list; dom->shared.set_prev=set_prev_list; dom->shared.reorder=reorder; dom->shared.set_destroy=set_destroy_both; dom->shared.set_least_fixpoint= set_least_fixpoint_list; return dom; }
14596.c
void bar(double); void foo(double); void foo(double X) { #pragma spf metadata replace(bar(X)) } void bar(double X) { if (X > 0) { #pragma spf transform replace with(foo) bar(X); } }
124342.c
#define _GNU_SOURCE #include <errno.h> #include <sys/epoll.h> #include <sys/select.h> #include <sys/syscall.h> #include <sys/wait.h> #include <sys/time.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <spawn.h> #include <string.h> #include "test.h" // ============================================================================ // Helper function // ============================================================================ static void free_pipe(int *pipe) { close(pipe[0]); close(pipe[1]); } // ============================================================================ // Test cases // ============================================================================ int test_fcntl_get_flags() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } if ((fcntl(pipe_fds[0], F_GETFL, 0) != O_RDONLY) || (fcntl(pipe_fds[1], F_GETFL, 0) != O_WRONLY)) { free_pipe(pipe_fds); THROW_ERROR("fcntl get flags failed"); } free_pipe(pipe_fds); return 0; } int test_fcntl_set_flags() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } fcntl(pipe_fds[0], F_SETFL, O_NONBLOCK); if ((fcntl(pipe_fds[0], F_GETFL, 0) != (O_NONBLOCK | O_RDONLY)) || (fcntl(pipe_fds[1], F_GETFL, 0) != O_WRONLY)) { free_pipe(pipe_fds); THROW_ERROR("fcntl set flags failed"); } free_pipe(pipe_fds); return 0; } int test_create_with_flags() { int pipe_fds[2]; if (pipe2(pipe_fds, O_NONBLOCK) < 0) { THROW_ERROR("failed to create a pipe"); } if ((fcntl(pipe_fds[0], F_GETFL, 0) != (O_NONBLOCK | O_RDONLY)) || (fcntl(pipe_fds[1], F_GETFL, 0) != (O_NONBLOCK | O_WRONLY))) { free_pipe(pipe_fds); THROW_ERROR("create flags failed\n"); } free_pipe(pipe_fds); return 0; } int test_select_timeout() { fd_set rfds; int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } struct timeval tv = { .tv_sec = 1, .tv_usec = 0 }; FD_ZERO(&rfds); FD_SET(pipe_fds[0], &rfds); struct timeval tv_start, tv_end; gettimeofday(&tv_start, NULL); select(pipe_fds[0] + 1, &rfds, NULL, NULL, &tv); gettimeofday(&tv_end, NULL); double total_s = tv_end.tv_sec - tv_start.tv_sec; if (total_s < 1) { printf("time consumed is %f\n", total_s + (double)(tv_end.tv_usec - tv_start.tv_usec) / 1000000); THROW_ERROR("select timer does not work correctly"); } free_pipe(pipe_fds); return 0; } int test_epoll_timeout() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } int pipe_read_fd = pipe_fds[0]; int pipe_write_fd = pipe_fds[1]; int ep_fd = epoll_create1(0); if (ep_fd < 0) { THROW_ERROR("failed to create an epoll"); } int ret; struct epoll_event event; event.events = EPOLLIN; // we want the write end to be readable event.data.u32 = pipe_write_fd; ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, pipe_write_fd, &event); if (ret < 0) { THROW_ERROR("failed to do epoll ctl"); } event.events = EPOLLOUT; // we want the read end to be writable event.data.u32 = pipe_read_fd; ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, pipe_read_fd, &event); if (ret < 0) { THROW_ERROR("failed to do epoll ctl"); } // We are waiting for the write end to be readable or the read end to be // writable, which can never happen. So the epoll_wait must end with // timeout. errno = 0; struct epoll_event events[2]; ret = epoll_wait(ep_fd, events, ARRAY_SIZE(events), 10 /* ms */); if (ret != 0 || errno != 0) { THROW_ERROR("failed to do epoll ctl"); } free_pipe(pipe_fds); close(ep_fd); return 0; } int test_poll_timeout() { // Start the timer struct timeval tv_start, tv_end; gettimeofday(&tv_start, NULL); int fds[2]; if (pipe(fds) < 0) { THROW_ERROR("pipe failed"); } struct pollfd polls[] = { { .fd = fds[0], .events = POLLOUT }, { .fd = fds[1], .events = POLLIN } }; poll(polls, 2, 1000); // Stop the timer gettimeofday(&tv_end, NULL); double total_s = tv_end.tv_sec - tv_start.tv_sec; if ((int)total_s < 1) { printf("time consumed is %f\n", total_s + (double)(tv_end.tv_usec - tv_start.tv_usec) / 1000000); THROW_ERROR("poll timer does not work correctly"); } return 0; } int test_select_no_timeout() { fd_set wfds; int ret = 0; int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } FD_ZERO(&wfds); FD_SET(pipe_fds[1], &wfds); ret = select(pipe_fds[1] + 1, NULL, &wfds, NULL, NULL); if (ret != 1) { free_pipe(pipe_fds); THROW_ERROR("select failed"); } if (FD_ISSET(pipe_fds[1], &wfds) == 0) { free_pipe(pipe_fds); THROW_ERROR("bad select return"); } free_pipe(pipe_fds); return 0; } int test_poll_no_timeout() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } struct pollfd polls[] = { { .fd = pipe_fds[0], .events = POLLIN }, { .fd = pipe_fds[1], .events = POLLOUT }, { .fd = pipe_fds[1], .events = POLLOUT }, }; int ret = poll(polls, 3, -1); if (ret < 0) { THROW_ERROR("poll error"); } if (polls[0].revents != 0 || (polls[1].revents & POLLOUT) == 0 || (polls[2].revents & POLLOUT) == 0 || ret != 2) { THROW_ERROR("wrong return events"); } return 0; } int test_epoll_no_timeout() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } int pipe_read_fd = pipe_fds[0]; int pipe_write_fd = pipe_fds[1]; int ep_fd = epoll_create1(0); if (ep_fd < 0) { THROW_ERROR("failed to create an epoll"); } int ret; struct epoll_event event; event.events = EPOLLOUT; // writable event.data.u32 = pipe_write_fd; ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, pipe_write_fd, &event); if (ret < 0) { THROW_ERROR("failed to do epoll ctl"); } event.events = EPOLLIN; // readable event.data.u32 = pipe_read_fd; ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, pipe_read_fd, &event); if (ret < 0) { THROW_ERROR("failed to do epoll ctl"); } struct epoll_event events[2]; ret = epoll_wait(ep_fd, events, ARRAY_SIZE(events), -1); // pipe_write_fd is ready, while pipe_read_fd is not if (ret != 1) { THROW_ERROR("failed to do epoll ctl"); } free_pipe(pipe_fds); close(ep_fd); return 0; } int test_select_read_write() { int pipe_fds[2]; if (pipe(pipe_fds) < 0) { THROW_ERROR("failed to create a pipe"); } int pipe_rd_fd = pipe_fds[0]; int pipe_wr_fd = pipe_fds[1]; posix_spawn_file_actions_t file_actions; posix_spawn_file_actions_init(&file_actions); posix_spawn_file_actions_adddup2(&file_actions, pipe_wr_fd, STDOUT_FILENO); posix_spawn_file_actions_addclose(&file_actions, pipe_rd_fd); const char *msg = "Echo!\n"; const char *child_prog = "/bin/hello_world"; const char *child_argv[3] = { child_prog, msg, NULL }; int child_pid; if (posix_spawn(&child_pid, child_prog, &file_actions, NULL, (char *const *)child_argv, NULL) < 0) { THROW_ERROR("failed to spawn a child process"); } close(pipe_wr_fd); const char *expected_str = msg; size_t expected_len = strlen(expected_str); char actual_str[32] = {0}; fd_set rfds; FD_ZERO(&rfds); FD_SET(pipe_fds[0], &rfds); if (select(pipe_fds[0] + 1, &rfds, NULL, NULL, NULL) <= 0) { free_pipe(pipe_fds); THROW_ERROR("select failed"); } if (read(pipe_rd_fd, actual_str, sizeof(actual_str) - 1) < 0) { THROW_ERROR("reading pipe failed"); }; if (strncmp(expected_str, actual_str, expected_len) != 0) { THROW_ERROR("received string is not as expected"); } close(pipe_rd_fd); int status = 0; if (wait4(child_pid, &status, 0, NULL) < 0) { THROW_ERROR("failed to wait4 the child process"); } return 0; } // ============================================================================ // Test suite // ============================================================================ static test_case_t test_cases[] = { // TEST_CASE(test_fcntl_get_flags), // TEST_CASE(test_fcntl_set_flags), // TEST_CASE(test_create_with_flags), TEST_CASE(test_select_timeout), TEST_CASE(test_poll_timeout), TEST_CASE(test_epoll_timeout), TEST_CASE(test_select_no_timeout), TEST_CASE(test_poll_no_timeout), TEST_CASE(test_epoll_no_timeout), TEST_CASE(test_select_read_write), }; int main(int argc, const char *argv[]) { return test_suite_run(test_cases, ARRAY_SIZE(test_cases)); }
425897.c
/* msi-tvanywhere-plus.h - Keytable for msi_tvanywhere_plus Remote Controller * * keymap imported from ir-keymaps.c * * Copyright (c) 2010 by Mauro Carvalho Chehab * * 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 <media/rc-map.h> #include <linux/module.h> /* Keycodes for remote on the MSI TV@nywhere Plus. The controller IC on the card is marked "KS003". The controller is I2C at address 0x30, but does not seem to respond to probes until a read is performed from a valid device. I don't know why... Note: This remote may be of similar or identical design to the Pixelview remote (?). The raw codes and duplicate button codes appear to be the same. Henry Wong <[email protected]> Some changes to formatting and keycodes by Mark Schultz <[email protected]> */ static struct rc_map_table msi_tvanywhere_plus[] = { /* ---- Remote Button Layout ---- POWER SOURCE SCAN MUTE TV/FM 1 2 3 |> 4 5 6 <| 7 8 9 ^^UP 0 + RECALL vvDN RECORD STOP PLAY MINIMIZE ZOOM CH+ VOL- VOL+ CH- SNAPSHOT MTS << FUNC >> RESET */ { 0x01, KEY_1 }, /* 1 */ { 0x0b, KEY_2 }, /* 2 */ { 0x1b, KEY_3 }, /* 3 */ { 0x05, KEY_4 }, /* 4 */ { 0x09, KEY_5 }, /* 5 */ { 0x15, KEY_6 }, /* 6 */ { 0x06, KEY_7 }, /* 7 */ { 0x0a, KEY_8 }, /* 8 */ { 0x12, KEY_9 }, /* 9 */ { 0x02, KEY_0 }, /* 0 */ { 0x10, KEY_KPPLUS }, /* + */ { 0x13, KEY_AGAIN }, /* Recall */ { 0x1e, KEY_POWER }, /* Power */ { 0x07, KEY_VIDEO }, /* Source */ { 0x1c, KEY_SEARCH }, /* Scan */ { 0x18, KEY_MUTE }, /* Mute */ { 0x03, KEY_RADIO }, /* TV/FM */ /* The next four keys are duplicates that appear to send the same IR code as Ch+, Ch-, >>, and << . The raw code assigned to them is the actual code + 0x20 - they will never be detected as such unless some way is discovered to distinguish these buttons from those that have the same code. */ { 0x3f, KEY_RIGHT }, /* |> and Ch+ */ { 0x37, KEY_LEFT }, /* <| and Ch- */ { 0x2c, KEY_UP }, /* ^^Up and >> */ { 0x24, KEY_DOWN }, /* vvDn and << */ { 0x00, KEY_RECORD }, /* Record */ { 0x08, KEY_STOP }, /* Stop */ { 0x11, KEY_PLAY }, /* Play */ { 0x0f, KEY_CLOSE }, /* Minimize */ { 0x19, KEY_ZOOM }, /* Zoom */ { 0x1a, KEY_CAMERA }, /* Snapshot */ { 0x0d, KEY_LANGUAGE }, /* MTS */ { 0x14, KEY_VOLUMEDOWN }, /* Vol- */ { 0x16, KEY_VOLUMEUP }, /* Vol+ */ { 0x17, KEY_CHANNELDOWN }, /* Ch- */ { 0x1f, KEY_CHANNELUP }, /* Ch+ */ { 0x04, KEY_REWIND }, /* << */ { 0x0e, KEY_MENU }, /* Function */ { 0x0c, KEY_FASTFORWARD }, /* >> */ { 0x1d, KEY_RESTART }, /* Reset */ }; static struct rc_map_list msi_tvanywhere_plus_map = { .map = { .scan = msi_tvanywhere_plus, .size = ARRAY_SIZE(msi_tvanywhere_plus), .rc_proto = RC_PROTO_UNKNOWN, /* Legacy IR type */ .name = RC_MAP_MSI_TVANYWHERE_PLUS, } }; static int __init init_rc_map_msi_tvanywhere_plus(void) { return rc_map_register(&msi_tvanywhere_plus_map); } static void __exit exit_rc_map_msi_tvanywhere_plus(void) { rc_map_unregister(&msi_tvanywhere_plus_map); } module_init(init_rc_map_msi_tvanywhere_plus) module_exit(exit_rc_map_msi_tvanywhere_plus) MODULE_LICENSE("GPL"); MODULE_AUTHOR("Mauro Carvalho Chehab");
103404.c
/* * Copyright 2015 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * */ #include "pp_debug.h" #include <linux/types.h> #include <linux/kernel.h> #include <linux/slab.h> #include "atom-types.h" #include "atombios.h" #include "processpptables.h" #include "cgs_common.h" #include "smu/smu_8_0_d.h" #include "smu8_fusion.h" #include "smu/smu_8_0_sh_mask.h" #include "smumgr.h" #include "hwmgr.h" #include "hardwaremanager.h" #include "cz_ppsmc.h" #include "smu8_hwmgr.h" #include "power_state.h" #include "pp_thermal.h" #define ixSMUSVI_NB_CURRENTVID 0xD8230044 #define CURRENT_NB_VID_MASK 0xff000000 #define CURRENT_NB_VID__SHIFT 24 #define ixSMUSVI_GFX_CURRENTVID 0xD8230048 #define CURRENT_GFX_VID_MASK 0xff000000 #define CURRENT_GFX_VID__SHIFT 24 static const unsigned long smu8_magic = (unsigned long) PHM_Cz_Magic; static struct smu8_power_state *cast_smu8_power_state(struct pp_hw_power_state *hw_ps) { if (smu8_magic != hw_ps->magic) return NULL; return (struct smu8_power_state *)hw_ps; } static const struct smu8_power_state *cast_const_smu8_power_state( const struct pp_hw_power_state *hw_ps) { if (smu8_magic != hw_ps->magic) return NULL; return (struct smu8_power_state *)hw_ps; } static uint32_t smu8_get_eclk_level(struct pp_hwmgr *hwmgr, uint32_t clock, uint32_t msg) { int i = 0; struct phm_vce_clock_voltage_dependency_table *ptable = hwmgr->dyn_state.vce_clock_voltage_dependency_table; switch (msg) { case PPSMC_MSG_SetEclkSoftMin: case PPSMC_MSG_SetEclkHardMin: for (i = 0; i < (int)ptable->count; i++) { if (clock <= ptable->entries[i].ecclk) break; } break; case PPSMC_MSG_SetEclkSoftMax: case PPSMC_MSG_SetEclkHardMax: for (i = ptable->count - 1; i >= 0; i--) { if (clock >= ptable->entries[i].ecclk) break; } break; default: break; } return i; } static uint32_t smu8_get_sclk_level(struct pp_hwmgr *hwmgr, uint32_t clock, uint32_t msg) { int i = 0; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; switch (msg) { case PPSMC_MSG_SetSclkSoftMin: case PPSMC_MSG_SetSclkHardMin: for (i = 0; i < (int)table->count; i++) { if (clock <= table->entries[i].clk) break; } break; case PPSMC_MSG_SetSclkSoftMax: case PPSMC_MSG_SetSclkHardMax: for (i = table->count - 1; i >= 0; i--) { if (clock >= table->entries[i].clk) break; } break; default: break; } return i; } static uint32_t smu8_get_uvd_level(struct pp_hwmgr *hwmgr, uint32_t clock, uint32_t msg) { int i = 0; struct phm_uvd_clock_voltage_dependency_table *ptable = hwmgr->dyn_state.uvd_clock_voltage_dependency_table; switch (msg) { case PPSMC_MSG_SetUvdSoftMin: case PPSMC_MSG_SetUvdHardMin: for (i = 0; i < (int)ptable->count; i++) { if (clock <= ptable->entries[i].vclk) break; } break; case PPSMC_MSG_SetUvdSoftMax: case PPSMC_MSG_SetUvdHardMax: for (i = ptable->count - 1; i >= 0; i--) { if (clock >= ptable->entries[i].vclk) break; } break; default: break; } return i; } static uint32_t smu8_get_max_sclk_level(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; if (data->max_sclk_level == 0) { smum_send_msg_to_smc(hwmgr, PPSMC_MSG_GetMaxSclkLevel); data->max_sclk_level = smum_get_argument(hwmgr) + 1; } return data->max_sclk_level; } static int smu8_initialize_dpm_defaults(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct amdgpu_device *adev = hwmgr->adev; data->gfx_ramp_step = 256*25/100; data->gfx_ramp_delay = 1; /* by default, we delay 1us */ data->mgcg_cgtt_local0 = 0x00000000; data->mgcg_cgtt_local1 = 0x00000000; data->clock_slow_down_freq = 25000; data->skip_clock_slow_down = 1; data->enable_nb_ps_policy = 1; /* disable until UNB is ready, Enabled */ data->voltage_drop_in_dce_power_gating = 0; /* disable until fully verified */ data->voting_rights_clients = 0x00C00033; data->static_screen_threshold = 8; data->ddi_power_gating_disabled = 0; data->bapm_enabled = 1; data->voltage_drop_threshold = 0; data->gfx_power_gating_threshold = 500; data->vce_slow_sclk_threshold = 20000; data->dce_slow_sclk_threshold = 30000; data->disable_driver_thermal_policy = 1; data->disable_nb_ps3_in_battery = 0; phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_ABM); phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_NonABMSupportInPPLib); phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_DynamicM3Arbiter); data->override_dynamic_mgpg = 1; phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_DynamicPatchPowerState); data->thermal_auto_throttling_treshold = 0; data->tdr_clock = 0; data->disable_gfx_power_gating_in_uvd = 0; phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_DynamicUVDState); phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_UVDDPM); phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_VCEDPM); data->cc6_settings.cpu_cc6_disable = false; data->cc6_settings.cpu_pstate_disable = false; data->cc6_settings.nb_pstate_switch_disable = false; data->cc6_settings.cpu_pstate_separation_time = 0; phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_DisableVoltageIsland); phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_UVDPowerGating); phm_cap_unset(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_VCEPowerGating); if (adev->pg_flags & AMD_PG_SUPPORT_UVD) phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_UVDPowerGating); if (adev->pg_flags & AMD_PG_SUPPORT_VCE) phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_VCEPowerGating); return 0; } /* convert form 8bit vid to real voltage in mV*4 */ static uint32_t smu8_convert_8Bit_index_to_voltage( struct pp_hwmgr *hwmgr, uint16_t voltage) { return 6200 - (voltage * 25); } static int smu8_construct_max_power_limits_table(struct pp_hwmgr *hwmgr, struct phm_clock_and_voltage_limits *table) { struct smu8_hwmgr *data = hwmgr->backend; struct smu8_sys_info *sys_info = &data->sys_info; struct phm_clock_voltage_dependency_table *dep_table = hwmgr->dyn_state.vddc_dependency_on_sclk; if (dep_table->count > 0) { table->sclk = dep_table->entries[dep_table->count-1].clk; table->vddc = smu8_convert_8Bit_index_to_voltage(hwmgr, (uint16_t)dep_table->entries[dep_table->count-1].v); } table->mclk = sys_info->nbp_memory_clock[0]; return 0; } static int smu8_init_dynamic_state_adjustment_rule_settings( struct pp_hwmgr *hwmgr, ATOM_CLK_VOLT_CAPABILITY *disp_voltage_table) { uint32_t table_size = sizeof(struct phm_clock_voltage_dependency_table) + (7 * sizeof(struct phm_clock_voltage_dependency_record)); struct phm_clock_voltage_dependency_table *table_clk_vlt = kzalloc(table_size, GFP_KERNEL); if (NULL == table_clk_vlt) { pr_err("Can not allocate memory!\n"); return -ENOMEM; } table_clk_vlt->count = 8; table_clk_vlt->entries[0].clk = PP_DAL_POWERLEVEL_0; table_clk_vlt->entries[0].v = 0; table_clk_vlt->entries[1].clk = PP_DAL_POWERLEVEL_1; table_clk_vlt->entries[1].v = 1; table_clk_vlt->entries[2].clk = PP_DAL_POWERLEVEL_2; table_clk_vlt->entries[2].v = 2; table_clk_vlt->entries[3].clk = PP_DAL_POWERLEVEL_3; table_clk_vlt->entries[3].v = 3; table_clk_vlt->entries[4].clk = PP_DAL_POWERLEVEL_4; table_clk_vlt->entries[4].v = 4; table_clk_vlt->entries[5].clk = PP_DAL_POWERLEVEL_5; table_clk_vlt->entries[5].v = 5; table_clk_vlt->entries[6].clk = PP_DAL_POWERLEVEL_6; table_clk_vlt->entries[6].v = 6; table_clk_vlt->entries[7].clk = PP_DAL_POWERLEVEL_7; table_clk_vlt->entries[7].v = 7; hwmgr->dyn_state.vddc_dep_on_dal_pwrl = table_clk_vlt; return 0; } static int smu8_get_system_info_data(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; ATOM_INTEGRATED_SYSTEM_INFO_V1_9 *info = NULL; uint32_t i; int result = 0; uint8_t frev, crev; uint16_t size; info = (ATOM_INTEGRATED_SYSTEM_INFO_V1_9 *)smu_atom_get_data_table(hwmgr->adev, GetIndexIntoMasterTable(DATA, IntegratedSystemInfo), &size, &frev, &crev); if (info == NULL) { pr_err("Could not retrieve the Integrated System Info Table!\n"); return -EINVAL; } if (crev != 9) { pr_err("Unsupported IGP table: %d %d\n", frev, crev); return -EINVAL; } data->sys_info.bootup_uma_clock = le32_to_cpu(info->ulBootUpUMAClock); data->sys_info.bootup_engine_clock = le32_to_cpu(info->ulBootUpEngineClock); data->sys_info.dentist_vco_freq = le32_to_cpu(info->ulDentistVCOFreq); data->sys_info.system_config = le32_to_cpu(info->ulSystemConfig); data->sys_info.bootup_nb_voltage_index = le16_to_cpu(info->usBootUpNBVoltage); data->sys_info.htc_hyst_lmt = (info->ucHtcHystLmt == 0) ? 5 : info->ucHtcHystLmt; data->sys_info.htc_tmp_lmt = (info->ucHtcTmpLmt == 0) ? 203 : info->ucHtcTmpLmt; if (data->sys_info.htc_tmp_lmt <= data->sys_info.htc_hyst_lmt) { pr_err("The htcTmpLmt should be larger than htcHystLmt.\n"); return -EINVAL; } data->sys_info.nb_dpm_enable = data->enable_nb_ps_policy && (le32_to_cpu(info->ulSystemConfig) >> 3 & 0x1); for (i = 0; i < SMU8_NUM_NBPSTATES; i++) { if (i < SMU8_NUM_NBPMEMORYCLOCK) { data->sys_info.nbp_memory_clock[i] = le32_to_cpu(info->ulNbpStateMemclkFreq[i]); } data->sys_info.nbp_n_clock[i] = le32_to_cpu(info->ulNbpStateNClkFreq[i]); } for (i = 0; i < MAX_DISPLAY_CLOCK_LEVEL; i++) { data->sys_info.display_clock[i] = le32_to_cpu(info->sDispClkVoltageMapping[i].ulMaximumSupportedCLK); } /* Here use 4 levels, make sure not exceed */ for (i = 0; i < SMU8_NUM_NBPSTATES; i++) { data->sys_info.nbp_voltage_index[i] = le16_to_cpu(info->usNBPStateVoltage[i]); } if (!data->sys_info.nb_dpm_enable) { for (i = 1; i < SMU8_NUM_NBPSTATES; i++) { if (i < SMU8_NUM_NBPMEMORYCLOCK) { data->sys_info.nbp_memory_clock[i] = data->sys_info.nbp_memory_clock[0]; } data->sys_info.nbp_n_clock[i] = data->sys_info.nbp_n_clock[0]; data->sys_info.nbp_voltage_index[i] = data->sys_info.nbp_voltage_index[0]; } } if (le32_to_cpu(info->ulGPUCapInfo) & SYS_INFO_GPUCAPS__ENABEL_DFS_BYPASS) { phm_cap_set(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_EnableDFSBypass); } data->sys_info.uma_channel_number = info->ucUMAChannelNumber; smu8_construct_max_power_limits_table (hwmgr, &hwmgr->dyn_state.max_clock_voltage_on_ac); smu8_init_dynamic_state_adjustment_rule_settings(hwmgr, &info->sDISPCLK_Voltage[0]); return result; } static int smu8_construct_boot_state(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->boot_power_level.engineClock = data->sys_info.bootup_engine_clock; data->boot_power_level.vddcIndex = (uint8_t)data->sys_info.bootup_nb_voltage_index; data->boot_power_level.dsDividerIndex = 0; data->boot_power_level.ssDividerIndex = 0; data->boot_power_level.allowGnbSlow = 1; data->boot_power_level.forceNBPstate = 0; data->boot_power_level.hysteresis_up = 0; data->boot_power_level.numSIMDToPowerDown = 0; data->boot_power_level.display_wm = 0; data->boot_power_level.vce_wm = 0; return 0; } static int smu8_upload_pptable_to_smu(struct pp_hwmgr *hwmgr) { struct SMU8_Fusion_ClkTable *clock_table; int ret; uint32_t i; void *table = NULL; pp_atomctrl_clock_dividers_kong dividers; struct phm_clock_voltage_dependency_table *vddc_table = hwmgr->dyn_state.vddc_dependency_on_sclk; struct phm_clock_voltage_dependency_table *vdd_gfx_table = hwmgr->dyn_state.vdd_gfx_dependency_on_sclk; struct phm_acp_clock_voltage_dependency_table *acp_table = hwmgr->dyn_state.acp_clock_voltage_dependency_table; struct phm_uvd_clock_voltage_dependency_table *uvd_table = hwmgr->dyn_state.uvd_clock_voltage_dependency_table; struct phm_vce_clock_voltage_dependency_table *vce_table = hwmgr->dyn_state.vce_clock_voltage_dependency_table; if (!hwmgr->need_pp_table_upload) return 0; ret = smum_download_powerplay_table(hwmgr, &table); PP_ASSERT_WITH_CODE((0 == ret && NULL != table), "Fail to get clock table from SMU!", return -EINVAL;); clock_table = (struct SMU8_Fusion_ClkTable *)table; /* patch clock table */ PP_ASSERT_WITH_CODE((vddc_table->count <= SMU8_MAX_HARDWARE_POWERLEVELS), "Dependency table entry exceeds max limit!", return -EINVAL;); PP_ASSERT_WITH_CODE((vdd_gfx_table->count <= SMU8_MAX_HARDWARE_POWERLEVELS), "Dependency table entry exceeds max limit!", return -EINVAL;); PP_ASSERT_WITH_CODE((acp_table->count <= SMU8_MAX_HARDWARE_POWERLEVELS), "Dependency table entry exceeds max limit!", return -EINVAL;); PP_ASSERT_WITH_CODE((uvd_table->count <= SMU8_MAX_HARDWARE_POWERLEVELS), "Dependency table entry exceeds max limit!", return -EINVAL;); PP_ASSERT_WITH_CODE((vce_table->count <= SMU8_MAX_HARDWARE_POWERLEVELS), "Dependency table entry exceeds max limit!", return -EINVAL;); for (i = 0; i < SMU8_MAX_HARDWARE_POWERLEVELS; i++) { /* vddc_sclk */ clock_table->SclkBreakdownTable.ClkLevel[i].GnbVid = (i < vddc_table->count) ? (uint8_t)vddc_table->entries[i].v : 0; clock_table->SclkBreakdownTable.ClkLevel[i].Frequency = (i < vddc_table->count) ? vddc_table->entries[i].clk : 0; atomctrl_get_engine_pll_dividers_kong(hwmgr, clock_table->SclkBreakdownTable.ClkLevel[i].Frequency, &dividers); clock_table->SclkBreakdownTable.ClkLevel[i].DfsDid = (uint8_t)dividers.pll_post_divider; /* vddgfx_sclk */ clock_table->SclkBreakdownTable.ClkLevel[i].GfxVid = (i < vdd_gfx_table->count) ? (uint8_t)vdd_gfx_table->entries[i].v : 0; /* acp breakdown */ clock_table->AclkBreakdownTable.ClkLevel[i].GfxVid = (i < acp_table->count) ? (uint8_t)acp_table->entries[i].v : 0; clock_table->AclkBreakdownTable.ClkLevel[i].Frequency = (i < acp_table->count) ? acp_table->entries[i].acpclk : 0; atomctrl_get_engine_pll_dividers_kong(hwmgr, clock_table->AclkBreakdownTable.ClkLevel[i].Frequency, &dividers); clock_table->AclkBreakdownTable.ClkLevel[i].DfsDid = (uint8_t)dividers.pll_post_divider; /* uvd breakdown */ clock_table->VclkBreakdownTable.ClkLevel[i].GfxVid = (i < uvd_table->count) ? (uint8_t)uvd_table->entries[i].v : 0; clock_table->VclkBreakdownTable.ClkLevel[i].Frequency = (i < uvd_table->count) ? uvd_table->entries[i].vclk : 0; atomctrl_get_engine_pll_dividers_kong(hwmgr, clock_table->VclkBreakdownTable.ClkLevel[i].Frequency, &dividers); clock_table->VclkBreakdownTable.ClkLevel[i].DfsDid = (uint8_t)dividers.pll_post_divider; clock_table->DclkBreakdownTable.ClkLevel[i].GfxVid = (i < uvd_table->count) ? (uint8_t)uvd_table->entries[i].v : 0; clock_table->DclkBreakdownTable.ClkLevel[i].Frequency = (i < uvd_table->count) ? uvd_table->entries[i].dclk : 0; atomctrl_get_engine_pll_dividers_kong(hwmgr, clock_table->DclkBreakdownTable.ClkLevel[i].Frequency, &dividers); clock_table->DclkBreakdownTable.ClkLevel[i].DfsDid = (uint8_t)dividers.pll_post_divider; /* vce breakdown */ clock_table->EclkBreakdownTable.ClkLevel[i].GfxVid = (i < vce_table->count) ? (uint8_t)vce_table->entries[i].v : 0; clock_table->EclkBreakdownTable.ClkLevel[i].Frequency = (i < vce_table->count) ? vce_table->entries[i].ecclk : 0; atomctrl_get_engine_pll_dividers_kong(hwmgr, clock_table->EclkBreakdownTable.ClkLevel[i].Frequency, &dividers); clock_table->EclkBreakdownTable.ClkLevel[i].DfsDid = (uint8_t)dividers.pll_post_divider; } ret = smum_upload_powerplay_table(hwmgr); return ret; } static int smu8_init_sclk_limit(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; unsigned long clock = 0, level; if (NULL == table || table->count <= 0) return -EINVAL; data->sclk_dpm.soft_min_clk = table->entries[0].clk; data->sclk_dpm.hard_min_clk = table->entries[0].clk; level = smu8_get_max_sclk_level(hwmgr) - 1; if (level < table->count) clock = table->entries[level].clk; else clock = table->entries[table->count - 1].clk; data->sclk_dpm.soft_max_clk = clock; data->sclk_dpm.hard_max_clk = clock; return 0; } static int smu8_init_uvd_limit(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_uvd_clock_voltage_dependency_table *table = hwmgr->dyn_state.uvd_clock_voltage_dependency_table; unsigned long clock = 0, level; if (NULL == table || table->count <= 0) return -EINVAL; data->uvd_dpm.soft_min_clk = 0; data->uvd_dpm.hard_min_clk = 0; smum_send_msg_to_smc(hwmgr, PPSMC_MSG_GetMaxUvdLevel); level = smum_get_argument(hwmgr); if (level < table->count) clock = table->entries[level].vclk; else clock = table->entries[table->count - 1].vclk; data->uvd_dpm.soft_max_clk = clock; data->uvd_dpm.hard_max_clk = clock; return 0; } static int smu8_init_vce_limit(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_vce_clock_voltage_dependency_table *table = hwmgr->dyn_state.vce_clock_voltage_dependency_table; unsigned long clock = 0, level; if (NULL == table || table->count <= 0) return -EINVAL; data->vce_dpm.soft_min_clk = 0; data->vce_dpm.hard_min_clk = 0; smum_send_msg_to_smc(hwmgr, PPSMC_MSG_GetMaxEclkLevel); level = smum_get_argument(hwmgr); if (level < table->count) clock = table->entries[level].ecclk; else clock = table->entries[table->count - 1].ecclk; data->vce_dpm.soft_max_clk = clock; data->vce_dpm.hard_max_clk = clock; return 0; } static int smu8_init_acp_limit(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_acp_clock_voltage_dependency_table *table = hwmgr->dyn_state.acp_clock_voltage_dependency_table; unsigned long clock = 0, level; if (NULL == table || table->count <= 0) return -EINVAL; data->acp_dpm.soft_min_clk = 0; data->acp_dpm.hard_min_clk = 0; smum_send_msg_to_smc(hwmgr, PPSMC_MSG_GetMaxAclkLevel); level = smum_get_argument(hwmgr); if (level < table->count) clock = table->entries[level].acpclk; else clock = table->entries[table->count - 1].acpclk; data->acp_dpm.soft_max_clk = clock; data->acp_dpm.hard_max_clk = clock; return 0; } static void smu8_init_power_gate_state(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->uvd_power_gated = false; data->vce_power_gated = false; data->samu_power_gated = false; #ifdef CONFIG_DRM_AMD_ACP data->acp_power_gated = false; #else smum_send_msg_to_smc(hwmgr, PPSMC_MSG_ACPPowerOFF); data->acp_power_gated = true; #endif } static void smu8_init_sclk_threshold(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->low_sclk_interrupt_threshold = 0; } static int smu8_update_sclk_limit(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; unsigned long clock = 0; unsigned long level; unsigned long stable_pstate_sclk; unsigned long percentage; data->sclk_dpm.soft_min_clk = table->entries[0].clk; level = smu8_get_max_sclk_level(hwmgr) - 1; if (level < table->count) data->sclk_dpm.soft_max_clk = table->entries[level].clk; else data->sclk_dpm.soft_max_clk = table->entries[table->count - 1].clk; clock = hwmgr->display_config->min_core_set_clock; if (clock == 0) pr_debug("min_core_set_clock not set\n"); if (data->sclk_dpm.hard_min_clk != clock) { data->sclk_dpm.hard_min_clk = clock; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkHardMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.hard_min_clk, PPSMC_MSG_SetSclkHardMin)); } clock = data->sclk_dpm.soft_min_clk; /* update minimum clocks for Stable P-State feature */ if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_StablePState)) { percentage = 75; /*Sclk - calculate sclk value based on percentage and find FLOOR sclk from VddcDependencyOnSCLK table */ stable_pstate_sclk = (hwmgr->dyn_state.max_clock_voltage_on_ac.mclk * percentage) / 100; if (clock < stable_pstate_sclk) clock = stable_pstate_sclk; } if (data->sclk_dpm.soft_min_clk != clock) { data->sclk_dpm.soft_min_clk = clock; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_min_clk, PPSMC_MSG_SetSclkSoftMin)); } if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_StablePState) && data->sclk_dpm.soft_max_clk != clock) { data->sclk_dpm.soft_max_clk = clock; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_max_clk, PPSMC_MSG_SetSclkSoftMax)); } return 0; } static int smu8_set_deep_sleep_sclk_threshold(struct pp_hwmgr *hwmgr) { if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_SclkDeepSleep)) { uint32_t clks = hwmgr->display_config->min_core_set_clock_in_sr; if (clks == 0) clks = SMU8_MIN_DEEP_SLEEP_SCLK; PP_DBG_LOG("Setting Deep Sleep Clock: %d\n", clks); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetMinDeepSleepSclk, clks); } return 0; } static int smu8_set_watermark_threshold(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetWatermarkFrequency, data->sclk_dpm.soft_max_clk); return 0; } static int smu8_nbdpm_pstate_enable_disable(struct pp_hwmgr *hwmgr, bool enable, bool lock) { struct smu8_hwmgr *hw_data = hwmgr->backend; if (hw_data->is_nb_dpm_enabled) { if (enable) { PP_DBG_LOG("enable Low Memory PState.\n"); return smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_EnableLowMemoryPstate, (lock ? 1 : 0)); } else { PP_DBG_LOG("disable Low Memory PState.\n"); return smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DisableLowMemoryPstate, (lock ? 1 : 0)); } } return 0; } static int smu8_disable_nb_dpm(struct pp_hwmgr *hwmgr) { int ret = 0; struct smu8_hwmgr *data = hwmgr->backend; unsigned long dpm_features = 0; if (data->is_nb_dpm_enabled) { smu8_nbdpm_pstate_enable_disable(hwmgr, true, true); dpm_features |= NB_DPM_MASK; ret = smum_send_msg_to_smc_with_parameter( hwmgr, PPSMC_MSG_DisableAllSmuFeatures, dpm_features); if (ret == 0) data->is_nb_dpm_enabled = false; } return ret; } static int smu8_enable_nb_dpm(struct pp_hwmgr *hwmgr) { int ret = 0; struct smu8_hwmgr *data = hwmgr->backend; unsigned long dpm_features = 0; if (!data->is_nb_dpm_enabled) { PP_DBG_LOG("enabling ALL SMU features.\n"); dpm_features |= NB_DPM_MASK; ret = smum_send_msg_to_smc_with_parameter( hwmgr, PPSMC_MSG_EnableAllSmuFeatures, dpm_features); if (ret == 0) data->is_nb_dpm_enabled = true; } return ret; } static int smu8_update_low_mem_pstate(struct pp_hwmgr *hwmgr, const void *input) { bool disable_switch; bool enable_low_mem_state; struct smu8_hwmgr *hw_data = hwmgr->backend; const struct phm_set_power_state_input *states = (struct phm_set_power_state_input *)input; const struct smu8_power_state *pnew_state = cast_const_smu8_power_state(states->pnew_state); if (hw_data->sys_info.nb_dpm_enable) { disable_switch = hw_data->cc6_settings.nb_pstate_switch_disable ? true : false; enable_low_mem_state = hw_data->cc6_settings.nb_pstate_switch_disable ? false : true; if (pnew_state->action == FORCE_HIGH) smu8_nbdpm_pstate_enable_disable(hwmgr, false, disable_switch); else if (pnew_state->action == CANCEL_FORCE_HIGH) smu8_nbdpm_pstate_enable_disable(hwmgr, true, disable_switch); else smu8_nbdpm_pstate_enable_disable(hwmgr, enable_low_mem_state, disable_switch); } return 0; } static int smu8_set_power_state_tasks(struct pp_hwmgr *hwmgr, const void *input) { int ret = 0; smu8_update_sclk_limit(hwmgr); smu8_set_deep_sleep_sclk_threshold(hwmgr); smu8_set_watermark_threshold(hwmgr); ret = smu8_enable_nb_dpm(hwmgr); if (ret) return ret; smu8_update_low_mem_pstate(hwmgr, input); return 0; } static int smu8_setup_asic_task(struct pp_hwmgr *hwmgr) { int ret; ret = smu8_upload_pptable_to_smu(hwmgr); if (ret) return ret; ret = smu8_init_sclk_limit(hwmgr); if (ret) return ret; ret = smu8_init_uvd_limit(hwmgr); if (ret) return ret; ret = smu8_init_vce_limit(hwmgr); if (ret) return ret; ret = smu8_init_acp_limit(hwmgr); if (ret) return ret; smu8_init_power_gate_state(hwmgr); smu8_init_sclk_threshold(hwmgr); return 0; } static void smu8_power_up_display_clock_sys_pll(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *hw_data = hwmgr->backend; hw_data->disp_clk_bypass_pending = false; hw_data->disp_clk_bypass = false; } static void smu8_clear_nb_dpm_flag(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *hw_data = hwmgr->backend; hw_data->is_nb_dpm_enabled = false; } static void smu8_reset_cc6_data(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *hw_data = hwmgr->backend; hw_data->cc6_settings.cc6_setting_changed = false; hw_data->cc6_settings.cpu_pstate_separation_time = 0; hw_data->cc6_settings.cpu_cc6_disable = false; hw_data->cc6_settings.cpu_pstate_disable = false; } static void smu8_program_voting_clients(struct pp_hwmgr *hwmgr) { cgs_write_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixCG_FREQ_TRAN_VOTING_0, SMU8_VOTINGRIGHTSCLIENTS_DFLT0); } static void smu8_clear_voting_clients(struct pp_hwmgr *hwmgr) { cgs_write_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixCG_FREQ_TRAN_VOTING_0, 0); } static int smu8_start_dpm(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->dpm_flags |= DPMFlags_SCLK_Enabled; return smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_EnableAllSmuFeatures, SCLK_DPM_MASK); } static int smu8_stop_dpm(struct pp_hwmgr *hwmgr) { int ret = 0; struct smu8_hwmgr *data = hwmgr->backend; unsigned long dpm_features = 0; if (data->dpm_flags & DPMFlags_SCLK_Enabled) { dpm_features |= SCLK_DPM_MASK; data->dpm_flags &= ~DPMFlags_SCLK_Enabled; ret = smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DisableAllSmuFeatures, dpm_features); } return ret; } static int smu8_program_bootup_state(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->sclk_dpm.soft_min_clk = data->sys_info.bootup_engine_clock; data->sclk_dpm.soft_max_clk = data->sys_info.bootup_engine_clock; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_min_clk, PPSMC_MSG_SetSclkSoftMin)); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_max_clk, PPSMC_MSG_SetSclkSoftMax)); return 0; } static void smu8_reset_acp_boot_level(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; data->acp_boot_level = 0xff; } static int smu8_enable_dpm_tasks(struct pp_hwmgr *hwmgr) { smu8_program_voting_clients(hwmgr); if (smu8_start_dpm(hwmgr)) return -EINVAL; smu8_program_bootup_state(hwmgr); smu8_reset_acp_boot_level(hwmgr); return 0; } static int smu8_disable_dpm_tasks(struct pp_hwmgr *hwmgr) { smu8_disable_nb_dpm(hwmgr); smu8_clear_voting_clients(hwmgr); if (smu8_stop_dpm(hwmgr)) return -EINVAL; return 0; } static int smu8_power_off_asic(struct pp_hwmgr *hwmgr) { smu8_disable_dpm_tasks(hwmgr); smu8_power_up_display_clock_sys_pll(hwmgr); smu8_clear_nb_dpm_flag(hwmgr); smu8_reset_cc6_data(hwmgr); return 0; } static int smu8_apply_state_adjust_rules(struct pp_hwmgr *hwmgr, struct pp_power_state *prequest_ps, const struct pp_power_state *pcurrent_ps) { struct smu8_power_state *smu8_ps = cast_smu8_power_state(&prequest_ps->hardware); const struct smu8_power_state *smu8_current_ps = cast_const_smu8_power_state(&pcurrent_ps->hardware); struct smu8_hwmgr *data = hwmgr->backend; struct PP_Clocks clocks = {0, 0, 0, 0}; bool force_high; smu8_ps->need_dfs_bypass = true; data->battery_state = (PP_StateUILabel_Battery == prequest_ps->classification.ui_label); clocks.memoryClock = hwmgr->display_config->min_mem_set_clock != 0 ? hwmgr->display_config->min_mem_set_clock : data->sys_info.nbp_memory_clock[1]; if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_StablePState)) clocks.memoryClock = hwmgr->dyn_state.max_clock_voltage_on_ac.mclk; force_high = (clocks.memoryClock > data->sys_info.nbp_memory_clock[SMU8_NUM_NBPMEMORYCLOCK - 1]) || (hwmgr->display_config->num_display >= 3); smu8_ps->action = smu8_current_ps->action; if (hwmgr->request_dpm_level == AMD_DPM_FORCED_LEVEL_PROFILE_PEAK) smu8_nbdpm_pstate_enable_disable(hwmgr, false, false); else if (hwmgr->request_dpm_level == AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD) smu8_nbdpm_pstate_enable_disable(hwmgr, false, true); else if (!force_high && (smu8_ps->action == FORCE_HIGH)) smu8_ps->action = CANCEL_FORCE_HIGH; else if (force_high && (smu8_ps->action != FORCE_HIGH)) smu8_ps->action = FORCE_HIGH; else smu8_ps->action = DO_NOTHING; return 0; } static int smu8_hwmgr_backend_init(struct pp_hwmgr *hwmgr) { int result = 0; struct smu8_hwmgr *data; data = kzalloc(sizeof(struct smu8_hwmgr), GFP_KERNEL); if (data == NULL) return -ENOMEM; hwmgr->backend = data; result = smu8_initialize_dpm_defaults(hwmgr); if (result != 0) { pr_err("smu8_initialize_dpm_defaults failed\n"); return result; } result = smu8_get_system_info_data(hwmgr); if (result != 0) { pr_err("smu8_get_system_info_data failed\n"); return result; } smu8_construct_boot_state(hwmgr); hwmgr->platform_descriptor.hardwareActivityPerformanceLevels = SMU8_MAX_HARDWARE_POWERLEVELS; return result; } static int smu8_hwmgr_backend_fini(struct pp_hwmgr *hwmgr) { if (hwmgr != NULL) { kfree(hwmgr->dyn_state.vddc_dep_on_dal_pwrl); hwmgr->dyn_state.vddc_dep_on_dal_pwrl = NULL; kfree(hwmgr->backend); hwmgr->backend = NULL; } return 0; } static int smu8_phm_force_dpm_highest(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_max_clk, PPSMC_MSG_SetSclkSoftMin)); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_max_clk, PPSMC_MSG_SetSclkSoftMax)); return 0; } static int smu8_phm_unforce_dpm_levels(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; unsigned long clock = 0, level; if (NULL == table || table->count <= 0) return -EINVAL; data->sclk_dpm.soft_min_clk = table->entries[0].clk; data->sclk_dpm.hard_min_clk = table->entries[0].clk; hwmgr->pstate_sclk = table->entries[0].clk; hwmgr->pstate_mclk = 0; level = smu8_get_max_sclk_level(hwmgr) - 1; if (level < table->count) clock = table->entries[level].clk; else clock = table->entries[table->count - 1].clk; data->sclk_dpm.soft_max_clk = clock; data->sclk_dpm.hard_max_clk = clock; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_min_clk, PPSMC_MSG_SetSclkSoftMin)); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_max_clk, PPSMC_MSG_SetSclkSoftMax)); return 0; } static int smu8_phm_force_dpm_lowest(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_min_clk, PPSMC_MSG_SetSclkSoftMax)); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, smu8_get_sclk_level(hwmgr, data->sclk_dpm.soft_min_clk, PPSMC_MSG_SetSclkSoftMin)); return 0; } static int smu8_dpm_force_dpm_level(struct pp_hwmgr *hwmgr, enum amd_dpm_forced_level level) { int ret = 0; switch (level) { case AMD_DPM_FORCED_LEVEL_HIGH: case AMD_DPM_FORCED_LEVEL_PROFILE_PEAK: ret = smu8_phm_force_dpm_highest(hwmgr); break; case AMD_DPM_FORCED_LEVEL_LOW: case AMD_DPM_FORCED_LEVEL_PROFILE_MIN_SCLK: case AMD_DPM_FORCED_LEVEL_PROFILE_STANDARD: ret = smu8_phm_force_dpm_lowest(hwmgr); break; case AMD_DPM_FORCED_LEVEL_AUTO: ret = smu8_phm_unforce_dpm_levels(hwmgr); break; case AMD_DPM_FORCED_LEVEL_MANUAL: case AMD_DPM_FORCED_LEVEL_PROFILE_EXIT: default: break; } return ret; } static int smu8_dpm_powerdown_uvd(struct pp_hwmgr *hwmgr) { if (PP_CAP(PHM_PlatformCaps_UVDPowerGating)) return smum_send_msg_to_smc(hwmgr, PPSMC_MSG_UVDPowerOFF); return 0; } static int smu8_dpm_powerup_uvd(struct pp_hwmgr *hwmgr) { if (PP_CAP(PHM_PlatformCaps_UVDPowerGating)) { return smum_send_msg_to_smc_with_parameter( hwmgr, PPSMC_MSG_UVDPowerON, PP_CAP(PHM_PlatformCaps_UVDDynamicPowerGating) ? 1 : 0); } return 0; } static int smu8_dpm_update_vce_dpm(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_vce_clock_voltage_dependency_table *ptable = hwmgr->dyn_state.vce_clock_voltage_dependency_table; /* Stable Pstate is enabled and we need to set the VCE DPM to highest level */ if (PP_CAP(PHM_PlatformCaps_StablePState) || hwmgr->en_umd_pstate) { data->vce_dpm.hard_min_clk = ptable->entries[ptable->count - 1].ecclk; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetEclkHardMin, smu8_get_eclk_level(hwmgr, data->vce_dpm.hard_min_clk, PPSMC_MSG_SetEclkHardMin)); } else { smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetEclkHardMin, 0); /* disable ECLK DPM 0. Otherwise VCE could hang if * switching SCLK from DPM 0 to 6/7 */ smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetEclkSoftMin, 1); } return 0; } static int smu8_dpm_powerdown_vce(struct pp_hwmgr *hwmgr) { if (PP_CAP(PHM_PlatformCaps_VCEPowerGating)) return smum_send_msg_to_smc(hwmgr, PPSMC_MSG_VCEPowerOFF); return 0; } static int smu8_dpm_powerup_vce(struct pp_hwmgr *hwmgr) { if (PP_CAP(PHM_PlatformCaps_VCEPowerGating)) return smum_send_msg_to_smc(hwmgr, PPSMC_MSG_VCEPowerON); return 0; } static uint32_t smu8_dpm_get_mclk(struct pp_hwmgr *hwmgr, bool low) { struct smu8_hwmgr *data = hwmgr->backend; return data->sys_info.bootup_uma_clock; } static uint32_t smu8_dpm_get_sclk(struct pp_hwmgr *hwmgr, bool low) { struct pp_power_state *ps; struct smu8_power_state *smu8_ps; if (hwmgr == NULL) return -EINVAL; ps = hwmgr->request_ps; if (ps == NULL) return -EINVAL; smu8_ps = cast_smu8_power_state(&ps->hardware); if (low) return smu8_ps->levels[0].engineClock; else return smu8_ps->levels[smu8_ps->level-1].engineClock; } static int smu8_dpm_patch_boot_state(struct pp_hwmgr *hwmgr, struct pp_hw_power_state *hw_ps) { struct smu8_hwmgr *data = hwmgr->backend; struct smu8_power_state *smu8_ps = cast_smu8_power_state(hw_ps); smu8_ps->level = 1; smu8_ps->nbps_flags = 0; smu8_ps->bapm_flags = 0; smu8_ps->levels[0] = data->boot_power_level; return 0; } static int smu8_dpm_get_pp_table_entry_callback( struct pp_hwmgr *hwmgr, struct pp_hw_power_state *hw_ps, unsigned int index, const void *clock_info) { struct smu8_power_state *smu8_ps = cast_smu8_power_state(hw_ps); const ATOM_PPLIB_CZ_CLOCK_INFO *smu8_clock_info = clock_info; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; uint8_t clock_info_index = smu8_clock_info->index; if (clock_info_index > (uint8_t)(hwmgr->platform_descriptor.hardwareActivityPerformanceLevels - 1)) clock_info_index = (uint8_t)(hwmgr->platform_descriptor.hardwareActivityPerformanceLevels - 1); smu8_ps->levels[index].engineClock = table->entries[clock_info_index].clk; smu8_ps->levels[index].vddcIndex = (uint8_t)table->entries[clock_info_index].v; smu8_ps->level = index + 1; if (phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_SclkDeepSleep)) { smu8_ps->levels[index].dsDividerIndex = 5; smu8_ps->levels[index].ssDividerIndex = 5; } return 0; } static int smu8_dpm_get_num_of_pp_table_entries(struct pp_hwmgr *hwmgr) { int result; unsigned long ret = 0; result = pp_tables_get_num_of_entries(hwmgr, &ret); return result ? 0 : ret; } static int smu8_dpm_get_pp_table_entry(struct pp_hwmgr *hwmgr, unsigned long entry, struct pp_power_state *ps) { int result; struct smu8_power_state *smu8_ps; ps->hardware.magic = smu8_magic; smu8_ps = cast_smu8_power_state(&(ps->hardware)); result = pp_tables_get_entry(hwmgr, entry, ps, smu8_dpm_get_pp_table_entry_callback); smu8_ps->uvd_clocks.vclk = ps->uvd_clocks.VCLK; smu8_ps->uvd_clocks.dclk = ps->uvd_clocks.DCLK; return result; } static int smu8_get_power_state_size(struct pp_hwmgr *hwmgr) { return sizeof(struct smu8_power_state); } static void smu8_hw_print_display_cfg( const struct cc6_settings *cc6_settings) { PP_DBG_LOG("New Display Configuration:\n"); PP_DBG_LOG(" cpu_cc6_disable: %d\n", cc6_settings->cpu_cc6_disable); PP_DBG_LOG(" cpu_pstate_disable: %d\n", cc6_settings->cpu_pstate_disable); PP_DBG_LOG(" nb_pstate_switch_disable: %d\n", cc6_settings->nb_pstate_switch_disable); PP_DBG_LOG(" cpu_pstate_separation_time: %d\n\n", cc6_settings->cpu_pstate_separation_time); } static int smu8_set_cpu_power_state(struct pp_hwmgr *hwmgr) { struct smu8_hwmgr *hw_data = hwmgr->backend; uint32_t data = 0; if (hw_data->cc6_settings.cc6_setting_changed) { hw_data->cc6_settings.cc6_setting_changed = false; smu8_hw_print_display_cfg(&hw_data->cc6_settings); data |= (hw_data->cc6_settings.cpu_pstate_separation_time & PWRMGT_SEPARATION_TIME_MASK) << PWRMGT_SEPARATION_TIME_SHIFT; data |= (hw_data->cc6_settings.cpu_cc6_disable ? 0x1 : 0x0) << PWRMGT_DISABLE_CPU_CSTATES_SHIFT; data |= (hw_data->cc6_settings.cpu_pstate_disable ? 0x1 : 0x0) << PWRMGT_DISABLE_CPU_PSTATES_SHIFT; PP_DBG_LOG("SetDisplaySizePowerParams data: 0x%X\n", data); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetDisplaySizePowerParams, data); } return 0; } static int smu8_store_cc6_data(struct pp_hwmgr *hwmgr, uint32_t separation_time, bool cc6_disable, bool pstate_disable, bool pstate_switch_disable) { struct smu8_hwmgr *hw_data = hwmgr->backend; if (separation_time != hw_data->cc6_settings.cpu_pstate_separation_time || cc6_disable != hw_data->cc6_settings.cpu_cc6_disable || pstate_disable != hw_data->cc6_settings.cpu_pstate_disable || pstate_switch_disable != hw_data->cc6_settings.nb_pstate_switch_disable) { hw_data->cc6_settings.cc6_setting_changed = true; hw_data->cc6_settings.cpu_pstate_separation_time = separation_time; hw_data->cc6_settings.cpu_cc6_disable = cc6_disable; hw_data->cc6_settings.cpu_pstate_disable = pstate_disable; hw_data->cc6_settings.nb_pstate_switch_disable = pstate_switch_disable; } return 0; } static int smu8_get_dal_power_level(struct pp_hwmgr *hwmgr, struct amd_pp_simple_clock_info *info) { uint32_t i; const struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dep_on_dal_pwrl; const struct phm_clock_and_voltage_limits *limits = &hwmgr->dyn_state.max_clock_voltage_on_ac; info->engine_max_clock = limits->sclk; info->memory_max_clock = limits->mclk; for (i = table->count - 1; i > 0; i--) { if (limits->vddc >= table->entries[i].v) { info->level = table->entries[i].clk; return 0; } } return -EINVAL; } static int smu8_force_clock_level(struct pp_hwmgr *hwmgr, enum pp_clock_type type, uint32_t mask) { switch (type) { case PP_SCLK: smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMin, mask); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetSclkSoftMax, mask); break; default: break; } return 0; } static int smu8_print_clock_levels(struct pp_hwmgr *hwmgr, enum pp_clock_type type, char *buf) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_clock_voltage_dependency_table *sclk_table = hwmgr->dyn_state.vddc_dependency_on_sclk; int i, now, size = 0; switch (type) { case PP_SCLK: now = PHM_GET_FIELD(cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTARGET_AND_CURRENT_PROFILE_INDEX), TARGET_AND_CURRENT_PROFILE_INDEX, CURR_SCLK_INDEX); for (i = 0; i < sclk_table->count; i++) size += sprintf(buf + size, "%d: %uMhz %s\n", i, sclk_table->entries[i].clk / 100, (i == now) ? "*" : ""); break; case PP_MCLK: now = PHM_GET_FIELD(cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTARGET_AND_CURRENT_PROFILE_INDEX), TARGET_AND_CURRENT_PROFILE_INDEX, CURR_MCLK_INDEX); for (i = SMU8_NUM_NBPMEMORYCLOCK; i > 0; i--) size += sprintf(buf + size, "%d: %uMhz %s\n", SMU8_NUM_NBPMEMORYCLOCK-i, data->sys_info.nbp_memory_clock[i-1] / 100, (SMU8_NUM_NBPMEMORYCLOCK-i == now) ? "*" : ""); break; default: break; } return size; } static int smu8_get_performance_level(struct pp_hwmgr *hwmgr, const struct pp_hw_power_state *state, PHM_PerformanceLevelDesignation designation, uint32_t index, PHM_PerformanceLevel *level) { const struct smu8_power_state *ps; struct smu8_hwmgr *data; uint32_t level_index; uint32_t i; if (level == NULL || hwmgr == NULL || state == NULL) return -EINVAL; data = hwmgr->backend; ps = cast_const_smu8_power_state(state); level_index = index > ps->level - 1 ? ps->level - 1 : index; level->coreClock = ps->levels[level_index].engineClock; if (designation == PHM_PerformanceLevelDesignation_PowerContainment) { for (i = 1; i < ps->level; i++) { if (ps->levels[i].engineClock > data->dce_slow_sclk_threshold) { level->coreClock = ps->levels[i].engineClock; break; } } } if (level_index == 0) level->memory_clock = data->sys_info.nbp_memory_clock[SMU8_NUM_NBPMEMORYCLOCK - 1]; else level->memory_clock = data->sys_info.nbp_memory_clock[0]; level->vddc = (smu8_convert_8Bit_index_to_voltage(hwmgr, ps->levels[level_index].vddcIndex) + 2) / 4; level->nonLocalMemoryFreq = 0; level->nonLocalMemoryWidth = 0; return 0; } static int smu8_get_current_shallow_sleep_clocks(struct pp_hwmgr *hwmgr, const struct pp_hw_power_state *state, struct pp_clock_info *clock_info) { const struct smu8_power_state *ps = cast_const_smu8_power_state(state); clock_info->min_eng_clk = ps->levels[0].engineClock / (1 << (ps->levels[0].ssDividerIndex)); clock_info->max_eng_clk = ps->levels[ps->level - 1].engineClock / (1 << (ps->levels[ps->level - 1].ssDividerIndex)); return 0; } static int smu8_get_clock_by_type(struct pp_hwmgr *hwmgr, enum amd_pp_clock_type type, struct amd_pp_clocks *clocks) { struct smu8_hwmgr *data = hwmgr->backend; int i; struct phm_clock_voltage_dependency_table *table; clocks->count = smu8_get_max_sclk_level(hwmgr); switch (type) { case amd_pp_disp_clock: for (i = 0; i < clocks->count; i++) clocks->clock[i] = data->sys_info.display_clock[i] * 10; break; case amd_pp_sys_clock: table = hwmgr->dyn_state.vddc_dependency_on_sclk; for (i = 0; i < clocks->count; i++) clocks->clock[i] = table->entries[i].clk * 10; break; case amd_pp_mem_clock: clocks->count = SMU8_NUM_NBPMEMORYCLOCK; for (i = 0; i < clocks->count; i++) clocks->clock[i] = data->sys_info.nbp_memory_clock[clocks->count - 1 - i] * 10; break; default: return -1; } return 0; } static int smu8_get_max_high_clocks(struct pp_hwmgr *hwmgr, struct amd_pp_simple_clock_info *clocks) { struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; unsigned long level; const struct phm_clock_and_voltage_limits *limits = &hwmgr->dyn_state.max_clock_voltage_on_ac; if ((NULL == table) || (table->count <= 0) || (clocks == NULL)) return -EINVAL; level = smu8_get_max_sclk_level(hwmgr) - 1; if (level < table->count) clocks->engine_max_clock = table->entries[level].clk; else clocks->engine_max_clock = table->entries[table->count - 1].clk; clocks->memory_max_clock = limits->mclk; return 0; } static int smu8_thermal_get_temperature(struct pp_hwmgr *hwmgr) { int actual_temp = 0; uint32_t val = cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTHM_TCON_CUR_TMP); uint32_t temp = PHM_GET_FIELD(val, THM_TCON_CUR_TMP, CUR_TEMP); if (PHM_GET_FIELD(val, THM_TCON_CUR_TMP, CUR_TEMP_RANGE_SEL)) actual_temp = ((temp / 8) - 49) * PP_TEMPERATURE_UNITS_PER_CENTIGRADES; else actual_temp = (temp / 8) * PP_TEMPERATURE_UNITS_PER_CENTIGRADES; return actual_temp; } static int smu8_read_sensor(struct pp_hwmgr *hwmgr, int idx, void *value, int *size) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_clock_voltage_dependency_table *table = hwmgr->dyn_state.vddc_dependency_on_sclk; struct phm_vce_clock_voltage_dependency_table *vce_table = hwmgr->dyn_state.vce_clock_voltage_dependency_table; struct phm_uvd_clock_voltage_dependency_table *uvd_table = hwmgr->dyn_state.uvd_clock_voltage_dependency_table; uint32_t sclk_index = PHM_GET_FIELD(cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTARGET_AND_CURRENT_PROFILE_INDEX), TARGET_AND_CURRENT_PROFILE_INDEX, CURR_SCLK_INDEX); uint32_t uvd_index = PHM_GET_FIELD(cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTARGET_AND_CURRENT_PROFILE_INDEX_2), TARGET_AND_CURRENT_PROFILE_INDEX_2, CURR_UVD_INDEX); uint32_t vce_index = PHM_GET_FIELD(cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixTARGET_AND_CURRENT_PROFILE_INDEX_2), TARGET_AND_CURRENT_PROFILE_INDEX_2, CURR_VCE_INDEX); uint32_t sclk, vclk, dclk, ecclk, tmp, activity_percent; uint16_t vddnb, vddgfx; int result; /* size must be at least 4 bytes for all sensors */ if (*size < 4) return -EINVAL; *size = 4; switch (idx) { case AMDGPU_PP_SENSOR_GFX_SCLK: if (sclk_index < NUM_SCLK_LEVELS) { sclk = table->entries[sclk_index].clk; *((uint32_t *)value) = sclk; return 0; } return -EINVAL; case AMDGPU_PP_SENSOR_VDDNB: tmp = (cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixSMUSVI_NB_CURRENTVID) & CURRENT_NB_VID_MASK) >> CURRENT_NB_VID__SHIFT; vddnb = smu8_convert_8Bit_index_to_voltage(hwmgr, tmp) / 4; *((uint32_t *)value) = vddnb; return 0; case AMDGPU_PP_SENSOR_VDDGFX: tmp = (cgs_read_ind_register(hwmgr->device, CGS_IND_REG__SMC, ixSMUSVI_GFX_CURRENTVID) & CURRENT_GFX_VID_MASK) >> CURRENT_GFX_VID__SHIFT; vddgfx = smu8_convert_8Bit_index_to_voltage(hwmgr, (u16)tmp) / 4; *((uint32_t *)value) = vddgfx; return 0; case AMDGPU_PP_SENSOR_UVD_VCLK: if (!data->uvd_power_gated) { if (uvd_index >= SMU8_MAX_HARDWARE_POWERLEVELS) { return -EINVAL; } else { vclk = uvd_table->entries[uvd_index].vclk; *((uint32_t *)value) = vclk; return 0; } } *((uint32_t *)value) = 0; return 0; case AMDGPU_PP_SENSOR_UVD_DCLK: if (!data->uvd_power_gated) { if (uvd_index >= SMU8_MAX_HARDWARE_POWERLEVELS) { return -EINVAL; } else { dclk = uvd_table->entries[uvd_index].dclk; *((uint32_t *)value) = dclk; return 0; } } *((uint32_t *)value) = 0; return 0; case AMDGPU_PP_SENSOR_VCE_ECCLK: if (!data->vce_power_gated) { if (vce_index >= SMU8_MAX_HARDWARE_POWERLEVELS) { return -EINVAL; } else { ecclk = vce_table->entries[vce_index].ecclk; *((uint32_t *)value) = ecclk; return 0; } } *((uint32_t *)value) = 0; return 0; case AMDGPU_PP_SENSOR_GPU_LOAD: result = smum_send_msg_to_smc(hwmgr, PPSMC_MSG_GetAverageGraphicsActivity); if (0 == result) { activity_percent = cgs_read_register(hwmgr->device, mmSMU_MP1_SRBM2P_ARG_0); activity_percent = activity_percent > 100 ? 100 : activity_percent; } else { activity_percent = 50; } *((uint32_t *)value) = activity_percent; return 0; case AMDGPU_PP_SENSOR_UVD_POWER: *((uint32_t *)value) = data->uvd_power_gated ? 0 : 1; return 0; case AMDGPU_PP_SENSOR_VCE_POWER: *((uint32_t *)value) = data->vce_power_gated ? 0 : 1; return 0; case AMDGPU_PP_SENSOR_GPU_TEMP: *((uint32_t *)value) = smu8_thermal_get_temperature(hwmgr); return 0; default: return -EINVAL; } } static int smu8_notify_cac_buffer_info(struct pp_hwmgr *hwmgr, uint32_t virtual_addr_low, uint32_t virtual_addr_hi, uint32_t mc_addr_low, uint32_t mc_addr_hi, uint32_t size) { smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DramAddrHiVirtual, mc_addr_hi); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DramAddrLoVirtual, mc_addr_low); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DramAddrHiPhysical, virtual_addr_hi); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DramAddrLoPhysical, virtual_addr_low); smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DramBufferSize, size); return 0; } static int smu8_get_thermal_temperature_range(struct pp_hwmgr *hwmgr, struct PP_TemperatureRange *thermal_data) { struct smu8_hwmgr *data = hwmgr->backend; memcpy(thermal_data, &SMU7ThermalPolicy[0], sizeof(struct PP_TemperatureRange)); thermal_data->max = (data->thermal_auto_throttling_treshold + data->sys_info.htc_hyst_lmt) * PP_TEMPERATURE_UNITS_PER_CENTIGRADES; return 0; } static int smu8_enable_disable_uvd_dpm(struct pp_hwmgr *hwmgr, bool enable) { struct smu8_hwmgr *data = hwmgr->backend; uint32_t dpm_features = 0; if (enable && phm_cap_enabled(hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_UVDDPM)) { data->dpm_flags |= DPMFlags_UVD_Enabled; dpm_features |= UVD_DPM_MASK; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_EnableAllSmuFeatures, dpm_features); } else { dpm_features |= UVD_DPM_MASK; data->dpm_flags &= ~DPMFlags_UVD_Enabled; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DisableAllSmuFeatures, dpm_features); } return 0; } int smu8_dpm_update_uvd_dpm(struct pp_hwmgr *hwmgr, bool bgate) { struct smu8_hwmgr *data = hwmgr->backend; struct phm_uvd_clock_voltage_dependency_table *ptable = hwmgr->dyn_state.uvd_clock_voltage_dependency_table; if (!bgate) { /* Stable Pstate is enabled and we need to set the UVD DPM to highest level */ if (PP_CAP(PHM_PlatformCaps_StablePState) || hwmgr->en_umd_pstate) { data->uvd_dpm.hard_min_clk = ptable->entries[ptable->count - 1].vclk; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_SetUvdHardMin, smu8_get_uvd_level(hwmgr, data->uvd_dpm.hard_min_clk, PPSMC_MSG_SetUvdHardMin)); smu8_enable_disable_uvd_dpm(hwmgr, true); } else { smu8_enable_disable_uvd_dpm(hwmgr, true); } } else { smu8_enable_disable_uvd_dpm(hwmgr, false); } return 0; } static int smu8_enable_disable_vce_dpm(struct pp_hwmgr *hwmgr, bool enable) { struct smu8_hwmgr *data = hwmgr->backend; uint32_t dpm_features = 0; if (enable && phm_cap_enabled( hwmgr->platform_descriptor.platformCaps, PHM_PlatformCaps_VCEDPM)) { data->dpm_flags |= DPMFlags_VCE_Enabled; dpm_features |= VCE_DPM_MASK; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_EnableAllSmuFeatures, dpm_features); } else { dpm_features |= VCE_DPM_MASK; data->dpm_flags &= ~DPMFlags_VCE_Enabled; smum_send_msg_to_smc_with_parameter(hwmgr, PPSMC_MSG_DisableAllSmuFeatures, dpm_features); } return 0; } static void smu8_dpm_powergate_acp(struct pp_hwmgr *hwmgr, bool bgate) { struct smu8_hwmgr *data = hwmgr->backend; if (data->acp_power_gated == bgate) return; if (bgate) smum_send_msg_to_smc(hwmgr, PPSMC_MSG_ACPPowerOFF); else smum_send_msg_to_smc(hwmgr, PPSMC_MSG_ACPPowerON); } static void smu8_dpm_powergate_uvd(struct pp_hwmgr *hwmgr, bool bgate) { struct smu8_hwmgr *data = hwmgr->backend; data->uvd_power_gated = bgate; if (bgate) { amdgpu_device_ip_set_powergating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_UVD, AMD_PG_STATE_GATE); amdgpu_device_ip_set_clockgating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_UVD, AMD_CG_STATE_GATE); smu8_dpm_update_uvd_dpm(hwmgr, true); smu8_dpm_powerdown_uvd(hwmgr); } else { smu8_dpm_powerup_uvd(hwmgr); amdgpu_device_ip_set_clockgating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_UVD, AMD_CG_STATE_UNGATE); amdgpu_device_ip_set_powergating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_UVD, AMD_PG_STATE_UNGATE); smu8_dpm_update_uvd_dpm(hwmgr, false); } } static void smu8_dpm_powergate_vce(struct pp_hwmgr *hwmgr, bool bgate) { struct smu8_hwmgr *data = hwmgr->backend; if (bgate) { amdgpu_device_ip_set_powergating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_VCE, AMD_PG_STATE_GATE); amdgpu_device_ip_set_clockgating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_VCE, AMD_CG_STATE_GATE); smu8_enable_disable_vce_dpm(hwmgr, false); smu8_dpm_powerdown_vce(hwmgr); data->vce_power_gated = true; } else { smu8_dpm_powerup_vce(hwmgr); data->vce_power_gated = false; amdgpu_device_ip_set_clockgating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_VCE, AMD_CG_STATE_UNGATE); amdgpu_device_ip_set_powergating_state(hwmgr->adev, AMD_IP_BLOCK_TYPE_VCE, AMD_PG_STATE_UNGATE); smu8_dpm_update_vce_dpm(hwmgr); smu8_enable_disable_vce_dpm(hwmgr, true); } } static const struct pp_hwmgr_func smu8_hwmgr_funcs = { .backend_init = smu8_hwmgr_backend_init, .backend_fini = smu8_hwmgr_backend_fini, .apply_state_adjust_rules = smu8_apply_state_adjust_rules, .force_dpm_level = smu8_dpm_force_dpm_level, .get_power_state_size = smu8_get_power_state_size, .powerdown_uvd = smu8_dpm_powerdown_uvd, .powergate_uvd = smu8_dpm_powergate_uvd, .powergate_vce = smu8_dpm_powergate_vce, .powergate_acp = smu8_dpm_powergate_acp, .get_mclk = smu8_dpm_get_mclk, .get_sclk = smu8_dpm_get_sclk, .patch_boot_state = smu8_dpm_patch_boot_state, .get_pp_table_entry = smu8_dpm_get_pp_table_entry, .get_num_of_pp_table_entries = smu8_dpm_get_num_of_pp_table_entries, .set_cpu_power_state = smu8_set_cpu_power_state, .store_cc6_data = smu8_store_cc6_data, .force_clock_level = smu8_force_clock_level, .print_clock_levels = smu8_print_clock_levels, .get_dal_power_level = smu8_get_dal_power_level, .get_performance_level = smu8_get_performance_level, .get_current_shallow_sleep_clocks = smu8_get_current_shallow_sleep_clocks, .get_clock_by_type = smu8_get_clock_by_type, .get_max_high_clocks = smu8_get_max_high_clocks, .read_sensor = smu8_read_sensor, .power_off_asic = smu8_power_off_asic, .asic_setup = smu8_setup_asic_task, .dynamic_state_management_enable = smu8_enable_dpm_tasks, .power_state_set = smu8_set_power_state_tasks, .dynamic_state_management_disable = smu8_disable_dpm_tasks, .notify_cac_buffer_info = smu8_notify_cac_buffer_info, .update_nbdpm_pstate = smu8_nbdpm_pstate_enable_disable, .get_thermal_temperature_range = smu8_get_thermal_temperature_range, }; int smu8_init_function_pointers(struct pp_hwmgr *hwmgr) { hwmgr->hwmgr_func = &smu8_hwmgr_funcs; hwmgr->pptable_func = &pptable_funcs; return 0; }
343656.c
#include "../vm.h" uint8_t vm_op_xor(t_vm *dxvm) { (dxvm->reg)[0] ^= (dxvm->reg)[1]; return (VM_STAT_RUN); }
364110.c
/*++ Copyright (c) 1990-2000 Microsoft Corporation Module Name: ARP.C - LAN arp module. Abstract: This file implements arp framing for IP layer on the upper edge and interfaces with ndis driver on the lower edge. Author: [Environment:] kernel mode only [Notes:] optional-notes Revision History: --*/ #include "precomp.h" //*** arp.c - ARP routines. // // This file containes all of the ARP related routines, including // table lookup, registration, etc. // // ARP is architected to support multiple protocols, but for now // it in only implemented to take one protocol (IP). This is done // for simplicity and ease of implementation. In the future we may // split ARP out into a seperate driver. #include "arp.h" #include "arpdef.h" #include "iproute.h" #include "iprtdef.h" #include "arpinfo.h" #include "tcpipbuf.h" #include "mdlpool.h" #include "ipifcons.h" #define NDIS_MAJOR_VERSION 0x4 #define NDIS_MINOR_VERSION 0 #ifndef NDIS_API #define NDIS_API #endif #define PPP_HW_ADDR "DEST" #define PPP_HW_ADDR_LEN 4 #if DBG uint fakereset = 0; #endif extern void IPReset(void *Context); UINT cUniAdapters = 0; extern uint EnableBcastArpReply; static ulong ARPLookahead = LOOKAHEAD_SIZE; static const uchar ENetBcst[] = "\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x08\x06"; static const uchar TRBcst[] = "\x10\x40\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00\x82\x70"; static const uchar FDDIBcst[] = "\x57\xff\xff\xff\xff\xff\xff\x00\x00\x00\x00\x00\x00"; static const uchar ARCBcst[] = "\x00\x00\xd5"; ulong TRFunctionalMcast = 0; //canonical or non-canonical? static uchar TRMcst[] = "\x10\x40\xc0\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x82\x70"; //#define TR_MCAST_FUNCTIONAL_ADDRESS 0xc00000040000 //canonical form #define TR_MCAST_FUNCTIONAL_ADDRESS 0x030000200000 static uchar TRNetMcst[] = "\x00\x04\x00\x00"; static const uchar ENetMcst[] = "\x01\x00\x5E\x00\x00\x00"; static const uchar FDDIMcst[] = "\x57\x01\x00\x5E\x00\x00\x00"; static const uchar ARPSNAP[] = "\xAA\xAA\x03\x00\x00\x00\x08\x06"; static const uchar ENetPtrnMsk[] = "\x00\x30"; static const uchar ENetSNAPPtrnMsk[] = "\x00\xC0\x3f"; //static const uchar TRPtrnMsk[] = "\x03\x00"; //static const uchar TRSNAPPtrnMsk[] = "\x03\xC0\x3f"; static const uchar TRPtrnMsk[] = "\x00\x00"; //NO AC/FC bits need to be checked static const uchar TRSNAPPtrnMsk[] = "\x00\xC0\x3f"; static const uchar FDDIPtrnMsk[] = "\x01\x00"; static const uchar FDDISNAPPtrnMsk[] = "\x01\x70\x1f"; static const uchar ARCPtrnMsk[] = "\x01"; static const uchar ARPPtrnMsk[] = "\x80\x00\x00\x0F"; static const uchar ARCARPPtrnMsk[] = "\x80\xC0\x03"; NDIS_STATUS __stdcall DoWakeupPattern(void *Context, PNET_PM_WAKEUP_PATTERN_DESC PtrnDesc, ushort protoid, BOOLEAN AddPattern); NDIS_STATUS ARPWakeupPattern(ARPInterface *Interface, IPAddr Address, BOOLEAN AddPattern); NDIS_STATUS AddrNotifyLink(ARPInterface *Interface); static WCHAR ARPName[] = TCP_NAME; NDIS_HANDLE ARPHandle; // Our NDIS protocol handle. uint ArpCacheLife; extern uint ArpMinValidCacheLife; uint sArpAlwaysSourceRoute; // True if we always send ARP requests uint ArpRetryCount; // retries for arp request with source // route info on token ring. uint sIPAlwaysSourceRoute; extern uchar TrRii; extern PDRIVER_OBJECT IPDriverObject; extern DisableTaskOffload; extern NDIS_STATUS __stdcall IPPnPEvent(void *, PNET_PNP_EVENT PnPEvent); extern NDIS_STATUS GetIPConfigValue(NDIS_HANDLE Handle, PUNICODE_STRING IPConfig); extern VOID IPUnload(IN PDRIVER_OBJECT DriverObject); extern BOOLEAN CopyToNdisSafe( PNDIS_BUFFER DestBuf, PNDIS_BUFFER *ppNextBuf, uchar *SrcBuf, uint Size, uint *StartOffset); extern void NDIS_API ARPSendComplete(NDIS_HANDLE, PNDIS_PACKET, NDIS_STATUS); extern void IPULUnloadNotify(void); extern void NotifyOfUnload(void); extern uint OpenIFConfig(PNDIS_STRING ConfigName, NDIS_HANDLE * Handle); extern int IsLLInterfaceValueNull(NDIS_HANDLE Handle); extern void CloseIFConfig(NDIS_HANDLE Handle); BOOLEAN QueryAndSetOffload(ARPInterface *ai); ARPTableEntry *CreateARPTableEntry(ARPInterface *Interface, IPAddr Destination, CTELockHandle *Handle, void *UserArp); NDIS_STATUS NDIS_API ARPRcvIndicationNew(NDIS_HANDLE Handle, NDIS_HANDLE Context, void *Header, uint HeaderSize, void *Data, uint Size, uint TotalSize, PNDIS_BUFFER pNdisBuffer, PINT pClientCnt); void CompleteIPSetNTEAddrRequestDelayed(CTEEvent *WorkerThreadEvent, PVOID Context); // Tables for bitswapping. const uchar SwapTableLo[] = { 0, // 0 0x08, // 1 0x04, // 2 0x0c, // 3 0x02, // 4 0x0a, // 5, 0x06, // 6, 0x0e, // 7, 0x01, // 8, 0x09, // 9, 0x05, // 10, 0x0d, // 11, 0x03, // 12, 0x0b, // 13, 0x07, // 14, 0x0f // 15 }; const uchar SwapTableHi[] = { 0, // 0 0x80, // 1 0x40, // 2 0xc0, // 3 0x20, // 4 0xa0, // 5, 0x60, // 6, 0xe0, // 7, 0x10, // 8, 0x90, // 9, 0x50, // 10, 0xd0, // 11, 0x30, // 12, 0xb0, // 13, 0x70, // 14, 0xf0 // 15 }; // Table of source route maximum I-field lengths for token ring. const ushort IFieldSize[] = { 516, 1500, 2052, 4472, 8191 }; #define LF_BIT_SHIFT 4 #define MAX_LF_BITS 4 // // Disposable init or paged code. // void FreeARPInterface(ARPInterface * Interface); void ARPOpen(void *Context); void NotifyConflictProc(CTEEvent * Event, void *Context); #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, ARPInit) #pragma alloc_text(PAGE, ARPOpen) #pragma alloc_text(PAGELK, ARPRegister) #pragma alloc_text(PAGE, NotifyConflictProc) #endif // ALLOC_PRAGMA LIST_ENTRY ArpInterfaceList; CACHE_LINE_KSPIN_LOCK ArpInterfaceListLock; HANDLE ArpEnetHeaderPool; HANDLE ArpAuxHeaderPool; #define BUFSIZE_ENET_HEADER_POOL sizeof(ENetHeader) + sizeof(ARPHeader) #define BUFSIZE_AUX_HEADER_POOL ARP_MAX_MEDIA_TR + (2 * sizeof(ARPHeader)) // // Support Structs for DoNDISRequest (BLOCKING & NON-BLOCKING) // typedef struct _RequestBlock { NDIS_REQUEST Request; // Request structure we'll use ULONG Blocking; // ? Is this Request Blocking ? CTEBlockStruc Block; // Structure for blocking on. No longer use // ai_block since multiple requests can // occur simultaneously. // ai_block is now only used for blocking on // opening and closing the NDIS adapter. ULONG RefCount; // Reference count (only used for blocking). // Reference counting is required for Windows ME since KeWaitForSingleObject // can fail (when the event is NOT set) and we need to protect the memory // until completion. } RequestBlock; // This prototype enables DoNDISRequest to compile without errors void NDIS_API ARPRequestComplete(NDIS_HANDLE Handle, PNDIS_REQUEST pRequest, NDIS_STATUS Status); //* FillARPControlBlock // // A utility routine to transfer a physical address into an ARPControlBlock, // taking into account different MAC address formats. // // Entry: // Interface - the ARPInterface which identifies the media // Entry - the ARP entry containing the MAC address // ArpContB - the control-block to be filled // __inline NDIS_STATUS FillARPControlBlock(ARPInterface* Interface, ARPTableEntry* Entry, ARPControlBlock* ArpContB) { ENetHeader *EHdr; TRHeader *TRHdr; FDDIHeader *FHdr; ARCNetHeader *AHdr; uint Size = 0; NDIS_STATUS Status; if (Interface->ai_media == NdisMediumArcnet878_2) { if (!ArpContB->PhyAddrLen) { return NDIS_STATUS_BUFFER_OVERFLOW; } Status = NDIS_STATUS_SUCCESS; } else if (ArpContB->PhyAddrLen < ARP_802_ADDR_LENGTH) { Size = ArpContB->PhyAddrLen; Status = NDIS_STATUS_BUFFER_OVERFLOW; } else { Size = ARP_802_ADDR_LENGTH; Status = NDIS_STATUS_SUCCESS; } switch (Interface->ai_media) { case NdisMedium802_3: EHdr = (ENetHeader *) Entry->ate_addr; RtlCopyMemory(ArpContB->PhyAddr, EHdr->eh_daddr, Size); ArpContB->PhyAddrLen = Size; break; case NdisMedium802_5: TRHdr = (TRHeader *) Entry->ate_addr; RtlCopyMemory(ArpContB->PhyAddr, TRHdr->tr_daddr, Size); ArpContB->PhyAddrLen = Size; break; case NdisMediumFddi: FHdr = (FDDIHeader *) Entry->ate_addr; RtlCopyMemory(ArpContB->PhyAddr, FHdr->fh_daddr, Size); ArpContB->PhyAddrLen = Size; break; case NdisMediumArcnet878_2: AHdr = (ARCNetHeader *) Entry->ate_addr; ArpContB->PhyAddr[0] = AHdr->ah_daddr; ArpContB->PhyAddrLen = 1; break; default: ASSERT(0); } return Status; } //* DoNDISRequest - Submit a (NON) BLOCKING request to an NDIS driver // // This is a utility routine to submit a general request to an NDIS // driver. The caller specifes the request code (OID), a buffer and // a length. This routine allocates a request structure, fills it in, & // submits the request. // // If the call is non-blocking, any memory allocated is deallocated // in ARPRequestComplete. Also as this callback is shared by both // DoNDISRequest blocking and non-blocking, we suffix the request // with a ULONG that tells ARPRequestComplete if this request is a // blocking request or not. If the request is non blocking, then the // ARPRequestComplete reclaims the memory allocated on the heap // // Important: // Allocate Info, which points to the Information Buffer passed to // NdisRequest, on the HEAP, if this request does not block. This // memory is automatically deallocated by ARPRequestComplete // // If the call is blocking, the request memory can be allocated on the // STACK. When we complete the request, the request on the stack // will automatically get unwound. // // Entry: // Adapter - A pointer to the ARPInterface adapter structure. // Request - Type of request to be done (Set or Query) // OID - Value to be set/queried. // Info - A pointer to the info buffer // Length - Length of data in the buffer // Needed - On return, filled in with bytes needed in buffer // Blocking - Whether NdisRequest is completed synchronously // // Exit: // Status - BLOCKING req - SUCCESS or some NDIS error code // NON-BLOCKING - SUCCESS, PENDING or some error // NDIS_STATUS DoNDISRequest(ARPInterface * Adapter, NDIS_REQUEST_TYPE RT, NDIS_OID OID, VOID * Info, UINT Length, UINT * Needed, BOOLEAN Blocking) { RequestBlock *pReqBlock; NDIS_STATUS Status; DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_REQUEST, (DTEXT("+DoNDISRequest(%x, %x, %x, %x, %d, %x, %x\n"), Adapter, RT, OID, Info, Length, Needed, Blocking)); if ((Adapter->ai_adminstate == INTERFACE_DOWN) || (Adapter->ai_handle == NULL)) { return NDIS_STATUS_ADAPTER_NOT_READY; } // Both blocking and non-blocking requests are allocated from NPP. The // blocking case is to protect against wait failure. pReqBlock = CTEAllocMemN(sizeof(RequestBlock), 'NiCT'); if (pReqBlock == NULL) { return NDIS_STATUS_RESOURCES; } if (Blocking) { // Initialize the structure to block on CTEInitBlockStruc(&pReqBlock->Block); // Reference count is initialize to two. One for the completion in // ARPRequestComplete and one for when the CTEBlock completes. // N.B. This ensures that we don't touch freed memory if // the CTEBlock fails on Windows ME. pReqBlock->RefCount = 2; DEBUGMSG(DBG_INFO && DBG_ARP && DBG_REQUEST, (DTEXT("DoNDISRequset block: pReqBlock %x OID %x\n"), pReqBlock, OID)); } else { DEBUGMSG(DBG_INFO && DBG_ARP && DBG_REQUEST, (DTEXT("DoNDISRequest async: pReqBlock %x OID %x\n"), pReqBlock, OID)); } // Now fill the request's info buffer (same for BLOCKING & NON-BLOCKING) pReqBlock->Block.cbs_status = NDIS_STATUS_SUCCESS; pReqBlock->Request.RequestType = RT; if (RT == NdisRequestSetInformation) { pReqBlock->Request.DATA.SET_INFORMATION.Oid = OID; pReqBlock->Request.DATA.SET_INFORMATION.InformationBuffer = Info; pReqBlock->Request.DATA.SET_INFORMATION.InformationBufferLength = Length; } else { pReqBlock->Request.DATA.QUERY_INFORMATION.Oid = OID; pReqBlock->Request.DATA.QUERY_INFORMATION.InformationBuffer = Info; pReqBlock->Request.DATA.QUERY_INFORMATION.InformationBufferLength = Length; } pReqBlock->Blocking = Blocking; // Submit the request. if (Adapter->ai_handle != NULL) { #if MILLEN // On Millennium, the AOL adapter returns with registers trashed. // We will work around by saving and restoring registers. // _asm { push esi push edi push ebx } #endif // MILLEN NdisRequest(&Status, Adapter->ai_handle, &pReqBlock->Request); #if MILLEN _asm { pop ebx pop edi pop esi } #endif // MILLEN } else { Status = NDIS_STATUS_FAILURE; } if (Blocking) { if (Status == NDIS_STATUS_PENDING) { CTEBlockTracker Tracker; Status = (NDIS_STATUS) CTEBlockWithTracker(&pReqBlock->Block, &Tracker, Adapter); #if MILLEN // If Status == -1, it means the wait failed -- due to system reasons. // Put in a reasonable failure. if (Status == -1) { Status = NDIS_STATUS_FAILURE; } #endif // MILLEN } else { // Since we aren't blocking, remove refcount for ARPRequestComplete. InterlockedDecrement( (PLONG) &pReqBlock->RefCount); } if (Needed != NULL) *Needed = pReqBlock->Request.DATA.QUERY_INFORMATION.BytesNeeded; if (InterlockedDecrement( (PLONG) &pReqBlock->RefCount) == 0) { CTEFreeMem(pReqBlock); } } else { if (Status != NDIS_STATUS_PENDING) { if (Needed != NULL) *Needed = pReqBlock->Request.DATA.QUERY_INFORMATION.BytesNeeded; ARPRequestComplete(Adapter->ai_handle, &pReqBlock->Request, Status); } } DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_REQUEST, (DTEXT("-DoNDISRequest [%x]\n"), Status)); return Status; } //* FreeARPBuffer - Free a header and buffer descriptor pair. // // Called when we're done with a buffer. We'll free the buffer and the // buffer descriptor pack to the interface. // // Entry: Interface - Interface buffer/bd came frome. // Buffer - NDIS_BUFFER to be freed. // // Returns: Nothing. // __inline VOID FreeARPBuffer(ARPInterface *Interface, PNDIS_BUFFER Buffer) { UNREFERENCED_PARAMETER(Interface); MdpFree(Buffer); } //* GetARPBuffer - Get a buffer and descriptor // // Returns a pointer to an NDIS_BUFFER and a pointer to a buffer // of the specified size. // // Entry: Interface - Pointer to ARPInterface structure to allocate buffer from. // BufPtr - Pointer to where to return buf address. // Size - Size in bytes of buffer needed. // // Returns: Pointer to NDIS_BUFFER if successfull, NULL if not // PNDIS_BUFFER GetARPBufferAtDpcLevel(ARPInterface *Interface, uchar **BufPtr, uchar Size) { PNDIS_BUFFER Mdl = NULL; UNREFERENCED_PARAMETER(Interface); #if DBG *BufPtr = NULL; #endif UNREFERENCED_PARAMETER(Interface); if (Size <= BUFSIZE_ENET_HEADER_POOL) { Mdl = MdpAllocateAtDpcLevel(ArpEnetHeaderPool, BufPtr); } else if (Size <= BUFSIZE_AUX_HEADER_POOL) { Mdl = MdpAllocateAtDpcLevel(ArpAuxHeaderPool, BufPtr); } if (Mdl) { NdisAdjustBufferLength(Mdl, Size); } return Mdl; } #if MILLEN #define GetARPBuffer GetARPBufferAtDpcLevel #else __inline PNDIS_BUFFER GetARPBuffer(ARPInterface *Interface, uchar **BufPtr, uchar Size) { KIRQL OldIrql; PNDIS_BUFFER Mdl; OldIrql = KeRaiseIrqlToDpcLevel(); Mdl = GetARPBufferAtDpcLevel(Interface, BufPtr, Size); KeLowerIrql(OldIrql); return Mdl; } #endif //* BitSwap - Bit swap two strings. // // A routine to bitswap two strings. // // Input: Dest - Destination of swap. // Src - Src string to be swapped. // Length - Length in bytes to swap. // // Returns: Nothing. // void BitSwap(uchar * Dest, uchar * Src, uint Length) { uint i; uchar Temp, TempSrc; for (i = 0; i < Length; i++, Dest++, Src++) { TempSrc = *Src; Temp = SwapTableLo[TempSrc >> 4] | SwapTableHi[TempSrc & 0x0f]; *Dest = Temp; } } //* SendARPPacket - Build a header, and send a packet. // // A utility routine to build and ARP header and send a packet. We assume // the media specific header has been built. // // Entry: Interface - Interface for NDIS drive. // Packet - Pointer to packet to be sent // Header - Pointer to header to fill in. // Opcode - Opcode for packet. // Address - Source HW address. // SrcAddr - Address to use as our source h/w address. // Destination - Destination IP address. // Src - Source IP address. // HWType - Hardware type. // CheckIF - TRUE iff we are to check the I/F status before // sending. // // Returns: NDIS_STATUS of send. // NDIS_STATUS SendARPPacket(ARPInterface * Interface, PNDIS_PACKET Packet, ARPHeader * Header, ushort Opcode, uchar * Address, uchar * SrcAddr, IPAddr Destination, IPAddr Src, ushort HWType, uint CheckIF) { NDIS_STATUS Status; PNDIS_BUFFER Buffer; uint PacketDone; uchar *AddrPtr; ulong Proc; Header->ah_hw = HWType; Header->ah_pro = net_short(ARP_ETYPE_IP); Header->ah_hlen = Interface->ai_addrlen; Header->ah_plen = sizeof(IPAddr); Header->ah_opcode = Opcode; AddrPtr = Header->ah_shaddr; if (SrcAddr == NULL) SrcAddr = Interface->ai_addr; RtlCopyMemory(AddrPtr, SrcAddr, Interface->ai_addrlen); AddrPtr += Interface->ai_addrlen; *(IPAddr UNALIGNED *) AddrPtr = Src; AddrPtr += sizeof(IPAddr); if (Address != (uchar *) NULL) RtlCopyMemory(AddrPtr, Address, Interface->ai_addrlen); else RtlZeroMemory(AddrPtr, Interface->ai_addrlen); AddrPtr += Interface->ai_addrlen; *(IPAddr UNALIGNED *) AddrPtr = Destination; PacketDone = FALSE; if (!CheckIF || (Interface->ai_operstatus == INTERFACE_UP)) { Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen++; NdisSend(&Status, Interface->ai_handle, Packet); if (Status != NDIS_STATUS_PENDING) { PacketDone = TRUE; Interface->ai_qlen[Proc].ai_qlen--; if (Status == NDIS_STATUS_SUCCESS) Interface->ai_outoctets += Packet->Private.TotalLength; else { if (Status == NDIS_STATUS_RESOURCES) Interface->ai_outdiscards++; else Interface->ai_outerrors++; } } } else { PacketDone = TRUE; Status = NDIS_STATUS_ADAPTER_NOT_READY; } if (PacketDone) { NdisUnchainBufferAtFront(Packet, &Buffer); FreeARPBuffer(Interface, Buffer); NdisFreePacket(Packet); } return Status; } //* SendARPRequest - Send an ARP packet // // Called when we need to ARP an IP address, or respond to a request. We'll send out // the packet, and the receiving routines will process the response. // // Entry: Interface - Interface to send the request on. // Destination - The IP address to be ARPed. // Type - Either RESOLVING_GLOBAL or RESOLVING_LOCAL // SrcAddr - NULL if we're sending from ourselves, the value // to use otherwise. // CheckIF - Flag passed through to SendARPPacket(). // // Returns: Status of attempt to send ARP request. // NDIS_STATUS SendARPRequest(ARPInterface * Interface, IPAddr Destination, uchar Type, uchar * SrcAddr, uint CheckIF) { uchar *MHeader; // Pointer to media header. PNDIS_BUFFER Buffer; // NDIS buffer descriptor. uchar MHeaderSize; // Size of media header. const uchar *MAddr; // Pointer to media address structure. uint SAddrOffset; // Offset into media address of source address. uchar SRFlag = 0; // Source routing flag. uchar SNAPLength = 0; const uchar *SNAPAddr; // Address of SNAP header. PNDIS_PACKET Packet; // Packet for sending. NDIS_STATUS Status; ushort HWType; IPAddr Src; CTELockHandle Handle; ARPIPAddr *Addr; // First, get a source address we can use. CTEGetLock(&Interface->ai_lock, &Handle); Addr = &Interface->ai_ipaddr; Src = NULL_IP_ADDR; do { if (!IP_ADDR_EQUAL(Addr->aia_addr, NULL_IP_ADDR)) { // // This is a valid address. See if it is the same as the // target address - i.e. arp'ing for ourselves. If it is, // we want to use that as our source address. // if (IP_ADDR_EQUAL(Addr->aia_addr, Destination)) { Src = Addr->aia_addr; break; } // See if the target is on this subnet. if (IP_ADDR_EQUAL( Addr->aia_addr & Addr->aia_mask, Destination & Addr->aia_mask )) { // // See if we've already found a suitable candidate on the // same subnet. If we haven't, we'll use this one. // if (!IP_ADDR_EQUAL( Addr->aia_addr & Addr->aia_mask, Src & Addr->aia_mask )) { Src = Addr->aia_addr; } } else { // He's not on our subnet. If we haven't already found a valid // address save this one in case we don't find a match for the // subnet. if (IP_ADDR_EQUAL(Src, NULL_IP_ADDR)) { Src = Addr->aia_addr; } } } Addr = Addr->aia_next; } while (Addr != NULL); CTEFreeLock(&Interface->ai_lock, Handle); // If we didn't find a source address, give up. if (IP_ADDR_EQUAL(Src, NULL_IP_ADDR)) return NDIS_STATUS_SUCCESS; NdisAllocatePacket(&Status, &Packet, Interface->ai_ppool); if (Status != NDIS_STATUS_SUCCESS) { Interface->ai_outdiscards++; return Status; } ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_owner = PACKET_OWNER_LINK; (Interface->ai_outpcount[AI_NONUCAST_INDEX])++; // Figure out what type of media this is, and do the appropriate thing. switch (Interface->ai_media) { case NdisMedium802_3: MHeaderSize = ARP_MAX_MEDIA_ENET; MAddr = ENetBcst; if (Interface->ai_snapsize == 0) { SNAPAddr = (uchar *) NULL; HWType = net_short(ARP_HW_ENET); } else { SNAPLength = sizeof(SNAPHeader); SNAPAddr = ARPSNAP; HWType = net_short(ARP_HW_802); } SAddrOffset = offsetof(struct ENetHeader, eh_saddr); break; case NdisMedium802_5: // Token ring. We have logic for dealing with the second transmit // of an arp request. MAddr = TRBcst; SAddrOffset = offsetof(struct TRHeader, tr_saddr); SNAPLength = sizeof(SNAPHeader); SNAPAddr = ARPSNAP; MHeaderSize = sizeof(TRHeader); HWType = net_short(ARP_HW_802); if (Type == ARP_RESOLVING_GLOBAL) { MHeaderSize += sizeof(RC); SRFlag = TR_RII; } break; case NdisMediumFddi: MHeaderSize = sizeof(FDDIHeader); MAddr = FDDIBcst; SNAPAddr = ARPSNAP; SNAPLength = sizeof(SNAPHeader); SAddrOffset = offsetof(struct FDDIHeader, fh_saddr); HWType = net_short(ARP_HW_ENET); break; case NdisMediumArcnet878_2: MHeaderSize = ARP_MAX_MEDIA_ARC; MAddr = ARCBcst; SNAPAddr = (uchar *) NULL; SAddrOffset = offsetof(struct ARCNetHeader, ah_saddr); HWType = net_short(ARP_HW_ARCNET); break; default: ASSERT(0); Interface->ai_outerrors++; return NDIS_STATUS_UNSUPPORTED_MEDIA; } if ((Buffer = GetARPBuffer(Interface, &MHeader, (uchar) (sizeof(ARPHeader) + MHeaderSize + SNAPLength))) == (PNDIS_BUFFER) NULL) { NdisFreePacket(Packet); Interface->ai_outdiscards++; return NDIS_STATUS_RESOURCES; } if (Interface->ai_media == NdisMediumArcnet878_2) { NdisAdjustBufferLength(Buffer, NdisBufferLength(Buffer) - ARCNET_ARPHEADER_ADJUSTMENT); } // Copy broadcast address into packet. RtlCopyMemory(MHeader, MAddr, MHeaderSize); // Fill in source address. if (SrcAddr == NULL) { SrcAddr = Interface->ai_addr; } if (Interface->ai_media == NdisMedium802_3 && Interface->ai_snapsize != 0) { ENetHeader *Hdr = (ENetHeader *) MHeader; // Using SNAP on ethernet. Adjust the etype to a length. Hdr->eh_type = net_short(sizeof(ARPHeader) + sizeof(SNAPHeader)); } RtlCopyMemory(&MHeader[SAddrOffset], SrcAddr, Interface->ai_addrlen); if ((Interface->ai_media == NdisMedium802_5) && (Type == ARP_RESOLVING_GLOBAL)) { // Turn on source routing. MHeader[SAddrOffset] |= SRFlag; MHeader[SAddrOffset + Interface->ai_addrlen] |= TrRii; } // Copy in SNAP header, if any. RtlCopyMemory(&MHeader[MHeaderSize], SNAPAddr, SNAPLength); // Media header is filled in. Now do ARP packet itself. NdisChainBufferAtFront(Packet, Buffer); return SendARPPacket(Interface, Packet, (ARPHeader *) & MHeader[MHeaderSize + SNAPLength], net_short(ARP_REQUEST), (uchar *) NULL, SrcAddr, Destination, Src, HWType, CheckIF); } //* SendARPReply - Reply to an ARP request. // // Called by our receive packet handler when we need to reply. We build a packet // and buffer and call SendARPPacket to send it. // // Entry: Interface - Pointer to interface to reply on. // Destination - IPAddress to reply to. // Src - Source address to reply from. // HWAddress - Hardware address to reply to. // SourceRoute - Source Routing information, if any. // SourceRouteSize - Size in bytes of soure routing. // UseSNAP - Whether or not to use SNAP for this reply. // // Returns: Nothing. // void SendARPReply(ARPInterface * Interface, IPAddr Destination, IPAddr Src, uchar * HWAddress, RC UNALIGNED * SourceRoute, uint SourceRouteSize, uint UseSNAP) { PNDIS_PACKET Packet; // Buffer and packet to be used. PNDIS_BUFFER Buffer; uchar *Header; // Pointer to media header. NDIS_STATUS Status; uchar Size = 0; // Size of media header buffer. ushort HWType; ENetHeader *EH; FDDIHeader *FH; ARCNetHeader *AH; TRHeader *TRH; // Allocate a packet for this. NdisAllocatePacket(&Status, &Packet, Interface->ai_ppool); if (Status != NDIS_STATUS_SUCCESS) { Interface->ai_outdiscards++; return; } ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_owner = PACKET_OWNER_LINK; (Interface->ai_outpcount[AI_UCAST_INDEX])++; Size = Interface->ai_hdrsize; if (UseSNAP) Size = Size + (uchar) Interface->ai_snapsize; if (Interface->ai_media == NdisMedium802_5) Size = Size + (uchar) SourceRouteSize; if ((Buffer = GetARPBuffer(Interface, &Header, (uchar) (Size + sizeof(ARPHeader)))) == (PNDIS_BUFFER) NULL) { Interface->ai_outdiscards++; NdisFreePacket(Packet); return; } // Decide how to build the header based on the media type. switch (Interface->ai_media) { case NdisMedium802_3: EH = (ENetHeader *) Header; RtlCopyMemory(EH->eh_daddr, HWAddress, ARP_802_ADDR_LENGTH); RtlCopyMemory(EH->eh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); if (!UseSNAP) { EH->eh_type = net_short(ARP_ETYPE_ARP); HWType = net_short(ARP_HW_ENET); } else { // Using SNAP on ethernet. EH->eh_type = net_short(sizeof(ARPHeader) + sizeof(SNAPHeader)); HWType = net_short(ARP_HW_802); RtlCopyMemory(Header + sizeof(ENetHeader), ARPSNAP, sizeof(SNAPHeader)); } break; case NdisMedium802_5: TRH = (TRHeader *) Header; TRH->tr_ac = ARP_AC; TRH->tr_fc = ARP_FC; RtlCopyMemory(TRH->tr_daddr, HWAddress, ARP_802_ADDR_LENGTH); RtlCopyMemory(TRH->tr_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); if (SourceRouteSize) { // If we have source route info, deal with // it. RtlCopyMemory(Header + sizeof(TRHeader), SourceRoute, SourceRouteSize); // Convert to directed response. ((RC *) & Header[sizeof(TRHeader)])->rc_blen &= RC_LENMASK; ((RC *) & Header[sizeof(TRHeader)])->rc_dlf ^= RC_DIR; TRH->tr_saddr[0] |= TR_RII; } RtlCopyMemory(Header + sizeof(TRHeader) + SourceRouteSize, ARPSNAP, sizeof(SNAPHeader)); HWType = net_short(ARP_HW_802); break; case NdisMediumFddi: FH = (FDDIHeader *) Header; FH->fh_pri = ARP_FDDI_PRI; RtlCopyMemory(FH->fh_daddr, HWAddress, ARP_802_ADDR_LENGTH); RtlCopyMemory(FH->fh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); RtlCopyMemory(Header + sizeof(FDDIHeader), ARPSNAP, sizeof(SNAPHeader)); HWType = net_short(ARP_HW_ENET); break; case NdisMediumArcnet878_2: AH = (ARCNetHeader *) Header; AH->ah_saddr = Interface->ai_addr[0]; AH->ah_daddr = *HWAddress; AH->ah_prot = ARP_ARCPROT_ARP; NdisAdjustBufferLength(Buffer, NdisBufferLength(Buffer) - ARCNET_ARPHEADER_ADJUSTMENT); HWType = net_short(ARP_HW_ARCNET); break; default: ASSERT(0); Interface->ai_outerrors++; FreeARPBuffer(Interface, Buffer); NdisFreePacket(Packet); return; } NdisChainBufferAtFront(Packet, Buffer); SendARPPacket(Interface, Packet, (ARPHeader *) (Header + Size), net_short(ARP_RESPONSE), HWAddress, NULL, Destination, Src, HWType, TRUE); } //* ARPRemoveRCE - Remove an RCE from the ATE list. // // This funtion removes a specified RCE from a given ATE. It assumes the ate_lock // is held by the caller. // // Entry: ATE - ATE from which RCE is to be removed. // RCE - RCE to be removed. // // Returns: Nothing // void ARPRemoveRCE(ARPTableEntry * ATE, RouteCacheEntry * RCE) { ARPContext *CurrentAC; // Current ARP Context being checked. #if DBG uint Found = FALSE; #endif CurrentAC = (ARPContext *) (((char *)&ATE->ate_rce) - offsetof(struct ARPContext, ac_next)); while (CurrentAC->ac_next != (RouteCacheEntry *) NULL) if (CurrentAC->ac_next == RCE) { ARPContext *DummyAC = (ARPContext *) RCE->rce_context; CurrentAC->ac_next = DummyAC->ac_next; DummyAC->ac_ate = (ARPTableEntry *) NULL; DummyAC->ac_next = NULL; #if DBG Found = TRUE; #endif break; } else CurrentAC = (ARPContext *) CurrentAC->ac_next->rce_context; ASSERT(Found); } //* ARPLookup - Look up an entry in the ARP table. // // Called to look up an entry in an interface's ARP table. If we find it, we'll // lock the entry and return a pointer to it, otherwise we return NULL. We // assume that the caller has the ARP table locked when we are called. // // The ARP table entry is structured as a hash table of pointers to // ARPTableEntrys.After hashing on the IP address, a linear search is done to // lookup the entry. // // If we find the entry, we lock it for the caller. If we don't find // the entry, we leave the ARP table locked so that the caller may atomically // insert a new entry without worrying about a duplicate being inserted between // the time the table was checked and the time the caller went to insert the // entry. // // Entry: Interface - The interface to be searched upon. // Address - The IP address we're looking up. // // Returns: Pointer to ARPTableEntry if found, or NULL if not. // ARPTableEntry * ARPLookup(ARPInterface * Interface, IPAddr Address) { int i = ARP_HASH(Address); // Index into hash table. ARPTableEntry *Current; // Current ARP Table entry being // examined. Current = (*Interface->ai_ARPTbl)[i]; while (Current != (ARPTableEntry *) NULL) { CTEGetLockAtDPC(&Current->ate_lock); if (IP_ADDR_EQUAL(Current->ate_dest, Address)) { // Found a match. return Current; } CTEFreeLockFromDPC(&Current->ate_lock); Current = Current->ate_next; } // If we got here, we didn't find the entry. Leave the table locked and // return the handle. return(ARPTableEntry *) NULL; } //* IsBCastOnIF- See it an address is a broadcast address on an interface. // // Called to see if a particular address is a broadcast address on an // interface. We'll check the global, net, and subnet broadcasts. We assume // the caller holds the lock on the interface. // // Entry: Interface - Interface to check. // Addr - Address to check. // // Returns: TRUE if it it a broadcast, FALSE otherwise. // uint IsBCastOnIF(ARPInterface * Interface, IPAddr Addr) { IPAddr BCast; IPMask Mask; ARPIPAddr *ARPAddr; IPAddr LocalAddr; // First get the interface broadcast address. BCast = Interface->ai_bcast; // First check for global broadcast. if (IP_ADDR_EQUAL(BCast, Addr) || CLASSD_ADDR(Addr)) return TRUE; // Now walk the local addresses, and check for net/subnet bcast on each // one. ARPAddr = &Interface->ai_ipaddr; do { // See if this one is valid. LocalAddr = ARPAddr->aia_addr; if (!IP_ADDR_EQUAL(LocalAddr, NULL_IP_ADDR)) { // He's valid. Mask = ARPAddr->aia_mask; // First check for subnet bcast. if (IP_ADDR_EQUAL((LocalAddr & Mask) | (BCast & ~Mask), Addr)) return TRUE; // Now check all nets broadcast. Mask = IPNetMask(LocalAddr); if (IP_ADDR_EQUAL((LocalAddr & Mask) | (BCast & ~Mask), Addr)) return TRUE; } ARPAddr = ARPAddr->aia_next; } while (ARPAddr != NULL); // If we're here, it's not a broadcast. return FALSE; } //* ARPSendBCast - See if this is a bcast or mcast frame, and send it. // // Called when we have a packet to send and we want to see if it's a broadcast // or multicast frame on this interface. We'll search the local addresses and // see if we can determine if it is. If it is, we'll send it here. Otherwise // we return FALSE, and the caller will try to resolve the address. // // Entry: Interface - A pointer to an AI structure. // Dest - Destination of datagram. // Packet - Packet to be sent. // Status - Place to return status of send attempt. // // Returns: TRUE if is was a bcast or mcast send, FALSE otherwise. // uint ARPSendBCast(ARPInterface * Interface, IPAddr Dest, PNDIS_PACKET Packet, PNDIS_STATUS Status) { uint IsBCast; CTELockHandle Handle; PNDIS_BUFFER ARPBuffer; // ARP Header buffer. uchar *BufAddr; // Address of NDIS buffer NDIS_STATUS MyStatus; ENetHeader *Hdr; FDDIHeader *FHdr; TRHeader *TRHdr; SNAPHeader UNALIGNED *SNAPPtr; RC UNALIGNED *RCPtr; ARCNetHeader *AHdr; uint DataLength; ulong Proc; // Get the lock, and see if it's a broadcast. CTEGetLock(&Interface->ai_lock, &Handle); IsBCast = IsBCastOnIF(Interface, Dest); CTEFreeLock(&Interface->ai_lock, Handle); if (IsBCast) { if (Interface->ai_operstatus == INTERFACE_UP) { uchar Size; Size = Interface->ai_hdrsize + Interface->ai_snapsize; if (Interface->ai_media == NdisMedium802_5) Size += sizeof(RC); ARPBuffer = GetARPBuffer(Interface, &BufAddr, Size); if (ARPBuffer != NULL) { uint UNALIGNED *Temp; // Got the buffer we need. switch (Interface->ai_media) { case NdisMedium802_3: Hdr = (ENetHeader *) BufAddr; if (!CLASSD_ADDR(Dest)) RtlCopyMemory(Hdr, ENetBcst, ARP_802_ADDR_LENGTH); else { RtlCopyMemory(Hdr, ENetMcst, ARP_802_ADDR_LENGTH); Temp = (uint UNALIGNED *) & Hdr->eh_daddr[2]; *Temp |= (Dest & ARP_MCAST_MASK); } RtlCopyMemory(Hdr->eh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); if (Interface->ai_snapsize == 0) { // No snap on this interface, so just use ETypr. Hdr->eh_type = net_short(ARP_ETYPE_IP); } else { ushort ShortDataLength; // We're using SNAP. Find the size of the packet. NdisQueryPacket(Packet, NULL, NULL, NULL, &DataLength); ShortDataLength = (ushort) (DataLength + sizeof(SNAPHeader)); Hdr->eh_type = net_short(ShortDataLength); SNAPPtr = (SNAPHeader UNALIGNED *) (BufAddr + sizeof(ENetHeader)); RtlCopyMemory(SNAPPtr, ARPSNAP, sizeof(SNAPHeader)); SNAPPtr->sh_etype = net_short(ARP_ETYPE_IP); } break; case NdisMedium802_5: // This is token ring. We'll have to mess around with // source routing. // for multicast - see RFC 1469. // Handle RFC 1469. if (!CLASSD_ADDR(Dest) || (!TRFunctionalMcast)) { TRHdr = (TRHeader *) BufAddr; RtlCopyMemory(TRHdr, TRBcst, offsetof(TRHeader, tr_saddr)); RtlCopyMemory(TRHdr->tr_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); } else { TRHdr = (TRHeader *) BufAddr; RtlCopyMemory(TRHdr, TRMcst, offsetof(TRHeader, tr_saddr)); RtlCopyMemory(TRHdr->tr_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); } if (sIPAlwaysSourceRoute) { TRHdr->tr_saddr[0] |= TR_RII; RCPtr = (RC UNALIGNED *) ((uchar *) TRHdr + sizeof(TRHeader)); RCPtr->rc_blen = TrRii | RC_LEN; RCPtr->rc_dlf = RC_BCST_LEN; SNAPPtr = (SNAPHeader UNALIGNED *) ((uchar *) RCPtr + sizeof(RC)); } else { // // Adjust the size of the buffer to account for the // fact that we don't have the RC field. // NdisAdjustBufferLength(ARPBuffer, (Size - sizeof(RC))); SNAPPtr = (SNAPHeader UNALIGNED *) ((uchar *) TRHdr + sizeof(TRHeader)); } RtlCopyMemory(SNAPPtr, ARPSNAP, sizeof(SNAPHeader)); SNAPPtr->sh_etype = net_short(ARP_ETYPE_IP); break; case NdisMediumFddi: FHdr = (FDDIHeader *) BufAddr; if (!CLASSD_ADDR(Dest)) RtlCopyMemory(FHdr, FDDIBcst, offsetof(FDDIHeader, fh_saddr)); else { RtlCopyMemory(FHdr, FDDIMcst, offsetof(FDDIHeader, fh_saddr)); Temp = (uint UNALIGNED *) & FHdr->fh_daddr[2]; *Temp |= (Dest & ARP_MCAST_MASK); } RtlCopyMemory(FHdr->fh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); SNAPPtr = (SNAPHeader UNALIGNED *) (BufAddr + sizeof(FDDIHeader)); RtlCopyMemory(SNAPPtr, ARPSNAP, sizeof(SNAPHeader)); SNAPPtr->sh_etype = net_short(ARP_ETYPE_IP); break; case NdisMediumArcnet878_2: AHdr = (ARCNetHeader *) BufAddr; AHdr->ah_saddr = Interface->ai_addr[0]; AHdr->ah_daddr = 0; AHdr->ah_prot = ARP_ARCPROT_IP; break; default: ASSERT(0); *Status = NDIS_STATUS_UNSUPPORTED_MEDIA; FreeARPBuffer(Interface, ARPBuffer); return FALSE; } (Interface->ai_outpcount[AI_NONUCAST_INDEX])++; Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen++; NdisChainBufferAtFront(Packet, ARPBuffer); NdisSend(&MyStatus, Interface->ai_handle, Packet); *Status = MyStatus; if (MyStatus != NDIS_STATUS_PENDING) { // Send finished // immediately. if (MyStatus == NDIS_STATUS_SUCCESS) { Interface->ai_outoctets += Packet->Private.TotalLength; } else { if (MyStatus == NDIS_STATUS_RESOURCES) Interface->ai_outdiscards++; else Interface->ai_outerrors++; } Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen--; NdisUnchainBufferAtFront(Packet, &ARPBuffer); FreeARPBuffer(Interface, ARPBuffer); } } else *Status = NDIS_STATUS_RESOURCES; } else *Status = NDIS_STATUS_ADAPTER_NOT_READY; return TRUE; } else return FALSE; } //* ARPResolveIP - resolves IP address // // Called by IP layer when it needs to find physical address of the host // given the interface and dest IP address // Entry: Interface - A pointer to the AI structure. // ArpControlBlock - A pointer to the BufDesc chain to be sent. // // Returns: Status. // NDIS_STATUS ARPResolveIP(void *Context, IPAddr Destination, void *ArpControlBlock) { ARPInterface *ai = (ARPInterface *) Context; // Set up as AI pointer. ARPControlBlock *ArpContB = (ARPControlBlock *) ArpControlBlock; ARPTableEntry *entry; // Pointer to ARP tbl. entry CTELockHandle Handle; // Lock handle NDIS_STATUS Status; uchar ate_state; CTEGetLock(&ai->ai_ARPTblLock, &Handle); // Check if we already got the mapping. if ((entry = ARPLookup(ai, Destination)) != NULL) { // Found a matching entry. ARPLookup returns with the ATE lock held. if (entry->ate_state != ARP_GOOD) { Status = NDIS_STATUS_FAILURE; } else { Status = FillARPControlBlock(ai, entry, ArpContB); } CTEFreeLockFromDPC(&entry->ate_lock); CTEFreeLock(&ai->ai_ARPTblLock, Handle); return Status; } // We need to send arp request. CTEFreeLock(&ai->ai_ARPTblLock, Handle); entry = CreateARPTableEntry(ai, Destination, &Handle, ArpContB); if (entry != NULL) { if (entry->ate_state <= ARP_RESOLVING) { // Newly created entry. // Someone else could have raced in and created the entry between // the time we free the lock and the time we called // CreateARPTableEntry(). We check this by looking at the packet // on the entry. If there is no old packet we'll ARP. If there is, // we'll call ARPSendData to figure out what to do. if (entry->ate_packet == NULL) { ate_state = entry->ate_state; CTEFreeLock(&entry->ate_lock, Handle); SendARPRequest(ai, Destination, ate_state, NULL, TRUE); // We don't know the state of the entry - we've freed the lock // and yielded, and it could conceivably have timed out by now, // or SendARPRequest could have failed, etc. We could take the // lock, check the status from SendARPRequest, see if it's // still the same packet, and then make a decision on the // return value, but it's easiest just to return pending. If // SendARPRequest failed, the entry will time out anyway. return NDIS_STATUS_PENDING; } else { CTEFreeLock(&entry->ate_lock, Handle); return NDIS_STATUS_PENDING; } } else if (entry->ate_state == ARP_GOOD) { // Yow! A valid entry. Status = FillARPControlBlock(ai, entry, ArpContB); //remove ArpContB from ate_resolveonly queue. if (entry->ate_resolveonly) { ARPControlBlock *TmpArpContB, *PrvArpContB = NULL; TmpArpContB = entry->ate_resolveonly; while (TmpArpContB && (ArpContB != TmpArpContB)) { PrvArpContB = TmpArpContB; TmpArpContB = TmpArpContB->next; } if (TmpArpContB == ArpContB) { if (PrvArpContB) { PrvArpContB->next = ArpContB->next; } else { entry->ate_resolveonly = NULL; } } } CTEFreeLock(&entry->ate_lock, Handle); return Status; } else { // An invalid entry! CTEFreeLock(&entry->ate_lock, Handle); return NDIS_STATUS_RESOURCES; } } else { // Couldn't create an entry. return NDIS_STATUS_RESOURCES; } } //* ARPSendData - Send a frame to a specific destination address. // // Called when we need to send a frame to a particular address, after the // ATE has been looked up. We take in an ATE and a packet, validate the state of the // ATE, and either send or ARP for the address if it's not done resolving. We assume // the lock on the ATE is held where we're called, and we'll free it before returning. // // Entry: Interface - A pointer to the AI structure. // Packet - A pointer to the BufDesc chain to be sent. // entry - A pointer to the ATE for the send. // lhandle - Pointer to a lock handle for the ATE. // // Returns: Status of the transmit - success, an error, or pending. // NDIS_STATUS ARPSendData(ARPInterface * Interface, PNDIS_PACKET Packet, ARPTableEntry * entry, CTELockHandle lhandle) { PNDIS_BUFFER ARPBuffer = NULL; // ARP Header buffer. uchar *BufAddr = NULL; // Address of NDIS buffer NDIS_STATUS Status; // Status of send. ulong Proc; #if BACK_FILL PMDL TmpMdl = NULL; #endif if (Interface->ai_operstatus == INTERFACE_UP) { if (entry->ate_state == ARP_GOOD) { // Entry is valid entry->ate_useticks = ArpCacheLife; #if BACK_FILL if (Interface->ai_media == NdisMedium802_3) { NdisQueryPacket(Packet, NULL, NULL, &TmpMdl, NULL); if (TmpMdl->MdlFlags & MDL_NETWORK_HEADER) { TmpMdl->MappedSystemVa = (PVOID) (((ULONG_PTR) TmpMdl->MappedSystemVa) - entry->ate_addrlength); TmpMdl->ByteOffset -= entry->ate_addrlength; TmpMdl->ByteCount += entry->ate_addrlength; ARPBuffer = (PNDIS_BUFFER) TmpMdl; BufAddr = TmpMdl->MappedSystemVa; } else { TmpMdl = NULL; } } if (ARPBuffer == (PNDIS_BUFFER) NULL) { ARPBuffer = GetARPBufferAtDpcLevel(Interface, &BufAddr, entry->ate_addrlength); } #else ARPBuffer = GetARPBufferAtDpcLevel(Interface, &BufAddr, entry->ate_addrlength); #endif if (ARPBuffer != (PNDIS_BUFFER) NULL) { // Everything's in good shape, copy header and send packet. (Interface->ai_outpcount[AI_UCAST_INDEX])++; Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen++; RtlCopyMemory(BufAddr, entry->ate_addr, entry->ate_addrlength); // If we're on Ethernet, see if we're using SNAP here. if (Interface->ai_media == NdisMedium802_3 && entry->ate_addrlength != sizeof(ENetHeader)) { ENetHeader *Header; uint DataSize; ushort ShortDataSize; // We're apparently using SNAP on Ethernet. Query the // packet for the size, and set the length properly. NdisQueryPacket(Packet, NULL, NULL, NULL, &DataSize); #if BACK_FILL if (!TmpMdl) { ShortDataSize = (ushort) (DataSize + sizeof(SNAPHeader)); } else { ShortDataSize = (ushort) (DataSize - entry->ate_addrlength + sizeof(SNAPHeader)); } #else // BACK_FILL ShortDataSize = (ushort) (DataSize + sizeof(SNAPHeader)); #endif // !BACK_FILL Header = (ENetHeader *) BufAddr; Header->eh_type = net_short(ShortDataSize); // In case backfill is enabled, we need to remember that // a SNAP header was appended to the Ethernet header // so we can restore the correct offsets in the MDL. ((PacketContext*) Packet->ProtocolReserved)->pc_common.pc_flags |= PACKET_FLAG_SNAP; } else ((PacketContext*) Packet->ProtocolReserved)->pc_common.pc_flags &= ~PACKET_FLAG_SNAP; CTEFreeLock(&entry->ate_lock, lhandle); #if BACK_FILL if (TmpMdl == NULL) { NdisChainBufferAtFront(Packet, ARPBuffer); } #else NdisChainBufferAtFront(Packet, ARPBuffer); #endif NdisSend(&Status, Interface->ai_handle, Packet); if (Status != NDIS_STATUS_PENDING) { // Send finished // immediately. if (Status == NDIS_STATUS_SUCCESS) { Interface->ai_outoctets += Packet->Private.TotalLength; } else { if (Status == NDIS_STATUS_RESOURCES) Interface->ai_outdiscards++; else Interface->ai_outerrors++; } Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen--; #if BACK_FILL if (TmpMdl == NULL) { NdisUnchainBufferAtFront(Packet, &ARPBuffer); FreeARPBuffer(Interface, ARPBuffer); } else { uint HdrSize; HdrSize = sizeof(ENetHeader); if (((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_flags & PACKET_FLAG_SNAP) HdrSize += Interface->ai_snapsize; TmpMdl->MappedSystemVa = (PVOID) (((ULONG_PTR) TmpMdl->MappedSystemVa) + HdrSize); TmpMdl->ByteOffset += HdrSize; TmpMdl->ByteCount -= HdrSize; } #else NdisUnchainBufferAtFront(Packet, &ARPBuffer); FreeARPBuffer(Interface, ARPBuffer); #endif } return Status; } else { // No buffer, free lock and return. CTEFreeLock(&entry->ate_lock, lhandle); Interface->ai_outdiscards++; return NDIS_STATUS_RESOURCES; } } // The IP addresses match, but the state of the ARP entry indicates // it's not valid. If the address is marked as resolving, we'll replace // the current cached packet with this one. If it's been more than // ARP_FLOOD_RATE ms. since we last sent an ARP request, we'll send // another one now. if (entry->ate_state <= ARP_RESOLVING) { PNDIS_PACKET OldPacket = entry->ate_packet; ulong Now = CTESystemUpTime(); entry->ate_packet = Packet; if ((Now - entry->ate_valid) > ARP_FLOOD_RATE) { IPAddr Dest = entry->ate_dest; entry->ate_valid = Now; entry->ate_state = ARP_RESOLVING_GLOBAL; // We've done this // at least once. CTEFreeLock(&entry->ate_lock, lhandle); SendARPRequest(Interface, Dest, ARP_RESOLVING_GLOBAL, NULL, TRUE); // Send a request. } else CTEFreeLock(&entry->ate_lock, lhandle); if (OldPacket) IPSendComplete(Interface->ai_context, OldPacket, NDIS_STATUS_SUCCESS); return NDIS_STATUS_PENDING; } else { ASSERT(0); CTEFreeLock(&entry->ate_lock, lhandle); Interface->ai_outerrors++; return NDIS_STATUS_INVALID_PACKET; } } else { // Adapter is down. Just return the error. CTEFreeLock(&entry->ate_lock, lhandle); return NDIS_STATUS_ADAPTER_NOT_READY; } } //* CreateARPTableEntry - Create a new entry in the ARP table. // // A function to put an entry into the ARP table. We allocate memory if we // need to. // // The first thing to do is get the lock on the ARP table, and see if the // entry already exists. If it does, we're done. Otherwise we need to // allocate memory and create a new entry. // // Entry: Interface - Interface for ARP table. // Destination - Destination address to be mapped. // Handle - Pointer to lock handle for entry. // // Returns: Pointer to newly created entry. // ARPTableEntry * CreateARPTableEntry(ARPInterface * Interface, IPAddr Destination, CTELockHandle * Handle, void *UserArp) { ARPTableEntry *NewEntry, *Entry; CTELockHandle TableHandle; int i = ARP_HASH(Destination); int Size; // First look for it, and if we don't find it return try to create one. CTEGetLock(&Interface->ai_ARPTblLock, &TableHandle); if ((Entry = ARPLookup(Interface, Destination)) != NULL) { CTEFreeLockFromDPC(&Interface->ai_ARPTblLock); *Handle = TableHandle; // if we are using arp api entry, turn off the // userarp flag so that handle arp need not free it. if (!UserArp && Entry->ate_userarp) { Entry->ate_userarp = 0; } if (UserArp) { if (Entry->ate_resolveonly) { // chain the current request at the end of the new // before using the new request as the head. // ((ARPControlBlock *)UserArp)->next = Entry->ate_resolveonly; } // link the new request. // Entry->ate_resolveonly = (ARPControlBlock *)UserArp; } return Entry; } // Allocate memory for the entry. If we can't, fail the request. Size = sizeof(ARPTableEntry) - 1 + (Interface->ai_media == NdisMedium802_5 ? ARP_MAX_MEDIA_TR : (Interface->ai_hdrsize + Interface->ai_snapsize)); if ((NewEntry = CTEAllocMemN(Size, 'QiCT')) == (ARPTableEntry *) NULL) { CTEFreeLock(&Interface->ai_ARPTblLock, TableHandle); return (ARPTableEntry *) NULL; } RtlZeroMemory(NewEntry, Size); NewEntry->ate_dest = Destination; if (Interface->ai_media != NdisMedium802_5 || sArpAlwaysSourceRoute) { NewEntry->ate_state = ARP_RESOLVING_GLOBAL; } else { NewEntry->ate_state = ARP_RESOLVING_LOCAL; } if (UserArp) { NewEntry->ate_userarp = 1; } NewEntry->ate_resolveonly = (ARPControlBlock *)UserArp; NewEntry->ate_valid = CTESystemUpTime(); NewEntry->ate_useticks = ArpCacheLife; CTEInitLock(&NewEntry->ate_lock); // Entry does not exist. Insert the new entry into the table at the // appropriate spot. // NewEntry->ate_next = (*Interface->ai_ARPTbl)[i]; (*Interface->ai_ARPTbl)[i] = NewEntry; Interface->ai_count++; CTEGetLockAtDPC(&NewEntry->ate_lock); CTEFreeLockFromDPC(&Interface->ai_ARPTblLock); *Handle = TableHandle; return NewEntry; } //* ARPTransmit - Send a frame. // // The main ARP transmit routine, called by the upper layer. This routine // takes as input a buf desc chain, RCE, and size. We validate the cached // information in the RCE. If it is valid, we use it to send the frame. // Otherwise we do a table lookup. If we find it in the table, we'll update // the RCE and continue. Otherwise we'll queue the packet and start an ARP // resolution. // // Entry: Context - A pointer to the AI structure. // Packet - A pointer to the BufDesc chain to be sent. // Destination - IP address of destination we're trying to reach, // RCE - A pointer to an RCE which may have cached information. // // Returns: Status of the transmit - success, an error, or pending. // NDIS_STATUS __stdcall ARPTransmit(void *Context, PNDIS_PACKET * PacketArray, uint NumberOfPackets, IPAddr Destination, RouteCacheEntry * RCE, void *LinkCtxt) { ARPInterface *ai = (ARPInterface *) Context; // Set up as AI pointer. ARPContext *ac = NULL; // ARP context pointer. ARPTableEntry *entry; // Pointer to ARP tbl. entry CTELockHandle Handle; // Lock handle NDIS_STATUS Status; PNDIS_PACKET Packet = *PacketArray; // // For now, we get only one packet... // DBG_UNREFERENCED_PARAMETER(NumberOfPackets); UNREFERENCED_PARAMETER(LinkCtxt); ASSERT(NumberOfPackets == 1); DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_TX, (DTEXT("+ARPTransmit(%x, %x, %d, %x, %x, %x)\n"), Context, PacketArray, NumberOfPackets, Destination, RCE, LinkCtxt)); if (ai->ai_operstatus != INTERFACE_UP) { return NDIS_STATUS_ADAPTER_NOT_READY; } CTEGetLock(&ai->ai_ARPTblLock, &Handle); if (RCE != (RouteCacheEntry *) NULL) { // Have a valid RCE. ac = (ARPContext *) RCE->rce_context; // Get pointer to context entry = ac->ac_ate; if (entry != (ARPTableEntry *) NULL) { // Have a valid ATE. CTEGetLockAtDPC(&entry->ate_lock); // Lock this structure if (IP_ADDR_EQUAL(entry->ate_dest, Destination)) { uint refresh,status; uchar state = entry->ate_state; refresh= entry->ate_refresh; CTEFreeLockFromDPC(&ai->ai_ARPTblLock); status = ARPSendData(ai, Packet, entry, Handle); // Send the data if (refresh) { if (sArpAlwaysSourceRoute) { // // If Always source route is on, // the state should ve resolving_global // so that SendArpRequest will send SR // header in case of 802.5. // state = ARP_RESOLVING_GLOBAL; } SendARPRequest(ai, Destination, state, NULL, TRUE); } return status; } // We have an RCE that identifies the wrong ATE. We'll free it from // this list and try and find an ATE that is valid. ARPRemoveRCE(entry, RCE); CTEFreeLockFromDPC(&entry->ate_lock); // Fall through to 'no valid entry' code. } } // Here we have no valid ATE, either because the RCE is NULL or the ATE // specified by the RCE was invalid. We'll try and find one in the table. If // we find one, we'll fill in this RCE and send the packet. Otherwise we'll // try to create one. At this point we hold the lock on the ARP table. if ((entry = ARPLookup(ai, Destination)) != (ARPTableEntry *) NULL) { // Found a matching entry. ARPLookup returns with the ATE lock held. if (RCE != (RouteCacheEntry *) NULL) { ac->ac_next = entry->ate_rce; // Fill in context for next time. entry->ate_rce = RCE; ac->ac_ate = entry; } DEBUGMSG(DBG_INFO && DBG_ARP && DBG_TX, (DTEXT("ARPTx: ATE %x - calling ARPSendData\n"), entry)); CTEFreeLockFromDPC(&ai->ai_ARPTblLock); return ARPSendData(ai, Packet, entry, Handle); } // No valid entry in the ARP table. First we'll see if we're sending to a // broadcast address or multicast address. If not, we'll try to create // an entry in the table and get an ARP resolution going. ARPLookup returns // with the table lock held when it fails, we'll free it here. CTEFreeLock(&ai->ai_ARPTblLock, Handle); if (ARPSendBCast(ai, Destination, Packet, &Status)) { return Status; } entry = CreateARPTableEntry(ai, Destination, &Handle, 0); if (entry != NULL) { if (entry->ate_state <= ARP_RESOLVING) { // Newly created entry. uchar state = entry->ate_state; DEBUGMSG(DBG_INFO && DBG_ARP && DBG_TX, (DTEXT("ARPTx: Created ATE %x\n"), entry)); // Someone else could have raced in and created the entry between // the time we free the lock and the time we called // CreateARPTableEntry(). We check this by looking at the packet // on the entry. If there is no old packet we'll ARP. If there is, // we'll call ARPSendData to figure out what to do. if (entry->ate_packet == NULL) { entry->ate_packet = Packet; DEBUGMSG(DBG_INFO && DBG_ARP && DBG_TX, (DTEXT("ARPTx: ATE %x - calling SendARPRequest\n"), entry)); CTEFreeLock(&entry->ate_lock, Handle); SendARPRequest(ai, Destination, state, NULL, TRUE); // We don't know the state of the entry - we've freed the lock // and yielded, and it could conceivably have timed out by now, // or SendARPRequest could have failed, etc. We could take the // lock, check the status from SendARPRequest, see if it's // still the same packet, and then make a decision on the // return value, but it's easiest just to return pending. If // SendARPRequest failed, the entry will time out anyway. return NDIS_STATUS_PENDING; } else { return ARPSendData(ai, Packet, entry, Handle); } } else if (entry->ate_state == ARP_GOOD) { // Yow! A valid entry. return ARPSendData(ai, Packet, entry, Handle); } else { // An invalid entry! CTEFreeLock(&entry->ate_lock, Handle); return NDIS_STATUS_RESOURCES; } } else { // Couldn't create an entry. DEBUGMSG(DBG_ERROR && DBG_ARP, (DTEXT("ARPTx: Failed to create ATE.\n"))); return NDIS_STATUS_RESOURCES; } } //* RemoveARPTableEntry - Delete an entry from the ARP table. // // This is a simple utility function to delete an entry from the ATP table. We // assume locks are held on both the table and the entry. // // Entry: Previous - The entry immediately before the one to be deleted. // Entry - The entry to be deleted. // // Returns: Nothing. // void RemoveARPTableEntry(ARPTableEntry * Previous, ARPTableEntry * Entry) { RouteCacheEntry *RCE; // Pointer to route cache entry ARPContext *AC; RCE = Entry->ate_rce; // Loop through and invalidate all RCEs on this ATE. while (RCE != (RouteCacheEntry *) NULL) { AC = (ARPContext *) RCE->rce_context; AC->ac_ate = (ARPTableEntry *) NULL; RCE = AC->ac_next; } // Splice this guy out of the list. Previous->ate_next = Entry->ate_next; } //* ARPFlushATE - removes ARP Table entry for given dest address // // Called by IP layer when it needs to flush the link layer address from arp // cache // Entry: Interface - A pointer to the AI structure. // Destination - Destination Address whose Xlation needs to be removed // // Returns: TRUE if the entry was found and flushed, FALSE otherwise // BOOLEAN ARPFlushATE(void *Context, IPAddr Address) { ARPInterface *ai = (ARPInterface *) Context; CTELockHandle lhandle, tlhandle; ARPTable *Table; ARPTableEntry *Current, *Previous; int i = ARP_HASH(Address); PNDIS_PACKET OldPacket = NULL; CTEGetLock(&ai->ai_ARPTblLock, &tlhandle); Table = ai->ai_ARPTbl; Current = (*Table)[i]; Previous = (ARPTableEntry *) ((uchar *) & ((*Table)[i]) - offsetof(struct ARPTableEntry, ate_next)); while (Current != (ARPTableEntry *) NULL) { CTEGetLock(&Current->ate_lock, &lhandle); if (IP_ADDR_EQUAL(Current->ate_dest, Address)) { // Found a match. if (Current->ate_resolveonly) { ARPControlBlock *ArpContB, *TmpArpContB; ArpContB = Current->ate_resolveonly; while (ArpContB) { ArpRtn rtn; rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = (ULONG) STATUS_UNSUCCESSFUL; TmpArpContB = ArpContB->next; (*rtn) (ArpContB, (IP_STATUS) STATUS_UNSUCCESSFUL); ArpContB = TmpArpContB; } Current->ate_resolveonly = NULL; } RemoveARPTableEntry(Previous, Current); CTEFreeLock(&Current->ate_lock, lhandle); OldPacket = Current->ate_packet; CTEFreeLock(&ai->ai_ARPTblLock, tlhandle); if (OldPacket) { IPSendComplete(ai->ai_context, OldPacket, NDIS_STATUS_SUCCESS); } CTEFreeMem(Current); return TRUE; } CTEFreeLock(&Current->ate_lock, lhandle); Previous = Current; Current = Current->ate_next; } CTEFreeLock(&ai->ai_ARPTblLock, tlhandle); return FALSE; } //* ARPFlushAllATE - removes all ARP Table entries. // // Entry: Interface - A pointer to the AI structure. // // Returns: None // void ARPFlushAllATE(void *Context) { ARPInterface *ai = (ARPInterface *) Context; CTELockHandle tlhandle; ARPTable *Table; int i; ARPTableEntry *ATE; PNDIS_PACKET PList = (PNDIS_PACKET) NULL; CTEGetLock(&ai->ai_ARPTblLock, &tlhandle); Table = ai->ai_ARPTbl; if (Table != NULL) { for (i = 0; i < ARP_TABLE_SIZE; i++) { while ((*Table)[i] != NULL) { ATE = (*Table)[i]; if (ATE->ate_resolveonly) { ARPControlBlock *ArpContB, *TmpArpContB; ArpContB = ATE->ate_resolveonly; while (ArpContB) { ArpRtn rtn; rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = (ULONG) STATUS_UNSUCCESSFUL; TmpArpContB = ArpContB->next; (*rtn) (ArpContB, (IP_STATUS) STATUS_UNSUCCESSFUL); ArpContB = TmpArpContB; } ATE->ate_resolveonly = NULL; } // Acquire ate_lock to ensure exclusive access to the ATE. CTEGetLockAtDPC(&ATE->ate_lock); RemoveARPTableEntry(STRUCT_OF(ARPTableEntry, &((*Table)[i]), ate_next), ATE); CTEFreeLockFromDPC(&ATE->ate_lock); if (ATE->ate_packet) { ((PacketContext *) ATE->ate_packet->ProtocolReserved)->pc_common.pc_link = PList; PList = ATE->ate_packet; } CTEFreeMem(ATE); } } } CTEFreeLock(&ai->ai_ARPTblLock, tlhandle); while (PList != (PNDIS_PACKET) NULL) { PNDIS_PACKET Packet = PList; PList = ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_link; IPSendComplete(ai->ai_context, Packet, NDIS_STATUS_SUCCESS); } } //* ARPXferData - Transfer data on behalf on an upper later protocol. // // This routine is called by the upper layer when it needs to transfer data // from an NDIS driver. We just map his call down. // // Entry: Context - Context value we gave to IP (really a pointer to an AI). // MACContext - Context value MAC gave us on a receive. // MyOffset - Packet offset we gave to the protocol earlier. // ByteOffset - Byte offset into packet protocol wants transferred. // BytesWanted - Number of bytes to transfer. // Packet - Pointer to packet to be used for transferring. // Transferred - Pointer to where to return bytes transferred. // // Returns: NDIS_STATUS of command. // NDIS_STATUS __stdcall ARPXferData(void *Context, NDIS_HANDLE MACContext, uint MyOffset, uint ByteOffset, uint BytesWanted, PNDIS_PACKET Packet, uint * Transferred) { ARPInterface *Interface = (ARPInterface *) Context; NDIS_STATUS Status; NdisTransferData(&Status, Interface->ai_handle, MACContext, ByteOffset + MyOffset, BytesWanted, Packet, Transferred); return Status; } //* ARPUpdateOperStatus - Update the OperStatus and LastChange values. // // Called whenever ai_adminstate or ai_mediastatus changes, to preserve // the invariant that ai_operstatus should only be up if the admin // status is up and media sense is present. // // Entry: Interface - Interface to update. // // Returns: Nothing. // __inline void ARPUpdateOperStatus(ARPInterface *Interface) { uchar NewOperStatus; if (Interface->ai_operstatus == INTERFACE_UNINIT) { return; } if ((Interface->ai_adminstate == IF_STATUS_DOWN) || (Interface->ai_mediastatus == FALSE)) { NewOperStatus = INTERFACE_DOWN; } else { NewOperStatus = INTERFACE_UP; } if (Interface->ai_operstatus != NewOperStatus) { Interface->ai_operstatus = NewOperStatus; Interface->ai_lastchange = GetTimeTicks(); } } //* ARPClose - Close an adapter. // // Called by IP when it wants to close an adapter, presumably due to an error condition. // We'll close the adapter, but we won't free any memory. // // Entry: Context - Context value we gave him earlier. // // Returns: Nothing. // void __stdcall ARPClose(void *Context) { ARPInterface *Interface = (ARPInterface *) Context; NDIS_STATUS Status; CTELockHandle LockHandle; NDIS_HANDLE Handle; Interface->ai_mediastatus = FALSE; ARPUpdateOperStatus(Interface); // // Mark the interface as going away so it will disappear from the // entity list. // Interface->ai_operstatus = INTERFACE_UNINIT; CTEInitBlockStruc(&Interface->ai_block); CTEGetLock(&Interface->ai_lock, &LockHandle); if (Interface->ai_handle != (NDIS_HANDLE) NULL) { Handle = Interface->ai_handle; CTEFreeLock(&Interface->ai_lock, LockHandle); NdisCloseAdapter(&Status, Handle); if (Status == NDIS_STATUS_PENDING) { Status = CTEBlock(&Interface->ai_block); } Interface->ai_handle = NULL; } else { CTEFreeLock(&Interface->ai_lock, LockHandle); } } //* ARPInvalidate - Notification that an RCE is invalid. // // Called by IP when an RCE is closed or otherwise invalidated. We look up // the ATE for the specified RCE, and then remove the RCE from the ATE list. // // Entry: Context - Context value we gave him earlier. // RCE - RCE to be invalidated // // Returns: Nothing. // void __stdcall ARPInvalidate(void *Context, RouteCacheEntry *RCE) { ARPInterface *Interface = (ARPInterface *) Context; ARPTableEntry *ATE; CTELockHandle Handle; ARPContext *AC = (ARPContext *) RCE->rce_context; CTEGetLock(&Interface->ai_ARPTblLock, &Handle); #if DBG if (!(RCE->rce_flags & RCE_CONNECTED)) { ARPTableEntry *tmpATE; ATE = ARPLookup(Interface, RCE->rce_dest); if (ATE != NULL) { tmpATE = ATE; while (ATE) { if (ATE->ate_rce == RCE) { DbgBreakPoint(); } ATE = ATE->ate_next; } CTEFreeLockFromDPC(&Interface->ai_ARPTblLock); CTEFreeLock(&tmpATE->ate_lock, Handle); return; } } #endif if ((ATE = AC->ac_ate) == (ARPTableEntry *) NULL) { CTEFreeLock(&Interface->ai_ARPTblLock, Handle); // No matching ATE. return; } CTEGetLockAtDPC(&ATE->ate_lock); ARPRemoveRCE(ATE, RCE); RtlZeroMemory(RCE->rce_context, RCE_CONTEXT_SIZE); CTEFreeLockFromDPC(&Interface->ai_ARPTblLock); CTEFreeLock(&ATE->ate_lock, Handle); } //* ARPSetMCastList - Set the multicast address list for the adapter. // // Called to try and set the multicast reception list for the adapter. // We allocate a buffer big enough to hold the new address list, and format // the address list into the buffer. Then we submit the NDIS request to set // the list. If we can't set the list because the multicast address list is // full we'll put the card into all multicast mode. // // Input: Interface - Interface on which to set list. // // Returns: NDIS_STATUS of attempt. // NDIS_STATUS ARPSetMCastList(ARPInterface * Interface) { CTELockHandle Handle; uchar *MCastBuffer, *CurrentPtr; uint MCastSize; NDIS_STATUS Status = NDIS_STATUS_SUCCESS; uint i; ARPMCastAddr *AddrPtr; IPAddr UNALIGNED *Temp; CTEGetLock(&Interface->ai_lock, &Handle); MCastSize = Interface->ai_mcastcnt * ARP_802_ADDR_LENGTH; if (MCastSize != 0) MCastBuffer = CTEAllocMemN(MCastSize, 'RiCT'); else MCastBuffer = NULL; if (MCastBuffer != NULL || MCastSize == 0) { // Got the buffer. Loop through, building the list. AddrPtr = Interface->ai_mcast; CurrentPtr = MCastBuffer; for (i = 0; i < Interface->ai_mcastcnt; i++) { ASSERT(AddrPtr != NULL); if (Interface->ai_media == NdisMedium802_3) { RtlCopyMemory(CurrentPtr, ENetMcst, ARP_802_ADDR_LENGTH); Temp = (IPAddr UNALIGNED *) (CurrentPtr + 2); *Temp |= AddrPtr->ama_addr; } else if ((Interface->ai_media == NdisMedium802_5) & TRFunctionalMcast) { RtlCopyMemory(CurrentPtr, TRNetMcst, ARP_802_ADDR_LENGTH - 2); MCastSize = 4; } else if (Interface->ai_media == NdisMediumFddi) { RtlCopyMemory(CurrentPtr, ((FDDIHeader *) FDDIMcst)->fh_daddr, ARP_802_ADDR_LENGTH); Temp = (IPAddr UNALIGNED *) (CurrentPtr + 2); *Temp |= AddrPtr->ama_addr; } else ASSERT(0); CurrentPtr += ARP_802_ADDR_LENGTH; AddrPtr = AddrPtr->ama_next; } CTEFreeLock(&Interface->ai_lock, Handle); // We're built the list. Now give it to the driver to handle. if (Interface->ai_media == NdisMedium802_3) { Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_802_3_MULTICAST_LIST, MCastBuffer, MCastSize, NULL, TRUE); } else if ((Interface->ai_media == NdisMedium802_5) & TRFunctionalMcast) { if (!(Interface->ai_pfilter & NDIS_PACKET_TYPE_FUNCTIONAL)) { Interface->ai_pfilter |= NDIS_PACKET_TYPE_FUNCTIONAL; Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Interface->ai_pfilter, sizeof(uint), NULL, TRUE); } Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_802_5_CURRENT_FUNCTIONAL, MCastBuffer, MCastSize, NULL, TRUE); KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL, "SetMcast after OID-- TR mcast address on %x status %x\n", Interface, Status)); } else if (Interface->ai_media == NdisMediumFddi) { Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_FDDI_LONG_MULTICAST_LIST, MCastBuffer, MCastSize, NULL, TRUE); } else ASSERT(0); if (MCastBuffer != NULL) { CTEFreeMem(MCastBuffer); } if (Status == NDIS_STATUS_MULTICAST_FULL) { // Multicast list is full. Try to set the filter to all multicasts. Interface->ai_pfilter |= NDIS_PACKET_TYPE_ALL_MULTICAST; Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Interface->ai_pfilter, sizeof(uint), NULL, TRUE); } } else { CTEFreeLock(&Interface->ai_lock, Handle); Status = NDIS_STATUS_RESOURCES; } return Status; } //* ARPFindMCast - Find a multicast address structure on our list. // // Called as a utility to find a multicast address structure. If we find // it, we return a pointer to it and it's predecessor. Otherwise we return // NULL. We assume the caller holds the lock on the interface already. // // Input: Interface - Interface to search. // Addr - Addr to find. // Prev - Where to return previous pointer. // // Returns: Pointer if we find one, NULL otherwise. // ARPMCastAddr * ARPFindMCast(ARPInterface * Interface, IPAddr Addr, ARPMCastAddr ** Prev) { ARPMCastAddr *AddrPtr, *PrevPtr; PrevPtr = STRUCT_OF(ARPMCastAddr, &Interface->ai_mcast, ama_next); AddrPtr = PrevPtr->ama_next; while (AddrPtr != NULL) { if (IP_ADDR_EQUAL(AddrPtr->ama_addr, Addr)) break; else { PrevPtr = AddrPtr; AddrPtr = PrevPtr->ama_next; } } *Prev = PrevPtr; return AddrPtr; } //* ARPDelMCast - Delete a multicast address. // // Called when we want to delete a multicast address. We look for a matching // (masked) address. If we find one, we'll dec. the reference count and if // it goes to 0 we'll pull him from the list and reset the multicast list. // // Input: Interface - Interface on which to act. // Addr - Address to be deleted. // // Returns: TRUE if it worked, FALSE otherwise. // uint ARPDelMCast(ARPInterface * Interface, IPAddr Addr) { ARPMCastAddr *AddrPtr, *PrevPtr; CTELockHandle Handle; uint Status = TRUE; // When we support TR (RFC 1469) fully we'll need to change this. if (Interface->ai_media == NdisMedium802_3 || Interface->ai_media == NdisMediumFddi || (Interface->ai_media == NdisMedium802_5 && TRFunctionalMcast)) { // This is an interface that supports mcast addresses. Addr &= ARP_MCAST_MASK; CTEGetLock(&Interface->ai_lock, &Handle); AddrPtr = ARPFindMCast(Interface, Addr, &PrevPtr); if (AddrPtr != NULL) { // We found one. Dec. his refcnt, and if it's 0 delete him. (AddrPtr->ama_refcnt)--; if (AddrPtr->ama_refcnt == 0) { // He's done. PrevPtr->ama_next = AddrPtr->ama_next; (Interface->ai_mcastcnt)--; CTEFreeLock(&Interface->ai_lock, Handle); CTEFreeMem(AddrPtr); ARPSetMCastList(Interface); CTEGetLock(&Interface->ai_lock, &Handle); } } else Status = FALSE; CTEFreeLock(&Interface->ai_lock, Handle); } return Status; } //* ARPAddMCast - Add a multicast address. // // Called when we want to start receiving a multicast address. We'll mask // the address and look it up in our address list. If we find it, we'll just // bump the reference count. Otherwise we'll try to create one and put him // on the list. In that case we'll need to set the multicast address list for // the adapter. // // Input: Interface - Interface to set on. // Addr - Address to set. // // Returns: TRUE if we succeed, FALSE if we fail. // uint ARPAddMCast(ARPInterface * Interface, IPAddr Addr) { ARPMCastAddr *AddrPtr, *PrevPtr; CTELockHandle Handle; uint Status = TRUE; if (Interface->ai_operstatus != INTERFACE_UP) { return FALSE; } // Currently we don't do anything with token ring, since we send // all mcasts as TR broadcasts. When we comply with RFC 1469 we'll need to // fix this. if ((Interface->ai_media == NdisMedium802_3) || (Interface->ai_media == NdisMediumFddi) || ((Interface->ai_media == NdisMedium802_5) && TRFunctionalMcast)) { Addr &= ARP_MCAST_MASK; CTEGetLock(&Interface->ai_lock, &Handle); AddrPtr = ARPFindMCast(Interface, Addr, &PrevPtr); if (AddrPtr != NULL) { // We found one, just bump refcnt. (AddrPtr->ama_refcnt)++; } else { // Didn't find one. Allocate space for one, link him in, and // try to set the list. AddrPtr = CTEAllocMemN(sizeof(ARPMCastAddr), 'SiCT'); if (AddrPtr != NULL) { // Got one. Link him in. AddrPtr->ama_addr = Addr; AddrPtr->ama_refcnt = 1; AddrPtr->ama_next = Interface->ai_mcast; Interface->ai_mcast = AddrPtr; (Interface->ai_mcastcnt)++; CTEFreeLock(&Interface->ai_lock, Handle); // Now try to set the list. if (ARPSetMCastList(Interface) != NDIS_STATUS_SUCCESS) { // Couldn't set the list. Call the delete routine to delete // the address we just tried to set. Status = ARPDelMCast(Interface, Addr); ASSERT(Status); Status = FALSE; } CTEGetLock(&Interface->ai_lock, &Handle); } else Status = FALSE; // Couldn't get memory. } // We've done out best. Free the lock and return. CTEFreeLock(&Interface->ai_lock, Handle); } return Status; } //* ARPAddAddr - Add an address to the ARP table. // // This routine is called by IP to add an address as a local address, or // or specify the broadcast address for this interface. // // Entry: Context - Context we gave IP earlier (really an ARPInterface ptr) // Type - Type of address (local, p-arp, multicast, or // broadcast). // Address - Broadcast IP address to be added. // Mask - Mask for address. // // Returns: 0 if we failed, non-zero otherwise // uint __stdcall ARPAddAddr(void *Context, uint Type, IPAddr Address, IPMask Mask, void *Context2) { ARPInterface *Interface = (ARPInterface *) Context; CTELockHandle Handle; if (Type != LLIP_ADDR_LOCAL && Type != LLIP_ADDR_PARP) { // Not a local address, must be broadcast or multicast. if (Type == LLIP_ADDR_BCAST) { Interface->ai_bcast = Address; return TRUE; } else if (Type == LLIP_ADDR_MCAST) { return ARPAddMCast(Interface, Address); } else return FALSE; } else { // This is a local address. CTEGetLock(&Interface->ai_lock, &Handle); if (Type != LLIP_ADDR_PARP) { uint RetStatus = FALSE; uint ArpForSelf = FALSE; if (IP_ADDR_EQUAL(Interface->ai_ipaddr.aia_addr, 0)) { Interface->ai_ipaddr.aia_addr = Address; Interface->ai_ipaddr.aia_mask = Mask; Interface->ai_ipaddr.aia_age = ArpRetryCount; if (Interface->ai_operstatus == INTERFACE_UP) { // When ArpRetryCount is 0, we'll return immediately // below, so don't save completion context Interface->ai_ipaddr.aia_context = (ArpRetryCount > 0)? Context2 : NULL; ArpForSelf = TRUE; } else { Interface->ai_ipaddr.aia_context = NULL; } RetStatus = TRUE; } else { ARPIPAddr *NewAddr; NewAddr = CTEAllocMemNBoot(sizeof(ARPIPAddr), 'TiCT'); if (NewAddr != (ARPIPAddr *) NULL) { NewAddr->aia_addr = Address; NewAddr->aia_mask = Mask; NewAddr->aia_age = ArpRetryCount; NewAddr->aia_next = Interface->ai_ipaddr.aia_next; if (Interface->ai_operstatus == INTERFACE_UP) { // When ArpRetryCount is 0, we'll return immediately // below, so don't save completion context NewAddr->aia_context = (ArpRetryCount > 0)? Context2 : NULL; ArpForSelf = TRUE; } else { NewAddr->aia_context = NULL; } Interface->ai_ipaddr.aia_next = NewAddr; RetStatus = TRUE; } } if (RetStatus) { Interface->ai_ipaddrcnt++; if (Interface->ai_telladdrchng) { CTEFreeLock(&Interface->ai_lock, Handle); AddrNotifyLink(Interface); } else { CTEFreeLock(&Interface->ai_lock, Handle); } } else { CTEFreeLock(&Interface->ai_lock, Handle); } // add wakeup pattern for this address, if the address is in // conflict ip will turn around and delete the address thus // deleting the wakeup pattern. ARPWakeupPattern(Interface, Address, TRUE); // ARP for the address we've added, to see it it already exists. if (RetStatus == TRUE && ArpForSelf == TRUE) { if (ArpRetryCount) { SendARPRequest(Interface, Address, ARP_RESOLVING_GLOBAL, NULL, TRUE); return IP_PENDING; } else { return TRUE; } } return RetStatus; } else if (Type == LLIP_ADDR_PARP) { ARPPArpAddr *NewPArp, *TmpPArp; // He's adding a proxy arp address. // Don't allow to add duplicate proxy arp entries TmpPArp = Interface->ai_parpaddr; while (TmpPArp) { if (IP_ADDR_EQUAL(TmpPArp->apa_addr, Address) && IP_ADDR_EQUAL(TmpPArp->apa_mask, Mask)) { CTEFreeLock(&Interface->ai_lock, Handle); return FALSE; } TmpPArp = TmpPArp->apa_next; } NewPArp = CTEAllocMemN(sizeof(ARPPArpAddr), 'UiCT'); if (NewPArp != NULL) { NewPArp->apa_addr = Address; NewPArp->apa_mask = Mask; NewPArp->apa_next = Interface->ai_parpaddr; Interface->ai_parpaddr = NewPArp; Interface->ai_parpcount++; CTEFreeLock(&Interface->ai_lock, Handle); return TRUE; } CTEFreeLock(&Interface->ai_lock, Handle); } return FALSE; } } //* ARPDeleteAddr - Delete a local or proxy address. // // Called to delete a local or proxy address. // // Entry: Context - An ARPInterface pointer. // Type - Type of address (local or p-arp). // Address - IP address to be deleted. // Mask - Mask for address. Used only for deleting proxy-ARP // entries. // // Returns: 0 if we failed, non-zero otherwise // uint __stdcall ARPDeleteAddr(void *Context, uint Type, IPAddr Address, IPMask Mask) { ARPInterface *Interface = (ARPInterface *) Context; CTELockHandle Handle; ARPIPAddr *DelAddr, *PrevAddr; ARPPArpAddr *DelPAddr, *PrevPAddr; SetAddrControl *SAC; AddAddrNotifyEvent *DelayedEvent; if (Type == LLIP_ADDR_LOCAL) { CTEGetLock(&Interface->ai_lock, &Handle); if (IP_ADDR_EQUAL(Interface->ai_ipaddr.aia_addr, Address)) { IPAddr IpAddress; ARPIPAddr *Addr; Addr = &Interface->ai_ipaddr; IpAddress = Addr->aia_addr; Interface->ai_ipaddr.aia_addr = NULL_IP_ADDR; Interface->ai_ipaddrcnt--; if (Interface->ai_telladdrchng) { CTEFreeLock(&Interface->ai_lock, Handle); AddrNotifyLink(Interface); CTEGetLock(&Interface->ai_lock, &Handle); } // if the address is deleted before the add completes, complete the add here // Doing this will complete the irp and also decrements the refcount on the interface if (Addr->aia_context != NULL) { SAC = (SetAddrControl *) Addr->aia_context; Addr->aia_context = NULL; CTEFreeLock(&Interface->ai_lock, Handle); // We cannot call completion routine at timer DPC // because completion routine will need to notify // TDI clients and that could take long time. DelayedEvent = CTEAllocMemNBoot(sizeof(AddAddrNotifyEvent), 'ViCT'); if (DelayedEvent) { DelayedEvent->SAC = SAC; DelayedEvent->Address = IpAddress; DelayedEvent->Status = IP_SUCCESS; CTEInitEvent(&DelayedEvent->Event, CompleteIPSetNTEAddrRequestDelayed); CTEScheduleDelayedEvent(&DelayedEvent->Event, DelayedEvent); } else { ASSERT(FALSE); return FALSE; } } else { CTEFreeLock(&Interface->ai_lock, Handle); } ARPWakeupPattern(Interface, Address, FALSE); return TRUE; } else { PrevAddr = STRUCT_OF(ARPIPAddr, &Interface->ai_ipaddr, aia_next); DelAddr = PrevAddr->aia_next; while (DelAddr != NULL) if (IP_ADDR_EQUAL(DelAddr->aia_addr, Address)) break; else { PrevAddr = DelAddr; DelAddr = DelAddr->aia_next; } if (DelAddr != NULL) { PrevAddr->aia_next = DelAddr->aia_next; if (DelAddr->aia_next && DelAddr->aia_next->aia_age == ARPADDR_MARKER) { DelAddr->aia_next->aia_context = (PVOID) PrevAddr; } Interface->ai_ipaddrcnt--; if (Interface->ai_telladdrchng) { CTEFreeLock(&Interface->ai_lock, Handle); AddrNotifyLink(Interface); } else { CTEFreeLock(&Interface->ai_lock, Handle); } if (DelAddr->aia_context != NULL) { SAC = (SetAddrControl *) DelAddr->aia_context; DelAddr->aia_context = NULL; DelayedEvent = CTEAllocMemNBoot(sizeof(AddAddrNotifyEvent), 'ViCT'); if (DelayedEvent) { DelayedEvent->SAC = SAC; DelayedEvent->Address = DelAddr->aia_addr; DelayedEvent->Status = IP_SUCCESS; CTEInitEvent(&DelayedEvent->Event, CompleteIPSetNTEAddrRequestDelayed); CTEScheduleDelayedEvent(&DelayedEvent->Event, DelayedEvent); } else { ASSERT(FALSE); return FALSE; } } CTEFreeMem(DelAddr); ARPWakeupPattern(Interface, Address, FALSE); } else { CTEFreeLock(&Interface->ai_lock, Handle); } return(DelAddr != NULL); } } else if (Type == LLIP_ADDR_PARP) { CTEGetLock(&Interface->ai_lock, &Handle); PrevPAddr = STRUCT_OF(ARPPArpAddr, &Interface->ai_parpaddr, apa_next); DelPAddr = PrevPAddr->apa_next; while (DelPAddr != NULL) if (IP_ADDR_EQUAL(DelPAddr->apa_addr, Address) && DelPAddr->apa_mask == Mask) break; else { PrevPAddr = DelPAddr; DelPAddr = DelPAddr->apa_next; } if (DelPAddr != NULL) { PrevPAddr->apa_next = DelPAddr->apa_next; Interface->ai_parpcount--; CTEFreeMem(DelPAddr); } CTEFreeLock(&Interface->ai_lock, Handle); return(DelPAddr != NULL); } else if (Type == LLIP_ADDR_MCAST) return ARPDelMCast(Interface, Address); else return FALSE; } //*AddrNotifyLink - Notify link layer of Network Address changes // // Called when address are added/deleted on an interface // // Entry: Interface - ARPinterface pointer // // returns: NDIS_STATUS.Also sets ai_telladdrchng if status is failure // when this happens caller can check and see if next addr notification // need to be done or not. // NDIS_STATUS AddrNotifyLink(ARPInterface * Interface) { PNETWORK_ADDRESS_LIST AddressList; NETWORK_ADDRESS UNALIGNED *Address; int i = 0, size, count; ARPIPAddr *addrlist; NDIS_STATUS status = NDIS_STATUS_FAILURE; CTELockHandle Handle; CTEGetLock(&Interface->ai_lock, &Handle); size = Interface->ai_ipaddrcnt * (sizeof(NETWORK_ADDRESS_IP) + FIELD_OFFSET(NETWORK_ADDRESS, Address)) + FIELD_OFFSET(NETWORK_ADDRESS_LIST, Address); AddressList = CTEAllocMemN(size, 'WiCT'); if (AddressList) { addrlist = &Interface->ai_ipaddr; count = Interface->ai_ipaddrcnt; AddressList->AddressType = NDIS_PROTOCOL_ID_TCP_IP; while (addrlist && count) { NETWORK_ADDRESS_IP UNALIGNED *tmpIPAddr; uchar *Address0; // // Skip if this is a Marker. // if (addrlist->aia_age != ARPADDR_MARKER) { Address0 = (uchar *) & AddressList->Address[0]; Address = (PNETWORK_ADDRESS) (Address0 + i * (FIELD_OFFSET(NETWORK_ADDRESS, Address) + sizeof(NETWORK_ADDRESS_IP))); tmpIPAddr = (PNETWORK_ADDRESS_IP) & Address->Address[0]; Address->AddressLength = sizeof(NETWORK_ADDRESS_IP); Address->AddressType = NDIS_PROTOCOL_ID_TCP_IP; RtlCopyMemory(&tmpIPAddr->in_addr, &addrlist->aia_addr, sizeof(IPAddr)); count--; i++; } addrlist = addrlist->aia_next; } CTEFreeLock(&Interface->ai_lock, Handle); AddressList->AddressCount = i; status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_NETWORK_LAYER_ADDRESSES, AddressList, size, NULL, TRUE); if (status != NDIS_STATUS_SUCCESS) { CTEGetLock(&Interface->ai_lock, &Handle); Interface->ai_telladdrchng = 0; CTEFreeLock(&Interface->ai_lock, Handle); } CTEFreeMem(AddressList); } else { CTEFreeLock(&Interface->ai_lock, Handle); status = NDIS_STATUS_RESOURCES; } return status; } #if !MILLEN //* ARPCancelPackets // // Entry: Context - Pointer to the ARPInterface // ID - Pattern that need to be passed down to ndis // // Returns: Nothing // VOID __stdcall ARPCancelPackets(void *Context, void *ID) { ARPInterface *Interface = (ARPInterface *) Context; NdisCancelSendPackets(Interface->ai_handle,ID); } #endif //* DoWakeupPattern - Adds and removes wakeup pattern. // // Entry: Context - Pointer to the ARPInterface // PtrnDesc - Pattern buffer(s) of high level protocol // protoid - the proto type used in ethernet or snap type fields. // AddPattern - TRUE if pattern is to be added, FALSE if it is to be removed. // // Returns: Nothing. // NDIS_STATUS __stdcall DoWakeupPattern(void *Context, PNET_PM_WAKEUP_PATTERN_DESC PtrnDesc, ushort protoid, BOOLEAN AddPattern) { ARPInterface *Interface = (ARPInterface *) Context; uint PtrnLen; uint PtrnBufferLen; uint MaskLen; PNET_PM_WAKEUP_PATTERN_DESC CurPtrnDesc; uchar *NextMask, *NextPtrn; const uchar *MMask; uint MMaskLength; uchar NextMaskBit; uchar *Buffer; PNDIS_PM_PACKET_PATTERN PtrnBuffer; NDIS_STATUS Status; // // First find the total length of the pattern. // Pattern starts right at MacHeader. // // First add the media portion of the header. // PtrnLen = Interface->ai_hdrsize + Interface->ai_snapsize; // now add the high level proto pattern size. CurPtrnDesc = PtrnDesc; while (CurPtrnDesc != (PNET_PM_WAKEUP_PATTERN_DESC) NULL) { PtrnLen += CurPtrnDesc->PtrnLen; CurPtrnDesc = CurPtrnDesc->Next; } // length of the mask: every byte of pattern requires // one bit of the mask. MaskLen = GetWakeupPatternMaskLength(PtrnLen); // total length of the pattern buffer to be given to ndis. PtrnBufferLen = sizeof(NDIS_PM_PACKET_PATTERN) + PtrnLen + MaskLen; if ((Buffer = CTEAllocMemN(PtrnBufferLen, 'XiCT')) == (uchar *) NULL) { return NDIS_STATUS_RESOURCES; } RtlZeroMemory(Buffer, PtrnBufferLen); PtrnBuffer = (PNDIS_PM_PACKET_PATTERN) Buffer; PtrnBuffer->PatternSize = PtrnLen; NextMask = Buffer + sizeof(NDIS_PM_PACKET_PATTERN); NextPtrn = NextMask + MaskLen; PtrnBuffer->MaskSize = MaskLen; PtrnBuffer->PatternOffset = (ULONG) ((ULONG_PTR) NextPtrn - (ULONG_PTR) PtrnBuffer); // Figure out what type of media this is, and do the appropriate thing. switch (Interface->ai_media) { case NdisMedium802_3: if (Interface->ai_snapsize == 0) { ENetHeader UNALIGNED *Hdr = (ENetHeader UNALIGNED *) NextPtrn; Hdr->eh_type = net_short(protoid); MMask = ENetPtrnMsk; } else { MMask = ENetSNAPPtrnMsk; } break; case NdisMedium802_5: if (Interface->ai_snapsize == 0) { MMask = TRPtrnMsk; } else { MMask = TRSNAPPtrnMsk; } break; case NdisMediumFddi: if (Interface->ai_snapsize == 0) { MMask = FDDIPtrnMsk; } else { MMask = FDDISNAPPtrnMsk; } break; case NdisMediumArcnet878_2: MMask = ARCPtrnMsk; break; default: ASSERT(0); Interface->ai_outerrors++; CTEFreeMem(Buffer); return NDIS_STATUS_UNSUPPORTED_MEDIA; } NextPtrn += Interface->ai_hdrsize; // Copy in SNAP header, if any. if (Interface->ai_snapsize) { SNAPHeader UNALIGNED *SNAPPtr = (SNAPHeader UNALIGNED *) NextPtrn; RtlCopyMemory(SNAPPtr, ARPSNAP, Interface->ai_snapsize); SNAPPtr->sh_etype = net_short(protoid); NextPtrn += Interface->ai_snapsize; } // MMaskLength = (Interface->ai_snapsize + Interface->ai_hdrsize - 1) / 8 + 1; // copy the mask for media part RtlCopyMemory(NextMask, MMask, MMaskLength); NextMaskBit = (Interface->ai_hdrsize + Interface->ai_snapsize) % 8; NextMask = NextMask + (Interface->ai_hdrsize + Interface->ai_snapsize) / 8; // copy the pattern and mask of high level proto. CurPtrnDesc = PtrnDesc; while (CurPtrnDesc) { uint CopyBits = CurPtrnDesc->PtrnLen; uchar *SrcMask = CurPtrnDesc->Mask; uchar SrcMaskBit = 0; RtlCopyMemory(NextPtrn, CurPtrnDesc->Ptrn, CurPtrnDesc->PtrnLen); NextPtrn += CurPtrnDesc->PtrnLen; while (CopyBits--) { *NextMask |= ((*SrcMask & (0x1 << SrcMaskBit)) ? (0x1 << NextMaskBit) : 0); if ((NextMaskBit = ((NextMaskBit + 1) % 8)) == 0) { NextMask++; } if ((SrcMaskBit = ((SrcMaskBit + 1) % 8)) == 0) { SrcMask++; } } CurPtrnDesc = CurPtrnDesc->Next; } // now tell ndis to set or remove the pattern. Status = DoNDISRequest( Interface, NdisRequestSetInformation, AddPattern ? OID_PNP_ADD_WAKE_UP_PATTERN : OID_PNP_REMOVE_WAKE_UP_PATTERN, PtrnBuffer, PtrnBufferLen, NULL, TRUE); CTEFreeMem(Buffer); return Status; } //* ARPWakeupPattern - add or remove ARP wakeup pattern. // // Entry: Interface - Pointer to the ARPInterface // Addr - IPAddr for which we need to set ARP pattern filter. // // Returns: Nothing. // NDIS_STATUS ARPWakeupPattern(ARPInterface * Interface, IPAddr Addr, BOOLEAN AddPattern) { PNET_PM_WAKEUP_PATTERN_DESC PtrnDesc; uint PtrnLen; uint MaskLen; const uchar *PtrnMask; NDIS_STATUS Status; // // create high level proto (ARP here) pattern descriptor. // // len of pattern. PtrnLen = sizeof(ARPHeader); // adjust for Arcnet. if (Interface->ai_media == NdisMediumArcnet878_2) { PtrnLen -= ARCNET_ARPHEADER_ADJUSTMENT; PtrnMask = ARCARPPtrnMsk; } else { PtrnMask = ARPPtrnMsk; } // masklen = 1 bit per every byte of pattern. MaskLen = GetWakeupPatternMaskLength(PtrnLen); if ((PtrnDesc = CTEAllocMemN(sizeof(NET_PM_WAKEUP_PATTERN_DESC) + PtrnLen + MaskLen, 'YiCT')) != (PNET_PM_WAKEUP_PATTERN_DESC) NULL) { ARPHeader UNALIGNED *Hdr; uchar *IPAddrPtr; RtlZeroMemory(PtrnDesc, sizeof(NET_PM_WAKEUP_PATTERN_DESC) + PtrnLen + MaskLen); // set the ptrn and mask pointers in the buffer. PtrnDesc->PtrnLen = (USHORT) PtrnLen; PtrnDesc->Ptrn = (uchar *) PtrnDesc + sizeof(NET_PM_WAKEUP_PATTERN_DESC); PtrnDesc->Mask = (uchar *) PtrnDesc + sizeof(NET_PM_WAKEUP_PATTERN_DESC) + PtrnLen; // we need to wakeup on ARP request for our IPAddr. // so set the opcode and dest ip addr fields of ARP. Hdr = (ARPHeader UNALIGNED *) PtrnDesc->Ptrn; Hdr->ah_opcode = net_short(ARP_REQUEST); IPAddrPtr = Hdr->ah_shaddr + Interface->ai_addrlen + sizeof(IPAddr) + Interface->ai_addrlen; *(IPAddr UNALIGNED *) IPAddrPtr = Addr; RtlCopyMemory(PtrnDesc->Mask, PtrnMask, MaskLen); // give it to ndis. Status = DoWakeupPattern( Interface, PtrnDesc, ARP_ETYPE_ARP, AddPattern); // free the ptrn desc. CTEFreeMem(PtrnDesc); //now add wakeup pattren for directed mac address { uint PtrnBufferLen; PNDIS_PM_PACKET_PATTERN PtrnBuffer; uchar *Buffer; PtrnLen = ARP_802_ADDR_LENGTH; //eth dest address MaskLen = 1; //1 byte, needs 6 bits, 1 bit/byte PtrnBufferLen = sizeof(NDIS_PM_PACKET_PATTERN) + PtrnLen + MaskLen; Buffer = CTEAllocMem(PtrnBufferLen); if (Buffer) { RtlZeroMemory(Buffer, PtrnBufferLen); PtrnBuffer = (PNDIS_PM_PACKET_PATTERN) Buffer; PtrnBuffer->PatternSize = PtrnLen; PtrnBuffer->MaskSize = MaskLen; PtrnBuffer->PatternOffset = sizeof(NDIS_PM_PACKET_PATTERN) + 1; *(Buffer + sizeof(NDIS_PM_PACKET_PATTERN)) = 0x3F; RtlCopyMemory(Buffer + sizeof(NDIS_PM_PACKET_PATTERN) + 1, Interface->ai_addr, ARP_802_ADDR_LENGTH); Status = DoNDISRequest( Interface, NdisRequestSetInformation, AddPattern ? OID_PNP_ADD_WAKE_UP_PATTERN : OID_PNP_REMOVE_WAKE_UP_PATTERN, PtrnBuffer, PtrnBufferLen, NULL, TRUE); CTEFreeMem(Buffer); } } return Status; } return IP_NO_RESOURCES; } //** CompleteIPSetNTEAddrRequestDelayed - // // calls CompleteIPSetNTEAddrRequest on a delayed worker thread // // Entry: // Context - pointer to the control block // Exit: // None. // void CompleteIPSetNTEAddrRequestDelayed(CTEEvent * WorkerThreadEvent, PVOID Context) { AddAddrNotifyEvent *DelayedEvent; SetAddrControl *SAC; IPAddr Address; IP_STATUS Status; UNREFERENCED_PARAMETER(WorkerThreadEvent); DelayedEvent = (AddAddrNotifyEvent *) Context; SAC = DelayedEvent->SAC; // the client context block; Address = DelayedEvent->Address; // The address for which SetNTEAddr was called for. Status = DelayedEvent->Status; // Free the worker thread event. CTEFreeMem(Context); IPAddAddrComplete(Address, SAC, Status); } #if FFP_SUPPORT //* ARPReclaimRequestMem - Post processing upon request completion // // Called upon completion of NDIS requests that originate at ARP // // Input: pRequestInfo - Points to request IP sends ARP // // Returns: None // void ARPReclaimRequestMem(PVOID pRequestInfo) { // Decrement ref count, and reclaim memory if it drops to zero if (InterlockedDecrement( (PLONG) &((ReqInfoBlock *) pRequestInfo)->RequestRefs) == 0) { // TCPTRACE(("ARPReclaimRequestMem: Freeing mem at pReqInfo = %08X\n", // pRequestInfo)); CTEFreeMem(pRequestInfo); } } #endif // if FFP_SUPPORT //* ARPTimeout - ARP timeout routine. // // This is the timeout routine that is called periodically. We scan the ARP table, looking // for invalid entries that can be removed. // // Entry: Timer - Pointer to the timer that just fired. // Context - Pointer to the interface to be timed out. // // Returns: Nothing. // void ARPTimeout(CTEEvent * Timer, void *Context) { ARPInterface *Interface = (ARPInterface *) Context; // Our interface. ARPTable *Table; ARPTableEntry *Current, *Previous; int i; // Index variable. ulong Now = CTESystemUpTime(), ValidTime; CTELockHandle tblhandle; uchar Deleted; PNDIS_PACKET PList = (PNDIS_PACKET) NULL; ARPIPAddr *Addr; ARPIPAddr Marker; UNREFERENCED_PARAMETER(Timer); // Walk down the list of addresses, decrementing the age. CTEGetLock(&Interface->ai_lock, &tblhandle); if (Interface->ai_conflict && !(--Interface->ai_delay)) { ARPNotifyStruct *NotifyStruct = Interface->ai_conflict; CTEScheduleDelayedEvent(&NotifyStruct->ans_event, NotifyStruct); Interface->ai_conflict = NULL; } Addr = &Interface->ai_ipaddr; // // Marker is used to track the next addr to be processed // in the ipaddr list. Initialize it so that its aia_age is // OLD_LOCAL, and aia_addr is NULL_IP_ADDR. The places where // address list is scanned will skip ARPIPAddr with NULL_IP_ADDR // and in ARPDeleteAddr, if an addr element before the marker is // removed, Marker's aia_context will be changed to its prev element. // Marker.aia_addr = NULL_IP_ADDR; do { if (Addr->aia_age != ARPADDR_OLD_LOCAL) { IPAddr IpAddress; (Addr->aia_age)--; // // Insert Marker after this Addr // Marker's aia_context is used as blink // Marker.aia_age = ARPADDR_MARKER; Marker.aia_next = Addr->aia_next; Marker.aia_context = Addr; Addr->aia_next = &Marker; if (Addr->aia_age == ARPADDR_OLD_LOCAL) { if (Addr->aia_context != NULL) { SetAddrControl *SAC; AddAddrNotifyEvent *DelayedEvent; SAC = (SetAddrControl *) Addr->aia_context; Addr->aia_context = NULL; IpAddress = Addr->aia_addr; CTEFreeLock(&Interface->ai_lock, tblhandle); // We cannot call completion routine at timer DPC // because completion routine will need to notify // TDI clients and that could take long time. DelayedEvent = CTEAllocMemNBoot(sizeof(AddAddrNotifyEvent), 'ZiCT'); if (DelayedEvent) { DelayedEvent->SAC = SAC; DelayedEvent->Address = IpAddress; DelayedEvent->Status = IP_SUCCESS; CTEInitEvent(&DelayedEvent->Event, CompleteIPSetNTEAddrRequestDelayed); CTEScheduleDelayedEvent(&DelayedEvent->Event, DelayedEvent); } CTEGetLock(&Interface->ai_lock, &tblhandle); } } else { IpAddress = Addr->aia_addr; CTEFreeLock(&Interface->ai_lock, tblhandle); SendARPRequest(Interface, IpAddress, ARP_RESOLVING_GLOBAL, NULL, TRUE); CTEGetLock(&Interface->ai_lock, &tblhandle); } // // We are done scanning the list // Remove the Marker // Addr = Marker.aia_next; ((ARPIPAddr *)(Marker.aia_context))->aia_next = Marker.aia_next; } else { Addr = Addr->aia_next; } } while (Addr != NULL); CTEFreeLock(&Interface->ai_lock, tblhandle); // Loop through the ARP table for this interface, and delete stale entries. CTEGetLock(&Interface->ai_ARPTblLock, &tblhandle); Table = Interface->ai_ARPTbl; for (i = 0; i < ARP_TABLE_SIZE; i++) { Previous = (ARPTableEntry *) ((uchar *) & ((*Table)[i]) - offsetof(struct ARPTableEntry, ate_next)); Current = (*Table)[i]; while (Current != (ARPTableEntry *) NULL) { CTEGetLockAtDPC(&Current->ate_lock); Deleted = 0; //Delete the entry if it was used for api purpose if (Current->ate_resolveonly) { ARPControlBlock *ArpContB, *tmpArpContB; PNDIS_PACKET Packet = Current->ate_packet; ArpContB = Current->ate_resolveonly; ASSERT(Current->ate_resolveonly != NULL); while (ArpContB) { ArpRtn rtn; //Complete the pending request rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = 0; tmpArpContB = ArpContB->next; (*rtn) (ArpContB, (IP_STATUS) STATUS_UNSUCCESSFUL); ArpContB = tmpArpContB; } Current->ate_resolveonly = NULL; if (Packet != (PNDIS_PACKET) NULL) { ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_link = PList; PList = Packet; } RemoveARPTableEntry(Previous, Current); Interface->ai_count--; Deleted = 1; goto doneapi; } if (Current->ate_state == ARP_GOOD) { // // The ARP entry is valid for ARP_VALID_TIMEOUT by default. // If a cache life greater than ARP_VALID_TIMEOUT has been // configured, we'll make the entry valid for that time. // ValidTime = ArpCacheLife * ARP_TIMER_TIME; if (ValidTime < (ArpMinValidCacheLife * 1000)) { ValidTime = (ArpMinValidCacheLife * 1000); } } else { ValidTime = ARP_RESOLVE_TIMEOUT; } if (Current->ate_valid != ALWAYS_VALID && (((Now - Current->ate_valid) > ValidTime) || (Current->ate_state == ARP_GOOD && !(--(Current->ate_useticks))))) { if (Current->ate_state != ARP_RESOLVING_LOCAL) { // Really need to delete this guy. PNDIS_PACKET Packet = Current->ate_packet; if (((Now - Current->ate_valid) > ValidTime) && Current->ate_refresh) { DEBUGMSG(DBG_INFO && DBG_ARP, (DTEXT("ARPTimeout: Expiring ATE %x\n"), Current)); if (Packet != (PNDIS_PACKET) NULL) { ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_link = PList; PList = Packet; } RemoveARPTableEntry(Previous, Current); Interface->ai_count--; Deleted = 1; } else { //Just try to validate this again. Current->ate_valid = Now + ARP_REFRESH_TIME; Current->ate_refresh=TRUE; } } else { IPAddr Dest = Current->ate_dest; // This entry is only resoving locally, presumably this is // token ring. We'll need to transmit a 'global' resolution // now. ASSERT(Interface->ai_media == NdisMedium802_5); Now = CTESystemUpTime(); Current->ate_valid = Now; Current->ate_state = ARP_RESOLVING_GLOBAL; CTEFreeLockFromDPC(&Current->ate_lock); CTEFreeLock(&Interface->ai_ARPTblLock, tblhandle); // Send a global request. SendARPRequest(Interface, Dest, ARP_RESOLVING_GLOBAL, NULL, TRUE); CTEGetLock(&Interface->ai_ARPTblLock, &tblhandle); // Since we've freed the locks, we need to start over from // the start of this chain. Previous = STRUCT_OF(ARPTableEntry, &((*Table)[i]), ate_next); Current = (*Table)[i]; continue; } } doneapi: // If we deleted the entry, leave the previous pointer alone, // advance the current pointer, and free the memory. Otherwise // move both pointers forward. We can free the entry lock now // because the next pointers are protected by the table lock, and // we've removed it from the list so nobody else should // find it anyway. CTEFreeLockFromDPC(&Current->ate_lock); if (Deleted) { ARPTableEntry *Temp = Current; Current = Current->ate_next; CTEFreeMem(Temp); } else { Previous = Current; Current = Current->ate_next; } } } CTEFreeLock(&Interface->ai_ARPTblLock, tblhandle); while (PList != (PNDIS_PACKET) NULL) { PNDIS_PACKET Packet = PList; PList = ((PacketContext *) Packet->ProtocolReserved)->pc_common.pc_link; IPSendComplete(Interface->ai_context, Packet, NDIS_STATUS_SUCCESS); } // // Dont requeue if interface is going down and we need to stop the timer // if (Interface->ai_stoptimer) { // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARP interface %lx is down - dont requeue the timer - signal the waiter\n", Interface)); Interface->ai_timerstarted = FALSE; CTESignal(&Interface->ai_timerblock, NDIS_STATUS_SUCCESS); } else { CTEStartTimer(&Interface->ai_timer, ARP_TIMER_TIME, ARPTimeout, Interface); } #if FFP_SUPPORT // Flush Processing - This can be done after starting the timer CTEGetLock(&Interface->ai_lock, &tblhandle); // If FFP supported on this interface & it is time to do a flush if ((Interface->ai_ffpversion) && (++Interface->ai_ffplastflush >= FFP_ARP_FLUSH_INTERVAL)) { ReqInfoBlock *pRequestInfo; FFPFlushParams *pFlushInfo; TCPTRACE(("ARPTimeout: Sending a FFP flush to ARPInterface %08X\n", Interface)); // Allocate the request block - For General and Request Specific Parts pRequestInfo = CTEAllocMemN(sizeof(ReqInfoBlock) + sizeof(FFPFlushParams), '0ICT'); // TCPTRACE(("ARPTimeout: Allocated mem at pReqInfo = %08X\n", // pRequestInfo)); if (pRequestInfo != NULL) { // Prepare the params for the request [Part common to all requests] pRequestInfo->RequestType = OID_FFP_FLUSH; pRequestInfo->ReqCompleteCallback = ARPReclaimRequestMem; // Prepare the params for the request [Part specific to this request] pRequestInfo->RequestLength = sizeof(FFPFlushParams); // Flush all caches that FFP keeps - just a safe reset of FFP state pFlushInfo = (FFPFlushParams *) pRequestInfo->RequestInfo; pFlushInfo->NdisProtocolType = NDIS_PROTOCOL_ID_TCP_IP; // Assign the ref count to 1 => Used for just a single request pRequestInfo->RequestRefs = 1; DoNDISRequest(Interface, NdisRequestSetInformation, OID_FFP_FLUSH, pFlushInfo, sizeof(FFPFlushParams), NULL, FALSE); // Reset the number of timer ticks since the last FFP request Interface->ai_ffplastflush = 0; } else { TCPTRACE(("Error: Unable to allocate memory for NdisRequest\n")); } } #if DBG if (fakereset) { NDIS_STATUS Status; NdisReset(&Status, Interface->ai_handle); KdPrint(("fakereset: %x\n", Status)); } #endif CTEFreeLock(&Interface->ai_lock, tblhandle); #endif // if FFP_SUPPORT } //* IsLocalAddr - Return info. about local status of address. // // Called when we need info. about whether or not a particular address is // local. We return info about whether or not it is, and if it is how old // it is. // // Entry: Interface - Pointer to interface structure to be searched. // Address - Address in question. // // Returns: ARPADDR_*, for how old it is. // // uint IsLocalAddr(ARPInterface * Interface, IPAddr Address) { CTELockHandle Handle; ARPIPAddr *CurrentAddr; uint Age; // If we are asking about the null ip address, we don't want to consider // it as a true local address. // if (IP_ADDR_EQUAL(Address, NULL_IP_ADDR)) { return ARPADDR_NOT_LOCAL; } CTEGetLock(&Interface->ai_lock, &Handle); CurrentAddr = &Interface->ai_ipaddr; Age = ARPADDR_NOT_LOCAL; do { if (CurrentAddr->aia_addr == Address) { Age = CurrentAddr->aia_age; break; } CurrentAddr = CurrentAddr->aia_next; } while (CurrentAddr != NULL); CTEFreeLock(&Interface->ai_lock, Handle); return Age; } //* ARPLocalAddr - Determine whether or not a given address if local. // // This routine is called when we receive an incoming packet and need to // determine whether or not it's local. We look up the provided address on // the specified interface. // // Entry: Interface - Pointer to interface structure to be searched. // Address - Address in question. // // Returns: TRUE if it is a local address, FALSE if it's not. // uchar ARPLocalAddr(ARPInterface * Interface, IPAddr Address) { CTELockHandle Handle; ARPPArpAddr *CurrentPArp; IPMask Mask, NetMask; IPAddr MatchAddress; // First, see if he's a local (not-proxy) address. if (IsLocalAddr(Interface, Address) != ARPADDR_NOT_LOCAL) return TRUE; CTEGetLock(&Interface->ai_lock, &Handle); // Didn't find him in out local address list. See if he exists on our // proxy ARP list. for (CurrentPArp = Interface->ai_parpaddr; CurrentPArp != NULL; CurrentPArp = CurrentPArp->apa_next) { // See if this guy matches. Mask = CurrentPArp->apa_mask; MatchAddress = Address & Mask; if (IP_ADDR_EQUAL(CurrentPArp->apa_addr, MatchAddress)) { // He matches. We need to make a few more checks to make sure // we don't reply to a broadcast address. if (Mask == HOST_MASK) { // We're matching the whole address, so it's OK. CTEFreeLock(&Interface->ai_lock, Handle); return TRUE; } // See if the non-mask part it all-zeros. Since the mask presumably // covers a subnet, this trick will prevent us from replying to // a zero host part. if (IP_ADDR_EQUAL(MatchAddress, Address)) continue; // See if the host part is all ones. if (IP_ADDR_EQUAL(Address, MatchAddress | (IP_LOCAL_BCST & ~Mask))) continue; // If the mask we were given is not the net mask for this address, // we'll need to repeat the above checks. NetMask = IPNetMask(Address); if (NetMask != Mask) { MatchAddress = Address & NetMask; if (IP_ADDR_EQUAL(MatchAddress, Address)) continue; if (IP_ADDR_EQUAL(Address, MatchAddress | (IP_LOCAL_BCST & ~NetMask))) continue; } // If we get to this point we've passed all the tests, so it's // local. CTEFreeLock(&Interface->ai_lock, Handle); return TRUE; } } CTEFreeLock(&Interface->ai_lock, Handle); return FALSE; } //* NotifyConflictProc - Notify the user of an address conflict. // // Called when we need to notify the user of an address conflict. The // exact mechanism is system dependent, but generally involves a popup. // // Input: Event - Event that fired. // Context - Pointer to ARPNotifyStructure. // // Returns: Nothing. // void NotifyConflictProc(CTEEvent * Event, void *Context) { #if MILLEN // // Call into VIP to VIP_NotifyConflicProc. This will schedule an Appy // event, etc. This is a little sleazy, but we do an INT 20, give the // appropriate index into service table and VIP VxD ID. // // void VIP_NotifyConflictProc(CTEEvent *Event, void *Context); // Event is unused. // _asm { push Context push Context _emit 0xcd _emit 0x20 _emit 0x15 // VIP_NotifyConflictProc (Low) _emit 0x00 // VIP_NotifyConflictProc (High) _emit 0x89 // VIP VxD ID (Low) _emit 0x04 // VIP VxD ID (High) add esp,8 } #else // MILLEN ARPNotifyStruct *NotifyStruct = (ARPNotifyStruct *) Context; PWCHAR stringList[2]; uchar IPAddrBuffer[(sizeof(IPAddr) * 4)]; uchar HWAddrBuffer[(ARP_802_ADDR_LENGTH * 3)]; WCHAR unicodeIPAddrBuffer[((sizeof(IPAddr) * 4) + 1)]; WCHAR unicodeHWAddrBuffer[(ARP_802_ADDR_LENGTH * 3)]; uint i; uint IPAddrCharCount; UNICODE_STRING unicodeString; ANSI_STRING ansiString; PAGED_CODE(); UNREFERENCED_PARAMETER(Event); // // Convert the IP address into a string. // IPAddrCharCount = 0; for (i = 0; i < sizeof(IPAddr); i++) { uint CurrentByte; CurrentByte = NotifyStruct->ans_addr & 0xff; if (CurrentByte > 99) { IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 100) + '0'; CurrentByte %= 100; IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 10) + '0'; CurrentByte %= 10; } else if (CurrentByte > 9) { IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 10) + '0'; CurrentByte %= 10; } IPAddrBuffer[IPAddrCharCount++] = (uchar)CurrentByte + '0'; if (i != (sizeof(IPAddr) - 1)) IPAddrBuffer[IPAddrCharCount++] = '.'; NotifyStruct->ans_addr >>= 8; } // // Convert the hardware address into a string. // for (i = 0; i < NotifyStruct->ans_hwaddrlen; i++) { uchar CurrentHalf; CurrentHalf = NotifyStruct->ans_hwaddr[i] >> 4; HWAddrBuffer[i * 3] = (uchar) (CurrentHalf < 10 ? CurrentHalf + '0' : (CurrentHalf - 10) + 'A'); CurrentHalf = NotifyStruct->ans_hwaddr[i] & 0x0f; HWAddrBuffer[(i * 3) + 1] = (uchar) (CurrentHalf < 10 ? CurrentHalf + '0' : (CurrentHalf - 10) + 'A'); if (i != (NotifyStruct->ans_hwaddrlen - 1)) HWAddrBuffer[(i * 3) + 2] = ':'; } // // Unicode the strings. // *unicodeIPAddrBuffer = *unicodeHWAddrBuffer = UNICODE_NULL; unicodeString.Buffer = unicodeIPAddrBuffer; unicodeString.Length = 0; unicodeString.MaximumLength = sizeof(WCHAR) * ((sizeof(IPAddr) * 4) + 1); ansiString.Buffer = (PCHAR) IPAddrBuffer; ansiString.Length = (USHORT) IPAddrCharCount; ansiString.MaximumLength = (USHORT) IPAddrCharCount; RtlAnsiStringToUnicodeString( &unicodeString, &ansiString, FALSE ); stringList[0] = unicodeIPAddrBuffer; unicodeString.Buffer = unicodeHWAddrBuffer; unicodeString.Length = 0; unicodeString.MaximumLength = sizeof(WCHAR) * (ARP_802_ADDR_LENGTH * 3); ansiString.Buffer = (PCHAR) HWAddrBuffer; ansiString.Length = (ushort) ((NotifyStruct->ans_hwaddrlen * 3) - 1); ansiString.MaximumLength = (ushort)(NotifyStruct->ans_hwaddrlen * 3); RtlAnsiStringToUnicodeString( &unicodeString, &ansiString, FALSE ); stringList[1] = unicodeHWAddrBuffer; // // Kick off a popup and log an event. // if (NotifyStruct->ans_shutoff) { CTELogEvent( IPDriverObject, EVENT_TCPIP_ADDRESS_CONFLICT1, 0, 2, stringList, 0, NULL ); IoRaiseInformationalHardError( STATUS_IP_ADDRESS_CONFLICT1, NULL, NULL ); } else { CTELogEvent( IPDriverObject, EVENT_TCPIP_ADDRESS_CONFLICT2, 0, 2, stringList, 0, NULL ); IoRaiseInformationalHardError( STATUS_IP_ADDRESS_CONFLICT2, NULL, NULL ); } CTEFreeMem(NotifyStruct); #endif // !MILLEN return; } //* DebugConflictProc - Prints some debugging info in case of addr conflicts // Prints the ip and hw addr of the guy causing the conflict // Context - Pointer to ARPNotifyStructure. // // Returns: Nothing. // void DebugConflictProc(void *Context) { ARPNotifyStruct *NotifyStruct = (ARPNotifyStruct *) Context; uchar IPAddrBuffer[(sizeof(IPAddr) * 4)]; uchar HWAddrBuffer[(ARP_802_ADDR_LENGTH * 3)]; uint i; uint IPAddrCharCount; IPAddr ans_addr; // // Save the IP address in case we need it later, then convert into // a string. // ans_addr = NotifyStruct->ans_addr; IPAddrCharCount = 0; for (i = 0; i < sizeof(IPAddr); i++) { uint CurrentByte; CurrentByte = NotifyStruct->ans_addr & 0xff; if (CurrentByte > 99) { IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 100) + '0'; CurrentByte %= 100; IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 10) + '0'; CurrentByte %= 10; } else if (CurrentByte > 9) { IPAddrBuffer[IPAddrCharCount++] = (uchar)(CurrentByte / 10) + '0'; CurrentByte %= 10; } IPAddrBuffer[IPAddrCharCount++] = (uchar) (CurrentByte) + '0'; if (i != (sizeof(IPAddr) - 1)) IPAddrBuffer[IPAddrCharCount++] = '.'; NotifyStruct->ans_addr >>= 8; } IPAddrBuffer[IPAddrCharCount] = '\0'; // // Convert the hardware address into a string. // for (i = 0; i < NotifyStruct->ans_hwaddrlen; i++) { uchar CurrentHalf; CurrentHalf = NotifyStruct->ans_hwaddr[i] >> 4; HWAddrBuffer[i * 3] = (uchar) (CurrentHalf < 10 ? CurrentHalf + '0' : (CurrentHalf - 10) + 'A'); CurrentHalf = NotifyStruct->ans_hwaddr[i] & 0x0f; HWAddrBuffer[(i * 3) + 1] = (uchar) (CurrentHalf < 10 ? CurrentHalf + '0' : (CurrentHalf - 10) + 'A'); if (i != (NotifyStruct->ans_hwaddrlen - 1)) HWAddrBuffer[(i * 3) + 2] = ':'; } HWAddrBuffer[((NotifyStruct->ans_hwaddrlen * 3) - 1)] = '\0'; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL, "TCPIP: Address Conflict: IPAddr %s HWAddr %s \n", IPAddrBuffer, HWAddrBuffer)); return; } //* HandleARPPacket - Process an incoming ARP packet. // // This is the main routine to process an incoming ARP packet. We look at // all ARP frames, and update our cache entry for the source address if one // exists. Else, if we are the target we create an entry if one doesn't // exist. Finally, we'll handle the opcode, responding if this is a request // or sending pending packets if this is a response. // // Entry: Interface - Pointer to interface structure for this adapter. // Header - Pointer to header buffer. // HeaderSize - Size of header buffer. // ARPHdr - ARP packet header. // ARPHdrSize - Size of ARP header. // ProtOffset - Offset into original data field of arp header. // Will be non-zero if we're using SNAP. // // Returns: An NDIS_STATUS value to be returned to the NDIS driver. // NDIS_STATUS HandleARPPacket(ARPInterface * Interface, void *Header, uint HeaderSize, ARPHeader UNALIGNED * ARPHdr, uint ARPHdrSize, uint ProtOffset) { ARPTableEntry *Entry; // Entry in ARP table CTELockHandle LHandle = DISPATCH_LEVEL, TableHandle; RC UNALIGNED *SourceRoute = (RC UNALIGNED *) NULL; // Pointer to Source Route info, if any. uint SourceRouteSize = 0; ulong Now = CTESystemUpTime(); uchar LocalAddr; uint LocalAddrAge; uchar *SHAddr, *DHAddr; IPAddr UNALIGNED *SPAddr, *DPAddr; ENetHeader *ENetHdr; TRHeader *TRHdr; FDDIHeader *FHdr; ARCNetHeader *AHdr; ushort MaxMTU; uint UseSNAP; SetAddrControl *SAC=NULL; ARPIPAddr *CurrentAddr; AddAddrNotifyEvent *DelayedEvent; uint NUCast; DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_RX, (DTEXT("+HandleARPPacket(%x, %x, %d, %x, %d, %d)\n"), Interface, Header, HeaderSize, ARPHdr, ARPHdrSize, ProtOffset)); // Validate the opcode // if ((ARPHdr->ah_opcode != net_short(ARP_REQUEST)) && (ARPHdr->ah_opcode != net_short(ARP_RESPONSE))) { return NDIS_STATUS_NOT_RECOGNIZED; } // We examine all ARP frames. If we find the source address in the ARP table, we'll // update the hardware address and set the state to valid. If we're the // target and he's not in the table, we'll add him. Otherwise if we're the // target and this is a response we'll send any pending packets to him. if (Interface->ai_media != NdisMediumArcnet878_2) { if (ARPHdrSize < sizeof(ARPHeader)) return NDIS_STATUS_NOT_RECOGNIZED; // Frame is too small. if (ARPHdr->ah_hw != net_short(ARP_HW_ENET) && ARPHdr->ah_hw != net_short(ARP_HW_802)) return NDIS_STATUS_NOT_RECOGNIZED; // Wrong HW type if (ARPHdr->ah_hlen != ARP_802_ADDR_LENGTH) return NDIS_STATUS_NOT_RECOGNIZED; // Wrong address length. if (Interface->ai_media == NdisMedium802_3 && Interface->ai_snapsize == 0) UseSNAP = FALSE; else UseSNAP = (ProtOffset != 0); // Figure out SR size on TR. if (Interface->ai_media == NdisMedium802_5) { // Check for source route information. SR is present if the header // size is greater than the standard TR header size. If the SR is // only an RC field, we ignore it because it came from the same // ring which is the same as no SR. if ((HeaderSize - sizeof(TRHeader)) > sizeof(RC)) { SourceRouteSize = HeaderSize - sizeof(TRHeader); SourceRoute = (RC UNALIGNED *) ((uchar *) Header + sizeof(TRHeader)); } } SHAddr = ARPHdr->ah_shaddr; SPAddr = (IPAddr UNALIGNED *) & ARPHdr->ah_spaddr; DHAddr = ARPHdr->ah_dhaddr; DPAddr = (IPAddr UNALIGNED *) & ARPHdr->ah_dpaddr; } else { if (ARPHdrSize < (sizeof(ARPHeader) - ARCNET_ARPHEADER_ADJUSTMENT)) return NDIS_STATUS_NOT_RECOGNIZED; // Frame is too small. if (ARPHdr->ah_hw != net_short(ARP_HW_ARCNET)) return NDIS_STATUS_NOT_RECOGNIZED; // Wrong HW type if (ARPHdr->ah_hlen != 1) return NDIS_STATUS_NOT_RECOGNIZED; // Wrong address length. UseSNAP = FALSE; SHAddr = ARPHdr->ah_shaddr; SPAddr = (IPAddr UNALIGNED *) (SHAddr + 1); DHAddr = (uchar *) SPAddr + sizeof(IPAddr); DPAddr = (IPAddr UNALIGNED *) (DHAddr + 1); } if (ARPHdr->ah_pro != net_short(ARP_ETYPE_IP)) return NDIS_STATUS_NOT_RECOGNIZED; // Unsupported protocol type. if (ARPHdr->ah_plen != sizeof(IPAddr)) return NDIS_STATUS_NOT_RECOGNIZED; LocalAddrAge = ARPADDR_NOT_LOCAL; // First, let's see if we have an address conflict. // LocalAddrAge = IsLocalAddr(Interface, *SPAddr); if (LocalAddrAge != ARPADDR_NOT_LOCAL) { // The source IP address is one of ours. See if the source h/w address // is ours also. if (ARPHdr->ah_hlen != Interface->ai_addrlen || CTEMemCmp(SHAddr, Interface->ai_addr, Interface->ai_addrlen) != 0) { uint Shutoff = FALSE; BOOLEAN PopUP = TRUE; ARPNotifyStruct *NotifyStruct; // This isn't from us; we must have an address conflict somewhere. // We always log an error about this. If what triggered this is a // response and the address in conflict is young, we'll turn off // the interface. if (LocalAddrAge != ARPADDR_OLD_LOCAL && ARPHdr->ah_opcode == net_short(ARP_RESPONSE)) { // Send an arp request with the owner's address to reset the // caches. CTEGetLock(&Interface->ai_lock, &LHandle); // now find the address that is in conflict and get the // corresponding client context. CurrentAddr = &Interface->ai_ipaddr; do { if (CurrentAddr->aia_addr == *SPAddr) { SAC = (SetAddrControl *) CurrentAddr->aia_context; CurrentAddr->aia_context = NULL; break; } CurrentAddr = CurrentAddr->aia_next; } while (CurrentAddr != NULL); CTEFreeLock(&Interface->ai_lock, LHandle); SendARPRequest(Interface, *SPAddr, ARP_RESOLVING_GLOBAL, SHAddr, FALSE); // Send a request. Shutoff = TRUE; // Display the debug information for remote boot/install. // This code should be kept. { ARPNotifyStruct *DebugNotifyStruct; DebugNotifyStruct = CTEAllocMemN(offsetof(ARPNotifyStruct, ans_hwaddr) + ARPHdr->ah_hlen, '1ICT'); if (DebugNotifyStruct != NULL) { DebugNotifyStruct->ans_addr = *SPAddr; DebugNotifyStruct->ans_shutoff = Shutoff; DebugNotifyStruct->ans_hwaddrlen = (uint) ARPHdr->ah_hlen; RtlCopyMemory(DebugNotifyStruct->ans_hwaddr, SHAddr, ARPHdr->ah_hlen); DebugConflictProc(DebugNotifyStruct); CTEFreeMem(DebugNotifyStruct); } } if ((SAC != NULL) && !SAC->StaticAddr) { // This is a dhcp adapter. // Don't display a warning dialog in this case - DHCP will // alert the user // PopUP = FALSE; } // We cannot call completion routine at this time // because completion routine calls back into arp to // reset the address and that may go down into ndis. DelayedEvent = CTEAllocMemN(sizeof(AddAddrNotifyEvent), '2ICT'); if (DelayedEvent) { DelayedEvent->SAC = SAC; DelayedEvent->Address = *SPAddr; DelayedEvent->Status = IP_DUPLICATE_ADDRESS; CTEInitEvent(&DelayedEvent->Event, CompleteIPSetNTEAddrRequestDelayed); CTEScheduleDelayedEvent(&DelayedEvent->Event, DelayedEvent); } else { ASSERT(FALSE); } if (!PopUP) { goto no_dialog; } } else { if (ARPHdr->ah_opcode == net_short(ARP_REQUEST) && (IsLocalAddr(Interface, *DPAddr) == ARPADDR_OLD_LOCAL)) { // Send a response for gratuitous ARP. SendARPReply(Interface, *SPAddr, *DPAddr, SHAddr, SourceRoute, SourceRouteSize, UseSNAP); Shutoff = FALSE; } else if (LocalAddrAge != ARPADDR_OLD_LOCAL) { // our address is still young. we dont need to put the // warning popup as it will be done by the code that // checks for arp response in above if portion of the code. goto no_dialog; } // Else. We have an old local address and received an ARP for // a third address. Fall through and indicate address // conflict. } // Now allocate a structure, and schedule an event to notify // the user. NotifyStruct = CTEAllocMemN(offsetof(ARPNotifyStruct, ans_hwaddr) + ARPHdr->ah_hlen, '3ICT'); if (NotifyStruct != NULL) { NotifyStruct->ans_addr = *SPAddr; NotifyStruct->ans_shutoff = Shutoff; NotifyStruct->ans_hwaddrlen = (uint) ARPHdr->ah_hlen; RtlCopyMemory(NotifyStruct->ans_hwaddr, SHAddr, ARPHdr->ah_hlen); CTEInitEvent(&NotifyStruct->ans_event, NotifyConflictProc); if (Shutoff) { // Delay notification for few seconds. Interface->ai_conflict = NotifyStruct; #if MILLEN Interface->ai_delay = 5; #else Interface->ai_delay = 90; // delay 3 seconds. #endif } else CTEScheduleDelayedEvent(&NotifyStruct->ans_event, NotifyStruct); } no_dialog: ; } return NDIS_STATUS_NOT_RECOGNIZED; } if (!EnableBcastArpReply) { // Check for bogus arp entry NUCast = ((*(SHAddr) & Interface->ai_bcastmask) == Interface->ai_bcastval) ? AI_NONUCAST_INDEX : AI_UCAST_INDEX; if (NUCast == AI_NONUCAST_INDEX) { return NDIS_STATUS_NOT_RECOGNIZED; } } CTEGetLock(&Interface->ai_ARPTblLock, &TableHandle); MaxMTU = Interface->ai_mtu; LocalAddr = ARPLocalAddr(Interface, *DPAddr); // If the sender's address is not remote (i.e. multicast, broadcast, // local, or just invalid), We don't want to create an entry for it or // bother looking it up. // if ((DEST_REMOTE == GetAddrType(*SPAddr))) { Entry = ARPLookup(Interface, *SPAddr); if (Entry == (ARPTableEntry *) NULL) { // Didn't find him, create one if it's for us. The call to ARPLookup // returned with the ARPTblLock held, so we need to free it. CTEFreeLock(&Interface->ai_ARPTblLock, TableHandle); if (LocalAddr) { // If this was an ARP request, we need to create a new // entry for the source info. If this was a reply, it was // unsolicited and we don't create an entry. // if (ARPHdr->ah_opcode != net_short(ARP_RESPONSE)) { Entry = CreateARPTableEntry(Interface, *SPAddr, &LHandle, 0); } } else { return NDIS_STATUS_NOT_RECOGNIZED; // Not in our table, and not for us. } } else { //if this is for userarp, make sure that it is out of the table //while we still have the arp table lock. if (Entry->ate_userarp) { ARPTable *Table; ARPTableEntry *PrevATE, *CurrentATE; uint Index = ARP_HASH(*SPAddr); Table = Interface->ai_ARPTbl; PrevATE = STRUCT_OF(ARPTableEntry, &((*Table)[Index]), ate_next); CurrentATE = PrevATE; while (CurrentATE != (ARPTableEntry *) NULL) { if (CurrentATE == Entry) { break; } PrevATE = CurrentATE; CurrentATE = CurrentATE->ate_next; } if (CurrentATE != NULL) { RemoveARPTableEntry(PrevATE, CurrentATE); Interface->ai_count--; } } CTEFreeLockFromDPC(&Interface->ai_ARPTblLock); LHandle = TableHandle; } } else { // Source address was invalid for an Arp table entry. CTEFreeLock(&Interface->ai_ARPTblLock, TableHandle); Entry = NULL; } // At this point, entry should be valid and we hold the lock on the entry // in LHandle or entry is NULL. if (Entry != (ARPTableEntry *) NULL) { PNDIS_PACKET Packet; // Packet to be sent. DEBUGMSG(DBG_INFO && DBG_ARP && DBG_RX, (DTEXT("HandleARPPacket: resolving addr for ATE %x\n"), Entry)); Entry->ate_refresh = FALSE; // If the entry is already static, we'll want to leave it as static. if (Entry->ate_valid != ALWAYS_VALID) { // OK, we have an entry to use, and hold the lock on it. Fill in the // required fields. switch (Interface->ai_media) { case NdisMedium802_3: // This is an Ethernet. ENetHdr = (ENetHeader *) Entry->ate_addr; RtlCopyMemory(ENetHdr->eh_daddr, SHAddr, ARP_802_ADDR_LENGTH); RtlCopyMemory(ENetHdr->eh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); ENetHdr->eh_type = net_short(ARP_ETYPE_IP); // If we're using SNAP on this entry, copy in the SNAP header. if (UseSNAP) { RtlCopyMemory(&Entry->ate_addr[sizeof(ENetHeader)], ARPSNAP, sizeof(SNAPHeader)); Entry->ate_addrlength = (uchar) (sizeof(ENetHeader) + sizeof(SNAPHeader)); *(ushort UNALIGNED *) & Entry->ate_addr[Entry->ate_addrlength - 2] = net_short(ARP_ETYPE_IP); } else Entry->ate_addrlength = sizeof(ENetHeader); Entry->ate_state = ARP_GOOD; Entry->ate_valid = Now; // Mark last time he was // valid. Entry->ate_useticks = ArpCacheLife; break; case NdisMedium802_5: // This is TR. // For token ring we have to deal with source routing. There's // a special case to handle multiple responses for an all-routes // request - if the entry is currently good and we knew it was // valid recently, we won't update the entry. if (Entry->ate_state != ARP_GOOD || (Now - Entry->ate_valid) > ARP_RESOLVE_TIMEOUT) { TRHdr = (TRHeader *) Entry->ate_addr; // We need to update a TR entry. TRHdr->tr_ac = ARP_AC; TRHdr->tr_fc = ARP_FC; RtlCopyMemory(TRHdr->tr_daddr, SHAddr, ARP_802_ADDR_LENGTH); RtlCopyMemory(TRHdr->tr_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); if (SourceRoute != (RC UNALIGNED *) NULL) { uchar MaxIFieldBits; // We have source routing information. RtlCopyMemory(&Entry->ate_addr[sizeof(TRHeader)], SourceRoute, SourceRouteSize); MaxIFieldBits = (SourceRoute->rc_dlf & RC_LF_MASK) >> LF_BIT_SHIFT; MaxIFieldBits = MIN(MaxIFieldBits, MAX_LF_BITS); MaxMTU = IFieldSize[MaxIFieldBits]; // The new MTU we've computed is the max I-field size, // which doesn't include source routing info but // does include SNAP info. Subtract off the SNAP size. MaxMTU -= sizeof(SNAPHeader); TRHdr->tr_saddr[0] |= TR_RII; (*(RC UNALIGNED *) & Entry->ate_addr[sizeof(TRHeader)]).rc_dlf ^= RC_DIR; // Make sure it's non-broadcast. (*(RC UNALIGNED *) & Entry->ate_addr[sizeof(TRHeader)]).rc_blen &= RC_LENMASK; } RtlCopyMemory(&Entry->ate_addr[sizeof(TRHeader) + SourceRouteSize], ARPSNAP, sizeof(SNAPHeader)); Entry->ate_state = ARP_GOOD; Entry->ate_valid = Now; Entry->ate_useticks = ArpCacheLife; Entry->ate_addrlength = (uchar) (sizeof(TRHeader) + SourceRouteSize + sizeof(SNAPHeader)); *(ushort *) & Entry->ate_addr[Entry->ate_addrlength - 2] = net_short(ARP_ETYPE_IP); } break; case NdisMediumFddi: FHdr = (FDDIHeader *) Entry->ate_addr; FHdr->fh_pri = ARP_FDDI_PRI; RtlCopyMemory(FHdr->fh_daddr, SHAddr, ARP_802_ADDR_LENGTH); RtlCopyMemory(FHdr->fh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); RtlCopyMemory(&Entry->ate_addr[sizeof(FDDIHeader)], ARPSNAP, sizeof(SNAPHeader)); Entry->ate_addrlength = (uchar) (sizeof(FDDIHeader) + sizeof(SNAPHeader)); *(ushort UNALIGNED *) & Entry->ate_addr[Entry->ate_addrlength - 2] = net_short(ARP_ETYPE_IP); Entry->ate_state = ARP_GOOD; Entry->ate_valid = Now; // Mark last time he was // valid. Entry->ate_useticks = ArpCacheLife; break; case NdisMediumArcnet878_2: AHdr = (ARCNetHeader *) Entry->ate_addr; AHdr->ah_saddr = Interface->ai_addr[0]; AHdr->ah_daddr = *SHAddr; AHdr->ah_prot = ARP_ARCPROT_IP; Entry->ate_addrlength = sizeof(ARCNetHeader); Entry->ate_state = ARP_GOOD; Entry->ate_valid = Now; // Mark last time he was // valid. break; default: ASSERT(0); break; } } if (Entry->ate_resolveonly) { ARPControlBlock *ArpContB, *TmpArpContB; ArpContB = Entry->ate_resolveonly; ASSERT(Entry->ate_resolveonly != NULL); while (ArpContB) { ArpRtn rtn; rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = FillARPControlBlock(Interface, Entry, ArpContB); TmpArpContB = ArpContB->next; (*rtn) (ArpContB, STATUS_SUCCESS); ArpContB = TmpArpContB; } Entry->ate_resolveonly = NULL; if (Entry->ate_userarp) { PNDIS_PACKET OldPacket = NULL; OldPacket = Entry->ate_packet; CTEFreeLock(&Entry->ate_lock, LHandle); CTEFreeMem(Entry); if (OldPacket) { IPSendComplete(Interface->ai_context, OldPacket, NDIS_STATUS_SUCCESS); } } else { CTEFreeLock(&Entry->ate_lock, LHandle); } return NDIS_STATUS_SUCCESS; } // At this point we've updated the entry, and we still hold the lock // on it. If we have a packet that was pending to be sent, send it now. // Otherwise just free the lock. Packet = Entry->ate_packet; if (Packet != NULL) { // We have a packet to send. ASSERT(Entry->ate_state == ARP_GOOD); Entry->ate_packet = NULL; DEBUGMSG(DBG_INFO && DBG_ARP && DBG_TX, (DTEXT("ARPHandlePacket: Sending packet %x after resolving ATE %x\n"), Packet, Entry)); if (ARPSendData(Interface, Packet, Entry, LHandle) != NDIS_STATUS_PENDING) { IPSendComplete(Interface->ai_context, Packet, NDIS_STATUS_SUCCESS); } } else { CTEFreeLock(&Entry->ate_lock, LHandle); } } // See if the MTU is less than our local one. This should only happen // in the case of token ring source routing. if (MaxMTU < Interface->ai_mtu) { LLIPAddrMTUChange LAM; LAM.lam_mtu = MaxMTU; LAM.lam_addr = *SPAddr; // It is less. Notify IP. ASSERT(Interface->ai_media == NdisMedium802_5); IPStatus(Interface->ai_context, LLIP_STATUS_ADDR_MTU_CHANGE, &LAM, sizeof(LLIPAddrMTUChange), NULL); } // At this point we've updated the entry (if we had one), and we've freed // all locks. If it's for a local address and it's a request, reply to // it. if (LocalAddr) { // It's for us. if (ARPHdr->ah_opcode == net_short(ARP_REQUEST)) { // It's a request, and we need to respond. SendARPReply(Interface, *SPAddr, *DPAddr, SHAddr, SourceRoute, SourceRouteSize, UseSNAP); } } return NDIS_STATUS_SUCCESS; } //* InitAdapter - Initialize an adapter. // // Called when an adapter is open to finish initialization. We set // up our lookahead size and packet filter, and we're ready to go. // // Entry: // adapter - Pointer to an adapter structure for the adapter to be // initialized. // // Exit: Nothing // void InitAdapter(ARPInterface * Adapter) { NDIS_STATUS Status; CTELockHandle Handle; ARPIPAddr *Addr, *OldAddr; if ((Status = DoNDISRequest(Adapter, NdisRequestSetInformation, OID_GEN_CURRENT_LOOKAHEAD, &ARPLookahead, sizeof(ARPLookahead), NULL, TRUE)) != NDIS_STATUS_SUCCESS) { Adapter->ai_operstatus = INTERFACE_UNINIT; return; } if ((Status = DoNDISRequest(Adapter, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Adapter->ai_pfilter, sizeof(uint), NULL, TRUE)) == NDIS_STATUS_SUCCESS) { uint MediaStatus; Adapter->ai_adminstate = IF_STATUS_UP; Adapter->ai_mediastatus = TRUE; if ((Status = DoNDISRequest(Adapter, NdisRequestQueryInformation, OID_GEN_MEDIA_CONNECT_STATUS, &MediaStatus, sizeof(MediaStatus), NULL, TRUE)) == NDIS_STATUS_SUCCESS) { if (MediaStatus == NdisMediaStateDisconnected) { Adapter->ai_mediastatus = FALSE; } } ARPUpdateOperStatus(Adapter); // Now walk through any addresses we have and ARP for them , only when ArpRetryCount != 0. if (ArpRetryCount) { CTEGetLock(&Adapter->ai_lock, &Handle); OldAddr = NULL; Addr = &Adapter->ai_ipaddr; do { if (!IP_ADDR_EQUAL(Addr->aia_addr, NULL_IP_ADDR)) { IPAddr Address = Addr->aia_addr; Addr->aia_age = ArpRetryCount; CTEFreeLock(&Adapter->ai_lock, Handle); OldAddr = Addr; SendARPRequest(Adapter, Address, ARP_RESOLVING_GLOBAL, NULL, TRUE); CTEGetLock(&Adapter->ai_lock, &Handle); Addr = &Adapter->ai_ipaddr; while (Addr != OldAddr && Addr != NULL) { Addr = Addr->aia_next; } if (Addr != NULL) { Addr = Addr->aia_next; } } else { Addr = Addr->aia_next; } } while (Addr != NULL); CTEFreeLock(&Adapter->ai_lock, Handle); } } else { KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_ERROR_LEVEL, "**InitAdapter setting FAILED\n")); Adapter->ai_operstatus = INTERFACE_UNINIT; } } //** ARPOAComplete - ARP Open adapter complete handler. // // This routine is called by the NDIS driver when an open adapter // call completes. Presumably somebody is blocked waiting for this, so // we'll wake him up now. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Status - Final status of command. // ErrorStatus - Final error status. // // Exit: Nothing. // void NDIS_API ARPOAComplete(NDIS_HANDLE Handle, NDIS_STATUS Status, NDIS_STATUS ErrorStatus) { ARPInterface *ai = (ARPInterface *) Handle; // For compiler. UNREFERENCED_PARAMETER(ErrorStatus); CTESignal(&ai->ai_block, (uint) Status); // Wake him up, and return status. } //** ARPCAComplete - ARP close adapter complete handler. // // This routine is called by the NDIS driver when a close adapter // call completes. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Status - Final status of command. // // Exit: Nothing. // void NDIS_API ARPCAComplete(NDIS_HANDLE Handle, NDIS_STATUS Status) { ARPInterface *ai = (ARPInterface *) Handle; // For compiler. CTESignal(&ai->ai_block, (uint) Status); // Wake him up, and return status. } //** ARPSendComplete - ARP send complete handler. // // This routine is called by the NDIS driver when a send completes. // This is a pretty time critical operation, we need to get through here // quickly. We'll strip our buffer off and put it back, and call the upper // later send complete handler. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Packet - A pointer to the packet that was sent. // Status - Final status of command. // // Exit: Nothing. // void NDIS_API ARPSendComplete(NDIS_HANDLE Handle, PNDIS_PACKET Packet, NDIS_STATUS Status) { ARPInterface *Interface = (ARPInterface *) Handle; PacketContext *PC = (PacketContext *) Packet->ProtocolReserved; PNDIS_BUFFER Buffer; uint DataLength; ulong Proc; Proc = KeGetCurrentProcessorNumber(); Interface->ai_qlen[Proc].ai_qlen--; if (Status == NDIS_STATUS_SUCCESS) { DataLength = Packet->Private.TotalLength; if (!(Packet->Private.ValidCounts)) { NdisQueryPacket(Packet, NULL, NULL, NULL,&DataLength); } Interface->ai_outoctets += DataLength; } else { if (Status == NDIS_STATUS_RESOURCES) Interface->ai_outdiscards++; else Interface->ai_outerrors++; } #if BACK_FILL // Get first buffer on packet. if (Interface->ai_media == NdisMedium802_3) { PMDL TmpMdl = NULL; uint HdrSize; NdisQueryPacket(Packet, NULL, NULL, &TmpMdl, NULL); if (TmpMdl->MdlFlags & MDL_NETWORK_HEADER) { HdrSize = sizeof(ENetHeader); if (((PacketContext*) Packet->ProtocolReserved)->pc_common.pc_flags & PACKET_FLAG_SNAP) HdrSize += Interface->ai_snapsize; TmpMdl->MappedSystemVa = (PVOID) (((ULONG_PTR) TmpMdl->MappedSystemVa) + HdrSize); TmpMdl->ByteOffset += HdrSize; TmpMdl->ByteCount -= HdrSize; } else { NdisUnchainBufferAtFront(Packet, &Buffer); FreeARPBuffer(Interface, Buffer); // Free it up. } } else { NdisUnchainBufferAtFront(Packet, &Buffer); FreeARPBuffer(Interface, Buffer); // Free it up. } #else // Get first buffer on packet. NdisUnchainBufferAtFront(Packet, &Buffer); ASSERT(Buffer); FreeARPBuffer(Interface, Buffer); // Free it up. #endif if (PC->pc_common.pc_owner != PACKET_OWNER_LINK) { // We don't own this one. IPSendComplete(Interface->ai_context, Packet, Status); return; } // This packet belongs to us, so free it. NdisFreePacket(Packet); } //** ARPTDComplete - ARP transfer data complete handler. // // This routine is called by the NDIS driver when a transfer data // call completes. Since we never transfer data ourselves, this must be // from the upper layer. We'll just call his routine and let him deal // with it. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Packet - A pointer to the packet used for the TD. // Status - Final status of command. // BytesCopied - Count of bytes copied. // // Exit: Nothing. // void NDIS_API ARPTDComplete(NDIS_HANDLE Handle, PNDIS_PACKET Packet, NDIS_STATUS Status, uint BytesCopied) { ARPInterface *ai = (ARPInterface *) Handle; IPTDComplete(ai->ai_context, Packet, Status, BytesCopied); } //** ARPResetComplete - ARP reset complete handler. // // This routine is called by the NDIS driver when a reset completes. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Status - Final status of command. // // Exit: Nothing. // void NDIS_API ARPResetComplete(NDIS_HANDLE Handle, NDIS_STATUS Status) { ARPInterface *ai = (ARPInterface *) Handle; UNREFERENCED_PARAMETER(Status); KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ArpResetComplete on %x\n", ai->ai_context)); IPReset(ai->ai_context); } //** ARPRequestComplete - ARP request complete handler. // // This routine is called by the NDIS driver when a general request // completes. If ARP blocks on a request, we'll just give a wake up // to whoever's blocked on this request. Else if it is a non-blocking // request, we extract the request complete callback fn in the request // call it, and then deallocate the request block (that is on the heap) // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Request - A pointer to the request that completed. // Status - Final status of command. // // Exit: Nothing. // void NDIS_API ARPRequestComplete(NDIS_HANDLE Handle, PNDIS_REQUEST pRequest, NDIS_STATUS Status) { RequestBlock *rb = STRUCT_OF(RequestBlock, pRequest, Request); DBG_UNREFERENCED_PARAMETER(Handle); DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_REQUEST, (DTEXT("+ARPRequestComplete(%x, %x, %x) RequestBlock %x\n"), Handle, pRequest, Status, rb)); if (rb->Blocking) { // Request through BLOCKING DoNDISRequest // Signal the blocked guy here CTESignal(&rb->Block, (uint) Status); if (InterlockedDecrement( (PLONG) &rb->RefCount) == 0) { CTEFreeMem(rb); } } else { ReqInfoBlock *rib; RCCALL reqcallback; // Request through NON-BLOCKING DoNDISRequest // Extract the callback fn pointer & params if (pRequest->RequestType == NdisRequestSetInformation) rib = STRUCT_OF(ReqInfoBlock, pRequest->DATA.SET_INFORMATION.InformationBuffer, RequestInfo); else rib = STRUCT_OF(ReqInfoBlock, pRequest->DATA.QUERY_INFORMATION.InformationBuffer, RequestInfo); reqcallback = rib->ReqCompleteCallback; if (reqcallback) reqcallback(rib); // Free ARP memory associated with request KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPRequestComplete: Freeing mem at pRequest = %08X\n", rb)); CTEFreeMem(rb); } DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_REQUEST, (DTEXT("-ARPRequestComplete [%x]\n"), Status)); } //** ARPRcv - ARP receive data handler. // // This routine is called when data arrives from the NDIS driver. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Context - NDIS context to be used for TD. // Header - Pointer to header // HeaderSize - Size of header // Data - Pointer to buffer of received data // Size - Byte count of data in buffer. // TotalSize - Byte count of total packet size. // // Exit: Status indicating whether or not we took the packet. // NDIS_STATUS NDIS_API ARPRcv(NDIS_HANDLE Handle, NDIS_HANDLE Context, void *Header, uint HeaderSize, void *Data, uint Size, uint TotalSize) { ARPInterface *Interface = Handle; NDIS_STATUS status; PINT OrigPacket = NULL; //get the original packet (if any) //this is required to make task offload work //note: We shall hack the pClientCount Field //to point to the packet as a short term solution //to avoid changing all atm - ip interface changes if (Interface->ai_OffloadFlags || Interface->ai_IPSecOffloadFlags) { OrigPacket = (PINT) NdisGetReceivedPacket(Interface->ai_handle, Context); } //Call the new interface with null mdl and context pointers status = ARPRcvIndicationNew(Handle, Context, Header, HeaderSize, Data, Size, TotalSize, NULL, OrigPacket); return status; } //** ARPRcvPacket - ARP receive data handler. // // This routine is called when data arrives from the NDIS driver. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Packet - Contains the incoming frame // // Returns number of upper layer folks latching on to this frame // // INT ARPRcvPacket(NDIS_HANDLE Handle, PNDIS_PACKET Packet) { UINT HeaderBufferSize = NDIS_GET_PACKET_HEADER_SIZE(Packet); UINT firstbufferLength, bufferLength, LookAheadBufferSize; PNDIS_BUFFER pFirstBuffer; PUCHAR headerBuffer; NTSTATUS ntStatus; INT ClientCnt = 0; // // Query the number of buffers, the first MDL's descriptor and the packet length // NdisGetFirstBufferFromPacket(Packet, // packet &pFirstBuffer, // first buffer descriptor &headerBuffer, // ptr to the start of packet &firstbufferLength, // length of the header+lookahead &bufferLength); // length of the bytes in the buffers // // ReceiveContext is the packet itself // LookAheadBufferSize = firstbufferLength - HeaderBufferSize; ntStatus = ARPRcvIndicationNew(Handle, Packet, headerBuffer, HeaderBufferSize, headerBuffer + HeaderBufferSize, // LookaheadBuffer LookAheadBufferSize, // LookaheadBufferSize bufferLength - HeaderBufferSize, // PacketSize - since // the whole packet is // indicated pFirstBuffer, // pMdl &ClientCnt // tdi client count ); return ClientCnt; } //** ARPRcvIndicationNew - ARP receive data handler. // // This routine is called when data arrives from the NDIS driver. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // Context - NDIS context to be used for TD. // Header - Pointer to header // HeaderSize - Size of header // Data - Pointer to buffer of received data // Size - Byte count of data in buffer. // TotalSize - Byte count of total packet size. // pMdl - NDIS_BUFFER of incoming frame // pClientCnt address to return the clinet counts // // Exit: Status indicating whether or not we took the packet. // NDIS_STATUS NDIS_API ARPRcvIndicationNew(NDIS_HANDLE Handle, NDIS_HANDLE Context, void *Header, uint HeaderSize, void *Data, uint Size, uint TotalSize, PNDIS_BUFFER pNdisBuffer, PINT pClientCnt) { ARPInterface *Interface = Handle; // Interface for this driver. ENetHeader UNALIGNED *EHdr = (ENetHeader UNALIGNED *) Header; SNAPHeader UNALIGNED *SNAPHdr; ushort type; // Protocol type uint ProtOffset; // Offset in Data to non-media info. uint NUCast; // TRUE if the frame is not a unicast frame. if ((Interface->ai_operstatus == INTERFACE_UP) && HeaderSize >= (uint) Interface->ai_hdrsize) { // Per RFC 1213 and its successors, the inoctets count includes // the MAC header bytes. Interface->ai_inoctets += HeaderSize + TotalSize; NUCast = ((*((uchar UNALIGNED *) EHdr + Interface->ai_bcastoff) & Interface->ai_bcastmask) == Interface->ai_bcastval) ? AI_NONUCAST_INDEX : AI_UCAST_INDEX; if ((Interface->ai_promiscuous) && (!NUCast)) { // AI_UCAST_INDEX = 0 switch (Interface->ai_media) { case NdisMedium802_3:{ // Enet if (Interface->ai_addrlen != ARP_802_ADDR_LENGTH || CTEMemCmp(EHdr->eh_daddr, Interface->ai_addr, ARP_802_ADDR_LENGTH) != 0) { NUCast = AI_PROMIS_INDEX; } break; } case NdisMedium802_5:{ // token ring TRHeader UNALIGNED *THdr = (TRHeader UNALIGNED *) Header; if (Interface->ai_addrlen != ARP_802_ADDR_LENGTH || CTEMemCmp(THdr->tr_daddr, Interface->ai_addr, ARP_802_ADDR_LENGTH) != 0) { NUCast = AI_PROMIS_INDEX; } break; } case NdisMediumFddi:{ // FDDI FDDIHeader UNALIGNED *FHdr = (FDDIHeader UNALIGNED *) Header; if (Interface->ai_addrlen != ARP_802_ADDR_LENGTH || CTEMemCmp(FHdr->fh_daddr, Interface->ai_addr, ARP_802_ADDR_LENGTH) != 0) { NUCast = AI_PROMIS_INDEX; } break; } case NdisMediumArcnet878_2:{ // ArcNet DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_RX, (DTEXT("-ARPRcvIndicationNew [NOT_RECOGNIZED]\n"))); return NDIS_STATUS_NOT_RECOGNIZED; break; } default: ASSERT(0); Interface->ai_outerrors++; DEBUGMSG(DBG_TRACE && DBG_ARP && DBG_RX, (DTEXT("-ARPRcvIndicationNew [UNSUPPORTED_MEDIA]\n"))); return NDIS_STATUS_UNSUPPORTED_MEDIA; } } if ((Interface->ai_media == NdisMedium802_3) && (type = net_short(EHdr->eh_type)) >= MIN_ETYPE) { ProtOffset = 0; } else if (Interface->ai_media != NdisMediumArcnet878_2) { SNAPHdr = (SNAPHeader UNALIGNED *) Data; if (Size >= sizeof(SNAPHeader) && SNAPHdr->sh_dsap == SNAP_SAP && SNAPHdr->sh_ssap == SNAP_SAP && SNAPHdr->sh_ctl == SNAP_UI) { type = net_short(SNAPHdr->sh_etype); ProtOffset = sizeof(SNAPHeader); } else { //handle XID/TEST here. Interface->ai_uknprotos++; return NDIS_STATUS_NOT_RECOGNIZED; } } else { ARCNetHeader UNALIGNED *AH = (ARCNetHeader UNALIGNED *) Header; ProtOffset = 0; if (AH->ah_prot == ARP_ARCPROT_IP) type = ARP_ETYPE_IP; else if (AH->ah_prot == ARP_ARCPROT_ARP) type = ARP_ETYPE_ARP; else type = 0; } if (type == ARP_ETYPE_IP) { (Interface->ai_inpcount[NUCast])++; ASSERT (KeGetCurrentIrql() <= DISPATCH_LEVEL); IPRcvPacket(Interface->ai_context, (uchar *) Data + ProtOffset, Size - ProtOffset, TotalSize - ProtOffset, Context, ProtOffset, NUCast, HeaderSize, pNdisBuffer, (PUINT) pClientCnt, NULL); return NDIS_STATUS_SUCCESS; } else { if (type == ARP_ETYPE_ARP) { (Interface->ai_inpcount[NUCast])++; return HandleARPPacket(Interface, Header, HeaderSize, (ARPHeader *) ((uchar *) Data + ProtOffset), Size - ProtOffset, ProtOffset); } else { Interface->ai_uknprotos++; return NDIS_STATUS_NOT_RECOGNIZED; } } } else { // Interface is marked as down. return NDIS_STATUS_NOT_RECOGNIZED; } } //** ARPRcvComplete - ARP receive complete handler. // // This routine is called by the NDIS driver after some number of // receives. In some sense, it indicates 'idle time'. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // // Exit: Nothing. // void NDIS_API ARPRcvComplete(NDIS_HANDLE Handle) { UNREFERENCED_PARAMETER(Handle); IPRcvComplete(); } //** ARPStatus - ARP status handler. // // Called by the NDIS driver when some sort of status change occurs. // We take action depending on the type of status. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // GStatus - General type of status that caused the call. // Status - Pointer to a buffer of status specific information. // StatusSize - Size of the status buffer. // // Exit: Nothing. // void NDIS_API ARPStatus(NDIS_HANDLE Handle, NDIS_STATUS GStatus, void *Status, uint StatusSize) { ARPInterface *ai = (ARPInterface *) Handle; // // ndis calls this sometimes even before ip interface is created. // if ((ai->ai_context) && (ai->ai_operstatus != INTERFACE_INIT)) { IPStatus(ai->ai_context, GStatus, Status, StatusSize, NULL); switch (GStatus) { //reflect media connect/disconnect status in //operstatus for query purpose case NDIS_STATUS_MEDIA_CONNECT: ai->ai_mediastatus = TRUE; ARPUpdateOperStatus(ai); break; case NDIS_STATUS_MEDIA_DISCONNECT: ai->ai_mediastatus = FALSE; ARPUpdateOperStatus(ai); break; default: break; } } } //** ARPStatusComplete - ARP status complete handler. // // A routine called by the NDIS driver so that we can do postprocessing // after a status event. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // // Exit: Nothing. // void NDIS_API ARPStatusComplete(NDIS_HANDLE Handle) { UNREFERENCED_PARAMETER(Handle); } //** ARPPnPEvent - ARP PnPEvent handler. // // Called by the NDIS driver when PnP or PM events occurs. // // Entry: // Handle - The binding handle we specified (really a pointer to an AI). // NetPnPEvent - This is a pointer to a NET_PNP_EVENT that describes // the PnP indication. // // Exit: // Just call into IP and return status. // NDIS_STATUS ARPPnPEvent(NDIS_HANDLE Handle, PNET_PNP_EVENT NetPnPEvent) { ARPInterface *ai = (ARPInterface *) Handle; // // ndis can calls this sometimes even before ip interface is created. // if (ai && !ai->ai_context) { return STATUS_SUCCESS; } else { return IPPnPEvent(ai ? ai->ai_context : NULL, NetPnPEvent); } } //** ARPSetNdisRequest - ARP Ndisrequest handler. // // Called by the upper driver to set the packet filter for the interface. // // Entry: // Context - Context value we gave to IP (really a pointer to an AI). // OID - Object ID to set/unset // On - Set_if, clear_if or clear_card // // Exit: // returns status. // NDIS_STATUS __stdcall ARPSetNdisRequest(void *Context, NDIS_OID OID, uint On) { int Status; ARPInterface *Interface = (ARPInterface *) Context; if (On == SET_IF) { Interface->ai_pfilter |= OID; if (OID == NDIS_PACKET_TYPE_PROMISCUOUS) { Interface->ai_promiscuous = 1; } Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Interface->ai_pfilter, sizeof(uint), NULL, TRUE); } else { // turn off Interface->ai_pfilter &= ~(OID); if (OID == NDIS_PACKET_TYPE_PROMISCUOUS) { Interface->ai_promiscuous = 0; } Status = DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Interface->ai_pfilter, sizeof(uint), NULL, TRUE); } return Status; } //** ARPPnPComplete - ARP PnP complete handler. // // Called by the upper driver to do the post processing of pnp event. // // Entry: // Context - Context value we gave to IP (really a pointer to an AI). // Status - Status code of the pnp operation. // NetPnPEvent - This is a pointer to a NET_PNP_EVENT that describes // the PnP indication. // // Exit: // returns nothing. // void __stdcall ARPPnPComplete(void *Context, NDIS_STATUS Status, PNET_PNP_EVENT NetPnPEvent) { ARPInterface *Interface = (ARPInterface *) Context; NdisCompletePnPEvent(Status, (Interface ? Interface->ai_handle : NULL), NetPnPEvent); } extern void NDIS_API ARPBindAdapter(PNDIS_STATUS RetStatus, NDIS_HANDLE BindContext, PNDIS_STRING AdapterName, PVOID SS1, PVOID SS2); extern void NDIS_API ARPUnbindAdapter(PNDIS_STATUS RetStatus, NDIS_HANDLE ProtBindContext, NDIS_HANDLE UnbindContext); extern void NDIS_API ARPUnloadProtocol(void); extern void ArpUnload(PDRIVER_OBJECT); //* ARPReadNext - Read the next entry in the ARP table. // // Called by the GetInfo code to read the next ATE in the table. We assume // the context passed in is valid, and the caller has the ARP TableLock. // // Input: Context - Pointer to a IPNMEContext. // Interface - Pointer to interface for table to read on. // Buffer - Pointer to an IPNetToMediaEntry structure. // // Returns: TRUE if more data is available to be read, FALSE is not. // uint ARPReadNext(void *Context, ARPInterface * Interface, void *Buffer) { IPNMEContext *NMContext = (IPNMEContext *) Context; IPNetToMediaEntry *IPNMEntry = (IPNetToMediaEntry *) Buffer; CTELockHandle Handle; ARPTableEntry *CurrentATE; uint i; ARPTable *Table = Interface->ai_ARPTbl; uint AddrOffset; CurrentATE = NMContext->inc_entry; // Fill in the buffer. CTEGetLock(&CurrentATE->ate_lock, &Handle); IPNMEntry->inme_index = Interface->ai_index; IPNMEntry->inme_physaddrlen = Interface->ai_addrlen; switch (Interface->ai_media) { case NdisMedium802_3: AddrOffset = 0; break; case NdisMedium802_5: AddrOffset = offsetof(struct TRHeader, tr_daddr); break; case NdisMediumFddi: AddrOffset = offsetof(struct FDDIHeader, fh_daddr); break; case NdisMediumArcnet878_2: AddrOffset = offsetof(struct ARCNetHeader, ah_daddr); break; default: AddrOffset = 0; break; } RtlCopyMemory(IPNMEntry->inme_physaddr, &CurrentATE->ate_addr[AddrOffset], Interface->ai_addrlen); IPNMEntry->inme_addr = CurrentATE->ate_dest; if (CurrentATE->ate_state == ARP_GOOD) IPNMEntry->inme_type = (CurrentATE->ate_valid == ALWAYS_VALID ? INME_TYPE_STATIC : INME_TYPE_DYNAMIC); else IPNMEntry->inme_type = INME_TYPE_INVALID; CTEFreeLock(&CurrentATE->ate_lock, Handle); // We've filled it in. Now update the context. if (CurrentATE->ate_next != NULL) { NMContext->inc_entry = CurrentATE->ate_next; return TRUE; } else { // The next ATE is NULL. Loop through the ARP Table looking for a new // one. i = NMContext->inc_index + 1; while (i < ARP_TABLE_SIZE) { if ((*Table)[i] != NULL) { NMContext->inc_entry = (*Table)[i]; NMContext->inc_index = i; return TRUE; break; } else i++; } NMContext->inc_index = 0; NMContext->inc_entry = NULL; return FALSE; } } //* ARPValidateContext - Validate the context for reading an ARP table. // // Called to start reading an ARP table sequentially. We take in // a context, and if the values are 0 we return information about the // first route in the table. Otherwise we make sure that the context value // is valid, and if it is we return TRUE. // We assume the caller holds the ARPInterface lock. // // Input: Context - Pointer to a RouteEntryContext. // Interface - Pointer to an interface // Valid - Where to return information about context being // valid. // // Returns: TRUE if more data to be read in table, FALSE if not. *Valid set // to TRUE if input context is valid // uint ARPValidateContext(void *Context, ARPInterface * Interface, uint * Valid) { IPNMEContext *NMContext = (IPNMEContext *) Context; uint i; ARPTableEntry *TargetATE; ARPTableEntry *CurrentATE; ARPTable *Table = Interface->ai_ARPTbl; i = NMContext->inc_index; TargetATE = NMContext->inc_entry; // If the context values are 0 and NULL, we're starting from the beginning. if (i == 0 && TargetATE == NULL) { *Valid = TRUE; do { if ((CurrentATE = (*Table)[i]) != NULL) { break; } i++; } while (i < ARP_TABLE_SIZE); if (CurrentATE != NULL) { NMContext->inc_index = i; NMContext->inc_entry = CurrentATE; return TRUE; } else return FALSE; } else { // We've been given a context. We just need to make sure that it's // valid. if (i < ARP_TABLE_SIZE) { CurrentATE = (*Table)[i]; while (CurrentATE != NULL) { if (CurrentATE == TargetATE) { *Valid = TRUE; return TRUE; break; } else { CurrentATE = CurrentATE->ate_next; } } } // If we get here, we didn't find the matching ATE. *Valid = FALSE; return FALSE; } } #define IFE_FIXED_SIZE offsetof(struct IFEntry, if_descr) //* ARPQueryInfo - ARP query information handler. // // Called to query information about the ARP table or statistics about the // actual interface. // // Input: IFContext - Interface context (pointer to an ARPInterface). // ID - TDIObjectID for object. // Buffer - Buffer to put data into. // Size - Pointer to size of buffer. On return, filled with // bytes copied. // Context - Pointer to context block. // // Returns: Status of attempt to query information. // int __stdcall ARPQueryInfo(void *IFContext, TDIObjectID * ID, PNDIS_BUFFER Buffer, uint * Size, void *Context) { ARPInterface *AI = (ARPInterface *) IFContext; uint Offset = 0; uint BufferSize = *Size; CTELockHandle Handle; uint ContextValid, DataLeft; uint BytesCopied = 0; uchar InfoBuff[sizeof(IFEntry)]; uint Entity; uint Instance; BOOLEAN fStatus; long QueueLength = 0; uint i; DEBUGMSG(DBG_TRACE && DBG_QUERYINFO, (DTEXT("+ARPQueryInfo(%x, %x, %x, %x, %x)\n"), IFContext, ID, Buffer, Size, Context)); Entity = ID->toi_entity.tei_entity; Instance = ID->toi_entity.tei_instance; // TCPTRACE(("ARPQueryInfo: AI %lx, Instance %lx, ai_atinst %lx, ai_ifinst %lx\n", // AI, Instance, AI->ai_atinst, AI->ai_ifinst )); // First, make sure it's possibly an ID we can handle. if ((Entity != AT_ENTITY || Instance != AI->ai_atinst) && (Entity != IF_ENTITY || Instance != AI->ai_ifinst)) { return TDI_INVALID_REQUEST; } *Size = 0; // In case of an error. if (ID->toi_type != INFO_TYPE_PROVIDER) return TDI_INVALID_PARAMETER; if (ID->toi_class == INFO_CLASS_GENERIC) { if (ID->toi_id == ENTITY_TYPE_ID) { // He's trying to see what type we are. if (BufferSize >= sizeof(uint)) { *(uint *) & InfoBuff[0] = (Entity == AT_ENTITY) ? AT_ARP : IF_MIB; fStatus = CopyToNdisSafe(Buffer, NULL, InfoBuff, sizeof(uint), &Offset); if (fStatus == FALSE) { return TDI_NO_RESOURCES; } *Size = sizeof(uint); return TDI_SUCCESS; } else return TDI_BUFFER_TOO_SMALL; } return TDI_INVALID_PARAMETER; } // Might be able to handle this. if (Entity == AT_ENTITY) { // It's an address translation object. It could be a MIB object or // an implementation specific object (the generic objects were handled // above). if (ID->toi_class == INFO_CLASS_IMPLEMENTATION) { ARPPArpAddr *PArpAddr; // It's an implementation specific ID. The only ones we handle // are the PARP_COUNT_ID and the PARP_ENTRY ID. if (ID->toi_id == AT_ARP_PARP_COUNT_ID) { // He wants to know the count. Just return that to him. if (BufferSize >= sizeof(uint)) { CTEGetLock(&AI->ai_lock, &Handle); fStatus = CopyToNdisSafe(Buffer, NULL, (uchar *) & AI->ai_parpcount, sizeof(uint), &Offset); CTEFreeLock(&AI->ai_lock, Handle); if (fStatus == FALSE) { return TDI_NO_RESOURCES; } *Size = sizeof(uint); return TDI_SUCCESS; } else return TDI_BUFFER_TOO_SMALL; } if (ID->toi_id != AT_ARP_PARP_ENTRY_ID) return TDI_INVALID_PARAMETER; // It's for Proxy ARP entries. The context should be either NULL // or a pointer to the next one to be read. CTEGetLock(&AI->ai_lock, &Handle); PArpAddr = *(ARPPArpAddr **) Context; if (PArpAddr != NULL) { ARPPArpAddr *CurrentPARP; // Loop through the P-ARP addresses on the interface, and // see if we can find this one. CurrentPARP = AI->ai_parpaddr; while (CurrentPARP != NULL) { if (CurrentPARP == PArpAddr) break; else CurrentPARP = CurrentPARP->apa_next; } // If we found a match, PARPAddr points to where to begin // reading. Otherwise, fail the request. if (CurrentPARP == NULL) { // Didn't find a match, so fail the request. CTEFreeLock(&AI->ai_lock, Handle); return TDI_INVALID_PARAMETER; } } else PArpAddr = AI->ai_parpaddr; // PARPAddr points to the next entry to put in the buffer, if // there is one. while (PArpAddr != NULL) { if ((int)(BufferSize - BytesCopied) >= (int)sizeof(ProxyArpEntry)) { ProxyArpEntry *TempPArp; TempPArp = (ProxyArpEntry *) InfoBuff; TempPArp->pae_status = PAE_STATUS_VALID; TempPArp->pae_addr = PArpAddr->apa_addr; TempPArp->pae_mask = PArpAddr->apa_mask; BytesCopied += sizeof(ProxyArpEntry); fStatus = CopyToNdisSafe(Buffer, &Buffer, (uchar *) TempPArp, sizeof(ProxyArpEntry), &Offset); if (fStatus == FALSE) { CTEFreeLock(&AI->ai_lock, Handle); return TDI_NO_RESOURCES; } PArpAddr = PArpAddr->apa_next; } else break; } // We're done copying. Free the lock and return the correct // status. CTEFreeLock(&AI->ai_lock, Handle); *Size = BytesCopied; **(ARPPArpAddr ***) & Context = PArpAddr; return(PArpAddr == NULL) ? TDI_SUCCESS : TDI_BUFFER_OVERFLOW; } if (ID->toi_id == AT_MIB_ADDRXLAT_INFO_ID) { AddrXlatInfo *AXI; // It's for the count. Just return the number of entries in the // table. if (BufferSize >= sizeof(AddrXlatInfo)) { *Size = sizeof(AddrXlatInfo); AXI = (AddrXlatInfo *) InfoBuff; AXI->axi_count = AI->ai_count; AXI->axi_index = AI->ai_index; fStatus = CopyToNdisSafe(Buffer, NULL, (uchar *) AXI, sizeof(AddrXlatInfo), &Offset); if (fStatus == FALSE) { return TDI_NO_RESOURCES; } *Size = sizeof(AddrXlatInfo); return TDI_SUCCESS; } else return TDI_BUFFER_TOO_SMALL; } if (ID->toi_id == AT_MIB_ADDRXLAT_ENTRY_ID) { // He's trying to read the table. // Make sure we have a valid context. CTEGetLock(&AI->ai_ARPTblLock, &Handle); DataLeft = ARPValidateContext(Context, AI, &ContextValid); // If the context is valid, we'll continue trying to read. if (!ContextValid) { CTEFreeLock(&AI->ai_ARPTblLock, Handle); return TDI_INVALID_PARAMETER; } while (DataLeft) { // The invariant here is that there is data in the table to // read. We may or may not have room for it. So DataLeft // is TRUE, and BufferSize - BytesCopied is the room left // in the buffer. if ((int)(BufferSize - BytesCopied) >= (int)sizeof(IPNetToMediaEntry)) { DataLeft = ARPReadNext(Context, AI, InfoBuff); BytesCopied += sizeof(IPNetToMediaEntry); fStatus = CopyToNdisSafe(Buffer, &Buffer, InfoBuff, sizeof(IPNetToMediaEntry), &Offset); if (fStatus == FALSE) { CTEFreeLock(&AI->ai_ARPTblLock, Handle); return(TDI_NO_RESOURCES); } } else break; } *Size = BytesCopied; CTEFreeLock(&AI->ai_ARPTblLock, Handle); return(!DataLeft ? TDI_SUCCESS : TDI_BUFFER_OVERFLOW); } return TDI_INVALID_PARAMETER; } if (ID->toi_class != INFO_CLASS_PROTOCOL) return TDI_INVALID_PARAMETER; // He must be asking for interface level information. See if we support // what he's asking for. if (ID->toi_id == IF_MIB_STATS_ID) { IFEntry *IFE = (IFEntry *) InfoBuff; uint speed; // He's asking for statistics. Make sure his buffer is at least big // enough to hold the fixed part. if (BufferSize < IFE_FIXED_SIZE) { return TDI_BUFFER_TOO_SMALL; } // He's got enough to hold the fixed part. Build the IFEntry structure, // and copy it to his buffer. IFE->if_index = AI->ai_index; switch (AI->ai_media) { case NdisMedium802_3: IFE->if_type = IF_TYPE_ETHERNET_CSMACD; break; case NdisMedium802_5: IFE->if_type = IF_TYPE_ISO88025_TOKENRING; break; case NdisMediumFddi: IFE->if_type = IF_TYPE_FDDI; break; case NdisMediumArcnet878_2: default: IFE->if_type = IF_TYPE_OTHER; break; } IFE->if_mtu = AI->ai_mtu; // Some adapters support dynamic speed settings and causes this // query to return a different speed from the Networks Connection // folder. Therefore, we will requery the speed of the // interface. Should we update the ai_speed? Anf if so, do we update // if_speed as well? IFE->if_speed = AI->ai_speed; if (AI->ai_mediastatus == TRUE) { if (DoNDISRequest( AI, NdisRequestQueryInformation, OID_GEN_LINK_SPEED, &speed, sizeof(speed), NULL, TRUE) == NDIS_STATUS_SUCCESS) { // Update to real value we want to return. speed *= 100L; IFE->if_speed = speed; } else { // Should we fail, or just update with known speed. IFE->if_speed = AI->ai_speed; } } IFE->if_physaddrlen = AI->ai_addrlen; RtlCopyMemory(IFE->if_physaddr, AI->ai_addr, AI->ai_addrlen); IFE->if_adminstatus = (uint) AI->ai_adminstate; if (AI->ai_operstatus == INTERFACE_UP) { IFE->if_operstatus = IF_OPER_STATUS_OPERATIONAL; } else { // DOWN,INIT, and UNINIT all count as non-operational IFE->if_operstatus = IF_OPER_STATUS_NON_OPERATIONAL; } IFE->if_lastchange = AI->ai_lastchange; IFE->if_inoctets = AI->ai_inoctets; IFE->if_inucastpkts = AI->ai_inpcount[AI_UCAST_INDEX] + AI->ai_inpcount[AI_PROMIS_INDEX]; IFE->if_innucastpkts = AI->ai_inpcount[AI_NONUCAST_INDEX]; IFE->if_indiscards = AI->ai_indiscards; IFE->if_inerrors = AI->ai_inerrors; IFE->if_inunknownprotos = AI->ai_uknprotos; IFE->if_outoctets = AI->ai_outoctets; IFE->if_outucastpkts = AI->ai_outpcount[AI_UCAST_INDEX]; IFE->if_outnucastpkts = AI->ai_outpcount[AI_NONUCAST_INDEX]; IFE->if_outdiscards = AI->ai_outdiscards; IFE->if_outerrors = AI->ai_outerrors; for (i=0; i < (uint)KeNumberProcessors; i++) { QueueLength += AI->ai_qlen[i].ai_qlen; } IFE->if_outqlen = max(0, QueueLength); IFE->if_descrlen = AI->ai_desclen; #if FFP_SUPPORT // If FFP enabled on this interface, adjust IF stats for FFP'd packets if (AI->ai_ffpversion) { FFPAdapterStats IFStatsInfo = { NDIS_PROTOCOL_ID_TCP_IP, 0, 0, 0, 0, 0, 0, 0, 0 }; // Update ARP SNMP vars to account for FFP'd packets if (DoNDISRequest(AI, NdisRequestQueryInformation, OID_FFP_ADAPTER_STATS, &IFStatsInfo, sizeof(FFPAdapterStats), NULL, TRUE) == NDIS_STATUS_SUCCESS) { // Compensate 'inoctets' for packets not seen due to FFP IFE->if_inoctets += IFStatsInfo.InOctetsForwarded; IFE->if_inoctets += IFStatsInfo.InOctetsDiscarded; // Compensate 'inucastpkts' for packets not seen due to FFP // Assume all FFP fwded/dropped pkts came in as Eth Unicasts // A check to see if it is a ucast or an mcast would slow FFP IFE->if_inucastpkts += IFStatsInfo.InPacketsForwarded; IFE->if_inucastpkts += IFStatsInfo.InPacketsDiscarded; // Compensate 'outoctets' for packets not seen due to FFP IFE->if_outoctets += IFStatsInfo.OutOctetsForwarded; // Compensate 'outucastpkts' for packets not seen due to FFP // Assume all FFP fwded are sent as Ethernet Unicasts // A check to see if it is a ucast or an mcast would slow FFP IFE->if_outucastpkts += IFStatsInfo.OutPacketsForwarded; } } #endif // if FFP_SUPPORT fStatus = CopyToNdisSafe(Buffer, &Buffer, (uchar *) IFE, IFE_FIXED_SIZE, &Offset); if (fStatus == FALSE) { return TDI_NO_RESOURCES; } // See if he has room for the descriptor string. if (BufferSize >= (IFE_FIXED_SIZE + AI->ai_desclen)) { // He has room. Copy it. if (AI->ai_desclen != 0) { fStatus = CopyToNdisSafe( Buffer, NULL, (PUCHAR) AI->ai_desc, AI->ai_desclen, &Offset); } if (fStatus == FALSE) { return TDI_NO_RESOURCES; } *Size = IFE_FIXED_SIZE + AI->ai_desclen; return TDI_SUCCESS; } else { // Not enough room to copy the desc. string. *Size = IFE_FIXED_SIZE; return TDI_BUFFER_OVERFLOW; } } else if (ID->toi_id == IF_FRIENDLY_NAME_ID) { int Status; PNDIS_BUFFER NextBuffer; NDIS_STRING NdisString; // This is a query for the adapter's friendly name. // We'll convert this to an OID_GEN_FRIENDLY_NAME query for NDIS, // and transfer the resulting UNICODE_STRING to the caller's buffer // as a nul-terminated Unicode string. if (NdisQueryAdapterInstanceName(&NdisString, AI->ai_handle) == NDIS_STATUS_SUCCESS) { // Verify that the buffer is large enough for the string we just // retrieved and, if so, attempt to copy the string to the // caller's buffer. If that succeeds, nul-terminate the resulting // string. if (BufferSize >= (NdisString.Length + 1) * sizeof(WCHAR)) { fStatus = CopyToNdisSafe(Buffer, &NextBuffer, (uchar *)NdisString.Buffer, NdisString.Length, &Offset); if (fStatus) { WCHAR Nul = L'\0'; fStatus = CopyToNdisSafe(Buffer, &NextBuffer, (uchar *)&Nul, sizeof(Nul), &Offset); if (fStatus) { *Size = NdisString.Length + sizeof(Nul); Status = TDI_SUCCESS; } else Status = TDI_NO_RESOURCES; } else Status = TDI_NO_RESOURCES; } else Status = TDI_BUFFER_OVERFLOW; NdisFreeString(NdisString); return Status; } else return TDI_NO_RESOURCES; } else if (ID->toi_id == IF_QUERY_SET_OFFLOAD_ID) { IFOffloadCapability IFOC; if (BufferSize < sizeof(IFOC)) { return TDI_BUFFER_TOO_SMALL; } if (QueryAndSetOffload(AI)) { IFOC.ifoc_OffloadFlags = AI->ai_OffloadFlags; IFOC.ifoc_IPSecOffloadFlags = AI->ai_IPSecOffloadFlags; if (CopyToNdisSafe(Buffer, NULL, (uchar*)&IFOC, sizeof(IFOC), &Offset)) { return TDI_SUCCESS; } } return TDI_NO_RESOURCES; } return TDI_INVALID_PARAMETER; } //* ARPSetInfo - ARP set information handler. // // The ARP set information handler. We support setting of an I/F admin // status, and setting/deleting of ARP table entries. // // Input: Context - Pointer to I/F to set on. // ID - The object ID // Buffer - Pointer to buffer containing value to set. // Size - Size in bytes of Buffer. // // Returns: Status of attempt to set information. // int __stdcall ARPSetInfo(void *Context, TDIObjectID * ID, void *Buffer, uint Size) { ARPInterface *Interface = (ARPInterface *) Context; CTELockHandle Handle, EntryHandle; int Status; IFEntry UNALIGNED *IFE = (IFEntry UNALIGNED *) Buffer; IPNetToMediaEntry UNALIGNED *IPNME; ARPTableEntry *PrevATE, *CurrentATE; ARPTable *Table; ENetHeader *Header; uint Entity, Instance; PNDIS_PACKET Packet; Entity = ID->toi_entity.tei_entity; Instance = ID->toi_entity.tei_instance; // First, make sure it's possibly an ID we can handle. if ((Entity != AT_ENTITY || Instance != Interface->ai_atinst) && (Entity != IF_ENTITY || Instance != Interface->ai_ifinst)) { return TDI_INVALID_REQUEST; } if (ID->toi_type != INFO_TYPE_PROVIDER) { return TDI_INVALID_PARAMETER; } // Might be able to handle this. if (Entity == IF_ENTITY) { // It's for the I/F level, see if it's for the statistics. if (ID->toi_class != INFO_CLASS_PROTOCOL) return TDI_INVALID_PARAMETER; if (ID->toi_id == IF_MIB_STATS_ID) { // It's for the stats. Make sure it's a valid size. if (Size >= IFE_FIXED_SIZE) { // It's a valid size. See what he wants to do. CTEGetLock(&Interface->ai_lock, &Handle); switch (IFE->if_adminstatus) { case IF_STATUS_UP: // He's marking it up. If the operational state is // alse up, mark the whole interface as up. Interface->ai_adminstate = IF_STATUS_UP; ARPUpdateOperStatus(Interface); Status = TDI_SUCCESS; break; case IF_STATUS_DOWN: // He's taking it down. Mark both the admin state and // the interface state down. Interface->ai_adminstate = IF_STATUS_DOWN; ARPUpdateOperStatus(Interface); Status = TDI_SUCCESS; break; case IF_STATUS_TESTING: // He's trying to cause up to do testing, which we // don't support. Just return success. Status = TDI_SUCCESS; break; default: Status = TDI_INVALID_PARAMETER; break; } CTEFreeLock(&Interface->ai_lock, Handle); return Status; } else return TDI_INVALID_PARAMETER; } else { return TDI_INVALID_PARAMETER; } } // Not for the interface level. See if it's an implementation or protocol // class. if (ID->toi_class == INFO_CLASS_IMPLEMENTATION) { ProxyArpEntry UNALIGNED *PArpEntry; ARPIPAddr *Addr; IPAddr AddAddr; IPMask Mask; // It's for the implementation. It should be the proxy-ARP ID. if (ID->toi_id != AT_ARP_PARP_ENTRY_ID || Size < sizeof(ProxyArpEntry)) return TDI_INVALID_PARAMETER; PArpEntry = (ProxyArpEntry UNALIGNED *) Buffer; AddAddr = PArpEntry->pae_addr; Mask = PArpEntry->pae_mask; // See if he's trying to add or delete a proxy arp entry. if (PArpEntry->pae_status == PAE_STATUS_VALID) { // We're trying to add an entry. We won't allow an entry // to be added that we believe to be invalid or conflicting // with our local addresses. if (!VALID_MASK(Mask)) return TDI_INVALID_PARAMETER; if (!IP_ADDR_EQUAL(AddAddr & Mask, AddAddr) || IP_ADDR_EQUAL(AddAddr, NULL_IP_ADDR) || IP_ADDR_EQUAL(AddAddr, IP_LOCAL_BCST) || IP_LOOPBACK(AddAddr) || CLASSD_ADDR(AddAddr) || CLASSE_ADDR(AddAddr)) return TDI_INVALID_PARAMETER; // Walk through the list of addresses on the interface, and see // if they would match the AddAddr. If so, fail the request. CTEGetLock(&Interface->ai_lock, &Handle); if (IsBCastOnIF(Interface, AddAddr & Mask)) { CTEFreeLock(&Interface->ai_lock, Handle); return TDI_INVALID_PARAMETER; } Addr = &Interface->ai_ipaddr; do { if (!IP_ADDR_EQUAL(Addr->aia_addr, NULL_IP_ADDR)) { if (IP_ADDR_EQUAL(Addr->aia_addr & Mask, AddAddr)) break; } Addr = Addr->aia_next; } while (Addr != NULL); CTEFreeLock(&Interface->ai_lock, Handle); if (Addr != NULL) return TDI_INVALID_PARAMETER; // At this point, we believe we're ok. Try to add the address. if (ARPAddAddr(Interface, LLIP_ADDR_PARP, AddAddr, Mask, NULL)) return TDI_SUCCESS; else return TDI_NO_RESOURCES; } else { if (PArpEntry->pae_status == PAE_STATUS_INVALID) { // He's trying to delete a proxy ARP address. if (ARPDeleteAddr(Interface, LLIP_ADDR_PARP, AddAddr, Mask)) return TDI_SUCCESS; } return TDI_INVALID_PARAMETER; } } if (ID->toi_class != INFO_CLASS_PROTOCOL) { return TDI_INVALID_PARAMETER; } if (ID->toi_id == AT_MIB_ADDRXLAT_ENTRY_ID && Size >= sizeof(IPNetToMediaEntry)) { // He does want to set an ARP table entry. See if he's trying to // create or delete one. IPNME = (IPNetToMediaEntry UNALIGNED *) Buffer; if (IPNME->inme_type == INME_TYPE_INVALID) { uint Index = ARP_HASH(IPNME->inme_addr); // We're trying to delete an entry. See if we can find it, // and then delete it. CTEGetLock(&Interface->ai_ARPTblLock, &Handle); Table = Interface->ai_ARPTbl; PrevATE = STRUCT_OF(ARPTableEntry, &((*Table)[Index]), ate_next); CurrentATE = (*Table)[Index]; while (CurrentATE != (ARPTableEntry *) NULL) { if (CurrentATE->ate_dest == IPNME->inme_addr) { // Found him. Break out of the loop. break; } else { PrevATE = CurrentATE; CurrentATE = CurrentATE->ate_next; } } if (CurrentATE != NULL) { CTEGetLock(&CurrentATE->ate_lock, &EntryHandle); if (CurrentATE->ate_resolveonly) { ARPControlBlock *ArpContB, *TmpArpContB; ArpContB = CurrentATE->ate_resolveonly; while (ArpContB) { ArpRtn rtn; rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = (IP_STATUS) STATUS_UNSUCCESSFUL; TmpArpContB = ArpContB->next; (*rtn) (ArpContB, (IP_STATUS) STATUS_UNSUCCESSFUL); ArpContB = TmpArpContB; } CurrentATE->ate_resolveonly = NULL; } RemoveARPTableEntry(PrevATE, CurrentATE); Interface->ai_count--; CTEFreeLockFromDPC(&CurrentATE->ate_lock); CTEFreeLock(&Interface->ai_ARPTblLock, Handle); if (CurrentATE->ate_packet != NULL) { IPSendComplete(Interface->ai_context, CurrentATE->ate_packet, NDIS_STATUS_SUCCESS); } CTEFreeMem(CurrentATE); return TDI_SUCCESS; } else Status = TDI_INVALID_PARAMETER; CTEFreeLock(&Interface->ai_ARPTblLock, Handle); return Status; } // We're not trying to delete. See if we're trying to create. if (IPNME->inme_type != INME_TYPE_DYNAMIC && IPNME->inme_type != INME_TYPE_STATIC) { // Not creating, return an error. return TDI_INVALID_PARAMETER; } // Make sure he's trying to create a valid address. if (IPNME->inme_physaddrlen != Interface->ai_addrlen) return TDI_INVALID_PARAMETER; // We're trying to create an entry. Call CreateARPTableEntry to create // one, and fill it in. CurrentATE = CreateARPTableEntry(Interface, IPNME->inme_addr, &Handle, 0); if (CurrentATE == NULL) { return TDI_NO_RESOURCES; } // We've created or found an entry. Fill it in. Header = (ENetHeader *) CurrentATE->ate_addr; switch (Interface->ai_media) { case NdisMedium802_5: { TRHeader *Temp = (TRHeader *) Header; // Fill in the TR specific parts, and set the length to the // size of a TR header. Temp->tr_ac = ARP_AC; Temp->tr_fc = ARP_FC; RtlCopyMemory(&Temp->tr_saddr[ARP_802_ADDR_LENGTH], ARPSNAP, sizeof(SNAPHeader)); Header = (ENetHeader *) & Temp->tr_daddr; CurrentATE->ate_addrlength = sizeof(TRHeader) + sizeof(SNAPHeader); } break; case NdisMedium802_3: CurrentATE->ate_addrlength = sizeof(ENetHeader); break; case NdisMediumFddi: { FDDIHeader *Temp = (FDDIHeader *) Header; Temp->fh_pri = ARP_FDDI_PRI; RtlCopyMemory(&Temp->fh_saddr[ARP_802_ADDR_LENGTH], ARPSNAP, sizeof(SNAPHeader)); Header = (ENetHeader *) & Temp->fh_daddr; CurrentATE->ate_addrlength = sizeof(FDDIHeader) + sizeof(SNAPHeader); } break; case NdisMediumArcnet878_2: { ARCNetHeader *Temp = (ARCNetHeader *) Header; Temp->ah_saddr = Interface->ai_addr[0]; Temp->ah_daddr = IPNME->inme_physaddr[0]; Temp->ah_prot = ARP_ARCPROT_IP; CurrentATE->ate_addrlength = sizeof(ARCNetHeader); } break; default: ASSERT(0); break; } // Copy in the source and destination addresses. if (Interface->ai_media != NdisMediumArcnet878_2) { RtlCopyMemory(Header->eh_daddr, IPNME->inme_physaddr, ARP_802_ADDR_LENGTH); RtlCopyMemory(Header->eh_saddr, Interface->ai_addr, ARP_802_ADDR_LENGTH); // Now fill in the Ethertype. *(ushort *) & CurrentATE->ate_addr[CurrentATE->ate_addrlength - 2] = net_short(ARP_ETYPE_IP); } // If he's creating a static entry, mark it as always valid. Otherwise // mark him as valid now. if (IPNME->inme_type == INME_TYPE_STATIC) CurrentATE->ate_valid = ALWAYS_VALID; else CurrentATE->ate_valid = CTESystemUpTime(); CurrentATE->ate_state = ARP_GOOD; Packet = CurrentATE->ate_packet; CurrentATE->ate_packet = NULL; CTEFreeLock(&CurrentATE->ate_lock, Handle); if (Packet) { IPSendComplete(Interface->ai_context, Packet, NDIS_STATUS_SUCCESS); } return TDI_SUCCESS; } return TDI_INVALID_PARAMETER; } #pragma BEGIN_INIT //** ARPInit - Initialize the ARP module. // // This functions intializes all of the ARP module, including allocating // the ARP table and any other necessary data structures. // // Entry: nothing. // // Exit: Returns 0 if we fail to init., !0 if we succeed. // int ARPInit() { NDIS_STATUS Status; // Status for NDIS calls. NDIS_PROTOCOL_CHARACTERISTICS Characteristics; DEBUGMSG(DBG_TRACE && DBG_INIT, (DTEXT("+ARPInit()\n"))); RtlZeroMemory(&Characteristics, sizeof(NDIS_PROTOCOL_CHARACTERISTICS)); Characteristics.MajorNdisVersion = NDIS_MAJOR_VERSION; Characteristics.MinorNdisVersion = NDIS_MINOR_VERSION; Characteristics.OpenAdapterCompleteHandler = ARPOAComplete; Characteristics.CloseAdapterCompleteHandler = ARPCAComplete; Characteristics.SendCompleteHandler = ARPSendComplete; Characteristics.TransferDataCompleteHandler = ARPTDComplete; Characteristics.ResetCompleteHandler = ARPResetComplete; Characteristics.RequestCompleteHandler = ARPRequestComplete; Characteristics.ReceiveHandler = ARPRcv, Characteristics.ReceiveCompleteHandler = ARPRcvComplete; Characteristics.StatusHandler = ARPStatus; Characteristics.StatusCompleteHandler = ARPStatusComplete; // // Re-direct to IP since IP now binds to NDIS. // Characteristics.BindAdapterHandler = IPBindAdapter; // ARPBindAdapter; Characteristics.UnbindAdapterHandler = ARPUnbindAdapter; Characteristics.PnPEventHandler = ARPPnPEvent; #if MILLEN Characteristics.UnloadHandler = ARPUnloadProtocol; #endif // MILLEN RtlInitUnicodeString(&(Characteristics.Name), ARPName); Characteristics.ReceivePacketHandler = ARPRcvPacket; DEBUGMSG(DBG_INFO && DBG_INIT, (DTEXT("ARPInit: Calling NdisRegisterProtocol %d:%d %ws\n"), NDIS_MAJOR_VERSION, NDIS_MINOR_VERSION, ARPName)); NdisRegisterProtocol(&Status, &ARPHandle, (NDIS_PROTOCOL_CHARACTERISTICS *) & Characteristics, sizeof(Characteristics)); DEBUGMSG(DBG_TRACE && DBG_INIT, (DTEXT("-ARPInit [%x]\n"), Status)); if (Status == NDIS_STATUS_SUCCESS) { return(1); } else { return(0); } } //* FreeARPInterface - Free an ARP interface // // Called in the event of some sort of initialization failure. We free all // the memory associated with an ARP interface. // // Entry: Interface - Pointer to interface structure to be freed. // // Returns: Nothing. // void FreeARPInterface(ARPInterface *Interface) { NDIS_STATUS Status; ARPTable *Table; // ARP table. uint i; // Index variable. ARPTableEntry *ATE; CTELockHandle LockHandle; NDIS_HANDLE Handle; if (Interface->ai_timerstarted && !CTEStopTimer(&Interface->ai_timer)) { // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Could not stop ai_timer - waiting for event\n")); (VOID) CTEBlock(&Interface->ai_timerblock); KeClearEvent(&Interface->ai_timerblock.cbs_event); } // If we're bound to the adapter, close it now. CTEInitBlockStruc(&Interface->ai_block); CTEGetLock(&Interface->ai_lock, &LockHandle); if (Interface->ai_handle != (NDIS_HANDLE) NULL) { Handle = Interface->ai_handle; Interface->ai_handle = NULL; CTEFreeLock(&Interface->ai_lock, LockHandle); NdisCloseAdapter(&Status, Handle); if (Status == NDIS_STATUS_PENDING) Status = CTEBlock(&Interface->ai_block); } else { CTEFreeLock(&Interface->ai_lock, LockHandle); } // First free any outstanding ARP table entries. Table = Interface->ai_ARPTbl; if (Table != NULL) { for (i = 0; i < ARP_TABLE_SIZE; i++) { while ((*Table)[i] != NULL) { ATE = (*Table)[i]; if (ATE->ate_resolveonly) { ARPControlBlock *ArpContB, *TmpArpContB; ArpContB = ATE->ate_resolveonly; while (ArpContB) { ArpRtn rtn; rtn = (ArpRtn) ArpContB->CompletionRtn; ArpContB->status = (IP_STATUS) STATUS_UNSUCCESSFUL; TmpArpContB = ArpContB->next; (*rtn) (ArpContB, (IP_STATUS) STATUS_UNSUCCESSFUL); ArpContB = TmpArpContB; } ATE->ate_resolveonly = NULL; } RemoveARPTableEntry(STRUCT_OF(ARPTableEntry, &((*Table)[i]), ate_next), ATE); if (ATE->ate_packet) { IPSendComplete(Interface->ai_context, ATE->ate_packet, NDIS_STATUS_SUCCESS); } CTEFreeMem(ATE); } } CTEFreeMem(Table); } Interface->ai_ARPTbl = NULL; if (Interface->ai_ppool != (NDIS_HANDLE) NULL) NdisFreePacketPool(Interface->ai_ppool); if (Interface->ai_qlen) { CTEFreeMem(Interface->ai_qlen); } if (Interface->ai_devicename.Buffer != NULL) { CTEFreeMem(Interface->ai_devicename.Buffer); } if (Interface->ai_desc) { CTEFreeMem(Interface->ai_desc); } // Free the interface itself. CTEFreeMem(Interface); } //** ARPOpen - Open an adapter for reception. // // This routine is called when the upper layer is done initializing and wishes to // begin receiveing packets. The adapter is actually 'open', we just call InitAdapter // to set the packet filter and lookahead size. // // Input: Context - Interface pointer we gave to IP earlier. // // Returns: Nothing // void __stdcall ARPOpen(void *Context) { ARPInterface *Interface = (ARPInterface *) Context; InitAdapter(Interface); // Set the packet filter - we'll begin receiving. } //* ARPGetEList - Get the entity list. // // Called at init time to get an entity list. We fill our stuff in, and // then call the interfaces below us to allow them to do the same. // // Input: EntityList - Pointer to entity list to be filled in. // Count - Pointer to number of entries in the list. // // Returns Status of attempt to get the info. // int __stdcall ARPGetEList(void *Context, TDIEntityID * EList, uint * Count) { ARPInterface *Interface = (ARPInterface *) Context; uint MyATBase; uint MyIFBase; uint i; TDIEntityID *ATEntity, *IFEntity; TDIEntityID *EntityList; // Walk down the list, looking for existing AT or IF entities, and // adjust our base instance accordingly. // if we are already on the list then do nothing. // if we are going away, mark our entry invalid. EntityList = EList; MyATBase = 0; MyIFBase = 0; ATEntity = NULL; IFEntity = NULL; for (i = 0; i < *Count; i++, EntityList++) { if (EntityList->tei_entity == AT_ENTITY) { // if we are already on the list remember our entity item // o/w find an instance # for us. if (EntityList->tei_instance == Interface->ai_atinst && EntityList->tei_instance != INVALID_ENTITY_INSTANCE) { ATEntity = EntityList; // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - Found our interface %lx at_atinst %lx\n",Interface, Interface->ai_atinst)); } else { MyATBase = MAX(MyATBase, EntityList->tei_instance + 1); } } else { if (EntityList->tei_entity == IF_ENTITY) // if we are already on the list remember our entity item // o/w find an instance # for us. if (EntityList->tei_instance == Interface->ai_ifinst && EntityList->tei_instance != INVALID_ENTITY_INSTANCE) { IFEntity = EntityList; // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - Found our interface %lx ai_ifinst %lx\n",Interface, Interface->ai_ifinst)); } else { MyIFBase = MAX(MyIFBase, EntityList->tei_instance + 1); } } if (ATEntity && IFEntity) { break; } } if (ATEntity) { // we are already on the list. // are we going away? if (Interface->ai_operstatus == INTERFACE_UNINIT) { // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - our interface %lx atinst %lx going away \n",Interface, Interface->ai_atinst)); ATEntity->tei_instance = (ULONG) INVALID_ENTITY_INSTANCE; } } else { // we are not on the list. // insert ourself iff we are not going away. if (Interface->ai_operstatus != INTERFACE_UNINIT) { // make sure we have the room for it. if (*Count >= MAX_TDI_ENTITIES) { return FALSE; } Interface->ai_atinst = MyATBase; ATEntity = &EList[*Count]; ATEntity->tei_entity = AT_ENTITY; ATEntity->tei_instance = MyATBase; (*Count)++; // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - adding interface %lx atinst %lx \n",Interface, Interface->ai_atinst)); } } if (IFEntity) { // we are already on the list. // are we going away? if (Interface->ai_operstatus == INTERFACE_UNINIT) { // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - our interface %lx ifinst %lx going away \n",Interface, Interface->ai_ifinst)); IFEntity->tei_instance = (ULONG) INVALID_ENTITY_INSTANCE; } } else { // we are not on the list. // insert ourself iff we are not going away. if (Interface->ai_operstatus != INTERFACE_UNINIT) { // make sure we have the room for it. if (*Count >= MAX_TDI_ENTITIES) { return FALSE; } Interface->ai_ifinst = MyIFBase; IFEntity = &EList[*Count]; IFEntity->tei_entity = IF_ENTITY; IFEntity->tei_instance = MyIFBase; (*Count)++; // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetElist - adding interface %lx ifinst %lx \n",Interface, Interface->ai_ifinst)); } } // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ARPGetEList: arp interface %lx, ai_atinst %lx, ai_ifinst %lx, total %lx\n", // Interface, Interface->ai_atinst, Interface->ai_ifinst, *Count)); return TRUE; } extern uint UseEtherSNAP(PNDIS_STRING Name); extern void GetAlwaysSourceRoute(uint * pArpAlwaysSourceRoute, uint * pIPAlwaysSourceRoute); extern uint GetArpCacheLife(void); extern uint GetArpRetryCount(void); //** InitTaskOffloadHeader - Initializes the task offload header wrt version // and encapsulation, etc. // // All task offload header structure members are initialized. // // Input: // ai - ARPInterface for which we are initializing // the task offload header. // TaskOffloadHeader - Pointer to task offload header to initialize. // Returns: // None. // VOID InitTaskOffloadHeader(ARPInterface *ai, PNDIS_TASK_OFFLOAD_HEADER TaskOffloadHeader) { TaskOffloadHeader->Version = NDIS_TASK_OFFLOAD_VERSION; TaskOffloadHeader->Size = sizeof(NDIS_TASK_OFFLOAD_HEADER); TaskOffloadHeader->EncapsulationFormat.Flags.FixedHeaderSize = 1; TaskOffloadHeader->EncapsulationFormat.EncapsulationHeaderSize = ai->ai_hdrsize; TaskOffloadHeader->OffsetFirstTask = 0; if (ai->ai_media == NdisMedium802_3) { if (ai->ai_snapsize) { TaskOffloadHeader->EncapsulationFormat.Encapsulation = LLC_SNAP_ROUTED_Encapsulation; TaskOffloadHeader->EncapsulationFormat.EncapsulationHeaderSize += ai->ai_snapsize; } else { TaskOffloadHeader->EncapsulationFormat.Encapsulation = IEEE_802_3_Encapsulation; } } else if (ai->ai_media == NdisMedium802_5) { TaskOffloadHeader->EncapsulationFormat.Encapsulation = IEEE_802_5_Encapsulation; } else { TaskOffloadHeader->EncapsulationFormat.Encapsulation = UNSPECIFIED_Encapsulation; } return; } //**SetOffload - Set offload capabilities // // // All task offload header structure members are initialized. // // Input: // ai - ARPInterface for which we are initializing // the task offload header. // TaskOffloadHeader - Pointer to task offload header to initialize. // Bufsize - length of task offload buffer allocated by teh caller // // Returns: // TRUE - successfully set the offload capability // FALSE - failure case // BOOLEAN SetOffload(ARPInterface *ai,PNDIS_TASK_OFFLOAD_HEADER TaskOffloadHeader,uint BufSize) { PNDIS_TASK_OFFLOAD tmpoffload; PNDIS_TASK_OFFLOAD TaskOffload, NextTaskOffLoad, LastTaskOffload; NDIS_TASK_IPSEC ipsecCaps; uint TotalLength; NDIS_STATUS Status; uint PrevOffLoad=ai->ai_OffloadFlags; uint PrevIPSecOffLoad=ai->ai_IPSecOffloadFlags; //Parse the buffer for Checksum and tcplargesend offload capabilities KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Something to Offload. offload buffer size %x\n", BufSize)); ASSERT(TaskOffloadHeader->OffsetFirstTask == sizeof(NDIS_TASK_OFFLOAD_HEADER)); TaskOffload = tmpoffload = (NDIS_TASK_OFFLOAD *) ((uchar *) TaskOffloadHeader + TaskOffloadHeader->OffsetFirstTask); if (BufSize >= (TaskOffloadHeader->OffsetFirstTask + sizeof(NDIS_TASK_OFFLOAD))) { while (tmpoffload) { if (tmpoffload->Task == TcpIpChecksumNdisTask) { //Okay we this adapter supports checksum offload //check if tcp and/or ip chksums bits are present PNDIS_TASK_TCP_IP_CHECKSUM ChecksumInfo; ChecksumInfo = (PNDIS_TASK_TCP_IP_CHECKSUM) & tmpoffload->TaskBuffer[0]; //if (ChecksumInfo->V4Transmit.V4Checksum) { KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"V4 Checksum offload\n")); if (ChecksumInfo->V4Transmit.TcpChecksum) { ai->ai_OffloadFlags |= TCP_XMT_CHECKSUM_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," Tcp Checksum offload\n")); } if (ChecksumInfo->V4Transmit.IpChecksum) { ai->ai_OffloadFlags |= IP_XMT_CHECKSUM_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," IP xmt Checksum offload\n")); } if (ChecksumInfo->V4Receive.TcpChecksum) { ai->ai_OffloadFlags |= TCP_RCV_CHECKSUM_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," Tcp Rcv Checksum offload\n")); } if (ChecksumInfo->V4Receive.IpChecksum) { ai->ai_OffloadFlags |= IP_RCV_CHECKSUM_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," IP rcv Checksum offload\n")); } if (ChecksumInfo->V4Transmit.IpOptionsSupported) { ai->ai_OffloadFlags |= IP_CHECKSUM_OPT_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," IP Checksum xmt options offload\n")); } if (ChecksumInfo->V4Transmit.TcpOptionsSupported) { ai->ai_OffloadFlags |= TCP_CHECKSUM_OPT_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," TCP Checksum xmt options offload\n")); } } else if ((tmpoffload->Task == TcpLargeSendNdisTask) && (ai->ai_snapsize == 0)) { PNDIS_TASK_TCP_LARGE_SEND TcpLargeSend, in_LargeSend = (PNDIS_TASK_TCP_LARGE_SEND) & tmpoffload->TaskBuffer[0]; TcpLargeSend = &ai->ai_TcpLargeSend; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," Tcp large send!! \n")); TcpLargeSend->MaxOffLoadSize = in_LargeSend->MaxOffLoadSize; TcpLargeSend->MinSegmentCount = in_LargeSend->MinSegmentCount; // // If MaxOffLoadSize is zero, reject this request. // if (TcpLargeSend->MaxOffLoadSize) { ai->ai_OffloadFlags |= TCP_LARGE_SEND_OFFLOAD; // no tcp or ip options when doing large send // Need to reevaluate this as we turn on Time stamp option. if (in_LargeSend->TcpOptions) { ai->ai_OffloadFlags |= TCP_LARGE_SEND_TCPOPT_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," TCP largesend options offload\n")); } if (in_LargeSend->IpOptions) { ai->ai_OffloadFlags |= TCP_LARGE_SEND_IPOPT_OFFLOAD; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL," IP largesend options offload\n")); } } } else if (tmpoffload->Task == IpSecNdisTask) { PNDIS_TASK_IPSEC pIPSecCaps = (PNDIS_TASK_IPSEC) & tmpoffload->TaskBuffer[0]; // // Save off the capabilities for setting them later. // ipsecCaps = *pIPSecCaps; // // CryptoOnly is assumed if we have IpSecNdisTask // ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_CRYPTO_ONLY; // // Do Support first // if (pIPSecCaps->Supported.AH_ESP_COMBINED) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_ESP; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AH_ESP\n")); } if (pIPSecCaps->Supported.TRANSPORT_TUNNEL_COMBINED) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_TUNNEL; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"TPT_TUNNEL\n")); } if (pIPSecCaps->Supported.V4_OPTIONS) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_V4_OPTIONS; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"V4_OPTIONS\n")); } if (pIPSecCaps->Supported.RESERVED) { if (pIPSecCaps->Supported.RESERVED & IPSEC_TPT_UDPESP_ENCAPTYPE_IKE) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_UDPESP_IKE; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_UDPESP_IKE\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TUN_UDPESP_ENCAPTYPE_IKE) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TUNNEL_UDPESP_IKE; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TUNNEL_UDPESP_IKE\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TPTOVERTUN_UDPESP_ENCAPTYPE_IKE) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_IKE; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_IKE\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TPT_UDPESP_OVER_PURE_TUN_ENCAPTYPE_IKE) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_IKE; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_IKE\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TPT_UDPESP_ENCAPTYPE_OTHER) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_UDPESP_OTHER; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_UDPESP_OTHER\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TUN_UDPESP_ENCAPTYPE_OTHER) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TUNNEL_UDPESP_OTHER; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TUNNEL_UDPESP_OTHER\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TPTOVERTUN_UDPESP_ENCAPTYPE_OTHER) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_OTHER; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_OTHER\n")); } if (pIPSecCaps->Supported.RESERVED & IPSEC_TPT_UDPESP_OVER_PURE_TUN_ENCAPTYPE_OTHER) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_OTHER; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_OTHER\n")); } } // // Do V4AH next // if (pIPSecCaps->V4AH.MD5) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_MD5; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"MD5\n")); } if (pIPSecCaps->V4AH.SHA_1) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_SHA_1; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"SHA\n")); } if (pIPSecCaps->V4AH.Transport) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_TPT; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AH_TRANSPORT\n")); } if (pIPSecCaps->V4AH.Tunnel) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_TUNNEL; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AH_TUNNEL\n")); } if (pIPSecCaps->V4AH.Send) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_XMT; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AH_XMT\n")); } if (pIPSecCaps->V4AH.Receive) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_AH_RCV; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"AH_RCV\n")); } // // Do V4ESP next // if (pIPSecCaps->V4ESP.DES) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_DES; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_DES\n")); } if (pIPSecCaps->V4ESP.RESERVED) { pIPSecCaps->V4ESP.RESERVED = 0; //ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_DES_40; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_DES_40\n")); } if (pIPSecCaps->V4ESP.TRIPLE_DES) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_3_DES; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_3_DES\n")); } if (pIPSecCaps->V4ESP.NULL_ESP) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_NONE; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_NONE\n")); } if (pIPSecCaps->V4ESP.Transport) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_TPT; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_TRANSPORT\n")); } if (pIPSecCaps->V4ESP.Tunnel) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_TUNNEL; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_TUNNEL\n")); } if (pIPSecCaps->V4ESP.Send) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_XMT; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_XMT\n")); } if (pIPSecCaps->V4ESP.Receive) { ai->ai_IPSecOffloadFlags |= IPSEC_OFFLOAD_ESP_RCV; KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"ESP_RCV\n")); } } // Point to the next offload structure if (tmpoffload->OffsetNextTask) { tmpoffload = (PNDIS_TASK_OFFLOAD) ((PUCHAR) tmpoffload + tmpoffload->OffsetNextTask); } else { tmpoffload = NULL; } } //while } else { //if BufSize is not okay KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"response of task offload does not have sufficient space even for 1 offload task!!\n")); return FALSE; } // Enable the capabilities by setting them. if (PrevOffLoad) { ai->ai_OffloadFlags &= PrevOffLoad; } if (PrevIPSecOffLoad) { ai->ai_IPSecOffloadFlags &= PrevIPSecOffLoad; } TaskOffload->Task = 0; TaskOffload->OffsetNextTask = 0; NextTaskOffLoad = LastTaskOffload = TaskOffload; TotalLength = sizeof(NDIS_TASK_OFFLOAD_HEADER); if ((ai->ai_OffloadFlags & TCP_XMT_CHECKSUM_OFFLOAD) || (ai->ai_OffloadFlags & IP_XMT_CHECKSUM_OFFLOAD) || (ai->ai_OffloadFlags & TCP_RCV_CHECKSUM_OFFLOAD) || (ai->ai_OffloadFlags & IP_RCV_CHECKSUM_OFFLOAD)) { PNDIS_TASK_TCP_IP_CHECKSUM ChksumBuf = (PNDIS_TASK_TCP_IP_CHECKSUM) & NextTaskOffLoad->TaskBuffer[0]; NextTaskOffLoad->Task = TcpIpChecksumNdisTask; NextTaskOffLoad->TaskBufferLength = sizeof(NDIS_TASK_TCP_IP_CHECKSUM); NextTaskOffLoad->OffsetNextTask = FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer) + NextTaskOffLoad->TaskBufferLength; TotalLength += NextTaskOffLoad->OffsetNextTask; RtlZeroMemory(ChksumBuf, sizeof(NDIS_TASK_TCP_IP_CHECKSUM)); if (ai->ai_OffloadFlags & TCP_XMT_CHECKSUM_OFFLOAD) { ChksumBuf->V4Transmit.TcpChecksum = 1; } if (ai->ai_OffloadFlags & IP_XMT_CHECKSUM_OFFLOAD) { ChksumBuf->V4Transmit.IpChecksum = 1; } if (ai->ai_OffloadFlags & TCP_RCV_CHECKSUM_OFFLOAD) { ChksumBuf->V4Receive.TcpChecksum = 1; } if (ai->ai_OffloadFlags & IP_RCV_CHECKSUM_OFFLOAD) { ChksumBuf->V4Receive.IpChecksum = 1; } // // Enable Options capability if present. // if (ai->ai_OffloadFlags & IP_CHECKSUM_OPT_OFFLOAD) { ChksumBuf->V4Transmit.IpOptionsSupported = 1; } if (ai->ai_OffloadFlags & TCP_CHECKSUM_OPT_OFFLOAD) { ChksumBuf->V4Transmit.TcpOptionsSupported = 1; } LastTaskOffload = NextTaskOffLoad; NextTaskOffLoad = (PNDIS_TASK_OFFLOAD) ((PUCHAR) NextTaskOffLoad + NextTaskOffLoad->OffsetNextTask); } if (ai->ai_OffloadFlags & TCP_LARGE_SEND_OFFLOAD) { PNDIS_TASK_TCP_LARGE_SEND TcpLargeSend, out_LargeSend = (PNDIS_TASK_TCP_LARGE_SEND) & NextTaskOffLoad->TaskBuffer[0]; NextTaskOffLoad->Task = TcpLargeSendNdisTask; NextTaskOffLoad->TaskBufferLength = sizeof(NDIS_TASK_TCP_LARGE_SEND); NextTaskOffLoad->OffsetNextTask = FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer) + NextTaskOffLoad->TaskBufferLength; TotalLength += NextTaskOffLoad->OffsetNextTask; //(uchar)TaskOffload + sizeof(NDIS_TASK_OFFLOAD) + NextTaskOffload->TaskBufferLength; TcpLargeSend = &ai->ai_TcpLargeSend; RtlZeroMemory(out_LargeSend, sizeof(NDIS_TASK_TCP_LARGE_SEND)); out_LargeSend->MaxOffLoadSize = TcpLargeSend->MaxOffLoadSize; out_LargeSend->MinSegmentCount = TcpLargeSend->MinSegmentCount; if (ai->ai_OffloadFlags & TCP_LARGE_SEND_TCPOPT_OFFLOAD) { out_LargeSend->TcpOptions = 1; } if (ai->ai_OffloadFlags & TCP_LARGE_SEND_IPOPT_OFFLOAD) { out_LargeSend->IpOptions = 1; } LastTaskOffload = NextTaskOffLoad; NextTaskOffLoad = (PNDIS_TASK_OFFLOAD) ((PUCHAR) NextTaskOffLoad + NextTaskOffLoad->OffsetNextTask); } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_CRYPTO_ONLY) { PNDIS_TASK_IPSEC pIPSecCaps = (PNDIS_TASK_IPSEC) & NextTaskOffLoad->TaskBuffer[0]; // // plunk down the advertised capabilities // RtlZeroMemory(pIPSecCaps, sizeof(NDIS_TASK_IPSEC)); NextTaskOffLoad->Task = IpSecNdisTask; NextTaskOffLoad->TaskBufferLength = sizeof(NDIS_TASK_IPSEC); NextTaskOffLoad->OffsetNextTask = (FIELD_OFFSET(NDIS_TASK_OFFLOAD, TaskBuffer) + NextTaskOffLoad->TaskBufferLength); TotalLength += NextTaskOffLoad->OffsetNextTask; if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_ESP) { pIPSecCaps->Supported.AH_ESP_COMBINED = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_TUNNEL) { pIPSecCaps->Supported.TRANSPORT_TUNNEL_COMBINED = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_V4_OPTIONS) { pIPSecCaps->Supported.V4_OPTIONS = 1; } pIPSecCaps->Supported.RESERVED = 0; if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_UDPESP_IKE) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPT_UDPESP_ENCAPTYPE_IKE; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TUNNEL_UDPESP_IKE) { pIPSecCaps->Supported.RESERVED |= IPSEC_TUN_UDPESP_ENCAPTYPE_IKE; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_IKE) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPTOVERTUN_UDPESP_ENCAPTYPE_IKE; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_IKE) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPT_UDPESP_OVER_PURE_TUN_ENCAPTYPE_IKE; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_UDPESP_OTHER) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPT_UDPESP_ENCAPTYPE_OTHER; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TUNNEL_UDPESP_OTHER) { pIPSecCaps->Supported.RESERVED |= IPSEC_TUN_UDPESP_ENCAPTYPE_OTHER; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_OVER_TUNNEL_UDPESP_OTHER) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPTOVERTUN_UDPESP_ENCAPTYPE_OTHER; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_TPT_UDPESP_OVER_PURE_TUNNEL_OTHER) { pIPSecCaps->Supported.RESERVED |= IPSEC_TPT_UDPESP_OVER_PURE_TUN_ENCAPTYPE_OTHER; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_MD5) { pIPSecCaps->V4AH.MD5 = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_SHA_1) { pIPSecCaps->V4AH.SHA_1 = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_TPT) { pIPSecCaps->V4AH.Transport = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_TUNNEL) { pIPSecCaps->V4AH.Tunnel = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_XMT) { pIPSecCaps->V4AH.Send = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_AH_RCV) { pIPSecCaps->V4AH.Receive = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_DES) { pIPSecCaps->V4ESP.DES = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_3_DES) { pIPSecCaps->V4ESP.TRIPLE_DES = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_NONE) { pIPSecCaps->V4ESP.NULL_ESP = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_TPT) { pIPSecCaps->V4ESP.Transport = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_TUNNEL) { pIPSecCaps->V4ESP.Tunnel = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_XMT) { pIPSecCaps->V4ESP.Send = 1; } if (ai->ai_IPSecOffloadFlags & IPSEC_OFFLOAD_ESP_RCV) { pIPSecCaps->V4ESP.Receive = 1; } LastTaskOffload = NextTaskOffLoad; NextTaskOffLoad = (PNDIS_TASK_OFFLOAD) ((PUCHAR) NextTaskOffLoad + NextTaskOffLoad->OffsetNextTask); } LastTaskOffload->OffsetNextTask = 0; // Okay, lets set this now. Status = DoNDISRequest(ai, NdisRequestSetInformation, OID_TCP_TASK_OFFLOAD, TaskOffloadHeader, TotalLength, NULL, TRUE); if (Status != NDIS_STATUS_SUCCESS) { KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL, "Failed to enable indicated offload capabilities!!\n")); ai->ai_OffloadFlags = 0; ai->ai_IPSecOffloadFlags = 0; } return TRUE; } //**QueryOffload - Query offload capabilities // // Input: // ai - ARPInterface for which we are initializing // the task offload header. // Returns: // TRUE/FALSE - Success/Failure to query/set // BOOLEAN QueryAndSetOffload(ARPInterface *ai) { PNDIS_TASK_OFFLOAD_HEADER TaskOffloadHeader; NDIS_STATUS Status; BOOLEAN stat; uint Needed = 0; uchar *buffer; // Query and set checksum capability TaskOffloadHeader = CTEAllocMemNBoot(sizeof(NDIS_TASK_OFFLOAD_HEADER), '8ICT'); Status = STATUS_BUFFER_OVERFLOW; if (TaskOffloadHeader) { InitTaskOffloadHeader(ai, TaskOffloadHeader); Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_TCP_TASK_OFFLOAD, TaskOffloadHeader, sizeof(NDIS_TASK_OFFLOAD_HEADER), &Needed, TRUE); // Need to initialize Needed to the real size of the buffer. The NDIS // call may not init on success. if (Status == NDIS_STATUS_SUCCESS) { Needed = sizeof(NDIS_TASK_OFFLOAD_HEADER); } else if ((Status == NDIS_STATUS_INVALID_LENGTH) || (Status == NDIS_STATUS_BUFFER_TOO_SHORT)) { // We know the size we need. Allocate a buffer. ASSERT(Needed >= sizeof(NDIS_TASK_OFFLOAD_HEADER)); buffer = CTEAllocMemNBoot(Needed, '9ICT'); KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL, "Calling OID_TCP_TASK_OFFLOAD with %d bytes\n", Needed)); if (buffer != NULL) { CTEFreeMem(TaskOffloadHeader); TaskOffloadHeader = (PNDIS_TASK_OFFLOAD_HEADER) buffer; InitTaskOffloadHeader(ai, TaskOffloadHeader); Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_TCP_TASK_OFFLOAD, buffer, Needed, NULL, TRUE); } } } if ((Status != NDIS_STATUS_SUCCESS) || (TaskOffloadHeader && TaskOffloadHeader->OffsetFirstTask == 0)) { //Make sure that the flag is null. ai->ai_OffloadFlags = 0; ai->ai_IPSecOffloadFlags = 0; if (TaskOffloadHeader) { CTEFreeMem(TaskOffloadHeader); } return FALSE; } if (TaskOffloadHeader) { stat = SetOffload(ai, TaskOffloadHeader, Needed); CTEFreeMem(TaskOffloadHeader); return stat; } return FALSE; } //** ARPRegister - Register a protocol with the ARP module. // // We register a protocol for ARP processing. We also open the // NDIS adapter here. // // Note that much of the information passed in here is unused, as // ARP currently only works with IP. // // Entry: // Adapter - Name of the adapter to bind to. // IPContext - Value to be passed to IP on upcalls. // int ARPRegister(PNDIS_STRING Adapter, uint *Flags, struct ARPInterface **Interface) { ARPInterface *ai; // Pointer to interface struct. for this interface. NDIS_STATUS Status, OpenStatus; // Status values. uint i = 0; // Medium index. NDIS_MEDIUM MediaArray[MAX_MEDIA]; uint mss; uint speed; uint MacOpts; uchar bcastmask, bcastval, bcastoff, addrlen, hdrsize, snapsize; uint OID; uint PF; TRANSPORT_HEADER_OFFSET IPHdrOffset; CTELockHandle LockHandle; UINT MediaType; NDIS_STRING NdisString; DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("+ARPRegister(%x, %x, %x)\n"), Adapter, Flags, Interface)); if ((ai = CTEAllocMemNBoot(sizeof(ARPInterface), '4ICT')) == (ARPInterface *) NULL) return FALSE; // Couldn't allocate memory for this one. *Interface = ai; RtlZeroMemory(ai, sizeof(ARPInterface)); CTEInitTimer(&ai->ai_timer); ai->ai_timerstarted = FALSE; ai->ai_stoptimer = FALSE; MediaArray[MEDIA_DIX] = NdisMedium802_3; MediaArray[MEDIA_TR] = NdisMedium802_5; MediaArray[MEDIA_FDDI] = NdisMediumFddi; MediaArray[MEDIA_ARCNET] = NdisMediumArcnet878_2; // Initialize this adapter interface structure. ai->ai_operstatus = INTERFACE_INIT; ai->ai_adminstate = IF_STATUS_UNKNOWN; ai->ai_mediastatus = FALSE; ai->ai_lastchange = GetTimeTicks(); ai->ai_bcast = IP_LOCAL_BCST; ai->ai_atinst = ai->ai_ifinst = (UINT)INVALID_ENTITY_INSTANCE; ai->ai_telladdrchng = 1; //Initially let us do try to do network layer address stuff // Initialize the locks. CTEInitLock(&ai->ai_lock); CTEInitLock(&ai->ai_ARPTblLock); GetAlwaysSourceRoute(&sArpAlwaysSourceRoute, &sIPAlwaysSourceRoute); ArpCacheLife = GetArpCacheLife(); if (!ArpCacheLife) { ArpCacheLife = 1; } ArpCacheLife = (ArpCacheLife * 1000L) / ARP_TIMER_TIME; ArpRetryCount = GetArpRetryCount(); if (!ArpMinValidCacheLife) { ArpMinValidCacheLife = 1; } // Allocate the buffer and packet pools. NdisAllocatePacketPoolEx(&Status, &ai->ai_ppool, ARP_DEFAULT_PACKETS, ARP_DEFAULT_PACKETS * 1000, sizeof(struct PCCommon)); if (Status != NDIS_STATUS_SUCCESS) { FreeARPInterface(ai); return FALSE; } // Allocate the ARP table ai->ai_ARPTbl = (ARPTable *) CTEAllocMemNBoot(ARP_TABLE_SIZE * sizeof(ARPTableEntry*), '5ICT'); if (ai->ai_ARPTbl == (ARPTable *) NULL) { FreeARPInterface(ai); return FALSE; } // // NULL out the pointers // RtlZeroMemory(ai->ai_ARPTbl, ARP_TABLE_SIZE * sizeof(ARPTableEntry *)); // Allocate the Counters Structure with best effort in avoiding false sharing ai->ai_qlen = CTEAllocMem(KeNumberProcessors * sizeof(PP_AI_COUNTERS)); if (ai->ai_qlen == (PPP_AI_COUNTERS) NULL) { FreeARPInterface(ai); return FALSE; } RtlZeroMemory(ai->ai_qlen, KeNumberProcessors * sizeof(PP_AI_COUNTERS)); CTEInitBlockStruc(&ai->ai_block); DEBUGMSG(DBG_INFO && DBG_PNP, (DTEXT("ARPRegister calling NdisOpenAdapter\n"))); // Open the NDIS adapter. NdisOpenAdapter(&Status, &OpenStatus, &ai->ai_handle, &i, MediaArray, MAX_MEDIA, ARPHandle, ai, Adapter, 0, NULL); // Block for open to complete. if (Status == NDIS_STATUS_PENDING) Status = (NDIS_STATUS) CTEBlock(&ai->ai_block); ai->ai_media = MediaArray[i]; // Fill in media type. // Open adapter completed. If it succeeded, we'll finish our intialization. // If it failed, bail out now. if (Status != NDIS_STATUS_SUCCESS) { ai->ai_handle = NULL; FreeARPInterface(ai); return FALSE; } #if FFP_SUPPORT // Store NIC driver handle NdisGetDriverHandle(ai->ai_handle, &ai->ai_driver); #endif // Read the local address. switch (ai->ai_media) { case NdisMedium802_3: addrlen = ARP_802_ADDR_LENGTH; bcastmask = ENET_BCAST_MASK; bcastval = ENET_BCAST_VAL; bcastoff = ENET_BCAST_OFF; OID = OID_802_3_CURRENT_ADDRESS; hdrsize = sizeof(ENetHeader); if (!UseEtherSNAP(Adapter)) { snapsize = 0; } else { snapsize = sizeof(SNAPHeader); } PF = NDIS_PACKET_TYPE_BROADCAST | \ NDIS_PACKET_TYPE_DIRECTED | \ NDIS_PACKET_TYPE_MULTICAST; ai->ai_mediatype = IF_TYPE_IS088023_CSMACD; break; case NdisMedium802_5: addrlen = ARP_802_ADDR_LENGTH; bcastmask = TR_BCAST_MASK; bcastval = TR_BCAST_VAL; bcastoff = TR_BCAST_OFF; OID = OID_802_5_CURRENT_ADDRESS; hdrsize = sizeof(TRHeader); snapsize = sizeof(SNAPHeader); PF = NDIS_PACKET_TYPE_BROADCAST | NDIS_PACKET_TYPE_DIRECTED; ai->ai_mediatype = IF_TYPE_ISO88025_TOKENRING; break; case NdisMediumFddi: addrlen = ARP_802_ADDR_LENGTH; bcastmask = FDDI_BCAST_MASK; bcastval = FDDI_BCAST_VAL; bcastoff = FDDI_BCAST_OFF; OID = OID_FDDI_LONG_CURRENT_ADDR; hdrsize = sizeof(FDDIHeader); snapsize = sizeof(SNAPHeader); PF = NDIS_PACKET_TYPE_BROADCAST | \ NDIS_PACKET_TYPE_DIRECTED | \ NDIS_PACKET_TYPE_MULTICAST; ai->ai_mediatype = IF_TYPE_FDDI; break; case NdisMediumArcnet878_2: addrlen = 1; bcastmask = ARC_BCAST_MASK; bcastval = ARC_BCAST_VAL; bcastoff = ARC_BCAST_OFF; OID = OID_ARCNET_CURRENT_ADDRESS; hdrsize = sizeof(ARCNetHeader); snapsize = 0; PF = NDIS_PACKET_TYPE_BROADCAST | NDIS_PACKET_TYPE_DIRECTED; ai->ai_mediatype = IF_TYPE_ARCNET; break; default: ASSERT(0); FreeARPInterface(ai); return FALSE; } ai->ai_bcastmask = bcastmask; ai->ai_bcastval = bcastval; ai->ai_bcastoff = bcastoff; ai->ai_addrlen = addrlen; ai->ai_hdrsize = hdrsize; ai->ai_snapsize = snapsize; ai->ai_pfilter = PF; Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID, ai->ai_addr, addrlen, NULL, TRUE); if (Status != NDIS_STATUS_SUCCESS) { FreeARPInterface(ai); return FALSE; } // Read the maximum frame size. if ((Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_GEN_MAXIMUM_FRAME_SIZE, &mss, sizeof(mss), NULL, TRUE)) != NDIS_STATUS_SUCCESS) { FreeARPInterface(ai); return FALSE; } // If this is token ring, figure out the RC len stuff now. mss -= (uint) ai->ai_snapsize; if (ai->ai_media == NdisMedium802_5) { mss -= (sizeof(RC) + (ARP_MAX_RD * sizeof(ushort))); } else { if (ai->ai_media == NdisMediumFddi) { mss = MIN(mss, ARP_FDDI_MSS); } } ai->ai_mtu = (ushort) mss; // Read the speed for local purposes. if ((Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_GEN_LINK_SPEED, &speed, sizeof(speed), NULL, TRUE)) == NDIS_STATUS_SUCCESS) { ai->ai_speed = speed * 100L; } // Read and save the options. Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_GEN_MAC_OPTIONS, &MacOpts, sizeof(MacOpts), NULL, TRUE); if (Status != NDIS_STATUS_SUCCESS) { *Flags = 0; } else { *Flags = (MacOpts & NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA) ? LIP_COPY_FLAG : 0; } if (CTEMemCmp(ai->ai_addr, PPP_HW_ADDR, PPP_HW_ADDR_LEN) == 0) { *Flags = *Flags | LIP_P2P_FLAG; } // // Query the media capability to determine if it is a uni-directional adapter. // Status = DoNDISRequest( ai, NdisRequestQueryInformation, OID_GEN_MEDIA_CAPABILITIES, &MediaType, sizeof(MediaType), NULL, TRUE); // Blocking. if (Status == NDIS_STATUS_SUCCESS) { // Bit field of Rx and Tx. If only Rx, set uni flag. if (MediaType == NDIS_MEDIA_CAP_RECEIVE) { DEBUGMSG(DBG_WARN, (DTEXT("ARPRegister: ai %x: MEDIA_CAP_RX -> UniAdapter!!\n"), ai)); *Flags |= LIP_UNI_FLAG; InterlockedIncrement( (PLONG) &cUniAdapters); } } // Read and store the vendor description string. Status = NdisQueryAdapterInstanceName(&NdisString, ai->ai_handle); if (Status == NDIS_STATUS_SUCCESS) { ANSI_STRING AnsiString; // Convert the string to ANSI, and use the new ANSI string's buffer // to store the description in the ARP interface. // N.B. The conversion results in a nul-terminated string. Status = RtlUnicodeStringToAnsiString(&AnsiString, &NdisString, TRUE); if (Status == STATUS_SUCCESS) { ai->ai_desc = AnsiString.Buffer; ai->ai_desclen = (uint)strlen(AnsiString.Buffer) + 1; } NdisFreeString(NdisString); } if (!ArpEnetHeaderPool || !ArpAuxHeaderPool) { PVOID SectionHandle; // Allocate our small and big buffer pools. Take the interface list // lock simply to protect creating of the buffer pools if we haven't // already done so. We could have used our own lock, but the interface // list lock is global, and not already used in this path. // // This routine is in pageable memory. Since getting the lock // requires writable access to LockHandle at DISPATCH, we need to // lock this code in. // SectionHandle = MmLockPagableCodeSection(ARPRegister); CTEGetLock(&ArpInterfaceListLock.Lock, &LockHandle); if (!ArpEnetHeaderPool) { ArpEnetHeaderPool = MdpCreatePool(BUFSIZE_ENET_HEADER_POOL, 'ehCT'); } if (!ArpAuxHeaderPool) { ArpAuxHeaderPool = MdpCreatePool(BUFSIZE_AUX_HEADER_POOL, 'ahCT'); } CTEFreeLock(&ArpInterfaceListLock.Lock, LockHandle); MmUnlockPagableImageSection(SectionHandle); if (!ArpAuxHeaderPool || !ArpEnetHeaderPool) { FreeARPInterface(ai); return FALSE; } } ai->ai_promiscuous = 0; #if FFP_SUPPORT { FFPVersionParams Version = { NDIS_PROTOCOL_ID_TCP_IP, 0 }; // Initialize all FFP Handling Variables ai->ai_ffpversion = 0; ai->ai_ffplastflush = 0; // Query FFP Handling capabilities Status = DoNDISRequest(ai, NdisRequestQueryInformation, OID_FFP_SUPPORT, &Version, sizeof(FFPVersionParams), NULL, TRUE); // Non-Zero Value indicates FFP support if (Version.FFPVersion) { // Set the FFP startup parameters FFPSupportParams Info; Info.NdisProtocolType = NDIS_PROTOCOL_ID_TCP_IP; Info.FastForwardingCacheSize = FFPRegFastForwardingCacheSize; Info.FFPControlFlags = FFPRegControlFlags; // But store away the version first ai->ai_ffpversion = Version.FFPVersion; DoNDISRequest(ai, NdisRequestSetInformation, OID_FFP_SUPPORT, &Info, sizeof(FFPSupportParams), NULL, TRUE); TCPTRACE(("Setting FFP capabilities: Cache Size = %lu, Flags = %08x\n", Info.FastForwardingCacheSize, Info.FFPControlFlags)); } } #endif // if FFP_SUPPORT ai->ai_OffloadFlags = 0; ai->ai_IPSecOffloadFlags = 0; if (DisableTaskOffload) { KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Taskoffload disabled\n")); } else { if(!QueryAndSetOffload(ai)){ DEBUGMSG(DBG_ERROR, (DTEXT("ARP: Query and set offload failed.\n"))); } } // query the wakeup capabilities. Status = DoNDISRequest( ai, NdisRequestQueryInformation, OID_PNP_CAPABILITIES, &ai->ai_wakeupcap, sizeof(NDIS_PNP_CAPABILITIES), NULL, TRUE); if (Status == NDIS_STATUS_SUCCESS) { uint wakeup = NDIS_PNP_WAKE_UP_PATTERN_MATCH; // enable wakeup capabilities. Status = DoNDISRequest( ai, NdisRequestSetInformation, OID_PNP_ENABLE_WAKE_UP, &wakeup, sizeof(wakeup), NULL, TRUE); if (Status != NDIS_STATUS_SUCCESS) { ai->ai_wakeupcap.WakeUpCapabilities.MinPatternWakeUp = NdisDeviceStateUnspecified; } } // Store the device name, we need to pass this to our TDI clients when // we do the PNP notification. if ((ai->ai_devicename.Buffer = CTEAllocMemNBoot(Adapter->MaximumLength, 'aICT')) == NULL) { FreeARPInterface(ai); return FALSE; } RtlCopyMemory(ai->ai_devicename.Buffer, Adapter->Buffer, Adapter->MaximumLength); ai->ai_devicename.Length = Adapter->Length; ai->ai_devicename.MaximumLength = Adapter->MaximumLength; ai->ai_timerstarted = TRUE; IPHdrOffset.HeaderOffset = ai->ai_snapsize + ai->ai_hdrsize; IPHdrOffset.ProtocolType = NDIS_PROTOCOL_ID_TCP_IP; Status = DoNDISRequest(ai, NdisRequestSetInformation, OID_GEN_TRANSPORT_HEADER_OFFSET, &IPHdrOffset, sizeof(TRANSPORT_HEADER_OFFSET), NULL, TRUE); // Everything's set up, so get the ARP timer running. CTEStartTimer(&ai->ai_timer, ARP_TIMER_TIME, ARPTimeout, ai); return TRUE; } #pragma END_INIT //* ARPDynRegister - Dynamically register IP. // // Called by IP when he's about done binding to register with us. Since we // call him directly, we don't save his info here. We do keep his context // and index number. // // Input: See ARPRegister // // Returns: Nothing. // int __stdcall ARPDynRegister( IN PNDIS_STRING Adapter, IN void *IPContext, IN struct _IP_HANDLERS *IpHandlers, OUT struct LLIPBindInfo *Info, IN uint NumIFBound) { ARPInterface *Interface = (ARPInterface *) Info->lip_context; UNREFERENCED_PARAMETER(Adapter); UNREFERENCED_PARAMETER(IpHandlers); Interface->ai_context = IPContext; Interface->ai_index = NumIFBound; // TCPTRACE(("Arp Interface %lx ai_context %lx ai_index %lx\n",Interface, Interface->ai_context, Interface->ai_index)); return TRUE; } //* ARPBindAdapter - Bind and initialize an adapter. // // Called in a PNP environment to initialize and bind an adapter. We open // the adapter and get it running, and then we call up to IP to tell him // about it. IP will initialize, and if all goes well call us back to start // receiving. // // Input: RetStatus - Where to return the status of this call. // BindContext - Handle to use for calling BindAdapterComplete. // AdapterName - Pointer to name of adapter. // SS1 - System specific 1 parameter. // SS2 - System specific 2 parameter. // // Returns: Nothing. // void NDIS_API ARPBindAdapter(PNDIS_STATUS RetStatus, NDIS_HANDLE BindContext, PNDIS_STRING AdapterName, PVOID SS1, PVOID SS2) { uint Flags; // MAC binding flags. ARPInterface *Interface; // Newly created interface. IP_STATUS Status; // State of IPAddInterface call. LLIPBindInfo BindInfo; // Binding information for IP. NDIS_HANDLE Handle; NDIS_STRING IPConfigName; DBG_UNREFERENCED_PARAMETER(BindContext); DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("+ARPBindAdapter(%x, %x, %x, %x, %x)\n"), RetStatus, BindContext, AdapterName, SS1, SS2)); if (!OpenIFConfig(SS1, &Handle)) { *RetStatus = NDIS_STATUS_FAILURE; DEBUGMSG(DBG_ERROR && DBG_PNP, (DTEXT("ARPBindAdapter: Open failure\n"))); DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("-ARPBindAdapter [%x]\n"), *RetStatus)); return; } #if !MILLEN if ((*RetStatus = GetIPConfigValue(Handle, &IPConfigName)) != NDIS_STATUS_SUCCESS) { CloseIFConfig(Handle); DEBUGMSG(DBG_ERROR && DBG_PNP, (DTEXT("ARPBindAdapter: GetIPConfigValue failure\n"))); DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("-ARPBindAdapter [%x]\n"), *RetStatus)); return; } #endif // !MILLEN CloseIFConfig(Handle); // First, open the adapter and get the info. if (!ARPRegister(AdapterName, &Flags, &Interface)) { #if !MILLEN CTEFreeMem(IPConfigName.Buffer); #endif // !MILLEN *RetStatus = NDIS_STATUS_FAILURE; DEBUGMSG(DBG_ERROR && DBG_PNP, (DTEXT("ARPBindAdapter: ARPRegister failure\n"))); DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("-ARPBindAdapter [%x]\n"), *RetStatus)); return; } // OK, we're opened the adapter. Call IP to tell him about it. BindInfo.lip_context = Interface; BindInfo.lip_transmit = ARPTransmit; BindInfo.lip_transfer = ARPXferData; BindInfo.lip_close = ARPClose; BindInfo.lip_addaddr = ARPAddAddr; BindInfo.lip_deladdr = ARPDeleteAddr; BindInfo.lip_invalidate = ARPInvalidate; BindInfo.lip_open = ARPOpen; BindInfo.lip_qinfo = ARPQueryInfo; BindInfo.lip_setinfo = ARPSetInfo; BindInfo.lip_getelist = ARPGetEList; BindInfo.lip_dondisreq = DoNDISRequest; BindInfo.lip_mss = Interface->ai_mtu; BindInfo.lip_speed = Interface->ai_speed; BindInfo.lip_flags = Flags; BindInfo.lip_addrlen = Interface->ai_addrlen; BindInfo.lip_addr = Interface->ai_addr; BindInfo.lip_dowakeupptrn = DoWakeupPattern; BindInfo.lip_pnpcomplete = ARPPnPComplete; BindInfo.lip_setndisrequest = ARPSetNdisRequest; BindInfo.lip_arpresolveip = ARPResolveIP; BindInfo.lip_arpflushate = ARPFlushATE; BindInfo.lip_arpflushallate = ARPFlushAllATE; #if !MILLEN BindInfo.lip_cancelpackets = ARPCancelPackets; #endif #if FFP_SUPPORT // NDIS Driver Handle, FFP Version are passed up // [ Non zero version implies FFP Support exists ] BindInfo.lip_ffpversion = Interface->ai_ffpversion; BindInfo.lip_ffpdriver = (ULONG_PTR) Interface->ai_driver; #endif //Interface capability is passed on to IP via BindInfo BindInfo.lip_OffloadFlags = Interface->ai_OffloadFlags; BindInfo.lip_IPSecOffloadFlags = Interface->ai_IPSecOffloadFlags; BindInfo.lip_MaxOffLoadSize = (uint) Interface->ai_TcpLargeSend.MaxOffLoadSize; BindInfo.lip_MaxSegments = (uint) Interface->ai_TcpLargeSend.MinSegmentCount; BindInfo.lip_closelink = NULL; BindInfo.lip_pnpcap = Interface->ai_wakeupcap.Flags; DEBUGMSG(DBG_INFO && DBG_PNP, (DTEXT("ARPBindAdapter calling IPAddInterface.\n"))); Status = IPAddInterface(AdapterName, NULL, #if MILLEN (PNDIS_STRING) SS1, #else // MILLEN (PNDIS_STRING) & IPConfigName, #endif // !MILLEN SS2, Interface, ARPDynRegister, &BindInfo, 0, Interface->ai_mediatype, IF_ACCESS_BROADCAST, IF_CONNECTION_DEDICATED); #if !MILLEN CTEFreeMem(IPConfigName.Buffer); #endif // !MILLEN if (Status != IP_SUCCESS) { // Need to close the binding. FreeARPInterface will do that, as well // as freeing resources. DEBUGMSG(DBG_ERROR && DBG_PNP, (DTEXT("ARPBindAdapter: IPAddInterface failure %x\n"), Status)); FreeARPInterface(Interface); *RetStatus = NDIS_STATUS_FAILURE; } else { // // Insert into ARP IF list // ExInterlockedInsertTailList(&ArpInterfaceList, &Interface->ai_linkage, &ArpInterfaceListLock.Lock); *RetStatus = NDIS_STATUS_SUCCESS; } DEBUGMSG(DBG_TRACE && DBG_PNP, (DTEXT("-ARPBindAdapter [%x]\n"), *RetStatus)); } //* ARPUnbindAdapter - Unbind from an adapter. // // Called when we need to unbind from an adapter. We'll call up to IP to tell // him. When he's done, we'll free our memory and return. // // Input: RetStatus - Where to return status from call. // ProtBindContext - The context we gave NDIS earlier - really a // pointer to an ARPInterface structure. // UnbindContext - Context for completeing this request. // // Returns: Nothing. // void NDIS_API ARPUnbindAdapter(PNDIS_STATUS RetStatus, NDIS_HANDLE ProtBindContext, NDIS_HANDLE UnbindContext) { ARPInterface *Interface = (ARPInterface *) ProtBindContext; NDIS_STATUS Status; // Status of close call. CTELockHandle LockHandle; // Shut him up, so we don't get any more frames. Interface->ai_pfilter = 0; if (Interface->ai_handle != NULL) { DoNDISRequest(Interface, NdisRequestSetInformation, OID_GEN_CURRENT_PACKET_FILTER, &Interface->ai_pfilter, sizeof(uint), NULL, TRUE); } CTEInitBlockStrucEx(&Interface->ai_timerblock); Interface->ai_stoptimer = TRUE; // Mark him as down. Interface->ai_adminstate = IF_STATUS_DOWN; ARPUpdateOperStatus(Interface); // Mark the interface as going away so it will disappear from the // entity list. Interface->ai_operstatus = INTERFACE_UNINIT; #if FFP_SUPPORT // Stop FFP on this interface Interface->ai_ffpversion = 0; #endif KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Flushing all ates %x\n", Interface)); ARPFlushAllATE(Interface); // Now tell IP he's gone. We need to make sure that we don't tell him twice. // To do this we set the context to NULL after we tell him the first time, // and we check to make sure it's non-NULL before notifying him. if (Interface->ai_context != NULL) { IPDelInterface(Interface->ai_context, TRUE); Interface->ai_context = NULL; } // Finally, close him. We do this here so we can return a valid status. CTEGetLock(&Interface->ai_lock, &LockHandle); if (Interface->ai_handle != NULL) { NDIS_HANDLE Handle = Interface->ai_handle; CTEFreeLock(&Interface->ai_lock, LockHandle); CTEInitBlockStruc(&Interface->ai_block); NdisCloseAdapter(&Status, Handle); // Block for close to complete. if (Status == NDIS_STATUS_PENDING) { Status = (NDIS_STATUS) CTEBlock(&Interface->ai_block); } Interface->ai_handle = NULL; } else { CTEFreeLock(&Interface->ai_lock, LockHandle); Status = NDIS_STATUS_SUCCESS; } //Check if are called from ARPUnload if ((ARPInterface *) UnbindContext != Interface) { CTELockHandle Handle; //No. Acquire lock and remove entry. CTEGetLock(&ArpInterfaceListLock.Lock, &Handle); RemoveEntryList(&Interface->ai_linkage); CTEFreeLock(&ArpInterfaceListLock.Lock, Handle); } *RetStatus = Status; if (Status == NDIS_STATUS_SUCCESS) { FreeARPInterface(Interface); } } extern ulong VIPTerminate; //* ARPUnloadProtocol - Unload. // // Called when we need to unload. All we do is call up to IP, and return. // // Input: Nothing. // // Returns: Nothing. // void NDIS_API ARPUnloadProtocol(void) { #if MILLEN DEBUGMSG(1, (DTEXT("ARPUnloadProtocol called! What to do???\n"))); #endif // MILLEN } VOID ArpUnload(IN PDRIVER_OBJECT DriverObject) /*++ Routine Description: This routine unloads the TCPIP stack. It unbinds from any NDIS drivers that are open and frees all resources associated with the transport. The I/O system will not call us until nobody above has IPX open. NOTE: Also, since other ARP modules depend on IP, they are unloaded before out unload handler is called. We concern ourselves with the LAN arp only at this point Arguments: DriverObject - Pointer to driver object created by the system. Return Value: None. When the function returns, the driver is unloaded. --*/ { PLIST_ENTRY pEntry; CTELockHandle LockHandle; NDIS_STATUS status; ARPInterface *Interface; // // Walk the list of opened ARP interfaces, issuing // PnP deletes on each in turn. // CTEGetLock(&ArpInterfaceListLock.Lock, &LockHandle); while(!IsListEmpty(&ArpInterfaceList)) { pEntry = ArpInterfaceList.Flink; Interface = STRUCT_OF(ARPInterface, pEntry, ai_linkage); RemoveEntryList(&Interface->ai_linkage); CTEFreeLock(&ArpInterfaceListLock.Lock, LockHandle); // KdPrintEx((DPFLTR_TCPIP_ID, DPFLTR_INFO_LEVEL,"Issuing unbind on %lx\n", Interface)); ARPUnbindAdapter(&status, Interface, Interface); CTEGetLock(&ArpInterfaceListLock.Lock, &LockHandle); } CTEFreeLock(&ArpInterfaceListLock.Lock, LockHandle); MdpDestroyPool(ArpEnetHeaderPool); MdpDestroyPool(ArpAuxHeaderPool); // // Deal with any residual events/timers // Only one timer sits at this layer: ai_timer, which is stopped // on the unbind above. // // // call into IP so it can cleanup. // IPUnload(DriverObject); }
545128.c
/* add zurita 345 Registro hecho add angel 999 Registro hecho add yoselin 888 Registro hecho add alejandro 4675 Registro hecho add samuel 5555 Registro hecho add christo 1244 Registro hecho add maury 999913 Registro hecho add alejandro 999 Este usuario ya estaba registrado view alejandro angel christo maury samuel yoselin zurita ^C */ #include <stdio.h> #include <string.h> // strstr #include <stdlib.h> // malloc & free #include <ctype.h> // isspace & tolower #define MAX 80 char linea[MAX], password[MAX], user[MAX]; int saca(); // Function that give us the line void get (char l[MAX],char p[MAX],char u[MAX]); /* Function that give us the user and the password and agrega gente*/ typedef struct treenode { char* user; //usuario char* password; //contraseña struct treenode* leftChild; struct treenode* rightChild; unsigned int depth; } node; node* insert(char* u, char* p, node* pos, int d) { node* temp; if (pos == NULL) { pos = (node*)malloc(sizeof(node)); pos->user = u; pos->password = p; pos->depth = d; printf("Registro hecho\n\n"); /* int strcmp(const char *cadena1, const char *cadena2); Devuelve 0 si las cadenas de texto son iguales (incluyendo mayúsculas y minúsculas); si la primera cadena es mayor que la segunda, devuelve un número positivo; si es mayor la segunda, devuelve un valor negativo. Existen variantes (no estándar, dependientes del compilador) que comparar dos cadenas despreciando mayúsculas y minúsculas, como stricmp */ } else { if (strcmp(pos->user, u) == 0) { printf("Este usuario ya estaba registrado\n\n"); } else if (strcmp(pos->user, u)>0) { // value is smaller si pos->value > value /*printf("Registro algo menor\n\n");*/ temp = insert(u, p, pos->leftChild, d + 1); if (pos->leftChild == NULL) { pos->leftChild = temp; } } else if (strcmp(pos->user, u)<0){ temp = insert(u, p, pos->rightChild, d + 1); // value is larger /*printf("Registro algo mayor\n\n");*/ if (pos->rightChild == NULL) { pos->rightChild = temp; } } } return pos; } void alpha(node* position) { if (position != NULL) { alpha(position->leftChild); printf("%s ", position->user); alpha(position->rightChild); } } int main() { extern char linea[]; node* n = NULL; node* tree = NULL; int l = 0; char* u;//// n es el tamaño del arreglo unidimencional puede ver mas de esto en argdemo.c char* p; int i; while ((l = saca()) == 0) { if (strstr(linea, "del") != NULL&&strlen(linea)>=7) { // if we found "del" we need to delete get(linea, password, user); u = (char*)malloc(sizeof(int*) * strlen(user)); p = (char*)malloc(sizeof(int*) * strlen(password)); for (i=0; i<strlen(user);i++){ u[i]=user[i]; } for (i=0; i<strlen(password);i++){ p[i]=password[i]; } printf ("%s %s end\n", password, user); printf ("%s %s end\n", p, u); /// De este modo es igual usar p o password } else if (strstr(linea, "add") != NULL&&strlen(linea)>=7) { // if we found "add" we need to add get(linea, password, user); u = (char*)malloc(sizeof(int*) * strlen(user)); p = (char*)malloc(sizeof(int*) * strlen(password)); for (i=0; i<strlen(user);i++){ u[i]=user[i]; } for (i=0; i<strlen(password);i++){ p[i]=password[i]; } /* printf ("%s %s end\n", password, user); printf ("%s %s end\n", p, u);*/ /// De este modo es igual usar p o password n = insert(u,p, tree, 0); if (tree == NULL) { tree = n; // this is the root } } else if (strstr(linea, "view") != NULL) { // if we found "show" we need to show alpha(tree); printf("\n"); } else{ printf("Checa tu entrada\n"); } } /// Here return 0; } int saca() { // Function that give us the line, modification of a SATU ELISA SCHAEFFER code Longest2.c nocomment.c extern char linea[]; int c, i = 0; for (; i < MAX - 1 && (c = getchar()) != EOF && c != '\n';) { linea[i++] = c; } linea[i] = '\0'; // caracter end of string return c == EOF; } void get (char l[MAX],char p[MAX],char u[MAX]){ int a = 4, b = 0, c=0; while (l[a]!=' '&&l[a]!='\t'){ u[b]=l[a]; b++; a++; } u[b]='\0'; int longitud = strlen(u); a++; while (l[a]!=' '&&l[a]!='\t'&&l[a]!='\0'){ p[c]=l[a]; c++; a++; } p[c]='\0'; int longitud2 = strlen(p); }
32158.c
/* v3_info.c */ /* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL * project 1999. */ /* ==================================================================== * Copyright (c) 1999 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * ([email protected]). This product includes software written by Tim * Hudson ([email protected]). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1_mac.h> #include <openssl/x509v3.h> static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD *method, STACK_OF(ACCESS_DESCRIPTION) *ainfo, STACK_OF(CONF_VALUE) *ret); static STACK_OF(ACCESS_DESCRIPTION) *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval); X509V3_EXT_METHOD v3_info = { NID_info_access, X509V3_EXT_MULTILINE, (X509V3_EXT_NEW)AUTHORITY_INFO_ACCESS_new, (X509V3_EXT_FREE)AUTHORITY_INFO_ACCESS_free, (X509V3_EXT_D2I)d2i_AUTHORITY_INFO_ACCESS, (X509V3_EXT_I2D)i2d_AUTHORITY_INFO_ACCESS, NULL, NULL, (X509V3_EXT_I2V)i2v_AUTHORITY_INFO_ACCESS, (X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS, NULL, NULL, NULL}; static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD *method, STACK_OF(ACCESS_DESCRIPTION) *ainfo, STACK_OF(CONF_VALUE) *ret) { ACCESS_DESCRIPTION *desc; int i; char objtmp[80], *ntmp; CONF_VALUE *vtmp; for(i = 0; i < sk_ACCESS_DESCRIPTION_num(ainfo); i++) { desc = sk_ACCESS_DESCRIPTION_value(ainfo, i); ret = i2v_GENERAL_NAME(method, desc->location, ret); if(!ret) break; vtmp = sk_CONF_VALUE_value(ret, i); i2t_ASN1_OBJECT(objtmp, 80, desc->method); ntmp = OPENSSL_malloc(strlen(objtmp) + strlen(vtmp->name) + 5); if(!ntmp) { X509V3err(X509V3_F_I2V_AUTHORITY_INFO_ACCESS, ERR_R_MALLOC_FAILURE); return NULL; } strcpy(ntmp, objtmp); strcat(ntmp, " - "); strcat(ntmp, vtmp->name); OPENSSL_free(vtmp->name); vtmp->name = ntmp; } if(!ret) return sk_CONF_VALUE_new_null(); return ret; } static STACK_OF(ACCESS_DESCRIPTION) *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD *method, X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval) { STACK_OF(ACCESS_DESCRIPTION) *ainfo = NULL; CONF_VALUE *cnf, ctmp; ACCESS_DESCRIPTION *acc; int i, objlen; char *objtmp, *ptmp; if(!(ainfo = sk_ACCESS_DESCRIPTION_new_null())) { X509V3err(X509V3_F_V2I_ACCESS_DESCRIPTION,ERR_R_MALLOC_FAILURE); return NULL; } for(i = 0; i < sk_CONF_VALUE_num(nval); i++) { cnf = sk_CONF_VALUE_value(nval, i); if(!(acc = ACCESS_DESCRIPTION_new()) || !sk_ACCESS_DESCRIPTION_push(ainfo, acc)) { X509V3err(X509V3_F_V2I_ACCESS_DESCRIPTION,ERR_R_MALLOC_FAILURE); goto err; } ptmp = strchr(cnf->name, ';'); if(!ptmp) { X509V3err(X509V3_F_V2I_ACCESS_DESCRIPTION,X509V3_R_INVALID_SYNTAX); goto err; } objlen = ptmp - cnf->name; ctmp.name = ptmp + 1; ctmp.value = cnf->value; if(!(acc->location = v2i_GENERAL_NAME(method, ctx, &ctmp))) goto err; if(!(objtmp = OPENSSL_malloc(objlen + 1))) { X509V3err(X509V3_F_V2I_ACCESS_DESCRIPTION,ERR_R_MALLOC_FAILURE); goto err; } strncpy(objtmp, cnf->name, objlen); objtmp[objlen] = 0; acc->method = OBJ_txt2obj(objtmp, 0); if(!acc->method) { X509V3err(X509V3_F_V2I_ACCESS_DESCRIPTION,X509V3_R_BAD_OBJECT); ERR_add_error_data(2, "value=", objtmp); OPENSSL_free(objtmp); goto err; } OPENSSL_free(objtmp); } return ainfo; err: sk_ACCESS_DESCRIPTION_pop_free(ainfo, ACCESS_DESCRIPTION_free); return NULL; } int i2d_ACCESS_DESCRIPTION(ACCESS_DESCRIPTION *a, unsigned char **pp) { M_ASN1_I2D_vars(a); M_ASN1_I2D_len(a->method, i2d_ASN1_OBJECT); M_ASN1_I2D_len(a->location, i2d_GENERAL_NAME); M_ASN1_I2D_seq_total(); M_ASN1_I2D_put(a->method, i2d_ASN1_OBJECT); M_ASN1_I2D_put(a->location, i2d_GENERAL_NAME); M_ASN1_I2D_finish(); } ACCESS_DESCRIPTION *ACCESS_DESCRIPTION_new(void) { ACCESS_DESCRIPTION *ret=NULL; ASN1_CTX c; M_ASN1_New_Malloc(ret, ACCESS_DESCRIPTION); ret->method = OBJ_nid2obj(NID_undef); ret->location = NULL; return (ret); M_ASN1_New_Error(ASN1_F_ACCESS_DESCRIPTION_NEW); } ACCESS_DESCRIPTION *d2i_ACCESS_DESCRIPTION(ACCESS_DESCRIPTION **a, unsigned char **pp, long length) { M_ASN1_D2I_vars(a,ACCESS_DESCRIPTION *,ACCESS_DESCRIPTION_new); M_ASN1_D2I_Init(); M_ASN1_D2I_start_sequence(); M_ASN1_D2I_get(ret->method, d2i_ASN1_OBJECT); M_ASN1_D2I_get(ret->location, d2i_GENERAL_NAME); M_ASN1_D2I_Finish(a, ACCESS_DESCRIPTION_free, ASN1_F_D2I_ACCESS_DESCRIPTION); } void ACCESS_DESCRIPTION_free(ACCESS_DESCRIPTION *a) { if (a == NULL) return; ASN1_OBJECT_free(a->method); GENERAL_NAME_free(a->location); OPENSSL_free (a); } STACK_OF(ACCESS_DESCRIPTION) *AUTHORITY_INFO_ACCESS_new(void) { return sk_ACCESS_DESCRIPTION_new_null(); } void AUTHORITY_INFO_ACCESS_free(STACK_OF(ACCESS_DESCRIPTION) *a) { sk_ACCESS_DESCRIPTION_pop_free(a, ACCESS_DESCRIPTION_free); } STACK_OF(ACCESS_DESCRIPTION) *d2i_AUTHORITY_INFO_ACCESS(STACK_OF(ACCESS_DESCRIPTION) **a, unsigned char **pp, long length) { return d2i_ASN1_SET_OF_ACCESS_DESCRIPTION(a, pp, length, d2i_ACCESS_DESCRIPTION, ACCESS_DESCRIPTION_free, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL); } int i2d_AUTHORITY_INFO_ACCESS(STACK_OF(ACCESS_DESCRIPTION) *a, unsigned char **pp) { return i2d_ASN1_SET_OF_ACCESS_DESCRIPTION(a, pp, i2d_ACCESS_DESCRIPTION, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL, IS_SEQUENCE); } IMPLEMENT_STACK_OF(ACCESS_DESCRIPTION) IMPLEMENT_ASN1_SET_OF(ACCESS_DESCRIPTION)
452399.c
//===-- mulsc3_test.c - Test __mulsc3 -------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file tests __mulsc3 for the compiler_rt library. // //===----------------------------------------------------------------------===// #include "int_lib.h" #include <math.h> #include <complex.h> #include <stdio.h> // Returns: the product of a + ib and c + id COMPILER_RT_ABI float _Complex __mulsc3(float __a, float __b, float __c, float __d); enum {zero, non_zero, inf, NaN, non_zero_nan}; int classify(float _Complex x) { if (x == 0) return zero; if (isinf(crealf(x)) || isinf(cimagf(x))) return inf; if (isnan(crealf(x)) && isnan(cimagf(x))) return NaN; if (isnan(crealf(x))) { if (cimagf(x) == 0) return NaN; return non_zero_nan; } if (isnan(cimagf(x))) { if (crealf(x) == 0) return NaN; return non_zero_nan; } return non_zero; } int test__mulsc3(float a, float b, float c, float d) { float _Complex r = __mulsc3(a, b, c, d); // printf("test__mulsc3(%f, %f, %f, %f) = %f + I%f\n", // a, b, c, d, crealf(r), cimagf(r)); float _Complex dividend; float _Complex divisor; __real__ dividend = a; __imag__ dividend = b; __real__ divisor = c; __imag__ divisor = d; switch (classify(dividend)) { case zero: switch (classify(divisor)) { case zero: if (classify(r) != zero) return 1; break; case non_zero: if (classify(r) != zero) return 1; break; case inf: if (classify(r) != NaN) return 1; break; case NaN: if (classify(r) != NaN) return 1; break; case non_zero_nan: if (classify(r) != NaN) return 1; break; } break; case non_zero: switch (classify(divisor)) { case zero: if (classify(r) != zero) return 1; break; case non_zero: if (classify(r) != non_zero) return 1; { float _Complex z = a * c - b * d + _Complex_I*(a * d + b * c); // relaxed tolerance to arbitrary (1.e-6) amount. if (cabsf((r-z)/r) > 1.e-6) return 1; } break; case inf: if (classify(r) != inf) return 1; break; case NaN: if (classify(r) != NaN) return 1; break; case non_zero_nan: if (classify(r) != NaN) return 1; break; } break; case inf: switch (classify(divisor)) { case zero: if (classify(r) != NaN) return 1; break; case non_zero: if (classify(r) != inf) return 1; break; case inf: if (classify(r) != inf) return 1; break; case NaN: if (classify(r) != NaN) return 1; break; case non_zero_nan: if (classify(r) != inf) return 1; break; } break; case NaN: switch (classify(divisor)) { case zero: if (classify(r) != NaN) return 1; break; case non_zero: if (classify(r) != NaN) return 1; break; case inf: if (classify(r) != NaN) return 1; break; case NaN: if (classify(r) != NaN) return 1; break; case non_zero_nan: if (classify(r) != NaN) return 1; break; } break; case non_zero_nan: switch (classify(divisor)) { case zero: if (classify(r) != NaN) return 1; break; case non_zero: if (classify(r) != NaN) return 1; break; case inf: if (classify(r) != inf) return 1; break; case NaN: if (classify(r) != NaN) return 1; break; case non_zero_nan: if (classify(r) != NaN) return 1; break; } break; } return 0; } float x[][2] = { { 1.e-6, 1.e-6}, {-1.e-6, 1.e-6}, {-1.e-6, -1.e-6}, { 1.e-6, -1.e-6}, { 1.e+6, 1.e-6}, {-1.e+6, 1.e-6}, {-1.e+6, -1.e-6}, { 1.e+6, -1.e-6}, { 1.e-6, 1.e+6}, {-1.e-6, 1.e+6}, {-1.e-6, -1.e+6}, { 1.e-6, -1.e+6}, { 1.e+6, 1.e+6}, {-1.e+6, 1.e+6}, {-1.e+6, -1.e+6}, { 1.e+6, -1.e+6}, {NAN, NAN}, {-INFINITY, NAN}, {-2, NAN}, {-1, NAN}, {-0.5, NAN}, {-0., NAN}, {+0., NAN}, {0.5, NAN}, {1, NAN}, {2, NAN}, {INFINITY, NAN}, {NAN, -INFINITY}, {-INFINITY, -INFINITY}, {-2, -INFINITY}, {-1, -INFINITY}, {-0.5, -INFINITY}, {-0., -INFINITY}, {+0., -INFINITY}, {0.5, -INFINITY}, {1, -INFINITY}, {2, -INFINITY}, {INFINITY, -INFINITY}, {NAN, -2}, {-INFINITY, -2}, {-2, -2}, {-1, -2}, {-0.5, -2}, {-0., -2}, {+0., -2}, {0.5, -2}, {1, -2}, {2, -2}, {INFINITY, -2}, {NAN, -1}, {-INFINITY, -1}, {-2, -1}, {-1, -1}, {-0.5, -1}, {-0., -1}, {+0., -1}, {0.5, -1}, {1, -1}, {2, -1}, {INFINITY, -1}, {NAN, -0.5}, {-INFINITY, -0.5}, {-2, -0.5}, {-1, -0.5}, {-0.5, -0.5}, {-0., -0.5}, {+0., -0.5}, {0.5, -0.5}, {1, -0.5}, {2, -0.5}, {INFINITY, -0.5}, {NAN, -0.}, {-INFINITY, -0.}, {-2, -0.}, {-1, -0.}, {-0.5, -0.}, {-0., -0.}, {+0., -0.}, {0.5, -0.}, {1, -0.}, {2, -0.}, {INFINITY, -0.}, {NAN, 0.}, {-INFINITY, 0.}, {-2, 0.}, {-1, 0.}, {-0.5, 0.}, {-0., 0.}, {+0., 0.}, {0.5, 0.}, {1, 0.}, {2, 0.}, {INFINITY, 0.}, {NAN, 0.5}, {-INFINITY, 0.5}, {-2, 0.5}, {-1, 0.5}, {-0.5, 0.5}, {-0., 0.5}, {+0., 0.5}, {0.5, 0.5}, {1, 0.5}, {2, 0.5}, {INFINITY, 0.5}, {NAN, 1}, {-INFINITY, 1}, {-2, 1}, {-1, 1}, {-0.5, 1}, {-0., 1}, {+0., 1}, {0.5, 1}, {1, 1}, {2, 1}, {INFINITY, 1}, {NAN, 2}, {-INFINITY, 2}, {-2, 2}, {-1, 2}, {-0.5, 2}, {-0., 2}, {+0., 2}, {0.5, 2}, {1, 2}, {2, 2}, {INFINITY, 2}, {NAN, INFINITY}, {-INFINITY, INFINITY}, {-2, INFINITY}, {-1, INFINITY}, {-0.5, INFINITY}, {-0., INFINITY}, {+0., INFINITY}, {0.5, INFINITY}, {1, INFINITY}, {2, INFINITY}, {INFINITY, INFINITY} }; int main() { const unsigned N = sizeof(x) / sizeof(x[0]); unsigned i, j; for (i = 0; i < N; ++i) { for (j = 0; j < N; ++j) { if (test__mulsc3(x[i][0], x[i][1], x[j][0], x[j][1])) return 1; } } return 0; }
901669.c
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mod_proxy.h" #include "mod_core.h" #include "apr_optional.h" #include "scoreboard.h" #include "mod_status.h" #include "proxy_util.h" #if (MODULE_MAGIC_NUMBER_MAJOR > 20020903) #include "mod_ssl.h" #else APR_DECLARE_OPTIONAL_FN(int, ssl_proxy_enable, (conn_rec *)); APR_DECLARE_OPTIONAL_FN(int, ssl_engine_disable, (conn_rec *)); APR_DECLARE_OPTIONAL_FN(int, ssl_is_https, (conn_rec *)); APR_DECLARE_OPTIONAL_FN(char *, ssl_var_lookup, (apr_pool_t *, server_rec *, conn_rec *, request_rec *, char *)); #endif #ifndef MAX #define MAX(x,y) ((x) >= (y) ? (x) : (y)) #endif static const char * const proxy_id = "proxy"; apr_global_mutex_t *proxy_mutex = NULL; /* * A Web proxy module. Stages: * * translate_name: set filename to proxy:<URL> * map_to_storage: run proxy_walk (rather than directory_walk/file_walk) * can't trust directory_walk/file_walk since these are * not in our filesystem. Prevents mod_http from serving * the TRACE request we will set aside to handle later. * fix_ups: convert the URL stored in the filename to the * canonical form. * handler: handle proxy requests */ /* -------------------------------------------------------------- */ /* Translate the URL into a 'filename' */ static const char *set_worker_param(apr_pool_t *p, proxy_worker *worker, const char *key, const char *val) { int ival; apr_interval_time_t timeout; if (!strcasecmp(key, "loadfactor")) { /* Normalized load factor. Used with BalancerMamber, * it is a number between 1 and 100. */ worker->s->lbfactor = atoi(val); if (worker->s->lbfactor < 1 || worker->s->lbfactor > 100) return "LoadFactor must be a number between 1..100"; } else if (!strcasecmp(key, "retry")) { /* If set it will give the retry timeout for the worker * The default value is 60 seconds, meaning that if * in error state, it will be retried after that timeout. */ ival = atoi(val); if (ival < 0) return "Retry must be a positive value"; worker->s->retry = apr_time_from_sec(ival); worker->s->retry_set = 1; } else if (!strcasecmp(key, "ttl")) { /* Time in seconds that will destroy all the connections * that exceed the smax */ ival = atoi(val); if (ival < 1) return "TTL must be at least one second"; worker->s->ttl = apr_time_from_sec(ival); } else if (!strcasecmp(key, "min")) { /* Initial number of connections to remote */ ival = atoi(val); if (ival < 0) return "Min must be a positive number"; worker->s->min = ival; } else if (!strcasecmp(key, "max")) { /* Maximum number of connections to remote */ ival = atoi(val); if (ival < 0) return "Max must be a positive number"; worker->s->hmax = ival; } /* XXX: More inteligent naming needed */ else if (!strcasecmp(key, "smax")) { /* Maximum number of connections to remote that * will not be destroyed */ ival = atoi(val); if (ival < 0) return "Smax must be a positive number"; worker->s->smax = ival; } else if (!strcasecmp(key, "acquire")) { /* Acquire timeout in given unit (default is milliseconds). * If set this will be the maximum time to * wait for a free connection. */ if (ap_timeout_parameter_parse(val, &timeout, "ms") != APR_SUCCESS) return "Acquire timeout has wrong format"; if (timeout < 1000) return "Acquire must be at least one millisecond"; worker->s->acquire = timeout; worker->s->acquire_set = 1; } else if (!strcasecmp(key, "timeout")) { /* Connection timeout in seconds. * Defaults to server timeout. */ ival = atoi(val); if (ival < 1) return "Timeout must be at least one second"; worker->s->timeout = apr_time_from_sec(ival); worker->s->timeout_set = 1; } else if (!strcasecmp(key, "iobuffersize")) { long s = atol(val); if (s < 512 && s) { return "IOBufferSize must be >= 512 bytes, or 0 for system default."; } worker->s->io_buffer_size = (s ? s : AP_IOBUFSIZE); worker->s->io_buffer_size_set = 1; } else if (!strcasecmp(key, "receivebuffersize")) { ival = atoi(val); if (ival < 512 && ival != 0) { return "ReceiveBufferSize must be >= 512 bytes, or 0 for system default."; } worker->s->recv_buffer_size = ival; worker->s->recv_buffer_size_set = 1; } else if (!strcasecmp(key, "keepalive")) { if (!strcasecmp(val, "on")) worker->s->keepalive = 1; else if (!strcasecmp(val, "off")) worker->s->keepalive = 0; else return "KeepAlive must be On|Off"; worker->s->keepalive_set = 1; } else if (!strcasecmp(key, "disablereuse")) { if (!strcasecmp(val, "on")) worker->s->disablereuse = 1; else if (!strcasecmp(val, "off")) worker->s->disablereuse = 0; else return "DisableReuse must be On|Off"; worker->s->disablereuse_set = 1; } else if (!strcasecmp(key, "route")) { /* Worker route. */ if (strlen(val) >= sizeof(worker->s->route)) return apr_psprintf(p, "Route length must be < %d characters", (int)sizeof(worker->s->route)); PROXY_STRNCPY(worker->s->route, val); } else if (!strcasecmp(key, "redirect")) { /* Worker redirection route. */ if (strlen(val) >= sizeof(worker->s->redirect)) return apr_psprintf(p, "Redirect length must be < %d characters", (int)sizeof(worker->s->redirect)); PROXY_STRNCPY(worker->s->redirect, val); } else if (!strcasecmp(key, "status")) { const char *v; int mode = 1; apr_status_t rv; /* Worker status. */ for (v = val; *v; v++) { if (*v == '+') { mode = 1; v++; } else if (*v == '-') { mode = 0; v++; } rv = ap_proxy_set_wstatus(*v, mode, worker); if (rv != APR_SUCCESS) return "Unknown status parameter option"; } } else if (!strcasecmp(key, "flushpackets")) { if (!strcasecmp(val, "on")) worker->s->flush_packets = flush_on; else if (!strcasecmp(val, "off")) worker->s->flush_packets = flush_off; else if (!strcasecmp(val, "auto")) worker->s->flush_packets = flush_auto; else return "flushpackets must be on|off|auto"; } else if (!strcasecmp(key, "flushwait")) { ival = atoi(val); if (ival > 1000 || ival < 0) { return "flushwait must be <= 1000, or 0 for system default of 10 millseconds."; } if (ival == 0) worker->s->flush_wait = PROXY_FLUSH_WAIT; else worker->s->flush_wait = ival * 1000; /* change to microseconds */ } else if (!strcasecmp(key, "ping")) { /* Ping/Pong timeout in given unit (default is second). */ if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS) return "Ping/Pong timeout has wrong format"; if (timeout < 1000 && timeout >= 0) return "Ping/Pong timeout must be at least one millisecond"; worker->s->ping_timeout = timeout; worker->s->ping_timeout_set = 1; } else if (!strcasecmp(key, "lbset")) { ival = atoi(val); if (ival < 0 || ival > 99) return "lbset must be between 0 and 99"; worker->s->lbset = ival; } else if (!strcasecmp(key, "connectiontimeout")) { /* Request timeout in given unit (default is second). * Defaults to connection timeout */ if (ap_timeout_parameter_parse(val, &timeout, "s") != APR_SUCCESS) return "Connectiontimeout has wrong format"; if (timeout < 1000) return "Connectiontimeout must be at least one millisecond."; worker->s->conn_timeout = timeout; worker->s->conn_timeout_set = 1; } else if (!strcasecmp(key, "flusher")) { if (strlen(val) >= sizeof(worker->s->flusher)) apr_psprintf(p, "flusher name length must be < %d characters", (int)sizeof(worker->s->flusher)); PROXY_STRNCPY(worker->s->flusher, val); } else { return "unknown Worker parameter"; } return NULL; } static const char *set_balancer_param(proxy_server_conf *conf, apr_pool_t *p, proxy_balancer *balancer, const char *key, const char *val) { int ival; if (!strcasecmp(key, "stickysession")) { char *path; /* Balancer sticky session name. * Set to something like JSESSIONID or * PHPSESSIONID, etc.., */ if (strlen(val) >= sizeof(balancer->s->sticky_path)) apr_psprintf(p, "stickysession length must be < %d characters", (int)sizeof(balancer->s->sticky_path)); PROXY_STRNCPY(balancer->s->sticky_path, val); PROXY_STRNCPY(balancer->s->sticky, val); if ((path = strchr((char *)balancer->s->sticky, '|'))) { *path++ = '\0'; PROXY_STRNCPY(balancer->s->sticky_path, path); } } else if (!strcasecmp(key, "stickysessionsep")) { /* separator/delimiter for sessionid and route, * normally '.' */ if (strlen(val) != 1) { if (!strcasecmp(val, "off")) balancer->s->sticky_separator = 0; else return "stickysessionsep must be a single character or Off"; } else balancer->s->sticky_separator = *val; } else if (!strcasecmp(key, "nofailover")) { /* If set to 'on' the session will break * if the worker is in error state or * disabled. */ if (!strcasecmp(val, "on")) balancer->s->sticky_force = 1; else if (!strcasecmp(val, "off")) balancer->s->sticky_force = 0; else return "failover must be On|Off"; } else if (!strcasecmp(key, "timeout")) { /* Balancer timeout in seconds. * If set this will be the maximum time to * wait for a free worker. * Default is not to wait. */ ival = atoi(val); if (ival < 1) return "timeout must be at least one second"; balancer->s->timeout = apr_time_from_sec(ival); } else if (!strcasecmp(key, "maxattempts")) { /* Maximum number of failover attempts before * giving up. */ ival = atoi(val); if (ival < 0) return "maximum number of attempts must be a positive number"; balancer->s->max_attempts = ival; balancer->s->max_attempts_set = 1; } else if (!strcasecmp(key, "lbmethod")) { proxy_balancer_method *provider; if (strlen(val) > (sizeof(balancer->s->lbpname)-1)) return "unknown lbmethod"; provider = ap_lookup_provider(PROXY_LBMETHOD, val, "0"); if (provider) { balancer->lbmethod = provider; if (PROXY_STRNCPY(balancer->s->lbpname, val) == APR_SUCCESS) { return NULL; } else { return "lbmethod name too large"; } } return "unknown lbmethod"; } else if (!strcasecmp(key, "scolonpathdelim")) { /* If set to 'on' then ';' will also be * used as a session path separator/delim (ala * mod_jk) */ if (!strcasecmp(val, "on")) balancer->s->scolonsep = 1; else if (!strcasecmp(val, "off")) balancer->s->scolonsep = 0; else return "scolonpathdelim must be On|Off"; } else if (!strcasecmp(key, "failonstatus")) { char *val_split; char *status; char *tok_state; val_split = apr_pstrdup(p, val); balancer->errstatuses = apr_array_make(p, 1, sizeof(int)); status = apr_strtok(val_split, ", ", &tok_state); while (status != NULL) { ival = atoi(status); if (ap_is_HTTP_VALID_RESPONSE(ival)) { *(int *)apr_array_push(balancer->errstatuses) = ival; } else { return "failonstatus must be one or more HTTP response codes"; } status = apr_strtok(NULL, ", ", &tok_state); } } else if (!strcasecmp(key, "failontimeout")) { if (!strcasecmp(val, "on")) balancer->failontimeout = 1; else if (!strcasecmp(val, "off")) balancer->failontimeout = 0; else return "failontimeout must be On|Off"; } else if (!strcasecmp(key, "nonce")) { if (!strcasecmp(val, "None")) { *balancer->s->nonce = '\0'; } else { if (PROXY_STRNCPY(balancer->s->nonce, val) != APR_SUCCESS) { return "Provided nonce is too large"; } } } else if (!strcasecmp(key, "growth")) { ival = atoi(val); if (ival < 1 || ival > 100) /* arbitrary limit here */ return "growth must be between 1 and 100"; balancer->growth = ival; } else if (!strcasecmp(key, "forcerecovery")) { if (!strcasecmp(val, "on")) balancer->s->forcerecovery = 1; else if (!strcasecmp(val, "off")) balancer->s->forcerecovery = 0; else return "forcerecovery must be On|Off"; } else { return "unknown Balancer parameter"; } return NULL; } static int alias_match(const char *uri, const char *alias_fakename) { const char *end_fakename = alias_fakename + strlen(alias_fakename); const char *aliasp = alias_fakename, *urip = uri; const char *end_uri = uri + strlen(uri); while (aliasp < end_fakename && urip < end_uri) { if (*aliasp == '/') { /* any number of '/' in the alias matches any number in * the supplied URI, but there must be at least one... */ if (*urip != '/') return 0; while (*aliasp == '/') ++aliasp; while (*urip == '/') ++urip; } else { /* Other characters are compared literally */ if (*urip++ != *aliasp++) return 0; } } /* fixup badly encoded stuff (e.g. % as last character) */ if (aliasp > end_fakename) { aliasp = end_fakename; } if (urip > end_uri) { urip = end_uri; } /* We reach the end of the uri before the end of "alias_fakename" * for example uri is "/" and alias_fakename "/examples" */ if (urip == end_uri && aliasp != end_fakename) { return 0; } /* Check last alias path component matched all the way */ if (aliasp[-1] != '/' && *urip != '\0' && *urip != '/') return 0; /* Return number of characters from URI which matched (may be * greater than length of alias, since we may have matched * doubled slashes) */ return urip - uri; } /* Detect if an absoluteURI should be proxied or not. Note that we * have to do this during this phase because later phases are * "short-circuiting"... i.e. translate_names will end when the first * module returns OK. So for example, if the request is something like: * * GET http://othervhost/cgi-bin/printenv HTTP/1.0 * * mod_alias will notice the /cgi-bin part and ScriptAlias it and * short-circuit the proxy... just because of the ordering in the * configuration file. */ static int proxy_detect(request_rec *r) { void *sconf = r->server->module_config; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module); /* Ick... msvc (perhaps others) promotes ternary short results to int */ if (conf->req && r->parsed_uri.scheme) { /* but it might be something vhosted */ if (!(r->parsed_uri.hostname && !strcasecmp(r->parsed_uri.scheme, ap_http_scheme(r)) && ap_matches_request_vhost(r, r->parsed_uri.hostname, (apr_port_t)(r->parsed_uri.port_str ? r->parsed_uri.port : ap_default_port(r))))) { r->proxyreq = PROXYREQ_PROXY; r->uri = r->unparsed_uri; r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL); r->handler = "proxy-server"; } } /* We need special treatment for CONNECT proxying: it has no scheme part */ else if (conf->req && r->method_number == M_CONNECT && r->parsed_uri.hostname && r->parsed_uri.port_str) { r->proxyreq = PROXYREQ_PROXY; r->uri = r->unparsed_uri; r->filename = apr_pstrcat(r->pool, "proxy:", r->uri, NULL); r->handler = "proxy-server"; } return DECLINED; } static const char *proxy_interpolate(request_rec *r, const char *str) { /* Interpolate an env str in a configuration string * Syntax ${var} --> value_of(var) * Method: replace one var, and recurse on remainder of string * Nothing clever here, and crap like nested vars may do silly things * but we'll at least avoid sending the unwary into a loop */ const char *start; const char *end; const char *var; const char *val; const char *firstpart; start = ap_strstr_c(str, "${"); if (start == NULL) { return str; } end = ap_strchr_c(start+2, '}'); if (end == NULL) { return str; } /* OK, this is syntax we want to interpolate. Is there such a var ? */ var = apr_pstrmemdup(r->pool, start+2, end-(start+2)); val = apr_table_get(r->subprocess_env, var); firstpart = apr_pstrmemdup(r->pool, str, (start-str)); if (val == NULL) { return apr_pstrcat(r->pool, firstpart, proxy_interpolate(r, end+1), NULL); } else { return apr_pstrcat(r->pool, firstpart, val, proxy_interpolate(r, end+1), NULL); } } static apr_array_header_t *proxy_vars(request_rec *r, apr_array_header_t *hdr) { int i; apr_array_header_t *ret = apr_array_make(r->pool, hdr->nelts, sizeof (struct proxy_alias)); struct proxy_alias *old = (struct proxy_alias *) hdr->elts; for (i = 0; i < hdr->nelts; ++i) { struct proxy_alias *newcopy = apr_array_push(ret); newcopy->fake = (old[i].flags & PROXYPASS_INTERPOLATE) ? proxy_interpolate(r, old[i].fake) : old[i].fake; newcopy->real = (old[i].flags & PROXYPASS_INTERPOLATE) ? proxy_interpolate(r, old[i].real) : old[i].real; } return ret; } PROXY_DECLARE(int) ap_proxy_trans_match(request_rec *r, struct proxy_alias *ent, proxy_dir_conf *dconf) { int len; const char *fake; const char *real; ap_regmatch_t regm[AP_MAX_REG_MATCH]; ap_regmatch_t reg1[AP_MAX_REG_MATCH]; char *found = NULL; int mismatch = 0; unsigned int nocanon = ent->flags & PROXYPASS_NOCANON; const char *use_uri = nocanon ? r->unparsed_uri : r->uri; if (dconf && (dconf->interpolate_env == 1) && (ent->flags & PROXYPASS_INTERPOLATE)) { fake = proxy_interpolate(r, ent->fake); real = proxy_interpolate(r, ent->real); } else { fake = ent->fake; real = ent->real; } if (ent->regex) { if (!ap_regexec(ent->regex, r->uri, AP_MAX_REG_MATCH, regm, 0)) { if ((real[0] == '!') && (real[1] == '\0')) { return DECLINED; } /* test that we haven't reduced the URI */ if (nocanon && ap_regexec(ent->regex, r->unparsed_uri, AP_MAX_REG_MATCH, reg1, 0)) { mismatch = 1; use_uri = r->uri; } found = ap_pregsub(r->pool, real, use_uri, AP_MAX_REG_MATCH, (use_uri == r->uri) ? regm : reg1); if (!found) { ap_log_rerror(APLOG_MARK, APLOG_CRIT, 0, r, APLOGNO(01135) "Substitution in regular expression failed. " "Replacement too long?"); return HTTP_INTERNAL_SERVER_ERROR; } /* Note: The strcmp() below catches cases where there * was no regex substitution. This is so cases like: * * ProxyPassMatch \.gif balancer://foo * * will work "as expected". The upshot is that the 2 * directives below act the exact same way (ie: $1 is implied): * * ProxyPassMatch ^(/.*\.gif)$ balancer://foo * ProxyPassMatch ^(/.*\.gif)$ balancer://foo$1 * * which may be confusing. */ if (strcmp(found, real) != 0) { found = apr_pstrcat(r->pool, "proxy:", found, NULL); } else { found = apr_pstrcat(r->pool, "proxy:", real, use_uri, NULL); } } } else { len = alias_match(r->uri, fake); if (len != 0) { if ((real[0] == '!') && (real[1] == '\0')) { return DECLINED; } if (nocanon && len != alias_match(r->unparsed_uri, ent->fake)) { mismatch = 1; use_uri = r->uri; } found = apr_pstrcat(r->pool, "proxy:", real, use_uri + len, NULL); } } if (mismatch) { /* We made a reducing transformation, so we can't safely use * unparsed_uri. Safe fallback is to ignore nocanon. */ ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01136) "Unescaped URL path matched ProxyPass; ignoring unsafe nocanon"); } if (found) { r->filename = found; r->handler = "proxy-server"; r->proxyreq = PROXYREQ_REVERSE; if (nocanon && !mismatch) { /* mod_proxy_http needs to be told. Different module. */ apr_table_setn(r->notes, "proxy-nocanon", "1"); } if (ent->flags & PROXYPASS_NOQUERY) { apr_table_setn(r->notes, "proxy-noquery", "1"); } return OK; } return DONE; } static int proxy_trans(request_rec *r) { int i; struct proxy_alias *ent; proxy_dir_conf *dconf; proxy_server_conf *conf; if (r->proxyreq) { /* someone has already set up the proxy, it was possibly ourselves * in proxy_detect */ return OK; } if ((r->unparsed_uri[0] == '*' && r->unparsed_uri[1] == '\0') || !r->uri || r->uri[0] != '/') { return DECLINED; } /* XXX: since r->uri has been manipulated already we're not really * compliant with RFC1945 at this point. But this probably isn't * an issue because this is a hybrid proxy/origin server. */ dconf = ap_get_module_config(r->per_dir_config, &proxy_module); /* short way - this location is reverse proxied? */ if (dconf->alias) { int rv = ap_proxy_trans_match(r, dconf->alias, dconf); if (DONE != rv) { return rv; } } conf = (proxy_server_conf *) ap_get_module_config(r->server->module_config, &proxy_module); /* long way - walk the list of aliases, find a match */ if (conf->aliases->nelts) { ent = (struct proxy_alias *) conf->aliases->elts; for (i = 0; i < conf->aliases->nelts; i++) { int rv = ap_proxy_trans_match(r, &ent[i], dconf); if (DONE != rv) { return rv; } } } return DECLINED; } static int proxy_walk(request_rec *r) { proxy_server_conf *sconf = ap_get_module_config(r->server->module_config, &proxy_module); ap_conf_vector_t *per_dir_defaults = r->server->lookup_defaults; ap_conf_vector_t **sec_proxy = (ap_conf_vector_t **) sconf->sec_proxy->elts; ap_conf_vector_t *entry_config; proxy_dir_conf *entry_proxy; int num_sec = sconf->sec_proxy->nelts; /* XXX: shouldn't we use URI here? Canonicalize it first? * Pass over "proxy:" prefix */ const char *proxyname = r->filename + 6; int j; apr_pool_t *rxpool = NULL; for (j = 0; j < num_sec; ++j) { int nmatch = 0; int i; ap_regmatch_t *pmatch = NULL; entry_config = sec_proxy[j]; entry_proxy = ap_get_module_config(entry_config, &proxy_module); if (entry_proxy->r) { if (entry_proxy->refs && entry_proxy->refs->nelts) { if (!rxpool) { apr_pool_create(&rxpool, r->pool); } nmatch = entry_proxy->refs->nelts; pmatch = apr_palloc(rxpool, nmatch*sizeof(ap_regmatch_t)); } if (ap_regexec(entry_proxy->r, proxyname, nmatch, pmatch, 0)) { continue; } for (i = 0; i < nmatch; i++) { if (pmatch[i].rm_so >= 0 && pmatch[i].rm_eo >= 0 && ((const char **)entry_proxy->refs->elts)[i]) { apr_table_setn(r->subprocess_env, ((const char **)entry_proxy->refs->elts)[i], apr_pstrndup(r->pool, proxyname + pmatch[i].rm_so, pmatch[i].rm_eo - pmatch[i].rm_so)); } } } else if ( /* XXX: What about case insensitive matching ??? * Compare regex, fnmatch or string as appropriate * If the entry doesn't relate, then continue */ entry_proxy->p_is_fnmatch ? apr_fnmatch(entry_proxy->p, proxyname, 0) : strncmp(proxyname, entry_proxy->p, strlen(entry_proxy->p))) { continue; } per_dir_defaults = ap_merge_per_dir_configs(r->pool, per_dir_defaults, entry_config); } r->per_dir_config = per_dir_defaults; if (rxpool) { apr_pool_destroy(rxpool); } return OK; } static int proxy_map_location(request_rec *r) { int access_status; if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0) return DECLINED; /* Don't let the core or mod_http map_to_storage hooks handle this, * We don't need directory/file_walk, and we want to TRACE on our own. */ if ((access_status = proxy_walk(r))) { ap_die(access_status, r); return access_status; } return OK; } /* -------------------------------------------------------------- */ /* Fixup the filename */ /* * Canonicalise the URL */ static int proxy_fixup(request_rec *r) { char *url, *p; int access_status; proxy_dir_conf *dconf = ap_get_module_config(r->per_dir_config, &proxy_module); if (!r->proxyreq || !r->filename || strncmp(r->filename, "proxy:", 6) != 0) return DECLINED; /* XXX: Shouldn't we try this before we run the proxy_walk? */ url = &r->filename[6]; if ((dconf->interpolate_env == 1) && (r->proxyreq == PROXYREQ_REVERSE)) { /* create per-request copy of reverse proxy conf, * and interpolate vars in it */ proxy_req_conf *rconf = apr_palloc(r->pool, sizeof(proxy_req_conf)); ap_set_module_config(r->request_config, &proxy_module, rconf); rconf->raliases = proxy_vars(r, dconf->raliases); rconf->cookie_paths = proxy_vars(r, dconf->cookie_paths); rconf->cookie_domains = proxy_vars(r, dconf->cookie_domains); } /* canonicalise each specific scheme */ if ((access_status = proxy_run_canon_handler(r, url))) { return access_status; } p = strchr(url, ':'); if (p == NULL || p == url) return HTTP_BAD_REQUEST; return OK; /* otherwise; we've done the best we can */ } /* Send a redirection if the request contains a hostname which is not */ /* fully qualified, i.e. doesn't have a domain name appended. Some proxy */ /* servers like Netscape's allow this and access hosts from the local */ /* domain in this case. I think it is better to redirect to a FQDN, since */ /* these will later be found in the bookmarks files. */ /* The "ProxyDomain" directive determines what domain will be appended */ static int proxy_needsdomain(request_rec *r, const char *url, const char *domain) { char *nuri; const char *ref; /* We only want to worry about GETs */ if (!r->proxyreq || r->method_number != M_GET || !r->parsed_uri.hostname) return DECLINED; /* If host does contain a dot already, or it is "localhost", decline */ if (strchr(r->parsed_uri.hostname, '.') != NULL /* has domain, or IPv4 literal */ || strchr(r->parsed_uri.hostname, ':') != NULL /* IPv6 literal */ || strcasecmp(r->parsed_uri.hostname, "localhost") == 0) return DECLINED; /* host name has a dot already */ ref = apr_table_get(r->headers_in, "Referer"); /* Reassemble the request, but insert the domain after the host name */ /* Note that the domain name always starts with a dot */ r->parsed_uri.hostname = apr_pstrcat(r->pool, r->parsed_uri.hostname, domain, NULL); nuri = apr_uri_unparse(r->pool, &r->parsed_uri, APR_URI_UNP_REVEALPASSWORD); apr_table_setn(r->headers_out, "Location", nuri); ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, r, APLOGNO(01138) "Domain missing: %s sent to %s%s%s", r->uri, apr_uri_unparse(r->pool, &r->parsed_uri, APR_URI_UNP_OMITUSERINFO), ref ? " from " : "", ref ? ref : ""); return HTTP_MOVED_PERMANENTLY; } /* -------------------------------------------------------------- */ /* Invoke handler */ static int proxy_handler(request_rec *r) { char *uri, *scheme, *p; const char *p2; void *sconf = r->server->module_config; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module); apr_array_header_t *proxies = conf->proxies; struct proxy_remote *ents = (struct proxy_remote *) proxies->elts; int i, rc, access_status; int direct_connect = 0; const char *str; apr_int64_t maxfwd; proxy_balancer *balancer = NULL; proxy_worker *worker = NULL; int attempts = 0, max_attempts = 0; struct dirconn_entry *list = (struct dirconn_entry *)conf->dirconn->elts; int saved_status; /* is this for us? */ if (!r->filename) { return DECLINED; } if (!r->proxyreq) { /* We may have forced the proxy handler via config or .htaccess */ if (r->handler && strncmp(r->handler, "proxy:", 6) == 0 && strncmp(r->filename, "proxy:", 6) != 0) { r->proxyreq = PROXYREQ_REVERSE; r->filename = apr_pstrcat(r->pool, r->handler, r->filename, NULL); } else { return DECLINED; } } else if (strncmp(r->filename, "proxy:", 6) != 0) { return DECLINED; } /* handle max-forwards / OPTIONS / TRACE */ if ((str = apr_table_get(r->headers_in, "Max-Forwards"))) { char *end; maxfwd = apr_strtoi64(str, &end, 10); if (maxfwd < 0 || maxfwd == APR_INT64_MAX || *end) { return ap_proxyerror(r, HTTP_BAD_REQUEST, apr_psprintf(r->pool, "Max-Forwards value '%s' could not be parsed", str)); } else if (maxfwd == 0) { switch (r->method_number) { case M_TRACE: { int access_status; r->proxyreq = PROXYREQ_NONE; if ((access_status = ap_send_http_trace(r))) ap_die(access_status, r); else ap_finalize_request_protocol(r); return OK; } case M_OPTIONS: { int access_status; r->proxyreq = PROXYREQ_NONE; if ((access_status = ap_send_http_options(r))) ap_die(access_status, r); else ap_finalize_request_protocol(r); return OK; } default: { return ap_proxyerror(r, HTTP_BAD_REQUEST, "Max-Forwards has reached zero - proxy loop?"); } } } maxfwd = (maxfwd > 0) ? maxfwd - 1 : 0; } else { /* set configured max-forwards */ maxfwd = conf->maxfwd; } if (maxfwd >= 0) { apr_table_setn(r->headers_in, "Max-Forwards", apr_psprintf(r->pool, "%" APR_INT64_T_FMT, maxfwd)); } if (r->method_number == M_TRACE) { core_server_config *coreconf = (core_server_config *) ap_get_core_module_config(sconf); if (coreconf->trace_enable == AP_TRACE_DISABLE) { /* Allow "error-notes" string to be printed by ap_send_error_response() * Note; this goes nowhere, canned error response need an overhaul. */ apr_table_setn(r->notes, "error-notes", "TRACE forbidden by server configuration"); apr_table_setn(r->notes, "verbose-error-to", "*"); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01139) "TRACE forbidden by server configuration"); return HTTP_METHOD_NOT_ALLOWED; } /* Can't test ap_should_client_block, we aren't ready to send * the client a 100 Continue response till the connection has * been established */ if (coreconf->trace_enable != AP_TRACE_EXTENDED && (r->read_length || r->read_chunked || r->remaining)) { /* Allow "error-notes" string to be printed by ap_send_error_response() * Note; this goes nowhere, canned error response need an overhaul. */ apr_table_setn(r->notes, "error-notes", "TRACE with request body is not allowed"); apr_table_setn(r->notes, "verbose-error-to", "*"); ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01140) "TRACE with request body is not allowed"); return HTTP_REQUEST_ENTITY_TOO_LARGE; } } uri = r->filename + 6; p = strchr(uri, ':'); if (p == NULL) { ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01141) "proxy_handler no URL in %s", r->filename); return HTTP_BAD_REQUEST; } /* If the host doesn't have a domain name, add one and redirect. */ if (conf->domain != NULL) { rc = proxy_needsdomain(r, uri, conf->domain); if (ap_is_HTTP_REDIRECT(rc)) return HTTP_MOVED_PERMANENTLY; } scheme = apr_pstrmemdup(r->pool, uri, p - uri); /* Check URI's destination host against NoProxy hosts */ /* Bypass ProxyRemote server lookup if configured as NoProxy */ for (direct_connect = i = 0; i < conf->dirconn->nelts && !direct_connect; i++) { direct_connect = list[i].matcher(&list[i], r); } #if DEBUGGING ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, (direct_connect) ? "NoProxy for %s" : "UseProxy for %s", r->uri); #endif do { char *url = uri; /* Try to obtain the most suitable worker */ access_status = ap_proxy_pre_request(&worker, &balancer, r, conf, &url); if (access_status != OK) { /* * Only return if access_status is not HTTP_SERVICE_UNAVAILABLE * This gives other modules the chance to hook into the * request_status hook and decide what to do in this situation. */ if (access_status != HTTP_SERVICE_UNAVAILABLE) return access_status; /* * Ensure that balancer is NULL if worker is NULL to prevent * potential problems in the post_request hook. */ if (!worker) balancer = NULL; goto cleanup; } /* Initialise worker if needed, note the shared area must be initialized by the balancer logic */ if (balancer) { ap_proxy_initialize_worker(worker, r->server, conf->pool); } if (balancer && balancer->s->max_attempts_set && !max_attempts) max_attempts = balancer->s->max_attempts; /* firstly, try a proxy, unless a NoProxy directive is active */ if (!direct_connect) { for (i = 0; i < proxies->nelts; i++) { p2 = ap_strchr_c(ents[i].scheme, ':'); /* is it a partial URL? */ if (strcmp(ents[i].scheme, "*") == 0 || (ents[i].use_regex && ap_regexec(ents[i].regexp, url, 0, NULL, 0) == 0) || (p2 == NULL && strcasecmp(scheme, ents[i].scheme) == 0) || (p2 != NULL && strncasecmp(url, ents[i].scheme, strlen(ents[i].scheme)) == 0)) { /* handle the scheme */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01142) "Trying to run scheme_handler against proxy"); access_status = proxy_run_scheme_handler(r, worker, conf, url, ents[i].hostname, ents[i].port); /* Did the scheme handler process the request? */ if (access_status != DECLINED) { const char *cl_a; char *end; apr_off_t cl; /* * An fatal error or success, so no point in * retrying with a direct connection. */ if (access_status != HTTP_BAD_GATEWAY) { goto cleanup; } cl_a = apr_table_get(r->headers_in, "Content-Length"); if (cl_a) { apr_strtoff(&cl, cl_a, &end, 10); /* * The request body is of length > 0. We cannot * retry with a direct connection since we already * sent (parts of) the request body to the proxy * and do not have any longer. */ if (cl > 0) { goto cleanup; } } /* * Transfer-Encoding was set as input header, so we had * a request body. We cannot retry with a direct * connection for the same reason as above. */ if (apr_table_get(r->headers_in, "Transfer-Encoding")) { goto cleanup; } } } } } /* otherwise, try it direct */ /* N.B. what if we're behind a firewall, where we must use a proxy or * give up?? */ /* handle the scheme */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, r, APLOGNO(01143) "Running scheme %s handler (attempt %d)", scheme, attempts); AP_PROXY_RUN(r, worker, conf, url, attempts); access_status = proxy_run_scheme_handler(r, worker, conf, url, NULL, 0); if (access_status == OK) break; else if (access_status == HTTP_INTERNAL_SERVER_ERROR) { /* Unrecoverable server error. * We can not failover to another worker. * Mark the worker as unusable if member of load balancer */ if (balancer) { worker->s->status |= PROXY_WORKER_IN_ERROR; worker->s->error_time = apr_time_now(); } break; } else if (access_status == HTTP_SERVICE_UNAVAILABLE) { /* Recoverable server error. * We can failover to another worker * Mark the worker as unusable if member of load balancer */ if (balancer) { worker->s->status |= PROXY_WORKER_IN_ERROR; worker->s->error_time = apr_time_now(); } } else { /* Unrecoverable error. * Return the origin status code to the client. */ break; } /* Try again if the worker is unusable and the service is * unavailable. */ } while (!PROXY_WORKER_IS_USABLE(worker) && max_attempts > attempts++); if (DECLINED == access_status) { ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, APLOGNO(01144) "No protocol handler was valid for the URL %s. " "If you are using a DSO version of mod_proxy, make sure " "the proxy submodules are included in the configuration " "using LoadModule.", r->uri); access_status = HTTP_INTERNAL_SERVER_ERROR; goto cleanup; } cleanup: /* * Save current r->status and set it to the value of access_status which * might be different (e.g. r->status could be HTTP_OK if e.g. we override * the error page on the proxy or if the error was not generated by the * backend itself but by the proxy e.g. a bad gateway) in order to give * ap_proxy_post_request a chance to act correctly on the status code. */ saved_status = r->status; r->status = access_status; ap_proxy_post_request(worker, balancer, r, conf); /* * Only restore r->status if it has not been changed by * ap_proxy_post_request as we assume that this change was intentional. */ if (r->status == access_status) { r->status = saved_status; } proxy_run_request_status(&access_status, r); AP_PROXY_RUN_FINISHED(r, attempts, access_status); return access_status; } /* -------------------------------------------------------------- */ /* Setup configurable data */ static void * create_proxy_config(apr_pool_t *p, server_rec *s) { proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf)); ps->sec_proxy = apr_array_make(p, 10, sizeof(ap_conf_vector_t *)); ps->proxies = apr_array_make(p, 10, sizeof(struct proxy_remote)); ps->aliases = apr_array_make(p, 10, sizeof(struct proxy_alias)); ps->noproxies = apr_array_make(p, 10, sizeof(struct noproxy_entry)); ps->dirconn = apr_array_make(p, 10, sizeof(struct dirconn_entry)); ps->workers = apr_array_make(p, 10, sizeof(proxy_worker)); ps->balancers = apr_array_make(p, 10, sizeof(proxy_balancer)); ps->forward = NULL; ps->reverse = NULL; ps->domain = NULL; ps->id = apr_psprintf(p, "p%x", 1); /* simply for storage size */ ps->viaopt = via_off; /* initially backward compatible with 1.3.1 */ ps->viaopt_set = 0; /* 0 means default */ ps->req = 0; ps->max_balancers = 0; ps->bal_persist = 0; ps->inherit = 1; ps->inherit_set = 0; ps->ppinherit = 1; ps->ppinherit_set = 0; ps->bgrowth = 5; ps->bgrowth_set = 0; ps->req_set = 0; ps->recv_buffer_size = 0; /* this default was left unset for some reason */ ps->recv_buffer_size_set = 0; ps->io_buffer_size = AP_IOBUFSIZE; ps->io_buffer_size_set = 0; ps->maxfwd = DEFAULT_MAX_FORWARDS; ps->maxfwd_set = 0; ps->timeout = 0; ps->timeout_set = 0; ps->badopt = bad_error; ps->badopt_set = 0; ps->source_address = NULL; ps->source_address_set = 0; apr_pool_create_ex(&ps->pool, p, NULL, NULL); return ps; } static void * merge_proxy_config(apr_pool_t *p, void *basev, void *overridesv) { proxy_server_conf *ps = apr_pcalloc(p, sizeof(proxy_server_conf)); proxy_server_conf *base = (proxy_server_conf *) basev; proxy_server_conf *overrides = (proxy_server_conf *) overridesv; ps->inherit = (overrides->inherit_set == 0) ? base->inherit : overrides->inherit; ps->inherit_set = overrides->inherit_set || base->inherit_set; ps->ppinherit = (overrides->ppinherit_set == 0) ? base->ppinherit : overrides->ppinherit; ps->ppinherit_set = overrides->ppinherit_set || base->ppinherit_set; if (ps->ppinherit) { ps->proxies = apr_array_append(p, base->proxies, overrides->proxies); } else { ps->proxies = overrides->proxies; } ps->sec_proxy = apr_array_append(p, base->sec_proxy, overrides->sec_proxy); ps->aliases = apr_array_append(p, base->aliases, overrides->aliases); ps->noproxies = apr_array_append(p, base->noproxies, overrides->noproxies); ps->dirconn = apr_array_append(p, base->dirconn, overrides->dirconn); if (ps->inherit || ps->ppinherit) { ps->workers = apr_array_append(p, base->workers, overrides->workers); ps->balancers = apr_array_append(p, base->balancers, overrides->balancers); } else { ps->workers = overrides->workers; ps->balancers = overrides->balancers; } ps->forward = overrides->forward ? overrides->forward : base->forward; ps->reverse = overrides->reverse ? overrides->reverse : base->reverse; ps->domain = (overrides->domain == NULL) ? base->domain : overrides->domain; ps->id = (overrides->id == NULL) ? base->id : overrides->id; ps->viaopt = (overrides->viaopt_set == 0) ? base->viaopt : overrides->viaopt; ps->viaopt_set = overrides->viaopt_set || base->viaopt_set; ps->req = (overrides->req_set == 0) ? base->req : overrides->req; ps->req_set = overrides->req_set || base->req_set; ps->bgrowth = (overrides->bgrowth_set == 0) ? base->bgrowth : overrides->bgrowth; ps->bgrowth_set = overrides->bgrowth_set || base->bgrowth_set; ps->max_balancers = overrides->max_balancers || base->max_balancers; ps->bal_persist = overrides->bal_persist; ps->recv_buffer_size = (overrides->recv_buffer_size_set == 0) ? base->recv_buffer_size : overrides->recv_buffer_size; ps->recv_buffer_size_set = overrides->recv_buffer_size_set || base->recv_buffer_size_set; ps->io_buffer_size = (overrides->io_buffer_size_set == 0) ? base->io_buffer_size : overrides->io_buffer_size; ps->io_buffer_size_set = overrides->io_buffer_size_set || base->io_buffer_size_set; ps->maxfwd = (overrides->maxfwd_set == 0) ? base->maxfwd : overrides->maxfwd; ps->maxfwd_set = overrides->maxfwd_set || base->maxfwd_set; ps->timeout = (overrides->timeout_set == 0) ? base->timeout : overrides->timeout; ps->timeout_set = overrides->timeout_set || base->timeout_set; ps->badopt = (overrides->badopt_set == 0) ? base->badopt : overrides->badopt; ps->badopt_set = overrides->badopt_set || base->badopt_set; ps->proxy_status = (overrides->proxy_status_set == 0) ? base->proxy_status : overrides->proxy_status; ps->proxy_status_set = overrides->proxy_status_set || base->proxy_status_set; ps->source_address = (overrides->source_address_set == 0) ? base->source_address : overrides->source_address; ps->source_address_set = overrides->source_address_set || base->source_address_set; ps->pool = base->pool; return ps; } static const char *set_source_address(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); struct apr_sockaddr_t *addr; if (APR_SUCCESS == apr_sockaddr_info_get(&addr, arg, APR_UNSPEC, 0, 0, psf->pool)) { psf->source_address = addr; psf->source_address_set = 1; } else { return "ProxySourceAddress invalid value"; } return NULL; } static void *create_proxy_dir_config(apr_pool_t *p, char *dummy) { proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf)); /* Filled in by proxysection, when applicable */ /* Put these in the dir config so they work inside <Location> */ new->raliases = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->cookie_paths = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->cookie_domains = apr_array_make(p, 10, sizeof(struct proxy_alias)); new->preserve_host_set = 0; new->preserve_host = 0; new->interpolate_env = -1; /* unset */ new->error_override = 0; new->error_override_set = 0; new->add_forwarded_headers = 1; return (void *) new; } static void *merge_proxy_dir_config(apr_pool_t *p, void *basev, void *addv) { proxy_dir_conf *new = (proxy_dir_conf *) apr_pcalloc(p, sizeof(proxy_dir_conf)); proxy_dir_conf *add = (proxy_dir_conf *) addv; proxy_dir_conf *base = (proxy_dir_conf *) basev; new->p = add->p; new->p_is_fnmatch = add->p_is_fnmatch; new->r = add->r; new->refs = add->refs; /* Put these in the dir config so they work inside <Location> */ new->raliases = apr_array_append(p, base->raliases, add->raliases); new->cookie_paths = apr_array_append(p, base->cookie_paths, add->cookie_paths); new->cookie_domains = apr_array_append(p, base->cookie_domains, add->cookie_domains); new->interpolate_env = (add->interpolate_env == -1) ? base->interpolate_env : add->interpolate_env; new->preserve_host = (add->preserve_host_set == 0) ? base->preserve_host : add->preserve_host; new->preserve_host_set = add->preserve_host_set || base->preserve_host_set; new->error_override = (add->error_override_set == 0) ? base->error_override : add->error_override; new->error_override_set = add->error_override_set || base->error_override_set; new->alias = (add->alias_set == 0) ? base->alias : add->alias; new->alias_set = add->alias_set || base->alias_set; new->add_forwarded_headers = add->add_forwarded_headers; return new; } static const char * add_proxy(cmd_parms *cmd, void *dummy, const char *f1, const char *r1, int regex) { server_rec *s = cmd->server; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module); struct proxy_remote *new; char *p, *q; char *r, *f, *scheme; ap_regex_t *reg = NULL; int port; r = apr_pstrdup(cmd->pool, r1); scheme = apr_pstrdup(cmd->pool, r1); f = apr_pstrdup(cmd->pool, f1); p = strchr(r, ':'); if (p == NULL || p[1] != '/' || p[2] != '/' || p[3] == '\0') { if (regex) return "ProxyRemoteMatch: Bad syntax for a remote proxy server"; else return "ProxyRemote: Bad syntax for a remote proxy server"; } else { scheme[p-r] = 0; } q = strchr(p + 3, ':'); if (q != NULL) { if (sscanf(q + 1, "%u", &port) != 1 || port > 65535) { if (regex) return "ProxyRemoteMatch: Bad syntax for a remote proxy server (bad port number)"; else return "ProxyRemote: Bad syntax for a remote proxy server (bad port number)"; } *q = '\0'; } else port = -1; *p = '\0'; if (regex) { reg = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED); if (!reg) return "Regular expression for ProxyRemoteMatch could not be compiled."; } else if (strchr(f, ':') == NULL) ap_str_tolower(f); /* lowercase scheme */ ap_str_tolower(p + 3); /* lowercase hostname */ if (port == -1) { port = apr_uri_port_of_scheme(scheme); } new = apr_array_push(conf->proxies); new->scheme = f; new->protocol = r; new->hostname = p + 3; new->port = port; new->regexp = reg; new->use_regex = regex; return NULL; } static const char * add_proxy_noregex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1) { return add_proxy(cmd, dummy, f1, r1, 0); } static const char * add_proxy_regex(cmd_parms *cmd, void *dummy, const char *f1, const char *r1) { return add_proxy(cmd, dummy, f1, r1, 1); } static char *de_socketfy(apr_pool_t *p, char *url) { char *ptr; /* * We could be passed a URL during the config stage that contains * the UDS path... ignore it */ if (!strncasecmp(url, "unix:", 5) && ((ptr = ap_strchr(url, '|')) != NULL)) { /* move past the 'unix:...|' UDS path info */ char *ret, *c; ret = ptr + 1; /* special case: "unix:....|scheme:" is OK, expand * to "unix:....|scheme://localhost" * */ c = ap_strchr(ret, ':'); if (c == NULL) { return NULL; } if (c[1] == '\0') { return apr_pstrcat(p, ret, "//localhost", NULL); } else { return ret; } } return url; } static const char * add_pass(cmd_parms *cmd, void *dummy, const char *arg, int is_regex) { proxy_dir_conf *dconf = (proxy_dir_conf *)dummy; server_rec *s = cmd->server; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module); struct proxy_alias *new; char *f = cmd->path; char *r = NULL; char *word; apr_table_t *params = apr_table_make(cmd->pool, 5); const apr_array_header_t *arr; const apr_table_entry_t *elts; int i; int use_regex = is_regex; unsigned int flags = 0; const char *err; err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES); if (err) { return err; } while (*arg) { word = ap_getword_conf(cmd->pool, &arg); if (!f) { if (!strcmp(word, "~")) { if (is_regex) { return "ProxyPassMatch invalid syntax ('~' usage)."; } use_regex = 1; continue; } f = word; } else if (!r) { r = word; } else if (!strcasecmp(word,"nocanon")) { flags |= PROXYPASS_NOCANON; } else if (!strcasecmp(word,"interpolate")) { flags |= PROXYPASS_INTERPOLATE; } else if (!strcasecmp(word,"noquery")) { flags |= PROXYPASS_NOQUERY; } else { char *val = strchr(word, '='); if (!val) { if (cmd->path) { if (*r == '/') { return "ProxyPass|ProxyPassMatch can not have a path when defined in " "a location."; } else { return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must " "be in the form 'key=value'."; } } else { return "Invalid ProxyPass|ProxyPassMatch parameter. Parameter must be " "in the form 'key=value'."; } } else *val++ = '\0'; apr_table_setn(params, word, val); } }; if (r == NULL) { return "ProxyPass|ProxyPassMatch needs a path when not defined in a location"; } /* if per directory, save away the single alias */ if (cmd->path) { dconf->alias = apr_pcalloc(cmd->pool, sizeof(struct proxy_alias)); dconf->alias_set = 1; new = dconf->alias; if (apr_fnmatch_test(f)) { use_regex = 1; } } /* if per server, add to the alias array */ else { new = apr_array_push(conf->aliases); } new->fake = apr_pstrdup(cmd->pool, f); new->real = apr_pstrdup(cmd->pool, de_socketfy(cmd->pool, r)); new->flags = flags; if (use_regex) { new->regex = ap_pregcomp(cmd->pool, f, AP_REG_EXTENDED); if (new->regex == NULL) return "Regular expression could not be compiled."; } else { new->regex = NULL; } if (r[0] == '!' && r[1] == '\0') return NULL; arr = apr_table_elts(params); elts = (const apr_table_entry_t *)arr->elts; /* Distinguish the balancer from worker */ if (ap_proxy_valid_balancer_name(r, 9)) { proxy_balancer *balancer = ap_proxy_get_balancer(cmd->pool, conf, r, 0); char *fake_copy; /* * In the regex case supplying a fake URL doesn't make sense as it * cannot be parsed anyway with apr_uri_parse later on in * ap_proxy_define_balancer / ap_proxy_update_balancer */ if (use_regex) { fake_copy = NULL; } else { fake_copy = f; } if (!balancer) { const char *err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, r, fake_copy, 0); if (err) return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL); } else { ap_proxy_update_balancer(cmd->pool, balancer, fake_copy); } for (i = 0; i < arr->nelts; i++) { const char *err = set_balancer_param(conf, cmd->pool, balancer, elts[i].key, elts[i].val); if (err) return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL); } new->balancer = balancer; } else { proxy_worker *worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, new->real); int reuse = 0; if (!worker) { const char *err; if (use_regex) { err = ap_proxy_define_match_worker(cmd->pool, &worker, NULL, conf, r, 0); } else { err = ap_proxy_define_worker(cmd->pool, &worker, NULL, conf, r, 0); } if (err) return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL); PROXY_COPY_CONF_PARAMS(worker, conf); } else if ((use_regex != 0) ^ (worker->s->is_name_matchable != 0)) { return apr_pstrcat(cmd->temp_pool, "ProxyPass/<Proxy> and " "ProxyPassMatch/<ProxyMatch> can't be used " "altogether with the same worker name ", "(", worker->s->name, ")", NULL); } else { reuse = 1; ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01145) "Sharing worker '%s' instead of creating new worker '%s'", ap_proxy_worker_name(cmd->pool, worker), new->real); } for (i = 0; i < arr->nelts; i++) { if (reuse) { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01146) "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing", elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker)); } else { const char *err = set_worker_param(cmd->pool, worker, elts[i].key, elts[i].val); if (err) return apr_pstrcat(cmd->temp_pool, "ProxyPass ", err, NULL); } } } return NULL; } static const char * add_pass_noregex(cmd_parms *cmd, void *dummy, const char *arg) { return add_pass(cmd, dummy, arg, 0); } static const char * add_pass_regex(cmd_parms *cmd, void *dummy, const char *arg) { return add_pass(cmd, dummy, arg, 1); } static const char * add_pass_reverse(cmd_parms *cmd, void *dconf, const char *f, const char *r, const char *i) { proxy_dir_conf *conf = dconf; struct proxy_alias *new; const char *fake; const char *real; const char *interp; const char *err; err = ap_check_cmd_context(cmd, NOT_IN_DIRECTORY|NOT_IN_FILES); if (err) { return err; } if (cmd->path == NULL) { if (r == NULL || !strcasecmp(r, "interpolate")) { return "ProxyPassReverse needs a path when not defined in a location"; } fake = f; real = r; interp = i; } else { if (r && strcasecmp(r, "interpolate")) { return "ProxyPassReverse can not have a path when defined in a location"; } fake = cmd->path; real = f; interp = r; } new = apr_array_push(conf->raliases); new->fake = fake; new->real = real; new->flags = interp ? PROXYPASS_INTERPOLATE : 0; return NULL; } static const char* cookie_path(cmd_parms *cmd, void *dconf, const char *f, const char *r, const char *interp) { proxy_dir_conf *conf = dconf; struct proxy_alias *new; new = apr_array_push(conf->cookie_paths); new->fake = f; new->real = r; new->flags = interp ? PROXYPASS_INTERPOLATE : 0; return NULL; } static const char* cookie_domain(cmd_parms *cmd, void *dconf, const char *f, const char *r, const char *interp) { proxy_dir_conf *conf = dconf; struct proxy_alias *new; new = apr_array_push(conf->cookie_domains); new->fake = f; new->real = r; new->flags = interp ? PROXYPASS_INTERPOLATE : 0; return NULL; } static const char * set_proxy_exclude(cmd_parms *parms, void *dummy, const char *arg) { server_rec *s = parms->server; proxy_server_conf *conf = ap_get_module_config(s->module_config, &proxy_module); struct noproxy_entry *new; struct noproxy_entry *list = (struct noproxy_entry *) conf->noproxies->elts; struct apr_sockaddr_t *addr; int found = 0; int i; /* Don't duplicate entries */ for (i = 0; i < conf->noproxies->nelts; i++) { if (strcasecmp(arg, list[i].name) == 0) { /* ignore case for host names */ found = 1; break; } } if (!found) { new = apr_array_push(conf->noproxies); new->name = arg; if (APR_SUCCESS == apr_sockaddr_info_get(&addr, new->name, APR_UNSPEC, 0, 0, parms->pool)) { new->addr = addr; } else { new->addr = NULL; } } return NULL; } /* Similar to set_proxy_exclude(), but defining directly connected hosts, * which should never be accessed via the configured ProxyRemote servers */ static const char * set_proxy_dirconn(cmd_parms *parms, void *dummy, const char *arg) { server_rec *s = parms->server; proxy_server_conf *conf = ap_get_module_config(s->module_config, &proxy_module); struct dirconn_entry *New; struct dirconn_entry *list = (struct dirconn_entry *) conf->dirconn->elts; int found = 0; int i; /* Don't duplicate entries */ for (i = 0; i < conf->dirconn->nelts; i++) { if (strcasecmp(arg, list[i].name) == 0) { found = 1; break; } } if (!found) { New = apr_array_push(conf->dirconn); New->name = apr_pstrdup(parms->pool, arg); New->hostaddr = NULL; if (ap_proxy_is_ipaddr(New, parms->pool)) { #if DEBUGGING ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Parsed addr %s", inet_ntoa(New->addr)); ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Parsed mask %s", inet_ntoa(New->mask)); #endif } else if (ap_proxy_is_domainname(New, parms->pool)) { ap_str_tolower(New->name); #if DEBUGGING ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Parsed domain %s", New->name); #endif } else if (ap_proxy_is_hostname(New, parms->pool)) { ap_str_tolower(New->name); #if DEBUGGING ap_log_error(APLOG_MARK, APLOG_STARTUP, 0, NULL, "Parsed host %s", New->name); #endif } else { ap_proxy_is_word(New, parms->pool); #if DEBUGGING fprintf(stderr, "Parsed word %s\n", New->name); #endif } } return NULL; } static const char * set_proxy_domain(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); if (arg[0] != '.') return "ProxyDomain: domain name must start with a dot."; psf->domain = arg; return NULL; } static const char * set_proxy_req(cmd_parms *parms, void *dummy, int flag) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); psf->req = flag; psf->req_set = 1; return NULL; } static const char * set_proxy_error_override(cmd_parms *parms, void *dconf, int flag) { proxy_dir_conf *conf = dconf; conf->error_override = flag; conf->error_override_set = 1; return NULL; } static const char * add_proxy_http_headers(cmd_parms *parms, void *dconf, int flag) { proxy_dir_conf *conf = dconf; conf->add_forwarded_headers = flag; return NULL; } static const char * set_preserve_host(cmd_parms *parms, void *dconf, int flag) { proxy_dir_conf *conf = dconf; conf->preserve_host = flag; conf->preserve_host_set = 1; return NULL; } static const char * set_recv_buffer_size(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); int s = atoi(arg); if (s < 512 && s != 0) { return "ProxyReceiveBufferSize must be >= 512 bytes, or 0 for system default."; } psf->recv_buffer_size = s; psf->recv_buffer_size_set = 1; return NULL; } static const char * set_io_buffer_size(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); long s = atol(arg); if (s < 512 && s) { return "ProxyIOBufferSize must be >= 512 bytes, or 0 for system default."; } psf->io_buffer_size = (s ? s : AP_IOBUFSIZE); psf->io_buffer_size_set = 1; return NULL; } static const char * set_max_forwards(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); long s = atol(arg); psf->maxfwd = s; psf->maxfwd_set = 1; return NULL; } static const char* set_proxy_timeout(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); int timeout; timeout = atoi(arg); if (timeout<1) { return "Proxy Timeout must be at least 1 second."; } psf->timeout_set = 1; psf->timeout = apr_time_from_sec(timeout); return NULL; } static const char* set_via_opt(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); if (strcasecmp(arg, "Off") == 0) psf->viaopt = via_off; else if (strcasecmp(arg, "On") == 0) psf->viaopt = via_on; else if (strcasecmp(arg, "Block") == 0) psf->viaopt = via_block; else if (strcasecmp(arg, "Full") == 0) psf->viaopt = via_full; else { return "ProxyVia must be one of: " "off | on | full | block"; } psf->viaopt_set = 1; return NULL; } static const char* set_bad_opt(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); if (strcasecmp(arg, "IsError") == 0) psf->badopt = bad_error; else if (strcasecmp(arg, "Ignore") == 0) psf->badopt = bad_ignore; else if (strcasecmp(arg, "StartBody") == 0) psf->badopt = bad_body; else { return "ProxyBadHeader must be one of: " "IsError | Ignore | StartBody"; } psf->badopt_set = 1; return NULL; } static const char* set_status_opt(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); if (strcasecmp(arg, "Off") == 0) psf->proxy_status = status_off; else if (strcasecmp(arg, "On") == 0) psf->proxy_status = status_on; else if (strcasecmp(arg, "Full") == 0) psf->proxy_status = status_full; else { return "ProxyStatus must be one of: " "off | on | full"; } psf->proxy_status_set = 1; return NULL; } static const char *set_bgrowth(cmd_parms *parms, void *dummy, const char *arg) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); int growth = atoi(arg); if (growth < 0 || growth > 1000) { return "BalancerGrowth must be between 0 and 1000"; } psf->bgrowth = growth; psf->bgrowth_set = 1; return NULL; } static const char *set_persist(cmd_parms *parms, void *dummy, int flag) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); psf->bal_persist = flag; return NULL; } static const char *set_inherit(cmd_parms *parms, void *dummy, int flag) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); psf->inherit = flag; psf->inherit_set = 1; return NULL; } static const char *set_ppinherit(cmd_parms *parms, void *dummy, int flag) { proxy_server_conf *psf = ap_get_module_config(parms->server->module_config, &proxy_module); psf->ppinherit = flag; psf->ppinherit_set = 1; return NULL; } static const char *add_member(cmd_parms *cmd, void *dummy, const char *arg) { server_rec *s = cmd->server; proxy_server_conf *conf = ap_get_module_config(s->module_config, &proxy_module); proxy_balancer *balancer; proxy_worker *worker; char *path = cmd->path; char *name = NULL; char *word; apr_table_t *params = apr_table_make(cmd->pool, 5); const apr_array_header_t *arr; const apr_table_entry_t *elts; int reuse = 0; int i; /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); if (err) return err; if (cmd->path) path = apr_pstrdup(cmd->pool, cmd->path); while (*arg) { char *val; word = ap_getword_conf(cmd->pool, &arg); val = strchr(word, '='); if (!val) { if (!path) path = word; else if (!name) name = word; else { if (cmd->path) return "BalancerMember can not have a balancer name when defined in a location"; else return "Invalid BalancerMember parameter. Parameter must " "be in the form 'key=value'"; } } else { *val++ = '\0'; apr_table_setn(params, word, val); } } if (!path) return "BalancerMember must define balancer name when outside <Proxy > section"; if (!name) return "BalancerMember must define remote proxy server"; ap_str_tolower(path); /* lowercase scheme://hostname */ /* Try to find the balancer */ balancer = ap_proxy_get_balancer(cmd->temp_pool, conf, path, 0); if (!balancer) { err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, path, "/", 0); if (err) return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL); } /* Try to find existing worker */ worker = ap_proxy_get_worker(cmd->temp_pool, balancer, conf, de_socketfy(cmd->temp_pool, name)); if (!worker) { ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01147) "Defining worker '%s' for balancer '%s'", name, balancer->s->name); if ((err = ap_proxy_define_worker(cmd->pool, &worker, balancer, conf, name, 0)) != NULL) return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL); ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, cmd->server, APLOGNO(01148) "Defined worker '%s' for balancer '%s'", ap_proxy_worker_name(cmd->pool, worker), balancer->s->name); PROXY_COPY_CONF_PARAMS(worker, conf); } else { reuse = 1; ap_log_error(APLOG_MARK, APLOG_INFO, 0, cmd->server, APLOGNO(01149) "Sharing worker '%s' instead of creating new worker '%s'", ap_proxy_worker_name(cmd->pool, worker), name); } arr = apr_table_elts(params); elts = (const apr_table_entry_t *)arr->elts; for (i = 0; i < arr->nelts; i++) { if (reuse) { ap_log_error(APLOG_MARK, APLOG_WARNING, 0, cmd->server, APLOGNO(01150) "Ignoring parameter '%s=%s' for worker '%s' because of worker sharing", elts[i].key, elts[i].val, ap_proxy_worker_name(cmd->pool, worker)); } else { err = set_worker_param(cmd->pool, worker, elts[i].key, elts[i].val); if (err) return apr_pstrcat(cmd->temp_pool, "BalancerMember ", err, NULL); } } return NULL; } static const char * set_proxy_param(cmd_parms *cmd, void *dummy, const char *arg) { server_rec *s = cmd->server; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(s->module_config, &proxy_module); char *name = NULL; char *word, *val; proxy_balancer *balancer = NULL; proxy_worker *worker = NULL; int in_proxy_section = 0; /* XXX: Should this be NOT_IN_DIRECTORY|NOT_IN_FILES? */ const char *err = ap_check_cmd_context(cmd, NOT_IN_HTACCESS); if (err) return err; if (cmd->directive->parent && strncasecmp(cmd->directive->parent->directive, "<Proxy", 6) == 0) { const char *pargs = cmd->directive->parent->args; /* Directive inside <Proxy section * Parent directive arg is the worker/balancer name. */ name = ap_getword_conf(cmd->temp_pool, &pargs); if ((word = ap_strchr(name, '>'))) *word = '\0'; in_proxy_section = 1; } else { /* Standard set directive with worker/balancer * name as first param. */ name = ap_getword_conf(cmd->temp_pool, &arg); } if (ap_proxy_valid_balancer_name(name, 9)) { balancer = ap_proxy_get_balancer(cmd->pool, conf, name, 0); if (!balancer) { if (in_proxy_section) { err = ap_proxy_define_balancer(cmd->pool, &balancer, conf, name, "/", 0); if (err) return apr_pstrcat(cmd->temp_pool, "ProxySet ", err, NULL); } else return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '", name, "' Balancer.", NULL); } } else { worker = ap_proxy_get_worker(cmd->temp_pool, NULL, conf, de_socketfy(cmd->temp_pool, name)); if (!worker) { if (in_proxy_section) { err = ap_proxy_define_worker(cmd->pool, &worker, NULL, conf, name, 0); if (err) return apr_pstrcat(cmd->temp_pool, "ProxySet ", err, NULL); } else return apr_pstrcat(cmd->temp_pool, "ProxySet can not find '", name, "' Worker.", NULL); } } while (*arg) { word = ap_getword_conf(cmd->pool, &arg); val = strchr(word, '='); if (!val) { return "Invalid ProxySet parameter. Parameter must be " "in the form 'key=value'"; } else *val++ = '\0'; if (worker) err = set_worker_param(cmd->pool, worker, word, val); else err = set_balancer_param(conf, cmd->pool, balancer, word, val); if (err) return apr_pstrcat(cmd->temp_pool, "ProxySet: ", err, " ", word, "=", val, "; ", name, NULL); } return NULL; } static void ap_add_per_proxy_conf(server_rec *s, ap_conf_vector_t *dir_config) { proxy_server_conf *sconf = ap_get_module_config(s->module_config, &proxy_module); void **new_space = (void **)apr_array_push(sconf->sec_proxy); *new_space = dir_config; } static const char *proxysection(cmd_parms *cmd, void *mconfig, const char *arg) { const char *errmsg; const char *endp = ap_strrchr_c(arg, '>'); int old_overrides = cmd->override; char *old_path = cmd->path; proxy_dir_conf *conf; ap_conf_vector_t *new_dir_conf = ap_create_per_dir_config(cmd->pool); ap_regex_t *r = NULL; const command_rec *thiscmd = cmd->cmd; char *word, *val; proxy_balancer *balancer = NULL; proxy_worker *worker = NULL; int use_regex = 0; const char *err = ap_check_cmd_context(cmd, NOT_IN_DIR_LOC_FILE); proxy_server_conf *sconf = (proxy_server_conf *) ap_get_module_config(cmd->server->module_config, &proxy_module); if (err != NULL) { return err; } if (endp == NULL) { return apr_pstrcat(cmd->pool, cmd->cmd->name, "> directive missing closing '>'", NULL); } arg = apr_pstrndup(cmd->pool, arg, endp-arg); if (!arg) { if (thiscmd->cmd_data) return "<ProxyMatch > block must specify a path"; else return "<Proxy > block must specify a path"; } cmd->path = ap_getword_conf(cmd->pool, &arg); cmd->override = OR_ALL|ACCESS_CONF; if (!strncasecmp(cmd->path, "proxy:", 6)) cmd->path += 6; /* XXX Ignore case? What if we proxy a case-insensitive server?!? * While we are at it, shouldn't we also canonicalize the entire * scheme? See proxy_fixup() */ if (thiscmd->cmd_data) { /* <ProxyMatch> */ r = ap_pregcomp(cmd->pool, cmd->path, AP_REG_EXTENDED); if (!r) { return "Regex could not be compiled"; } use_regex = 1; } /* initialize our config and fetch it */ conf = ap_set_config_vectors(cmd->server, new_dir_conf, cmd->path, &proxy_module, cmd->pool); errmsg = ap_walk_config(cmd->directive->first_child, cmd, new_dir_conf); if (errmsg != NULL) return errmsg; conf->r = r; conf->p = cmd->path; conf->p_is_fnmatch = apr_fnmatch_test(conf->p); if (r) { conf->refs = apr_array_make(cmd->pool, 8, sizeof(char *)); ap_regname(r, conf->refs, AP_REG_MATCH, 1); } ap_add_per_proxy_conf(cmd->server, new_dir_conf); if (*arg != '\0') { if (thiscmd->cmd_data) return "Multiple <ProxyMatch> arguments not (yet) supported."; if (conf->p_is_fnmatch) return apr_pstrcat(cmd->pool, thiscmd->name, "> arguments are not supported for wildchar url.", NULL); if (!ap_strchr_c(conf->p, ':')) return apr_pstrcat(cmd->pool, thiscmd->name, "> arguments are not supported for non url.", NULL); if (ap_proxy_valid_balancer_name((char *)conf->p, 9)) { balancer = ap_proxy_get_balancer(cmd->pool, sconf, conf->p, 0); if (!balancer) { err = ap_proxy_define_balancer(cmd->pool, &balancer, sconf, conf->p, "/", 0); if (err) return apr_pstrcat(cmd->temp_pool, thiscmd->name, " ", err, NULL); } } else { worker = ap_proxy_get_worker(cmd->temp_pool, NULL, sconf, de_socketfy(cmd->temp_pool, (char*)conf->p)); if (!worker) { if (use_regex) { err = ap_proxy_define_match_worker(cmd->pool, &worker, NULL, sconf, conf->p, 0); } else { err = ap_proxy_define_worker(cmd->pool, &worker, NULL, sconf, conf->p, 0); } if (err) return apr_pstrcat(cmd->temp_pool, thiscmd->name, " ", err, NULL); } else if ((use_regex != 0) ^ (worker->s->is_name_matchable != 0)) { return apr_pstrcat(cmd->temp_pool, "ProxyPass/<Proxy> and " "ProxyPassMatch/<ProxyMatch> can't be used " "altogether with the same worker name ", "(", worker->s->name, ")", NULL); } } if (worker == NULL && balancer == NULL) { return apr_pstrcat(cmd->pool, thiscmd->name, "> arguments are supported only for workers.", NULL); } while (*arg) { word = ap_getword_conf(cmd->pool, &arg); val = strchr(word, '='); if (!val) { return "Invalid Proxy parameter. Parameter must be " "in the form 'key=value'"; } else *val++ = '\0'; if (worker) err = set_worker_param(cmd->pool, worker, word, val); else err = set_balancer_param(sconf, cmd->pool, balancer, word, val); if (err) return apr_pstrcat(cmd->temp_pool, thiscmd->name, " ", err, " ", word, "=", val, "; ", conf->p, NULL); } } cmd->path = old_path; cmd->override = old_overrides; return NULL; } static const command_rec proxy_cmds[] = { AP_INIT_RAW_ARGS("<Proxy", proxysection, NULL, RSRC_CONF, "Container for directives affecting resources located in the proxied " "location"), AP_INIT_RAW_ARGS("<ProxyMatch", proxysection, (void*)1, RSRC_CONF, "Container for directives affecting resources located in the proxied " "location, in regular expression syntax"), AP_INIT_FLAG("ProxyRequests", set_proxy_req, NULL, RSRC_CONF, "on if the true proxy requests should be accepted"), AP_INIT_TAKE2("ProxyRemote", add_proxy_noregex, NULL, RSRC_CONF, "a scheme, partial URL or '*' and a proxy server"), AP_INIT_TAKE2("ProxyRemoteMatch", add_proxy_regex, NULL, RSRC_CONF, "a regex pattern and a proxy server"), AP_INIT_FLAG("ProxyPassInterpolateEnv", ap_set_flag_slot_char, (void*)APR_OFFSETOF(proxy_dir_conf, interpolate_env), RSRC_CONF|ACCESS_CONF, "Interpolate Env Vars in reverse Proxy") , AP_INIT_RAW_ARGS("ProxyPass", add_pass_noregex, NULL, RSRC_CONF|ACCESS_CONF, "a virtual path and a URL"), AP_INIT_RAW_ARGS("ProxyPassMatch", add_pass_regex, NULL, RSRC_CONF|ACCESS_CONF, "a virtual path and a URL"), AP_INIT_TAKE123("ProxyPassReverse", add_pass_reverse, NULL, RSRC_CONF|ACCESS_CONF, "a virtual path and a URL for reverse proxy behaviour"), AP_INIT_TAKE23("ProxyPassReverseCookiePath", cookie_path, NULL, RSRC_CONF|ACCESS_CONF, "Path rewrite rule for proxying cookies"), AP_INIT_TAKE23("ProxyPassReverseCookieDomain", cookie_domain, NULL, RSRC_CONF|ACCESS_CONF, "Domain rewrite rule for proxying cookies"), AP_INIT_ITERATE("ProxyBlock", set_proxy_exclude, NULL, RSRC_CONF, "A list of names, hosts or domains to which the proxy will not connect"), AP_INIT_TAKE1("ProxyReceiveBufferSize", set_recv_buffer_size, NULL, RSRC_CONF, "Receive buffer size for outgoing HTTP and FTP connections in bytes"), AP_INIT_TAKE1("ProxyIOBufferSize", set_io_buffer_size, NULL, RSRC_CONF, "IO buffer size for outgoing HTTP and FTP connections in bytes"), AP_INIT_TAKE1("ProxyMaxForwards", set_max_forwards, NULL, RSRC_CONF, "The maximum number of proxies a request may be forwarded through."), AP_INIT_ITERATE("NoProxy", set_proxy_dirconn, NULL, RSRC_CONF, "A list of domains, hosts, or subnets to which the proxy will connect directly"), AP_INIT_TAKE1("ProxyDomain", set_proxy_domain, NULL, RSRC_CONF, "The default intranet domain name (in absence of a domain in the URL)"), AP_INIT_TAKE1("ProxyVia", set_via_opt, NULL, RSRC_CONF, "Configure Via: proxy header header to one of: on | off | block | full"), AP_INIT_FLAG("ProxyErrorOverride", set_proxy_error_override, NULL, RSRC_CONF|ACCESS_CONF, "use our error handling pages instead of the servers' we are proxying"), AP_INIT_FLAG("ProxyPreserveHost", set_preserve_host, NULL, RSRC_CONF|ACCESS_CONF, "on if we should preserve host header while proxying"), AP_INIT_TAKE1("ProxyTimeout", set_proxy_timeout, NULL, RSRC_CONF, "Set the timeout (in seconds) for a proxied connection. " "This overrides the server timeout"), AP_INIT_TAKE1("ProxyBadHeader", set_bad_opt, NULL, RSRC_CONF, "How to handle bad header line in response: IsError | Ignore | StartBody"), AP_INIT_RAW_ARGS("BalancerMember", add_member, NULL, RSRC_CONF|ACCESS_CONF, "A balancer name and scheme with list of params"), AP_INIT_TAKE1("BalancerGrowth", set_bgrowth, NULL, RSRC_CONF, "Number of additional Balancers that can be added post-config"), AP_INIT_FLAG("BalancerPersist", set_persist, NULL, RSRC_CONF, "on if the balancer should persist changes on reboot/restart made via the Balancer Manager"), AP_INIT_FLAG("BalancerInherit", set_inherit, NULL, RSRC_CONF, "on if this server should inherit Balancers and Workers defined in the main server " "(Setting to off recommended if using the Balancer Manager)"), AP_INIT_FLAG("ProxyPassInherit", set_ppinherit, NULL, RSRC_CONF, "on if this server should inherit all ProxyPass directives defined in the main server " "(Setting to off recommended if using the Balancer Manager)"), AP_INIT_TAKE1("ProxyStatus", set_status_opt, NULL, RSRC_CONF, "Configure Status: proxy status to one of: on | off | full"), AP_INIT_RAW_ARGS("ProxySet", set_proxy_param, NULL, RSRC_CONF|ACCESS_CONF, "A balancer or worker name with list of params"), AP_INIT_TAKE1("ProxySourceAddress", set_source_address, NULL, RSRC_CONF, "Configure local source IP used for request forward"), AP_INIT_FLAG("ProxyAddHeaders", add_proxy_http_headers, NULL, RSRC_CONF|ACCESS_CONF, "on if X-Forwarded-* headers should be added or completed"), {NULL} }; static APR_OPTIONAL_FN_TYPE(ssl_proxy_enable) *proxy_ssl_enable = NULL; static APR_OPTIONAL_FN_TYPE(ssl_engine_disable) *proxy_ssl_disable = NULL; static APR_OPTIONAL_FN_TYPE(ssl_is_https) *proxy_is_https = NULL; static APR_OPTIONAL_FN_TYPE(ssl_var_lookup) *proxy_ssl_val = NULL; PROXY_DECLARE(int) ap_proxy_ssl_enable(conn_rec *c) { /* * if c == NULL just check if the optional function was imported * else run the optional function so ssl filters are inserted */ if (proxy_ssl_enable) { return c ? proxy_ssl_enable(c) : 1; } return 0; } PROXY_DECLARE(int) ap_proxy_ssl_disable(conn_rec *c) { if (proxy_ssl_disable) { return proxy_ssl_disable(c); } return 0; } PROXY_DECLARE(int) ap_proxy_conn_is_https(conn_rec *c) { if (proxy_is_https) { return proxy_is_https(c); } else return 0; } PROXY_DECLARE(const char *) ap_proxy_ssl_val(apr_pool_t *p, server_rec *s, conn_rec *c, request_rec *r, const char *var) { if (proxy_ssl_val) { /* XXX Perhaps the casting useless */ return (const char *)proxy_ssl_val(p, s, c, r, (char *)var); } else return NULL; } static int proxy_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { apr_status_t rv = ap_global_mutex_create(&proxy_mutex, NULL, proxy_id, NULL, s, pconf, 0); if (rv != APR_SUCCESS) { ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02478) "failed to create %s mutex", proxy_id); return rv; } proxy_ssl_enable = APR_RETRIEVE_OPTIONAL_FN(ssl_proxy_enable); proxy_ssl_disable = APR_RETRIEVE_OPTIONAL_FN(ssl_engine_disable); proxy_is_https = APR_RETRIEVE_OPTIONAL_FN(ssl_is_https); proxy_ssl_val = APR_RETRIEVE_OPTIONAL_FN(ssl_var_lookup); ap_proxy_strmatch_path = apr_strmatch_precompile(pconf, "path=", 0); ap_proxy_strmatch_domain = apr_strmatch_precompile(pconf, "domain=", 0); return OK; } /* * proxy Extension to mod_status */ static int proxy_status_hook(request_rec *r, int flags) { int i, n; void *sconf = r->server->module_config; proxy_server_conf *conf = (proxy_server_conf *) ap_get_module_config(sconf, &proxy_module); proxy_balancer *balancer = NULL; proxy_worker **worker = NULL; if ((flags & AP_STATUS_SHORT) || conf->balancers->nelts == 0 || conf->proxy_status == status_off) return OK; balancer = (proxy_balancer *)conf->balancers->elts; for (i = 0; i < conf->balancers->nelts; i++) { ap_rputs("<hr />\n<h1>Proxy LoadBalancer Status for ", r); ap_rvputs(r, balancer->s->name, "</h1>\n\n", NULL); ap_rputs("\n\n<table border=\"0\"><tr>" "<th>SSes</th><th>Timeout</th><th>Method</th>" "</tr>\n<tr>", r); if (*balancer->s->sticky) { if (strcmp(balancer->s->sticky, balancer->s->sticky_path)) { ap_rvputs(r, "<td>", balancer->s->sticky, " | ", balancer->s->sticky_path, NULL); } else { ap_rvputs(r, "<td>", balancer->s->sticky, NULL); } } else { ap_rputs("<td> - ", r); } ap_rprintf(r, "</td><td>%" APR_TIME_T_FMT "</td>", apr_time_sec(balancer->s->timeout)); ap_rprintf(r, "<td>%s</td>\n", balancer->lbmethod->name); ap_rputs("</table>\n", r); ap_rputs("\n\n<table border=\"0\"><tr>" "<th>Sch</th><th>Host</th><th>Stat</th>" "<th>Route</th><th>Redir</th>" "<th>F</th><th>Set</th><th>Acc</th><th>Wr</th><th>Rd</th>" "</tr>\n", r); worker = (proxy_worker **)balancer->workers->elts; for (n = 0; n < balancer->workers->nelts; n++) { char fbuf[50]; ap_rvputs(r, "<tr>\n<td>", (*worker)->s->scheme, "</td>", NULL); ap_rvputs(r, "<td>", (*worker)->s->hostname, "</td><td>", NULL); ap_rvputs(r, ap_proxy_parse_wstatus(r->pool, *worker), NULL); ap_rvputs(r, "</td><td>", (*worker)->s->route, NULL); ap_rvputs(r, "</td><td>", (*worker)->s->redirect, NULL); ap_rprintf(r, "</td><td>%d</td>", (*worker)->s->lbfactor); ap_rprintf(r, "<td>%d</td>", (*worker)->s->lbset); ap_rprintf(r, "<td>%" APR_SIZE_T_FMT "</td><td>", (*worker)->s->elected); ap_rputs(apr_strfsize((*worker)->s->transferred, fbuf), r); ap_rputs("</td><td>", r); ap_rputs(apr_strfsize((*worker)->s->read, fbuf), r); ap_rputs("</td>\n", r); /* TODO: Add the rest of dynamic worker data */ ap_rputs("</tr>\n", r); ++worker; } ap_rputs("</table>\n", r); ++balancer; } ap_rputs("<hr /><table>\n" "<tr><th>SSes</th><td>Sticky session name</td></tr>\n" "<tr><th>Timeout</th><td>Balancer Timeout</td></tr>\n" "<tr><th>Sch</th><td>Connection scheme</td></tr>\n" "<tr><th>Host</th><td>Backend Hostname</td></tr>\n" "<tr><th>Stat</th><td>Worker status</td></tr>\n" "<tr><th>Route</th><td>Session Route</td></tr>\n" "<tr><th>Redir</th><td>Session Route Redirection</td></tr>\n" "<tr><th>F</th><td>Load Balancer Factor</td></tr>\n" "<tr><th>Acc</th><td>Number of uses</td></tr>\n" "<tr><th>Wr</th><td>Number of bytes transferred</td></tr>\n" "<tr><th>Rd</th><td>Number of bytes read</td></tr>\n" "</table>", r); return OK; } static void child_init(apr_pool_t *p, server_rec *s) { proxy_worker *reverse = NULL; apr_status_t rv = apr_global_mutex_child_init(&proxy_mutex, apr_global_mutex_lockfile(proxy_mutex), p); if (rv != APR_SUCCESS) { ap_log_error(APLOG_MARK, APLOG_CRIT, rv, s, APLOGNO(02479) "could not init proxy_mutex in child"); exit(1); /* Ugly, but what else? */ } /* TODO */ while (s) { void *sconf = s->module_config; proxy_server_conf *conf; proxy_worker *worker; int i; conf = (proxy_server_conf *)ap_get_module_config(sconf, &proxy_module); /* * NOTE: non-balancer members don't use shm at all... * after all, why should they? */ worker = (proxy_worker *)conf->workers->elts; for (i = 0; i < conf->workers->nelts; i++, worker++) { ap_proxy_initialize_worker(worker, s, conf->pool); } /* Create and initialize forward worker if defined */ if (conf->req_set && conf->req) { proxy_worker *forward; ap_proxy_define_worker(p, &forward, NULL, NULL, "http://www.apache.org", 0); conf->forward = forward; PROXY_STRNCPY(conf->forward->s->name, "proxy:forward"); PROXY_STRNCPY(conf->forward->s->hostname, "*"); PROXY_STRNCPY(conf->forward->s->scheme, "*"); conf->forward->hash.def = conf->forward->s->hash.def = ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_DEFAULT); conf->forward->hash.fnv = conf->forward->s->hash.fnv = ap_proxy_hashfunc(conf->forward->s->name, PROXY_HASHFUNC_FNV); /* Do not disable worker in case of errors */ conf->forward->s->status |= PROXY_WORKER_IGNORE_ERRORS; /* Mark as the "generic" worker */ conf->forward->s->status |= PROXY_WORKER_GENERIC; ap_proxy_initialize_worker(conf->forward, s, conf->pool); /* Disable address cache for generic forward worker */ conf->forward->s->is_address_reusable = 0; } if (!reverse) { ap_proxy_define_worker(p, &reverse, NULL, NULL, "http://www.apache.org", 0); PROXY_STRNCPY(reverse->s->name, "proxy:reverse"); PROXY_STRNCPY(reverse->s->hostname, "*"); PROXY_STRNCPY(reverse->s->scheme, "*"); reverse->hash.def = reverse->s->hash.def = ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_DEFAULT); reverse->hash.fnv = reverse->s->hash.fnv = ap_proxy_hashfunc(reverse->s->name, PROXY_HASHFUNC_FNV); /* Do not disable worker in case of errors */ reverse->s->status |= PROXY_WORKER_IGNORE_ERRORS; /* Mark as the "generic" worker */ reverse->s->status |= PROXY_WORKER_GENERIC; conf->reverse = reverse; ap_proxy_initialize_worker(conf->reverse, s, conf->pool); /* Disable address cache for generic reverse worker */ reverse->s->is_address_reusable = 0; } conf->reverse = reverse; s = s->next; } } /* * This routine is called before the server processes the configuration * files. */ static int proxy_pre_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp) { apr_status_t rv = ap_mutex_register(pconf, proxy_id, NULL, APR_LOCK_DEFAULT, 0); if (rv != APR_SUCCESS) { ap_log_perror(APLOG_MARK, APLOG_CRIT, rv, plog, APLOGNO(02480) "failed to register %s mutex", proxy_id); return 500; /* An HTTP status would be a misnomer! */ } APR_OPTIONAL_HOOK(ap, status_hook, proxy_status_hook, NULL, NULL, APR_HOOK_MIDDLE); /* Reset workers count on gracefull restart */ proxy_lb_workers = 0; return OK; } static void register_hooks(apr_pool_t *p) { /* fixup before mod_rewrite, so that the proxied url will not * escaped accidentally by our fixup. */ static const char * const aszSucc[] = { "mod_rewrite.c", NULL}; /* Only the mpm_winnt has child init hook handler. * make sure that we are called after the mpm * initializes. */ static const char *const aszPred[] = { "mpm_winnt.c", "mod_proxy_balancer.c", NULL}; /* handler */ ap_hook_handler(proxy_handler, NULL, NULL, APR_HOOK_FIRST); /* filename-to-URI translation */ ap_hook_translate_name(proxy_trans, aszSucc, NULL, APR_HOOK_FIRST); /* walk <Proxy > entries and suppress default TRACE behavior */ ap_hook_map_to_storage(proxy_map_location, NULL,NULL, APR_HOOK_FIRST); /* fixups */ ap_hook_fixups(proxy_fixup, NULL, aszSucc, APR_HOOK_FIRST); /* post read_request handling */ ap_hook_post_read_request(proxy_detect, NULL, NULL, APR_HOOK_FIRST); /* pre config handling */ ap_hook_pre_config(proxy_pre_config, NULL, NULL, APR_HOOK_MIDDLE); /* post config handling */ ap_hook_post_config(proxy_post_config, NULL, NULL, APR_HOOK_MIDDLE); /* child init handling */ ap_hook_child_init(child_init, aszPred, NULL, APR_HOOK_MIDDLE); /* register optional functions within proxy_util.c */ proxy_util_register_hooks(p); } AP_DECLARE_MODULE(proxy) = { STANDARD20_MODULE_STUFF, create_proxy_dir_config, /* create per-directory config structure */ merge_proxy_dir_config, /* merge per-directory config structures */ create_proxy_config, /* create per-server config structure */ merge_proxy_config, /* merge per-server config structures */ proxy_cmds, /* command table */ register_hooks }; APR_HOOK_STRUCT( APR_HOOK_LINK(scheme_handler) APR_HOOK_LINK(canon_handler) APR_HOOK_LINK(pre_request) APR_HOOK_LINK(post_request) APR_HOOK_LINK(request_status) ) APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, scheme_handler, (request_rec *r, proxy_worker *worker, proxy_server_conf *conf, char *url, const char *proxyhost, apr_port_t proxyport),(r,worker,conf, url,proxyhost,proxyport),DECLINED) APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, canon_handler, (request_rec *r, char *url),(r, url),DECLINED) APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, pre_request, ( proxy_worker **worker, proxy_balancer **balancer, request_rec *r, proxy_server_conf *conf, char **url),(worker,balancer, r,conf,url),DECLINED) APR_IMPLEMENT_EXTERNAL_HOOK_RUN_FIRST(proxy, PROXY, int, post_request, (proxy_worker *worker, proxy_balancer *balancer, request_rec *r, proxy_server_conf *conf),(worker, balancer,r,conf),DECLINED) APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, fixups, (request_rec *r), (r), OK, DECLINED) APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, request_status, (int *status, request_rec *r), (status, r), OK, DECLINED) APR_IMPLEMENT_OPTIONAL_HOOK_RUN_ALL(proxy, PROXY, int, detach_backend, (request_rec *r, proxy_conn_rec *backend), (r, backend), OK, DECLINED)
494211.c
#include "LKH.h" /* * The MergeTourWithBestTour function attempts to find a short * tour by merging the current tour with the tour in the array BestTour. * * If a tour shorter than BestTour is found, Pred and Suc of each * node point to its neighbors, and the tour cost is returned. */ GainType MergeTourWithBestTour() { Node *N1, *N2, *M1, *M2; int i; if (ProblemType != ATSP) { for (i = 1; i <= Dimension; i++) { N1 = &NodeSet[BestTour[i - 1]]; N2 = &NodeSet[BestTour[i]]; N1->Next = N2; } } else { int Dim = Dimension / 2; for (i = 1; i <= Dim; i++) { N1 = &NodeSet[BestTour[i - 1]]; N2 = &NodeSet[BestTour[i]]; M1 = &NodeSet[N1->Id + Dim]; M2 = &NodeSet[N2->Id + Dim]; M1->Next = N1; N1->Next = M2; M2->Next = N2; } } return MergeWithTour(); }
880918.c
/* vi: set sw=4 ts=4: */ /* * Check user and group names for illegal characters * * Copyright (C) 2008 Tito Ragusa <[email protected]> * * Licensed under GPLv2 or later, see file LICENSE in this source tree. */ #include "libbb.h" /* To avoid problems, the username should consist only of * letters, digits, underscores, periods, at signs and dashes, * and not start with a dash (as defined by IEEE Std 1003.1-2001). * For compatibility with Samba machine accounts $ is also supported * at the end of the username. */ void FAST_FUNC die_if_bad_username(const char *name) { const char *start = name; /* 1st char being dash or dot isn't valid: * for example, name like ".." can make adduser * chown "/home/.." recursively - NOT GOOD. * Name of just a single "$" is also rejected. */ goto skip; do { unsigned char ch; /* These chars are valid unless they are at the 1st pos: */ if (*name == '-' || *name == '.' /* $ is allowed if it's the last char: */ || (*name == '$' && !name[1]) ) { continue; } skip: ch = *name; if (ch == '_' /* || ch == '@' -- we disallow this too. Think about "user@host" */ /* open-coded isalnum: */ || (ch >= '0' && ch <= '9') || ((ch|0x20) >= 'a' && (ch|0x20) <= 'z') ) { continue; } bb_error_msg_and_die("illegal character with code %u at position %u", (unsigned)ch, (unsigned)(name - start)); } while (*++name); /* The minimum size of the login name is one char or two if * last char is the '$'. Violations of this are caught above. * The maximum size of the login name is LOGIN_NAME_MAX * including the terminating null byte. */ if (name - start >= LOGIN_NAME_MAX) bb_error_msg_and_die("name is too long"); }
846890.c
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007-2012 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2015 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "ompi/mpi/fortran/mpif-h/bindings.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak PMPI_TYPE_CREATE_RESIZED = ompi_type_create_resized_f #pragma weak pmpi_type_create_resized = ompi_type_create_resized_f #pragma weak pmpi_type_create_resized_ = ompi_type_create_resized_f #pragma weak pmpi_type_create_resized__ = ompi_type_create_resized_f #pragma weak PMPI_Type_create_resized_f = ompi_type_create_resized_f #pragma weak PMPI_Type_create_resized_f08 = ompi_type_create_resized_f #else OMPI_GENERATE_F77_BINDINGS (PMPI_TYPE_CREATE_RESIZED, pmpi_type_create_resized, pmpi_type_create_resized_, pmpi_type_create_resized__, pompi_type_create_resized_f, (MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr), (oldtype, lb, extent, newtype, ierr) ) #endif #endif #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_TYPE_CREATE_RESIZED = ompi_type_create_resized_f #pragma weak mpi_type_create_resized = ompi_type_create_resized_f #pragma weak mpi_type_create_resized_ = ompi_type_create_resized_f #pragma weak mpi_type_create_resized__ = ompi_type_create_resized_f #pragma weak MPI_Type_create_resized_f = ompi_type_create_resized_f #pragma weak MPI_Type_create_resized_f08 = ompi_type_create_resized_f #else #if ! OMPI_BUILD_MPI_PROFILING OMPI_GENERATE_F77_BINDINGS (MPI_TYPE_CREATE_RESIZED, mpi_type_create_resized, mpi_type_create_resized_, mpi_type_create_resized__, ompi_type_create_resized_f, (MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr), (oldtype, lb, extent, newtype, ierr) ) #else #define ompi_type_create_resized_f pompi_type_create_resized_f #endif #endif void ompi_type_create_resized_f(MPI_Fint *oldtype, MPI_Aint *lb, MPI_Aint *extent, MPI_Fint *newtype, MPI_Fint *ierr) { int c_ierr; MPI_Datatype c_old = PMPI_Type_f2c(*oldtype); MPI_Datatype c_new; c_ierr = PMPI_Type_create_resized(c_old, *lb, *extent, &c_new); if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); if (MPI_SUCCESS == c_ierr) { *newtype = PMPI_Type_c2f(c_new); } }
772874.c
/** * Copyright (c) 2016 - 2018, Nordic Semiconductor ASA * * 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, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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 Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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 "nrf_bootloader.h" #include "compiler_abstraction.h" #include "nrf.h" #include "boards.h" #include "sdk_config.h" #include "nrf_power.h" #include "nrf_delay.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_dfu.h" #include "nrf_error.h" #include "nrf_dfu_settings.h" #include "nrf_dfu_utils.h" #include "nrf_bootloader_wdt.h" #include "nrf_bootloader_info.h" #include "nrf_bootloader_app_start.h" #include "nrf_bootloader_fw_activation.h" #include "nrf_bootloader_dfu_timers.h" #include "app_scheduler.h" static nrf_dfu_observer_t m_user_observer; //<! Observer callback set by the user. static volatile bool m_flash_write_done; #define SCHED_QUEUE_SIZE 32 /**< Maximum number of events in the scheduler queue. */ #define SCHED_EVENT_DATA_SIZE NRF_DFU_SCHED_EVENT_DATA_SIZE /**< Maximum app_scheduler event size. */ #if !(defined(NRF_BL_DFU_ENTER_METHOD_BUTTON) && \ defined(NRF_BL_DFU_ENTER_METHOD_PINRESET) && \ defined(NRF_BL_DFU_ENTER_METHOD_GPREGRET) && \ defined(NRF_BL_DFU_ENTER_METHOD_BUTTONLESS)) #error Configuration file is missing flags. Update sdk_config.h. #endif STATIC_ASSERT((NRF_BL_DFU_INACTIVITY_TIMEOUT_MS >= 100) || (NRF_BL_DFU_INACTIVITY_TIMEOUT_MS == 0), "NRF_BL_DFU_INACTIVITY_TIMEOUT_MS must be 100 ms or more, or 0 to indicate that it is disabled."); #if defined(NRF_LOG_BACKEND_FLASH_START_PAGE) STATIC_ASSERT(NRF_LOG_BACKEND_FLASH_START_PAGE != 0, "If nrf_log flash backend is used it cannot use space after code because it would collide with settings page."); #endif /**@brief Weak implemenation of nrf_dfu_init * * @note This function will be overridden if nrf_dfu.c is * compiled and linked with the project */ #if (__LINT__ != 1) __WEAK uint32_t nrf_dfu_init(nrf_dfu_observer_t observer) { NRF_LOG_DEBUG("in weak nrf_dfu_init"); return NRF_SUCCESS; } #endif /**@brief Weak implementation of nrf_dfu_init * * @note This function must be overridden in application if * user-specific initialization is needed. */ __WEAK uint32_t nrf_dfu_init_user(void) { NRF_LOG_DEBUG("in weak nrf_dfu_init_user"); return NRF_SUCCESS; } static void flash_write_callback(void * p_context) { UNUSED_PARAMETER(p_context); m_flash_write_done = true; } static void reset_after_flash_write(void * p_context) { UNUSED_PARAMETER(p_context); NRF_LOG_FINAL_FLUSH(); #if NRF_MODULE_ENABLED(NRF_LOG_BACKEND_RTT) // To allow the buffer to be flushed by the host. nrf_delay_ms(100); #endif NVIC_SystemReset(); } static void bootloader_reset(void) { NRF_LOG_DEBUG("Resetting bootloader."); m_flash_write_done = false; nrf_dfu_settings_backup(reset_after_flash_write); } static void inactivity_timeout(void) { NRF_LOG_INFO("Inactivity timeout."); bootloader_reset(); } /**@brief Function for handling DFU events. */ static void dfu_observer(nrf_dfu_evt_type_t evt_type) { switch (evt_type) { case NRF_DFU_EVT_DFU_STARTED: case NRF_DFU_EVT_OBJECT_RECEIVED: nrf_bootloader_dfu_inactivity_timer_restart( NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_INACTIVITY_TIMEOUT_MS), inactivity_timeout); break; case NRF_DFU_EVT_DFU_COMPLETED: case NRF_DFU_EVT_DFU_ABORTED: bootloader_reset(); break; default: break; } if (m_user_observer) { m_user_observer(evt_type); } } /**@brief Function for initializing the event scheduler. */ static void scheduler_init(void) { APP_SCHED_INIT(SCHED_EVENT_DATA_SIZE, SCHED_QUEUE_SIZE); } /**@brief Suspend the CPU until an interrupt occurs. */ static void wait_for_event(void) { #ifdef BLE_STACK_SUPPORT_REQD (void)sd_app_evt_wait(); #else // Wait for an event. __WFE(); // Clear the internal event register. __SEV(); __WFE(); #endif } /**@brief Continually sleep and process tasks whenever woken. */ static void loop_forever(void) { while (true) { //feed the watchdog if enabled. nrf_bootloader_wdt_feed(); app_sched_execute(); if (!NRF_LOG_PROCESS()) { wait_for_event(); } } } /**@brief Function for initializing button used to enter DFU mode. */ static void dfu_enter_button_init(void) { nrf_gpio_cfg_sense_input(NRF_BL_DFU_ENTER_METHOD_BUTTON_PIN, BUTTON_PULL, NRF_GPIO_PIN_SENSE_LOW); } static bool crc_on_valid_app_required(void) { bool ret = true; if (NRF_BL_APP_CRC_CHECK_SKIPPED_ON_SYSTEMOFF_RESET && (nrf_power_resetreas_get() & NRF_POWER_RESETREAS_OFF_MASK)) { nrf_power_resetreas_clear(NRF_POWER_RESETREAS_OFF_MASK); ret = false; } else if (NRF_BL_APP_CRC_CHECK_SKIPPED_ON_GPREGRET2 && (nrf_power_gpregret2_get() & BOOTLOADER_DFU_SKIP_CRC)) { nrf_power_gpregret2_set(nrf_power_gpregret2_get() & ~BOOTLOADER_DFU_SKIP_CRC); ret = false; } else { } return ret; } /**@brief Function for clearing all DFU enter flags that * preserve state during reset. * * @details This is used to make sure that each of these flags * is checked only once after reset. */ static void dfu_enter_flags_clear(void) { if (NRF_BL_DFU_ENTER_METHOD_PINRESET && (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk)) { // Clear RESETPIN flag. NRF_POWER->RESETREAS |= POWER_RESETREAS_RESETPIN_Msk; } if (NRF_BL_DFU_ENTER_METHOD_GPREGRET && (nrf_power_gpregret_get() & BOOTLOADER_DFU_START)) { // Clear DFU mark in GPREGRET register. nrf_power_gpregret_set(nrf_power_gpregret_get() & ~BOOTLOADER_DFU_START); } if (NRF_BL_DFU_ENTER_METHOD_BUTTONLESS && (s_dfu_settings.enter_buttonless_dfu == 1)) { // Clear DFU flag in flash settings. s_dfu_settings.enter_buttonless_dfu = 0; APP_ERROR_CHECK(nrf_dfu_settings_write(NULL)); } } /**@brief Function for checking whether to enter DFU mode or not. */ static bool dfu_enter_check(void) { if (!nrf_dfu_app_is_valid(crc_on_valid_app_required())) { NRF_LOG_DEBUG("DFU mode because app is not valid."); return true; } if (NRF_BL_DFU_ENTER_METHOD_BUTTON && (nrf_gpio_pin_read(NRF_BL_DFU_ENTER_METHOD_BUTTON_PIN) == 0)) { NRF_LOG_DEBUG("DFU mode requested via button."); return true; } if (NRF_BL_DFU_ENTER_METHOD_PINRESET && (NRF_POWER->RESETREAS & POWER_RESETREAS_RESETPIN_Msk)) { NRF_LOG_DEBUG("DFU mode requested via pin-reset."); return true; } if (NRF_BL_DFU_ENTER_METHOD_GPREGRET && (nrf_power_gpregret_get() & BOOTLOADER_DFU_START)) { NRF_LOG_DEBUG("DFU mode requested via GPREGRET."); return true; } if (NRF_BL_DFU_ENTER_METHOD_BUTTONLESS && (s_dfu_settings.enter_buttonless_dfu == 1)) { NRF_LOG_DEBUG("DFU mode requested via bootloader settings."); return true; } return false; } ret_code_t nrf_bootloader_init(nrf_dfu_observer_t observer) { NRF_LOG_DEBUG("In nrf_bootloader_init"); ret_code_t ret_val; nrf_bootloader_fw_activation_result_t activation_result; uint32_t initial_timeout; bool dfu_enter = false; m_user_observer = observer; if (NRF_BL_DFU_ENTER_METHOD_BUTTON) { dfu_enter_button_init(); } ret_val = nrf_dfu_settings_init(false); if (ret_val != NRF_SUCCESS) { return NRF_ERROR_INTERNAL; } // Check if an update needs to be activated and activate it. activation_result = nrf_bootloader_fw_activate(); switch (activation_result) { case ACTIVATION_NONE: initial_timeout = NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_INACTIVITY_TIMEOUT_MS); dfu_enter = dfu_enter_check(); break; case ACTIVATION_SUCCESS_EXPECT_ADDITIONAL_UPDATE: initial_timeout = NRF_BOOTLOADER_MS_TO_TICKS(NRF_BL_DFU_CONTINUATION_TIMEOUT_MS); dfu_enter = true; break; case ACTIVATION_SUCCESS: bootloader_reset(); NRF_LOG_ERROR("Should never come here: After bootloader_reset()"); return NRF_ERROR_INTERNAL; // Should not reach this. case ACTIVATION_ERROR: default: return NRF_ERROR_INTERNAL; } if (dfu_enter) { nrf_bootloader_wdt_init(); scheduler_init(); // Clear all DFU stop flags. dfu_enter_flags_clear(); // Call user-defined init function if implemented ret_val = nrf_dfu_init_user(); if (ret_val != NRF_SUCCESS) { return NRF_ERROR_INTERNAL; } nrf_bootloader_dfu_inactivity_timer_restart(initial_timeout, inactivity_timeout); ret_val = nrf_dfu_init(dfu_observer); if (ret_val != NRF_SUCCESS) { return NRF_ERROR_INTERNAL; } NRF_LOG_DEBUG("Enter main loop"); loop_forever(); // This function will never return. NRF_LOG_ERROR("Should never come here: After looping forever."); } else { // Erase additional data like peer data or advertisement name ret_val = nrf_dfu_settings_additional_erase(); if (ret_val != NRF_SUCCESS) { return NRF_ERROR_INTERNAL; } m_flash_write_done = false; nrf_dfu_settings_backup(flash_write_callback); ASSERT(m_flash_write_done); nrf_bootloader_app_start(); NRF_LOG_ERROR("Should never come here: After nrf_bootloader_app_start()"); } // Should not be reached. return NRF_ERROR_INTERNAL; }
634505.c
/* * File: bHYPRE_StructGrid_Stub.c * Symbol: bHYPRE.StructGrid-v1.0.0 * Symbol Type: class * Babel Version: 1.0.4 * Description: Client-side glue code for bHYPRE.StructGrid * * WARNING: Automatically generated; changes will be lost * */ #include "bHYPRE_StructGrid.h" #include "bHYPRE_StructGrid_IOR.h" #ifndef included_sidl_interface_IOR_h #include "sidl_interface_IOR.h" #endif #ifndef included_sidl_rmi_InstanceHandle_h #include "sidl_rmi_InstanceHandle.h" #endif #ifndef included_sidl_rmi_ConnectRegistry_h #include "sidl_rmi_ConnectRegistry.h" #endif #include "sidl_Exception.h" #ifndef included_sidl_interface_IOR_h #include "sidl_interface_IOR.h" #endif #include <stddef.h> #include <string.h> #include "sidl_BaseInterface_IOR.h" #include "babel_config.h" #ifdef SIDL_DYNAMIC_LIBRARY #include <stdio.h> #include <stdlib.h> #include "sidl_Loader.h" #endif #define LANG_SPECIFIC_INIT() /* * connect_loaded is a boolean value showing if the IHConnect for this object has been loaded into the connectRegistry */ static int connect_loaded = 0; /* * Hold pointer to IOR functions. */ static const struct bHYPRE_StructGrid__external *_externals = NULL; /* * Lookup the symbol to get the IOR functions. */ static const struct bHYPRE_StructGrid__external* _loadIOR(void) /* * Return pointer to internal IOR functions. */ { #ifdef SIDL_STATIC_LIBRARY _externals = bHYPRE_StructGrid__externals(); #else _externals = (struct bHYPRE_StructGrid__external*)sidl_dynamicLoadIOR( "bHYPRE.StructGrid","bHYPRE_StructGrid__externals") ; sidl_checkIORVersion("bHYPRE.StructGrid", _externals->d_ior_major_version, _externals->d_ior_minor_version, 1, 0); #endif return _externals; } #define _getExternals() (_externals ? _externals : _loadIOR()) /* * Hold pointer to static entry point vector */ static const struct bHYPRE_StructGrid__sepv *_sepv = NULL; /* * Return pointer to static functions. */ #define _getSEPV() (_sepv ? _sepv : (_sepv = (*(_getExternals()->getStaticEPV))())) /* * Reset point to static functions. */ #define _resetSEPV() (_sepv = (*(_getExternals()->getStaticEPV))()) /* * Constructor function for the class. */ bHYPRE_StructGrid bHYPRE_StructGrid__create(sidl_BaseInterface* _ex) { return (*(_getExternals()->createObject))(NULL,_ex); } /** * Wraps up the private data struct pointer (struct bHYPRE_StructGrid__data) passed in rather than running the constructor. */ bHYPRE_StructGrid bHYPRE_StructGrid__wrapObj(void* data, sidl_BaseInterface* _ex) { return (*(_getExternals()->createObject))(data,_ex); } static bHYPRE_StructGrid bHYPRE_StructGrid__remoteCreate(const char* url, sidl_BaseInterface *_ex); /* * RMI constructor function for the class. */ bHYPRE_StructGrid bHYPRE_StructGrid__createRemote(const char* url, sidl_BaseInterface *_ex) { return bHYPRE_StructGrid__remoteCreate(url, _ex); } static struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__remoteConnect(const char* url, sidl_bool ar, sidl_BaseInterface *_ex); static struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__IHConnect(struct sidl_rmi_InstanceHandle__object* instance, sidl_BaseInterface *_ex); /* * RMI connector function for the class. */ bHYPRE_StructGrid bHYPRE_StructGrid__connect(const char* url, sidl_BaseInterface *_ex) { return bHYPRE_StructGrid__remoteConnect(url, TRUE, _ex); } /* * This function is the preferred way to create a Struct Grid. */ bHYPRE_StructGrid bHYPRE_StructGrid_Create( /* in */ bHYPRE_MPICommunicator mpi_comm, /* in */ int32_t dim, /* out */ sidl_BaseInterface *_ex) { bHYPRE_StructGrid _result; _result = (_getSEPV()->f_Create)( mpi_comm, dim, _ex); return _result; } /* * Set the MPI Communicator. * DEPRECATED, use Create: */ SIDL_C_INLINE_DEFN int32_t bHYPRE_StructGrid_SetCommunicator( /* in */ bHYPRE_StructGrid self, /* in */ bHYPRE_MPICommunicator mpi_comm, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { int32_t _result; _result = (*self->d_epv->f_SetCommunicator)( self, mpi_comm, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * The Destroy function doesn't necessarily destroy anything. * It is just another name for deleteRef. Thus it decrements the * object's reference count. The Babel memory management system will * destroy the object if the reference count goes to zero. */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid_Destroy( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f_Destroy)( self, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Method: SetDimension[] */ SIDL_C_INLINE_DEFN int32_t bHYPRE_StructGrid_SetDimension( /* in */ bHYPRE_StructGrid self, /* in */ int32_t dim, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { int32_t _result; _result = (*self->d_epv->f_SetDimension)( self, dim, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Define the lower and upper corners of a box of the grid. * "ilower" and "iupper" are arrays of size "dim", the number of spatial * dimensions. */ int32_t bHYPRE_StructGrid_SetExtents( /* in */ bHYPRE_StructGrid self, /* in rarray[dim] */ int32_t* ilower, /* in rarray[dim] */ int32_t* iupper, /* in */ int32_t dim, /* out */ sidl_BaseInterface *_ex) { int32_t _result; int32_t ilower_lower[1], ilower_upper[1], ilower_stride[1]; struct sidl_int__array ilower_real; struct sidl_int__array*ilower_tmp = &ilower_real; int32_t iupper_lower[1], iupper_upper[1], iupper_stride[1]; struct sidl_int__array iupper_real; struct sidl_int__array*iupper_tmp = &iupper_real; ilower_upper[0] = dim-1; sidl_int__array_init(ilower, ilower_tmp, 1, ilower_lower, ilower_upper, ilower_stride); iupper_upper[0] = dim-1; sidl_int__array_init(iupper, iupper_tmp, 1, iupper_lower, iupper_upper, iupper_stride); _result = (*self->d_epv->f_SetExtents)( self, ilower_tmp, iupper_tmp, _ex); #ifdef SIDL_DEBUG_REFCOUNT sidl__array_deleteRef((struct sidl__array*)ilower_tmp); sidl__array_deleteRef((struct sidl__array*)iupper_tmp); #endif /* SIDL_DEBUG_REFCOUNT */ return _result; } /* * Set the periodicity for the grid. Default is no periodicity. * * The argument {\tt periodic} is an {\tt dim}-dimensional integer array that * contains the periodicity for each dimension. A zero value for a dimension * means non-periodic, while a nonzero value means periodic and contains the * actual period. For example, periodicity in the first and third dimensions * for a 10x11x12 grid is indicated by the array [10,0,12]. * * NOTE: Some of the solvers in hypre have power-of-two restrictions on the size * of the periodic dimensions. */ SIDL_C_INLINE_DEFN int32_t bHYPRE_StructGrid_SetPeriodic( /* in */ bHYPRE_StructGrid self, /* in rarray[dim] */ int32_t* periodic, /* in */ int32_t dim, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { int32_t _result; int32_t periodic_lower[1], periodic_upper[1], periodic_stride[1]; struct sidl_int__array periodic_real; struct sidl_int__array*periodic_tmp = &periodic_real; periodic_upper[0] = dim-1; sidl_int__array_init(periodic, periodic_tmp, 1, periodic_lower, periodic_upper, periodic_stride); _result = (*self->d_epv->f_SetPeriodic)( self, periodic_tmp, _ex); #ifdef SIDL_DEBUG_REFCOUNT sidl__array_deleteRef((struct sidl__array*)periodic_tmp); #endif /* SIDL_DEBUG_REFCOUNT */ return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Set the number of ghost zones, separately on the lower and upper sides * for each dimension. * "num_ghost" is an array of size "dim2", twice the number of dimensions. */ SIDL_C_INLINE_DEFN int32_t bHYPRE_StructGrid_SetNumGhost( /* in */ bHYPRE_StructGrid self, /* in rarray[dim2] */ int32_t* num_ghost, /* in */ int32_t dim2, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { int32_t _result; int32_t num_ghost_lower[1], num_ghost_upper[1], num_ghost_stride[1]; struct sidl_int__array num_ghost_real; struct sidl_int__array*num_ghost_tmp = &num_ghost_real; num_ghost_upper[0] = dim2-1; sidl_int__array_init(num_ghost, num_ghost_tmp, 1, num_ghost_lower, num_ghost_upper, num_ghost_stride); _result = (*self->d_epv->f_SetNumGhost)( self, num_ghost_tmp, _ex); #ifdef SIDL_DEBUG_REFCOUNT sidl__array_deleteRef((struct sidl__array*)num_ghost_tmp); #endif /* SIDL_DEBUG_REFCOUNT */ return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * final construction of the object before its use */ SIDL_C_INLINE_DEFN int32_t bHYPRE_StructGrid_Assemble( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { int32_t _result; _result = (*self->d_epv->f_Assemble)( self, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * <p> * Add one to the intrinsic reference count in the underlying object. * Object in <code>sidl</code> have an intrinsic reference count. * Objects continue to exist as long as the reference count is * positive. Clients should call this method whenever they * create another ongoing reference to an object or interface. * </p> * <p> * This does not have a return value because there is no language * independent type that can refer to an interface or a * class. * </p> */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid_addRef( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f_addRef)( self, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Decrease by one the intrinsic reference count in the underlying * object, and delete the object if the reference is non-positive. * Objects in <code>sidl</code> have an intrinsic reference count. * Clients should call this method whenever they remove a * reference to an object or interface. */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid_deleteRef( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f_deleteRef)( self, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Return true if and only if <code>obj</code> refers to the same * object as this object. */ SIDL_C_INLINE_DEFN sidl_bool bHYPRE_StructGrid_isSame( /* in */ bHYPRE_StructGrid self, /* in */ sidl_BaseInterface iobj, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { sidl_bool _result; _result = (*self->d_epv->f_isSame)( self, iobj, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Return whether this object is an instance of the specified type. * The string name must be the <code>sidl</code> type name. This * routine will return <code>true</code> if and only if a cast to * the string type name would succeed. */ SIDL_C_INLINE_DEFN sidl_bool bHYPRE_StructGrid_isType( /* in */ bHYPRE_StructGrid self, /* in */ const char* name, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { sidl_bool _result; _result = (*self->d_epv->f_isType)( self, name, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Return the meta-data about the class implementing this interface. */ SIDL_C_INLINE_DEFN sidl_ClassInfo bHYPRE_StructGrid_getClassInfo( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { sidl_ClassInfo _result; _result = (*self->d_epv->f_getClassInfo)( self, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Cast method for interface and class type conversions. */ bHYPRE_StructGrid bHYPRE_StructGrid__cast( void* obj, sidl_BaseInterface* _ex) { bHYPRE_StructGrid cast = NULL; if(!connect_loaded) { connect_loaded = 1; sidl_rmi_ConnectRegistry_registerConnect("bHYPRE.StructGrid", ( void*)bHYPRE_StructGrid__IHConnect,_ex);SIDL_CHECK(*_ex); } if (obj != NULL) { sidl_BaseInterface base = (sidl_BaseInterface) obj; cast = (bHYPRE_StructGrid) (*base->d_epv->f__cast)( base->d_object, "bHYPRE.StructGrid", _ex); SIDL_CHECK(*_ex); } EXIT: return cast; } /* * String cast method for interface and class type conversions. */ void* bHYPRE_StructGrid__cast2( void* obj, const char* type, sidl_BaseInterface* _ex) { void* cast = NULL; if (obj != NULL) { sidl_BaseInterface base = (sidl_BaseInterface) obj; cast = (*base->d_epv->f__cast)(base->d_object, type, _ex); SIDL_CHECK(*_ex); } EXIT: return cast; } /* * Select and execute a method by name */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid__exec( /* in */ bHYPRE_StructGrid self, /* in */ const char* methodName, /* in */ sidl_rmi_Call inArgs, /* in */ sidl_rmi_Return outArgs, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f__exec)( self, methodName, inArgs, outArgs, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Get the URL of the Implementation of this object (for RMI) */ SIDL_C_INLINE_DEFN char* bHYPRE_StructGrid__getURL( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { char* _result; _result = (*self->d_epv->f__getURL)( self, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * On a remote object, addrefs the remote instance. */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid__raddRef( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f__raddRef)( self, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * Method to enable/disable static hooks execution. */ void bHYPRE_StructGrid__set_hooks_static( int32_t on, struct sidl_BaseInterface__object **_ex) { (_getSEPV()->f__set_hooks_static)( on, _ex); _resetSEPV(); } /* * Method to set whether or not method hooks should be invoked. */ SIDL_C_INLINE_DEFN void bHYPRE_StructGrid__set_hooks( /* in */ bHYPRE_StructGrid self, /* in */ sidl_bool on, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { (*self->d_epv->f__set_hooks)( self, on, _ex); } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * TRUE if this object is remote, false if local */ SIDL_C_INLINE_DEFN sidl_bool bHYPRE_StructGrid__isRemote( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) #if SIDL_C_INLINE_REPEAT_DEFN { sidl_bool _result; _result = (*self->d_epv->f__isRemote)( self, _ex); return _result; } #else /* ISO C 1999 inline semantics */ ; #endif /* SIDL_C_INLINE_REPEAT_DEFN */ /* * TRUE if this object is remote, false if local */ sidl_bool bHYPRE_StructGrid__isLocal( /* in */ bHYPRE_StructGrid self, /* out */ sidl_BaseInterface *_ex) { return !bHYPRE_StructGrid__isRemote(self,_ex); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_createCol( int32_t dimen, const int32_t lower[], const int32_t upper[]) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_createCol( dimen, lower, upper); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_createRow( int32_t dimen, const int32_t lower[], const int32_t upper[]) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_createRow( dimen, lower, upper); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_create1d(int32_t len) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_create1d(len); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_create1dInit( int32_t len, bHYPRE_StructGrid* data) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_create1dInit( len, (struct sidl_BaseInterface__object **)data); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_create2dCol(int32_t m, int32_t n) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_create2dCol(m, n); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_create2dRow(int32_t m, int32_t n) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_create2dRow(m, n); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_borrow( bHYPRE_StructGrid* firstElement, int32_t dimen, const int32_t lower[], const int32_t upper[], const int32_t stride[]) { return (struct bHYPRE_StructGrid__array*)sidl_interface__array_borrow( (struct sidl_BaseInterface__object **) firstElement, dimen, lower, upper, stride); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_smartCopy( struct bHYPRE_StructGrid__array *array) { return (struct bHYPRE_StructGrid__array*) sidl_interface__array_smartCopy((struct sidl_interface__array *)array); } void bHYPRE_StructGrid__array_addRef( struct bHYPRE_StructGrid__array* array) { sidl_interface__array_addRef((struct sidl_interface__array *)array); } void bHYPRE_StructGrid__array_deleteRef( struct bHYPRE_StructGrid__array* array) { sidl_interface__array_deleteRef((struct sidl_interface__array *)array); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get1( const struct bHYPRE_StructGrid__array* array, const int32_t i1) { return (bHYPRE_StructGrid) sidl_interface__array_get1((const struct sidl_interface__array *)array , i1); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get2( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2) { return (bHYPRE_StructGrid) sidl_interface__array_get2((const struct sidl_interface__array *)array , i1, i2); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get3( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3) { return (bHYPRE_StructGrid) sidl_interface__array_get3((const struct sidl_interface__array *)array , i1, i2, i3); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get4( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4) { return (bHYPRE_StructGrid) sidl_interface__array_get4((const struct sidl_interface__array *)array , i1, i2, i3, i4); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get5( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5) { return (bHYPRE_StructGrid) sidl_interface__array_get5((const struct sidl_interface__array *)array , i1, i2, i3, i4, i5); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get6( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5, const int32_t i6) { return (bHYPRE_StructGrid) sidl_interface__array_get6((const struct sidl_interface__array *)array , i1, i2, i3, i4, i5, i6); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get7( const struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5, const int32_t i6, const int32_t i7) { return (bHYPRE_StructGrid) sidl_interface__array_get7((const struct sidl_interface__array *)array , i1, i2, i3, i4, i5, i6, i7); } bHYPRE_StructGrid bHYPRE_StructGrid__array_get( const struct bHYPRE_StructGrid__array* array, const int32_t indices[]) { return (bHYPRE_StructGrid) sidl_interface__array_get((const struct sidl_interface__array *)array, indices); } void bHYPRE_StructGrid__array_set1( struct bHYPRE_StructGrid__array* array, const int32_t i1, bHYPRE_StructGrid const value) { sidl_interface__array_set1((struct sidl_interface__array *)array , i1, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set2( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, bHYPRE_StructGrid const value) { sidl_interface__array_set2((struct sidl_interface__array *)array , i1, i2, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set3( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, bHYPRE_StructGrid const value) { sidl_interface__array_set3((struct sidl_interface__array *)array , i1, i2, i3, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set4( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, bHYPRE_StructGrid const value) { sidl_interface__array_set4((struct sidl_interface__array *)array , i1, i2, i3, i4, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set5( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5, bHYPRE_StructGrid const value) { sidl_interface__array_set5((struct sidl_interface__array *)array , i1, i2, i3, i4, i5, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set6( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5, const int32_t i6, bHYPRE_StructGrid const value) { sidl_interface__array_set6((struct sidl_interface__array *)array , i1, i2, i3, i4, i5, i6, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set7( struct bHYPRE_StructGrid__array* array, const int32_t i1, const int32_t i2, const int32_t i3, const int32_t i4, const int32_t i5, const int32_t i6, const int32_t i7, bHYPRE_StructGrid const value) { sidl_interface__array_set7((struct sidl_interface__array *)array , i1, i2, i3, i4, i5, i6, i7, (struct sidl_BaseInterface__object *)value); } void bHYPRE_StructGrid__array_set( struct bHYPRE_StructGrid__array* array, const int32_t indices[], bHYPRE_StructGrid const value) { sidl_interface__array_set((struct sidl_interface__array *)array, indices, ( struct sidl_BaseInterface__object *)value); } int32_t bHYPRE_StructGrid__array_dimen( const struct bHYPRE_StructGrid__array* array) { return sidl_interface__array_dimen((struct sidl_interface__array *)array); } int32_t bHYPRE_StructGrid__array_lower( const struct bHYPRE_StructGrid__array* array, const int32_t ind) { return sidl_interface__array_lower((struct sidl_interface__array *)array, ind); } int32_t bHYPRE_StructGrid__array_upper( const struct bHYPRE_StructGrid__array* array, const int32_t ind) { return sidl_interface__array_upper((struct sidl_interface__array *)array, ind); } int32_t bHYPRE_StructGrid__array_length( const struct bHYPRE_StructGrid__array* array, const int32_t ind) { return sidl_interface__array_length((struct sidl_interface__array *)array, ind); } int32_t bHYPRE_StructGrid__array_stride( const struct bHYPRE_StructGrid__array* array, const int32_t ind) { return sidl_interface__array_stride((struct sidl_interface__array *)array, ind); } int bHYPRE_StructGrid__array_isColumnOrder( const struct bHYPRE_StructGrid__array* array) { return sidl_interface__array_isColumnOrder((struct sidl_interface__array *)array); } int bHYPRE_StructGrid__array_isRowOrder( const struct bHYPRE_StructGrid__array* array) { return sidl_interface__array_isRowOrder((struct sidl_interface__array *)array); } void bHYPRE_StructGrid__array_copy( const struct bHYPRE_StructGrid__array* src, struct bHYPRE_StructGrid__array* dest) { sidl_interface__array_copy((const struct sidl_interface__array *)src, (struct sidl_interface__array *)dest); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_slice( struct bHYPRE_StructGrid__array* src, int32_t dimen, const int32_t numElem[], const int32_t *srcStart, const int32_t *srcStride, const int32_t *newStart) { return (struct bHYPRE_StructGrid__array*) sidl_interface__array_slice((struct sidl_interface__array *)src, dimen, numElem, srcStart, srcStride, newStart); } struct bHYPRE_StructGrid__array* bHYPRE_StructGrid__array_ensure( struct bHYPRE_StructGrid__array* src, int32_t dimen, int ordering) { return (struct bHYPRE_StructGrid__array*) sidl_interface__array_ensure((struct sidl_interface__array *)src, dimen, ordering); } #include <stdlib.h> #include <string.h> #ifndef included_sidl_BaseClass_h #include "sidl_BaseClass.h" #endif #ifndef included_sidl_ClassInfo_h #include "sidl_ClassInfo.h" #endif #ifndef included_sidl_rmi_ProtocolFactory_h #include "sidl_rmi_ProtocolFactory.h" #endif #ifndef included_sidl_rmi_InstanceRegistry_h #include "sidl_rmi_InstanceRegistry.h" #endif #ifndef included_sidl_rmi_InstanceHandle_h #include "sidl_rmi_InstanceHandle.h" #endif #ifndef included_sidl_rmi_Invocation_h #include "sidl_rmi_Invocation.h" #endif #ifndef included_sidl_rmi_Response_h #include "sidl_rmi_Response.h" #endif #ifndef included_sidl_rmi_ServerRegistry_h #include "sidl_rmi_ServerRegistry.h" #endif #ifndef included_sidl_rmi_ConnectRegistry_h #include "sidl_rmi_ConnectRegistry.h" #endif #ifndef included_sidl_io_Serializable_h #include "sidl_io_Serializable.h" #endif #include "sidl_Exception.h" #ifndef NULL #define NULL 0 #endif #include "sidl_thread.h" #ifdef HAVE_PTHREAD static struct sidl_recursive_mutex_t bHYPRE_StructGrid__mutex= SIDL_RECURSIVE_MUTEX_INITIALIZER; #define LOCK_STATIC_GLOBALS sidl_recursive_mutex_lock( &bHYPRE_StructGrid__mutex ) #define UNLOCK_STATIC_GLOBALS sidl_recursive_mutex_unlock( &bHYPRE_StructGrid__mutex ) /* #define HAVE_LOCKED_STATIC_GLOBALS (sidl_recursive_mutex_trylock( &bHYPRE_StructGrid__mutex )==EDEADLOCK) */ #else #define LOCK_STATIC_GLOBALS #define UNLOCK_STATIC_GLOBALS /* #define HAVE_LOCKED_STATIC_GLOBALS (1) */ #endif /* Static variables to hold version of IOR */ static const int32_t s_IOR_MAJOR_VERSION = 1; static const int32_t s_IOR_MINOR_VERSION = 0; /* Static variables for managing EPV initialization. */ static int s_remote_initialized = 0; static struct bHYPRE_StructGrid__epv s_rem_epv__bhypre_structgrid; static struct sidl_BaseClass__epv s_rem_epv__sidl_baseclass; static struct sidl_BaseInterface__epv s_rem_epv__sidl_baseinterface; /* REMOTE CAST: dynamic type casting for remote objects. */ static void* remote_bHYPRE_StructGrid__cast( struct bHYPRE_StructGrid__object* self, const char* name, sidl_BaseInterface* _ex) { int cmp0, cmp1; void* cast = NULL; *_ex = NULL; /* default to no exception */ cmp0 = strcmp(name, "sidl.BaseClass"); if (!cmp0) { (*self->d_epv->f_addRef)(self, _ex); SIDL_CHECK(*_ex); cast = ((struct sidl_BaseClass__object*)self); return cast; } else if (cmp0 < 0) { cmp1 = strcmp(name, "bHYPRE.StructGrid"); if (!cmp1) { (*self->d_epv->f_addRef)(self, _ex); SIDL_CHECK(*_ex); cast = ((struct bHYPRE_StructGrid__object*)self); return cast; } } else if (cmp0 > 0) { cmp1 = strcmp(name, "sidl.BaseInterface"); if (!cmp1) { (*self->d_epv->f_addRef)(self, _ex); SIDL_CHECK(*_ex); cast = &((*self).d_sidl_baseclass.d_sidl_baseinterface); return cast; } } if ((*self->d_epv->f_isType)(self,name, _ex)) { void* (*func)(struct sidl_rmi_InstanceHandle__object*, struct sidl_BaseInterface__object**) = (void* (*)(struct sidl_rmi_InstanceHandle__object*, struct sidl_BaseInterface__object**)) sidl_rmi_ConnectRegistry_getConnect(name, _ex);SIDL_CHECK(*_ex); cast = (*func)(((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih, _ex); } return cast; EXIT: return NULL; } /* REMOTE DELETE: call the remote destructor for the object. */ static void remote_bHYPRE_StructGrid__delete( struct bHYPRE_StructGrid__object* self, sidl_BaseInterface* _ex) { *_ex = NULL; free((void*) self); } /* REMOTE GETURL: call the getURL function for the object. */ static char* remote_bHYPRE_StructGrid__getURL( struct bHYPRE_StructGrid__object* self, sidl_BaseInterface* _ex) { struct sidl_rmi_InstanceHandle__object *conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; *_ex = NULL; if(conn != NULL) { return sidl_rmi_InstanceHandle_getObjectURL(conn, _ex); } return NULL; } /* REMOTE ADDREF: For internal babel use only! Remote addRef. */ static void remote_bHYPRE_StructGrid__raddRef( struct bHYPRE_StructGrid__object* self,sidl_BaseInterface* _ex) { sidl_BaseException netex = NULL; /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; struct sidl_rmi_InstanceHandle__object *_conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Response _rsvp = NULL; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "addRef", _ex ); SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv,_ex);SIDL_CHECK(*_ex); /* Check for exceptions */ netex = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex); if(netex != NULL) { sidl_BaseInterface throwaway_exception = NULL; *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(netex, &throwaway_exception); return; } /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv,&_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp,&_throwaway); } return; } /* REMOTE ISREMOTE: returns true if this object is Remote (it is). */ static sidl_bool remote_bHYPRE_StructGrid__isRemote( struct bHYPRE_StructGrid__object* self, sidl_BaseInterface *_ex) { *_ex = NULL; return TRUE; } /* REMOTE METHOD STUB:_set_hooks */ static void remote_bHYPRE_StructGrid__set_hooks( /* in */ struct bHYPRE_StructGrid__object* self , /* in */ sidl_bool on, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "_set_hooks", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packBool( _inv, "on", on, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid._set_hooks.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return; } } /* REMOTE EXEC: call the exec function for the object. */ static void remote_bHYPRE_StructGrid__exec( struct bHYPRE_StructGrid__object* self,const char* methodName, sidl_rmi_Call inArgs, sidl_rmi_Return outArgs, sidl_BaseInterface* _ex) { *_ex = NULL; } /* REMOTE METHOD STUB:SetCommunicator */ static int32_t remote_bHYPRE_StructGrid_SetCommunicator( /* in */ struct bHYPRE_StructGrid__object* self , /* in */ struct bHYPRE_MPICommunicator__object* mpi_comm, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "SetCommunicator", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ if(mpi_comm){ char* _url = sidl_BaseInterface__getURL((sidl_BaseInterface)mpi_comm, _ex);SIDL_CHECK(*_ex); sidl_rmi_Invocation_packString( _inv, "mpi_comm", _url, _ex);SIDL_CHECK( *_ex); free((void*)_url); } else { sidl_rmi_Invocation_packString( _inv, "mpi_comm", NULL, _ex);SIDL_CHECK( *_ex); } /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.SetCommunicator.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:Destroy */ static void remote_bHYPRE_StructGrid_Destroy( /* in */ struct bHYPRE_StructGrid__object* self , /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "Destroy", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.Destroy.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return; } } /* REMOTE METHOD STUB:SetDimension */ static int32_t remote_bHYPRE_StructGrid_SetDimension( /* in */ struct bHYPRE_StructGrid__object* self , /* in */ int32_t dim, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "SetDimension", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packInt( _inv, "dim", dim, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.SetDimension.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:SetExtents */ static int32_t remote_bHYPRE_StructGrid_SetExtents( /* in */ struct bHYPRE_StructGrid__object* self , /* in rarray[dim] */ struct sidl_int__array* ilower, /* in rarray[dim] */ struct sidl_int__array* iupper, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "SetExtents", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packIntArray( _inv, "ilower", ilower, sidl_column_major_order,1,0, _ex);SIDL_CHECK(*_ex); sidl_rmi_Invocation_packIntArray( _inv, "iupper", iupper, sidl_column_major_order,1,0, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.SetExtents.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:SetPeriodic */ static int32_t remote_bHYPRE_StructGrid_SetPeriodic( /* in */ struct bHYPRE_StructGrid__object* self , /* in rarray[dim] */ struct sidl_int__array* periodic, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "SetPeriodic", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packIntArray( _inv, "periodic", periodic, sidl_column_major_order,1,0, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.SetPeriodic.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:SetNumGhost */ static int32_t remote_bHYPRE_StructGrid_SetNumGhost( /* in */ struct bHYPRE_StructGrid__object* self , /* in rarray[dim2] */ struct sidl_int__array* num_ghost, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "SetNumGhost", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packIntArray( _inv, "num_ghost", num_ghost, sidl_column_major_order,1,0, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.SetNumGhost.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:Assemble */ static int32_t remote_bHYPRE_StructGrid_Assemble( /* in */ struct bHYPRE_StructGrid__object* self , /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; int32_t _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "Assemble", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.Assemble.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackInt( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:addRef */ static void remote_bHYPRE_StructGrid_addRef( /* in */ struct bHYPRE_StructGrid__object* self , /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { struct bHYPRE_StructGrid__remote* r_obj = (struct bHYPRE_StructGrid__remote*)self->d_data; LOCK_STATIC_GLOBALS; r_obj->d_refcount++; UNLOCK_STATIC_GLOBALS; } } /* REMOTE METHOD STUB:deleteRef */ static void remote_bHYPRE_StructGrid_deleteRef( /* in */ struct bHYPRE_StructGrid__object* self , /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { struct bHYPRE_StructGrid__remote* r_obj = (struct bHYPRE_StructGrid__remote*)self->d_data; LOCK_STATIC_GLOBALS; r_obj->d_refcount--; if(r_obj->d_refcount == 0) { sidl_rmi_InstanceHandle_deleteRef(r_obj->d_ih, _ex); free(r_obj); free(self); } UNLOCK_STATIC_GLOBALS; } } /* REMOTE METHOD STUB:isSame */ static sidl_bool remote_bHYPRE_StructGrid_isSame( /* in */ struct bHYPRE_StructGrid__object* self , /* in */ struct sidl_BaseInterface__object* iobj, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; sidl_bool _retval = FALSE; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "isSame", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ if(iobj){ char* _url = sidl_BaseInterface__getURL((sidl_BaseInterface)iobj, _ex);SIDL_CHECK(*_ex); sidl_rmi_Invocation_packString( _inv, "iobj", _url, _ex);SIDL_CHECK(*_ex); free((void*)_url); } else { sidl_rmi_Invocation_packString( _inv, "iobj", NULL, _ex);SIDL_CHECK(*_ex); } /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.isSame.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackBool( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:isType */ static sidl_bool remote_bHYPRE_StructGrid_isType( /* in */ struct bHYPRE_StructGrid__object* self , /* in */ const char* name, /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; sidl_bool _retval = FALSE; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "isType", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ sidl_rmi_Invocation_packString( _inv, "name", name, _ex);SIDL_CHECK(*_ex); /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.isType.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackBool( _rsvp, "_retval", &_retval, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE METHOD STUB:getClassInfo */ static struct sidl_ClassInfo__object* remote_bHYPRE_StructGrid_getClassInfo( /* in */ struct bHYPRE_StructGrid__object* self , /* out */ struct sidl_BaseInterface__object* *_ex) { LANG_SPECIFIC_INIT(); *_ex = NULL; { /* initialize a new invocation */ sidl_BaseInterface _throwaway = NULL; sidl_BaseException _be = NULL; sidl_rmi_Response _rsvp = NULL; char*_retval_str = NULL; struct sidl_ClassInfo__object* _retval = 0; struct sidl_rmi_InstanceHandle__object * _conn = ((struct bHYPRE_StructGrid__remote*)self->d_data)->d_ih; sidl_rmi_Invocation _inv = sidl_rmi_InstanceHandle_createInvocation( _conn, "getClassInfo", _ex ); SIDL_CHECK(*_ex); /* pack in and inout arguments */ /* send actual RMI request */ _rsvp = sidl_rmi_Invocation_invokeMethod(_inv, _ex);SIDL_CHECK(*_ex); _be = sidl_rmi_Response_getExceptionThrown(_rsvp, _ex);SIDL_CHECK(*_ex); if(_be != NULL) { sidl_BaseInterface throwaway_exception = NULL; sidl_BaseException_addLine(_be, "Exception unserialized from bHYPRE.StructGrid.getClassInfo.", &throwaway_exception); *_ex = (sidl_BaseInterface) sidl_BaseInterface__rmicast(_be, &throwaway_exception); goto EXIT; } /* extract return value */ sidl_rmi_Response_unpackString( _rsvp, "_retval", &_retval_str, _ex);SIDL_CHECK(*_ex); _retval = sidl_ClassInfo__connectI(_retval_str, FALSE, _ex);SIDL_CHECK( *_ex); /* unpack out and inout arguments */ /* cleanup and return */ EXIT: if(_inv) { sidl_rmi_Invocation_deleteRef(_inv, &_throwaway); } if(_rsvp) { sidl_rmi_Response_deleteRef(_rsvp, &_throwaway); } return _retval; } } /* REMOTE EPV: create remote entry point vectors (EPVs). */ static void bHYPRE_StructGrid__init_remote_epv(void) { /* assert( HAVE_LOCKED_STATIC_GLOBALS ); */ struct bHYPRE_StructGrid__epv* epv = &s_rem_epv__bhypre_structgrid; struct sidl_BaseClass__epv* e0 = &s_rem_epv__sidl_baseclass; struct sidl_BaseInterface__epv* e1 = &s_rem_epv__sidl_baseinterface; epv->f__cast = remote_bHYPRE_StructGrid__cast; epv->f__delete = remote_bHYPRE_StructGrid__delete; epv->f__exec = remote_bHYPRE_StructGrid__exec; epv->f__getURL = remote_bHYPRE_StructGrid__getURL; epv->f__raddRef = remote_bHYPRE_StructGrid__raddRef; epv->f__isRemote = remote_bHYPRE_StructGrid__isRemote; epv->f__set_hooks = remote_bHYPRE_StructGrid__set_hooks; epv->f__ctor = NULL; epv->f__ctor2 = NULL; epv->f__dtor = NULL; epv->f_SetCommunicator = remote_bHYPRE_StructGrid_SetCommunicator; epv->f_Destroy = remote_bHYPRE_StructGrid_Destroy; epv->f_SetDimension = remote_bHYPRE_StructGrid_SetDimension; epv->f_SetExtents = remote_bHYPRE_StructGrid_SetExtents; epv->f_SetPeriodic = remote_bHYPRE_StructGrid_SetPeriodic; epv->f_SetNumGhost = remote_bHYPRE_StructGrid_SetNumGhost; epv->f_Assemble = remote_bHYPRE_StructGrid_Assemble; epv->f_addRef = remote_bHYPRE_StructGrid_addRef; epv->f_deleteRef = remote_bHYPRE_StructGrid_deleteRef; epv->f_isSame = remote_bHYPRE_StructGrid_isSame; epv->f_isType = remote_bHYPRE_StructGrid_isType; epv->f_getClassInfo = remote_bHYPRE_StructGrid_getClassInfo; e0->f__cast = (void* (*)(struct sidl_BaseClass__object*,const char*, sidl_BaseInterface*)) epv->f__cast; e0->f__delete = (void (*)(struct sidl_BaseClass__object*, sidl_BaseInterface*)) epv->f__delete; e0->f__getURL = (char* (*)(struct sidl_BaseClass__object*, sidl_BaseInterface*)) epv->f__getURL; e0->f__raddRef = (void (*)(struct sidl_BaseClass__object*, sidl_BaseInterface*)) epv->f__raddRef; e0->f__isRemote = (sidl_bool (*)(struct sidl_BaseClass__object*, sidl_BaseInterface*)) epv->f__isRemote; e0->f__set_hooks = (void (*)(struct sidl_BaseClass__object*,int32_t, sidl_BaseInterface*)) epv->f__set_hooks; e0->f__exec = (void (*)(struct sidl_BaseClass__object*,const char*, struct sidl_rmi_Call__object*,struct sidl_rmi_Return__object*,struct sidl_BaseInterface__object **)) epv->f__exec; e0->f_addRef = (void (*)(struct sidl_BaseClass__object*,struct sidl_BaseInterface__object **)) epv->f_addRef; e0->f_deleteRef = (void (*)(struct sidl_BaseClass__object*,struct sidl_BaseInterface__object **)) epv->f_deleteRef; e0->f_isSame = (sidl_bool (*)(struct sidl_BaseClass__object*,struct sidl_BaseInterface__object*,struct sidl_BaseInterface__object **)) epv->f_isSame; e0->f_isType = (sidl_bool (*)(struct sidl_BaseClass__object*,const char*,struct sidl_BaseInterface__object **)) epv->f_isType; e0->f_getClassInfo = (struct sidl_ClassInfo__object* (*)(struct sidl_BaseClass__object*,struct sidl_BaseInterface__object **)) epv->f_getClassInfo; e1->f__cast = (void* (*)(void*,const char*,sidl_BaseInterface*)) epv->f__cast; e1->f__delete = (void (*)(void*,sidl_BaseInterface*)) epv->f__delete; e1->f__getURL = (char* (*)(void*,sidl_BaseInterface*)) epv->f__getURL; e1->f__raddRef = (void (*)(void*,sidl_BaseInterface*)) epv->f__raddRef; e1->f__isRemote = (sidl_bool (*)(void*,sidl_BaseInterface*)) epv->f__isRemote; e1->f__set_hooks = (void (*)(void*,int32_t, sidl_BaseInterface*)) epv->f__set_hooks; e1->f__exec = (void (*)(void*,const char*,struct sidl_rmi_Call__object*,struct sidl_rmi_Return__object*,struct sidl_BaseInterface__object **)) epv->f__exec; e1->f_addRef = (void (*)(void*,struct sidl_BaseInterface__object **)) epv->f_addRef; e1->f_deleteRef = (void (*)(void*,struct sidl_BaseInterface__object **)) epv->f_deleteRef; e1->f_isSame = (sidl_bool (*)(void*,struct sidl_BaseInterface__object*, struct sidl_BaseInterface__object **)) epv->f_isSame; e1->f_isType = (sidl_bool (*)(void*,const char*,struct sidl_BaseInterface__object **)) epv->f_isType; e1->f_getClassInfo = (struct sidl_ClassInfo__object* (*)(void*,struct sidl_BaseInterface__object **)) epv->f_getClassInfo; s_remote_initialized = 1; } /* Create an instance that connects to an existing remote object. */ static struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__remoteConnect(const char *url, sidl_bool ar, sidl_BaseInterface *_ex) { struct bHYPRE_StructGrid__object* self; struct bHYPRE_StructGrid__object* s0; struct sidl_BaseClass__object* s1; struct bHYPRE_StructGrid__remote* r_obj; sidl_rmi_InstanceHandle instance = NULL; char* objectID = NULL; objectID = NULL; *_ex = NULL; if(url == NULL) {return NULL;} objectID = sidl_rmi_ServerRegistry_isLocalObject(url, _ex); if(objectID) { sidl_BaseInterface bi = ( sidl_BaseInterface)sidl_rmi_InstanceRegistry_getInstanceByString(objectID, _ex); SIDL_CHECK(*_ex); return bHYPRE_StructGrid__rmicast(bi,_ex);SIDL_CHECK(*_ex); } instance = sidl_rmi_ProtocolFactory_connectInstance(url, ar, _ex ); SIDL_CHECK(*_ex); if ( instance == NULL) { return NULL; } self = (struct bHYPRE_StructGrid__object*) malloc( sizeof(struct bHYPRE_StructGrid__object)); r_obj = (struct bHYPRE_StructGrid__remote*) malloc( sizeof(struct bHYPRE_StructGrid__remote)); r_obj->d_refcount = 1; r_obj->d_ih = instance; s0 = self; s1 = &s0->d_sidl_baseclass; LOCK_STATIC_GLOBALS; if (!s_remote_initialized) { bHYPRE_StructGrid__init_remote_epv(); } UNLOCK_STATIC_GLOBALS; s1->d_sidl_baseinterface.d_epv = &s_rem_epv__sidl_baseinterface; s1->d_sidl_baseinterface.d_object = (void*) self; s1->d_data = (void*) r_obj; s1->d_epv = &s_rem_epv__sidl_baseclass; s0->d_data = (void*) r_obj; s0->d_epv = &s_rem_epv__bhypre_structgrid; self->d_data = (void*) r_obj; return self; EXIT: return NULL; } /* Create an instance that uses an already existing */ /* InstanceHandle to connect to an existing remote object. */ static struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__IHConnect(sidl_rmi_InstanceHandle instance, sidl_BaseInterface *_ex) { struct bHYPRE_StructGrid__object* self; struct bHYPRE_StructGrid__object* s0; struct sidl_BaseClass__object* s1; struct bHYPRE_StructGrid__remote* r_obj; self = (struct bHYPRE_StructGrid__object*) malloc( sizeof(struct bHYPRE_StructGrid__object)); r_obj = (struct bHYPRE_StructGrid__remote*) malloc( sizeof(struct bHYPRE_StructGrid__remote)); r_obj->d_refcount = 1; r_obj->d_ih = instance; s0 = self; s1 = &s0->d_sidl_baseclass; LOCK_STATIC_GLOBALS; if (!s_remote_initialized) { bHYPRE_StructGrid__init_remote_epv(); } UNLOCK_STATIC_GLOBALS; s1->d_sidl_baseinterface.d_epv = &s_rem_epv__sidl_baseinterface; s1->d_sidl_baseinterface.d_object = (void*) self; s1->d_data = (void*) r_obj; s1->d_epv = &s_rem_epv__sidl_baseclass; s0->d_data = (void*) r_obj; s0->d_epv = &s_rem_epv__bhypre_structgrid; self->d_data = (void*) r_obj; sidl_rmi_InstanceHandle_addRef(instance,_ex);SIDL_CHECK(*_ex); return self; EXIT: return NULL; } /* REMOTE: generate remote instance given URL string. */ static struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__remoteCreate(const char *url, sidl_BaseInterface *_ex) { sidl_BaseInterface _throwaway_exception = NULL; struct bHYPRE_StructGrid__object* self; struct bHYPRE_StructGrid__object* s0; struct sidl_BaseClass__object* s1; struct bHYPRE_StructGrid__remote* r_obj; sidl_rmi_InstanceHandle instance = sidl_rmi_ProtocolFactory_createInstance( url, "bHYPRE.StructGrid", _ex ); SIDL_CHECK(*_ex); if ( instance == NULL) { return NULL; } self = (struct bHYPRE_StructGrid__object*) malloc( sizeof(struct bHYPRE_StructGrid__object)); r_obj = (struct bHYPRE_StructGrid__remote*) malloc( sizeof(struct bHYPRE_StructGrid__remote)); r_obj->d_refcount = 1; r_obj->d_ih = instance; s0 = self; s1 = &s0->d_sidl_baseclass; LOCK_STATIC_GLOBALS; if (!s_remote_initialized) { bHYPRE_StructGrid__init_remote_epv(); } UNLOCK_STATIC_GLOBALS; s1->d_sidl_baseinterface.d_epv = &s_rem_epv__sidl_baseinterface; s1->d_sidl_baseinterface.d_object = (void*) self; s1->d_data = (void*) r_obj; s1->d_epv = &s_rem_epv__sidl_baseclass; s0->d_data = (void*) r_obj; s0->d_epv = &s_rem_epv__bhypre_structgrid; self->d_data = (void*) r_obj; return self; EXIT: if(instance) { sidl_rmi_InstanceHandle_deleteRef(instance, &_throwaway_exception); } return NULL; } /* * Cast method for interface and class type conversions. */ struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__rmicast( void* obj, sidl_BaseInterface* _ex) { struct bHYPRE_StructGrid__object* cast = NULL; *_ex = NULL; if(!connect_loaded) { sidl_rmi_ConnectRegistry_registerConnect("bHYPRE.StructGrid", ( void*)bHYPRE_StructGrid__IHConnect, _ex); connect_loaded = 1; } if (obj != NULL) { struct sidl_BaseInterface__object* base = (struct sidl_BaseInterface__object*) obj; cast = (struct bHYPRE_StructGrid__object*) (*base->d_epv->f__cast)( base->d_object, "bHYPRE.StructGrid", _ex); SIDL_CHECK(*_ex); } return cast; EXIT: return NULL; } /* * RMI connector function for the class. */ struct bHYPRE_StructGrid__object* bHYPRE_StructGrid__connectI(const char* url, sidl_bool ar, struct sidl_BaseInterface__object **_ex) { return bHYPRE_StructGrid__remoteConnect(url, ar, _ex); }
495199.c
/**********************************************************************/ /* ____ ____ */ /* / /\/ / */ /* /___/ \ / */ /* \ \ \/ */ /* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ /* / / All Right Reserved. */ /* /---/ /\ */ /* \ \ / \ */ /* \___\/\___\ */ /***********************************************************************/ /* This file is designed for use with ISim build 0xc3576ebc */ #define XSI_HIDE_SYMBOL_SPEC true #include "xsi.h" #include <memory.h> #ifdef __GNUC__ #include <stdlib.h> #else #include <malloc.h> #define alloca _alloca #endif static void Gate_8735_0(char *t0) { char *t1; char *t2; char *t3; char *t4; char *t5; char *t6; char *t7; char *t8; char *t9; char *t10; char *t11; char *t12; char *t13; char *t14; char *t15; double t16; double t17; LAB0: t1 = (t0 + 2824U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: t2 = (t0 + 1344U); t3 = *((char **)t2); t2 = (t0 + 1504U); t4 = *((char **)t2); t2 = (t0 + 3488); t5 = (t2 + 56U); t6 = *((char **)t5); t7 = (t6 + 56U); t8 = *((char **)t7); t9 = (t0 + 1304U); xsi_vlog_nmosSwitch_new(t8, t9, 0, 0, t4); t10 = (t0 + 3488); t11 = (t10 + 56U); t12 = (t0 + 1304U); xsi_vlog_switch_set_trans_strength(*((char **)t11), t12, 0, 0, 0); t13 = (t0 + 3488); t14 = (t0 + 472); t15 = *((char **)t14); t16 = xsi_vlog_convert_to_real(t15, 32, 1); t17 = (t16 < 0.00000000000000000); if (t17 == 1) goto LAB4; LAB5: t16 = (t16 + 0.50000000000000000); t16 = ((int64)(t16)); LAB6: t16 = (t16 * 1.0000000000000000); xsi_driver_vfirst_trans_bufif_delayed(t13, 0, 0, t16, 0); t14 = (t0 + 3392); *((int *)t14) = 1; LAB1: return; LAB4: t16 = 0.00000000000000000; goto LAB6; } static void Gate_8736_1(char *t0) { char *t1; char *t2; char *t3; char *t4; char *t5; char *t6; char *t7; char *t8; char *t9; char *t10; char *t11; char *t12; char *t13; char *t14; char *t15; double t16; double t17; LAB0: t1 = (t0 + 3072U); t2 = *((char **)t1); if (t2 == 0) goto LAB2; LAB3: goto *t2; LAB2: t2 = (t0 + 1344U); t3 = *((char **)t2); t2 = (t0 + 1664U); t4 = *((char **)t2); t2 = (t0 + 3552); t5 = (t2 + 56U); t6 = *((char **)t5); t7 = (t6 + 56U); t8 = *((char **)t7); t9 = (t0 + 1304U); xsi_vlog_pmosSwitch_new(t8, t9, 0, 0, t4); t10 = (t0 + 3552); t11 = (t10 + 56U); t12 = (t0 + 1304U); xsi_vlog_switch_set_trans_strength(*((char **)t11), t12, 0, 0, 0); t13 = (t0 + 3552); t14 = (t0 + 472); t15 = *((char **)t14); t16 = xsi_vlog_convert_to_real(t15, 32, 1); t17 = (t16 < 0.00000000000000000); if (t17 == 1) goto LAB4; LAB5: t16 = (t16 + 0.50000000000000000); t16 = ((int64)(t16)); LAB6: t16 = (t16 * 1.0000000000000000); xsi_driver_vfirst_trans_bufif_delayed(t13, 0, 0, t16, 0); t14 = (t0 + 3408); *((int *)t14) = 1; LAB1: return; LAB4: t16 = 0.00000000000000000; goto LAB6; } extern void secureip_m_00000000001584608696_3015407066_init() { static char *pe[] = {(void *)Gate_8735_0,(void *)Gate_8736_1}; xsi_register_didat("secureip_m_00000000001584608696_3015407066", "isim/demo_tb.exe.sim/secureip/m_00000000001584608696_3015407066.didat"); xsi_register_executes(pe); }