repo_name
string
path
string
copies
string
size
string
content
string
license
string
DaTwo/cleanflight
lib/main/STM32F10x_StdPeriph_Driver/src/stm32f10x_spi.c
528
29316
/** ****************************************************************************** * @file stm32f10x_spi.c * @author MCD Application Team * @version V3.5.0 * @date 11-March-2011 * @brief This file provides all the SPI firmware functions. ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f10x_spi.h" #include "stm32f10x_rcc.h" /** @addtogroup STM32F10x_StdPeriph_Driver * @{ */ /** @defgroup SPI * @brief SPI driver modules * @{ */ /** @defgroup SPI_Private_TypesDefinitions * @{ */ /** * @} */ /** @defgroup SPI_Private_Defines * @{ */ /* SPI SPE mask */ #define CR1_SPE_Set ((uint16_t)0x0040) #define CR1_SPE_Reset ((uint16_t)0xFFBF) /* I2S I2SE mask */ #define I2SCFGR_I2SE_Set ((uint16_t)0x0400) #define I2SCFGR_I2SE_Reset ((uint16_t)0xFBFF) /* SPI CRCNext mask */ #define CR1_CRCNext_Set ((uint16_t)0x1000) /* SPI CRCEN mask */ #define CR1_CRCEN_Set ((uint16_t)0x2000) #define CR1_CRCEN_Reset ((uint16_t)0xDFFF) /* SPI SSOE mask */ #define CR2_SSOE_Set ((uint16_t)0x0004) #define CR2_SSOE_Reset ((uint16_t)0xFFFB) /* SPI registers Masks */ #define CR1_CLEAR_Mask ((uint16_t)0x3040) #define I2SCFGR_CLEAR_Mask ((uint16_t)0xF040) /* SPI or I2S mode selection masks */ #define SPI_Mode_Select ((uint16_t)0xF7FF) #define I2S_Mode_Select ((uint16_t)0x0800) /* I2S clock source selection masks */ #define I2S2_CLOCK_SRC ((uint32_t)(0x00020000)) #define I2S3_CLOCK_SRC ((uint32_t)(0x00040000)) #define I2S_MUL_MASK ((uint32_t)(0x0000F000)) #define I2S_DIV_MASK ((uint32_t)(0x000000F0)) /** * @} */ /** @defgroup SPI_Private_Macros * @{ */ /** * @} */ /** @defgroup SPI_Private_Variables * @{ */ /** * @} */ /** @defgroup SPI_Private_FunctionPrototypes * @{ */ /** * @} */ /** @defgroup SPI_Private_Functions * @{ */ /** * @brief Deinitializes the SPIx peripheral registers to their default * reset values (Affects also the I2Ss). * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @retval None */ void SPI_I2S_DeInit(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); if (SPIx == SPI1) { /* Enable SPI1 reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE); /* Release SPI1 from reset state */ RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE); } else if (SPIx == SPI2) { /* Enable SPI2 reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); /* Release SPI2 from reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); } else { if (SPIx == SPI3) { /* Enable SPI3 reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, ENABLE); /* Release SPI3 from reset state */ RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, DISABLE); } } } /** * @brief Initializes the SPIx peripheral according to the specified * parameters in the SPI_InitStruct. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param SPI_InitStruct: pointer to a SPI_InitTypeDef structure that * contains the configuration information for the specified SPI peripheral. * @retval None */ void SPI_Init(SPI_TypeDef* SPIx, SPI_InitTypeDef* SPI_InitStruct) { uint16_t tmpreg = 0; /* check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Check the SPI parameters */ assert_param(IS_SPI_DIRECTION_MODE(SPI_InitStruct->SPI_Direction)); assert_param(IS_SPI_MODE(SPI_InitStruct->SPI_Mode)); assert_param(IS_SPI_DATASIZE(SPI_InitStruct->SPI_DataSize)); assert_param(IS_SPI_CPOL(SPI_InitStruct->SPI_CPOL)); assert_param(IS_SPI_CPHA(SPI_InitStruct->SPI_CPHA)); assert_param(IS_SPI_NSS(SPI_InitStruct->SPI_NSS)); assert_param(IS_SPI_BAUDRATE_PRESCALER(SPI_InitStruct->SPI_BaudRatePrescaler)); assert_param(IS_SPI_FIRST_BIT(SPI_InitStruct->SPI_FirstBit)); assert_param(IS_SPI_CRC_POLYNOMIAL(SPI_InitStruct->SPI_CRCPolynomial)); /*---------------------------- SPIx CR1 Configuration ------------------------*/ /* Get the SPIx CR1 value */ tmpreg = SPIx->CR1; /* Clear BIDIMode, BIDIOE, RxONLY, SSM, SSI, LSBFirst, BR, MSTR, CPOL and CPHA bits */ tmpreg &= CR1_CLEAR_Mask; /* Configure SPIx: direction, NSS management, first transmitted bit, BaudRate prescaler master/salve mode, CPOL and CPHA */ /* Set BIDImode, BIDIOE and RxONLY bits according to SPI_Direction value */ /* Set SSM, SSI and MSTR bits according to SPI_Mode and SPI_NSS values */ /* Set LSBFirst bit according to SPI_FirstBit value */ /* Set BR bits according to SPI_BaudRatePrescaler value */ /* Set CPOL bit according to SPI_CPOL value */ /* Set CPHA bit according to SPI_CPHA value */ tmpreg |= (uint16_t)((uint32_t)SPI_InitStruct->SPI_Direction | SPI_InitStruct->SPI_Mode | SPI_InitStruct->SPI_DataSize | SPI_InitStruct->SPI_CPOL | SPI_InitStruct->SPI_CPHA | SPI_InitStruct->SPI_NSS | SPI_InitStruct->SPI_BaudRatePrescaler | SPI_InitStruct->SPI_FirstBit); /* Write to SPIx CR1 */ SPIx->CR1 = tmpreg; /* Activate the SPI mode (Reset I2SMOD bit in I2SCFGR register) */ SPIx->I2SCFGR &= SPI_Mode_Select; /*---------------------------- SPIx CRCPOLY Configuration --------------------*/ /* Write to SPIx CRCPOLY */ SPIx->CRCPR = SPI_InitStruct->SPI_CRCPolynomial; } /** * @brief Initializes the SPIx peripheral according to the specified * parameters in the I2S_InitStruct. * @param SPIx: where x can be 2 or 3 to select the SPI peripheral * (configured in I2S mode). * @param I2S_InitStruct: pointer to an I2S_InitTypeDef structure that * contains the configuration information for the specified SPI peripheral * configured in I2S mode. * @note * The function calculates the optimal prescaler needed to obtain the most * accurate audio frequency (depending on the I2S clock source, the PLL values * and the product configuration). But in case the prescaler value is greater * than 511, the default value (0x02) will be configured instead. * * @retval None */ void I2S_Init(SPI_TypeDef* SPIx, I2S_InitTypeDef* I2S_InitStruct) { uint16_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1; uint32_t tmp = 0; RCC_ClocksTypeDef RCC_Clocks; uint32_t sourceclock = 0; /* Check the I2S parameters */ assert_param(IS_SPI_23_PERIPH(SPIx)); assert_param(IS_I2S_MODE(I2S_InitStruct->I2S_Mode)); assert_param(IS_I2S_STANDARD(I2S_InitStruct->I2S_Standard)); assert_param(IS_I2S_DATA_FORMAT(I2S_InitStruct->I2S_DataFormat)); assert_param(IS_I2S_MCLK_OUTPUT(I2S_InitStruct->I2S_MCLKOutput)); assert_param(IS_I2S_AUDIO_FREQ(I2S_InitStruct->I2S_AudioFreq)); assert_param(IS_I2S_CPOL(I2S_InitStruct->I2S_CPOL)); /*----------------------- SPIx I2SCFGR & I2SPR Configuration -----------------*/ /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ SPIx->I2SCFGR &= I2SCFGR_CLEAR_Mask; SPIx->I2SPR = 0x0002; /* Get the I2SCFGR register value */ tmpreg = SPIx->I2SCFGR; /* If the default value has to be written, reinitialize i2sdiv and i2sodd*/ if(I2S_InitStruct->I2S_AudioFreq == I2S_AudioFreq_Default) { i2sodd = (uint16_t)0; i2sdiv = (uint16_t)2; } /* If the requested audio frequency is not the default, compute the prescaler */ else { /* Check the frame length (For the Prescaler computing) */ if(I2S_InitStruct->I2S_DataFormat == I2S_DataFormat_16b) { /* Packet length is 16 bits */ packetlength = 1; } else { /* Packet length is 32 bits */ packetlength = 2; } /* Get the I2S clock source mask depending on the peripheral number */ if(((uint32_t)SPIx) == SPI2_BASE) { /* The mask is relative to I2S2 */ tmp = I2S2_CLOCK_SRC; } else { /* The mask is relative to I2S3 */ tmp = I2S3_CLOCK_SRC; } /* Check the I2S clock source configuration depending on the Device: Only Connectivity line devices have the PLL3 VCO clock */ #ifdef STM32F10X_CL if((RCC->CFGR2 & tmp) != 0) { /* Get the configuration bits of RCC PLL3 multiplier */ tmp = (uint32_t)((RCC->CFGR2 & I2S_MUL_MASK) >> 12); /* Get the value of the PLL3 multiplier */ if((tmp > 5) && (tmp < 15)) { /* Multiplier is between 8 and 14 (value 15 is forbidden) */ tmp += 2; } else { if (tmp == 15) { /* Multiplier is 20 */ tmp = 20; } } /* Get the PREDIV2 value */ sourceclock = (uint32_t)(((RCC->CFGR2 & I2S_DIV_MASK) >> 4) + 1); /* Calculate the Source Clock frequency based on PLL3 and PREDIV2 values */ sourceclock = (uint32_t) ((HSE_Value / sourceclock) * tmp * 2); } else { /* I2S Clock source is System clock: Get System Clock frequency */ RCC_GetClocksFreq(&RCC_Clocks); /* Get the source clock value: based on System Clock value */ sourceclock = RCC_Clocks.SYSCLK_Frequency; } #else /* STM32F10X_HD */ /* I2S Clock source is System clock: Get System Clock frequency */ RCC_GetClocksFreq(&RCC_Clocks); /* Get the source clock value: based on System Clock value */ sourceclock = RCC_Clocks.SYSCLK_Frequency; #endif /* STM32F10X_CL */ /* Compute the Real divider depending on the MCLK output state with a floating point */ if(I2S_InitStruct->I2S_MCLKOutput == I2S_MCLKOutput_Enable) { /* MCLK output is enabled */ tmp = (uint16_t)(((((sourceclock / 256) * 10) / I2S_InitStruct->I2S_AudioFreq)) + 5); } else { /* MCLK output is disabled */ tmp = (uint16_t)(((((sourceclock / (32 * packetlength)) *10 ) / I2S_InitStruct->I2S_AudioFreq)) + 5); } /* Remove the floating point */ tmp = tmp / 10; /* Check the parity of the divider */ i2sodd = (uint16_t)(tmp & (uint16_t)0x0001); /* Compute the i2sdiv prescaler */ i2sdiv = (uint16_t)((tmp - i2sodd) / 2); /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ i2sodd = (uint16_t) (i2sodd << 8); } /* Test if the divider is 1 or 0 or greater than 0xFF */ if ((i2sdiv < 2) || (i2sdiv > 0xFF)) { /* Set the default values */ i2sdiv = 2; i2sodd = 0; } /* Write to SPIx I2SPR register the computed value */ SPIx->I2SPR = (uint16_t)(i2sdiv | (uint16_t)(i2sodd | (uint16_t)I2S_InitStruct->I2S_MCLKOutput)); /* Configure the I2S with the SPI_InitStruct values */ tmpreg |= (uint16_t)(I2S_Mode_Select | (uint16_t)(I2S_InitStruct->I2S_Mode | \ (uint16_t)(I2S_InitStruct->I2S_Standard | (uint16_t)(I2S_InitStruct->I2S_DataFormat | \ (uint16_t)I2S_InitStruct->I2S_CPOL)))); /* Write to SPIx I2SCFGR */ SPIx->I2SCFGR = tmpreg; } /** * @brief Fills each SPI_InitStruct member with its default value. * @param SPI_InitStruct : pointer to a SPI_InitTypeDef structure which will be initialized. * @retval None */ void SPI_StructInit(SPI_InitTypeDef* SPI_InitStruct) { /*--------------- Reset SPI init structure parameters values -----------------*/ /* Initialize the SPI_Direction member */ SPI_InitStruct->SPI_Direction = SPI_Direction_2Lines_FullDuplex; /* initialize the SPI_Mode member */ SPI_InitStruct->SPI_Mode = SPI_Mode_Slave; /* initialize the SPI_DataSize member */ SPI_InitStruct->SPI_DataSize = SPI_DataSize_8b; /* Initialize the SPI_CPOL member */ SPI_InitStruct->SPI_CPOL = SPI_CPOL_Low; /* Initialize the SPI_CPHA member */ SPI_InitStruct->SPI_CPHA = SPI_CPHA_1Edge; /* Initialize the SPI_NSS member */ SPI_InitStruct->SPI_NSS = SPI_NSS_Hard; /* Initialize the SPI_BaudRatePrescaler member */ SPI_InitStruct->SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_2; /* Initialize the SPI_FirstBit member */ SPI_InitStruct->SPI_FirstBit = SPI_FirstBit_MSB; /* Initialize the SPI_CRCPolynomial member */ SPI_InitStruct->SPI_CRCPolynomial = 7; } /** * @brief Fills each I2S_InitStruct member with its default value. * @param I2S_InitStruct : pointer to a I2S_InitTypeDef structure which will be initialized. * @retval None */ void I2S_StructInit(I2S_InitTypeDef* I2S_InitStruct) { /*--------------- Reset I2S init structure parameters values -----------------*/ /* Initialize the I2S_Mode member */ I2S_InitStruct->I2S_Mode = I2S_Mode_SlaveTx; /* Initialize the I2S_Standard member */ I2S_InitStruct->I2S_Standard = I2S_Standard_Phillips; /* Initialize the I2S_DataFormat member */ I2S_InitStruct->I2S_DataFormat = I2S_DataFormat_16b; /* Initialize the I2S_MCLKOutput member */ I2S_InitStruct->I2S_MCLKOutput = I2S_MCLKOutput_Disable; /* Initialize the I2S_AudioFreq member */ I2S_InitStruct->I2S_AudioFreq = I2S_AudioFreq_Default; /* Initialize the I2S_CPOL member */ I2S_InitStruct->I2S_CPOL = I2S_CPOL_Low; } /** * @brief Enables or disables the specified SPI peripheral. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param NewState: new state of the SPIx peripheral. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_Cmd(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI peripheral */ SPIx->CR1 |= CR1_SPE_Set; } else { /* Disable the selected SPI peripheral */ SPIx->CR1 &= CR1_SPE_Reset; } } /** * @brief Enables or disables the specified SPI peripheral (in I2S mode). * @param SPIx: where x can be 2 or 3 to select the SPI peripheral. * @param NewState: new state of the SPIx peripheral. * This parameter can be: ENABLE or DISABLE. * @retval None */ void I2S_Cmd(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_23_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI peripheral (in I2S mode) */ SPIx->I2SCFGR |= I2SCFGR_I2SE_Set; } else { /* Disable the selected SPI peripheral (in I2S mode) */ SPIx->I2SCFGR &= I2SCFGR_I2SE_Reset; } } /** * @brief Enables or disables the specified SPI/I2S interrupts. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @param SPI_I2S_IT: specifies the SPI/I2S interrupt source to be enabled or disabled. * This parameter can be one of the following values: * @arg SPI_I2S_IT_TXE: Tx buffer empty interrupt mask * @arg SPI_I2S_IT_RXNE: Rx buffer not empty interrupt mask * @arg SPI_I2S_IT_ERR: Error interrupt mask * @param NewState: new state of the specified SPI/I2S interrupt. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_I2S_ITConfig(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT, FunctionalState NewState) { uint16_t itpos = 0, itmask = 0 ; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); assert_param(IS_SPI_I2S_CONFIG_IT(SPI_I2S_IT)); /* Get the SPI/I2S IT index */ itpos = SPI_I2S_IT >> 4; /* Set the IT mask */ itmask = (uint16_t)1 << (uint16_t)itpos; if (NewState != DISABLE) { /* Enable the selected SPI/I2S interrupt */ SPIx->CR2 |= itmask; } else { /* Disable the selected SPI/I2S interrupt */ SPIx->CR2 &= (uint16_t)~itmask; } } /** * @brief Enables or disables the SPIx/I2Sx DMA interface. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @param SPI_I2S_DMAReq: specifies the SPI/I2S DMA transfer request to be enabled or disabled. * This parameter can be any combination of the following values: * @arg SPI_I2S_DMAReq_Tx: Tx buffer DMA transfer request * @arg SPI_I2S_DMAReq_Rx: Rx buffer DMA transfer request * @param NewState: new state of the selected SPI/I2S DMA transfer request. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_I2S_DMACmd(SPI_TypeDef* SPIx, uint16_t SPI_I2S_DMAReq, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); assert_param(IS_SPI_I2S_DMAREQ(SPI_I2S_DMAReq)); if (NewState != DISABLE) { /* Enable the selected SPI/I2S DMA requests */ SPIx->CR2 |= SPI_I2S_DMAReq; } else { /* Disable the selected SPI/I2S DMA requests */ SPIx->CR2 &= (uint16_t)~SPI_I2S_DMAReq; } } /** * @brief Transmits a Data through the SPIx/I2Sx peripheral. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @param Data : Data to be transmitted. * @retval None */ void SPI_I2S_SendData(SPI_TypeDef* SPIx, uint16_t Data) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Write in the DR register the data to be sent */ SPIx->DR = Data; } /** * @brief Returns the most recent received data by the SPIx/I2Sx peripheral. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @retval The value of the received data. */ uint16_t SPI_I2S_ReceiveData(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Return the data in the DR register */ return SPIx->DR; } /** * @brief Configures internally by software the NSS pin for the selected SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param SPI_NSSInternalSoft: specifies the SPI NSS internal state. * This parameter can be one of the following values: * @arg SPI_NSSInternalSoft_Set: Set NSS pin internally * @arg SPI_NSSInternalSoft_Reset: Reset NSS pin internally * @retval None */ void SPI_NSSInternalSoftwareConfig(SPI_TypeDef* SPIx, uint16_t SPI_NSSInternalSoft) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_NSS_INTERNAL(SPI_NSSInternalSoft)); if (SPI_NSSInternalSoft != SPI_NSSInternalSoft_Reset) { /* Set NSS pin internally by software */ SPIx->CR1 |= SPI_NSSInternalSoft_Set; } else { /* Reset NSS pin internally by software */ SPIx->CR1 &= SPI_NSSInternalSoft_Reset; } } /** * @brief Enables or disables the SS output for the selected SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param NewState: new state of the SPIx SS output. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_SSOutputCmd(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI SS output */ SPIx->CR2 |= CR2_SSOE_Set; } else { /* Disable the selected SPI SS output */ SPIx->CR2 &= CR2_SSOE_Reset; } } /** * @brief Configures the data size for the selected SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param SPI_DataSize: specifies the SPI data size. * This parameter can be one of the following values: * @arg SPI_DataSize_16b: Set data frame format to 16bit * @arg SPI_DataSize_8b: Set data frame format to 8bit * @retval None */ void SPI_DataSizeConfig(SPI_TypeDef* SPIx, uint16_t SPI_DataSize) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_DATASIZE(SPI_DataSize)); /* Clear DFF bit */ SPIx->CR1 &= (uint16_t)~SPI_DataSize_16b; /* Set new DFF bit value */ SPIx->CR1 |= SPI_DataSize; } /** * @brief Transmit the SPIx CRC value. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @retval None */ void SPI_TransmitCRC(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Enable the selected SPI CRC transmission */ SPIx->CR1 |= CR1_CRCNext_Set; } /** * @brief Enables or disables the CRC value calculation of the transferred bytes. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param NewState: new state of the SPIx CRC value calculation. * This parameter can be: ENABLE or DISABLE. * @retval None */ void SPI_CalculateCRC(SPI_TypeDef* SPIx, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_FUNCTIONAL_STATE(NewState)); if (NewState != DISABLE) { /* Enable the selected SPI CRC calculation */ SPIx->CR1 |= CR1_CRCEN_Set; } else { /* Disable the selected SPI CRC calculation */ SPIx->CR1 &= CR1_CRCEN_Reset; } } /** * @brief Returns the transmit or the receive CRC register value for the specified SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param SPI_CRC: specifies the CRC register to be read. * This parameter can be one of the following values: * @arg SPI_CRC_Tx: Selects Tx CRC register * @arg SPI_CRC_Rx: Selects Rx CRC register * @retval The selected CRC register value.. */ uint16_t SPI_GetCRC(SPI_TypeDef* SPIx, uint8_t SPI_CRC) { uint16_t crcreg = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_CRC(SPI_CRC)); if (SPI_CRC != SPI_CRC_Rx) { /* Get the Tx CRC register */ crcreg = SPIx->TXCRCR; } else { /* Get the Rx CRC register */ crcreg = SPIx->RXCRCR; } /* Return the selected CRC register */ return crcreg; } /** * @brief Returns the CRC Polynomial register value for the specified SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @retval The CRC Polynomial register value. */ uint16_t SPI_GetCRCPolynomial(SPI_TypeDef* SPIx) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); /* Return the CRC polynomial register */ return SPIx->CRCPR; } /** * @brief Selects the data transfer direction in bi-directional mode for the specified SPI. * @param SPIx: where x can be 1, 2 or 3 to select the SPI peripheral. * @param SPI_Direction: specifies the data transfer direction in bi-directional mode. * This parameter can be one of the following values: * @arg SPI_Direction_Tx: Selects Tx transmission direction * @arg SPI_Direction_Rx: Selects Rx receive direction * @retval None */ void SPI_BiDirectionalLineConfig(SPI_TypeDef* SPIx, uint16_t SPI_Direction) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_DIRECTION(SPI_Direction)); if (SPI_Direction == SPI_Direction_Tx) { /* Set the Tx only mode */ SPIx->CR1 |= SPI_Direction_Tx; } else { /* Set the Rx only mode */ SPIx->CR1 &= SPI_Direction_Rx; } } /** * @brief Checks whether the specified SPI/I2S flag is set or not. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @param SPI_I2S_FLAG: specifies the SPI/I2S flag to check. * This parameter can be one of the following values: * @arg SPI_I2S_FLAG_TXE: Transmit buffer empty flag. * @arg SPI_I2S_FLAG_RXNE: Receive buffer not empty flag. * @arg SPI_I2S_FLAG_BSY: Busy flag. * @arg SPI_I2S_FLAG_OVR: Overrun flag. * @arg SPI_FLAG_MODF: Mode Fault flag. * @arg SPI_FLAG_CRCERR: CRC Error flag. * @arg I2S_FLAG_UDR: Underrun Error flag. * @arg I2S_FLAG_CHSIDE: Channel Side flag. * @retval The new state of SPI_I2S_FLAG (SET or RESET). */ FlagStatus SPI_I2S_GetFlagStatus(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_GET_FLAG(SPI_I2S_FLAG)); /* Check the status of the specified SPI/I2S flag */ if ((SPIx->SR & SPI_I2S_FLAG) != (uint16_t)RESET) { /* SPI_I2S_FLAG is set */ bitstatus = SET; } else { /* SPI_I2S_FLAG is reset */ bitstatus = RESET; } /* Return the SPI_I2S_FLAG status */ return bitstatus; } /** * @brief Clears the SPIx CRC Error (CRCERR) flag. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * @param SPI_I2S_FLAG: specifies the SPI flag to clear. * This function clears only CRCERR flag. * @note * - OVR (OverRun error) flag is cleared by software sequence: a read * operation to SPI_DR register (SPI_I2S_ReceiveData()) followed by a read * operation to SPI_SR register (SPI_I2S_GetFlagStatus()). * - UDR (UnderRun error) flag is cleared by a read operation to * SPI_SR register (SPI_I2S_GetFlagStatus()). * - MODF (Mode Fault) flag is cleared by software sequence: a read/write * operation to SPI_SR register (SPI_I2S_GetFlagStatus()) followed by a * write operation to SPI_CR1 register (SPI_Cmd() to enable the SPI). * @retval None */ void SPI_I2S_ClearFlag(SPI_TypeDef* SPIx, uint16_t SPI_I2S_FLAG) { /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_CLEAR_FLAG(SPI_I2S_FLAG)); /* Clear the selected SPI CRC Error (CRCERR) flag */ SPIx->SR = (uint16_t)~SPI_I2S_FLAG; } /** * @brief Checks whether the specified SPI/I2S interrupt has occurred or not. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * - 2 or 3 in I2S mode * @param SPI_I2S_IT: specifies the SPI/I2S interrupt source to check. * This parameter can be one of the following values: * @arg SPI_I2S_IT_TXE: Transmit buffer empty interrupt. * @arg SPI_I2S_IT_RXNE: Receive buffer not empty interrupt. * @arg SPI_I2S_IT_OVR: Overrun interrupt. * @arg SPI_IT_MODF: Mode Fault interrupt. * @arg SPI_IT_CRCERR: CRC Error interrupt. * @arg I2S_IT_UDR: Underrun Error interrupt. * @retval The new state of SPI_I2S_IT (SET or RESET). */ ITStatus SPI_I2S_GetITStatus(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT) { ITStatus bitstatus = RESET; uint16_t itpos = 0, itmask = 0, enablestatus = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_GET_IT(SPI_I2S_IT)); /* Get the SPI/I2S IT index */ itpos = 0x01 << (SPI_I2S_IT & 0x0F); /* Get the SPI/I2S IT mask */ itmask = SPI_I2S_IT >> 4; /* Set the IT mask */ itmask = 0x01 << itmask; /* Get the SPI_I2S_IT enable bit status */ enablestatus = (SPIx->CR2 & itmask) ; /* Check the status of the specified SPI/I2S interrupt */ if (((SPIx->SR & itpos) != (uint16_t)RESET) && enablestatus) { /* SPI_I2S_IT is set */ bitstatus = SET; } else { /* SPI_I2S_IT is reset */ bitstatus = RESET; } /* Return the SPI_I2S_IT status */ return bitstatus; } /** * @brief Clears the SPIx CRC Error (CRCERR) interrupt pending bit. * @param SPIx: where x can be * - 1, 2 or 3 in SPI mode * @param SPI_I2S_IT: specifies the SPI interrupt pending bit to clear. * This function clears only CRCERR interrupt pending bit. * @note * - OVR (OverRun Error) interrupt pending bit is cleared by software * sequence: a read operation to SPI_DR register (SPI_I2S_ReceiveData()) * followed by a read operation to SPI_SR register (SPI_I2S_GetITStatus()). * - UDR (UnderRun Error) interrupt pending bit is cleared by a read * operation to SPI_SR register (SPI_I2S_GetITStatus()). * - MODF (Mode Fault) interrupt pending bit is cleared by software sequence: * a read/write operation to SPI_SR register (SPI_I2S_GetITStatus()) * followed by a write operation to SPI_CR1 register (SPI_Cmd() to enable * the SPI). * @retval None */ void SPI_I2S_ClearITPendingBit(SPI_TypeDef* SPIx, uint8_t SPI_I2S_IT) { uint16_t itpos = 0; /* Check the parameters */ assert_param(IS_SPI_ALL_PERIPH(SPIx)); assert_param(IS_SPI_I2S_CLEAR_IT(SPI_I2S_IT)); /* Get the SPI IT index */ itpos = 0x01 << (SPI_I2S_IT & 0x0F); /* Clear the selected SPI CRC Error (CRCERR) interrupt pending bit */ SPIx->SR = (uint16_t)~itpos; } /** * @} */ /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
gpl-3.0
orbea/RetroArch
gfx/include/userland/interface/khronos/egl/egl_client_config.c
19
13759
/* Copyright (c) 2012, Broadcom Europe Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "interface/khronos/common/khrn_int_common.h" #include "interface/khronos/common/khrn_client_platform.h" #include "interface/khronos/include/EGL/eglext.h" #include "interface/khronos/egl/egl_client_config.h" //#define BGR_FB typedef uint32_t FEATURES_T; #define FEATURES_PACK(r, g, b, a, d, s, m, mask, lockable) ((FEATURES_T)((((uint32_t)(r)) << 28 | (g) << 24 | (b) << 20 | (a) << 16 | (d) << 8 | (s) << 4 | (m) << 3 | ((mask) >> 3) << 2) | (lockable) << 1)) typedef struct { FEATURES_T features; KHRN_IMAGE_FORMAT_T color, depth, multisample, mask; } FEATURES_AND_FORMATS_T; /* formats For 0 <= id < EGL_MAX_CONFIGS: formats[id].features is valid */ static FEATURES_AND_FORMATS_T formats[EGL_MAX_CONFIGS] = { // LOCKABLE // MASK | // R G B A D S M | | COLOR DEPTH MULTISAMPLE MASK {FEATURES_PACK(8, 8, 8, 8, 24, 8, 0, 0, 0), ABGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 24, 8, 0, 0, 0), XBGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 24, 0, 0, 0, 0), ABGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 24, 0, 0, 0, 0), XBGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 0, 8, 0, 0, 0), ABGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 0, 8, 0, 0, 0), XBGR_8888, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 0, 0, 0, 0, 0), ABGR_8888, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 0, 0, 0, 0, 0), XBGR_8888, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 24, 8, 1, 0, 0), ABGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 24, 8, 1, 0, 0), XBGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 24, 0, 1, 0, 0), ABGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 24, 0, 1, 0, 0), XBGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 0, 8, 1, 0, 0), ABGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 0, 8, 1, 0, 0), XBGR_8888, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 8, 0, 0, 1, 0, 0), ABGR_8888, IMAGE_FORMAT_INVALID, COL_32_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(8, 8, 8, 0, 0, 0, 1, 0, 0), XBGR_8888, IMAGE_FORMAT_INVALID, COL_32_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 24, 8, 0, 0, 0), RGB_565, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 24, 0, 0, 0, 0), RGB_565, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 0, 8, 0, 0, 0), RGB_565, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 0, 0, 0, 0, 0), RGB_565, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 24, 8, 1, 0, 0), RGB_565, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 24, 0, 1, 0, 0), RGB_565, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 0, 8, 1, 0, 0), RGB_565, DEPTH_32_TLBD /*?*/, DEPTH_COL_64_TLBD, IMAGE_FORMAT_INVALID}, {FEATURES_PACK(5, 6, 5, 0, 0, 0, 1, 0, 0), RGB_565, IMAGE_FORMAT_INVALID, COL_32_TLBD, IMAGE_FORMAT_INVALID}, #ifndef EGL_NO_ALPHA_MASK_CONFIGS {FEATURES_PACK(8, 8, 8, 8, 0, 0, 0, 8, 0), ABGR_8888, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, A_8_RSO}, {FEATURES_PACK(8, 8, 8, 0, 0, 0, 0, 8, 0), XBGR_8888, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, A_8_RSO}, {FEATURES_PACK(5, 6, 5, 0, 0, 0, 0, 8, 0), RGB_565, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID, A_8_RSO}, #endif {FEATURES_PACK(5, 6, 5, 0, 16, 0, 0, 0, 0), RGB_565, DEPTH_32_TLBD, IMAGE_FORMAT_INVALID, IMAGE_FORMAT_INVALID}, }; void egl_config_install_configs(int type) { uint32_t i; for (i = 0; i != ARR_COUNT(formats); ++i) { formats[i].color = (type == 0) ? khrn_image_to_rso_format(formats[i].color) : khrn_image_to_tf_format(formats[i].color); } } static bool bindable_rgb(FEATURES_T features); static bool bindable_rgba(FEATURES_T features); #include "interface/khronos/egl/egl_client_config_cr.c" /* KHRN_IMAGE_FORMAT_T egl_config_get_color_format(int id) Implementation notes: We may return an image format which cannot be rendered to. Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Return value is a hardware framebuffer-supported uncompressed color KHRN_IMAGE_FORMAT_T */ KHRN_IMAGE_FORMAT_T egl_config_get_color_format(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return formats[id].color; } /* KHRN_IMAGE_FORMAT_T egl_config_get_depth_format(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Return value is a hardware framebuffer-supported depth KHRN_IMAGE_FORMAT_T or IMAGE_FORMAT_INVALID */ KHRN_IMAGE_FORMAT_T egl_config_get_depth_format(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return formats[id].depth; } /* KHRN_IMAGE_FORMAT_T egl_config_get_mask_format(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Return value is a hardware framebuffer-supported mask KHRN_IMAGE_FORMAT_T or IMAGE_FORMAT_INVALID */ KHRN_IMAGE_FORMAT_T egl_config_get_mask_format(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return formats[id].mask; } /* KHRN_IMAGE_FORMAT_T egl_config_get_multisample_format(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Return value is a hardware framebuffer-supported multisample color format or IMAGE_FORMAT_INVALID */ KHRN_IMAGE_FORMAT_T egl_config_get_multisample_format(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return formats[id].multisample; } /* bool egl_config_get_multisample(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: - */ bool egl_config_get_multisample(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return FEATURES_UNPACK_MULTI(formats[id].features); } /* bool bindable_rgb(FEATURES_T features) bool bindable_rgba(FEATURES_T features) Preconditions: features is a valid FEATURES_T Postconditions: - */ static bool bindable_rgb(FEATURES_T features) { return !FEATURES_UNPACK_MULTI(features) && !FEATURES_UNPACK_ALPHA(features); } static bool bindable_rgba(FEATURES_T features) { return !FEATURES_UNPACK_MULTI(features); } bool egl_config_bindable(int id, EGLenum format) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); switch (format) { case EGL_NO_TEXTURE: return true; case EGL_TEXTURE_RGB: return bindable_rgb(formats[id].features); case EGL_TEXTURE_RGBA: return bindable_rgba(formats[id].features); default: UNREACHABLE(); return false; } } /* bool egl_config_match_pixmap_info(int id, KHRN_IMAGE_WRAP_T *image) TODO: decide how tolerant we should be when matching to native pixmaps. At present they match if the red, green, blue and alpha channels all have the same bit depths. Preconditions: 0 <= id < EGL_MAX_CONFIGS image is a pointer to a valid KHRN_IMAGE_WRAP_T, possibly with null data pointer match is a bitmask which is a subset of PLATFORM_PIXMAP_MATCH_NONRENDERABLE|PLATFORM_PIXMAP_MATCH_RENDERABLE Postconditions: - */ bool egl_config_match_pixmap_info(int id, KHRN_IMAGE_WRAP_T *image) { FEATURES_T features = formats[id].features; KHRN_IMAGE_FORMAT_T format = image->format; vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return khrn_image_get_red_size(format) == FEATURES_UNPACK_RED(features) && khrn_image_get_green_size(format) == FEATURES_UNPACK_GREEN(features) && khrn_image_get_blue_size(format) == FEATURES_UNPACK_BLUE(features) && khrn_image_get_alpha_size(format) == FEATURES_UNPACK_ALPHA(features); } /* uint32_t egl_config_get_api_support(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Result is a bitmap which is a subset of (EGL_OPENGL_ES_BIT | EGL_OPENVG_BIT | EGL_OPENGL_ES2_BIT) */ uint32_t egl_config_get_api_support(int id) { /* no configs are api-specific (ie if you can use a config with gl, you can * use it with vg too, and vice-versa). however, some configs have color * buffer formats that are incompatible with the hardware, and so can't be * used with any api. such configs may still be useful eg with the surface * locking extension... */ #if EGL_KHR_lock_surface /* to reduce confusion, just say no for all lockable configs. this #if can be * safely commented out -- the color buffer format check below will catch * lockable configs we actually can't use */ if (egl_config_is_lockable(id)) { return 0; } #endif switch (egl_config_get_color_format(id)) { case ABGR_8888_RSO: case ABGR_8888_TF: case ABGR_8888_LT: case XBGR_8888_RSO: case XBGR_8888_TF: case XBGR_8888_LT: case ARGB_8888_RSO: case ARGB_8888_TF: case ARGB_8888_LT: case XRGB_8888_RSO: case XRGB_8888_TF: case XRGB_8888_LT: case RGB_565_RSO: case RGB_565_TF: case RGB_565_LT: #ifndef NO_OPENVG return (uint32_t)(EGL_OPENGL_ES_BIT | EGL_OPENVG_BIT | EGL_OPENGL_ES2_BIT); #else return (uint32_t)(EGL_OPENGL_ES_BIT | EGL_OPENGL_ES2_BIT); #endif default: break; } return 0; } /* uint32_t egl_config_get_api_conformance(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: Result is a bitmap which is a subset of (EGL_OPENGL_ES_BIT | EGL_OPENVG_BIT | EGL_OPENGL_ES2_BIT) */ uint32_t egl_config_get_api_conformance(int id) { /* vg doesn't support multisampled surfaces properly */ return egl_config_get_api_support(id) & ~(FEATURES_UNPACK_MULTI(formats[id].features) ? EGL_OPENVG_BIT : 0); } bool egl_config_bpps_match(int id0, int id1) /* bpps of all buffers match */ { FEATURES_T config0 = formats[id0].features; FEATURES_T config1 = formats[id1].features; return FEATURES_UNPACK_RED(config0) == FEATURES_UNPACK_RED(config1) && FEATURES_UNPACK_GREEN(config0) == FEATURES_UNPACK_GREEN(config1) && FEATURES_UNPACK_BLUE(config0) == FEATURES_UNPACK_BLUE(config1) && FEATURES_UNPACK_ALPHA(config0) == FEATURES_UNPACK_ALPHA(config1) && FEATURES_UNPACK_DEPTH(config0) == FEATURES_UNPACK_DEPTH(config1) && FEATURES_UNPACK_STENCIL(config0) == FEATURES_UNPACK_STENCIL(config1) && FEATURES_UNPACK_MASK(config0) == FEATURES_UNPACK_MASK(config1); } #if EGL_KHR_lock_surface /* KHRN_IMAGE_FORMAT_T egl_config_get_mapped_format(int id) Returns the format of the mapped buffer when an EGL surface is locked. Preconditions: 0 <= id < EGL_MAX_CONFIGS egl_config_is_lockable(id) Postconditions: Return value is RGB_565_RSO or ARGB_8888_RSO */ KHRN_IMAGE_FORMAT_T egl_config_get_mapped_format(int id) { KHRN_IMAGE_FORMAT_T result; vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); vcos_assert(FEATURES_UNPACK_LOCKABLE(formats[id].features)); /* If any t-format images were lockable, we would convert to raster format here */ result = egl_config_get_color_format(id); vcos_assert(khrn_image_is_rso(result)); return result; } /* bool egl_config_is_lockable(int id) Preconditions: 0 <= id < EGL_MAX_CONFIGS Postconditions: - */ bool egl_config_is_lockable(int id) { vcos_assert(id >= 0 && id < EGL_MAX_CONFIGS); return FEATURES_UNPACK_LOCKABLE(formats[id].features); } #endif
gpl-3.0
dougmassay/Sigil
3rdparty/hunspell/src/tools/unmunch.c
19
12920
/* Un-munch a root word list with affix tags * to recreate the original word list */ #include <ctype.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #if defined(__linux__) && !defined(__ANDROID__) #include <error.h> #include <errno.h> #include <sys/mman.h> #endif #include "unmunch.h" int main(int argc, char** argv) { int i; int al, wl; FILE * wrdlst; FILE * afflst; char *wf, *af; char * ap; char ts[MAX_LN_LEN]; (void)argc; /* first parse the command line options */ /* arg1 - munched wordlist, arg2 - affix file */ if (argv[1]) { wf = mystrdup(argv[1]); } else { fprintf(stderr,"correct syntax is:\n"); fprintf(stderr,"unmunch dic_file affix_file\n"); exit(1); } if (argv[2]) { af = mystrdup(argv[2]); } else { fprintf(stderr,"correct syntax is:\n"); fprintf(stderr,"unmunch dic_file affix_file\n"); exit(1); } /* open the affix file */ afflst = fopen(af,"r"); if (!afflst) { fprintf(stderr,"Error - could not open affix description file\n"); exit(1); } /* step one is to parse the affix file building up the internal affix data structures */ numpfx = 0; numsfx = 0; fullstrip = 0; if (parse_aff_file(afflst)) { fprintf(stderr,"Error - in affix file loading\n"); exit(1); } fclose(afflst); fprintf(stderr,"parsed in %d prefixes and %d suffixes\n",numpfx,numsfx); /* affix file is now parsed so create hash table of wordlist on the fly */ /* open the wordlist */ wrdlst = fopen(wf,"r"); if (!wrdlst) { fprintf(stderr,"Error - could not open word list file\n"); exit(1); } /* skip over the hash table size */ if (! fgets(ts, MAX_LN_LEN-1,wrdlst)) { fclose(wrdlst); return 2; } mychomp(ts); while (fgets(ts,MAX_LN_LEN-1,wrdlst)) { mychomp(ts); /* split each line into word and affix char strings */ ap = strchr(ts,'/'); if (ap) { *ap = '\0'; ap++; al = strlen(ap); } else { al = 0; ap = NULL; } wl = strlen(ts); numwords = 0; wlist[numwords].word = mystrdup(ts); wlist[numwords].pallow = 0; numwords++; if (al) expand_rootword(ts,wl,ap); for (i=0; i < numwords; i++) { fprintf(stdout,"%s\n",wlist[i].word); free(wlist[i].word); wlist[i].word = NULL; wlist[i].pallow = 0; } } fclose(wrdlst); return 0; } int parse_aff_file(FILE * afflst) { int i, j; int numents=0; char achar='\0'; short ff=0; char ft; struct affent * ptr= NULL; struct affent * nptr= NULL; char * line = malloc(MAX_LN_LEN); while (fgets(line,MAX_LN_LEN,afflst)) { mychomp(line); ft = ' '; fprintf(stderr,"parsing line: %s\n",line); if (strncmp(line,"FULLSTRIP",9) == 0) fullstrip = 1; if (strncmp(line,"PFX",3) == 0) ft = 'P'; if (strncmp(line,"SFX",3) == 0) ft = 'S'; if (ft != ' ') { char * tp = line; char * piece; ff = 0; i = 0; while ((piece=mystrsep(&tp,' '))) { if (*piece != '\0') { switch(i) { case 0: break; case 1: { achar = *piece; break; } case 2: { if (*piece == 'Y') ff = XPRODUCT; break; } case 3: { numents = atoi(piece); ptr = malloc(numents * sizeof(struct affent)); ptr->achar = achar; ptr->xpflg = ff; fprintf(stderr,"parsing %c entries %d\n",achar,numents); break; } default: break; } i++; } free(piece); } /* now parse all of the sub entries*/ nptr = ptr; for (j=0; j < numents; j++) { if (!fgets(line,MAX_LN_LEN,afflst)) return 1; mychomp(line); tp = line; i = 0; while ((piece=mystrsep(&tp,' '))) { if (*piece != '\0') { switch(i) { case 0: { if (nptr != ptr) { nptr->achar = ptr->achar; nptr->xpflg = ptr->xpflg; } break; } case 1: break; case 2: { nptr->strip = mystrdup(piece); nptr->stripl = strlen(nptr->strip); if (strcmp(nptr->strip,"0") == 0) { free(nptr->strip); nptr->strip=mystrdup(""); nptr->stripl = 0; } break; } case 3: { nptr->appnd = mystrdup(piece); nptr->appndl = strlen(nptr->appnd); if (strcmp(nptr->appnd,"0") == 0) { free(nptr->appnd); nptr->appnd=mystrdup(""); nptr->appndl = 0; } break; } case 4: { encodeit(nptr,piece);} fprintf(stderr, " affix: %s %d, strip: %s %d\n",nptr->appnd, nptr->appndl,nptr->strip,nptr->stripl); default: break; } i++; } free(piece); } nptr++; } if (ft == 'P') { ptable[numpfx].aep = ptr; ptable[numpfx].num = numents; fprintf(stderr,"ptable %d num is %d flag %c\n",numpfx,ptable[numpfx].num,ptr->achar); numpfx++; } else { stable[numsfx].aep = ptr; stable[numsfx].num = numents; fprintf(stderr,"stable %d num is %d flag %c\n",numsfx,stable[numsfx].num,ptr->achar); numsfx++; } ptr = NULL; nptr = NULL; numents = 0; achar='\0'; } } free(line); return 0; } void encodeit(struct affent * ptr, char * cs) { int nc; int neg; int grp; unsigned char c; int n; int ec; int nm; int i, j, k; unsigned char mbr[MAX_WD_LEN]; /* now clear the conditions array */ for (i=0;i<SET_SIZE;i++) ptr->conds[i] = (unsigned char) 0; /* now parse the string to create the conds array */ nc = strlen(cs); neg = 0; /* complement indicator */ grp = 0; /* group indicator */ n = 0; /* number of conditions */ ec = 0; /* end condition indicator */ nm = 0; /* number of member in group */ i = 0; if (strcmp(cs,".")==0) { ptr->numconds = 0; return; } while (i < nc) { c = *((unsigned char *)(cs + i)); if (c == '[') { grp = 1; c = 0; } if ((grp == 1) && (c == '^')) { neg = 1; c = 0; } if (c == ']') { ec = 1; c = 0; } if ((grp == 1) && (c != 0)) { *(mbr + nm) = c; nm++; c = 0; } if (c != 0) { ec = 1; } if (ec) { if (grp == 1) { if (neg == 0) { for (j=0;j<nm;j++) { k = (unsigned int) mbr[j]; ptr->conds[k] = ptr->conds[k] | (1 << n); } } else { for (j=0;j<SET_SIZE;j++) ptr->conds[j] = ptr->conds[j] | (1 << n); for (j=0;j<nm;j++) { k = (unsigned int) mbr[j]; ptr->conds[k] = ptr->conds[k] & ~(1 << n); } } neg = 0; grp = 0; nm = 0; } else { /* not a group so just set the proper bit for this char */ /* but first handle special case of . inside condition */ if (c == '.') { /* wild card character so set them all */ for (j=0;j<SET_SIZE;j++) ptr->conds[j] = ptr->conds[j] | (1 << n); } else { ptr->conds[(unsigned int) c] = ptr->conds[(unsigned int)c] | (1 << n); } } n++; ec = 0; } i++; } ptr->numconds = n; return; } /* add a prefix to word */ void pfx_add (const char * word, int len, struct affent* ep, int num) { struct affent * aent; int cond; int tlen; unsigned char * cp; int i; char * pp; char tword[MAX_WD_LEN]; for (aent = ep, i = num; i > 0; aent++, i--) { /* now make sure all conditions match */ if ((len + fullstrip > aent->stripl) && (len >= aent->numconds) && ((aent->stripl == 0) || (strncmp(aent->strip, word, aent->stripl) == 0))) { cp = (unsigned char *) word; for (cond = 0; cond < aent->numconds; cond++) { if ((aent->conds[*cp++] & (1 << cond)) == 0) break; } if (cond >= aent->numconds) { /* we have a match so add prefix */ tlen = 0; if (aent->appndl) { strcpy(tword,aent->appnd); tlen += aent->appndl; } pp = tword + tlen; strcpy(pp, (word + aent->stripl)); tlen = tlen + len - aent->stripl; if (numwords < MAX_WORDS) { wlist[numwords].word = mystrdup(tword); wlist[numwords].pallow = 0; numwords++; } } } } } /* add a suffix to a word */ void suf_add (const char * word, int len, struct affent * ep, int num) { struct affent * aent; int tlen; int cond; unsigned char * cp; int i; char tword[MAX_WD_LEN]; char * pp; for (aent = ep, i = num; i > 0; aent++, i--) { /* if conditions hold on root word * then strip off strip string and add suffix */ if ((len + fullstrip > aent->stripl) && (len >= aent->numconds) && ((aent->stripl == 0) || (strcmp(aent->strip, word + len - aent->stripl) == 0))) { cp = (unsigned char *) (word + len); for (cond = aent->numconds; --cond >= 0; ) { if ((aent->conds[*--cp] & (1 << cond)) == 0) break; } if (cond < 0) { /* we have a matching condition */ strcpy(tword,word); tlen = len; if (aent->stripl) { tlen -= aent->stripl; } pp = (tword + tlen); if (aent->appndl) { strcpy (pp, aent->appnd); tlen += aent->stripl; } else *pp = '\0'; if (numwords < MAX_WORDS) { wlist[numwords].word = mystrdup(tword); wlist[numwords].pallow = (aent->xpflg & XPRODUCT); numwords++; } } } } } int expand_rootword(const char * ts, int wl, const char * ap) { int i; int j; int nh=0; int nwl; for (i=0; i < numsfx; i++) { if (strchr(ap,(stable[i].aep)->achar)) { suf_add(ts, wl, stable[i].aep, stable[i].num); } } nh = numwords; if (nh > 1) { for (j=1;j<nh;j++){ if (wlist[j].pallow) { for (i=0; i < numpfx; i++) { if (strchr(ap,(ptable[i].aep)->achar)) { if ((ptable[i].aep)->xpflg & XPRODUCT) { nwl = strlen(wlist[j].word); pfx_add(wlist[j].word, nwl, ptable[i].aep, ptable[i].num); } } } } } } for (i=0; i < numpfx; i++) { if (strchr(ap,(ptable[i].aep)->achar)) { pfx_add(ts, wl, ptable[i].aep, ptable[i].num); } } return 0; } /* strip strings into token based on single char delimiter * acts like strsep() but only uses a delim char and not * a delim string */ char * mystrsep(char ** stringp, const char delim) { char * rv = NULL; char * mp = *stringp; int n = strlen(mp); if (n > 0) { char * dp = (char *)memchr(mp,(int)((unsigned char)delim),n); if (dp) { int nc; *stringp = dp+1; nc = (int)((unsigned long)dp - (unsigned long)mp); rv = (char *) malloc(nc+1); if (rv) { memcpy(rv,mp,nc); *(rv+nc) = '\0'; } } else { rv = (char *) malloc(n+1); if (rv) { memcpy(rv, mp, n); *(rv+n) = '\0'; *stringp = mp + n; } } } return rv; } char * mystrdup(const char * s) { char * d = NULL; if (s) { int sl = strlen(s)+1; d = (char *) malloc(sl); if (d) memcpy(d,s,sl); } return d; } void mychomp(char * s) { int k = strlen(s); if ((k > 0) && (*(s+k-1) == '\n')) *(s+k-1) = '\0'; if ((k > 1) && (*(s+k-2) == '\r')) *(s+k-2) = '\0'; }
gpl-3.0
mikeller/betaflight
src/main/target/SPRACINGF4EVO/target.c
19
3168
/* * This file is part of Cleanflight and Betaflight. * * Cleanflight and Betaflight are free software. You can redistribute * this software and/or modify this software 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. * * Cleanflight and Betaflight are distributed in the hope that they * 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 software. * * If not, see <http://www.gnu.org/licenses/>. */ #include <stdint.h> #include "platform.h" #include "drivers/io.h" #include "drivers/timer.h" #include "drivers/timer_def.h" #include "drivers/dma.h" const timerHardware_t timerHardware[USABLE_TIMER_CHANNEL_COUNT] = { DEF_TIM(TIM9, CH2, PA3, TIM_USE_PPM | TIM_USE_PWM, 0, 0), // PPM / PWM1 / UART2 RX DEF_TIM(TIM9, CH1, PA2, TIM_USE_PWM, 0, 0), // PPM / PWM2 / UART2 TX DEF_TIM(TIM8, CH1, PC6, TIM_USE_MOTOR, 0, 1), // ESC 1 DEF_TIM(TIM8, CH2, PC7, TIM_USE_MOTOR, 0, 1), // ESC 2 DEF_TIM(TIM8, CH4, PC9, TIM_USE_MOTOR, 0, 0), // ESC 3 DEF_TIM(TIM8, CH3, PC8, TIM_USE_MOTOR, 0, 1), // ESC 4 #if defined(SPRACINGF4EVO_REV) && (SPRACINGF4EVO_REV >= 2) DEF_TIM(TIM4, CH1, PB6, TIM_USE_MOTOR, 0, 0), // ESC 5 / Conflicts with USART5_RX / SPI3_RX - SPI3_RX can be mapped to DMA1_ST3_CH0 DEF_TIM(TIM4, CH2, PB7, TIM_USE_MOTOR, 0, 0), // ESC 6 / Conflicts with USART3_RX #else #ifdef USE_TIM10_TIM11_FOR_MOTORS DEF_TIM(TIM10, CH1, PB8, TIM_USE_MOTOR, 0, 0), // ESC 5 DEF_TIM(TIM11, CH1, PB9, TIM_USE_MOTOR, 0, 0), // ESC 6 #else DEF_TIM(TIM4, CH3, PB8, TIM_USE_MOTOR, 0, 0), // ESC 5 DEF_TIM(TIM4, CH4, PB9, TIM_USE_MOTOR, 0, 0), // ESC 6 #endif #endif DEF_TIM(TIM3, CH4, PB1, TIM_USE_MOTOR, 0, 0), // ESC 7 DEF_TIM(TIM3, CH3, PB0, TIM_USE_MOTOR, 0, 0), // ESC 8 DEF_TIM(TIM2, CH2, PA1, TIM_USE_LED, 0, 0), // LED Strip // Additional 2 PWM channels available on UART3 RX/TX pins // However, when using led strip the timer cannot be used, but no code appears to prevent that right now DEF_TIM(TIM2, CH3, PB10, TIM_USE_MOTOR, 0, 0), // Shared with UART3 TX PIN and SPI3 TX (OSD) DEF_TIM(TIM2, CH4, PB11, TIM_USE_MOTOR, 0, 1), // Shared with UART3 RX PIN DEF_TIM(TIM1, CH1, PA8, TIM_USE_TRANSPONDER, 0, 0), // Transponder // Additional 2 PWM channels available on UART1 RX/TX pins // However, when using transponder the timer cannot be used, but no code appears to prevent that right now DEF_TIM(TIM1, CH2, PA9, TIM_USE_SERVO | TIM_USE_PWM, 0, 1), // PWM 3 DEF_TIM(TIM1, CH3, PA10, TIM_USE_SERVO | TIM_USE_PWM, 0, 1), // PWM 4 };
gpl-3.0
tenwx/shadowsocks-libev
libsodium/src/libsodium/crypto_stream/chacha20/ref/stream_chacha20_ref.c
22
9104
/* chacha-merged.c version 20080118 D. J. Bernstein Public domain. */ #include <stdint.h> #include <stdlib.h> #include <string.h> #include "utils.h" #include "crypto_stream_chacha20.h" #include "stream_chacha20_ref.h" #include "../stream_chacha20.h" struct chacha_ctx { uint32_t input[16]; }; typedef uint8_t u8; typedef uint32_t u32; typedef struct chacha_ctx chacha_ctx; #define U8C(v) (v##U) #define U32C(v) (v##U) #define U8V(v) ((u8)(v) & U8C(0xFF)) #define U32V(v) ((u32)(v) & U32C(0xFFFFFFFF)) #define ROTL32(v, n) \ (U32V((v) << (n)) | ((v) >> (32 - (n)))) #define U8TO32_LITTLE(p) \ (((u32)((p)[0]) ) | \ ((u32)((p)[1]) << 8) | \ ((u32)((p)[2]) << 16) | \ ((u32)((p)[3]) << 24)) #define U32TO8_LITTLE(p, v) \ do { \ (p)[0] = U8V((v) ); \ (p)[1] = U8V((v) >> 8); \ (p)[2] = U8V((v) >> 16); \ (p)[3] = U8V((v) >> 24); \ } while (0) #define ROTATE(v,c) (ROTL32(v,c)) #define XOR(v,w) ((v) ^ (w)) #define PLUS(v,w) (U32V((v) + (w))) #define PLUSONE(v) (PLUS((v),1)) #define QUARTERROUND(a,b,c,d) \ a = PLUS(a,b); d = ROTATE(XOR(d,a),16); \ c = PLUS(c,d); b = ROTATE(XOR(b,c),12); \ a = PLUS(a,b); d = ROTATE(XOR(d,a), 8); \ c = PLUS(c,d); b = ROTATE(XOR(b,c), 7); static const unsigned char sigma[16] = { 'e', 'x', 'p', 'a', 'n', 'd', ' ', '3', '2', '-', 'b', 'y', 't', 'e', ' ', 'k' }; static void chacha_keysetup(chacha_ctx *ctx, const u8 *k) { const unsigned char *constants; ctx->input[4] = U8TO32_LITTLE(k + 0); ctx->input[5] = U8TO32_LITTLE(k + 4); ctx->input[6] = U8TO32_LITTLE(k + 8); ctx->input[7] = U8TO32_LITTLE(k + 12); k += 16; constants = sigma; ctx->input[8] = U8TO32_LITTLE(k + 0); ctx->input[9] = U8TO32_LITTLE(k + 4); ctx->input[10] = U8TO32_LITTLE(k + 8); ctx->input[11] = U8TO32_LITTLE(k + 12); ctx->input[0] = U8TO32_LITTLE(constants + 0); ctx->input[1] = U8TO32_LITTLE(constants + 4); ctx->input[2] = U8TO32_LITTLE(constants + 8); ctx->input[3] = U8TO32_LITTLE(constants + 12); } static void chacha_ivsetup(chacha_ctx *ctx, const u8 *iv, const u8 *counter) { ctx->input[12] = counter == NULL ? 0 : U8TO32_LITTLE(counter + 0); ctx->input[13] = counter == NULL ? 0 : U8TO32_LITTLE(counter + 4); ctx->input[14] = U8TO32_LITTLE(iv + 0); ctx->input[15] = U8TO32_LITTLE(iv + 4); } static void chacha_ietf_ivsetup(chacha_ctx *ctx, const u8 *iv, const u8 *counter) { ctx->input[12] = counter == NULL ? 0 : U8TO32_LITTLE(counter); ctx->input[13] = U8TO32_LITTLE(iv + 0); ctx->input[14] = U8TO32_LITTLE(iv + 4); ctx->input[15] = U8TO32_LITTLE(iv + 8); } static void chacha_encrypt_bytes(chacha_ctx *ctx, const u8 *m, u8 *c, unsigned long long bytes) { u32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; u32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15; u8 *ctarget = NULL; u8 tmp[64]; unsigned int i; if (!bytes) { return; /* LCOV_EXCL_LINE */ } if (bytes > 64ULL * (1ULL << 32) - 64ULL) { abort(); } j0 = ctx->input[0]; j1 = ctx->input[1]; j2 = ctx->input[2]; j3 = ctx->input[3]; j4 = ctx->input[4]; j5 = ctx->input[5]; j6 = ctx->input[6]; j7 = ctx->input[7]; j8 = ctx->input[8]; j9 = ctx->input[9]; j10 = ctx->input[10]; j11 = ctx->input[11]; j12 = ctx->input[12]; j13 = ctx->input[13]; j14 = ctx->input[14]; j15 = ctx->input[15]; for (;;) { if (bytes < 64) { memset(tmp, 0, 64); for (i = 0; i < bytes; ++i) { tmp[i] = m[i]; } m = tmp; ctarget = c; c = tmp; } x0 = j0; x1 = j1; x2 = j2; x3 = j3; x4 = j4; x5 = j5; x6 = j6; x7 = j7; x8 = j8; x9 = j9; x10 = j10; x11 = j11; x12 = j12; x13 = j13; x14 = j14; x15 = j15; for (i = 20; i > 0; i -= 2) { QUARTERROUND(x0, x4, x8, x12) QUARTERROUND(x1, x5, x9, x13) QUARTERROUND(x2, x6, x10, x14) QUARTERROUND(x3, x7, x11, x15) QUARTERROUND(x0, x5, x10, x15) QUARTERROUND(x1, x6, x11, x12) QUARTERROUND(x2, x7, x8, x13) QUARTERROUND(x3, x4, x9, x14) } x0 = PLUS(x0, j0); x1 = PLUS(x1, j1); x2 = PLUS(x2, j2); x3 = PLUS(x3, j3); x4 = PLUS(x4, j4); x5 = PLUS(x5, j5); x6 = PLUS(x6, j6); x7 = PLUS(x7, j7); x8 = PLUS(x8, j8); x9 = PLUS(x9, j9); x10 = PLUS(x10, j10); x11 = PLUS(x11, j11); x12 = PLUS(x12, j12); x13 = PLUS(x13, j13); x14 = PLUS(x14, j14); x15 = PLUS(x15, j15); x0 = XOR(x0, U8TO32_LITTLE(m + 0)); x1 = XOR(x1, U8TO32_LITTLE(m + 4)); x2 = XOR(x2, U8TO32_LITTLE(m + 8)); x3 = XOR(x3, U8TO32_LITTLE(m + 12)); x4 = XOR(x4, U8TO32_LITTLE(m + 16)); x5 = XOR(x5, U8TO32_LITTLE(m + 20)); x6 = XOR(x6, U8TO32_LITTLE(m + 24)); x7 = XOR(x7, U8TO32_LITTLE(m + 28)); x8 = XOR(x8, U8TO32_LITTLE(m + 32)); x9 = XOR(x9, U8TO32_LITTLE(m + 36)); x10 = XOR(x10, U8TO32_LITTLE(m + 40)); x11 = XOR(x11, U8TO32_LITTLE(m + 44)); x12 = XOR(x12, U8TO32_LITTLE(m + 48)); x13 = XOR(x13, U8TO32_LITTLE(m + 52)); x14 = XOR(x14, U8TO32_LITTLE(m + 56)); x15 = XOR(x15, U8TO32_LITTLE(m + 60)); j12 = PLUSONE(j12); /* LCOV_EXCL_START */ if (!j12) { j13 = PLUSONE(j13); } /* LCOV_EXCL_STOP */ U32TO8_LITTLE(c + 0, x0); U32TO8_LITTLE(c + 4, x1); U32TO8_LITTLE(c + 8, x2); U32TO8_LITTLE(c + 12, x3); U32TO8_LITTLE(c + 16, x4); U32TO8_LITTLE(c + 20, x5); U32TO8_LITTLE(c + 24, x6); U32TO8_LITTLE(c + 28, x7); U32TO8_LITTLE(c + 32, x8); U32TO8_LITTLE(c + 36, x9); U32TO8_LITTLE(c + 40, x10); U32TO8_LITTLE(c + 44, x11); U32TO8_LITTLE(c + 48, x12); U32TO8_LITTLE(c + 52, x13); U32TO8_LITTLE(c + 56, x14); U32TO8_LITTLE(c + 60, x15); if (bytes <= 64) { if (bytes < 64) { for (i = 0; i < (unsigned int) bytes; ++i) { ctarget[i] = c[i]; } } ctx->input[12] = j12; ctx->input[13] = j13; return; } bytes -= 64; c += 64; m += 64; } } static int stream_ref(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) { struct chacha_ctx ctx; if (!clen) { return 0; } (void) sizeof(int[crypto_stream_chacha20_KEYBYTES == 256 / 8 ? 1 : -1]); chacha_keysetup(&ctx, k); chacha_ivsetup(&ctx, n, NULL); memset(c, 0, clen); chacha_encrypt_bytes(&ctx, c, c, clen); sodium_memzero(&ctx, sizeof ctx); return 0; } static int stream_ietf_ref(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) { struct chacha_ctx ctx; if (!clen) { return 0; } (void) sizeof(int[crypto_stream_chacha20_KEYBYTES == 256 / 8 ? 1 : -1]); chacha_keysetup(&ctx, k); chacha_ietf_ivsetup(&ctx, n, NULL); memset(c, 0, clen); chacha_encrypt_bytes(&ctx, c, c, clen); sodium_memzero(&ctx, sizeof ctx); return 0; } static int stream_ref_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k) { struct chacha_ctx ctx; uint8_t ic_bytes[8]; uint32_t ic_high; uint32_t ic_low; if (!mlen) { return 0; } ic_high = U32V(ic >> 32); ic_low = U32V(ic); U32TO8_LITTLE(&ic_bytes[0], ic_low); U32TO8_LITTLE(&ic_bytes[4], ic_high); chacha_keysetup(&ctx, k); chacha_ivsetup(&ctx, n, ic_bytes); chacha_encrypt_bytes(&ctx, m, c, mlen); sodium_memzero(&ctx, sizeof ctx); return 0; } static int stream_ietf_ref_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint32_t ic, const unsigned char *k) { struct chacha_ctx ctx; uint8_t ic_bytes[4]; if (!mlen) { return 0; } U32TO8_LITTLE(ic_bytes, ic); chacha_keysetup(&ctx, k); chacha_ietf_ivsetup(&ctx, n, ic_bytes); chacha_encrypt_bytes(&ctx, m, c, mlen); sodium_memzero(&ctx, sizeof ctx); return 0; } struct crypto_stream_chacha20_implementation crypto_stream_chacha20_ref_implementation = { SODIUM_C99(.stream =) stream_ref, SODIUM_C99(.stream_ietf =) stream_ietf_ref, SODIUM_C99(.stream_xor_ic =) stream_ref_xor_ic, SODIUM_C99(.stream_ietf_xor_ic =) stream_ietf_ref_xor_ic };
gpl-3.0
andrepan/vsprog
dongle/firmware/USB_TO_XXX/USB_TO_PWM.c
23
3330
/************************************************************************** * Copyright (C) 2008 - 2010 by Simon Qian * * SimonQian@SimonQian.com * * * * Project: Versaloon * * File: USB_TO_PWM.c * * Author: SimonQian * * Versaion: See changelog * * Purpose: implementation file for USB_TO_PWM * * License: See license * *------------------------------------------------------------------------* * Change Log: * * YYYY-MM-DD: What(by Who) * * 2008-11-07: created(by SimonQian) * **************************************************************************/ #include "app_cfg.h" #if USB_TO_PWM_EN #include "USB_TO_XXX.h" #include "app_interfaces.h" void USB_TO_PWM_ProcessCmd(uint8_t *dat, uint16_t len) { uint16_t index, length; uint8_t command, device_idx; uint16_t kHz, count; uint8_t mode; index = 0; while(index < len) { command = dat[index] & USB_TO_XXX_CMDMASK; device_idx = dat[index] & USB_TO_XXX_IDXMASK; length = GET_LE_U16(&dat[index + 1]); index += 3; switch(command) { case USB_TO_XXX_INIT: if (app_interfaces.pwm.init(device_idx)) { buffer_reply[rep_len++] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len++] = USB_TO_XXX_OK; } break; case USB_TO_XXX_CONFIG: mode = dat[index]; if (app_interfaces.pwm.config_mode(device_idx, mode)) { buffer_reply[rep_len++] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len++] = USB_TO_XXX_OK; } break; case USB_TO_XXX_FINI: if (app_interfaces.pwm.fini(device_idx)) { buffer_reply[rep_len++] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len++] = USB_TO_XXX_OK; } break; case USB_TO_XXX_OUT: count = GET_LE_U16(&dat[index + 0]); if (app_interfaces.pwm.out(device_idx, count, (uint16_t *)&dat[index + 2])) { buffer_reply[rep_len++] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len++] = USB_TO_XXX_OK; } break; case USB_TO_XXX_IN: count = GET_LE_U16(&dat[index + 0]); if (app_interfaces.pwm.in(device_idx, count, (uint16_t *)&buffer_reply[rep_len + 1])) { buffer_reply[rep_len] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len] = USB_TO_XXX_OK; } rep_len += 1 + 4 * count; break; case USB_TO_XXX_SYNC: kHz = GET_LE_U16(&dat[index]); if (app_interfaces.pwm.config_freq(device_idx, kHz)) { buffer_reply[rep_len++] = USB_TO_XXX_FAILED; } else { buffer_reply[rep_len++] = USB_TO_XXX_OK; } break; default: buffer_reply[rep_len++] = USB_TO_XXX_CMD_NOT_SUPPORT; break; } index += length; } } #endif
gpl-3.0
r0mai/metashell
3rd/templight/clang/test/OpenMP/target_teams_distribute_parallel_for_simd_is_device_ptr_ast_print.cpp
23
9884
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // RUN: %clang_cc1 -verify -fopenmp-simd -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp-simd -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int da[5] = { 0 }; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(g) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(rg) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; return; } }; // CHECK: struct SA // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: ST g[10]; // CHECK-NEXT: STarr &rg = this->g; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = this->i; // CHECK-NEXT: int *k = &this->j; // CHECK-NEXT: int *&z = this->k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: arr &raa = this->aa; // CHECK-NEXT: func( // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->k){{$}} // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->g) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->rg) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T> T tmain(T argc) { const T da[5] = { 0 }; S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; return 0; } // CHECK: template<> int tmain<int>(int argc) { // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK: template<> int *tmain<int *>(int *argc) { // CHECK-NEXT: int *const da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int *i; // CHECK-NEXT: int *&j = i; // CHECK-NEXT: int **k = &j; // CHECK-NEXT: int **&z = k; // CHECK-NEXT: int *aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-LABEL: int main(int argc, char **argv) { int main(int argc, char **argv) { const int da[5] = { 0 }; S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; return tmain<int>(argc) + *tmain<int *>(&argc); } #endif
gpl-3.0
DD4WH/mchf-github
mchf-eclipse/basesw/ovi40/Drivers/CMSIS/DSP_Lib/Source/MatrixFunctions/arm_mat_cmplx_mult_q15.c
279
13606
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_cmplx_mat_mult_q15.c * * Description: Q15 complex matrix multiplication. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * 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 ARM LIMITED 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 "arm_math.h" /** * @ingroup groupMatrix */ /** * @addtogroup CmplxMatrixMult * @{ */ /** * @brief Q15 Complex matrix multiplication * @param[in] *pSrcA points to the first input complex matrix structure * @param[in] *pSrcB points to the second input complex matrix structure * @param[out] *pDst points to output complex matrix structure * @param[in] *pScratch points to the array for storing intermediate results * @return The function returns either * <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking. * * \par Conditions for optimum performance * Input, output and state buffers should be aligned by 32-bit * * \par Restrictions * If the silicon does not support unaligned memory access enable the macro UNALIGNED_SUPPORT_DISABLE * In this case input, output, scratch buffers should be aligned by 32-bit * * @details * <b>Scaling and Overflow Behavior:</b> * * \par * The function is implemented using a 64-bit internal accumulator. The inputs to the * multiplications are in 1.15 format and multiplications yield a 2.30 result. * The 2.30 intermediate * results are accumulated in a 64-bit accumulator in 34.30 format. This approach * provides 33 guard bits and there is no risk of overflow. The 34.30 result is then * truncated to 34.15 format by discarding the low 15 bits and then saturated to * 1.15 format. * * \par * Refer to <code>arm_mat_mult_fast_q15()</code> for a faster but less precise version of this function. * */ arm_status arm_mat_cmplx_mult_q15( const arm_matrix_instance_q15 * pSrcA, const arm_matrix_instance_q15 * pSrcB, arm_matrix_instance_q15 * pDst, q15_t * pScratch) { /* accumulator */ q15_t *pSrcBT = pScratch; /* input data matrix pointer for transpose */ q15_t *pInA = pSrcA->pData; /* input data matrix pointer A of Q15 type */ q15_t *pInB = pSrcB->pData; /* input data matrix pointer B of Q15 type */ q15_t *px; /* Temporary output data matrix pointer */ uint16_t numRowsA = pSrcA->numRows; /* number of rows of input matrix A */ uint16_t numColsB = pSrcB->numCols; /* number of columns of input matrix B */ uint16_t numColsA = pSrcA->numCols; /* number of columns of input matrix A */ uint16_t numRowsB = pSrcB->numRows; /* number of rows of input matrix A */ uint16_t col, i = 0u, row = numRowsB, colCnt; /* loop counters */ arm_status status; /* status of matrix multiplication */ q63_t sumReal, sumImag; #ifdef UNALIGNED_SUPPORT_DISABLE q15_t in; /* Temporary variable to hold the input value */ q15_t a, b, c, d; #else q31_t in; /* Temporary variable to hold the input value */ q31_t prod1, prod2; q31_t pSourceA, pSourceB; #endif #ifdef ARM_MATH_MATRIX_CHECK /* Check for matrix mismatch condition */ if((pSrcA->numCols != pSrcB->numRows) || (pSrcA->numRows != pDst->numRows) || (pSrcB->numCols != pDst->numCols)) { /* Set status as ARM_MATH_SIZE_MISMATCH */ status = ARM_MATH_SIZE_MISMATCH; } else #endif { /* Matrix transpose */ do { /* Apply loop unrolling and exchange the columns with row elements */ col = numColsB >> 2; /* The pointer px is set to starting address of the column being processed */ px = pSrcBT + i; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while(col > 0u) { #ifdef UNALIGNED_SUPPORT_DISABLE /* Read two elements from the row */ in = *pInB++; *px = in; in = *pInB++; px[1] = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *pInB++; *px = in; in = *pInB++; px[1] = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *pInB++; *px = in; in = *pInB++; px[1] = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *pInB++; *px = in; in = *pInB++; px[1] = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Decrement the column loop counter */ col--; } /* If the columns of pSrcB is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ col = numColsB % 0x4u; while(col > 0u) { /* Read two elements from the row */ in = *pInB++; *px = in; in = *pInB++; px[1] = in; #else /* Read two elements from the row */ in = *__SIMD32(pInB)++; *__SIMD32(px) = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *__SIMD32(pInB)++; *__SIMD32(px) = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *__SIMD32(pInB)++; *__SIMD32(px) = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Read two elements from the row */ in = *__SIMD32(pInB)++; *__SIMD32(px) = in; /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Decrement the column loop counter */ col--; } /* If the columns of pSrcB is not a multiple of 4, compute any remaining output samples here. ** No loop unrolling is used. */ col = numColsB % 0x4u; while(col > 0u) { /* Read two elements from the row */ in = *__SIMD32(pInB)++; *__SIMD32(px) = in; #endif /* Update the pointer px to point to the next row of the transposed matrix */ px += numRowsB * 2; /* Decrement the column loop counter */ col--; } i = i + 2u; /* Decrement the row loop counter */ row--; } while(row > 0u); /* Reset the variables for the usage in the following multiplication process */ row = numRowsA; i = 0u; px = pDst->pData; /* The following loop performs the dot-product of each row in pSrcA with each column in pSrcB */ /* row loop */ do { /* For every row wise process, the column loop counter is to be initiated */ col = numColsB; /* For every row wise process, the pIn2 pointer is set ** to the starting address of the transposed pSrcB data */ pInB = pSrcBT; /* column loop */ do { /* Set the variable sum, that acts as accumulator, to zero */ sumReal = 0; sumImag = 0; /* Apply loop unrolling and compute 2 MACs simultaneously. */ colCnt = numColsA >> 1; /* Initiate the pointer pIn1 to point to the starting address of the column being processed */ pInA = pSrcA->pData + i * 2; /* matrix multiplication */ while(colCnt > 0u) { /* c(m,n) = a(1,1)*b(1,1) + a(1,2) * b(2,1) + .... + a(m,p)*b(p,n) */ #ifdef UNALIGNED_SUPPORT_DISABLE /* read real and imag values from pSrcA buffer */ a = *pInA; b = *(pInA + 1u); /* read real and imag values from pSrcB buffer */ c = *pInB; d = *(pInB + 1u); /* Multiply and Accumlates */ sumReal += (q31_t) a *c; sumImag += (q31_t) a *d; sumReal -= (q31_t) b *d; sumImag += (q31_t) b *c; /* read next real and imag values from pSrcA buffer */ a = *(pInA + 2u); b = *(pInA + 3u); /* read next real and imag values from pSrcB buffer */ c = *(pInB + 2u); d = *(pInB + 3u); /* update pointer */ pInA += 4u; /* Multiply and Accumlates */ sumReal += (q31_t) a *c; sumImag += (q31_t) a *d; sumReal -= (q31_t) b *d; sumImag += (q31_t) b *c; /* update pointer */ pInB += 4u; #else /* read real and imag values from pSrcA and pSrcB buffer */ pSourceA = *__SIMD32(pInA)++; pSourceB = *__SIMD32(pInB)++; /* Multiply and Accumlates */ #ifdef ARM_MATH_BIG_ENDIAN prod1 = -__SMUSD(pSourceA, pSourceB); #else prod1 = __SMUSD(pSourceA, pSourceB); #endif prod2 = __SMUADX(pSourceA, pSourceB); sumReal += (q63_t) prod1; sumImag += (q63_t) prod2; /* read real and imag values from pSrcA and pSrcB buffer */ pSourceA = *__SIMD32(pInA)++; pSourceB = *__SIMD32(pInB)++; /* Multiply and Accumlates */ #ifdef ARM_MATH_BIG_ENDIAN prod1 = -__SMUSD(pSourceA, pSourceB); #else prod1 = __SMUSD(pSourceA, pSourceB); #endif prod2 = __SMUADX(pSourceA, pSourceB); sumReal += (q63_t) prod1; sumImag += (q63_t) prod2; #endif /* #ifdef UNALIGNED_SUPPORT_DISABLE */ /* Decrement the loop counter */ colCnt--; } /* process odd column samples */ if((numColsA & 0x1u) > 0u) { /* c(m,n) = a(1,1)*b(1,1) + a(1,2) * b(2,1) + .... + a(m,p)*b(p,n) */ #ifdef UNALIGNED_SUPPORT_DISABLE /* read real and imag values from pSrcA and pSrcB buffer */ a = *pInA++; b = *pInA++; c = *pInB++; d = *pInB++; /* Multiply and Accumlates */ sumReal += (q31_t) a *c; sumImag += (q31_t) a *d; sumReal -= (q31_t) b *d; sumImag += (q31_t) b *c; #else /* read real and imag values from pSrcA and pSrcB buffer */ pSourceA = *__SIMD32(pInA)++; pSourceB = *__SIMD32(pInB)++; /* Multiply and Accumlates */ #ifdef ARM_MATH_BIG_ENDIAN prod1 = -__SMUSD(pSourceA, pSourceB); #else prod1 = __SMUSD(pSourceA, pSourceB); #endif prod2 = __SMUADX(pSourceA, pSourceB); sumReal += (q63_t) prod1; sumImag += (q63_t) prod2; #endif /* #ifdef UNALIGNED_SUPPORT_DISABLE */ } /* Saturate and store the result in the destination buffer */ *px++ = (q15_t) (__SSAT(sumReal >> 15, 16)); *px++ = (q15_t) (__SSAT(sumImag >> 15, 16)); /* Decrement the column loop counter */ col--; } while(col > 0u); i = i + numColsA; /* Decrement the row loop counter */ row--; } while(row > 0u); /* set status as ARM_MATH_SUCCESS */ status = ARM_MATH_SUCCESS; } /* Return to application */ return (status); } /** * @} end of MatrixMult group */
gpl-3.0
endisd/samba
source4/auth/kerberos/kerberos.c
24
3617
/* Unix SMB/CIFS implementation. kerberos utility library Copyright (C) Andrew Tridgell 2001 Copyright (C) Remus Koos 2001 Copyright (C) Nalin Dahyabhai 2004. Copyright (C) Jeremy Allison 2004. Copyright (C) Andrew Bartlett <abartlet@samba.org> 2004-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 "system/kerberos.h" #include "auth/kerberos/kerberos.h" #ifdef HAVE_KRB5 /* simulate a kinit, putting the tgt in the given credentials cache. Orignally by remus@snapserver.com This version is built to use a keyblock, rather than needing the original password. */ krb5_error_code kerberos_kinit_keyblock_cc(krb5_context ctx, krb5_ccache cc, krb5_principal principal, krb5_keyblock *keyblock, time_t *expire_time, time_t *kdc_time) { krb5_error_code code = 0; krb5_creds my_creds; krb5_get_init_creds_opt *options; if ((code = krb5_get_init_creds_opt_alloc(ctx, &options))) { return code; } krb5_get_init_creds_opt_set_default_flags(ctx, NULL, NULL, options); if ((code = krb5_get_init_creds_keyblock(ctx, &my_creds, principal, keyblock, 0, NULL, options))) { return code; } if ((code = krb5_cc_initialize(ctx, cc, principal))) { krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return code; } if ((code = krb5_cc_store_cred(ctx, cc, &my_creds))) { krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return code; } if (expire_time) { *expire_time = (time_t) my_creds.times.endtime; } if (kdc_time) { *kdc_time = (time_t) my_creds.times.starttime; } krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return 0; } /* simulate a kinit, putting the tgt in the given credentials cache. Orignally by remus@snapserver.com */ krb5_error_code kerberos_kinit_password_cc(krb5_context ctx, krb5_ccache cc, krb5_principal principal, const char *password, time_t *expire_time, time_t *kdc_time) { krb5_error_code code = 0; krb5_creds my_creds; krb5_get_init_creds_opt *options; if ((code = krb5_get_init_creds_opt_alloc(ctx, &options))) { return code; } krb5_get_init_creds_opt_set_default_flags(ctx, NULL, NULL, options); if ((code = krb5_get_init_creds_password(ctx, &my_creds, principal, password, NULL, NULL, 0, NULL, options))) { return code; } if ((code = krb5_cc_initialize(ctx, cc, principal))) { krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return code; } if ((code = krb5_cc_store_cred(ctx, cc, &my_creds))) { krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return code; } if (expire_time) { *expire_time = (time_t) my_creds.times.endtime; } if (kdc_time) { *kdc_time = (time_t) my_creds.times.starttime; } krb5_get_init_creds_opt_free(ctx, options); krb5_free_cred_contents(ctx, &my_creds); return 0; } #endif
gpl-3.0
error414/cleanflight
lib/main/DSP_Lib/Source/FilteringFunctions/arm_biquad_cascade_df2T_f32.c
280
19341
/* ---------------------------------------------------------------------- * Copyright (C) 2010-2014 ARM Limited. All rights reserved. * * $Date: 19. March 2015 * $Revision: V.1.4.5 * * Project: CMSIS DSP Library * Title: arm_biquad_cascade_df2T_f32.c * * Description: Processing function for the floating-point transposed * direct form II Biquad cascade filter. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * 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 ARM LIMITED 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 "arm_math.h" /** * @ingroup groupFilters */ /** * @defgroup BiquadCascadeDF2T Biquad Cascade IIR Filters Using a Direct Form II Transposed Structure * * This set of functions implements arbitrary order recursive (IIR) filters using a transposed direct form II structure. * The filters are implemented as a cascade of second order Biquad sections. * These functions provide a slight memory savings as compared to the direct form I Biquad filter functions. * Only floating-point data is supported. * * This function operate on blocks of input and output data and each call to the function * processes <code>blockSize</code> samples through the filter. * <code>pSrc</code> points to the array of input data and * <code>pDst</code> points to the array of output data. * Both arrays contain <code>blockSize</code> values. * * \par Algorithm * Each Biquad stage implements a second order filter using the difference equation: * <pre> * y[n] = b0 * x[n] + d1 * d1 = b1 * x[n] + a1 * y[n] + d2 * d2 = b2 * x[n] + a2 * y[n] * </pre> * where d1 and d2 represent the two state values. * * \par * A Biquad filter using a transposed Direct Form II structure is shown below. * \image html BiquadDF2Transposed.gif "Single transposed Direct Form II Biquad" * Coefficients <code>b0, b1, and b2 </code> multiply the input signal <code>x[n]</code> and are referred to as the feedforward coefficients. * Coefficients <code>a1</code> and <code>a2</code> multiply the output signal <code>y[n]</code> and are referred to as the feedback coefficients. * Pay careful attention to the sign of the feedback coefficients. * Some design tools flip the sign of the feedback coefficients: * <pre> * y[n] = b0 * x[n] + d1; * d1 = b1 * x[n] - a1 * y[n] + d2; * d2 = b2 * x[n] - a2 * y[n]; * </pre> * In this case the feedback coefficients <code>a1</code> and <code>a2</code> must be negated when used with the CMSIS DSP Library. * * \par * Higher order filters are realized as a cascade of second order sections. * <code>numStages</code> refers to the number of second order stages used. * For example, an 8th order filter would be realized with <code>numStages=4</code> second order stages. * A 9th order filter would be realized with <code>numStages=5</code> second order stages with the * coefficients for one of the stages configured as a first order filter (<code>b2=0</code> and <code>a2=0</code>). * * \par * <code>pState</code> points to the state variable array. * Each Biquad stage has 2 state variables <code>d1</code> and <code>d2</code>. * The state variables are arranged in the <code>pState</code> array as: * <pre> * {d11, d12, d21, d22, ...} * </pre> * where <code>d1x</code> refers to the state variables for the first Biquad and * <code>d2x</code> refers to the state variables for the second Biquad. * The state array has a total length of <code>2*numStages</code> values. * The state variables are updated after each block of data is processed; the coefficients are untouched. * * \par * The CMSIS library contains Biquad filters in both Direct Form I and transposed Direct Form II. * The advantage of the Direct Form I structure is that it is numerically more robust for fixed-point data types. * That is why the Direct Form I structure supports Q15 and Q31 data types. * The transposed Direct Form II structure, on the other hand, requires a wide dynamic range for the state variables <code>d1</code> and <code>d2</code>. * Because of this, the CMSIS library only has a floating-point version of the Direct Form II Biquad. * The advantage of the Direct Form II Biquad is that it requires half the number of state variables, 2 rather than 4, per Biquad stage. * * \par Instance Structure * The coefficients and state variables for a filter are stored together in an instance data structure. * A separate instance structure must be defined for each filter. * Coefficient arrays may be shared among several instances while state variable arrays cannot be shared. * * \par Init Functions * There is also an associated initialization function. * The initialization function performs following operations: * - Sets the values of the internal structure fields. * - Zeros out the values in the state buffer. * To do this manually without calling the init function, assign the follow subfields of the instance structure: * numStages, pCoeffs, pState. Also set all of the values in pState to zero. * * \par * Use of the initialization function is optional. * However, if the initialization function is used, then the instance structure cannot be placed into a const data section. * To place an instance structure into a const data section, the instance structure must be manually initialized. * Set the values in the state buffer to zeros before static initialization. * For example, to statically initialize the instance structure use * <pre> * arm_biquad_cascade_df2T_instance_f32 S1 = {numStages, pState, pCoeffs}; * </pre> * where <code>numStages</code> is the number of Biquad stages in the filter; <code>pState</code> is the address of the state buffer. * <code>pCoeffs</code> is the address of the coefficient buffer; * */ /** * @addtogroup BiquadCascadeDF2T * @{ */ /** * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. * @param[in] *S points to an instance of the filter data structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data * @param[in] blockSize number of samples to process. * @return none. */ LOW_OPTIMIZATION_ENTER void arm_biquad_cascade_df2T_f32( const arm_biquad_cascade_df2T_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize) { float32_t *pIn = pSrc; /* source pointer */ float32_t *pOut = pDst; /* destination pointer */ float32_t *pState = S->pState; /* State pointer */ float32_t *pCoeffs = S->pCoeffs; /* coefficient pointer */ float32_t acc1; /* accumulator */ float32_t b0, b1, b2, a1, a2; /* Filter coefficients */ float32_t Xn1; /* temporary input */ float32_t d1, d2; /* state variables */ uint32_t sample, stage = S->numStages; /* loop counters */ #if defined(ARM_MATH_CM7) float32_t Xn2, Xn3, Xn4, Xn5, Xn6, Xn7, Xn8; /* Input State variables */ float32_t Xn9, Xn10, Xn11, Xn12, Xn13, Xn14, Xn15, Xn16; float32_t acc2, acc3, acc4, acc5, acc6, acc7; /* Simulates the accumulator */ float32_t acc8, acc9, acc10, acc11, acc12, acc13, acc14, acc15, acc16; do { /* Reading the coefficients */ b0 = pCoeffs[0]; b1 = pCoeffs[1]; b2 = pCoeffs[2]; a1 = pCoeffs[3]; /* Apply loop unrolling and compute 16 output values simultaneously. */ sample = blockSize >> 4u; a2 = pCoeffs[4]; /*Reading the state values */ d1 = pState[0]; d2 = pState[1]; pCoeffs += 5u; /* First part of the processing with loop unrolling. Compute 16 outputs at a time. ** a second loop below computes the remaining 1 to 15 samples. */ while(sample > 0u) { /* y[n] = b0 * x[n] + d1 */ /* d1 = b1 * x[n] + a1 * y[n] + d2 */ /* d2 = b2 * x[n] + a2 * y[n] */ /* Read the first 2 inputs. 2 cycles */ Xn1 = pIn[0 ]; Xn2 = pIn[1 ]; /* Sample 1. 5 cycles */ Xn3 = pIn[2 ]; acc1 = b0 * Xn1 + d1; Xn4 = pIn[3 ]; d1 = b1 * Xn1 + d2; Xn5 = pIn[4 ]; d2 = b2 * Xn1; Xn6 = pIn[5 ]; d1 += a1 * acc1; Xn7 = pIn[6 ]; d2 += a2 * acc1; /* Sample 2. 5 cycles */ Xn8 = pIn[7 ]; acc2 = b0 * Xn2 + d1; Xn9 = pIn[8 ]; d1 = b1 * Xn2 + d2; Xn10 = pIn[9 ]; d2 = b2 * Xn2; Xn11 = pIn[10]; d1 += a1 * acc2; Xn12 = pIn[11]; d2 += a2 * acc2; /* Sample 3. 5 cycles */ Xn13 = pIn[12]; acc3 = b0 * Xn3 + d1; Xn14 = pIn[13]; d1 = b1 * Xn3 + d2; Xn15 = pIn[14]; d2 = b2 * Xn3; Xn16 = pIn[15]; d1 += a1 * acc3; pIn += 16; d2 += a2 * acc3; /* Sample 4. 5 cycles */ acc4 = b0 * Xn4 + d1; d1 = b1 * Xn4 + d2; d2 = b2 * Xn4; d1 += a1 * acc4; d2 += a2 * acc4; /* Sample 5. 5 cycles */ acc5 = b0 * Xn5 + d1; d1 = b1 * Xn5 + d2; d2 = b2 * Xn5; d1 += a1 * acc5; d2 += a2 * acc5; /* Sample 6. 5 cycles */ acc6 = b0 * Xn6 + d1; d1 = b1 * Xn6 + d2; d2 = b2 * Xn6; d1 += a1 * acc6; d2 += a2 * acc6; /* Sample 7. 5 cycles */ acc7 = b0 * Xn7 + d1; d1 = b1 * Xn7 + d2; d2 = b2 * Xn7; d1 += a1 * acc7; d2 += a2 * acc7; /* Sample 8. 5 cycles */ acc8 = b0 * Xn8 + d1; d1 = b1 * Xn8 + d2; d2 = b2 * Xn8; d1 += a1 * acc8; d2 += a2 * acc8; /* Sample 9. 5 cycles */ acc9 = b0 * Xn9 + d1; d1 = b1 * Xn9 + d2; d2 = b2 * Xn9; d1 += a1 * acc9; d2 += a2 * acc9; /* Sample 10. 5 cycles */ acc10 = b0 * Xn10 + d1; d1 = b1 * Xn10 + d2; d2 = b2 * Xn10; d1 += a1 * acc10; d2 += a2 * acc10; /* Sample 11. 5 cycles */ acc11 = b0 * Xn11 + d1; d1 = b1 * Xn11 + d2; d2 = b2 * Xn11; d1 += a1 * acc11; d2 += a2 * acc11; /* Sample 12. 5 cycles */ acc12 = b0 * Xn12 + d1; d1 = b1 * Xn12 + d2; d2 = b2 * Xn12; d1 += a1 * acc12; d2 += a2 * acc12; /* Sample 13. 5 cycles */ acc13 = b0 * Xn13 + d1; d1 = b1 * Xn13 + d2; d2 = b2 * Xn13; pOut[0 ] = acc1 ; d1 += a1 * acc13; pOut[1 ] = acc2 ; d2 += a2 * acc13; /* Sample 14. 5 cycles */ pOut[2 ] = acc3 ; acc14 = b0 * Xn14 + d1; pOut[3 ] = acc4 ; d1 = b1 * Xn14 + d2; pOut[4 ] = acc5 ; d2 = b2 * Xn14; pOut[5 ] = acc6 ; d1 += a1 * acc14; pOut[6 ] = acc7 ; d2 += a2 * acc14; /* Sample 15. 5 cycles */ pOut[7 ] = acc8 ; pOut[8 ] = acc9 ; acc15 = b0 * Xn15 + d1; pOut[9 ] = acc10; d1 = b1 * Xn15 + d2; pOut[10] = acc11; d2 = b2 * Xn15; pOut[11] = acc12; d1 += a1 * acc15; pOut[12] = acc13; d2 += a2 * acc15; /* Sample 16. 5 cycles */ pOut[13] = acc14; acc16 = b0 * Xn16 + d1; pOut[14] = acc15; d1 = b1 * Xn16 + d2; pOut[15] = acc16; d2 = b2 * Xn16; sample--; d1 += a1 * acc16; pOut += 16; d2 += a2 * acc16; } sample = blockSize & 0xFu; while(sample > 0u) { Xn1 = *pIn; acc1 = b0 * Xn1 + d1; pIn++; d1 = b1 * Xn1 + d2; *pOut = acc1; d2 = b2 * Xn1; pOut++; d1 += a1 * acc1; sample--; d2 += a2 * acc1; } /* Store the updated state variables back into the state array */ pState[0] = d1; /* The current stage input is given as the output to the next stage */ pIn = pDst; pState[1] = d2; /* decrement the loop counter */ stage--; pState += 2u; /*Reset the output working pointer */ pOut = pDst; } while(stage > 0u); #elif defined(ARM_MATH_CM0_FAMILY) /* Run the below code for Cortex-M0 */ do { /* Reading the coefficients */ b0 = *pCoeffs++; b1 = *pCoeffs++; b2 = *pCoeffs++; a1 = *pCoeffs++; a2 = *pCoeffs++; /*Reading the state values */ d1 = pState[0]; d2 = pState[1]; sample = blockSize; while(sample > 0u) { /* Read the input */ Xn1 = *pIn++; /* y[n] = b0 * x[n] + d1 */ acc1 = (b0 * Xn1) + d1; /* Store the result in the accumulator in the destination buffer. */ *pOut++ = acc1; /* Every time after the output is computed state should be updated. */ /* d1 = b1 * x[n] + a1 * y[n] + d2 */ d1 = ((b1 * Xn1) + (a1 * acc1)) + d2; /* d2 = b2 * x[n] + a2 * y[n] */ d2 = (b2 * Xn1) + (a2 * acc1); /* decrement the loop counter */ sample--; } /* Store the updated state variables back into the state array */ *pState++ = d1; *pState++ = d2; /* The current stage input is given as the output to the next stage */ pIn = pDst; /*Reset the output working pointer */ pOut = pDst; /* decrement the loop counter */ stage--; } while(stage > 0u); #else float32_t Xn2, Xn3, Xn4; /* Input State variables */ float32_t acc2, acc3, acc4; /* accumulator */ float32_t p0, p1, p2, p3, p4, A1; /* Run the below code for Cortex-M4 and Cortex-M3 */ do { /* Reading the coefficients */ b0 = *pCoeffs++; b1 = *pCoeffs++; b2 = *pCoeffs++; a1 = *pCoeffs++; a2 = *pCoeffs++; /*Reading the state values */ d1 = pState[0]; d2 = pState[1]; /* Apply loop unrolling and compute 4 output values simultaneously. */ sample = blockSize >> 2u; /* First part of the processing with loop unrolling. Compute 4 outputs at a time. ** a second loop below computes the remaining 1 to 3 samples. */ while(sample > 0u) { /* y[n] = b0 * x[n] + d1 */ /* d1 = b1 * x[n] + a1 * y[n] + d2 */ /* d2 = b2 * x[n] + a2 * y[n] */ /* Read the four inputs */ Xn1 = pIn[0]; Xn2 = pIn[1]; Xn3 = pIn[2]; Xn4 = pIn[3]; pIn += 4; p0 = b0 * Xn1; p1 = b1 * Xn1; acc1 = p0 + d1; p0 = b0 * Xn2; p3 = a1 * acc1; p2 = b2 * Xn1; A1 = p1 + p3; p4 = a2 * acc1; d1 = A1 + d2; d2 = p2 + p4; p1 = b1 * Xn2; acc2 = p0 + d1; p0 = b0 * Xn3; p3 = a1 * acc2; p2 = b2 * Xn2; A1 = p1 + p3; p4 = a2 * acc2; d1 = A1 + d2; d2 = p2 + p4; p1 = b1 * Xn3; acc3 = p0 + d1; p0 = b0 * Xn4; p3 = a1 * acc3; p2 = b2 * Xn3; A1 = p1 + p3; p4 = a2 * acc3; d1 = A1 + d2; d2 = p2 + p4; acc4 = p0 + d1; p1 = b1 * Xn4; p3 = a1 * acc4; p2 = b2 * Xn4; A1 = p1 + p3; p4 = a2 * acc4; d1 = A1 + d2; d2 = p2 + p4; pOut[0] = acc1; pOut[1] = acc2; pOut[2] = acc3; pOut[3] = acc4; pOut += 4; sample--; } sample = blockSize & 0x3u; while(sample > 0u) { Xn1 = *pIn++; p0 = b0 * Xn1; p1 = b1 * Xn1; acc1 = p0 + d1; p3 = a1 * acc1; p2 = b2 * Xn1; A1 = p1 + p3; p4 = a2 * acc1; d1 = A1 + d2; d2 = p2 + p4; *pOut++ = acc1; sample--; } /* Store the updated state variables back into the state array */ *pState++ = d1; *pState++ = d2; /* The current stage input is given as the output to the next stage */ pIn = pDst; /*Reset the output working pointer */ pOut = pDst; /* decrement the loop counter */ stage--; } while(stage > 0u); #endif } LOW_OPTIMIZATION_EXIT /** * @} end of BiquadCascadeDF2T group */
gpl-3.0
Pierre-A/cleanflight
src/main/drivers/adc_stm32f10x.c
30
5914
/* * This file is part of Cleanflight. * * Cleanflight 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. * * Cleanflight 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 Cleanflight. If not, see <http://www.gnu.org/licenses/>. */ #include <stdbool.h> #include <stdint.h> #include <string.h> #include "platform.h" #include "build_config.h" #include "system.h" #include "sensors/sensors.h" // FIXME dependency into the main code #include "sensor.h" #include "accgyro.h" #include "adc.h" #include "adc_impl.h" #ifndef ADC_INSTANCE #define ADC_INSTANCE ADC1 #define ADC_ABP2_PERIPHERAL RCC_APB2Periph_ADC1 #define ADC_AHB_PERIPHERAL RCC_AHBPeriph_DMA1 #define ADC_DMA_CHANNEL DMA1_Channel1 #endif // Driver for STM32F103CB onboard ADC // // Naze32 // Battery Voltage (VBAT) is connected to PA4 (ADC1_IN4) with 10k:1k divider // RSSI ADC uses CH2 (PA1, ADC1_IN1) // Current ADC uses CH8 (PB1, ADC1_IN9) // // NAZE rev.5 hardware has PA5 (ADC1_IN5) on breakout pad on bottom of board // void adcInit(drv_adc_config_t *init) { #if defined(CJMCU) || defined(CC3D) UNUSED(init); #endif uint8_t i; uint8_t configuredAdcChannels = 0; memset(&adcConfig, 0, sizeof(adcConfig)); GPIO_InitTypeDef GPIO_InitStructure; GPIO_StructInit(&GPIO_InitStructure); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN; #ifdef VBAT_ADC_GPIO if (init->enableVBat) { GPIO_InitStructure.GPIO_Pin = VBAT_ADC_GPIO_PIN; GPIO_Init(VBAT_ADC_GPIO, &GPIO_InitStructure); adcConfig[ADC_BATTERY].adcChannel = VBAT_ADC_CHANNEL; adcConfig[ADC_BATTERY].dmaIndex = configuredAdcChannels++; adcConfig[ADC_BATTERY].enabled = true; adcConfig[ADC_BATTERY].sampleTime = ADC_SampleTime_239Cycles5; } #endif #ifdef RSSI_ADC_GPIO if (init->enableRSSI) { GPIO_InitStructure.GPIO_Pin = RSSI_ADC_GPIO_PIN; GPIO_Init(RSSI_ADC_GPIO, &GPIO_InitStructure); adcConfig[ADC_RSSI].adcChannel = RSSI_ADC_CHANNEL; adcConfig[ADC_RSSI].dmaIndex = configuredAdcChannels++; adcConfig[ADC_RSSI].enabled = true; adcConfig[ADC_RSSI].sampleTime = ADC_SampleTime_239Cycles5; } #endif #ifdef EXTERNAL1_ADC_GPIO if (init->enableExternal1) { GPIO_InitStructure.GPIO_Pin = EXTERNAL1_ADC_GPIO_PIN; GPIO_Init(EXTERNAL1_ADC_GPIO, &GPIO_InitStructure); adcConfig[ADC_EXTERNAL1].adcChannel = EXTERNAL1_ADC_CHANNEL; adcConfig[ADC_EXTERNAL1].dmaIndex = configuredAdcChannels++; adcConfig[ADC_EXTERNAL1].enabled = true; adcConfig[ADC_EXTERNAL1].sampleTime = ADC_SampleTime_239Cycles5; } #endif #ifdef CURRENT_METER_ADC_GPIO if (init->enableCurrentMeter) { GPIO_InitStructure.GPIO_Pin = CURRENT_METER_ADC_GPIO_PIN; GPIO_Init(CURRENT_METER_ADC_GPIO, &GPIO_InitStructure); adcConfig[ADC_CURRENT].adcChannel = CURRENT_METER_ADC_CHANNEL; adcConfig[ADC_CURRENT].dmaIndex = configuredAdcChannels++; adcConfig[ADC_CURRENT].enabled = true; adcConfig[ADC_CURRENT].sampleTime = ADC_SampleTime_239Cycles5; } #endif RCC_ADCCLKConfig(RCC_PCLK2_Div8); // 9MHz from 72MHz APB2 clock(HSE), 8MHz from 64MHz (HSI) RCC_AHBPeriphClockCmd(ADC_AHB_PERIPHERAL, ENABLE); RCC_APB2PeriphClockCmd(ADC_ABP2_PERIPHERAL, ENABLE); // FIXME ADC driver assumes all the GPIO was already placed in 'AIN' mode DMA_DeInit(ADC_DMA_CHANNEL); DMA_InitTypeDef DMA_InitStructure; DMA_StructInit(&DMA_InitStructure); DMA_InitStructure.DMA_PeripheralBaseAddr = (uint32_t)&ADC_INSTANCE->DR; DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)adcValues; DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC; DMA_InitStructure.DMA_BufferSize = configuredAdcChannels; DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable; DMA_InitStructure.DMA_MemoryInc = configuredAdcChannels > 1 ? DMA_MemoryInc_Enable : DMA_MemoryInc_Disable; DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_HalfWord; DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_HalfWord; DMA_InitStructure.DMA_Mode = DMA_Mode_Circular; DMA_InitStructure.DMA_Priority = DMA_Priority_High; DMA_InitStructure.DMA_M2M = DMA_M2M_Disable; DMA_Init(ADC_DMA_CHANNEL, &DMA_InitStructure); DMA_Cmd(ADC_DMA_CHANNEL, ENABLE); ADC_InitTypeDef ADC_InitStructure; ADC_StructInit(&ADC_InitStructure); ADC_InitStructure.ADC_Mode = ADC_Mode_Independent; ADC_InitStructure.ADC_ScanConvMode = configuredAdcChannels > 1 ? ENABLE : DISABLE; ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = configuredAdcChannels; ADC_Init(ADC_INSTANCE, &ADC_InitStructure); uint8_t rank = 1; for (i = 0; i < ADC_CHANNEL_COUNT; i++) { if (!adcConfig[i].enabled) { continue; } ADC_RegularChannelConfig(ADC_INSTANCE, adcConfig[i].adcChannel, rank++, adcConfig[i].sampleTime); } ADC_DMACmd(ADC_INSTANCE, ENABLE); ADC_Cmd(ADC_INSTANCE, ENABLE); ADC_ResetCalibration(ADC_INSTANCE); while(ADC_GetResetCalibrationStatus(ADC_INSTANCE)); ADC_StartCalibration(ADC_INSTANCE); while(ADC_GetCalibrationStatus(ADC_INSTANCE)); ADC_SoftwareStartConvCmd(ADC_INSTANCE, ENABLE); }
gpl-3.0
FabianKnapp/nexmon
utilities/wireshark/epan/dissectors/packet-dcerpc-rs_plcy.c
32
3215
/* packet-dcerpc-rs_plcy.c * * Routines for dcerpc RS_PLCY dissection * Copyright 2003, Jaime Fournier <Jaime.Fournier@hush.com> * This information is based off the released idl files from opengroup. * ftp://ftp.opengroup.org/pub/dce122/dce/src/security.tar.gz rs_plcy.idl * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include "packet-dcerpc.h" void proto_register_dcerpc_rs_plcy(void); void proto_reg_handoff_dcerpc_rs_plcy(void); /* Global hf index fields */ static int proto_dcerpc_rs_plcy = -1; static int hf_rs_plcy_opnum = -1; static gint ett_dcerpc_rs_plcy = -1; static e_guid_t uuid_dcerpc_rs_plcy = { 0x4c878280, 0x4000, 0x0000, { 0x0D, 0x00, 0x02, 0x87, 0x14, 0x00, 0x00, 0x00 } }; static guint16 ver_dcerpc_rs_plcy = 1; static dcerpc_sub_dissector dcerpc_rs_plcy_dissectors[] = { { 0, "rs_properties_get_info", NULL, NULL }, { 1, "rs_properties_set_info ", NULL, NULL }, { 2, "rs_policy_get_info", NULL, NULL }, { 3, "rs_policy_set_info", NULL, NULL }, { 4, "rs_policy_get_effective", NULL, NULL }, { 5, "rs_policy_get_override_info", NULL, NULL }, { 6, "rs_policy_set_override_info", NULL, NULL }, { 7, "rs_auth_policy_get_info", NULL, NULL }, { 8, "rs_auth_policy_get_effective", NULL, NULL }, { 9, "rs_auth_policy_set_info", NULL, NULL }, { 0, NULL, NULL, NULL } }; void proto_register_dcerpc_rs_plcy(void) { static hf_register_info hf[] = { /* Global indexes */ { &hf_rs_plcy_opnum, { "Operation", "rs_plcy.opnum", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }}, }; static gint *ett[] = { &ett_dcerpc_rs_plcy }; proto_dcerpc_rs_plcy = proto_register_protocol( "RS Interface properties", "RS_PLCY", "rs_plcy"); proto_register_field_array(proto_dcerpc_rs_plcy, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_dcerpc_rs_plcy(void) { /* Register protocol as dcerpc */ dcerpc_init_uuid(proto_dcerpc_rs_plcy, ett_dcerpc_rs_plcy, &uuid_dcerpc_rs_plcy, ver_dcerpc_rs_plcy, dcerpc_rs_plcy_dissectors, hf_rs_plcy_opnum); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
gpl-3.0
terry2012/DECAF
DroidScope/qemu/tcg/tcg.c
37
69216
/* * Tiny Code Generator for QEMU * * Copyright (c) 2008 Fabrice Bellard * * 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. */ /* define it to use liveness analysis (better code) */ #define USE_LIVENESS_ANALYSIS #include "config.h" #if !defined(CONFIG_DEBUG_TCG) && !defined(NDEBUG) /* define it to suppress various consistency checks (faster) */ #define NDEBUG #endif #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <inttypes.h> #ifdef _WIN32 #include <malloc.h> #endif #ifdef _AIX #include <alloca.h> #endif #include "qemu-common.h" #include "cache-utils.h" #include "host-utils.h" #include "qemu-timer.h" /* Note: the long term plan is to reduce the dependancies on the QEMU CPU definitions. Currently they are used for qemu_ld/st instructions */ #define NO_CPU_IO_DEFS #include "cpu.h" #include "exec-all.h" #include "tcg-op.h" #include "elf.h" #if defined(CONFIG_USE_GUEST_BASE) && !defined(TCG_TARGET_HAS_GUEST_BASE) #error GUEST_BASE not supported on this host. #endif static void tcg_target_init(TCGContext *s); static void tcg_target_qemu_prologue(TCGContext *s); static void patch_reloc(uint8_t *code_ptr, int type, tcg_target_long value, tcg_target_long addend); static TCGOpDef tcg_op_defs[] = { #define DEF(s, oargs, iargs, cargs, flags) { #s, oargs, iargs, cargs, iargs + oargs + cargs, flags }, #include "tcg-opc.h" #undef DEF }; static TCGRegSet tcg_target_available_regs[2]; static TCGRegSet tcg_target_call_clobber_regs; /* XXX: move that inside the context */ uint16_t *gen_opc_ptr; TCGArg *gen_opparam_ptr; #ifdef CONFIG_MEMCHECK /* * Memchecker addition in this module is intended to build a map that matches * translated PC to a guest PC. Map is built in tcg_gen_code_common routine, * and is saved into temporary gen_opc_tpc2gpc_ptr array, that later will be * copied into the TranslationBlock that represents the translated code. */ #include "memcheck/memcheck_api.h" #endif // CONFIG_MEMCHECK static inline void tcg_out8(TCGContext *s, uint8_t v) { *s->code_ptr++ = v; } static inline void tcg_out16(TCGContext *s, uint16_t v) { *(uint16_t *)s->code_ptr = v; s->code_ptr += 2; } static inline void tcg_out32(TCGContext *s, uint32_t v) { *(uint32_t *)s->code_ptr = v; s->code_ptr += 4; } /* label relocation processing */ static void tcg_out_reloc(TCGContext *s, uint8_t *code_ptr, int type, int label_index, long addend) { TCGLabel *l; TCGRelocation *r; l = &s->labels[label_index]; if (l->has_value) { /* FIXME: This may break relocations on RISC targets that modify instruction fields in place. The caller may not have written the initial value. */ patch_reloc(code_ptr, type, l->u.value, addend); } else { /* add a new relocation entry */ r = tcg_malloc(sizeof(TCGRelocation)); r->type = type; r->ptr = code_ptr; r->addend = addend; r->next = l->u.first_reloc; l->u.first_reloc = r; } } static void tcg_out_label(TCGContext *s, int label_index, tcg_target_long value) { TCGLabel *l; TCGRelocation *r; l = &s->labels[label_index]; if (l->has_value) tcg_abort(); r = l->u.first_reloc; while (r != NULL) { patch_reloc(r->ptr, r->type, value, r->addend); r = r->next; } l->has_value = 1; l->u.value = value; } int gen_new_label(void) { TCGContext *s = &tcg_ctx; int idx; TCGLabel *l; if (s->nb_labels >= TCG_MAX_LABELS) tcg_abort(); idx = s->nb_labels++; l = &s->labels[idx]; l->has_value = 0; l->u.first_reloc = NULL; return idx; } #include "tcg-target.c" /* pool based memory allocation */ void *tcg_malloc_internal(TCGContext *s, int size) { TCGPool *p; int pool_size; if (size > TCG_POOL_CHUNK_SIZE) { /* big malloc: insert a new pool (XXX: could optimize) */ p = qemu_malloc(sizeof(TCGPool) + size); p->size = size; if (s->pool_current) s->pool_current->next = p; else s->pool_first = p; p->next = s->pool_current; } else { p = s->pool_current; if (!p) { p = s->pool_first; if (!p) goto new_pool; } else { if (!p->next) { new_pool: pool_size = TCG_POOL_CHUNK_SIZE; p = qemu_malloc(sizeof(TCGPool) + pool_size); p->size = pool_size; p->next = NULL; if (s->pool_current) s->pool_current->next = p; else s->pool_first = p; } else { p = p->next; } } } s->pool_current = p; s->pool_cur = p->data + size; s->pool_end = p->data + p->size; return p->data; } void tcg_pool_reset(TCGContext *s) { s->pool_cur = s->pool_end = NULL; s->pool_current = NULL; } void tcg_context_init(TCGContext *s) { int op, total_args, n; TCGOpDef *def; TCGArgConstraint *args_ct; int *sorted_args; memset(s, 0, sizeof(*s)); s->temps = s->static_temps; s->nb_globals = 0; /* Count total number of arguments and allocate the corresponding space */ total_args = 0; for(op = 0; op < NB_OPS; op++) { def = &tcg_op_defs[op]; n = def->nb_iargs + def->nb_oargs; total_args += n; } args_ct = qemu_malloc(sizeof(TCGArgConstraint) * total_args); sorted_args = qemu_malloc(sizeof(int) * total_args); for(op = 0; op < NB_OPS; op++) { def = &tcg_op_defs[op]; def->args_ct = args_ct; def->sorted_args = sorted_args; n = def->nb_iargs + def->nb_oargs; sorted_args += n; args_ct += n; } tcg_target_init(s); } void tcg_prologue_init(TCGContext *s) { /* init global prologue and epilogue */ s->code_buf = code_gen_prologue; s->code_ptr = s->code_buf; tcg_target_qemu_prologue(s); flush_icache_range((unsigned long)s->code_buf, (unsigned long)s->code_ptr); } void tcg_set_frame(TCGContext *s, int reg, tcg_target_long start, tcg_target_long size) { s->frame_start = start; s->frame_end = start + size; s->frame_reg = reg; } void tcg_func_start(TCGContext *s) { int i; tcg_pool_reset(s); s->nb_temps = s->nb_globals; for(i = 0; i < (TCG_TYPE_COUNT * 2); i++) s->first_free_temp[i] = -1; s->labels = tcg_malloc(sizeof(TCGLabel) * TCG_MAX_LABELS); s->nb_labels = 0; s->current_frame_offset = s->frame_start; gen_opc_ptr = gen_opc_buf; gen_opparam_ptr = gen_opparam_buf; } static inline void tcg_temp_alloc(TCGContext *s, int n) { if (n > TCG_MAX_TEMPS) tcg_abort(); } static inline int tcg_global_reg_new_internal(TCGType type, int reg, const char *name) { TCGContext *s = &tcg_ctx; TCGTemp *ts; int idx; #if TCG_TARGET_REG_BITS == 32 if (type != TCG_TYPE_I32) tcg_abort(); #endif if (tcg_regset_test_reg(s->reserved_regs, reg)) tcg_abort(); idx = s->nb_globals; tcg_temp_alloc(s, s->nb_globals + 1); ts = &s->temps[s->nb_globals]; ts->base_type = type; ts->type = type; ts->fixed_reg = 1; ts->reg = reg; ts->name = name; s->nb_globals++; tcg_regset_set_reg(s->reserved_regs, reg); return idx; } TCGv_i32 tcg_global_reg_new_i32(int reg, const char *name) { int idx; idx = tcg_global_reg_new_internal(TCG_TYPE_I32, reg, name); return MAKE_TCGV_I32(idx); } TCGv_i64 tcg_global_reg_new_i64(int reg, const char *name) { int idx; idx = tcg_global_reg_new_internal(TCG_TYPE_I64, reg, name); return MAKE_TCGV_I64(idx); } static inline int tcg_global_mem_new_internal(TCGType type, int reg, tcg_target_long offset, const char *name) { TCGContext *s = &tcg_ctx; TCGTemp *ts; int idx; idx = s->nb_globals; #if TCG_TARGET_REG_BITS == 32 if (type == TCG_TYPE_I64) { char buf[64]; tcg_temp_alloc(s, s->nb_globals + 2); ts = &s->temps[s->nb_globals]; ts->base_type = type; ts->type = TCG_TYPE_I32; ts->fixed_reg = 0; ts->mem_allocated = 1; ts->mem_reg = reg; #ifdef TCG_TARGET_WORDS_BIGENDIAN ts->mem_offset = offset + 4; #else ts->mem_offset = offset; #endif pstrcpy(buf, sizeof(buf), name); pstrcat(buf, sizeof(buf), "_0"); ts->name = strdup(buf); ts++; ts->base_type = type; ts->type = TCG_TYPE_I32; ts->fixed_reg = 0; ts->mem_allocated = 1; ts->mem_reg = reg; #ifdef TCG_TARGET_WORDS_BIGENDIAN ts->mem_offset = offset; #else ts->mem_offset = offset + 4; #endif pstrcpy(buf, sizeof(buf), name); pstrcat(buf, sizeof(buf), "_1"); ts->name = strdup(buf); s->nb_globals += 2; } else #endif { tcg_temp_alloc(s, s->nb_globals + 1); ts = &s->temps[s->nb_globals]; ts->base_type = type; ts->type = type; ts->fixed_reg = 0; ts->mem_allocated = 1; ts->mem_reg = reg; ts->mem_offset = offset; ts->name = name; s->nb_globals++; } return idx; } TCGv_i32 tcg_global_mem_new_i32(int reg, tcg_target_long offset, const char *name) { int idx; idx = tcg_global_mem_new_internal(TCG_TYPE_I32, reg, offset, name); return MAKE_TCGV_I32(idx); } TCGv_i64 tcg_global_mem_new_i64(int reg, tcg_target_long offset, const char *name) { int idx; idx = tcg_global_mem_new_internal(TCG_TYPE_I64, reg, offset, name); return MAKE_TCGV_I64(idx); } static inline int tcg_temp_new_internal(TCGType type, int temp_local) { TCGContext *s = &tcg_ctx; TCGTemp *ts; int idx, k; k = type; if (temp_local) k += TCG_TYPE_COUNT; idx = s->first_free_temp[k]; if (idx != -1) { /* There is already an available temp with the right type */ ts = &s->temps[idx]; s->first_free_temp[k] = ts->next_free_temp; ts->temp_allocated = 1; assert(ts->temp_local == temp_local); } else { idx = s->nb_temps; #if TCG_TARGET_REG_BITS == 32 if (type == TCG_TYPE_I64) { tcg_temp_alloc(s, s->nb_temps + 2); ts = &s->temps[s->nb_temps]; ts->base_type = type; ts->type = TCG_TYPE_I32; ts->temp_allocated = 1; ts->temp_local = temp_local; ts->name = NULL; ts++; ts->base_type = TCG_TYPE_I32; ts->type = TCG_TYPE_I32; ts->temp_allocated = 1; ts->temp_local = temp_local; ts->name = NULL; s->nb_temps += 2; } else #endif { tcg_temp_alloc(s, s->nb_temps + 1); ts = &s->temps[s->nb_temps]; ts->base_type = type; ts->type = type; ts->temp_allocated = 1; ts->temp_local = temp_local; ts->name = NULL; s->nb_temps++; } } #if defined(CONFIG_DEBUG_TCG) s->temps_in_use++; #endif return idx; } TCGv_i32 tcg_temp_new_internal_i32(int temp_local) { int idx; idx = tcg_temp_new_internal(TCG_TYPE_I32, temp_local); return MAKE_TCGV_I32(idx); } TCGv_i64 tcg_temp_new_internal_i64(int temp_local) { int idx; idx = tcg_temp_new_internal(TCG_TYPE_I64, temp_local); return MAKE_TCGV_I64(idx); } static inline void tcg_temp_free_internal(int idx) { TCGContext *s = &tcg_ctx; TCGTemp *ts; int k; #if defined(CONFIG_DEBUG_TCG) s->temps_in_use--; if (s->temps_in_use < 0) { fprintf(stderr, "More temporaries freed than allocated!\n"); } #endif assert(idx >= s->nb_globals && idx < s->nb_temps); ts = &s->temps[idx]; assert(ts->temp_allocated != 0); ts->temp_allocated = 0; k = ts->base_type; if (ts->temp_local) k += TCG_TYPE_COUNT; ts->next_free_temp = s->first_free_temp[k]; s->first_free_temp[k] = idx; } void tcg_temp_free_i32(TCGv_i32 arg) { tcg_temp_free_internal(GET_TCGV_I32(arg)); } void tcg_temp_free_i64(TCGv_i64 arg) { tcg_temp_free_internal(GET_TCGV_I64(arg)); } TCGv_i32 tcg_const_i32(int32_t val) { TCGv_i32 t0; t0 = tcg_temp_new_i32(); tcg_gen_movi_i32(t0, val); return t0; } TCGv_i64 tcg_const_i64(int64_t val) { TCGv_i64 t0; t0 = tcg_temp_new_i64(); tcg_gen_movi_i64(t0, val); return t0; } TCGv_i32 tcg_const_local_i32(int32_t val) { TCGv_i32 t0; t0 = tcg_temp_local_new_i32(); tcg_gen_movi_i32(t0, val); return t0; } TCGv_i64 tcg_const_local_i64(int64_t val) { TCGv_i64 t0; t0 = tcg_temp_local_new_i64(); tcg_gen_movi_i64(t0, val); return t0; } #if defined(CONFIG_DEBUG_TCG) void tcg_clear_temp_count(void) { TCGContext *s = &tcg_ctx; s->temps_in_use = 0; } int tcg_check_temp_count(void) { TCGContext *s = &tcg_ctx; if (s->temps_in_use) { /* Clear the count so that we don't give another * warning immediately next time around. */ s->temps_in_use = 0; return 1; } return 0; } #endif void tcg_register_helper(void *func, const char *name) { TCGContext *s = &tcg_ctx; int n; if ((s->nb_helpers + 1) > s->allocated_helpers) { n = s->allocated_helpers; if (n == 0) { n = 4; } else { n *= 2; } s->helpers = realloc(s->helpers, n * sizeof(TCGHelperInfo)); s->allocated_helpers = n; } s->helpers[s->nb_helpers].func = (tcg_target_ulong)func; s->helpers[s->nb_helpers].name = name; s->nb_helpers++; } /* Note: we convert the 64 bit args to 32 bit and do some alignment and endian swap. Maybe it would be better to do the alignment and endian swap in tcg_reg_alloc_call(). */ void tcg_gen_callN(TCGContext *s, TCGv_ptr func, unsigned int flags, int sizemask, TCGArg ret, int nargs, TCGArg *args) { #ifdef TCG_TARGET_I386 int call_type; #endif int i; int real_args; int nb_rets; TCGArg *nparam; #if defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64 for (i = 0; i < nargs; ++i) { int is_64bit = sizemask & (1 << (i+1)*2); int is_signed = sizemask & (2 << (i+1)*2); if (!is_64bit) { TCGv_i64 temp = tcg_temp_new_i64(); TCGv_i64 orig = MAKE_TCGV_I64(args[i]); if (is_signed) { tcg_gen_ext32s_i64(temp, orig); } else { tcg_gen_ext32u_i64(temp, orig); } args[i] = GET_TCGV_I64(temp); } } #endif /* TCG_TARGET_EXTEND_ARGS */ *gen_opc_ptr++ = INDEX_op_call; nparam = gen_opparam_ptr++; #ifdef TCG_TARGET_I386 call_type = (flags & TCG_CALL_TYPE_MASK); #endif if (ret != TCG_CALL_DUMMY_ARG) { #if TCG_TARGET_REG_BITS < 64 if (sizemask & 1) { #ifdef TCG_TARGET_WORDS_BIGENDIAN *gen_opparam_ptr++ = ret + 1; *gen_opparam_ptr++ = ret; #else *gen_opparam_ptr++ = ret; *gen_opparam_ptr++ = ret + 1; #endif nb_rets = 2; } else #endif { *gen_opparam_ptr++ = ret; nb_rets = 1; } } else { nb_rets = 0; } real_args = 0; for (i = 0; i < nargs; i++) { #if TCG_TARGET_REG_BITS < 64 int is_64bit = sizemask & (1 << (i+1)*2); if (is_64bit) { #ifdef TCG_TARGET_I386 /* REGPARM case: if the third parameter is 64 bit, it is allocated on the stack */ if (i == 2 && call_type == TCG_CALL_TYPE_REGPARM) { call_type = TCG_CALL_TYPE_REGPARM_2; flags = (flags & ~TCG_CALL_TYPE_MASK) | call_type; } #endif #ifdef TCG_TARGET_CALL_ALIGN_ARGS /* some targets want aligned 64 bit args */ if (real_args & 1) { *gen_opparam_ptr++ = TCG_CALL_DUMMY_ARG; real_args++; } #endif /* If stack grows up, then we will be placing successive arguments at lower addresses, which means we need to reverse the order compared to how we would normally treat either big or little-endian. For those arguments that will wind up in registers, this still works for HPPA (the only current STACK_GROWSUP target) since the argument registers are *also* allocated in decreasing order. If another such target is added, this logic may have to get more complicated to differentiate between stack arguments and register arguments. */ #if defined(TCG_TARGET_WORDS_BIGENDIAN) != defined(TCG_TARGET_STACK_GROWSUP) *gen_opparam_ptr++ = args[i] + 1; *gen_opparam_ptr++ = args[i]; #else *gen_opparam_ptr++ = args[i]; *gen_opparam_ptr++ = args[i] + 1; #endif real_args += 2; continue; } #endif /* TCG_TARGET_REG_BITS < 64 */ *gen_opparam_ptr++ = args[i]; real_args++; } *gen_opparam_ptr++ = GET_TCGV_PTR(func); *gen_opparam_ptr++ = flags; *nparam = (nb_rets << 16) | (real_args + 1); /* total parameters, needed to go backward in the instruction stream */ *gen_opparam_ptr++ = 1 + nb_rets + real_args + 3; #if defined(TCG_TARGET_EXTEND_ARGS) && TCG_TARGET_REG_BITS == 64 for (i = 0; i < nargs; ++i) { int is_64bit = sizemask & (1 << (i+1)*2); if (!is_64bit) { TCGv_i64 temp = MAKE_TCGV_I64(args[i]); tcg_temp_free_i64(temp); } } #endif /* TCG_TARGET_EXTEND_ARGS */ } #if TCG_TARGET_REG_BITS == 32 void tcg_gen_shifti_i64(TCGv_i64 ret, TCGv_i64 arg1, int c, int right, int arith) { if (c == 0) { tcg_gen_mov_i32(TCGV_LOW(ret), TCGV_LOW(arg1)); tcg_gen_mov_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1)); } else if (c >= 32) { c -= 32; if (right) { if (arith) { tcg_gen_sari_i32(TCGV_LOW(ret), TCGV_HIGH(arg1), c); tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), 31); } else { tcg_gen_shri_i32(TCGV_LOW(ret), TCGV_HIGH(arg1), c); tcg_gen_movi_i32(TCGV_HIGH(ret), 0); } } else { tcg_gen_shli_i32(TCGV_HIGH(ret), TCGV_LOW(arg1), c); tcg_gen_movi_i32(TCGV_LOW(ret), 0); } } else { TCGv_i32 t0, t1; t0 = tcg_temp_new_i32(); t1 = tcg_temp_new_i32(); if (right) { tcg_gen_shli_i32(t0, TCGV_HIGH(arg1), 32 - c); if (arith) tcg_gen_sari_i32(t1, TCGV_HIGH(arg1), c); else tcg_gen_shri_i32(t1, TCGV_HIGH(arg1), c); tcg_gen_shri_i32(TCGV_LOW(ret), TCGV_LOW(arg1), c); tcg_gen_or_i32(TCGV_LOW(ret), TCGV_LOW(ret), t0); tcg_gen_mov_i32(TCGV_HIGH(ret), t1); } else { tcg_gen_shri_i32(t0, TCGV_LOW(arg1), 32 - c); /* Note: ret can be the same as arg1, so we use t1 */ tcg_gen_shli_i32(t1, TCGV_LOW(arg1), c); tcg_gen_shli_i32(TCGV_HIGH(ret), TCGV_HIGH(arg1), c); tcg_gen_or_i32(TCGV_HIGH(ret), TCGV_HIGH(ret), t0); tcg_gen_mov_i32(TCGV_LOW(ret), t1); } tcg_temp_free_i32(t0); tcg_temp_free_i32(t1); } } #endif static void tcg_reg_alloc_start(TCGContext *s) { int i; TCGTemp *ts; for(i = 0; i < s->nb_globals; i++) { ts = &s->temps[i]; if (ts->fixed_reg) { ts->val_type = TEMP_VAL_REG; } else { ts->val_type = TEMP_VAL_MEM; } } for(i = s->nb_globals; i < s->nb_temps; i++) { ts = &s->temps[i]; ts->val_type = TEMP_VAL_DEAD; ts->mem_allocated = 0; ts->fixed_reg = 0; } for(i = 0; i < TCG_TARGET_NB_REGS; i++) { s->reg_to_temp[i] = -1; } } static char *tcg_get_arg_str_idx(TCGContext *s, char *buf, int buf_size, int idx) { TCGTemp *ts; ts = &s->temps[idx]; if (idx < s->nb_globals) { pstrcpy(buf, buf_size, ts->name); } else { if (ts->temp_local) snprintf(buf, buf_size, "loc%d", idx - s->nb_globals); else snprintf(buf, buf_size, "tmp%d", idx - s->nb_globals); } return buf; } char *tcg_get_arg_str_i32(TCGContext *s, char *buf, int buf_size, TCGv_i32 arg) { return tcg_get_arg_str_idx(s, buf, buf_size, GET_TCGV_I32(arg)); } char *tcg_get_arg_str_i64(TCGContext *s, char *buf, int buf_size, TCGv_i64 arg) { return tcg_get_arg_str_idx(s, buf, buf_size, GET_TCGV_I64(arg)); } static int helper_cmp(const void *p1, const void *p2) { const TCGHelperInfo *th1 = p1; const TCGHelperInfo *th2 = p2; if (th1->func < th2->func) return -1; else if (th1->func == th2->func) return 0; else return 1; } /* find helper definition (Note: A hash table would be better) */ static TCGHelperInfo *tcg_find_helper(TCGContext *s, tcg_target_ulong val) { int m, m_min, m_max; TCGHelperInfo *th; tcg_target_ulong v; if (unlikely(!s->helpers_sorted)) { qsort(s->helpers, s->nb_helpers, sizeof(TCGHelperInfo), helper_cmp); s->helpers_sorted = 1; } /* binary search */ m_min = 0; m_max = s->nb_helpers - 1; while (m_min <= m_max) { m = (m_min + m_max) >> 1; th = &s->helpers[m]; v = th->func; if (v == val) return th; else if (val < v) { m_max = m - 1; } else { m_min = m + 1; } } return NULL; } static const char * const cond_name[] = { [TCG_COND_EQ] = "eq", [TCG_COND_NE] = "ne", [TCG_COND_LT] = "lt", [TCG_COND_GE] = "ge", [TCG_COND_LE] = "le", [TCG_COND_GT] = "gt", [TCG_COND_LTU] = "ltu", [TCG_COND_GEU] = "geu", [TCG_COND_LEU] = "leu", [TCG_COND_GTU] = "gtu" }; void tcg_dump_ops(TCGContext *s, FILE *outfile) { const uint16_t *opc_ptr; const TCGArg *args; TCGArg arg; TCGOpcode c; int i, k, nb_oargs, nb_iargs, nb_cargs, first_insn; const TCGOpDef *def; char buf[128]; first_insn = 1; opc_ptr = gen_opc_buf; args = gen_opparam_buf; while (opc_ptr < gen_opc_ptr) { c = *opc_ptr++; def = &tcg_op_defs[c]; if (c == INDEX_op_debug_insn_start) { uint64_t pc; #if TARGET_LONG_BITS > TCG_TARGET_REG_BITS pc = ((uint64_t)args[1] << 32) | args[0]; #else pc = args[0]; #endif if (!first_insn) fprintf(outfile, "\n"); fprintf(outfile, " ---- 0x%" PRIx64, pc); first_insn = 0; nb_oargs = def->nb_oargs; nb_iargs = def->nb_iargs; nb_cargs = def->nb_cargs; } else if (c == INDEX_op_call) { TCGArg arg; /* variable number of arguments */ arg = *args++; nb_oargs = arg >> 16; nb_iargs = arg & 0xffff; nb_cargs = def->nb_cargs; fprintf(outfile, " %s ", def->name); /* function name */ fprintf(outfile, "%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[nb_oargs + nb_iargs - 1])); /* flags */ fprintf(outfile, ",$0x%" TCG_PRIlx, args[nb_oargs + nb_iargs]); /* nb out args */ fprintf(outfile, ",$%d", nb_oargs); for(i = 0; i < nb_oargs; i++) { fprintf(outfile, ","); fprintf(outfile, "%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[i])); } for(i = 0; i < (nb_iargs - 1); i++) { fprintf(outfile, ","); if (args[nb_oargs + i] == TCG_CALL_DUMMY_ARG) { fprintf(outfile, "<dummy>"); } else { fprintf(outfile, "%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[nb_oargs + i])); } } } else if (c == INDEX_op_movi_i32 #if TCG_TARGET_REG_BITS == 64 || c == INDEX_op_movi_i64 #endif ) { tcg_target_ulong val; TCGHelperInfo *th; nb_oargs = def->nb_oargs; nb_iargs = def->nb_iargs; nb_cargs = def->nb_cargs; fprintf(outfile, " %s %s,$", def->name, tcg_get_arg_str_idx(s, buf, sizeof(buf), args[0])); val = args[1]; th = tcg_find_helper(s, val); if (th) { fprintf(outfile, "%s", th->name); } else { if (c == INDEX_op_movi_i32) fprintf(outfile, "0x%x", (uint32_t)val); else fprintf(outfile, "0x%" PRIx64 , (uint64_t)val); } } else { fprintf(outfile, " %s ", def->name); if (c == INDEX_op_nopn) { /* variable number of arguments */ nb_cargs = *args; nb_oargs = 0; nb_iargs = 0; } else { nb_oargs = def->nb_oargs; nb_iargs = def->nb_iargs; nb_cargs = def->nb_cargs; } k = 0; for(i = 0; i < nb_oargs; i++) { if (k != 0) fprintf(outfile, ","); fprintf(outfile, "%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[k++])); } for(i = 0; i < nb_iargs; i++) { if (k != 0) fprintf(outfile, ","); fprintf(outfile, "%s", tcg_get_arg_str_idx(s, buf, sizeof(buf), args[k++])); } switch (c) { case INDEX_op_brcond_i32: #if TCG_TARGET_REG_BITS == 32 case INDEX_op_brcond2_i32: #elif TCG_TARGET_REG_BITS == 64 case INDEX_op_brcond_i64: #endif case INDEX_op_setcond_i32: #if TCG_TARGET_REG_BITS == 32 case INDEX_op_setcond2_i32: #elif TCG_TARGET_REG_BITS == 64 case INDEX_op_setcond_i64: #endif if (args[k] < ARRAY_SIZE(cond_name) && cond_name[args[k]]) fprintf(outfile, ",%s", cond_name[args[k++]]); else fprintf(outfile, ",$0x%" TCG_PRIlx, args[k++]); i = 1; break; default: i = 0; break; } for(; i < nb_cargs; i++) { if (k != 0) fprintf(outfile, ","); arg = args[k++]; fprintf(outfile, "$0x%" TCG_PRIlx, arg); } } fprintf(outfile, "\n"); args += nb_iargs + nb_oargs + nb_cargs; } } /* we give more priority to constraints with less registers */ static int get_constraint_priority(const TCGOpDef *def, int k) { const TCGArgConstraint *arg_ct; int i, n; arg_ct = &def->args_ct[k]; if (arg_ct->ct & TCG_CT_ALIAS) { /* an alias is equivalent to a single register */ n = 1; } else { if (!(arg_ct->ct & TCG_CT_REG)) return 0; n = 0; for(i = 0; i < TCG_TARGET_NB_REGS; i++) { if (tcg_regset_test_reg(arg_ct->u.regs, i)) n++; } } return TCG_TARGET_NB_REGS - n + 1; } /* sort from highest priority to lowest */ static void sort_constraints(TCGOpDef *def, int start, int n) { int i, j, p1, p2, tmp; for(i = 0; i < n; i++) def->sorted_args[start + i] = start + i; if (n <= 1) return; for(i = 0; i < n - 1; i++) { for(j = i + 1; j < n; j++) { p1 = get_constraint_priority(def, def->sorted_args[start + i]); p2 = get_constraint_priority(def, def->sorted_args[start + j]); if (p1 < p2) { tmp = def->sorted_args[start + i]; def->sorted_args[start + i] = def->sorted_args[start + j]; def->sorted_args[start + j] = tmp; } } } } void tcg_add_target_add_op_defs(const TCGTargetOpDef *tdefs) { TCGOpcode op; TCGOpDef *def; const char *ct_str; int i, nb_args; for(;;) { if (tdefs->op == (TCGOpcode)-1) break; op = tdefs->op; assert((unsigned)op < NB_OPS); def = &tcg_op_defs[op]; #if defined(CONFIG_DEBUG_TCG) /* Duplicate entry in op definitions? */ assert(!def->used); def->used = 1; #endif nb_args = def->nb_iargs + def->nb_oargs; for(i = 0; i < nb_args; i++) { ct_str = tdefs->args_ct_str[i]; /* Incomplete TCGTargetOpDef entry? */ assert(ct_str != NULL); tcg_regset_clear(def->args_ct[i].u.regs); def->args_ct[i].ct = 0; if (ct_str[0] >= '0' && ct_str[0] <= '9') { int oarg; oarg = ct_str[0] - '0'; assert(oarg < def->nb_oargs); assert(def->args_ct[oarg].ct & TCG_CT_REG); /* TCG_CT_ALIAS is for the output arguments. The input argument is tagged with TCG_CT_IALIAS. */ def->args_ct[i] = def->args_ct[oarg]; def->args_ct[oarg].ct = TCG_CT_ALIAS; def->args_ct[oarg].alias_index = i; def->args_ct[i].ct |= TCG_CT_IALIAS; def->args_ct[i].alias_index = oarg; } else { for(;;) { if (*ct_str == '\0') break; switch(*ct_str) { case 'i': def->args_ct[i].ct |= TCG_CT_CONST; ct_str++; break; default: if (target_parse_constraint(&def->args_ct[i], &ct_str) < 0) { fprintf(stderr, "Invalid constraint '%s' for arg %d of operation '%s'\n", ct_str, i, def->name); exit(1); } } } } } /* TCGTargetOpDef entry with too much information? */ assert(i == TCG_MAX_OP_ARGS || tdefs->args_ct_str[i] == NULL); /* sort the constraints (XXX: this is just an heuristic) */ sort_constraints(def, 0, def->nb_oargs); sort_constraints(def, def->nb_oargs, def->nb_iargs); #if 0 { int i; printf("%s: sorted=", def->name); for(i = 0; i < def->nb_oargs + def->nb_iargs; i++) printf(" %d", def->sorted_args[i]); printf("\n"); } #endif tdefs++; } #if defined(CONFIG_DEBUG_TCG) i = 0; for (op = 0; op < ARRAY_SIZE(tcg_op_defs); op++) { if (op < INDEX_op_call || op == INDEX_op_debug_insn_start) { /* Wrong entry in op definitions? */ if (tcg_op_defs[op].used) { fprintf(stderr, "Invalid op definition for %s\n", tcg_op_defs[op].name); i = 1; } } else { /* Missing entry in op definitions? */ if (!tcg_op_defs[op].used) { fprintf(stderr, "Missing op definition for %s\n", tcg_op_defs[op].name); i = 1; } } } if (i == 1) { tcg_abort(); } #endif } #ifdef USE_LIVENESS_ANALYSIS /* set a nop for an operation using 'nb_args' */ static inline void tcg_set_nop(TCGContext *s, uint16_t *opc_ptr, TCGArg *args, int nb_args) { if (nb_args == 0) { *opc_ptr = INDEX_op_nop; } else { *opc_ptr = INDEX_op_nopn; args[0] = nb_args; args[nb_args - 1] = nb_args; } } /* liveness analysis: end of function: globals are live, temps are dead. */ /* XXX: at this stage, not used as there would be little gains because most TBs end with a conditional jump. */ static inline void tcg_la_func_end(TCGContext *s, uint8_t *dead_temps) { memset(dead_temps, 0, s->nb_globals); memset(dead_temps + s->nb_globals, 1, s->nb_temps - s->nb_globals); } /* liveness analysis: end of basic block: globals are live, temps are dead, local temps are live. */ static inline void tcg_la_bb_end(TCGContext *s, uint8_t *dead_temps) { int i; TCGTemp *ts; memset(dead_temps, 0, s->nb_globals); ts = &s->temps[s->nb_globals]; for(i = s->nb_globals; i < s->nb_temps; i++) { if (ts->temp_local) dead_temps[i] = 0; else dead_temps[i] = 1; ts++; } } /* Liveness analysis : update the opc_dead_iargs array to tell if a given input arguments is dead. Instructions updating dead temporaries are removed. */ static void tcg_liveness_analysis(TCGContext *s) { int i, op_index, nb_args, nb_iargs, nb_oargs, arg, nb_ops; TCGOpcode op; TCGArg *args; const TCGOpDef *def; uint8_t *dead_temps; unsigned int dead_iargs; /* sanity check */ if (gen_opc_ptr - gen_opc_buf > OPC_BUF_SIZE) { fprintf(stderr, "PANIC: too many opcodes generated (%d > %d)\n", (int)(gen_opc_ptr - gen_opc_buf), OPC_BUF_SIZE); tcg_abort(); } gen_opc_ptr++; /* skip end */ nb_ops = gen_opc_ptr - gen_opc_buf; s->op_dead_iargs = tcg_malloc(nb_ops * sizeof(uint16_t)); dead_temps = tcg_malloc(s->nb_temps); memset(dead_temps, 1, s->nb_temps); args = gen_opparam_ptr; op_index = nb_ops - 1; while (op_index >= 0) { op = gen_opc_buf[op_index]; def = &tcg_op_defs[op]; switch(op) { case INDEX_op_call: { int call_flags; nb_args = args[-1]; args -= nb_args; nb_iargs = args[0] & 0xffff; nb_oargs = args[0] >> 16; args++; call_flags = args[nb_oargs + nb_iargs]; /* pure functions can be removed if their result is not used */ if (call_flags & TCG_CALL_PURE) { for(i = 0; i < nb_oargs; i++) { arg = args[i]; if (!dead_temps[arg]) goto do_not_remove_call; } tcg_set_nop(s, gen_opc_buf + op_index, args - 1, nb_args); } else { do_not_remove_call: /* output args are dead */ for(i = 0; i < nb_oargs; i++) { arg = args[i]; dead_temps[arg] = 1; } if (!(call_flags & TCG_CALL_CONST)) { /* globals are live (they may be used by the call) */ memset(dead_temps, 0, s->nb_globals); } /* input args are live */ dead_iargs = 0; for(i = 0; i < nb_iargs; i++) { arg = args[i + nb_oargs]; if (arg != TCG_CALL_DUMMY_ARG) { if (dead_temps[arg]) { dead_iargs |= (1 << i); } dead_temps[arg] = 0; } } s->op_dead_iargs[op_index] = dead_iargs; } args--; } break; case INDEX_op_set_label: args--; /* mark end of basic block */ tcg_la_bb_end(s, dead_temps); break; case INDEX_op_debug_insn_start: args -= def->nb_args; break; case INDEX_op_nopn: nb_args = args[-1]; args -= nb_args; break; case INDEX_op_discard: args--; /* mark the temporary as dead */ dead_temps[args[0]] = 1; break; case INDEX_op_end: break; /* XXX: optimize by hardcoding common cases (e.g. triadic ops) */ default: args -= def->nb_args; nb_iargs = def->nb_iargs; nb_oargs = def->nb_oargs; /* Test if the operation can be removed because all its outputs are dead. We assume that nb_oargs == 0 implies side effects */ if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) { for(i = 0; i < nb_oargs; i++) { arg = args[i]; if (!dead_temps[arg]) goto do_not_remove; } tcg_set_nop(s, gen_opc_buf + op_index, args, def->nb_args); #ifdef CONFIG_PROFILER s->del_op_count++; #endif } else { do_not_remove: /* output args are dead */ for(i = 0; i < nb_oargs; i++) { arg = args[i]; dead_temps[arg] = 1; } /* if end of basic block, update */ if (def->flags & TCG_OPF_BB_END) { tcg_la_bb_end(s, dead_temps); } else if (def->flags & TCG_OPF_CALL_CLOBBER) { /* globals are live */ memset(dead_temps, 0, s->nb_globals); } /* input args are live */ dead_iargs = 0; for(i = 0; i < nb_iargs; i++) { arg = args[i + nb_oargs]; if (dead_temps[arg]) { dead_iargs |= (1 << i); } dead_temps[arg] = 0; } s->op_dead_iargs[op_index] = dead_iargs; } break; } op_index--; } if (args != gen_opparam_buf) tcg_abort(); } #else /* dummy liveness analysis */ static void tcg_liveness_analysis(TCGContext *s) { int nb_ops; nb_ops = gen_opc_ptr - gen_opc_buf; s->op_dead_iargs = tcg_malloc(nb_ops * sizeof(uint16_t)); memset(s->op_dead_iargs, 0, nb_ops * sizeof(uint16_t)); } #endif #ifndef NDEBUG static void dump_regs(TCGContext *s) { TCGTemp *ts; int i; char buf[64]; for(i = 0; i < s->nb_temps; i++) { ts = &s->temps[i]; printf(" %10s: ", tcg_get_arg_str_idx(s, buf, sizeof(buf), i)); switch(ts->val_type) { case TEMP_VAL_REG: printf("%s", tcg_target_reg_names[ts->reg]); break; case TEMP_VAL_MEM: printf("%d(%s)", (int)ts->mem_offset, tcg_target_reg_names[ts->mem_reg]); break; case TEMP_VAL_CONST: printf("$0x%" TCG_PRIlx, ts->val); break; case TEMP_VAL_DEAD: printf("D"); break; default: printf("???"); break; } printf("\n"); } for(i = 0; i < TCG_TARGET_NB_REGS; i++) { if (s->reg_to_temp[i] >= 0) { printf("%s: %s\n", tcg_target_reg_names[i], tcg_get_arg_str_idx(s, buf, sizeof(buf), s->reg_to_temp[i])); } } } static void check_regs(TCGContext *s) { int reg, k; TCGTemp *ts; char buf[64]; for(reg = 0; reg < TCG_TARGET_NB_REGS; reg++) { k = s->reg_to_temp[reg]; if (k >= 0) { ts = &s->temps[k]; if (ts->val_type != TEMP_VAL_REG || ts->reg != reg) { printf("Inconsistency for register %s:\n", tcg_target_reg_names[reg]); goto fail; } } } for(k = 0; k < s->nb_temps; k++) { ts = &s->temps[k]; if (ts->val_type == TEMP_VAL_REG && !ts->fixed_reg && s->reg_to_temp[ts->reg] != k) { printf("Inconsistency for temp %s:\n", tcg_get_arg_str_idx(s, buf, sizeof(buf), k)); fail: printf("reg state:\n"); dump_regs(s); tcg_abort(); } } } #endif static void temp_allocate_frame(TCGContext *s, int temp) { TCGTemp *ts; ts = &s->temps[temp]; s->current_frame_offset = (s->current_frame_offset + sizeof(tcg_target_long) - 1) & ~(sizeof(tcg_target_long) - 1); if (s->current_frame_offset + sizeof(tcg_target_long) > s->frame_end) tcg_abort(); ts->mem_offset = s->current_frame_offset; ts->mem_reg = s->frame_reg; ts->mem_allocated = 1; s->current_frame_offset += sizeof(tcg_target_long); } /* free register 'reg' by spilling the corresponding temporary if necessary */ static void tcg_reg_free(TCGContext *s, int reg) { TCGTemp *ts; int temp; temp = s->reg_to_temp[reg]; if (temp != -1) { ts = &s->temps[temp]; assert(ts->val_type == TEMP_VAL_REG); if (!ts->mem_coherent) { if (!ts->mem_allocated) temp_allocate_frame(s, temp); tcg_out_st(s, ts->type, reg, ts->mem_reg, ts->mem_offset); } ts->val_type = TEMP_VAL_MEM; s->reg_to_temp[reg] = -1; } } /* Allocate a register belonging to reg1 & ~reg2 */ static int tcg_reg_alloc(TCGContext *s, TCGRegSet reg1, TCGRegSet reg2) { int i, reg; TCGRegSet reg_ct; tcg_regset_andnot(reg_ct, reg1, reg2); /* first try free registers */ for(i = 0; i < ARRAY_SIZE(tcg_target_reg_alloc_order); i++) { reg = tcg_target_reg_alloc_order[i]; if (tcg_regset_test_reg(reg_ct, reg) && s->reg_to_temp[reg] == -1) return reg; } /* XXX: do better spill choice */ for(i = 0; i < ARRAY_SIZE(tcg_target_reg_alloc_order); i++) { reg = tcg_target_reg_alloc_order[i]; if (tcg_regset_test_reg(reg_ct, reg)) { tcg_reg_free(s, reg); return reg; } } tcg_abort(); } /* save a temporary to memory. 'allocated_regs' is used in case a temporary registers needs to be allocated to store a constant. */ static void temp_save(TCGContext *s, int temp, TCGRegSet allocated_regs) { TCGTemp *ts; int reg; ts = &s->temps[temp]; if (!ts->fixed_reg) { switch(ts->val_type) { case TEMP_VAL_REG: tcg_reg_free(s, ts->reg); break; case TEMP_VAL_DEAD: ts->val_type = TEMP_VAL_MEM; break; case TEMP_VAL_CONST: reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type], allocated_regs); if (!ts->mem_allocated) temp_allocate_frame(s, temp); tcg_out_movi(s, ts->type, reg, ts->val); tcg_out_st(s, ts->type, reg, ts->mem_reg, ts->mem_offset); ts->val_type = TEMP_VAL_MEM; break; case TEMP_VAL_MEM: break; default: tcg_abort(); } } } /* save globals to their cannonical location and assume they can be modified be the following code. 'allocated_regs' is used in case a temporary registers needs to be allocated to store a constant. */ static void save_globals(TCGContext *s, TCGRegSet allocated_regs) { int i; for(i = 0; i < s->nb_globals; i++) { temp_save(s, i, allocated_regs); } } /* at the end of a basic block, we assume all temporaries are dead and all globals are stored at their canonical location. */ static void tcg_reg_alloc_bb_end(TCGContext *s, TCGRegSet allocated_regs) { TCGTemp *ts; int i; for(i = s->nb_globals; i < s->nb_temps; i++) { ts = &s->temps[i]; if (ts->temp_local) { temp_save(s, i, allocated_regs); } else { if (ts->val_type == TEMP_VAL_REG) { s->reg_to_temp[ts->reg] = -1; } ts->val_type = TEMP_VAL_DEAD; } } save_globals(s, allocated_regs); } #define IS_DEAD_IARG(n) ((dead_iargs >> (n)) & 1) static void tcg_reg_alloc_movi(TCGContext *s, const TCGArg *args) { TCGTemp *ots; tcg_target_ulong val; ots = &s->temps[args[0]]; val = args[1]; if (ots->fixed_reg) { /* for fixed registers, we do not do any constant propagation */ tcg_out_movi(s, ots->type, ots->reg, val); } else { /* The movi is not explicitly generated here */ if (ots->val_type == TEMP_VAL_REG) s->reg_to_temp[ots->reg] = -1; ots->val_type = TEMP_VAL_CONST; ots->val = val; } } static void tcg_reg_alloc_mov(TCGContext *s, const TCGOpDef *def, const TCGArg *args, unsigned int dead_iargs) { TCGTemp *ts, *ots; int reg; const TCGArgConstraint *arg_ct; ots = &s->temps[args[0]]; ts = &s->temps[args[1]]; arg_ct = &def->args_ct[0]; /* XXX: always mark arg dead if IS_DEAD_IARG(0) */ if (ts->val_type == TEMP_VAL_REG) { if (IS_DEAD_IARG(0) && !ts->fixed_reg && !ots->fixed_reg) { /* the mov can be suppressed */ if (ots->val_type == TEMP_VAL_REG) s->reg_to_temp[ots->reg] = -1; reg = ts->reg; s->reg_to_temp[reg] = -1; ts->val_type = TEMP_VAL_DEAD; } else { if (ots->val_type == TEMP_VAL_REG) { reg = ots->reg; } else { reg = tcg_reg_alloc(s, arg_ct->u.regs, s->reserved_regs); } if (ts->reg != reg) { tcg_out_mov(s, ots->type, reg, ts->reg); } } } else if (ts->val_type == TEMP_VAL_MEM) { if (ots->val_type == TEMP_VAL_REG) { reg = ots->reg; } else { reg = tcg_reg_alloc(s, arg_ct->u.regs, s->reserved_regs); } tcg_out_ld(s, ts->type, reg, ts->mem_reg, ts->mem_offset); } else if (ts->val_type == TEMP_VAL_CONST) { if (ots->fixed_reg) { reg = ots->reg; tcg_out_movi(s, ots->type, reg, ts->val); } else { /* propagate constant */ if (ots->val_type == TEMP_VAL_REG) s->reg_to_temp[ots->reg] = -1; ots->val_type = TEMP_VAL_CONST; ots->val = ts->val; return; } } else { tcg_abort(); } s->reg_to_temp[reg] = args[0]; ots->reg = reg; ots->val_type = TEMP_VAL_REG; ots->mem_coherent = 0; } static void tcg_reg_alloc_op(TCGContext *s, const TCGOpDef *def, TCGOpcode opc, const TCGArg *args, unsigned int dead_iargs) { TCGRegSet allocated_regs; int i, k, nb_iargs, nb_oargs, reg; TCGArg arg; const TCGArgConstraint *arg_ct; TCGTemp *ts; TCGArg new_args[TCG_MAX_OP_ARGS]; int const_args[TCG_MAX_OP_ARGS]; nb_oargs = def->nb_oargs; nb_iargs = def->nb_iargs; /* copy constants */ memcpy(new_args + nb_oargs + nb_iargs, args + nb_oargs + nb_iargs, sizeof(TCGArg) * def->nb_cargs); /* satisfy input constraints */ tcg_regset_set(allocated_regs, s->reserved_regs); for(k = 0; k < nb_iargs; k++) { i = def->sorted_args[nb_oargs + k]; arg = args[i]; arg_ct = &def->args_ct[i]; ts = &s->temps[arg]; if (ts->val_type == TEMP_VAL_MEM) { reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_ld(s, ts->type, reg, ts->mem_reg, ts->mem_offset); ts->val_type = TEMP_VAL_REG; ts->reg = reg; ts->mem_coherent = 1; s->reg_to_temp[reg] = arg; } else if (ts->val_type == TEMP_VAL_CONST) { if (tcg_target_const_match(ts->val, arg_ct)) { /* constant is OK for instruction */ const_args[i] = 1; new_args[i] = ts->val; goto iarg_end; } else { /* need to move to a register */ reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_movi(s, ts->type, reg, ts->val); ts->val_type = TEMP_VAL_REG; ts->reg = reg; ts->mem_coherent = 0; s->reg_to_temp[reg] = arg; } } assert(ts->val_type == TEMP_VAL_REG); if (arg_ct->ct & TCG_CT_IALIAS) { if (ts->fixed_reg) { /* if fixed register, we must allocate a new register if the alias is not the same register */ if (arg != args[arg_ct->alias_index]) goto allocate_in_reg; } else { /* if the input is aliased to an output and if it is not dead after the instruction, we must allocate a new register and move it */ if (!IS_DEAD_IARG(i - nb_oargs)) goto allocate_in_reg; } } reg = ts->reg; if (tcg_regset_test_reg(arg_ct->u.regs, reg)) { /* nothing to do : the constraint is satisfied */ } else { allocate_in_reg: /* allocate a new register matching the constraint and move the temporary register into it */ reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_mov(s, ts->type, reg, ts->reg); } new_args[i] = reg; const_args[i] = 0; tcg_regset_set_reg(allocated_regs, reg); iarg_end: ; } if (def->flags & TCG_OPF_BB_END) { tcg_reg_alloc_bb_end(s, allocated_regs); } else { /* mark dead temporaries and free the associated registers */ for(i = 0; i < nb_iargs; i++) { arg = args[nb_oargs + i]; if (IS_DEAD_IARG(i)) { ts = &s->temps[arg]; if (!ts->fixed_reg) { if (ts->val_type == TEMP_VAL_REG) s->reg_to_temp[ts->reg] = -1; ts->val_type = TEMP_VAL_DEAD; } } } if (def->flags & TCG_OPF_CALL_CLOBBER) { /* XXX: permit generic clobber register list ? */ for(reg = 0; reg < TCG_TARGET_NB_REGS; reg++) { if (tcg_regset_test_reg(tcg_target_call_clobber_regs, reg)) { tcg_reg_free(s, reg); } } /* XXX: for load/store we could do that only for the slow path (i.e. when a memory callback is called) */ /* store globals and free associated registers (we assume the insn can modify any global. */ save_globals(s, allocated_regs); } /* satisfy the output constraints */ tcg_regset_set(allocated_regs, s->reserved_regs); for(k = 0; k < nb_oargs; k++) { i = def->sorted_args[k]; arg = args[i]; arg_ct = &def->args_ct[i]; ts = &s->temps[arg]; if (arg_ct->ct & TCG_CT_ALIAS) { reg = new_args[arg_ct->alias_index]; } else { /* if fixed register, we try to use it */ reg = ts->reg; if (ts->fixed_reg && tcg_regset_test_reg(arg_ct->u.regs, reg)) { goto oarg_end; } reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); } tcg_regset_set_reg(allocated_regs, reg); /* if a fixed register is used, then a move will be done afterwards */ if (!ts->fixed_reg) { if (ts->val_type == TEMP_VAL_REG) s->reg_to_temp[ts->reg] = -1; ts->val_type = TEMP_VAL_REG; ts->reg = reg; /* temp value is modified, so the value kept in memory is potentially not the same */ ts->mem_coherent = 0; s->reg_to_temp[reg] = arg; } oarg_end: new_args[i] = reg; } } /* emit instruction */ tcg_out_op(s, opc, new_args, const_args); /* move the outputs in the correct register if needed */ for(i = 0; i < nb_oargs; i++) { ts = &s->temps[args[i]]; reg = new_args[i]; if (ts->fixed_reg && ts->reg != reg) { tcg_out_mov(s, ts->type, ts->reg, reg); } } } #ifdef TCG_TARGET_STACK_GROWSUP #define STACK_DIR(x) (-(x)) #else #define STACK_DIR(x) (x) #endif static int tcg_reg_alloc_call(TCGContext *s, const TCGOpDef *def, TCGOpcode opc, const TCGArg *args, unsigned int dead_iargs) { int nb_iargs, nb_oargs, flags, nb_regs, i, reg, nb_params; TCGArg arg, func_arg; TCGTemp *ts; tcg_target_long stack_offset, call_stack_size, func_addr; int const_func_arg, allocate_args; TCGRegSet allocated_regs; const TCGArgConstraint *arg_ct; arg = *args++; nb_oargs = arg >> 16; nb_iargs = arg & 0xffff; nb_params = nb_iargs - 1; flags = args[nb_oargs + nb_iargs]; nb_regs = tcg_target_get_call_iarg_regs_count(flags); if (nb_regs > nb_params) nb_regs = nb_params; /* assign stack slots first */ /* XXX: preallocate call stack */ call_stack_size = (nb_params - nb_regs) * sizeof(tcg_target_long); call_stack_size = (call_stack_size + TCG_TARGET_STACK_ALIGN - 1) & ~(TCG_TARGET_STACK_ALIGN - 1); allocate_args = (call_stack_size > TCG_STATIC_CALL_ARGS_SIZE); if (allocate_args) { tcg_out_addi(s, TCG_REG_CALL_STACK, -STACK_DIR(call_stack_size)); } stack_offset = TCG_TARGET_CALL_STACK_OFFSET; for(i = nb_regs; i < nb_params; i++) { arg = args[nb_oargs + i]; #ifdef TCG_TARGET_STACK_GROWSUP stack_offset -= sizeof(tcg_target_long); #endif if (arg != TCG_CALL_DUMMY_ARG) { ts = &s->temps[arg]; if (ts->val_type == TEMP_VAL_REG) { tcg_out_st(s, ts->type, ts->reg, TCG_REG_CALL_STACK, stack_offset); } else if (ts->val_type == TEMP_VAL_MEM) { reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type], s->reserved_regs); /* XXX: not correct if reading values from the stack */ tcg_out_ld(s, ts->type, reg, ts->mem_reg, ts->mem_offset); tcg_out_st(s, ts->type, reg, TCG_REG_CALL_STACK, stack_offset); } else if (ts->val_type == TEMP_VAL_CONST) { reg = tcg_reg_alloc(s, tcg_target_available_regs[ts->type], s->reserved_regs); /* XXX: sign extend may be needed on some targets */ tcg_out_movi(s, ts->type, reg, ts->val); tcg_out_st(s, ts->type, reg, TCG_REG_CALL_STACK, stack_offset); } else { tcg_abort(); } } #ifndef TCG_TARGET_STACK_GROWSUP stack_offset += sizeof(tcg_target_long); #endif } /* assign input registers */ tcg_regset_set(allocated_regs, s->reserved_regs); for(i = 0; i < nb_regs; i++) { arg = args[nb_oargs + i]; if (arg != TCG_CALL_DUMMY_ARG) { ts = &s->temps[arg]; reg = tcg_target_call_iarg_regs[i]; tcg_reg_free(s, reg); if (ts->val_type == TEMP_VAL_REG) { if (ts->reg != reg) { tcg_out_mov(s, ts->type, reg, ts->reg); } } else if (ts->val_type == TEMP_VAL_MEM) { tcg_out_ld(s, ts->type, reg, ts->mem_reg, ts->mem_offset); } else if (ts->val_type == TEMP_VAL_CONST) { /* XXX: sign extend ? */ tcg_out_movi(s, ts->type, reg, ts->val); } else { tcg_abort(); } tcg_regset_set_reg(allocated_regs, reg); } } /* assign function address */ func_arg = args[nb_oargs + nb_iargs - 1]; arg_ct = &def->args_ct[0]; ts = &s->temps[func_arg]; func_addr = ts->val; const_func_arg = 0; if (ts->val_type == TEMP_VAL_MEM) { reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_ld(s, ts->type, reg, ts->mem_reg, ts->mem_offset); func_arg = reg; tcg_regset_set_reg(allocated_regs, reg); } else if (ts->val_type == TEMP_VAL_REG) { reg = ts->reg; if (!tcg_regset_test_reg(arg_ct->u.regs, reg)) { reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_mov(s, ts->type, reg, ts->reg); } func_arg = reg; tcg_regset_set_reg(allocated_regs, reg); } else if (ts->val_type == TEMP_VAL_CONST) { if (tcg_target_const_match(func_addr, arg_ct)) { const_func_arg = 1; func_arg = func_addr; } else { reg = tcg_reg_alloc(s, arg_ct->u.regs, allocated_regs); tcg_out_movi(s, ts->type, reg, func_addr); func_arg = reg; tcg_regset_set_reg(allocated_regs, reg); } } else { tcg_abort(); } /* mark dead temporaries and free the associated registers */ for(i = 0; i < nb_iargs; i++) { arg = args[nb_oargs + i]; if (IS_DEAD_IARG(i)) { ts = &s->temps[arg]; if (!ts->fixed_reg) { if (ts->val_type == TEMP_VAL_REG) s->reg_to_temp[ts->reg] = -1; ts->val_type = TEMP_VAL_DEAD; } } } /* clobber call registers */ for(reg = 0; reg < TCG_TARGET_NB_REGS; reg++) { if (tcg_regset_test_reg(tcg_target_call_clobber_regs, reg)) { tcg_reg_free(s, reg); } } /* store globals and free associated registers (we assume the call can modify any global. */ if (!(flags & TCG_CALL_CONST)) { save_globals(s, allocated_regs); } tcg_out_op(s, opc, &func_arg, &const_func_arg); if (allocate_args) { tcg_out_addi(s, TCG_REG_CALL_STACK, STACK_DIR(call_stack_size)); } /* assign output registers and emit moves if needed */ for(i = 0; i < nb_oargs; i++) { arg = args[i]; ts = &s->temps[arg]; reg = tcg_target_call_oarg_regs[i]; assert(s->reg_to_temp[reg] == -1); if (ts->fixed_reg) { if (ts->reg != reg) { tcg_out_mov(s, ts->type, ts->reg, reg); } } else { if (ts->val_type == TEMP_VAL_REG) s->reg_to_temp[ts->reg] = -1; ts->val_type = TEMP_VAL_REG; ts->reg = reg; ts->mem_coherent = 0; s->reg_to_temp[reg] = arg; } } return nb_iargs + nb_oargs + def->nb_cargs + 1; } #ifdef CONFIG_PROFILER static int64_t tcg_table_op_count[NB_OPS]; static void dump_op_count(void) { int i; FILE *f; f = fopen("/tmp/op.log", "w"); for(i = INDEX_op_end; i < NB_OPS; i++) { fprintf(f, "%s %" PRId64 "\n", tcg_op_defs[i].name, tcg_table_op_count[i]); } fclose(f); } #endif static inline int tcg_gen_code_common(TCGContext *s, uint8_t *gen_code_buf, long search_pc) { TCGOpcode opc; int op_index; const TCGOpDef *def; unsigned int dead_iargs; const TCGArg *args; #ifdef CONFIG_MEMCHECK unsigned int tpc2gpc_index = 0; #endif // CONFIG_MEMCHECK #if !SUPPORT_GLOBAL_REGISTER_VARIABLE printf("ERROR: This emulator is built by compiler without global register variable\n" "support! Emulator reserves a register to point to target architecture state\n" "for better code generation. LLVM-based compilers such as clang and llvm-gcc\n" "currently don't support global register variable. Please see\n" "http://source.android.com/source/initializing.html for detail.\n\n"); tcg_abort(); #endif #ifdef DEBUG_DISAS if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) { qemu_log("OP:\n"); tcg_dump_ops(s, logfile); qemu_log("\n"); } #endif #ifdef CONFIG_PROFILER s->la_time -= profile_getclock(); #endif tcg_liveness_analysis(s); #ifdef CONFIG_PROFILER s->la_time += profile_getclock(); #endif #ifdef DEBUG_DISAS if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) { qemu_log("OP after liveness analysis:\n"); tcg_dump_ops(s, logfile); qemu_log("\n"); } #endif tcg_reg_alloc_start(s); s->code_buf = gen_code_buf; s->code_ptr = gen_code_buf; args = gen_opparam_buf; op_index = 0; #ifdef CONFIG_MEMCHECK gen_opc_tpc2gpc_pairs = 0; #endif // CONFIG_MEMCHECK for(;;) { #ifdef CONFIG_MEMCHECK /* On condition that memcheck is enabled, and operation index reached * new operation in the guest code, save (pc_tb, pc_guest) pair into * gen_opc_tpc2gpc array. Note that we do that only on condition that * search_pc is < 0. This way we make sure that this is "normal" * translation, called from tcg_gen_code, and not from * tcg_gen_code_search_pc. */ if (memcheck_enabled && search_pc < 0 && gen_opc_instr_start[op_index]) { gen_opc_tpc2gpc_ptr[tpc2gpc_index] = s->code_ptr; tpc2gpc_index++; gen_opc_tpc2gpc_ptr[tpc2gpc_index] = (void*)(ptrdiff_t)gen_opc_pc[op_index]; tpc2gpc_index++; gen_opc_tpc2gpc_pairs++; } #endif // CONFIG_MEMCHECK opc = gen_opc_buf[op_index]; #ifdef CONFIG_PROFILER tcg_table_op_count[opc]++; #endif def = &tcg_op_defs[opc]; #if 0 printf("%s: %d %d %d\n", def->name, def->nb_oargs, def->nb_iargs, def->nb_cargs); // dump_regs(s); #endif switch(opc) { case INDEX_op_mov_i32: #if TCG_TARGET_REG_BITS == 64 case INDEX_op_mov_i64: #endif dead_iargs = s->op_dead_iargs[op_index]; tcg_reg_alloc_mov(s, def, args, dead_iargs); break; case INDEX_op_movi_i32: #if TCG_TARGET_REG_BITS == 64 case INDEX_op_movi_i64: #endif tcg_reg_alloc_movi(s, args); break; case INDEX_op_debug_insn_start: /* debug instruction */ break; case INDEX_op_nop: case INDEX_op_nop1: case INDEX_op_nop2: case INDEX_op_nop3: break; case INDEX_op_nopn: args += args[0]; goto next; case INDEX_op_discard: { TCGTemp *ts; ts = &s->temps[args[0]]; /* mark the temporary as dead */ if (!ts->fixed_reg) { if (ts->val_type == TEMP_VAL_REG) s->reg_to_temp[ts->reg] = -1; ts->val_type = TEMP_VAL_DEAD; } } break; case INDEX_op_set_label: tcg_reg_alloc_bb_end(s, s->reserved_regs); tcg_out_label(s, args[0], (long)s->code_ptr); break; case INDEX_op_call: dead_iargs = s->op_dead_iargs[op_index]; args += tcg_reg_alloc_call(s, def, opc, args, dead_iargs); goto next; case INDEX_op_end: goto the_end; default: /* Note: in order to speed up the code, it would be much faster to have specialized register allocator functions for some common argument patterns */ dead_iargs = s->op_dead_iargs[op_index]; tcg_reg_alloc_op(s, def, opc, args, dead_iargs); break; } args += def->nb_args; next: if (search_pc >= 0 && search_pc < s->code_ptr - gen_code_buf) { return op_index; } op_index++; #ifndef NDEBUG check_regs(s); #endif } the_end: return -1; } int tcg_gen_code(TCGContext *s, uint8_t *gen_code_buf) { #ifdef CONFIG_PROFILER { int n; n = (gen_opc_ptr - gen_opc_buf); s->op_count += n; if (n > s->op_count_max) s->op_count_max = n; s->temp_count += s->nb_temps; if (s->nb_temps > s->temp_count_max) s->temp_count_max = s->nb_temps; } #endif /* sanity check */ if (gen_opc_ptr - gen_opc_buf > OPC_BUF_SIZE) { fprintf(stderr, "PANIC: too many opcodes generated (%d > %d)\n", (int)(gen_opc_ptr - gen_opc_buf), OPC_BUF_SIZE); tcg_abort(); } tcg_gen_code_common(s, gen_code_buf, -1); /* flush instruction cache */ flush_icache_range((unsigned long)gen_code_buf, (unsigned long)s->code_ptr); return s->code_ptr - gen_code_buf; } /* Return the index of the micro operation such as the pc after is < offset bytes from the start of the TB. The contents of gen_code_buf must not be changed, though writing the same values is ok. Return -1 if not found. */ int tcg_gen_code_search_pc(TCGContext *s, uint8_t *gen_code_buf, long offset) { return tcg_gen_code_common(s, gen_code_buf, offset); } #ifdef CONFIG_PROFILER void tcg_dump_info(FILE *f, fprintf_function cpu_fprintf) { TCGContext *s = &tcg_ctx; int64_t tot; tot = s->interm_time + s->code_time; cpu_fprintf(f, "JIT cycles %" PRId64 " (%0.3f s at 2.4 GHz)\n", tot, tot / 2.4e9); cpu_fprintf(f, "translated TBs %" PRId64 " (aborted=%" PRId64 " %0.1f%%)\n", s->tb_count, s->tb_count1 - s->tb_count, s->tb_count1 ? (double)(s->tb_count1 - s->tb_count) / s->tb_count1 * 100.0 : 0); cpu_fprintf(f, "avg ops/TB %0.1f max=%d\n", s->tb_count ? (double)s->op_count / s->tb_count : 0, s->op_count_max); cpu_fprintf(f, "deleted ops/TB %0.2f\n", s->tb_count ? (double)s->del_op_count / s->tb_count : 0); cpu_fprintf(f, "avg temps/TB %0.2f max=%d\n", s->tb_count ? (double)s->temp_count / s->tb_count : 0, s->temp_count_max); cpu_fprintf(f, "cycles/op %0.1f\n", s->op_count ? (double)tot / s->op_count : 0); cpu_fprintf(f, "cycles/in byte %0.1f\n", s->code_in_len ? (double)tot / s->code_in_len : 0); cpu_fprintf(f, "cycles/out byte %0.1f\n", s->code_out_len ? (double)tot / s->code_out_len : 0); if (tot == 0) tot = 1; cpu_fprintf(f, " gen_interm time %0.1f%%\n", (double)s->interm_time / tot * 100.0); cpu_fprintf(f, " gen_code time %0.1f%%\n", (double)s->code_time / tot * 100.0); cpu_fprintf(f, "liveness/code time %0.1f%%\n", (double)s->la_time / (s->code_time ? s->code_time : 1) * 100.0); cpu_fprintf(f, "cpu_restore count %" PRId64 "\n", s->restore_count); cpu_fprintf(f, " avg cycles %0.1f\n", s->restore_count ? (double)s->restore_time / s->restore_count : 0); dump_op_count(); } #else void tcg_dump_info(FILE *f, fprintf_function cpu_fprintf) { cpu_fprintf(f, "[TCG profiler not compiled]\n"); } #endif
gpl-3.0
chuncky/nuc900kernel
linux-2.6.35.4/arch/sh/kernel/cpu/sh4a/setup-shx3.c
806
13199
/* * SH-X3 Prototype Setup * * Copyright (C) 2007 - 2009 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/platform_device.h> #include <linux/init.h> #include <linux/serial.h> #include <linux/serial_sci.h> #include <linux/io.h> #include <linux/sh_timer.h> #include <asm/mmzone.h> /* * This intentionally only registers SCIF ports 0, 1, and 3. SCIF 2 * INTEVT values overlap with the FPU EXPEVT ones, requiring special * demuxing in the exception dispatch path. * * As this overlap is something that never should have made it in to * silicon in the first place, we just refuse to deal with the port at * all rather than adding infrastructure to hack around it. */ static struct plat_sci_port scif0_platform_data = { .mapbase = 0xffc30000, .flags = UPF_BOOT_AUTOCONF, .type = PORT_SCIF, .irqs = { 40, 41, 43, 42 }, }; static struct platform_device scif0_device = { .name = "sh-sci", .id = 0, .dev = { .platform_data = &scif0_platform_data, }, }; static struct plat_sci_port scif1_platform_data = { .mapbase = 0xffc40000, .flags = UPF_BOOT_AUTOCONF, .type = PORT_SCIF, .irqs = { 44, 45, 47, 46 }, }; static struct platform_device scif1_device = { .name = "sh-sci", .id = 1, .dev = { .platform_data = &scif1_platform_data, }, }; static struct plat_sci_port scif2_platform_data = { .mapbase = 0xffc60000, .flags = UPF_BOOT_AUTOCONF, .type = PORT_SCIF, .irqs = { 52, 53, 55, 54 }, }; static struct platform_device scif2_device = { .name = "sh-sci", .id = 2, .dev = { .platform_data = &scif2_platform_data, }, }; static struct sh_timer_config tmu0_platform_data = { .channel_offset = 0x04, .timer_bit = 0, .clockevent_rating = 200, }; static struct resource tmu0_resources[] = { [0] = { .start = 0xffc10008, .end = 0xffc10013, .flags = IORESOURCE_MEM, }, [1] = { .start = 16, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu0_device = { .name = "sh_tmu", .id = 0, .dev = { .platform_data = &tmu0_platform_data, }, .resource = tmu0_resources, .num_resources = ARRAY_SIZE(tmu0_resources), }; static struct sh_timer_config tmu1_platform_data = { .channel_offset = 0x10, .timer_bit = 1, .clocksource_rating = 200, }; static struct resource tmu1_resources[] = { [0] = { .start = 0xffc10014, .end = 0xffc1001f, .flags = IORESOURCE_MEM, }, [1] = { .start = 17, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu1_device = { .name = "sh_tmu", .id = 1, .dev = { .platform_data = &tmu1_platform_data, }, .resource = tmu1_resources, .num_resources = ARRAY_SIZE(tmu1_resources), }; static struct sh_timer_config tmu2_platform_data = { .channel_offset = 0x1c, .timer_bit = 2, }; static struct resource tmu2_resources[] = { [0] = { .start = 0xffc10020, .end = 0xffc1002f, .flags = IORESOURCE_MEM, }, [1] = { .start = 18, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu2_device = { .name = "sh_tmu", .id = 2, .dev = { .platform_data = &tmu2_platform_data, }, .resource = tmu2_resources, .num_resources = ARRAY_SIZE(tmu2_resources), }; static struct sh_timer_config tmu3_platform_data = { .channel_offset = 0x04, .timer_bit = 0, }; static struct resource tmu3_resources[] = { [0] = { .start = 0xffc20008, .end = 0xffc20013, .flags = IORESOURCE_MEM, }, [1] = { .start = 19, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu3_device = { .name = "sh_tmu", .id = 3, .dev = { .platform_data = &tmu3_platform_data, }, .resource = tmu3_resources, .num_resources = ARRAY_SIZE(tmu3_resources), }; static struct sh_timer_config tmu4_platform_data = { .channel_offset = 0x10, .timer_bit = 1, }; static struct resource tmu4_resources[] = { [0] = { .start = 0xffc20014, .end = 0xffc2001f, .flags = IORESOURCE_MEM, }, [1] = { .start = 20, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu4_device = { .name = "sh_tmu", .id = 4, .dev = { .platform_data = &tmu4_platform_data, }, .resource = tmu4_resources, .num_resources = ARRAY_SIZE(tmu4_resources), }; static struct sh_timer_config tmu5_platform_data = { .channel_offset = 0x1c, .timer_bit = 2, }; static struct resource tmu5_resources[] = { [0] = { .start = 0xffc20020, .end = 0xffc2002b, .flags = IORESOURCE_MEM, }, [1] = { .start = 21, .flags = IORESOURCE_IRQ, }, }; static struct platform_device tmu5_device = { .name = "sh_tmu", .id = 5, .dev = { .platform_data = &tmu5_platform_data, }, .resource = tmu5_resources, .num_resources = ARRAY_SIZE(tmu5_resources), }; static struct platform_device *shx3_early_devices[] __initdata = { &scif0_device, &scif1_device, &scif2_device, &tmu0_device, &tmu1_device, &tmu2_device, &tmu3_device, &tmu4_device, &tmu5_device, }; static int __init shx3_devices_setup(void) { return platform_add_devices(shx3_early_devices, ARRAY_SIZE(shx3_early_devices)); } arch_initcall(shx3_devices_setup); void __init plat_early_device_setup(void) { early_platform_add_devices(shx3_early_devices, ARRAY_SIZE(shx3_early_devices)); } enum { UNUSED = 0, /* interrupt sources */ IRL_LLLL, IRL_LLLH, IRL_LLHL, IRL_LLHH, IRL_LHLL, IRL_LHLH, IRL_LHHL, IRL_LHHH, IRL_HLLL, IRL_HLLH, IRL_HLHL, IRL_HLHH, IRL_HHLL, IRL_HHLH, IRL_HHHL, IRQ0, IRQ1, IRQ2, IRQ3, HUDII, TMU0, TMU1, TMU2, TMU3, TMU4, TMU5, PCII0, PCII1, PCII2, PCII3, PCII4, PCII5, PCII6, PCII7, PCII8, PCII9, SCIF0_ERI, SCIF0_RXI, SCIF0_BRI, SCIF0_TXI, SCIF1_ERI, SCIF1_RXI, SCIF1_BRI, SCIF1_TXI, SCIF2_ERI, SCIF2_RXI, SCIF2_BRI, SCIF2_TXI, SCIF3_ERI, SCIF3_RXI, SCIF3_BRI, SCIF3_TXI, DMAC0_DMINT0, DMAC0_DMINT1, DMAC0_DMINT2, DMAC0_DMINT3, DMAC0_DMINT4, DMAC0_DMINT5, DMAC0_DMAE, DU, DMAC1_DMINT6, DMAC1_DMINT7, DMAC1_DMINT8, DMAC1_DMINT9, DMAC1_DMINT10, DMAC1_DMINT11, DMAC1_DMAE, IIC, VIN0, VIN1, VCORE0, ATAPI, DTU0, DTU1, DTU2, DTU3, FE0, FE1, GPIO0, GPIO1, GPIO2, GPIO3, PAM, IRM, INTICI0, INTICI1, INTICI2, INTICI3, INTICI4, INTICI5, INTICI6, INTICI7, /* interrupt groups */ IRL, PCII56789, SCIF0, SCIF1, SCIF2, SCIF3, DMAC0, DMAC1, }; static struct intc_vect vectors[] __initdata = { INTC_VECT(HUDII, 0x3e0), INTC_VECT(TMU0, 0x400), INTC_VECT(TMU1, 0x420), INTC_VECT(TMU2, 0x440), INTC_VECT(TMU3, 0x460), INTC_VECT(TMU4, 0x480), INTC_VECT(TMU5, 0x4a0), INTC_VECT(PCII0, 0x500), INTC_VECT(PCII1, 0x520), INTC_VECT(PCII2, 0x540), INTC_VECT(PCII3, 0x560), INTC_VECT(PCII4, 0x580), INTC_VECT(PCII5, 0x5a0), INTC_VECT(PCII6, 0x5c0), INTC_VECT(PCII7, 0x5e0), INTC_VECT(PCII8, 0x600), INTC_VECT(PCII9, 0x620), INTC_VECT(SCIF0_ERI, 0x700), INTC_VECT(SCIF0_RXI, 0x720), INTC_VECT(SCIF0_BRI, 0x740), INTC_VECT(SCIF0_TXI, 0x760), INTC_VECT(SCIF1_ERI, 0x780), INTC_VECT(SCIF1_RXI, 0x7a0), INTC_VECT(SCIF1_BRI, 0x7c0), INTC_VECT(SCIF1_TXI, 0x7e0), INTC_VECT(SCIF3_ERI, 0x880), INTC_VECT(SCIF3_RXI, 0x8a0), INTC_VECT(SCIF3_BRI, 0x8c0), INTC_VECT(SCIF3_TXI, 0x8e0), INTC_VECT(DMAC0_DMINT0, 0x900), INTC_VECT(DMAC0_DMINT1, 0x920), INTC_VECT(DMAC0_DMINT2, 0x940), INTC_VECT(DMAC0_DMINT3, 0x960), INTC_VECT(DMAC0_DMINT4, 0x980), INTC_VECT(DMAC0_DMINT5, 0x9a0), INTC_VECT(DMAC0_DMAE, 0x9c0), INTC_VECT(DU, 0x9e0), INTC_VECT(DMAC1_DMINT6, 0xa00), INTC_VECT(DMAC1_DMINT7, 0xa20), INTC_VECT(DMAC1_DMINT8, 0xa40), INTC_VECT(DMAC1_DMINT9, 0xa60), INTC_VECT(DMAC1_DMINT10, 0xa80), INTC_VECT(DMAC1_DMINT11, 0xaa0), INTC_VECT(DMAC1_DMAE, 0xac0), INTC_VECT(IIC, 0xae0), INTC_VECT(VIN0, 0xb00), INTC_VECT(VIN1, 0xb20), INTC_VECT(VCORE0, 0xb00), INTC_VECT(ATAPI, 0xb60), INTC_VECT(DTU0, 0xc00), INTC_VECT(DTU0, 0xc20), INTC_VECT(DTU0, 0xc40), INTC_VECT(DTU1, 0xc60), INTC_VECT(DTU1, 0xc80), INTC_VECT(DTU1, 0xca0), INTC_VECT(DTU2, 0xcc0), INTC_VECT(DTU2, 0xce0), INTC_VECT(DTU2, 0xd00), INTC_VECT(DTU3, 0xd20), INTC_VECT(DTU3, 0xd40), INTC_VECT(DTU3, 0xd60), INTC_VECT(FE0, 0xe00), INTC_VECT(FE1, 0xe20), INTC_VECT(GPIO0, 0xe40), INTC_VECT(GPIO1, 0xe60), INTC_VECT(GPIO2, 0xe80), INTC_VECT(GPIO3, 0xea0), INTC_VECT(PAM, 0xec0), INTC_VECT(IRM, 0xee0), INTC_VECT(INTICI0, 0xf00), INTC_VECT(INTICI1, 0xf20), INTC_VECT(INTICI2, 0xf40), INTC_VECT(INTICI3, 0xf60), INTC_VECT(INTICI4, 0xf80), INTC_VECT(INTICI5, 0xfa0), INTC_VECT(INTICI6, 0xfc0), INTC_VECT(INTICI7, 0xfe0), }; static struct intc_group groups[] __initdata = { INTC_GROUP(IRL, IRL_LLLL, IRL_LLLH, IRL_LLHL, IRL_LLHH, IRL_LHLL, IRL_LHLH, IRL_LHHL, IRL_LHHH, IRL_HLLL, IRL_HLLH, IRL_HLHL, IRL_HLHH, IRL_HHLL, IRL_HHLH, IRL_HHHL), INTC_GROUP(PCII56789, PCII5, PCII6, PCII7, PCII8, PCII9), INTC_GROUP(SCIF0, SCIF0_ERI, SCIF0_RXI, SCIF0_BRI, SCIF0_TXI), INTC_GROUP(SCIF1, SCIF1_ERI, SCIF1_RXI, SCIF1_BRI, SCIF1_TXI), INTC_GROUP(SCIF3, SCIF3_ERI, SCIF3_RXI, SCIF3_BRI, SCIF3_TXI), INTC_GROUP(DMAC0, DMAC0_DMINT0, DMAC0_DMINT1, DMAC0_DMINT2, DMAC0_DMINT3, DMAC0_DMINT4, DMAC0_DMINT5, DMAC0_DMAE), INTC_GROUP(DMAC1, DMAC1_DMINT6, DMAC1_DMINT7, DMAC1_DMINT8, DMAC1_DMINT9, DMAC1_DMINT10, DMAC1_DMINT11), }; static struct intc_mask_reg mask_registers[] __initdata = { { 0xfe410030, 0xfe410050, 32, /* CnINTMSK0 / CnINTMSKCLR0 */ { IRQ0, IRQ1, IRQ2, IRQ3 } }, { 0xfe410040, 0xfe410060, 32, /* CnINTMSK1 / CnINTMSKCLR1 */ { IRL } }, { 0xfe410820, 0xfe410850, 32, /* CnINT2MSK0 / CnINT2MSKCLR0 */ { FE1, FE0, 0, ATAPI, VCORE0, VIN1, VIN0, IIC, DU, GPIO3, GPIO2, GPIO1, GPIO0, PAM, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* HUDI bits ignored */ 0, TMU5, TMU4, TMU3, TMU2, TMU1, TMU0, 0, } }, { 0xfe410830, 0xfe410860, 32, /* CnINT2MSK1 / CnINT2MSKCLR1 */ { 0, 0, 0, 0, DTU3, DTU2, DTU1, DTU0, /* IRM bits ignored */ PCII9, PCII8, PCII7, PCII6, PCII5, PCII4, PCII3, PCII2, PCII1, PCII0, DMAC1_DMAE, DMAC1_DMINT11, DMAC1_DMINT10, DMAC1_DMINT9, DMAC1_DMINT8, DMAC1_DMINT7, DMAC1_DMINT6, DMAC0_DMAE, DMAC0_DMINT5, DMAC0_DMINT4, DMAC0_DMINT3, DMAC0_DMINT2, DMAC0_DMINT1, DMAC0_DMINT0 } }, { 0xfe410840, 0xfe410870, 32, /* CnINT2MSK2 / CnINT2MSKCLR2 */ { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, SCIF3_TXI, SCIF3_BRI, SCIF3_RXI, SCIF3_ERI, SCIF2_TXI, SCIF2_BRI, SCIF2_RXI, SCIF2_ERI, SCIF1_TXI, SCIF1_BRI, SCIF1_RXI, SCIF1_ERI, SCIF0_TXI, SCIF0_BRI, SCIF0_RXI, SCIF0_ERI } }, }; static struct intc_prio_reg prio_registers[] __initdata = { { 0xfe410010, 0, 32, 4, /* INTPRI */ { IRQ0, IRQ1, IRQ2, IRQ3 } }, { 0xfe410800, 0, 32, 4, /* INT2PRI0 */ { 0, HUDII, TMU5, TMU4, TMU3, TMU2, TMU1, TMU0 } }, { 0xfe410804, 0, 32, 4, /* INT2PRI1 */ { DTU3, DTU2, DTU1, DTU0, SCIF3, SCIF2, SCIF1, SCIF0 } }, { 0xfe410808, 0, 32, 4, /* INT2PRI2 */ { DMAC1, DMAC0, PCII56789, PCII4, PCII3, PCII2, PCII1, PCII0 } }, { 0xfe41080c, 0, 32, 4, /* INT2PRI3 */ { FE1, FE0, ATAPI, VCORE0, VIN1, VIN0, IIC, DU} }, { 0xfe410810, 0, 32, 4, /* INT2PRI4 */ { 0, 0, PAM, GPIO3, GPIO2, GPIO1, GPIO0, IRM } }, { 0xfe410090, 0xfe4100a0, 32, 4, /* CnICIPRI / CnICIPRICLR */ { INTICI7, INTICI6, INTICI5, INTICI4, INTICI3, INTICI2, INTICI1, INTICI0 }, INTC_SMP(4, 4) }, }; static DECLARE_INTC_DESC(intc_desc, "shx3", vectors, groups, mask_registers, prio_registers, NULL); /* Support for external interrupt pins in IRQ mode */ static struct intc_vect vectors_irq[] __initdata = { INTC_VECT(IRQ0, 0x240), INTC_VECT(IRQ1, 0x280), INTC_VECT(IRQ2, 0x2c0), INTC_VECT(IRQ3, 0x300), }; static struct intc_sense_reg sense_registers[] __initdata = { { 0xfe41001c, 32, 2, /* ICR1 */ { IRQ0, IRQ1, IRQ2, IRQ3 } }, }; static DECLARE_INTC_DESC(intc_desc_irq, "shx3-irq", vectors_irq, groups, mask_registers, prio_registers, sense_registers); /* External interrupt pins in IRL mode */ static struct intc_vect vectors_irl[] __initdata = { INTC_VECT(IRL_LLLL, 0x200), INTC_VECT(IRL_LLLH, 0x220), INTC_VECT(IRL_LLHL, 0x240), INTC_VECT(IRL_LLHH, 0x260), INTC_VECT(IRL_LHLL, 0x280), INTC_VECT(IRL_LHLH, 0x2a0), INTC_VECT(IRL_LHHL, 0x2c0), INTC_VECT(IRL_LHHH, 0x2e0), INTC_VECT(IRL_HLLL, 0x300), INTC_VECT(IRL_HLLH, 0x320), INTC_VECT(IRL_HLHL, 0x340), INTC_VECT(IRL_HLHH, 0x360), INTC_VECT(IRL_HHLL, 0x380), INTC_VECT(IRL_HHLH, 0x3a0), INTC_VECT(IRL_HHHL, 0x3c0), }; static DECLARE_INTC_DESC(intc_desc_irl, "shx3-irl", vectors_irl, groups, mask_registers, prio_registers, NULL); void __init plat_irq_setup_pins(int mode) { switch (mode) { case IRQ_MODE_IRQ: register_intc_controller(&intc_desc_irq); break; case IRQ_MODE_IRL3210: register_intc_controller(&intc_desc_irl); break; default: BUG(); } } void __init plat_irq_setup(void) { register_intc_controller(&intc_desc); } void __init plat_mem_setup(void) { unsigned int nid = 1; /* Register CPU#0 URAM space as Node 1 */ setup_bootmem_node(nid++, 0x145f0000, 0x14610000); /* CPU0 */ #if 0 /* XXX: Not yet.. */ setup_bootmem_node(nid++, 0x14df0000, 0x14e10000); /* CPU1 */ setup_bootmem_node(nid++, 0x155f0000, 0x15610000); /* CPU2 */ setup_bootmem_node(nid++, 0x15df0000, 0x15e10000); /* CPU3 */ #endif setup_bootmem_node(nid++, 0x16000000, 0x16020000); /* CSM */ }
gpl-3.0
IXgnas/dixcovery_kernel
drivers/uwb/drp-ie.c
2342
9781
/* * UWB DRP IE management. * * Copyright (C) 2005-2006 Intel Corporation * Copyright (C) 2008 Cambridge Silicon Radio Ltd. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 as published by the Free Software Foundation. * * 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 <linux/kernel.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/uwb.h> #include "uwb-internal.h" /* * Return the reason code for a reservations's DRP IE. */ static int uwb_rsv_reason_code(struct uwb_rsv *rsv) { static const int reason_codes[] = { [UWB_RSV_STATE_O_INITIATED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_O_PENDING] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_O_MODIFIED] = UWB_DRP_REASON_MODIFIED, [UWB_RSV_STATE_O_ESTABLISHED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_O_TO_BE_MOVED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_O_MOVE_COMBINING] = UWB_DRP_REASON_MODIFIED, [UWB_RSV_STATE_O_MOVE_REDUCING] = UWB_DRP_REASON_MODIFIED, [UWB_RSV_STATE_O_MOVE_EXPANDING] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_ACCEPTED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_CONFLICT] = UWB_DRP_REASON_CONFLICT, [UWB_RSV_STATE_T_PENDING] = UWB_DRP_REASON_PENDING, [UWB_RSV_STATE_T_DENIED] = UWB_DRP_REASON_DENIED, [UWB_RSV_STATE_T_RESIZED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_EXPANDING_CONFLICT] = UWB_DRP_REASON_CONFLICT, [UWB_RSV_STATE_T_EXPANDING_PENDING] = UWB_DRP_REASON_PENDING, [UWB_RSV_STATE_T_EXPANDING_DENIED] = UWB_DRP_REASON_DENIED, }; return reason_codes[rsv->state]; } /* * Return the reason code for a reservations's companion DRP IE . */ static int uwb_rsv_companion_reason_code(struct uwb_rsv *rsv) { static const int companion_reason_codes[] = { [UWB_RSV_STATE_O_MOVE_EXPANDING] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = UWB_DRP_REASON_ACCEPTED, [UWB_RSV_STATE_T_EXPANDING_CONFLICT] = UWB_DRP_REASON_CONFLICT, [UWB_RSV_STATE_T_EXPANDING_PENDING] = UWB_DRP_REASON_PENDING, [UWB_RSV_STATE_T_EXPANDING_DENIED] = UWB_DRP_REASON_DENIED, }; return companion_reason_codes[rsv->state]; } /* * Return the status bit for a reservations's DRP IE. */ int uwb_rsv_status(struct uwb_rsv *rsv) { static const int statuses[] = { [UWB_RSV_STATE_O_INITIATED] = 0, [UWB_RSV_STATE_O_PENDING] = 0, [UWB_RSV_STATE_O_MODIFIED] = 1, [UWB_RSV_STATE_O_ESTABLISHED] = 1, [UWB_RSV_STATE_O_TO_BE_MOVED] = 0, [UWB_RSV_STATE_O_MOVE_COMBINING] = 1, [UWB_RSV_STATE_O_MOVE_REDUCING] = 1, [UWB_RSV_STATE_O_MOVE_EXPANDING] = 1, [UWB_RSV_STATE_T_ACCEPTED] = 1, [UWB_RSV_STATE_T_CONFLICT] = 0, [UWB_RSV_STATE_T_PENDING] = 0, [UWB_RSV_STATE_T_DENIED] = 0, [UWB_RSV_STATE_T_RESIZED] = 1, [UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = 1, [UWB_RSV_STATE_T_EXPANDING_CONFLICT] = 1, [UWB_RSV_STATE_T_EXPANDING_PENDING] = 1, [UWB_RSV_STATE_T_EXPANDING_DENIED] = 1, }; return statuses[rsv->state]; } /* * Return the status bit for a reservations's companion DRP IE . */ int uwb_rsv_companion_status(struct uwb_rsv *rsv) { static const int companion_statuses[] = { [UWB_RSV_STATE_O_MOVE_EXPANDING] = 0, [UWB_RSV_STATE_T_EXPANDING_ACCEPTED] = 1, [UWB_RSV_STATE_T_EXPANDING_CONFLICT] = 0, [UWB_RSV_STATE_T_EXPANDING_PENDING] = 0, [UWB_RSV_STATE_T_EXPANDING_DENIED] = 0, }; return companion_statuses[rsv->state]; } /* * Allocate a DRP IE. * * To save having to free/allocate a DRP IE when its MAS changes, * enough memory is allocated for the maxiumum number of DRP * allocation fields. This gives an overhead per reservation of up to * (UWB_NUM_ZONES - 1) * 4 = 60 octets. */ static struct uwb_ie_drp *uwb_drp_ie_alloc(void) { struct uwb_ie_drp *drp_ie; drp_ie = kzalloc(sizeof(struct uwb_ie_drp) + UWB_NUM_ZONES * sizeof(struct uwb_drp_alloc), GFP_KERNEL); if (drp_ie) { drp_ie->hdr.element_id = UWB_IE_DRP; } return drp_ie; } /* * Fill a DRP IE's allocation fields from a MAS bitmap. */ static void uwb_drp_ie_from_bm(struct uwb_ie_drp *drp_ie, struct uwb_mas_bm *mas) { int z, i, num_fields = 0, next = 0; struct uwb_drp_alloc *zones; __le16 current_bmp; DECLARE_BITMAP(tmp_bmp, UWB_NUM_MAS); DECLARE_BITMAP(tmp_mas_bm, UWB_MAS_PER_ZONE); zones = drp_ie->allocs; bitmap_copy(tmp_bmp, mas->bm, UWB_NUM_MAS); /* Determine unique MAS bitmaps in zones from bitmap. */ for (z = 0; z < UWB_NUM_ZONES; z++) { bitmap_copy(tmp_mas_bm, tmp_bmp, UWB_MAS_PER_ZONE); if (bitmap_weight(tmp_mas_bm, UWB_MAS_PER_ZONE) > 0) { bool found = false; current_bmp = (__le16) *tmp_mas_bm; for (i = 0; i < next; i++) { if (current_bmp == zones[i].mas_bm) { zones[i].zone_bm |= 1 << z; found = true; break; } } if (!found) { num_fields++; zones[next].zone_bm = 1 << z; zones[next].mas_bm = current_bmp; next++; } } bitmap_shift_right(tmp_bmp, tmp_bmp, UWB_MAS_PER_ZONE, UWB_NUM_MAS); } /* Store in format ready for transmission (le16). */ for (i = 0; i < num_fields; i++) { drp_ie->allocs[i].zone_bm = cpu_to_le16(zones[i].zone_bm); drp_ie->allocs[i].mas_bm = cpu_to_le16(zones[i].mas_bm); } drp_ie->hdr.length = sizeof(struct uwb_ie_drp) - sizeof(struct uwb_ie_hdr) + num_fields * sizeof(struct uwb_drp_alloc); } /** * uwb_drp_ie_update - update a reservation's DRP IE * @rsv: the reservation */ int uwb_drp_ie_update(struct uwb_rsv *rsv) { struct uwb_ie_drp *drp_ie; struct uwb_rsv_move *mv; int unsafe; if (rsv->state == UWB_RSV_STATE_NONE) { kfree(rsv->drp_ie); rsv->drp_ie = NULL; return 0; } unsafe = rsv->mas.unsafe ? 1 : 0; if (rsv->drp_ie == NULL) { rsv->drp_ie = uwb_drp_ie_alloc(); if (rsv->drp_ie == NULL) return -ENOMEM; } drp_ie = rsv->drp_ie; uwb_ie_drp_set_unsafe(drp_ie, unsafe); uwb_ie_drp_set_tiebreaker(drp_ie, rsv->tiebreaker); uwb_ie_drp_set_owner(drp_ie, uwb_rsv_is_owner(rsv)); uwb_ie_drp_set_status(drp_ie, uwb_rsv_status(rsv)); uwb_ie_drp_set_reason_code(drp_ie, uwb_rsv_reason_code(rsv)); uwb_ie_drp_set_stream_index(drp_ie, rsv->stream); uwb_ie_drp_set_type(drp_ie, rsv->type); if (uwb_rsv_is_owner(rsv)) { switch (rsv->target.type) { case UWB_RSV_TARGET_DEV: drp_ie->dev_addr = rsv->target.dev->dev_addr; break; case UWB_RSV_TARGET_DEVADDR: drp_ie->dev_addr = rsv->target.devaddr; break; } } else drp_ie->dev_addr = rsv->owner->dev_addr; uwb_drp_ie_from_bm(drp_ie, &rsv->mas); if (uwb_rsv_has_two_drp_ies(rsv)) { mv = &rsv->mv; if (mv->companion_drp_ie == NULL) { mv->companion_drp_ie = uwb_drp_ie_alloc(); if (mv->companion_drp_ie == NULL) return -ENOMEM; } drp_ie = mv->companion_drp_ie; /* keep all the same configuration of the main drp_ie */ memcpy(drp_ie, rsv->drp_ie, sizeof(struct uwb_ie_drp)); /* FIXME: handle properly the unsafe bit */ uwb_ie_drp_set_unsafe(drp_ie, 1); uwb_ie_drp_set_status(drp_ie, uwb_rsv_companion_status(rsv)); uwb_ie_drp_set_reason_code(drp_ie, uwb_rsv_companion_reason_code(rsv)); uwb_drp_ie_from_bm(drp_ie, &mv->companion_mas); } rsv->ie_valid = true; return 0; } /* * Set MAS bits from given MAS bitmap in a single zone of large bitmap. * * We are given a zone id and the MAS bitmap of bits that need to be set in * this zone. Note that this zone may already have bits set and this only * adds settings - we cannot simply assign the MAS bitmap contents to the * zone contents. We iterate over the the bits (MAS) in the zone and set the * bits that are set in the given MAS bitmap. */ static void uwb_drp_ie_single_zone_to_bm(struct uwb_mas_bm *bm, u8 zone, u16 mas_bm) { int mas; u16 mas_mask; for (mas = 0; mas < UWB_MAS_PER_ZONE; mas++) { mas_mask = 1 << mas; if (mas_bm & mas_mask) set_bit(zone * UWB_NUM_ZONES + mas, bm->bm); } } /** * uwb_drp_ie_zones_to_bm - convert DRP allocation fields to a bitmap * @mas: MAS bitmap that will be populated to correspond to the * allocation fields in the DRP IE * @drp_ie: the DRP IE that contains the allocation fields. * * The input format is an array of MAS allocation fields (16 bit Zone * bitmap, 16 bit MAS bitmap) as described in [ECMA-368] section * 16.8.6. The output is a full 256 bit MAS bitmap. * * We go over all the allocation fields, for each allocation field we * know which zones are impacted. We iterate over all the zones * impacted and call a function that will set the correct MAS bits in * each zone. */ void uwb_drp_ie_to_bm(struct uwb_mas_bm *bm, const struct uwb_ie_drp *drp_ie) { int numallocs = (drp_ie->hdr.length - 4) / 4; const struct uwb_drp_alloc *alloc; int cnt; u16 zone_bm, mas_bm; u8 zone; u16 zone_mask; bitmap_zero(bm->bm, UWB_NUM_MAS); for (cnt = 0; cnt < numallocs; cnt++) { alloc = &drp_ie->allocs[cnt]; zone_bm = le16_to_cpu(alloc->zone_bm); mas_bm = le16_to_cpu(alloc->mas_bm); for (zone = 0; zone < UWB_NUM_ZONES; zone++) { zone_mask = 1 << zone; if (zone_bm & zone_mask) uwb_drp_ie_single_zone_to_bm(bm, zone, mas_bm); } } }
gpl-3.0
crodrigues96/mtasa-blue
vendor/cegui-0.4.0-custom/WidgetSets/Falagard/src/FalTabPane.cpp
41
2784
/************************************************************************ filename: FalTabPane.cpp created: Fri Jul 8 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /************************************************************************* Crazy Eddie's GUI System (http://www.cegui.org.uk) Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk) 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *************************************************************************/ #include "StdInc.h" #include "FalTabPane.h" #include "falagard/CEGUIFalWidgetLookManager.h" #include "falagard/CEGUIFalWidgetLookFeel.h" // Start of CEGUI namespace section namespace CEGUI { const utf8 FalagardTabPane::WidgetTypeName[] = "Falagard/TabPane"; FalagardTabPane::FalagardTabPane(const String& type, const String& name) : TabPane(type, name) { } FalagardTabPane::~FalagardTabPane() { } void FalagardTabPane::populateRenderCache() { const StateImagery* imagery; // get WidgetLookFeel for the assigned look. const WidgetLookFeel& wlf = WidgetLookManager::getSingleton().getWidgetLook(d_lookName); // render basic imagery imagery = &wlf.getStateImagery(isDisabled() ? "Disabled" : "Enabled"); imagery->render(*this); } ////////////////////////////////////////////////////////////////////////// /************************************************************************* Factory Methods *************************************************************************/ ////////////////////////////////////////////////////////////////////////// Window* FalagardTabPaneFactory::createWindow(const String& name) { return new FalagardTabPane(d_type, name); } void FalagardTabPaneFactory::destroyWindow(Window* window) { delete window; } } // End of CEGUI namespace section
gpl-3.0
scopeInfinity/stk-code
lib/bullet/src/BulletCollision/Gimpact/gim_box_set.cpp
555
5738
/* ----------------------------------------------------------------------------- This source file is part of GIMPACT Library. For the latest info, see http://gimpact.sourceforge.net/ Copyright (c) 2006 Francisco Leon Najera. C.C. 80087371. email: projectileman@yahoo.com This library is free software; you can redistribute it and/or modify it under the terms of EITHER: (1) The GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The text of the GNU Lesser General Public License is included with this library in the file GIMPACT-LICENSE-LGPL.TXT. (2) The BSD-style license that is included with this library in the file GIMPACT-LICENSE-BSD.TXT. (3) The zlib/libpng license that is included with this library in the file GIMPACT-LICENSE-ZLIB.TXT. 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 files GIMPACT-LICENSE-LGPL.TXT, GIMPACT-LICENSE-ZLIB.TXT and GIMPACT-LICENSE-BSD.TXT for more details. ----------------------------------------------------------------------------- */ #include "gim_box_set.h" GUINT GIM_BOX_TREE::_calc_splitting_axis( gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex) { GUINT i; btVector3 means(btScalar(0.),btScalar(0.),btScalar(0.)); btVector3 variance(btScalar(0.),btScalar(0.),btScalar(0.)); GUINT numIndices = endIndex-startIndex; for (i=startIndex;i<endIndex;i++) { btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max + primitive_boxes[i].m_bound.m_min); means+=center; } means *= (btScalar(1.)/(btScalar)numIndices); for (i=startIndex;i<endIndex;i++) { btVector3 center = btScalar(0.5)*(primitive_boxes[i].m_bound.m_max + primitive_boxes[i].m_bound.m_min); btVector3 diff2 = center-means; diff2 = diff2 * diff2; variance += diff2; } variance *= (btScalar(1.)/ ((btScalar)numIndices-1) ); return variance.maxAxis(); } GUINT GIM_BOX_TREE::_sort_and_calc_splitting_index( gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex, GUINT splitAxis) { GUINT i; GUINT splitIndex =startIndex; GUINT numIndices = endIndex - startIndex; // average of centers btScalar splitValue = 0.0f; for (i=startIndex;i<endIndex;i++) { splitValue+= 0.5f*(primitive_boxes[i].m_bound.m_max[splitAxis] + primitive_boxes[i].m_bound.m_min[splitAxis]); } splitValue /= (btScalar)numIndices; //sort leafNodes so all values larger then splitValue comes first, and smaller values start from 'splitIndex'. for (i=startIndex;i<endIndex;i++) { btScalar center = 0.5f*(primitive_boxes[i].m_bound.m_max[splitAxis] + primitive_boxes[i].m_bound.m_min[splitAxis]); if (center > splitValue) { //swap primitive_boxes.swap(i,splitIndex); splitIndex++; } } //if the splitIndex causes unbalanced trees, fix this by using the center in between startIndex and endIndex //otherwise the tree-building might fail due to stack-overflows in certain cases. //unbalanced1 is unsafe: it can cause stack overflows //bool unbalanced1 = ((splitIndex==startIndex) || (splitIndex == (endIndex-1))); //unbalanced2 should work too: always use center (perfect balanced trees) //bool unbalanced2 = true; //this should be safe too: GUINT rangeBalancedIndices = numIndices/3; bool unbalanced = ((splitIndex<=(startIndex+rangeBalancedIndices)) || (splitIndex >=(endIndex-1-rangeBalancedIndices))); if (unbalanced) { splitIndex = startIndex+ (numIndices>>1); } btAssert(!((splitIndex==startIndex) || (splitIndex == (endIndex)))); return splitIndex; } void GIM_BOX_TREE::_build_sub_tree(gim_array<GIM_AABB_DATA> & primitive_boxes, GUINT startIndex, GUINT endIndex) { GUINT current_index = m_num_nodes++; btAssert((endIndex-startIndex)>0); if((endIndex-startIndex) == 1) //we got a leaf { m_node_array[current_index].m_left = 0; m_node_array[current_index].m_right = 0; m_node_array[current_index].m_escapeIndex = 0; m_node_array[current_index].m_bound = primitive_boxes[startIndex].m_bound; m_node_array[current_index].m_data = primitive_boxes[startIndex].m_data; return; } //configure inner node GUINT splitIndex; //calc this node bounding box m_node_array[current_index].m_bound.invalidate(); for (splitIndex=startIndex;splitIndex<endIndex;splitIndex++) { m_node_array[current_index].m_bound.merge(primitive_boxes[splitIndex].m_bound); } //calculate Best Splitting Axis and where to split it. Sort the incoming 'leafNodes' array within range 'startIndex/endIndex'. //split axis splitIndex = _calc_splitting_axis(primitive_boxes,startIndex,endIndex); splitIndex = _sort_and_calc_splitting_index( primitive_boxes,startIndex,endIndex,splitIndex); //configure this inner node : the left node index m_node_array[current_index].m_left = m_num_nodes; //build left child tree _build_sub_tree(primitive_boxes, startIndex, splitIndex ); //configure this inner node : the right node index m_node_array[current_index].m_right = m_num_nodes; //build right child tree _build_sub_tree(primitive_boxes, splitIndex ,endIndex); //configure this inner node : the escape index m_node_array[current_index].m_escapeIndex = m_num_nodes - current_index; } //! stackless build tree void GIM_BOX_TREE::build_tree( gim_array<GIM_AABB_DATA> & primitive_boxes) { // initialize node count to 0 m_num_nodes = 0; // allocate nodes m_node_array.resize(primitive_boxes.size()*2); _build_sub_tree(primitive_boxes, 0, primitive_boxes.size()); }
gpl-3.0
slfl/HUAWEI89_WE_KK_700
bootable/bootloader/lk/lib/libc/string/strtok.c
45
1662
/* ** Copyright 2001, Travis Geiselbrecht. All rights reserved. ** Distributed under the terms of the NewOS License. */ /* * Copyright (c) 2008 Travis Geiselbrecht * * 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 <string.h> #include <sys/types.h> static char *___strtok = NULL; char * strtok(char *s, char const *ct) { char *sbegin, *send; sbegin = s ? s : ___strtok; if (!sbegin) { return NULL; } sbegin += strspn(sbegin,ct); if (*sbegin == '\0') { ___strtok = NULL; return( NULL ); } send = strpbrk( sbegin, ct); if (send && *send != '\0') *send++ = '\0'; ___strtok = send; return (sbegin); }
gpl-3.0
ostrowt/soe
neo/sys/win32/win_taskkeyhook.cpp
57
4794
/* =========================================================================== Doom 3 GPL Source Code Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?). Doom 3 Source Code 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. Doom 3 Source Code 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #include "../../idlib/precompiled.h" #pragma hdrstop // // This file implements the low-level keyboard hook that traps the task keys. // //#define _WIN32_WINNT 0x0500 // for KBDLLHOOKSTRUCT #include <afxwin.h> // MFC core and standard components #include "win_local.h" #define DLLEXPORT __declspec(dllexport) // Magic registry key/value for "Remove Task Manager" policy. LPCTSTR KEY_DisableTaskMgr = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System"; LPCTSTR VAL_DisableTaskMgr = "DisableTaskMgr"; // The section is SHARED among all instances of this DLL. // A low-level keyboard hook is always a system-wide hook. #pragma data_seg (".mydata") HHOOK g_hHookKbdLL = NULL; // hook handle BOOL g_bBeep = FALSE; // beep on illegal key #pragma data_seg () #pragma comment(linker, "/SECTION:.mydata,RWS") // tell linker: make it shared /* ================ MyTaskKeyHookLL Low-level keyboard hook: Trap task-switching keys by returning without passing along. ================ */ LRESULT CALLBACK MyTaskKeyHookLL( int nCode, WPARAM wp, LPARAM lp ) { KBDLLHOOKSTRUCT *pkh = (KBDLLHOOKSTRUCT *) lp; if ( nCode == HC_ACTION ) { BOOL bCtrlKeyDown = GetAsyncKeyState( VK_CONTROL)>>((sizeof(SHORT) * 8) - 1 ); if ( ( pkh->vkCode == VK_ESCAPE && bCtrlKeyDown ) // Ctrl+Esc || ( pkh->vkCode == VK_TAB && pkh->flags & LLKHF_ALTDOWN ) // Alt+TAB || ( pkh->vkCode == VK_ESCAPE && pkh->flags & LLKHF_ALTDOWN ) // Alt+Esc || ( pkh->vkCode == VK_LWIN || pkh->vkCode == VK_RWIN ) // Start Menu ) { if ( g_bBeep && ( wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN ) ) { MessageBeep( 0 ); // beep on downstroke if requested } return 1; // return without processing the key strokes } } return CallNextHookEx( g_hHookKbdLL, nCode, wp, lp ); } /* ================ AreTaskKeysDisabled Are task keys disabled--ie, is hook installed? Note: This assumes there's no other hook that does the same thing! ================ */ BOOL AreTaskKeysDisabled() { return g_hHookKbdLL != NULL; } /* ================ IsTaskMgrDisabled ================ */ BOOL IsTaskMgrDisabled() { HKEY hk; if ( RegOpenKey( HKEY_CURRENT_USER, KEY_DisableTaskMgr, &hk ) != ERROR_SUCCESS ) { return FALSE; // no key ==> not disabled } DWORD val = 0; DWORD len = 4; return RegQueryValueEx( hk, VAL_DisableTaskMgr, NULL, NULL, (BYTE*)&val, &len ) == ERROR_SUCCESS && val == 1; } /* ================ DisableTaskKeys ================ */ void DisableTaskKeys( BOOL bDisable, BOOL bBeep, BOOL bTaskMgr ) { // task keys (Ctrl+Esc, Alt-Tab, etc.) if ( bDisable ) { if ( !g_hHookKbdLL ) { g_hHookKbdLL = SetWindowsHookEx( WH_KEYBOARD_LL, MyTaskKeyHookLL, win32.hInstance, 0 ); } } else if ( g_hHookKbdLL != NULL ) { UnhookWindowsHookEx( g_hHookKbdLL ); g_hHookKbdLL = NULL; } g_bBeep = bBeep; // task manager (Ctrl+Alt+Del) if ( bTaskMgr ) { HKEY hk; if ( RegOpenKey( HKEY_CURRENT_USER, KEY_DisableTaskMgr, &hk ) != ERROR_SUCCESS ) { RegCreateKey( HKEY_CURRENT_USER, KEY_DisableTaskMgr, &hk ); } if ( bDisable ) { // disable TM: set policy = 1 DWORD val = 1; RegSetValueEx( hk, VAL_DisableTaskMgr, NULL, REG_DWORD, (BYTE*)&val, sizeof(val) ); } else { // enable TM: remove policy RegDeleteValue( hk,VAL_DisableTaskMgr ); } } }
gpl-3.0
svebk/LSHBOX
include/eigen/test/simplicial_cholesky.cpp
58
1592
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2011 Gael Guennebaud <g.gael@free.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "sparse_solver.h" template<typename T> void test_simplicial_cholesky_T() { SimplicialCholesky<SparseMatrix<T>, Lower> chol_colmajor_lower; SimplicialCholesky<SparseMatrix<T>, Upper> chol_colmajor_upper; SimplicialLLT<SparseMatrix<T>, Lower> llt_colmajor_lower; SimplicialLDLT<SparseMatrix<T>, Upper> llt_colmajor_upper; SimplicialLDLT<SparseMatrix<T>, Lower> ldlt_colmajor_lower; SimplicialLDLT<SparseMatrix<T>, Upper> ldlt_colmajor_upper; check_sparse_spd_solving(chol_colmajor_lower); check_sparse_spd_solving(chol_colmajor_upper); check_sparse_spd_solving(llt_colmajor_lower); check_sparse_spd_solving(llt_colmajor_upper); check_sparse_spd_solving(ldlt_colmajor_lower); check_sparse_spd_solving(ldlt_colmajor_upper); check_sparse_spd_determinant(chol_colmajor_lower); check_sparse_spd_determinant(chol_colmajor_upper); check_sparse_spd_determinant(llt_colmajor_lower); check_sparse_spd_determinant(llt_colmajor_upper); check_sparse_spd_determinant(ldlt_colmajor_lower); check_sparse_spd_determinant(ldlt_colmajor_upper); } void test_simplicial_cholesky() { CALL_SUBTEST_1(test_simplicial_cholesky_T<double>()); CALL_SUBTEST_2(test_simplicial_cholesky_T<std::complex<double> >()); }
gpl-3.0
reliak/moonpdf
ext/sumatra/ext/unrar/extinfo.cpp
65
1629
#include "rar.hpp" #ifdef _WIN_ALL #include "win32acl.cpp" #include "win32stm.cpp" #endif #ifdef _BEOS #include "beosea.cpp" #endif #if defined(_EMX) && !defined(_DJGPP) #include "os2ea.cpp" #endif #ifdef _UNIX #include "uowners.cpp" #endif #ifndef SFX_MODULE void SetExtraInfo(CommandData *Cmd,Archive &Arc,char *Name,wchar *NameW) { switch(Arc.SubBlockHead.SubType) { #if defined(_EMX) && !defined(_DJGPP) case EA_HEAD: if (Cmd->ProcessEA) ExtractOS2EA(Arc,Name); break; #endif #ifdef _UNIX case UO_HEAD: if (Cmd->ProcessOwners) ExtractUnixOwner(Arc,Name); break; #endif #ifdef _BEOS case BEEA_HEAD: if (Cmd->ProcessEA) ExtractBeEA(Arc,Name); break; #endif #ifdef _WIN_ALL case NTACL_HEAD: if (Cmd->ProcessOwners) ExtractACL(Arc,Name,NameW); break; case STREAM_HEAD: ExtractStreams(Arc,Name,NameW); break; #endif } } #endif void SetExtraInfoNew(CommandData *Cmd,Archive &Arc,char *Name,wchar *NameW) { #if defined(_EMX) && !defined(_DJGPP) if (Cmd->ProcessEA && Arc.SubHead.CmpName(SUBHEAD_TYPE_OS2EA)) ExtractOS2EANew(Arc,Name); #endif #ifdef _UNIX if (Cmd->ProcessOwners && Arc.SubHead.CmpName(SUBHEAD_TYPE_UOWNER)) ExtractUnixOwnerNew(Arc,Name); #endif #ifdef _BEOS if (Cmd->ProcessEA && Arc.SubHead.CmpName(SUBHEAD_TYPE_UOWNER)) ExtractUnixOwnerNew(Arc,Name); #endif #ifdef _WIN_ALL if (Cmd->ProcessOwners && Arc.SubHead.CmpName(SUBHEAD_TYPE_ACL)) ExtractACLNew(Arc,Name,NameW); if (Arc.SubHead.CmpName(SUBHEAD_TYPE_STREAM)) ExtractStreamsNew(Arc,Name,NameW); #endif }
gpl-3.0
bennoleslie/gettext
gettext-tools/gnulib-lib/libxml/globals.c
67
29027
/* * globals.c: definition and handling of the set of global variables * of the library * * The bottom of this file is automatically generated by build_glob.py * based on the description file global.data * * See Copyright for the status of this software. * * Gary Pennington <Gary.Pennington@uk.sun.com> * daniel@veillard.com */ #define IN_LIBXML #include "libxml.h" #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <string.h> #include <libxml/globals.h> #include <libxml/xmlmemory.h> #include <libxml/threads.h> /* #define DEBUG_GLOBALS */ /* * Helpful Macro */ #ifdef LIBXML_THREAD_ENABLED #define IS_MAIN_THREAD (xmlIsMainThread()) #else #define IS_MAIN_THREAD 1 #endif /* * Mutex to protect "ForNewThreads" variables */ static xmlMutexPtr xmlThrDefMutex = NULL; /** * xmlInitGlobals: * * Additional initialisation for multi-threading */ void xmlInitGlobals(void) { xmlThrDefMutex = xmlNewMutex(); } /** * xmlCleanupGlobals: * * Additional cleanup for multi-threading */ void xmlCleanupGlobals(void) { if (xmlThrDefMutex != NULL) { xmlFreeMutex(xmlThrDefMutex); xmlThrDefMutex = NULL; } } /************************************************************************ * * * All the user accessible global variables of the library * * * ************************************************************************/ /* * Memory allocation routines */ #undef xmlFree #undef xmlMalloc #undef xmlMallocAtomic #undef xmlMemStrdup #undef xmlRealloc #if defined(DEBUG_MEMORY_LOCATION) || defined(DEBUG_MEMORY) xmlFreeFunc xmlFree = (xmlFreeFunc) xmlMemFree; xmlMallocFunc xmlMalloc = (xmlMallocFunc) xmlMemMalloc; xmlMallocFunc xmlMallocAtomic = (xmlMallocFunc) xmlMemMalloc; xmlReallocFunc xmlRealloc = (xmlReallocFunc) xmlMemRealloc; xmlStrdupFunc xmlMemStrdup = (xmlStrdupFunc) xmlMemoryStrdup; #else /** * xmlFree: * @mem: an already allocated block of memory * * The variable holding the libxml free() implementation */ xmlFreeFunc xmlFree = (xmlFreeFunc) free; /** * xmlMalloc: * @size: the size requested in bytes * * The variable holding the libxml malloc() implementation * * Returns a pointer to the newly allocated block or NULL in case of error */ xmlMallocFunc xmlMalloc = (xmlMallocFunc) malloc; /** * xmlMallocAtomic: * @size: the size requested in bytes * * The variable holding the libxml malloc() implementation for atomic * data (i.e. blocks not containings pointers), useful when using a * garbage collecting allocator. * * Returns a pointer to the newly allocated block or NULL in case of error */ xmlMallocFunc xmlMallocAtomic = (xmlMallocFunc) malloc; /** * xmlRealloc: * @mem: an already allocated block of memory * @size: the new size requested in bytes * * The variable holding the libxml realloc() implementation * * Returns a pointer to the newly reallocated block or NULL in case of error */ xmlReallocFunc xmlRealloc = (xmlReallocFunc) realloc; /** * xmlMemStrdup: * @str: a zero terminated string * * The variable holding the libxml strdup() implementation * * Returns the copy of the string or NULL in case of error */ xmlStrdupFunc xmlMemStrdup = (xmlStrdupFunc) xmlStrdup; #endif /* DEBUG_MEMORY_LOCATION || DEBUG_MEMORY */ #include <libxml/threads.h> #include <libxml/globals.h> #include <libxml/SAX.h> #undef docbDefaultSAXHandler #undef htmlDefaultSAXHandler #undef oldXMLWDcompatibility #undef xmlBufferAllocScheme #undef xmlDefaultBufferSize #undef xmlDefaultSAXHandler #undef xmlDefaultSAXLocator #undef xmlDoValidityCheckingDefaultValue #undef xmlGenericError #undef xmlStructuredError #undef xmlGenericErrorContext #undef xmlGetWarningsDefaultValue #undef xmlIndentTreeOutput #undef xmlTreeIndentString #undef xmlKeepBlanksDefaultValue #undef xmlLineNumbersDefaultValue #undef xmlLoadExtDtdDefaultValue #undef xmlParserDebugEntities #undef xmlParserVersion #undef xmlPedanticParserDefaultValue #undef xmlSaveNoEmptyTags #undef xmlSubstituteEntitiesDefaultValue #undef xmlRegisterNodeDefaultValue #undef xmlDeregisterNodeDefaultValue #undef xmlLastError #undef xmlParserInputBufferCreateFilenameValue #undef xmlOutputBufferCreateFilenameValue /** * xmlParserVersion: * * Constant string describing the internal version of the library */ const char *xmlParserVersion = LIBXML_VERSION_STRING LIBXML_VERSION_EXTRA; /** * xmlBufferAllocScheme: * * Global setting, default allocation policy for buffers, default is * XML_BUFFER_ALLOC_EXACT */ xmlBufferAllocationScheme xmlBufferAllocScheme = XML_BUFFER_ALLOC_EXACT; static xmlBufferAllocationScheme xmlBufferAllocSchemeThrDef = XML_BUFFER_ALLOC_EXACT; /** * xmlDefaultBufferSize: * * Global setting, default buffer size. Default value is BASE_BUFFER_SIZE */ int xmlDefaultBufferSize = BASE_BUFFER_SIZE; static int xmlDefaultBufferSizeThrDef = BASE_BUFFER_SIZE; /* * Parser defaults */ /** * oldXMLWDcompatibility: * * Global setting, DEPRECATED. */ int oldXMLWDcompatibility = 0; /* DEPRECATED */ /** * xmlParserDebugEntities: * * Global setting, asking the parser to print out debugging informations. * while handling entities. * Disabled by default */ int xmlParserDebugEntities = 0; static int xmlParserDebugEntitiesThrDef = 0; /** * xmlDoValidityCheckingDefaultValue: * * Global setting, indicate that the parser should work in validating mode. * Disabled by default. */ int xmlDoValidityCheckingDefaultValue = 0; static int xmlDoValidityCheckingDefaultValueThrDef = 0; /** * xmlGetWarningsDefaultValue: * * Global setting, indicate that the parser should provide warnings. * Activated by default. */ int xmlGetWarningsDefaultValue = 1; static int xmlGetWarningsDefaultValueThrDef = 1; /** * xmlLoadExtDtdDefaultValue: * * Global setting, indicate that the parser should load DTD while not * validating. * Disabled by default. */ int xmlLoadExtDtdDefaultValue = 0; static int xmlLoadExtDtdDefaultValueThrDef = 0; /** * xmlPedanticParserDefaultValue: * * Global setting, indicate that the parser be pedantic * Disabled by default. */ int xmlPedanticParserDefaultValue = 0; static int xmlPedanticParserDefaultValueThrDef = 0; /** * xmlLineNumbersDefaultValue: * * Global setting, indicate that the parser should store the line number * in the content field of elements in the DOM tree. * Disabled by default since this may not be safe for old classes of * applicaton. */ int xmlLineNumbersDefaultValue = 0; static int xmlLineNumbersDefaultValueThrDef = 0; /** * xmlKeepBlanksDefaultValue: * * Global setting, indicate that the parser should keep all blanks * nodes found in the content * Activated by default, this is actually needed to have the parser * conformant to the XML Recommendation, however the option is kept * for some applications since this was libxml1 default behaviour. */ int xmlKeepBlanksDefaultValue = 1; static int xmlKeepBlanksDefaultValueThrDef = 1; /** * xmlSubstituteEntitiesDefaultValue: * * Global setting, indicate that the parser should not generate entity * references but replace them with the actual content of the entity * Disabled by default, this should be activated when using XPath since * the XPath data model requires entities replacement and the XPath * engine does not handle entities references transparently. */ int xmlSubstituteEntitiesDefaultValue = 0; static int xmlSubstituteEntitiesDefaultValueThrDef = 0; xmlRegisterNodeFunc xmlRegisterNodeDefaultValue = NULL; static xmlRegisterNodeFunc xmlRegisterNodeDefaultValueThrDef = NULL; xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValue = NULL; static xmlDeregisterNodeFunc xmlDeregisterNodeDefaultValueThrDef = NULL; xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValue = NULL; static xmlParserInputBufferCreateFilenameFunc xmlParserInputBufferCreateFilenameValueThrDef = NULL; xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValue = NULL; static xmlOutputBufferCreateFilenameFunc xmlOutputBufferCreateFilenameValueThrDef = NULL; /* * Error handling */ /* xmlGenericErrorFunc xmlGenericError = xmlGenericErrorDefaultFunc; */ /* Must initialize xmlGenericError in xmlInitParser */ void XMLCDECL xmlGenericErrorDefaultFunc (void *ctx ATTRIBUTE_UNUSED, const char *msg, ...); /** * xmlGenericError: * * Global setting: function used for generic error callbacks */ xmlGenericErrorFunc xmlGenericError = xmlGenericErrorDefaultFunc; static xmlGenericErrorFunc xmlGenericErrorThrDef = xmlGenericErrorDefaultFunc; /** * xmlStructuredError: * * Global setting: function used for structured error callbacks */ xmlStructuredErrorFunc xmlStructuredError = NULL; static xmlStructuredErrorFunc xmlStructuredErrorThrDef = NULL; /** * xmlGenericErrorContext: * * Global setting passed to generic error callbacks */ void *xmlGenericErrorContext = NULL; static void *xmlGenericErrorContextThrDef = NULL; xmlError xmlLastError; /* * output defaults */ /** * xmlIndentTreeOutput: * * Global setting, asking the serializer to indent the output tree by default * Enabled by default */ int xmlIndentTreeOutput = 1; static int xmlIndentTreeOutputThrDef = 1; /** * xmlTreeIndentString: * * The string used to do one-level indent. By default is equal to " " (two spaces) */ const char *xmlTreeIndentString = " "; static const char *xmlTreeIndentStringThrDef = " "; /** * xmlSaveNoEmptyTags: * * Global setting, asking the serializer to not output empty tags * as <empty/> but <empty></empty>. those two forms are undistinguishable * once parsed. * Disabled by default */ int xmlSaveNoEmptyTags = 0; static int xmlSaveNoEmptyTagsThrDef = 0; #ifdef LIBXML_SAX1_ENABLED /** * xmlDefaultSAXHandler: * * Default SAX version1 handler for XML, builds the DOM tree */ xmlSAXHandlerV1 xmlDefaultSAXHandler = { xmlSAX2InternalSubset, xmlSAX2IsStandalone, xmlSAX2HasInternalSubset, xmlSAX2HasExternalSubset, xmlSAX2ResolveEntity, xmlSAX2GetEntity, xmlSAX2EntityDecl, xmlSAX2NotationDecl, xmlSAX2AttributeDecl, xmlSAX2ElementDecl, xmlSAX2UnparsedEntityDecl, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, xmlSAX2Reference, xmlSAX2Characters, xmlSAX2Characters, xmlSAX2ProcessingInstruction, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, xmlSAX2CDataBlock, xmlSAX2ExternalSubset, 0, }; #endif /* LIBXML_SAX1_ENABLED */ /** * xmlDefaultSAXLocator: * * The default SAX Locator * { getPublicId, getSystemId, getLineNumber, getColumnNumber} */ xmlSAXLocator xmlDefaultSAXLocator = { xmlSAX2GetPublicId, xmlSAX2GetSystemId, xmlSAX2GetLineNumber, xmlSAX2GetColumnNumber }; #ifdef LIBXML_HTML_ENABLED /** * htmlDefaultSAXHandler: * * Default old SAX v1 handler for HTML, builds the DOM tree */ xmlSAXHandlerV1 htmlDefaultSAXHandler = { xmlSAX2InternalSubset, NULL, NULL, NULL, NULL, xmlSAX2GetEntity, NULL, NULL, NULL, NULL, NULL, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, NULL, xmlSAX2Characters, xmlSAX2IgnorableWhitespace, xmlSAX2ProcessingInstruction, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, xmlSAX2CDataBlock, NULL, 0, }; #endif /* LIBXML_HTML_ENABLED */ #ifdef LIBXML_DOCB_ENABLED /** * docbDefaultSAXHandler: * * Default old SAX v1 handler for SGML DocBook, builds the DOM tree */ xmlSAXHandlerV1 docbDefaultSAXHandler = { xmlSAX2InternalSubset, xmlSAX2IsStandalone, xmlSAX2HasInternalSubset, xmlSAX2HasExternalSubset, xmlSAX2ResolveEntity, xmlSAX2GetEntity, xmlSAX2EntityDecl, NULL, NULL, NULL, NULL, xmlSAX2SetDocumentLocator, xmlSAX2StartDocument, xmlSAX2EndDocument, xmlSAX2StartElement, xmlSAX2EndElement, xmlSAX2Reference, xmlSAX2Characters, xmlSAX2IgnorableWhitespace, NULL, xmlSAX2Comment, xmlParserWarning, xmlParserError, xmlParserError, xmlSAX2GetParameterEntity, NULL, NULL, 0, }; #endif /* LIBXML_DOCB_ENABLED */ /** * xmlInitializeGlobalState: * @gs: a pointer to a newly allocated global state * * xmlInitializeGlobalState() initialize a global state with all the * default values of the library. */ void xmlInitializeGlobalState(xmlGlobalStatePtr gs) { #ifdef DEBUG_GLOBALS fprintf(stderr, "Initializing globals at %lu for thread %d\n", (unsigned long) gs, xmlGetThreadId()); #endif /* * Perform initialization as required by libxml */ if (xmlThrDefMutex == NULL) xmlInitGlobals(); xmlMutexLock(xmlThrDefMutex); #if defined(LIBXML_DOCB_ENABLED) && defined(LIBXML_LEGACY_ENABLED) && defined(LIBXML_SAX1_ENABLED) initdocbDefaultSAXHandler(&gs->docbDefaultSAXHandler); #endif #if defined(LIBXML_HTML_ENABLED) && defined(LIBXML_LEGACY_ENABLED) inithtmlDefaultSAXHandler(&gs->htmlDefaultSAXHandler); #endif gs->oldXMLWDcompatibility = 0; gs->xmlBufferAllocScheme = xmlBufferAllocSchemeThrDef; gs->xmlDefaultBufferSize = xmlDefaultBufferSizeThrDef; #if defined(LIBXML_SAX1_ENABLED) && defined(LIBXML_LEGACY_ENABLED) initxmlDefaultSAXHandler(&gs->xmlDefaultSAXHandler, 1); #endif /* LIBXML_SAX1_ENABLED */ gs->xmlDefaultSAXLocator.getPublicId = xmlSAX2GetPublicId; gs->xmlDefaultSAXLocator.getSystemId = xmlSAX2GetSystemId; gs->xmlDefaultSAXLocator.getLineNumber = xmlSAX2GetLineNumber; gs->xmlDefaultSAXLocator.getColumnNumber = xmlSAX2GetColumnNumber; gs->xmlDoValidityCheckingDefaultValue = xmlDoValidityCheckingDefaultValueThrDef; #if defined(DEBUG_MEMORY_LOCATION) | defined(DEBUG_MEMORY) gs->xmlFree = (xmlFreeFunc) xmlMemFree; gs->xmlMalloc = (xmlMallocFunc) xmlMemMalloc; gs->xmlMallocAtomic = (xmlMallocFunc) xmlMemMalloc; gs->xmlRealloc = (xmlReallocFunc) xmlMemRealloc; gs->xmlMemStrdup = (xmlStrdupFunc) xmlMemoryStrdup; #else gs->xmlFree = (xmlFreeFunc) free; gs->xmlMalloc = (xmlMallocFunc) malloc; gs->xmlMallocAtomic = (xmlMallocFunc) malloc; gs->xmlRealloc = (xmlReallocFunc) realloc; gs->xmlMemStrdup = (xmlStrdupFunc) xmlStrdup; #endif gs->xmlGetWarningsDefaultValue = xmlGetWarningsDefaultValueThrDef; gs->xmlIndentTreeOutput = xmlIndentTreeOutputThrDef; gs->xmlTreeIndentString = xmlTreeIndentStringThrDef; gs->xmlKeepBlanksDefaultValue = xmlKeepBlanksDefaultValueThrDef; gs->xmlLineNumbersDefaultValue = xmlLineNumbersDefaultValueThrDef; gs->xmlLoadExtDtdDefaultValue = xmlLoadExtDtdDefaultValueThrDef; gs->xmlParserDebugEntities = xmlParserDebugEntitiesThrDef; gs->xmlParserVersion = LIBXML_VERSION_STRING; gs->xmlPedanticParserDefaultValue = xmlPedanticParserDefaultValueThrDef; gs->xmlSaveNoEmptyTags = xmlSaveNoEmptyTagsThrDef; gs->xmlSubstituteEntitiesDefaultValue = xmlSubstituteEntitiesDefaultValueThrDef; gs->xmlGenericError = xmlGenericErrorThrDef; gs->xmlStructuredError = xmlStructuredErrorThrDef; gs->xmlGenericErrorContext = xmlGenericErrorContextThrDef; gs->xmlRegisterNodeDefaultValue = xmlRegisterNodeDefaultValueThrDef; gs->xmlDeregisterNodeDefaultValue = xmlDeregisterNodeDefaultValueThrDef; gs->xmlParserInputBufferCreateFilenameValue = xmlParserInputBufferCreateFilenameValueThrDef; gs->xmlOutputBufferCreateFilenameValue = xmlOutputBufferCreateFilenameValueThrDef; memset(&gs->xmlLastError, 0, sizeof(xmlError)); xmlMutexUnlock(xmlThrDefMutex); } /** * DOC_DISABLE : we ignore missing doc for the xmlThrDef functions, * those are really internal work */ void xmlThrDefSetGenericErrorFunc(void *ctx, xmlGenericErrorFunc handler) { xmlMutexLock(xmlThrDefMutex); xmlGenericErrorContextThrDef = ctx; if (handler != NULL) xmlGenericErrorThrDef = handler; else xmlGenericErrorThrDef = xmlGenericErrorDefaultFunc; xmlMutexUnlock(xmlThrDefMutex); } void xmlThrDefSetStructuredErrorFunc(void *ctx, xmlStructuredErrorFunc handler) { xmlMutexLock(xmlThrDefMutex); xmlGenericErrorContextThrDef = ctx; xmlStructuredErrorThrDef = handler; xmlMutexUnlock(xmlThrDefMutex); } /** * xmlRegisterNodeDefault: * @func: function pointer to the new RegisterNodeFunc * * Registers a callback for node creation * * Returns the old value of the registration function */ xmlRegisterNodeFunc xmlRegisterNodeDefault(xmlRegisterNodeFunc func) { xmlRegisterNodeFunc old = xmlRegisterNodeDefaultValue; __xmlRegisterCallbacks = 1; xmlRegisterNodeDefaultValue = func; return(old); } xmlRegisterNodeFunc xmlThrDefRegisterNodeDefault(xmlRegisterNodeFunc func) { xmlRegisterNodeFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlRegisterNodeDefaultValueThrDef; __xmlRegisterCallbacks = 1; xmlRegisterNodeDefaultValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } /** * xmlDeregisterNodeDefault: * @func: function pointer to the new DeregisterNodeFunc * * Registers a callback for node destruction * * Returns the previous value of the deregistration function */ xmlDeregisterNodeFunc xmlDeregisterNodeDefault(xmlDeregisterNodeFunc func) { xmlDeregisterNodeFunc old = xmlDeregisterNodeDefaultValue; __xmlRegisterCallbacks = 1; xmlDeregisterNodeDefaultValue = func; return(old); } xmlDeregisterNodeFunc xmlThrDefDeregisterNodeDefault(xmlDeregisterNodeFunc func) { xmlDeregisterNodeFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlDeregisterNodeDefaultValueThrDef; __xmlRegisterCallbacks = 1; xmlDeregisterNodeDefaultValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } xmlParserInputBufferCreateFilenameFunc xmlThrDefParserInputBufferCreateFilenameDefault(xmlParserInputBufferCreateFilenameFunc func) { xmlParserInputBufferCreateFilenameFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlParserInputBufferCreateFilenameValueThrDef; if (old == NULL) { old = __xmlParserInputBufferCreateFilename; } xmlParserInputBufferCreateFilenameValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } xmlOutputBufferCreateFilenameFunc xmlThrDefOutputBufferCreateFilenameDefault(xmlOutputBufferCreateFilenameFunc func) { xmlOutputBufferCreateFilenameFunc old; xmlMutexLock(xmlThrDefMutex); old = xmlOutputBufferCreateFilenameValueThrDef; #ifdef LIBXML_OUTPUT_ENABLED if (old == NULL) { old = __xmlOutputBufferCreateFilename; } #endif xmlOutputBufferCreateFilenameValueThrDef = func; xmlMutexUnlock(xmlThrDefMutex); return(old); } #ifdef LIBXML_DOCB_ENABLED #undef docbDefaultSAXHandler xmlSAXHandlerV1 * __docbDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&docbDefaultSAXHandler); else return (&xmlGetGlobalState()->docbDefaultSAXHandler); } #endif #ifdef LIBXML_HTML_ENABLED #undef htmlDefaultSAXHandler xmlSAXHandlerV1 * __htmlDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&htmlDefaultSAXHandler); else return (&xmlGetGlobalState()->htmlDefaultSAXHandler); } #endif #undef xmlLastError xmlError * __xmlLastError(void) { if (IS_MAIN_THREAD) return (&xmlLastError); else return (&xmlGetGlobalState()->xmlLastError); } /* * The following memory routines were apparently lost at some point, * and were re-inserted at this point on June 10, 2004. Hope it's * the right place for them :-) */ #if defined(LIBXML_THREAD_ALLOC_ENABLED) && defined(LIBXML_THREAD_ENABLED) #undef xmlMalloc xmlMallocFunc * __xmlMalloc(void){ if (IS_MAIN_THREAD) return (&xmlMalloc); else return (&xmlGetGlobalState()->xmlMalloc); } #undef xmlMallocAtomic xmlMallocFunc * __xmlMallocAtomic(void){ if (IS_MAIN_THREAD) return (&xmlMallocAtomic); else return (&xmlGetGlobalState()->xmlMallocAtomic); } #undef xmlRealloc xmlReallocFunc * __xmlRealloc(void){ if (IS_MAIN_THREAD) return (&xmlRealloc); else return (&xmlGetGlobalState()->xmlRealloc); } #undef xmlFree xmlFreeFunc * __xmlFree(void){ if (IS_MAIN_THREAD) return (&xmlFree); else return (&xmlGetGlobalState()->xmlFree); } xmlStrdupFunc * __xmlMemStrdup(void){ if (IS_MAIN_THREAD) return (&xmlMemStrdup); else return (&xmlGetGlobalState()->xmlMemStrdup); } #endif /* * Everything starting from the line below is * Automatically generated by build_glob.py. * Do not modify the previous line. */ #undef oldXMLWDcompatibility int * __oldXMLWDcompatibility(void) { if (IS_MAIN_THREAD) return (&oldXMLWDcompatibility); else return (&xmlGetGlobalState()->oldXMLWDcompatibility); } #undef xmlBufferAllocScheme xmlBufferAllocationScheme * __xmlBufferAllocScheme(void) { if (IS_MAIN_THREAD) return (&xmlBufferAllocScheme); else return (&xmlGetGlobalState()->xmlBufferAllocScheme); } xmlBufferAllocationScheme xmlThrDefBufferAllocScheme(xmlBufferAllocationScheme v) { xmlBufferAllocationScheme ret; xmlMutexLock(xmlThrDefMutex); ret = xmlBufferAllocSchemeThrDef; xmlBufferAllocSchemeThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlDefaultBufferSize int * __xmlDefaultBufferSize(void) { if (IS_MAIN_THREAD) return (&xmlDefaultBufferSize); else return (&xmlGetGlobalState()->xmlDefaultBufferSize); } int xmlThrDefDefaultBufferSize(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlDefaultBufferSizeThrDef; xmlDefaultBufferSizeThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #ifdef LIBXML_SAX1_ENABLED #undef xmlDefaultSAXHandler xmlSAXHandlerV1 * __xmlDefaultSAXHandler(void) { if (IS_MAIN_THREAD) return (&xmlDefaultSAXHandler); else return (&xmlGetGlobalState()->xmlDefaultSAXHandler); } #endif /* LIBXML_SAX1_ENABLED */ #undef xmlDefaultSAXLocator xmlSAXLocator * __xmlDefaultSAXLocator(void) { if (IS_MAIN_THREAD) return (&xmlDefaultSAXLocator); else return (&xmlGetGlobalState()->xmlDefaultSAXLocator); } #undef xmlDoValidityCheckingDefaultValue int * __xmlDoValidityCheckingDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlDoValidityCheckingDefaultValue); else return (&xmlGetGlobalState()->xmlDoValidityCheckingDefaultValue); } int xmlThrDefDoValidityCheckingDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlDoValidityCheckingDefaultValueThrDef; xmlDoValidityCheckingDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlGenericError xmlGenericErrorFunc * __xmlGenericError(void) { if (IS_MAIN_THREAD) return (&xmlGenericError); else return (&xmlGetGlobalState()->xmlGenericError); } #undef xmlStructuredError xmlStructuredErrorFunc * __xmlStructuredError(void) { if (IS_MAIN_THREAD) return (&xmlStructuredError); else return (&xmlGetGlobalState()->xmlStructuredError); } #undef xmlGenericErrorContext void * * __xmlGenericErrorContext(void) { if (IS_MAIN_THREAD) return (&xmlGenericErrorContext); else return (&xmlGetGlobalState()->xmlGenericErrorContext); } #undef xmlGetWarningsDefaultValue int * __xmlGetWarningsDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlGetWarningsDefaultValue); else return (&xmlGetGlobalState()->xmlGetWarningsDefaultValue); } int xmlThrDefGetWarningsDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlGetWarningsDefaultValueThrDef; xmlGetWarningsDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlIndentTreeOutput int * __xmlIndentTreeOutput(void) { if (IS_MAIN_THREAD) return (&xmlIndentTreeOutput); else return (&xmlGetGlobalState()->xmlIndentTreeOutput); } int xmlThrDefIndentTreeOutput(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlIndentTreeOutputThrDef; xmlIndentTreeOutputThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlTreeIndentString const char * * __xmlTreeIndentString(void) { if (IS_MAIN_THREAD) return (&xmlTreeIndentString); else return (&xmlGetGlobalState()->xmlTreeIndentString); } const char * xmlThrDefTreeIndentString(const char * v) { const char * ret; xmlMutexLock(xmlThrDefMutex); ret = xmlTreeIndentStringThrDef; xmlTreeIndentStringThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlKeepBlanksDefaultValue int * __xmlKeepBlanksDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlKeepBlanksDefaultValue); else return (&xmlGetGlobalState()->xmlKeepBlanksDefaultValue); } int xmlThrDefKeepBlanksDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlKeepBlanksDefaultValueThrDef; xmlKeepBlanksDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlLineNumbersDefaultValue int * __xmlLineNumbersDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlLineNumbersDefaultValue); else return (&xmlGetGlobalState()->xmlLineNumbersDefaultValue); } int xmlThrDefLineNumbersDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlLineNumbersDefaultValueThrDef; xmlLineNumbersDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlLoadExtDtdDefaultValue int * __xmlLoadExtDtdDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlLoadExtDtdDefaultValue); else return (&xmlGetGlobalState()->xmlLoadExtDtdDefaultValue); } int xmlThrDefLoadExtDtdDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlLoadExtDtdDefaultValueThrDef; xmlLoadExtDtdDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlParserDebugEntities int * __xmlParserDebugEntities(void) { if (IS_MAIN_THREAD) return (&xmlParserDebugEntities); else return (&xmlGetGlobalState()->xmlParserDebugEntities); } int xmlThrDefParserDebugEntities(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlParserDebugEntitiesThrDef; xmlParserDebugEntitiesThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlParserVersion const char * * __xmlParserVersion(void) { if (IS_MAIN_THREAD) return (&xmlParserVersion); else return (&xmlGetGlobalState()->xmlParserVersion); } #undef xmlPedanticParserDefaultValue int * __xmlPedanticParserDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlPedanticParserDefaultValue); else return (&xmlGetGlobalState()->xmlPedanticParserDefaultValue); } int xmlThrDefPedanticParserDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlPedanticParserDefaultValueThrDef; xmlPedanticParserDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlSaveNoEmptyTags int * __xmlSaveNoEmptyTags(void) { if (IS_MAIN_THREAD) return (&xmlSaveNoEmptyTags); else return (&xmlGetGlobalState()->xmlSaveNoEmptyTags); } int xmlThrDefSaveNoEmptyTags(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlSaveNoEmptyTagsThrDef; xmlSaveNoEmptyTagsThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlSubstituteEntitiesDefaultValue int * __xmlSubstituteEntitiesDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlSubstituteEntitiesDefaultValue); else return (&xmlGetGlobalState()->xmlSubstituteEntitiesDefaultValue); } int xmlThrDefSubstituteEntitiesDefaultValue(int v) { int ret; xmlMutexLock(xmlThrDefMutex); ret = xmlSubstituteEntitiesDefaultValueThrDef; xmlSubstituteEntitiesDefaultValueThrDef = v; xmlMutexUnlock(xmlThrDefMutex); return ret; } #undef xmlRegisterNodeDefaultValue xmlRegisterNodeFunc * __xmlRegisterNodeDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlRegisterNodeDefaultValue); else return (&xmlGetGlobalState()->xmlRegisterNodeDefaultValue); } #undef xmlDeregisterNodeDefaultValue xmlDeregisterNodeFunc * __xmlDeregisterNodeDefaultValue(void) { if (IS_MAIN_THREAD) return (&xmlDeregisterNodeDefaultValue); else return (&xmlGetGlobalState()->xmlDeregisterNodeDefaultValue); } #undef xmlParserInputBufferCreateFilenameValue xmlParserInputBufferCreateFilenameFunc * __xmlParserInputBufferCreateFilenameValue(void) { if (IS_MAIN_THREAD) return (&xmlParserInputBufferCreateFilenameValue); else return (&xmlGetGlobalState()->xmlParserInputBufferCreateFilenameValue); } #undef xmlOutputBufferCreateFilenameValue xmlOutputBufferCreateFilenameFunc * __xmlOutputBufferCreateFilenameValue(void) { if (IS_MAIN_THREAD) return (&xmlOutputBufferCreateFilenameValue); else return (&xmlGetGlobalState()->xmlOutputBufferCreateFilenameValue); } #define bottom_globals #include "elfgcchack.h"
gpl-3.0
JavaJens/TextSecure
jni/webrtc/modules/audio_coding/codecs/ilbc/refiner.c
68
4841
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /****************************************************************** iLBC Speech Coder ANSI-C Source Code WebRtcIlbcfix_Refiner.c ******************************************************************/ #include "defines.h" #include "constants.h" #include "enh_upsample.h" #include "my_corr.h" /*----------------------------------------------------------------* * find segment starting near idata+estSegPos that has highest * correlation with idata+centerStartPos through * idata+centerStartPos+ENH_BLOCKL-1 segment is found at a * resolution of ENH_UPSO times the original of the original * sampling rate *---------------------------------------------------------------*/ void WebRtcIlbcfix_Refiner( int16_t *updStartPos, /* (o) updated start point (Q-2) */ int16_t *idata, /* (i) original data buffer */ int16_t idatal, /* (i) dimension of idata */ int16_t centerStartPos, /* (i) beginning center segment */ int16_t estSegPos, /* (i) estimated beginning other segment (Q-2) */ int16_t *surround, /* (i/o) The contribution from this sequence summed with earlier contributions */ int16_t gain /* (i) Gain to use for this sequence */ ){ int16_t estSegPosRounded,searchSegStartPos,searchSegEndPos,corrdim; int16_t tloc,tloc2,i,st,en,fraction; int32_t maxtemp, scalefact; int16_t *filtStatePtr, *polyPtr; /* Stack based */ int16_t filt[7]; int32_t corrVecUps[ENH_CORRDIM*ENH_UPS0]; int32_t corrVecTemp[ENH_CORRDIM]; int16_t vect[ENH_VECTL]; int16_t corrVec[ENH_CORRDIM]; /* defining array bounds */ estSegPosRounded=WEBRTC_SPL_RSHIFT_W16((estSegPos - 2),2); searchSegStartPos=estSegPosRounded-ENH_SLOP; if (searchSegStartPos<0) { searchSegStartPos=0; } searchSegEndPos=estSegPosRounded+ENH_SLOP; if(searchSegEndPos+ENH_BLOCKL >= idatal) { searchSegEndPos=idatal-ENH_BLOCKL-1; } corrdim=searchSegEndPos-searchSegStartPos+1; /* compute upsampled correlation and find location of max */ WebRtcIlbcfix_MyCorr(corrVecTemp,idata+searchSegStartPos, (int16_t)(corrdim+ENH_BLOCKL-1),idata+centerStartPos,ENH_BLOCKL); /* Calculate the rescaling factor for the correlation in order to put the correlation in a int16_t vector instead */ maxtemp=WebRtcSpl_MaxAbsValueW32(corrVecTemp, (int16_t)corrdim); scalefact=WebRtcSpl_GetSizeInBits(maxtemp)-15; if (scalefact>0) { for (i=0;i<corrdim;i++) { corrVec[i]=(int16_t)WEBRTC_SPL_RSHIFT_W32(corrVecTemp[i], scalefact); } } else { for (i=0;i<corrdim;i++) { corrVec[i]=(int16_t)corrVecTemp[i]; } } /* In order to guarantee that all values are initialized */ for (i=corrdim;i<ENH_CORRDIM;i++) { corrVec[i]=0; } /* Upsample the correlation */ WebRtcIlbcfix_EnhUpsample(corrVecUps,corrVec); /* Find maximum */ tloc=WebRtcSpl_MaxIndexW32(corrVecUps, (int16_t) (ENH_UPS0*corrdim)); /* make vector can be upsampled without ever running outside bounds */ *updStartPos = (int16_t)WEBRTC_SPL_MUL_16_16(searchSegStartPos,4) + tloc + 4; tloc2 = WEBRTC_SPL_RSHIFT_W16((tloc+3), 2); st=searchSegStartPos+tloc2-ENH_FL0; /* initialize the vector to be filtered, stuff with zeros when data is outside idata buffer */ if(st<0){ WebRtcSpl_MemSetW16(vect, 0, (int16_t)(-st)); WEBRTC_SPL_MEMCPY_W16(&vect[-st], idata, (ENH_VECTL+st)); } else{ en=st+ENH_VECTL; if(en>idatal){ WEBRTC_SPL_MEMCPY_W16(vect, &idata[st], (ENH_VECTL-(en-idatal))); WebRtcSpl_MemSetW16(&vect[ENH_VECTL-(en-idatal)], 0, (int16_t)(en-idatal)); } else { WEBRTC_SPL_MEMCPY_W16(vect, &idata[st], ENH_VECTL); } } /* Calculate which of the 4 fractions to use */ fraction=(int16_t)WEBRTC_SPL_MUL_16_16(tloc2,ENH_UPS0)-tloc; /* compute the segment (this is actually a convolution) */ filtStatePtr = filt + 6; polyPtr = (int16_t*)WebRtcIlbcfix_kEnhPolyPhaser[fraction]; for (i=0;i<7;i++) { *filtStatePtr-- = *polyPtr++; } WebRtcSpl_FilterMAFastQ12( &vect[6], vect, filt, ENH_FLO_MULT2_PLUS1, ENH_BLOCKL); /* Add the contribution from this vector (scaled with gain) to the total surround vector */ WebRtcSpl_AddAffineVectorToVector( surround, vect, gain, (int32_t)32768, 16, ENH_BLOCKL); return; }
gpl-3.0
guougangxue/Sigil
src/BoostParts/libs/filesystem/src/path_traits.cpp
75
7749
// filesystem path_traits.cpp --------------------------------------------------------// // Copyright Beman Dawes 2008, 2009 // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt // Library home page: http://www.boost.org/libs/filesystem //--------------------------------------------------------------------------------------// // define BOOST_FILESYSTEM_SOURCE so that <boost/system/config.hpp> knows // the library is being built (possibly exporting rather than importing code) #define BOOST_FILESYSTEM_SOURCE #ifndef BOOST_SYSTEM_NO_DEPRECATED # define BOOST_SYSTEM_NO_DEPRECATED #endif #include <boost/filesystem/config.hpp> #include <boost/filesystem/path_traits.hpp> #include <boost/system/system_error.hpp> #include <boost/scoped_array.hpp> #include <locale> // for codecvt_base::result #include <cstring> // for strlen #include <cwchar> // for wcslen namespace pt = boost::filesystem::path_traits; namespace fs = boost::filesystem; namespace bs = boost::system; //--------------------------------------------------------------------------------------// // configuration // //--------------------------------------------------------------------------------------// #ifndef BOOST_FILESYSTEM_CODECVT_BUF_SIZE # define BOOST_FILESYSTEM_CODECVT_BUF_SIZE 256 #endif namespace { const std::size_t default_codecvt_buf_size = BOOST_FILESYSTEM_CODECVT_BUF_SIZE; //--------------------------------------------------------------------------------------// // // // The public convert() functions do buffer management, and then forward to the // // convert_aux() functions for the actual call to the codecvt facet. // // // //--------------------------------------------------------------------------------------// //--------------------------------------------------------------------------------------// // convert_aux const char* to wstring // //--------------------------------------------------------------------------------------// void convert_aux( const char* from, const char* from_end, wchar_t* to, wchar_t* to_end, std::wstring & target, const pt::codecvt_type & cvt) { //std::cout << std::hex // << " from=" << std::size_t(from) // << " from_end=" << std::size_t(from_end) // << " to=" << std::size_t(to) // << " to_end=" << std::size_t(to_end) // << std::endl; std::mbstate_t state = std::mbstate_t(); // perhaps unneeded, but cuts bug reports const char* from_next; wchar_t* to_next; std::codecvt_base::result res; if ((res=cvt.in(state, from, from_end, from_next, to, to_end, to_next)) != std::codecvt_base::ok) { //std::cout << " result is " << static_cast<int>(res) << std::endl; BOOST_FILESYSTEM_THROW(bs::system_error(res, fs::codecvt_error_category(), "boost::filesystem::path codecvt to wstring")); } target.append(to, to_next); } //--------------------------------------------------------------------------------------// // convert_aux const wchar_t* to string // //--------------------------------------------------------------------------------------// void convert_aux( const wchar_t* from, const wchar_t* from_end, char* to, char* to_end, std::string & target, const pt::codecvt_type & cvt) { //std::cout << std::hex // << " from=" << std::size_t(from) // << " from_end=" << std::size_t(from_end) // << " to=" << std::size_t(to) // << " to_end=" << std::size_t(to_end) // << std::endl; std::mbstate_t state = std::mbstate_t(); // perhaps unneeded, but cuts bug reports const wchar_t* from_next; char* to_next; std::codecvt_base::result res; if ((res=cvt.out(state, from, from_end, from_next, to, to_end, to_next)) != std::codecvt_base::ok) { //std::cout << " result is " << static_cast<int>(res) << std::endl; BOOST_FILESYSTEM_THROW(bs::system_error(res, fs::codecvt_error_category(), "boost::filesystem::path codecvt to string")); } target.append(to, to_next); } } // unnamed namespace //--------------------------------------------------------------------------------------// // path_traits // //--------------------------------------------------------------------------------------// namespace boost { namespace filesystem { namespace path_traits { //--------------------------------------------------------------------------------------// // convert const char* to wstring // //--------------------------------------------------------------------------------------// BOOST_FILESYSTEM_DECL void convert(const char* from, const char* from_end, // 0 for null terminated MBCS std::wstring & to, const codecvt_type & cvt) { BOOST_ASSERT(from); if (!from_end) // null terminated { from_end = from + std::strlen(from); } if (from == from_end) return; std::size_t buf_size = (from_end - from) * 3; // perhaps too large, but that's OK // dynamically allocate a buffer only if source is unusually large if (buf_size > default_codecvt_buf_size) { boost::scoped_array< wchar_t > buf(new wchar_t [buf_size]); convert_aux(from, from_end, buf.get(), buf.get()+buf_size, to, cvt); } else { wchar_t buf[default_codecvt_buf_size]; convert_aux(from, from_end, buf, buf+default_codecvt_buf_size, to, cvt); } } //--------------------------------------------------------------------------------------// // convert const wchar_t* to string // //--------------------------------------------------------------------------------------// BOOST_FILESYSTEM_DECL void convert(const wchar_t* from, const wchar_t* from_end, // 0 for null terminated MBCS std::string & to, const codecvt_type & cvt) { BOOST_ASSERT(from); if (!from_end) // null terminated { from_end = from + std::wcslen(from); } if (from == from_end) return; // The codecvt length functions may not be implemented, and I don't really // understand them either. Thus this code is just a guess; if it turns // out the buffer is too small then an error will be reported and the code // will have to be fixed. std::size_t buf_size = (from_end - from) * 4; // perhaps too large, but that's OK buf_size += 4; // encodings like shift-JIS need some prefix space // dynamically allocate a buffer only if source is unusually large if (buf_size > default_codecvt_buf_size) { boost::scoped_array< char > buf(new char [buf_size]); convert_aux(from, from_end, buf.get(), buf.get()+buf_size, to, cvt); } else { char buf[default_codecvt_buf_size]; convert_aux(from, from_end, buf, buf+default_codecvt_buf_size, to, cvt); } } }}} // namespace boost::filesystem::path_traits
gpl-3.0
WisniaPL/LeEco-Le1S-Kernel
drivers/mmc/host/mxs-mmc.c
80
19724
/* * Portions copyright (C) 2003 Russell King, PXA MMCI Driver * Portions copyright (C) 2004-2005 Pierre Ossman, W83L51xD SD/MMC driver * * Copyright 2008 Embedded Alley Solutions, Inc. * Copyright 2009-2011 Freescale Semiconductor, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/dmaengine.h> #include <linux/highmem.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/completion.h> #include <linux/mmc/host.h> #include <linux/mmc/mmc.h> #include <linux/mmc/sdio.h> #include <linux/gpio.h> #include <linux/regulator/consumer.h> #include <linux/module.h> #include <linux/pinctrl/consumer.h> #include <linux/stmp_device.h> #include <linux/spi/mxs-spi.h> #define DRIVER_NAME "mxs-mmc" #define MXS_MMC_IRQ_BITS (BM_SSP_CTRL1_SDIO_IRQ | \ BM_SSP_CTRL1_RESP_ERR_IRQ | \ BM_SSP_CTRL1_RESP_TIMEOUT_IRQ | \ BM_SSP_CTRL1_DATA_TIMEOUT_IRQ | \ BM_SSP_CTRL1_DATA_CRC_IRQ | \ BM_SSP_CTRL1_FIFO_UNDERRUN_IRQ | \ BM_SSP_CTRL1_RECV_TIMEOUT_IRQ | \ BM_SSP_CTRL1_FIFO_OVERRUN_IRQ) /* card detect polling timeout */ #define MXS_MMC_DETECT_TIMEOUT (HZ/2) struct mxs_mmc_host { struct mxs_ssp ssp; struct mmc_host *mmc; struct mmc_request *mrq; struct mmc_command *cmd; struct mmc_data *data; unsigned char bus_width; spinlock_t lock; int sdio_irq_en; int wp_gpio; bool wp_inverted; bool cd_inverted; bool broken_cd; bool non_removable; }; static int mxs_mmc_get_ro(struct mmc_host *mmc) { struct mxs_mmc_host *host = mmc_priv(mmc); int ret; if (!gpio_is_valid(host->wp_gpio)) return -EINVAL; ret = gpio_get_value(host->wp_gpio); if (host->wp_inverted) ret = !ret; return ret; } static int mxs_mmc_get_cd(struct mmc_host *mmc) { struct mxs_mmc_host *host = mmc_priv(mmc); struct mxs_ssp *ssp = &host->ssp; return host->non_removable || host->broken_cd || !(readl(ssp->base + HW_SSP_STATUS(ssp)) & BM_SSP_STATUS_CARD_DETECT) ^ host->cd_inverted; } static void mxs_mmc_reset(struct mxs_mmc_host *host) { struct mxs_ssp *ssp = &host->ssp; u32 ctrl0, ctrl1; stmp_reset_block(ssp->base); ctrl0 = BM_SSP_CTRL0_IGNORE_CRC; ctrl1 = BF_SSP(0x3, CTRL1_SSP_MODE) | BF_SSP(0x7, CTRL1_WORD_LENGTH) | BM_SSP_CTRL1_DMA_ENABLE | BM_SSP_CTRL1_POLARITY | BM_SSP_CTRL1_RECV_TIMEOUT_IRQ_EN | BM_SSP_CTRL1_DATA_CRC_IRQ_EN | BM_SSP_CTRL1_DATA_TIMEOUT_IRQ_EN | BM_SSP_CTRL1_RESP_TIMEOUT_IRQ_EN | BM_SSP_CTRL1_RESP_ERR_IRQ_EN; writel(BF_SSP(0xffff, TIMING_TIMEOUT) | BF_SSP(2, TIMING_CLOCK_DIVIDE) | BF_SSP(0, TIMING_CLOCK_RATE), ssp->base + HW_SSP_TIMING(ssp)); if (host->sdio_irq_en) { ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; ctrl1 |= BM_SSP_CTRL1_SDIO_IRQ_EN; } writel(ctrl0, ssp->base + HW_SSP_CTRL0); writel(ctrl1, ssp->base + HW_SSP_CTRL1(ssp)); } static void mxs_mmc_start_cmd(struct mxs_mmc_host *host, struct mmc_command *cmd); static void mxs_mmc_request_done(struct mxs_mmc_host *host) { struct mmc_command *cmd = host->cmd; struct mmc_data *data = host->data; struct mmc_request *mrq = host->mrq; struct mxs_ssp *ssp = &host->ssp; if (mmc_resp_type(cmd) & MMC_RSP_PRESENT) { if (mmc_resp_type(cmd) & MMC_RSP_136) { cmd->resp[3] = readl(ssp->base + HW_SSP_SDRESP0(ssp)); cmd->resp[2] = readl(ssp->base + HW_SSP_SDRESP1(ssp)); cmd->resp[1] = readl(ssp->base + HW_SSP_SDRESP2(ssp)); cmd->resp[0] = readl(ssp->base + HW_SSP_SDRESP3(ssp)); } else { cmd->resp[0] = readl(ssp->base + HW_SSP_SDRESP0(ssp)); } } if (data) { dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len, ssp->dma_dir); /* * If there was an error on any block, we mark all * data blocks as being in error. */ if (!data->error) data->bytes_xfered = data->blocks * data->blksz; else data->bytes_xfered = 0; host->data = NULL; if (mrq->stop) { mxs_mmc_start_cmd(host, mrq->stop); return; } } host->mrq = NULL; mmc_request_done(host->mmc, mrq); } static void mxs_mmc_dma_irq_callback(void *param) { struct mxs_mmc_host *host = param; mxs_mmc_request_done(host); } static irqreturn_t mxs_mmc_irq_handler(int irq, void *dev_id) { struct mxs_mmc_host *host = dev_id; struct mmc_command *cmd = host->cmd; struct mmc_data *data = host->data; struct mxs_ssp *ssp = &host->ssp; u32 stat; spin_lock(&host->lock); stat = readl(ssp->base + HW_SSP_CTRL1(ssp)); writel(stat & MXS_MMC_IRQ_BITS, ssp->base + HW_SSP_CTRL1(ssp) + STMP_OFFSET_REG_CLR); spin_unlock(&host->lock); if ((stat & BM_SSP_CTRL1_SDIO_IRQ) && (stat & BM_SSP_CTRL1_SDIO_IRQ_EN)) mmc_signal_sdio_irq(host->mmc); if (stat & BM_SSP_CTRL1_RESP_TIMEOUT_IRQ) cmd->error = -ETIMEDOUT; else if (stat & BM_SSP_CTRL1_RESP_ERR_IRQ) cmd->error = -EIO; if (data) { if (stat & (BM_SSP_CTRL1_DATA_TIMEOUT_IRQ | BM_SSP_CTRL1_RECV_TIMEOUT_IRQ)) data->error = -ETIMEDOUT; else if (stat & BM_SSP_CTRL1_DATA_CRC_IRQ) data->error = -EILSEQ; else if (stat & (BM_SSP_CTRL1_FIFO_UNDERRUN_IRQ | BM_SSP_CTRL1_FIFO_OVERRUN_IRQ)) data->error = -EIO; } return IRQ_HANDLED; } static struct dma_async_tx_descriptor *mxs_mmc_prep_dma( struct mxs_mmc_host *host, unsigned long flags) { struct mxs_ssp *ssp = &host->ssp; struct dma_async_tx_descriptor *desc; struct mmc_data *data = host->data; struct scatterlist * sgl; unsigned int sg_len; if (data) { /* data */ dma_map_sg(mmc_dev(host->mmc), data->sg, data->sg_len, ssp->dma_dir); sgl = data->sg; sg_len = data->sg_len; } else { /* pio */ sgl = (struct scatterlist *) ssp->ssp_pio_words; sg_len = SSP_PIO_NUM; } desc = dmaengine_prep_slave_sg(ssp->dmach, sgl, sg_len, ssp->slave_dirn, flags); if (desc) { desc->callback = mxs_mmc_dma_irq_callback; desc->callback_param = host; } else { if (data) dma_unmap_sg(mmc_dev(host->mmc), data->sg, data->sg_len, ssp->dma_dir); } return desc; } static void mxs_mmc_bc(struct mxs_mmc_host *host) { struct mxs_ssp *ssp = &host->ssp; struct mmc_command *cmd = host->cmd; struct dma_async_tx_descriptor *desc; u32 ctrl0, cmd0, cmd1; ctrl0 = BM_SSP_CTRL0_ENABLE | BM_SSP_CTRL0_IGNORE_CRC; cmd0 = BF_SSP(cmd->opcode, CMD0_CMD) | BM_SSP_CMD0_APPEND_8CYC; cmd1 = cmd->arg; if (host->sdio_irq_en) { ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; cmd0 |= BM_SSP_CMD0_CONT_CLKING_EN | BM_SSP_CMD0_SLOW_CLKING_EN; } ssp->ssp_pio_words[0] = ctrl0; ssp->ssp_pio_words[1] = cmd0; ssp->ssp_pio_words[2] = cmd1; ssp->dma_dir = DMA_NONE; ssp->slave_dirn = DMA_TRANS_NONE; desc = mxs_mmc_prep_dma(host, DMA_CTRL_ACK); if (!desc) goto out; dmaengine_submit(desc); dma_async_issue_pending(ssp->dmach); return; out: dev_warn(mmc_dev(host->mmc), "%s: failed to prep dma\n", __func__); } static void mxs_mmc_ac(struct mxs_mmc_host *host) { struct mxs_ssp *ssp = &host->ssp; struct mmc_command *cmd = host->cmd; struct dma_async_tx_descriptor *desc; u32 ignore_crc, get_resp, long_resp; u32 ctrl0, cmd0, cmd1; ignore_crc = (mmc_resp_type(cmd) & MMC_RSP_CRC) ? 0 : BM_SSP_CTRL0_IGNORE_CRC; get_resp = (mmc_resp_type(cmd) & MMC_RSP_PRESENT) ? BM_SSP_CTRL0_GET_RESP : 0; long_resp = (mmc_resp_type(cmd) & MMC_RSP_136) ? BM_SSP_CTRL0_LONG_RESP : 0; ctrl0 = BM_SSP_CTRL0_ENABLE | ignore_crc | get_resp | long_resp; cmd0 = BF_SSP(cmd->opcode, CMD0_CMD); cmd1 = cmd->arg; if (cmd->opcode == MMC_STOP_TRANSMISSION) cmd0 |= BM_SSP_CMD0_APPEND_8CYC; if (host->sdio_irq_en) { ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; cmd0 |= BM_SSP_CMD0_CONT_CLKING_EN | BM_SSP_CMD0_SLOW_CLKING_EN; } ssp->ssp_pio_words[0] = ctrl0; ssp->ssp_pio_words[1] = cmd0; ssp->ssp_pio_words[2] = cmd1; ssp->dma_dir = DMA_NONE; ssp->slave_dirn = DMA_TRANS_NONE; desc = mxs_mmc_prep_dma(host, DMA_CTRL_ACK); if (!desc) goto out; dmaengine_submit(desc); dma_async_issue_pending(ssp->dmach); return; out: dev_warn(mmc_dev(host->mmc), "%s: failed to prep dma\n", __func__); } static unsigned short mxs_ns_to_ssp_ticks(unsigned clock_rate, unsigned ns) { const unsigned int ssp_timeout_mul = 4096; /* * Calculate ticks in ms since ns are large numbers * and might overflow */ const unsigned int clock_per_ms = clock_rate / 1000; const unsigned int ms = ns / 1000; const unsigned int ticks = ms * clock_per_ms; const unsigned int ssp_ticks = ticks / ssp_timeout_mul; WARN_ON(ssp_ticks == 0); return ssp_ticks; } static void mxs_mmc_adtc(struct mxs_mmc_host *host) { struct mmc_command *cmd = host->cmd; struct mmc_data *data = cmd->data; struct dma_async_tx_descriptor *desc; struct scatterlist *sgl = data->sg, *sg; unsigned int sg_len = data->sg_len; unsigned int i; unsigned short dma_data_dir, timeout; enum dma_transfer_direction slave_dirn; unsigned int data_size = 0, log2_blksz; unsigned int blocks = data->blocks; struct mxs_ssp *ssp = &host->ssp; u32 ignore_crc, get_resp, long_resp, read; u32 ctrl0, cmd0, cmd1, val; ignore_crc = (mmc_resp_type(cmd) & MMC_RSP_CRC) ? 0 : BM_SSP_CTRL0_IGNORE_CRC; get_resp = (mmc_resp_type(cmd) & MMC_RSP_PRESENT) ? BM_SSP_CTRL0_GET_RESP : 0; long_resp = (mmc_resp_type(cmd) & MMC_RSP_136) ? BM_SSP_CTRL0_LONG_RESP : 0; if (data->flags & MMC_DATA_WRITE) { dma_data_dir = DMA_TO_DEVICE; slave_dirn = DMA_MEM_TO_DEV; read = 0; } else { dma_data_dir = DMA_FROM_DEVICE; slave_dirn = DMA_DEV_TO_MEM; read = BM_SSP_CTRL0_READ; } ctrl0 = BF_SSP(host->bus_width, CTRL0_BUS_WIDTH) | ignore_crc | get_resp | long_resp | BM_SSP_CTRL0_DATA_XFER | read | BM_SSP_CTRL0_WAIT_FOR_IRQ | BM_SSP_CTRL0_ENABLE; cmd0 = BF_SSP(cmd->opcode, CMD0_CMD); /* get logarithm to base 2 of block size for setting register */ log2_blksz = ilog2(data->blksz); /* * take special care of the case that data size from data->sg * is not equal to blocks x blksz */ for_each_sg(sgl, sg, sg_len, i) data_size += sg->length; if (data_size != data->blocks * data->blksz) blocks = 1; /* xfer count, block size and count need to be set differently */ if (ssp_is_old(ssp)) { ctrl0 |= BF_SSP(data_size, CTRL0_XFER_COUNT); cmd0 |= BF_SSP(log2_blksz, CMD0_BLOCK_SIZE) | BF_SSP(blocks - 1, CMD0_BLOCK_COUNT); } else { writel(data_size, ssp->base + HW_SSP_XFER_SIZE); writel(BF_SSP(log2_blksz, BLOCK_SIZE_BLOCK_SIZE) | BF_SSP(blocks - 1, BLOCK_SIZE_BLOCK_COUNT), ssp->base + HW_SSP_BLOCK_SIZE); } if (cmd->opcode == SD_IO_RW_EXTENDED) cmd0 |= BM_SSP_CMD0_APPEND_8CYC; cmd1 = cmd->arg; if (host->sdio_irq_en) { ctrl0 |= BM_SSP_CTRL0_SDIO_IRQ_CHECK; cmd0 |= BM_SSP_CMD0_CONT_CLKING_EN | BM_SSP_CMD0_SLOW_CLKING_EN; } /* set the timeout count */ timeout = mxs_ns_to_ssp_ticks(ssp->clk_rate, data->timeout_ns); val = readl(ssp->base + HW_SSP_TIMING(ssp)); val &= ~(BM_SSP_TIMING_TIMEOUT); val |= BF_SSP(timeout, TIMING_TIMEOUT); writel(val, ssp->base + HW_SSP_TIMING(ssp)); /* pio */ ssp->ssp_pio_words[0] = ctrl0; ssp->ssp_pio_words[1] = cmd0; ssp->ssp_pio_words[2] = cmd1; ssp->dma_dir = DMA_NONE; ssp->slave_dirn = DMA_TRANS_NONE; desc = mxs_mmc_prep_dma(host, 0); if (!desc) goto out; /* append data sg */ WARN_ON(host->data != NULL); host->data = data; ssp->dma_dir = dma_data_dir; ssp->slave_dirn = slave_dirn; desc = mxs_mmc_prep_dma(host, DMA_PREP_INTERRUPT | DMA_CTRL_ACK); if (!desc) goto out; dmaengine_submit(desc); dma_async_issue_pending(ssp->dmach); return; out: dev_warn(mmc_dev(host->mmc), "%s: failed to prep dma\n", __func__); } static void mxs_mmc_start_cmd(struct mxs_mmc_host *host, struct mmc_command *cmd) { host->cmd = cmd; switch (mmc_cmd_type(cmd)) { case MMC_CMD_BC: mxs_mmc_bc(host); break; case MMC_CMD_BCR: mxs_mmc_ac(host); break; case MMC_CMD_AC: mxs_mmc_ac(host); break; case MMC_CMD_ADTC: mxs_mmc_adtc(host); break; default: dev_warn(mmc_dev(host->mmc), "%s: unknown MMC command\n", __func__); break; } } static void mxs_mmc_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct mxs_mmc_host *host = mmc_priv(mmc); WARN_ON(host->mrq != NULL); host->mrq = mrq; mxs_mmc_start_cmd(host, mrq->cmd); } static void mxs_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct mxs_mmc_host *host = mmc_priv(mmc); if (ios->bus_width == MMC_BUS_WIDTH_8) host->bus_width = 2; else if (ios->bus_width == MMC_BUS_WIDTH_4) host->bus_width = 1; else host->bus_width = 0; if (ios->clock) mxs_ssp_set_clk_rate(&host->ssp, ios->clock); } static void mxs_mmc_enable_sdio_irq(struct mmc_host *mmc, int enable) { struct mxs_mmc_host *host = mmc_priv(mmc); struct mxs_ssp *ssp = &host->ssp; unsigned long flags; spin_lock_irqsave(&host->lock, flags); host->sdio_irq_en = enable; if (enable) { writel(BM_SSP_CTRL0_SDIO_IRQ_CHECK, ssp->base + HW_SSP_CTRL0 + STMP_OFFSET_REG_SET); writel(BM_SSP_CTRL1_SDIO_IRQ_EN, ssp->base + HW_SSP_CTRL1(ssp) + STMP_OFFSET_REG_SET); } else { writel(BM_SSP_CTRL0_SDIO_IRQ_CHECK, ssp->base + HW_SSP_CTRL0 + STMP_OFFSET_REG_CLR); writel(BM_SSP_CTRL1_SDIO_IRQ_EN, ssp->base + HW_SSP_CTRL1(ssp) + STMP_OFFSET_REG_CLR); } spin_unlock_irqrestore(&host->lock, flags); if (enable && readl(ssp->base + HW_SSP_STATUS(ssp)) & BM_SSP_STATUS_SDIO_IRQ) mmc_signal_sdio_irq(host->mmc); } static const struct mmc_host_ops mxs_mmc_ops = { .request = mxs_mmc_request, .get_ro = mxs_mmc_get_ro, .get_cd = mxs_mmc_get_cd, .set_ios = mxs_mmc_set_ios, .enable_sdio_irq = mxs_mmc_enable_sdio_irq, }; static struct platform_device_id mxs_ssp_ids[] = { { .name = "imx23-mmc", .driver_data = IMX23_SSP, }, { .name = "imx28-mmc", .driver_data = IMX28_SSP, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(platform, mxs_ssp_ids); static const struct of_device_id mxs_mmc_dt_ids[] = { { .compatible = "fsl,imx23-mmc", .data = (void *) IMX23_SSP, }, { .compatible = "fsl,imx28-mmc", .data = (void *) IMX28_SSP, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, mxs_mmc_dt_ids); static int mxs_mmc_probe(struct platform_device *pdev) { const struct of_device_id *of_id = of_match_device(mxs_mmc_dt_ids, &pdev->dev); struct device_node *np = pdev->dev.of_node; struct mxs_mmc_host *host; struct mmc_host *mmc; struct resource *iores; struct pinctrl *pinctrl; int ret = 0, irq_err; struct regulator *reg_vmmc; enum of_gpio_flags flags; struct mxs_ssp *ssp; u32 bus_width = 0; iores = platform_get_resource(pdev, IORESOURCE_MEM, 0); irq_err = platform_get_irq(pdev, 0); if (!iores || irq_err < 0) return -EINVAL; mmc = mmc_alloc_host(sizeof(struct mxs_mmc_host), &pdev->dev); if (!mmc) return -ENOMEM; host = mmc_priv(mmc); ssp = &host->ssp; ssp->dev = &pdev->dev; ssp->base = devm_ioremap_resource(&pdev->dev, iores); if (IS_ERR(ssp->base)) { ret = PTR_ERR(ssp->base); goto out_mmc_free; } ssp->devid = (enum mxs_ssp_id) of_id->data; host->mmc = mmc; host->sdio_irq_en = 0; reg_vmmc = devm_regulator_get(&pdev->dev, "vmmc"); if (!IS_ERR(reg_vmmc)) { ret = regulator_enable(reg_vmmc); if (ret) { dev_err(&pdev->dev, "Failed to enable vmmc regulator: %d\n", ret); goto out_mmc_free; } } pinctrl = devm_pinctrl_get_select_default(&pdev->dev); if (IS_ERR(pinctrl)) { ret = PTR_ERR(pinctrl); goto out_mmc_free; } ssp->clk = clk_get(&pdev->dev, NULL); if (IS_ERR(ssp->clk)) { ret = PTR_ERR(ssp->clk); goto out_mmc_free; } clk_prepare_enable(ssp->clk); mxs_mmc_reset(host); ssp->dmach = dma_request_slave_channel(&pdev->dev, "rx-tx"); if (!ssp->dmach) { dev_err(mmc_dev(host->mmc), "%s: failed to request dma\n", __func__); goto out_clk_put; } /* set mmc core parameters */ mmc->ops = &mxs_mmc_ops; mmc->caps = MMC_CAP_SD_HIGHSPEED | MMC_CAP_MMC_HIGHSPEED | MMC_CAP_SDIO_IRQ | MMC_CAP_NEEDS_POLL; of_property_read_u32(np, "bus-width", &bus_width); if (bus_width == 4) mmc->caps |= MMC_CAP_4_BIT_DATA; else if (bus_width == 8) mmc->caps |= MMC_CAP_4_BIT_DATA | MMC_CAP_8_BIT_DATA; host->broken_cd = of_property_read_bool(np, "broken-cd"); host->non_removable = of_property_read_bool(np, "non-removable"); if (host->non_removable) mmc->caps |= MMC_CAP_NONREMOVABLE; host->wp_gpio = of_get_named_gpio_flags(np, "wp-gpios", 0, &flags); if (flags & OF_GPIO_ACTIVE_LOW) host->wp_inverted = 1; host->cd_inverted = of_property_read_bool(np, "cd-inverted"); mmc->f_min = 400000; mmc->f_max = 288000000; mmc->ocr_avail = MMC_VDD_32_33 | MMC_VDD_33_34; mmc->max_segs = 52; mmc->max_blk_size = 1 << 0xf; mmc->max_blk_count = (ssp_is_old(ssp)) ? 0xff : 0xffffff; mmc->max_req_size = (ssp_is_old(ssp)) ? 0xffff : 0xffffffff; mmc->max_seg_size = dma_get_max_seg_size(ssp->dmach->device->dev); platform_set_drvdata(pdev, mmc); spin_lock_init(&host->lock); ret = devm_request_irq(&pdev->dev, irq_err, mxs_mmc_irq_handler, 0, DRIVER_NAME, host); if (ret) goto out_free_dma; ret = mmc_add_host(mmc); if (ret) goto out_free_dma; dev_info(mmc_dev(host->mmc), "initialized\n"); return 0; out_free_dma: if (ssp->dmach) dma_release_channel(ssp->dmach); out_clk_put: clk_disable_unprepare(ssp->clk); clk_put(ssp->clk); out_mmc_free: mmc_free_host(mmc); return ret; } static int mxs_mmc_remove(struct platform_device *pdev) { struct mmc_host *mmc = platform_get_drvdata(pdev); struct mxs_mmc_host *host = mmc_priv(mmc); struct mxs_ssp *ssp = &host->ssp; mmc_remove_host(mmc); platform_set_drvdata(pdev, NULL); if (ssp->dmach) dma_release_channel(ssp->dmach); clk_disable_unprepare(ssp->clk); clk_put(ssp->clk); mmc_free_host(mmc); return 0; } #ifdef CONFIG_PM static int mxs_mmc_suspend(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct mxs_mmc_host *host = mmc_priv(mmc); struct mxs_ssp *ssp = &host->ssp; int ret = 0; ret = mmc_suspend_host(mmc); clk_disable_unprepare(ssp->clk); return ret; } static int mxs_mmc_resume(struct device *dev) { struct mmc_host *mmc = dev_get_drvdata(dev); struct mxs_mmc_host *host = mmc_priv(mmc); struct mxs_ssp *ssp = &host->ssp; int ret = 0; clk_prepare_enable(ssp->clk); ret = mmc_resume_host(mmc); return ret; } static const struct dev_pm_ops mxs_mmc_pm_ops = { .suspend = mxs_mmc_suspend, .resume = mxs_mmc_resume, }; #endif static struct platform_driver mxs_mmc_driver = { .probe = mxs_mmc_probe, .remove = mxs_mmc_remove, .id_table = mxs_ssp_ids, .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &mxs_mmc_pm_ops, #endif .of_match_table = mxs_mmc_dt_ids, }, }; module_platform_driver(mxs_mmc_driver); MODULE_DESCRIPTION("FREESCALE MXS MMC peripheral"); MODULE_AUTHOR("Freescale Semiconductor"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRIVER_NAME);
gpl-3.0
timnugent/bandit-algorithms
eigen-3.2.4/test/nullary.cpp
80
4485
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2010-2011 Jitse Niesen <jitse@maths.leeds.ac.uk> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "main.h" template<typename MatrixType> bool equalsIdentity(const MatrixType& A) { typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; Scalar zero = static_cast<Scalar>(0); bool offDiagOK = true; for (Index i = 0; i < A.rows(); ++i) { for (Index j = i+1; j < A.cols(); ++j) { offDiagOK = offDiagOK && (A(i,j) == zero); } } for (Index i = 0; i < A.rows(); ++i) { for (Index j = 0; j < (std::min)(i, A.cols()); ++j) { offDiagOK = offDiagOK && (A(i,j) == zero); } } bool diagOK = (A.diagonal().array() == 1).all(); return offDiagOK && diagOK; } template<typename VectorType> void testVectorType(const VectorType& base) { typedef typename internal::traits<VectorType>::Index Index; typedef typename internal::traits<VectorType>::Scalar Scalar; const Index size = base.size(); Scalar high = internal::random<Scalar>(-500,500); Scalar low = (size == 1 ? high : internal::random<Scalar>(-500,500)); if (low>high) std::swap(low,high); const Scalar step = ((size == 1) ? 1 : (high-low)/(size-1)); // check whether the result yields what we expect it to do VectorType m(base); m.setLinSpaced(size,low,high); VectorType n(size); for (int i=0; i<size; ++i) n(i) = low+i*step; VERIFY_IS_APPROX(m,n); // random access version m = VectorType::LinSpaced(size,low,high); VERIFY_IS_APPROX(m,n); // Assignment of a RowVectorXd to a MatrixXd (regression test for bug #79). VERIFY( (MatrixXd(RowVectorXd::LinSpaced(3, 0, 1)) - RowVector3d(0, 0.5, 1)).norm() < std::numeric_limits<Scalar>::epsilon() ); // These guys sometimes fail! This is not good. Any ideas how to fix them!? //VERIFY( m(m.size()-1) == high ); //VERIFY( m(0) == low ); // sequential access version m = VectorType::LinSpaced(Sequential,size,low,high); VERIFY_IS_APPROX(m,n); // These guys sometimes fail! This is not good. Any ideas how to fix them!? //VERIFY( m(m.size()-1) == high ); //VERIFY( m(0) == low ); // check whether everything works with row and col major vectors Matrix<Scalar,Dynamic,1> row_vector(size); Matrix<Scalar,1,Dynamic> col_vector(size); row_vector.setLinSpaced(size,low,high); col_vector.setLinSpaced(size,low,high); // when using the extended precision (e.g., FPU) the relative error might exceed 1 bit // when computing the squared sum in isApprox, thus the 2x factor. VERIFY( row_vector.isApprox(col_vector.transpose(), Scalar(2)*NumTraits<Scalar>::epsilon())); Matrix<Scalar,Dynamic,1> size_changer(size+50); size_changer.setLinSpaced(size,low,high); VERIFY( size_changer.size() == size ); typedef Matrix<Scalar,1,1> ScalarMatrix; ScalarMatrix scalar; scalar.setLinSpaced(1,low,high); VERIFY_IS_APPROX( scalar, ScalarMatrix::Constant(high) ); VERIFY_IS_APPROX( ScalarMatrix::LinSpaced(1,low,high), ScalarMatrix::Constant(high) ); // regression test for bug 526 (linear vectorized transversal) if (size > 1) { m.tail(size-1).setLinSpaced(low, high); VERIFY_IS_APPROX(m(size-1), high); } } template<typename MatrixType> void testMatrixType(const MatrixType& m) { typedef typename MatrixType::Index Index; const Index rows = m.rows(); const Index cols = m.cols(); MatrixType A; A.setIdentity(rows, cols); VERIFY(equalsIdentity(A)); VERIFY(equalsIdentity(MatrixType::Identity(rows, cols))); } void test_nullary() { CALL_SUBTEST_1( testMatrixType(Matrix2d()) ); CALL_SUBTEST_2( testMatrixType(MatrixXcf(internal::random<int>(1,300),internal::random<int>(1,300))) ); CALL_SUBTEST_3( testMatrixType(MatrixXf(internal::random<int>(1,300),internal::random<int>(1,300))) ); for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_4( testVectorType(VectorXd(internal::random<int>(1,300))) ); CALL_SUBTEST_5( testVectorType(Vector4d()) ); // regression test for bug 232 CALL_SUBTEST_6( testVectorType(Vector3d()) ); CALL_SUBTEST_7( testVectorType(VectorXf(internal::random<int>(1,300))) ); CALL_SUBTEST_8( testVectorType(Vector3f()) ); CALL_SUBTEST_8( testVectorType(Matrix<float,1,1>()) ); } }
gpl-3.0
geminy/aidear
oss/linux/linux-4.7/lib/audit.c
1363
1781
#include <linux/init.h> #include <linux/types.h> #include <linux/audit.h> #include <asm/unistd.h> static unsigned dir_class[] = { #include <asm-generic/audit_dir_write.h> ~0U }; static unsigned read_class[] = { #include <asm-generic/audit_read.h> ~0U }; static unsigned write_class[] = { #include <asm-generic/audit_write.h> ~0U }; static unsigned chattr_class[] = { #include <asm-generic/audit_change_attr.h> ~0U }; static unsigned signal_class[] = { #include <asm-generic/audit_signal.h> ~0U }; int audit_classify_arch(int arch) { if (audit_is_compat(arch)) return 1; else return 0; } int audit_classify_syscall(int abi, unsigned syscall) { if (audit_is_compat(abi)) return audit_classify_compat_syscall(abi, syscall); switch(syscall) { #ifdef __NR_open case __NR_open: return 2; #endif #ifdef __NR_openat case __NR_openat: return 3; #endif #ifdef __NR_socketcall case __NR_socketcall: return 4; #endif #ifdef __NR_execveat case __NR_execveat: #endif case __NR_execve: return 5; default: return 0; } } static int __init audit_classes_init(void) { #ifdef CONFIG_AUDIT_COMPAT_GENERIC audit_register_class(AUDIT_CLASS_WRITE_32, compat_write_class); audit_register_class(AUDIT_CLASS_READ_32, compat_read_class); audit_register_class(AUDIT_CLASS_DIR_WRITE_32, compat_dir_class); audit_register_class(AUDIT_CLASS_CHATTR_32, compat_chattr_class); audit_register_class(AUDIT_CLASS_SIGNAL_32, compat_signal_class); #endif audit_register_class(AUDIT_CLASS_WRITE, write_class); audit_register_class(AUDIT_CLASS_READ, read_class); audit_register_class(AUDIT_CLASS_DIR_WRITE, dir_class); audit_register_class(AUDIT_CLASS_CHATTR, chattr_class); audit_register_class(AUDIT_CLASS_SIGNAL, signal_class); return 0; } __initcall(audit_classes_init);
gpl-3.0
jun496276723/CocosMFCEditor
cocos2d/external/recast/DetourCrowd/DetourProximityGrid.cpp
86
4850
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #include <string.h> #include <new> #include "DetourProximityGrid.h" #include "recast/Detour/DetourCommon.h" #include "recast/Detour/DetourMath.h" #include "recast/Detour/DetourAlloc.h" #include "recast/Detour/DetourAssert.h" dtProximityGrid* dtAllocProximityGrid() { void* mem = dtAlloc(sizeof(dtProximityGrid), DT_ALLOC_PERM); if (!mem) return 0; return new(mem) dtProximityGrid; } void dtFreeProximityGrid(dtProximityGrid* ptr) { if (!ptr) return; ptr->~dtProximityGrid(); dtFree(ptr); } inline int hashPos2(int x, int y, int n) { return ((x*73856093) ^ (y*19349663)) & (n-1); } dtProximityGrid::dtProximityGrid() : m_cellSize(0), m_pool(0), m_poolHead(0), m_poolSize(0), m_buckets(0), m_bucketsSize(0) { } dtProximityGrid::~dtProximityGrid() { dtFree(m_buckets); dtFree(m_pool); } bool dtProximityGrid::init(const int poolSize, const float cellSize) { dtAssert(poolSize > 0); dtAssert(cellSize > 0.0f); m_cellSize = cellSize; m_invCellSize = 1.0f / m_cellSize; // Allocate hashs buckets m_bucketsSize = dtNextPow2(poolSize); m_buckets = (unsigned short*)dtAlloc(sizeof(unsigned short)*m_bucketsSize, DT_ALLOC_PERM); if (!m_buckets) return false; // Allocate pool of items. m_poolSize = poolSize; m_poolHead = 0; m_pool = (Item*)dtAlloc(sizeof(Item)*m_poolSize, DT_ALLOC_PERM); if (!m_pool) return false; clear(); return true; } void dtProximityGrid::clear() { memset(m_buckets, 0xff, sizeof(unsigned short)*m_bucketsSize); m_poolHead = 0; m_bounds[0] = 0xffff; m_bounds[1] = 0xffff; m_bounds[2] = -0xffff; m_bounds[3] = -0xffff; } void dtProximityGrid::addItem(const unsigned short id, const float minx, const float miny, const float maxx, const float maxy) { const int iminx = (int)dtMathFloorf(minx * m_invCellSize); const int iminy = (int)dtMathFloorf(miny * m_invCellSize); const int imaxx = (int)dtMathFloorf(maxx * m_invCellSize); const int imaxy = (int)dtMathFloorf(maxy * m_invCellSize); m_bounds[0] = dtMin(m_bounds[0], iminx); m_bounds[1] = dtMin(m_bounds[1], iminy); m_bounds[2] = dtMax(m_bounds[2], imaxx); m_bounds[3] = dtMax(m_bounds[3], imaxy); for (int y = iminy; y <= imaxy; ++y) { for (int x = iminx; x <= imaxx; ++x) { if (m_poolHead < m_poolSize) { const int h = hashPos2(x, y, m_bucketsSize); const unsigned short idx = (unsigned short)m_poolHead; m_poolHead++; Item& item = m_pool[idx]; item.x = (short)x; item.y = (short)y; item.id = id; item.next = m_buckets[h]; m_buckets[h] = idx; } } } } int dtProximityGrid::queryItems(const float minx, const float miny, const float maxx, const float maxy, unsigned short* ids, const int maxIds) const { const int iminx = (int)dtMathFloorf(minx * m_invCellSize); const int iminy = (int)dtMathFloorf(miny * m_invCellSize); const int imaxx = (int)dtMathFloorf(maxx * m_invCellSize); const int imaxy = (int)dtMathFloorf(maxy * m_invCellSize); int n = 0; for (int y = iminy; y <= imaxy; ++y) { for (int x = iminx; x <= imaxx; ++x) { const int h = hashPos2(x, y, m_bucketsSize); unsigned short idx = m_buckets[h]; while (idx != 0xffff) { Item& item = m_pool[idx]; if ((int)item.x == x && (int)item.y == y) { // Check if the id exists already. const unsigned short* end = ids + n; unsigned short* i = ids; while (i != end && *i != item.id) ++i; // Item not found, add it. if (i == end) { if (n >= maxIds) return n; ids[n++] = item.id; } } idx = item.next; } } } return n; } int dtProximityGrid::getItemCountAt(const int x, const int y) const { int n = 0; const int h = hashPos2(x, y, m_bucketsSize); unsigned short idx = m_buckets[h]; while (idx != 0xffff) { Item& item = m_pool[idx]; if ((int)item.x == x && (int)item.y == y) n++; idx = item.next; } return n; }
gpl-3.0
miloh/Marlin
ArduinoAddons/Arduino_1.x.x/hardware/Melzi/cores/arduino/wiring_shift.c
1625
1601
/* wiring_shift.c - shiftOut() function Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) { uint8_t value = 0; uint8_t i; for (i = 0; i < 8; ++i) { digitalWrite(clockPin, HIGH); if (bitOrder == LSBFIRST) value |= digitalRead(dataPin) << i; else value |= digitalRead(dataPin) << (7 - i); digitalWrite(clockPin, LOW); } return value; } void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i < 8; i++) { if (bitOrder == LSBFIRST) digitalWrite(dataPin, !!(val & (1 << i))); else digitalWrite(dataPin, !!(val & (1 << (7 - i)))); digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } }
gpl-3.0
CognetTestbed/COGNET_CODE
KERNEL_SOURCE_CODE/linux-source-3.8.11-voyage/drivers/net/ethernet/atheros/atl1e/atl1e_ethtool.c
2908
11352
/* * Copyright(c) 2007 Atheros Corporation. All rights reserved. * * Derived from Intel e1000 driver * Copyright(c) 1999 - 2005 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 * Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include <linux/netdevice.h> #include <linux/ethtool.h> #include <linux/slab.h> #include "atl1e.h" static int atl1e_get_settings(struct net_device *netdev, struct ethtool_cmd *ecmd) { struct atl1e_adapter *adapter = netdev_priv(netdev); struct atl1e_hw *hw = &adapter->hw; ecmd->supported = (SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full | SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full | SUPPORTED_Autoneg | SUPPORTED_TP); if (hw->nic_type == athr_l1e) ecmd->supported |= SUPPORTED_1000baseT_Full; ecmd->advertising = ADVERTISED_TP; ecmd->advertising |= ADVERTISED_Autoneg; ecmd->advertising |= hw->autoneg_advertised; ecmd->port = PORT_TP; ecmd->phy_address = 0; ecmd->transceiver = XCVR_INTERNAL; if (adapter->link_speed != SPEED_0) { ethtool_cmd_speed_set(ecmd, adapter->link_speed); if (adapter->link_duplex == FULL_DUPLEX) ecmd->duplex = DUPLEX_FULL; else ecmd->duplex = DUPLEX_HALF; } else { ethtool_cmd_speed_set(ecmd, -1); ecmd->duplex = -1; } ecmd->autoneg = AUTONEG_ENABLE; return 0; } static int atl1e_set_settings(struct net_device *netdev, struct ethtool_cmd *ecmd) { struct atl1e_adapter *adapter = netdev_priv(netdev); struct atl1e_hw *hw = &adapter->hw; while (test_and_set_bit(__AT_RESETTING, &adapter->flags)) msleep(1); if (ecmd->autoneg == AUTONEG_ENABLE) { u16 adv4, adv9; if ((ecmd->advertising&ADVERTISE_1000_FULL)) { if (hw->nic_type == athr_l1e) { hw->autoneg_advertised = ecmd->advertising & AT_ADV_MASK; } else { clear_bit(__AT_RESETTING, &adapter->flags); return -EINVAL; } } else if (ecmd->advertising&ADVERTISE_1000_HALF) { clear_bit(__AT_RESETTING, &adapter->flags); return -EINVAL; } else { hw->autoneg_advertised = ecmd->advertising & AT_ADV_MASK; } ecmd->advertising = hw->autoneg_advertised | ADVERTISED_TP | ADVERTISED_Autoneg; adv4 = hw->mii_autoneg_adv_reg & ~ADVERTISE_ALL; adv9 = hw->mii_1000t_ctrl_reg & ~MII_AT001_CR_1000T_SPEED_MASK; if (hw->autoneg_advertised & ADVERTISE_10_HALF) adv4 |= ADVERTISE_10HALF; if (hw->autoneg_advertised & ADVERTISE_10_FULL) adv4 |= ADVERTISE_10FULL; if (hw->autoneg_advertised & ADVERTISE_100_HALF) adv4 |= ADVERTISE_100HALF; if (hw->autoneg_advertised & ADVERTISE_100_FULL) adv4 |= ADVERTISE_100FULL; if (hw->autoneg_advertised & ADVERTISE_1000_FULL) adv9 |= ADVERTISE_1000FULL; if (adv4 != hw->mii_autoneg_adv_reg || adv9 != hw->mii_1000t_ctrl_reg) { hw->mii_autoneg_adv_reg = adv4; hw->mii_1000t_ctrl_reg = adv9; hw->re_autoneg = true; } } else { clear_bit(__AT_RESETTING, &adapter->flags); return -EINVAL; } /* reset the link */ if (netif_running(adapter->netdev)) { atl1e_down(adapter); atl1e_up(adapter); } else atl1e_reset_hw(&adapter->hw); clear_bit(__AT_RESETTING, &adapter->flags); return 0; } static u32 atl1e_get_msglevel(struct net_device *netdev) { #ifdef DBG return 1; #else return 0; #endif } static int atl1e_get_regs_len(struct net_device *netdev) { return AT_REGS_LEN * sizeof(u32); } static void atl1e_get_regs(struct net_device *netdev, struct ethtool_regs *regs, void *p) { struct atl1e_adapter *adapter = netdev_priv(netdev); struct atl1e_hw *hw = &adapter->hw; u32 *regs_buff = p; u16 phy_data; memset(p, 0, AT_REGS_LEN * sizeof(u32)); regs->version = (1 << 24) | (hw->revision_id << 16) | hw->device_id; regs_buff[0] = AT_READ_REG(hw, REG_VPD_CAP); regs_buff[1] = AT_READ_REG(hw, REG_SPI_FLASH_CTRL); regs_buff[2] = AT_READ_REG(hw, REG_SPI_FLASH_CONFIG); regs_buff[3] = AT_READ_REG(hw, REG_TWSI_CTRL); regs_buff[4] = AT_READ_REG(hw, REG_PCIE_DEV_MISC_CTRL); regs_buff[5] = AT_READ_REG(hw, REG_MASTER_CTRL); regs_buff[6] = AT_READ_REG(hw, REG_MANUAL_TIMER_INIT); regs_buff[7] = AT_READ_REG(hw, REG_IRQ_MODU_TIMER_INIT); regs_buff[8] = AT_READ_REG(hw, REG_GPHY_CTRL); regs_buff[9] = AT_READ_REG(hw, REG_CMBDISDMA_TIMER); regs_buff[10] = AT_READ_REG(hw, REG_IDLE_STATUS); regs_buff[11] = AT_READ_REG(hw, REG_MDIO_CTRL); regs_buff[12] = AT_READ_REG(hw, REG_SERDES_LOCK); regs_buff[13] = AT_READ_REG(hw, REG_MAC_CTRL); regs_buff[14] = AT_READ_REG(hw, REG_MAC_IPG_IFG); regs_buff[15] = AT_READ_REG(hw, REG_MAC_STA_ADDR); regs_buff[16] = AT_READ_REG(hw, REG_MAC_STA_ADDR+4); regs_buff[17] = AT_READ_REG(hw, REG_RX_HASH_TABLE); regs_buff[18] = AT_READ_REG(hw, REG_RX_HASH_TABLE+4); regs_buff[19] = AT_READ_REG(hw, REG_MAC_HALF_DUPLX_CTRL); regs_buff[20] = AT_READ_REG(hw, REG_MTU); regs_buff[21] = AT_READ_REG(hw, REG_WOL_CTRL); regs_buff[22] = AT_READ_REG(hw, REG_SRAM_TRD_ADDR); regs_buff[23] = AT_READ_REG(hw, REG_SRAM_TRD_LEN); regs_buff[24] = AT_READ_REG(hw, REG_SRAM_RXF_ADDR); regs_buff[25] = AT_READ_REG(hw, REG_SRAM_RXF_LEN); regs_buff[26] = AT_READ_REG(hw, REG_SRAM_TXF_ADDR); regs_buff[27] = AT_READ_REG(hw, REG_SRAM_TXF_LEN); regs_buff[28] = AT_READ_REG(hw, REG_SRAM_TCPH_ADDR); regs_buff[29] = AT_READ_REG(hw, REG_SRAM_PKTH_ADDR); atl1e_read_phy_reg(hw, MII_BMCR, &phy_data); regs_buff[73] = (u32)phy_data; atl1e_read_phy_reg(hw, MII_BMSR, &phy_data); regs_buff[74] = (u32)phy_data; } static int atl1e_get_eeprom_len(struct net_device *netdev) { struct atl1e_adapter *adapter = netdev_priv(netdev); if (!atl1e_check_eeprom_exist(&adapter->hw)) return AT_EEPROM_LEN; else return 0; } static int atl1e_get_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct atl1e_adapter *adapter = netdev_priv(netdev); struct atl1e_hw *hw = &adapter->hw; u32 *eeprom_buff; int first_dword, last_dword; int ret_val = 0; int i; if (eeprom->len == 0) return -EINVAL; if (atl1e_check_eeprom_exist(hw)) /* not exist */ return -EINVAL; eeprom->magic = hw->vendor_id | (hw->device_id << 16); first_dword = eeprom->offset >> 2; last_dword = (eeprom->offset + eeprom->len - 1) >> 2; eeprom_buff = kmalloc(sizeof(u32) * (last_dword - first_dword + 1), GFP_KERNEL); if (eeprom_buff == NULL) return -ENOMEM; for (i = first_dword; i < last_dword; i++) { if (!atl1e_read_eeprom(hw, i * 4, &(eeprom_buff[i-first_dword]))) { kfree(eeprom_buff); return -EIO; } } memcpy(bytes, (u8 *)eeprom_buff + (eeprom->offset & 3), eeprom->len); kfree(eeprom_buff); return ret_val; } static int atl1e_set_eeprom(struct net_device *netdev, struct ethtool_eeprom *eeprom, u8 *bytes) { struct atl1e_adapter *adapter = netdev_priv(netdev); struct atl1e_hw *hw = &adapter->hw; u32 *eeprom_buff; u32 *ptr; int first_dword, last_dword; int ret_val = 0; int i; if (eeprom->len == 0) return -EOPNOTSUPP; if (eeprom->magic != (hw->vendor_id | (hw->device_id << 16))) return -EINVAL; first_dword = eeprom->offset >> 2; last_dword = (eeprom->offset + eeprom->len - 1) >> 2; eeprom_buff = kmalloc(AT_EEPROM_LEN, GFP_KERNEL); if (eeprom_buff == NULL) return -ENOMEM; ptr = eeprom_buff; if (eeprom->offset & 3) { /* need read/modify/write of first changed EEPROM word */ /* only the second byte of the word is being modified */ if (!atl1e_read_eeprom(hw, first_dword * 4, &(eeprom_buff[0]))) { ret_val = -EIO; goto out; } ptr++; } if (((eeprom->offset + eeprom->len) & 3)) { /* need read/modify/write of last changed EEPROM word */ /* only the first byte of the word is being modified */ if (!atl1e_read_eeprom(hw, last_dword * 4, &(eeprom_buff[last_dword - first_dword]))) { ret_val = -EIO; goto out; } } /* Device's eeprom is always little-endian, word addressable */ memcpy(ptr, bytes, eeprom->len); for (i = 0; i < last_dword - first_dword + 1; i++) { if (!atl1e_write_eeprom(hw, ((first_dword + i) * 4), eeprom_buff[i])) { ret_val = -EIO; goto out; } } out: kfree(eeprom_buff); return ret_val; } static void atl1e_get_drvinfo(struct net_device *netdev, struct ethtool_drvinfo *drvinfo) { struct atl1e_adapter *adapter = netdev_priv(netdev); strlcpy(drvinfo->driver, atl1e_driver_name, sizeof(drvinfo->driver)); strlcpy(drvinfo->version, atl1e_driver_version, sizeof(drvinfo->version)); strlcpy(drvinfo->fw_version, "L1e", sizeof(drvinfo->fw_version)); strlcpy(drvinfo->bus_info, pci_name(adapter->pdev), sizeof(drvinfo->bus_info)); drvinfo->n_stats = 0; drvinfo->testinfo_len = 0; drvinfo->regdump_len = atl1e_get_regs_len(netdev); drvinfo->eedump_len = atl1e_get_eeprom_len(netdev); } static void atl1e_get_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct atl1e_adapter *adapter = netdev_priv(netdev); wol->supported = WAKE_MAGIC | WAKE_PHY; wol->wolopts = 0; if (adapter->wol & AT_WUFC_EX) wol->wolopts |= WAKE_UCAST; if (adapter->wol & AT_WUFC_MC) wol->wolopts |= WAKE_MCAST; if (adapter->wol & AT_WUFC_BC) wol->wolopts |= WAKE_BCAST; if (adapter->wol & AT_WUFC_MAG) wol->wolopts |= WAKE_MAGIC; if (adapter->wol & AT_WUFC_LNKC) wol->wolopts |= WAKE_PHY; } static int atl1e_set_wol(struct net_device *netdev, struct ethtool_wolinfo *wol) { struct atl1e_adapter *adapter = netdev_priv(netdev); if (wol->wolopts & (WAKE_ARP | WAKE_MAGICSECURE | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST)) return -EOPNOTSUPP; /* these settings will always override what we currently have */ adapter->wol = 0; if (wol->wolopts & WAKE_MAGIC) adapter->wol |= AT_WUFC_MAG; if (wol->wolopts & WAKE_PHY) adapter->wol |= AT_WUFC_LNKC; device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol); return 0; } static int atl1e_nway_reset(struct net_device *netdev) { struct atl1e_adapter *adapter = netdev_priv(netdev); if (netif_running(netdev)) atl1e_reinit_locked(adapter); return 0; } static const struct ethtool_ops atl1e_ethtool_ops = { .get_settings = atl1e_get_settings, .set_settings = atl1e_set_settings, .get_drvinfo = atl1e_get_drvinfo, .get_regs_len = atl1e_get_regs_len, .get_regs = atl1e_get_regs, .get_wol = atl1e_get_wol, .set_wol = atl1e_set_wol, .get_msglevel = atl1e_get_msglevel, .nway_reset = atl1e_nway_reset, .get_link = ethtool_op_get_link, .get_eeprom_len = atl1e_get_eeprom_len, .get_eeprom = atl1e_get_eeprom, .set_eeprom = atl1e_set_eeprom, }; void atl1e_set_ethtool_ops(struct net_device *netdev) { SET_ETHTOOL_OPS(netdev, &atl1e_ethtool_ops); }
gpl-3.0
gmalik9/dokan
dokan/create.c
99
7491
/* Dokan : user-mode file system library for Windows Copyright (C) 2008 Hiroki Asakawa info@dokan-dev.net http://dokan-dev.net/en This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 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 Lesser General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "dokani.h" #include "fileinfo.h" VOID DispatchCreate( HANDLE Handle, PEVENT_CONTEXT EventContext, PDOKAN_INSTANCE DokanInstance) { static eventId = 0; ULONG length = sizeof(EVENT_INFORMATION); PEVENT_INFORMATION eventInfo = (PEVENT_INFORMATION)malloc(length); int status; DOKAN_FILE_INFO fileInfo; DWORD disposition; PDOKAN_OPEN_INFO openInfo; BOOL directoryRequested = FALSE; DWORD options; CheckFileName(EventContext->Create.FileName); RtlZeroMemory(eventInfo, length); RtlZeroMemory(&fileInfo, sizeof(DOKAN_FILE_INFO)); eventInfo->BufferLength = 0; eventInfo->SerialNumber = EventContext->SerialNumber; fileInfo.ProcessId = EventContext->ProcessId; fileInfo.DokanOptions = DokanInstance->DokanOptions; // DOKAN_OPEN_INFO is structure for a opened file // this will be freed by Close openInfo = malloc(sizeof(DOKAN_OPEN_INFO)); ZeroMemory(openInfo, sizeof(DOKAN_OPEN_INFO)); openInfo->OpenCount = 2; openInfo->EventContext = EventContext; openInfo->DokanInstance = DokanInstance; fileInfo.DokanContext = (ULONG64)openInfo; // pass it to driver and when the same handle is used get it back eventInfo->Context = (ULONG64)openInfo; // The high 8 bits of this parameter correspond to the Disposition parameter disposition = (EventContext->Create.CreateOptions >> 24) & 0x000000ff; status = -1; // in case being not dispatched // The low 24 bits of this member correspond to the CreateOptions parameter options = EventContext->Create.CreateOptions & FILE_VALID_OPTION_FLAGS; //DbgPrint("Create.CreateOptions 0x%x\n", options); // to open directory // even if this flag is not specifed, // there is a case to open a directory if (options & FILE_DIRECTORY_FILE) { //DbgPrint("FILE_DIRECTORY_FILE\n"); directoryRequested = TRUE; } // to open no directory file // event if this flag is not specified, // there is a case to open non directory file if (options & FILE_NON_DIRECTORY_FILE) { //DbgPrint("FILE_NON_DIRECTORY_FILE\n"); } if (options & FILE_DELETE_ON_CLOSE) { EventContext->Create.FileAttributes |= FILE_FLAG_DELETE_ON_CLOSE; } DbgPrint("###Create %04d\n", eventId); //DbgPrint("### OpenInfo %X\n", openInfo); openInfo->EventId = eventId++; // make a directory or open if (directoryRequested) { fileInfo.IsDirectory = TRUE; if (disposition == FILE_CREATE || disposition == FILE_OPEN_IF) { if (DokanInstance->DokanOperations->CreateDirectory) { status = DokanInstance->DokanOperations->CreateDirectory( EventContext->Create.FileName, &fileInfo); } } else if(disposition == FILE_OPEN) { if (DokanInstance->DokanOperations->OpenDirectory) { status = DokanInstance->DokanOperations->OpenDirectory( EventContext->Create.FileName, &fileInfo); } } else { DbgPrint("### Create other disposition : %d\n", disposition); } // open a file } else { DWORD creationDisposition = OPEN_EXISTING; fileInfo.IsDirectory = FALSE; DbgPrint(" CreateDisposition %X\n", disposition); switch(disposition) { case FILE_CREATE: creationDisposition = CREATE_NEW; break; case FILE_OPEN: creationDisposition = OPEN_EXISTING; break; case FILE_OPEN_IF: creationDisposition = OPEN_ALWAYS; break; case FILE_OVERWRITE: creationDisposition = TRUNCATE_EXISTING; break; case FILE_OVERWRITE_IF: creationDisposition = CREATE_ALWAYS; break; default: // TODO: should support FILE_SUPERSEDE ? DbgPrint("### Create other disposition : %d\n", disposition); break; } if(DokanInstance->DokanOperations->CreateFile) { status = DokanInstance->DokanOperations->CreateFile( EventContext->Create.FileName, EventContext->Create.DesiredAccess, EventContext->Create.ShareAccess, creationDisposition, EventContext->Create.FileAttributes, &fileInfo); } } // save the information about this access in DOKAN_OPEN_INFO openInfo->IsDirectory = fileInfo.IsDirectory; openInfo->UserContext = fileInfo.Context; // FILE_CREATED // FILE_DOES_NOT_EXIST // FILE_EXISTS // FILE_OPENED // FILE_OVERWRITTEN // FILE_SUPERSEDED if (status < 0) { int error = status * -1; DbgPrint("CreateFile status = %d\n", status); if (EventContext->Flags & SL_OPEN_TARGET_DIRECTORY) { DbgPrint("SL_OPEN_TARGET_DIRECTORY spcefied\n"); } eventInfo->Create.Information = FILE_DOES_NOT_EXIST; switch(error) { case ERROR_FILE_NOT_FOUND: if (EventContext->Flags & SL_OPEN_TARGET_DIRECTORY) eventInfo->Status = STATUS_SUCCESS; else eventInfo->Status = STATUS_OBJECT_NAME_NOT_FOUND; break; case ERROR_PATH_NOT_FOUND: //if (EventContext->Flags & SL_OPEN_TARGET_DIRECTORY) // eventInfo->Status = STATUS_SUCCESS; //else eventInfo->Status = STATUS_OBJECT_PATH_NOT_FOUND; break; case ERROR_ACCESS_DENIED: eventInfo->Status = STATUS_ACCESS_DENIED; break; case ERROR_SHARING_VIOLATION: eventInfo->Status = STATUS_SHARING_VIOLATION; break; case ERROR_INVALID_NAME: eventInfo->Status = STATUS_OBJECT_NAME_NOT_FOUND; break; case ERROR_FILE_EXISTS: case ERROR_ALREADY_EXISTS: eventInfo->Status = STATUS_OBJECT_NAME_COLLISION; eventInfo->Create.Information = FILE_EXISTS; break; case ERROR_PRIVILEGE_NOT_HELD: eventInfo->Status = STATUS_PRIVILEGE_NOT_HELD; break; case ERROR_NOT_READY: eventInfo->Status = STATUS_DEVICE_NOT_READY; break; default: eventInfo->Status = STATUS_INVALID_PARAMETER; DbgPrint("Create got unknown error code %d\n", error); } if (eventInfo->Status != STATUS_SUCCESS) { // Needs to free openInfo because Close is never called. free(openInfo); eventInfo->Context = 0; } } else { //DbgPrint("status = %d\n", status); eventInfo->Status = STATUS_SUCCESS; eventInfo->Create.Information = FILE_OPENED; if (disposition == FILE_CREATE || disposition == FILE_OPEN_IF || disposition == FILE_OVERWRITE_IF) { if (status != ERROR_ALREADY_EXISTS) { eventInfo->Create.Information = FILE_CREATED; } } if ((disposition == FILE_OVERWRITE_IF || disposition == FILE_OVERWRITE) && eventInfo->Create.Information != FILE_CREATED) { eventInfo->Create.Information = FILE_OVERWRITTEN; } if (fileInfo.IsDirectory) eventInfo->Create.Flags |= DOKAN_FILE_DIRECTORY; } SendEventInformation(Handle, eventInfo, length, DokanInstance); free(eventInfo); return; }
gpl-3.0
xynopsis/grsec-kernel
arch/m68k/kernel/bootinfo_proc.c
1379
1699
/* * Based on arch/arm/kernel/atags_proc.c */ #include <linux/fs.h> #include <linux/init.h> #include <linux/printk.h> #include <linux/proc_fs.h> #include <linux/slab.h> #include <linux/string.h> #include <asm/bootinfo.h> #include <asm/byteorder.h> static char bootinfo_tmp[1536] __initdata; static void *bootinfo_copy; static size_t bootinfo_size; static ssize_t bootinfo_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { return simple_read_from_buffer(buf, count, ppos, bootinfo_copy, bootinfo_size); } static const struct file_operations bootinfo_fops = { .read = bootinfo_read, .llseek = default_llseek, }; void __init save_bootinfo(const struct bi_record *bi) { const void *start = bi; size_t size = sizeof(bi->tag); while (be16_to_cpu(bi->tag) != BI_LAST) { uint16_t n = be16_to_cpu(bi->size); size += n; bi = (struct bi_record *)((unsigned long)bi + n); } if (size > sizeof(bootinfo_tmp)) { pr_err("Cannot save %zu bytes of bootinfo\n", size); return; } pr_info("Saving %zu bytes of bootinfo\n", size); memcpy(bootinfo_tmp, start, size); bootinfo_size = size; } static int __init init_bootinfo_procfs(void) { /* * This cannot go into save_bootinfo() because kmalloc and proc don't * work yet when it is called. */ struct proc_dir_entry *pde; if (!bootinfo_size) return -EINVAL; bootinfo_copy = kmalloc(bootinfo_size, GFP_KERNEL); if (!bootinfo_copy) return -ENOMEM; memcpy(bootinfo_copy, bootinfo_tmp, bootinfo_size); pde = proc_create_data("bootinfo", 0400, NULL, &bootinfo_fops, NULL); if (!pde) { kfree(bootinfo_copy); return -ENOMEM; } return 0; } arch_initcall(init_bootinfo_procfs);
gpl-3.0
BlastarIndia/Blastarix
blastarix-3.12.7/net/rds/tcp_listen.c
2662
5198
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * 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. * * 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 <linux/kernel.h> #include <linux/gfp.h> #include <linux/in.h> #include <net/tcp.h> #include "rds.h" #include "tcp.h" /* * cheesy, but simple.. */ static void rds_tcp_accept_worker(struct work_struct *work); static DECLARE_WORK(rds_tcp_listen_work, rds_tcp_accept_worker); static struct socket *rds_tcp_listen_sock; static int rds_tcp_accept_one(struct socket *sock) { struct socket *new_sock = NULL; struct rds_connection *conn; int ret; struct inet_sock *inet; ret = sock_create_lite(sock->sk->sk_family, sock->sk->sk_type, sock->sk->sk_protocol, &new_sock); if (ret) goto out; new_sock->type = sock->type; new_sock->ops = sock->ops; ret = sock->ops->accept(sock, new_sock, O_NONBLOCK); if (ret < 0) goto out; rds_tcp_tune(new_sock); inet = inet_sk(new_sock->sk); rdsdebug("accepted tcp %pI4:%u -> %pI4:%u\n", &inet->inet_saddr, ntohs(inet->inet_sport), &inet->inet_daddr, ntohs(inet->inet_dport)); conn = rds_conn_create(inet->inet_saddr, inet->inet_daddr, &rds_tcp_transport, GFP_KERNEL); if (IS_ERR(conn)) { ret = PTR_ERR(conn); goto out; } /* * see the comment above rds_queue_delayed_reconnect() */ if (!rds_conn_transition(conn, RDS_CONN_DOWN, RDS_CONN_CONNECTING)) { if (rds_conn_state(conn) == RDS_CONN_UP) rds_tcp_stats_inc(s_tcp_listen_closed_stale); else rds_tcp_stats_inc(s_tcp_connect_raced); rds_conn_drop(conn); ret = 0; goto out; } rds_tcp_set_callbacks(new_sock, conn); rds_connect_complete(conn); new_sock = NULL; ret = 0; out: if (new_sock) sock_release(new_sock); return ret; } static void rds_tcp_accept_worker(struct work_struct *work) { while (rds_tcp_accept_one(rds_tcp_listen_sock) == 0) cond_resched(); } void rds_tcp_listen_data_ready(struct sock *sk, int bytes) { void (*ready)(struct sock *sk, int bytes); rdsdebug("listen data ready sk %p\n", sk); read_lock(&sk->sk_callback_lock); ready = sk->sk_user_data; if (!ready) { /* check for teardown race */ ready = sk->sk_data_ready; goto out; } /* * ->sk_data_ready is also called for a newly established child socket * before it has been accepted and the accepter has set up their * data_ready.. we only want to queue listen work for our listening * socket */ if (sk->sk_state == TCP_LISTEN) queue_work(rds_wq, &rds_tcp_listen_work); out: read_unlock(&sk->sk_callback_lock); ready(sk, bytes); } int rds_tcp_listen_init(void) { struct sockaddr_in sin; struct socket *sock = NULL; int ret; ret = sock_create(PF_INET, SOCK_STREAM, IPPROTO_TCP, &sock); if (ret < 0) goto out; sock->sk->sk_reuse = SK_CAN_REUSE; rds_tcp_nonagle(sock); write_lock_bh(&sock->sk->sk_callback_lock); sock->sk->sk_user_data = sock->sk->sk_data_ready; sock->sk->sk_data_ready = rds_tcp_listen_data_ready; write_unlock_bh(&sock->sk->sk_callback_lock); sin.sin_family = PF_INET, sin.sin_addr.s_addr = (__force u32)htonl(INADDR_ANY); sin.sin_port = (__force u16)htons(RDS_TCP_PORT); ret = sock->ops->bind(sock, (struct sockaddr *)&sin, sizeof(sin)); if (ret < 0) goto out; ret = sock->ops->listen(sock, 64); if (ret < 0) goto out; rds_tcp_listen_sock = sock; sock = NULL; out: if (sock) sock_release(sock); return ret; } void rds_tcp_listen_stop(void) { struct socket *sock = rds_tcp_listen_sock; struct sock *sk; if (!sock) return; sk = sock->sk; /* serialize with and prevent further callbacks */ lock_sock(sk); write_lock_bh(&sk->sk_callback_lock); if (sk->sk_user_data) { sk->sk_data_ready = sk->sk_user_data; sk->sk_user_data = NULL; } write_unlock_bh(&sk->sk_callback_lock); release_sock(sk); /* wait for accepts to stop and close the socket */ flush_workqueue(rds_wq); sock_release(sock); rds_tcp_listen_sock = NULL; }
gpl-3.0
iBcker/shadowsocks-android
src/main/jni/badvpn/ncd/modules/list.c
360
22041
/** * @file list.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @section DESCRIPTION * * List construction module. * * Synopsis: * list(elem1, ..., elemN) * list listfrom(list l1, ..., list lN) * * Description: * The first form creates a list with the given elements. * The second form creates a list by concatenating the given * lists. * * Variables: * (empty) - list containing elem1, ..., elemN * length - number of elements in list * * Synopsis: list::append(arg) * * Synopsis: list::appendv(list arg) * Description: Appends the elements of arg to the list. * * Synopsis: list::length() * Variables: * (empty) - number of elements in list at the time of initialization * of this method * * Synopsis: list::get(string index) * Variables: * (empty) - element of list at position index (starting from zero) at the time of initialization * * Synopsis: list::shift() * * Synopsis: list::contains(value) * Variables: * (empty) - "true" if list contains value, "false" if not * * Synopsis: * list::find(start_pos, value) * Description: * finds the first occurrence of 'value' in the list at position >='start_pos'. * Variables: * pos - position of element, or "none" if not found * found - "true" if found, "false" if not * * Sysnopsis: * list::remove_at(remove_pos) * Description: * Removes the element at position 'remove_pos', which must refer to an existing element. * * Synopsis: * list::remove(value) * Description: * Removes the first occurrence of value in the list, which must be in the list. * * Synopsis: * list::set(list l1, ..., list lN) * Description: * Replaces the list with the concatenation of given lists. */ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <inttypes.h> #include <misc/offset.h> #include <misc/parse_number.h> #include <structure/IndexedList.h> #include <ncd/NCDModule.h> #include <ncd/extra/value_utils.h> #include <generated/blog_channel_ncd_list.h> #define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__) struct elem { IndexedListNode il_node; NCDValMem mem; NCDValRef val; }; struct instance { NCDModuleInst *i; IndexedList il; }; struct length_instance { NCDModuleInst *i; uint64_t length; }; struct get_instance { NCDModuleInst *i; NCDValMem mem; NCDValRef val; }; struct contains_instance { NCDModuleInst *i; int contains; }; struct find_instance { NCDModuleInst *i; int is_found; uint64_t found_pos; }; static uint64_t list_count (struct instance *o) { return IndexedList_Count(&o->il); } static struct elem * insert_value (NCDModuleInst *i, struct instance *o, NCDValRef val, uint64_t idx) { ASSERT(idx <= list_count(o)) ASSERT(!NCDVal_IsInvalid(val)) struct elem *e = malloc(sizeof(*e)); if (!e) { ModuleLog(i, BLOG_ERROR, "malloc failed"); goto fail0; } NCDValMem_Init(&e->mem); e->val = NCDVal_NewCopy(&e->mem, val); if (NCDVal_IsInvalid(e->val)) { goto fail1; } IndexedList_InsertAt(&o->il, &e->il_node, idx); return e; fail1: NCDValMem_Free(&e->mem); free(e); fail0: return NULL; } static void remove_elem (struct instance *o, struct elem *e) { IndexedList_Remove(&o->il, &e->il_node); NCDValMem_Free(&e->mem); free(e); } static struct elem * get_elem_at (struct instance *o, uint64_t idx) { ASSERT(idx < list_count(o)) IndexedListNode *iln = IndexedList_GetAt(&o->il, idx); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static struct elem * get_first_elem (struct instance *o) { ASSERT(list_count(o) > 0) IndexedListNode *iln = IndexedList_GetFirst(&o->il); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static struct elem * get_last_elem (struct instance *o) { ASSERT(list_count(o) > 0) IndexedListNode *iln = IndexedList_GetLast(&o->il); struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); return e; } static void cut_list_front (struct instance *o, uint64_t count) { while (list_count(o) > count) { remove_elem(o, get_first_elem(o)); } } static void cut_list_back (struct instance *o, uint64_t count) { while (list_count(o) > count) { remove_elem(o, get_last_elem(o)); } } static int append_list_contents (NCDModuleInst *i, struct instance *o, NCDValRef args) { ASSERT(NCDVal_IsList(args)) uint64_t orig_count = list_count(o); size_t append_count = NCDVal_ListCount(args); for (size_t j = 0; j < append_count; j++) { NCDValRef elem = NCDVal_ListGet(args, j); if (!insert_value(i, o, elem, list_count(o))) { goto fail; } } return 1; fail: cut_list_back(o, orig_count); return 0; } static int append_list_contents_contents (NCDModuleInst *i, struct instance *o, NCDValRef args) { ASSERT(NCDVal_IsList(args)) uint64_t orig_count = list_count(o); size_t append_count = NCDVal_ListCount(args); for (size_t j = 0; j < append_count; j++) { NCDValRef elem = NCDVal_ListGet(args, j); if (!NCDVal_IsList(elem)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail; } if (!append_list_contents(i, o, elem)) { goto fail; } } return 1; fail: cut_list_back(o, orig_count); return 0; } static struct elem * find_elem (struct instance *o, NCDValRef val, uint64_t start_idx, uint64_t *out_idx) { if (start_idx >= list_count(o)) { return NULL; } for (IndexedListNode *iln = IndexedList_GetAt(&o->il, start_idx); iln; iln = IndexedList_GetNext(&o->il, iln)) { struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); if (NCDVal_Compare(e->val, val) == 0) { if (out_idx) { *out_idx = start_idx; } return e; } start_idx++; } return NULL; } static int list_to_value (NCDModuleInst *i, struct instance *o, NCDValMem *mem, NCDValRef *out_val) { *out_val = NCDVal_NewList(mem, IndexedList_Count(&o->il)); if (NCDVal_IsInvalid(*out_val)) { goto fail; } for (IndexedListNode *iln = IndexedList_GetFirst(&o->il); iln; iln = IndexedList_GetNext(&o->il, iln)) { struct elem *e = UPPER_OBJECT(iln, struct elem, il_node); NCDValRef copy = NCDVal_NewCopy(mem, e->val); if (NCDVal_IsInvalid(copy)) { goto fail; } if (!NCDVal_ListAppend(*out_val, copy)) { goto fail; } } return 1; fail: return 0; } static void func_new_list (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct instance *o = vo; o->i = i; // init list IndexedList_Init(&o->il); // append contents if (!append_list_contents(i, o, params->args)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: cut_list_front(o, 0); NCDModuleInst_Backend_DeadError(i); } static void func_new_listfrom (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct instance *o = vo; o->i = i; // init list IndexedList_Init(&o->il); // append contents contents if (!append_list_contents_contents(i, o, params->args)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: cut_list_front(o, 0); NCDModuleInst_Backend_DeadError(i); } static void func_die (void *vo) { struct instance *o = vo; // free list elements cut_list_front(o, 0); NCDModuleInst_Backend_Dead(o->i); } static int func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct instance *o = vo; if (!strcmp(name, "")) { if (!list_to_value(o->i, o, mem, out)) { return 0; } return 1; } if (!strcmp(name, "length")) { *out = ncd_make_uintmax(mem, list_count(o)); return 1; } return 0; } static void append_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments NCDValRef arg; if (!NCDVal_ListRead(params->args, 1, &arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // append if (!insert_value(i, mo, arg, list_count(mo))) { goto fail0; } // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void appendv_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments NCDValRef arg; if (!NCDVal_ListRead(params->args, 1, &arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsList(arg)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // append if (!append_list_contents(i, mo, arg)) { goto fail0; } // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void length_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct length_instance *o = vo; o->i = i; // check arguments if (!NCDVal_ListRead(params->args, 0)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // remember length o->length = list_count(mo); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void length_func_die (void *vo) { struct length_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int length_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct length_instance *o = vo; if (!strcmp(name, "")) { *out = ncd_make_uintmax(mem, o->length); return 1; } return 0; } static void get_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct get_instance *o = vo; o->i = i; // check arguments NCDValRef index_arg; if (!NCDVal_ListRead(params->args, 1, &index_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(index_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } uintmax_t index; if (!ncd_read_uintmax(index_arg, &index)) { ModuleLog(o->i, BLOG_ERROR, "wrong value"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check index if (index >= list_count(mo)) { ModuleLog(o->i, BLOG_ERROR, "no element at index %"PRIuMAX, index); goto fail0; } // get element struct elem *e = get_elem_at(mo, index); // init mem NCDValMem_Init(&o->mem); // copy value o->val = NCDVal_NewCopy(&o->mem, e->val); if (NCDVal_IsInvalid(o->val)) { goto fail1; } // signal up NCDModuleInst_Backend_Up(o->i); return; fail1: NCDValMem_Free(&o->mem); fail0: NCDModuleInst_Backend_DeadError(i); } static void get_func_die (void *vo) { struct get_instance *o = vo; // free mem NCDValMem_Free(&o->mem); NCDModuleInst_Backend_Dead(o->i); } static int get_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct get_instance *o = vo; if (!strcmp(name, "")) { *out = NCDVal_NewCopy(mem, o->val); return 1; } return 0; } static void shift_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // check arguments if (!NCDVal_ListRead(params->args, 0)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check first if (list_count(mo) == 0) { ModuleLog(i, BLOG_ERROR, "list has no elements"); goto fail0; } // remove first remove_elem(mo, get_first_elem(mo)); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void contains_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct contains_instance *o = vo; o->i = i; // read arguments NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 1, &value_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // search o->contains = !!find_elem(mo, value_arg, 0, NULL); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void contains_func_die (void *vo) { struct contains_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int contains_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct contains_instance *o = vo; if (!strcmp(name, "")) { *out = ncd_make_boolean(mem, o->contains, o->i->params->iparams->string_index); return 1; } return 0; } static void find_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { struct find_instance *o = vo; o->i = i; // read arguments NCDValRef start_pos_arg; NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 2, &start_pos_arg, &value_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(start_pos_arg)) { ModuleLog(o->i, BLOG_ERROR, "wrong type"); goto fail0; } // read start position uintmax_t start_pos; if (!ncd_read_uintmax(start_pos_arg, &start_pos) || start_pos > UINT64_MAX) { ModuleLog(o->i, BLOG_ERROR, "wrong start pos"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // find o->is_found = !!find_elem(mo, value_arg, start_pos, &o->found_pos); // signal up NCDModuleInst_Backend_Up(o->i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void find_func_die (void *vo) { struct find_instance *o = vo; NCDModuleInst_Backend_Dead(o->i); } static int find_func_getvar (void *vo, const char *name, NCDValMem *mem, NCDValRef *out) { struct find_instance *o = vo; if (!strcmp(name, "pos")) { char value[64] = "none"; if (o->is_found) { generate_decimal_repr_string(o->found_pos, value); } *out = NCDVal_NewString(mem, value); return 1; } if (!strcmp(name, "found")) { *out = ncd_make_boolean(mem, o->is_found, o->i->params->iparams->string_index); return 1; } return 0; } static void removeat_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // read arguments NCDValRef remove_pos_arg; if (!NCDVal_ListRead(params->args, 1, &remove_pos_arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } if (!NCDVal_IsString(remove_pos_arg)) { ModuleLog(i, BLOG_ERROR, "wrong type"); goto fail0; } // read position uintmax_t remove_pos; if (!ncd_read_uintmax(remove_pos_arg, &remove_pos)) { ModuleLog(i, BLOG_ERROR, "wrong pos"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // check position if (remove_pos >= list_count(mo)) { ModuleLog(i, BLOG_ERROR, "pos out of range"); goto fail0; } // remove remove_elem(mo, get_elem_at(mo, remove_pos)); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void remove_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // read arguments NCDValRef value_arg; if (!NCDVal_ListRead(params->args, 1, &value_arg)) { ModuleLog(i, BLOG_ERROR, "wrong arity"); goto fail0; } // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // find element struct elem *e = find_elem(mo, value_arg, 0, NULL); if (!e) { ModuleLog(i, BLOG_ERROR, "value does not exist"); goto fail0; } // remove element remove_elem(mo, e); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static void set_func_new (void *unused, NCDModuleInst *i, const struct NCDModuleInst_new_params *params) { // get method object struct instance *mo = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user); // remember old count uint64_t old_count = list_count(mo); // append contents of our lists if (!append_list_contents_contents(i, mo, params->args)) { goto fail0; } // remove old elements cut_list_front(mo, list_count(mo) - old_count); // signal up NCDModuleInst_Backend_Up(i); return; fail0: NCDModuleInst_Backend_DeadError(i); } static struct NCDModule modules[] = { { .type = "list", .func_new2 = func_new_list, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "listfrom", .base_type = "list", .func_new2 = func_new_listfrom, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "concatlist", // alias for listfrom .base_type = "list", .func_new2 = func_new_listfrom, .func_die = func_die, .func_getvar = func_getvar, .alloc_size = sizeof(struct instance) }, { .type = "list::append", .func_new2 = append_func_new }, { .type = "list::appendv", .func_new2 = appendv_func_new }, { .type = "list::length", .func_new2 = length_func_new, .func_die = length_func_die, .func_getvar = length_func_getvar, .alloc_size = sizeof(struct length_instance) }, { .type = "list::get", .func_new2 = get_func_new, .func_die = get_func_die, .func_getvar = get_func_getvar, .alloc_size = sizeof(struct get_instance) }, { .type = "list::shift", .func_new2 = shift_func_new }, { .type = "list::contains", .func_new2 = contains_func_new, .func_die = contains_func_die, .func_getvar = contains_func_getvar, .alloc_size = sizeof(struct contains_instance) }, { .type = "list::find", .func_new2 = find_func_new, .func_die = find_func_die, .func_getvar = find_func_getvar, .alloc_size = sizeof(struct find_instance) }, { .type = "list::remove_at", .func_new2 = removeat_func_new }, { .type = "list::remove", .func_new2 = remove_func_new }, { .type = "list::set", .func_new2 = set_func_new }, { .type = NULL } }; const struct NCDModuleGroup ncdmodule_list = { .modules = modules };
gpl-3.0
luo3555/shadowsocks-android-bak
src/main/jni/openssl/crypto/x509/x509_r2x.c
873
4439
/* crypto/x509/x509_r2x.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "cryptlib.h" #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/objects.h> #include <openssl/buffer.h> X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey) { X509 *ret=NULL; X509_CINF *xi=NULL; X509_NAME *xn; if ((ret=X509_new()) == NULL) { X509err(X509_F_X509_REQ_TO_X509,ERR_R_MALLOC_FAILURE); goto err; } /* duplicate the request */ xi=ret->cert_info; if (sk_X509_ATTRIBUTE_num(r->req_info->attributes) != 0) { if ((xi->version=M_ASN1_INTEGER_new()) == NULL) goto err; if (!ASN1_INTEGER_set(xi->version,2)) goto err; /* xi->extensions=ri->attributes; <- bad, should not ever be done ri->attributes=NULL; */ } xn=X509_REQ_get_subject_name(r); if (X509_set_subject_name(ret,X509_NAME_dup(xn)) == 0) goto err; if (X509_set_issuer_name(ret,X509_NAME_dup(xn)) == 0) goto err; if (X509_gmtime_adj(xi->validity->notBefore,0) == NULL) goto err; if (X509_gmtime_adj(xi->validity->notAfter,(long)60*60*24*days) == NULL) goto err; X509_set_pubkey(ret,X509_REQ_get_pubkey(r)); if (!X509_sign(ret,pkey,EVP_md5())) goto err; if (0) { err: X509_free(ret); ret=NULL; } return(ret); }
gpl-3.0
kelvine/shadowsocks-android
src/main/jni/openssl/crypto/evp/e_bf.c
875
3950
/* crypto/evp/e_bf.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "cryptlib.h" #ifndef OPENSSL_NO_BF #include <openssl/evp.h> #include "evp_locl.h" #include <openssl/objects.h> #include <openssl/blowfish.h> static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc); typedef struct { BF_KEY ks; } EVP_BF_KEY; #define data(ctx) EVP_C_DATA(EVP_BF_KEY,ctx) IMPLEMENT_BLOCK_CIPHER(bf, ks, BF, EVP_BF_KEY, NID_bf, 8, 16, 8, 64, EVP_CIPH_VARIABLE_LENGTH, bf_init_key, NULL, EVP_CIPHER_set_asn1_iv, EVP_CIPHER_get_asn1_iv, NULL) static int bf_init_key(EVP_CIPHER_CTX *ctx, const unsigned char *key, const unsigned char *iv, int enc) { BF_set_key(&data(ctx)->ks,EVP_CIPHER_CTX_key_length(ctx),key); return 1; } #endif
gpl-3.0
disdi/MMC-DMA-Linux-performance
linux-3.15-rc8/drivers/phy/phy-exynos4x12-usb2.c
110
9248
/* * Samsung SoC USB 1.1/2.0 PHY driver - Exynos 4x12 support * * Copyright (C) 2013 Samsung Electronics Co., Ltd. * Author: Kamil Debski <k.debski@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/io.h> #include <linux/phy/phy.h> #include <linux/regmap.h> #include "phy-samsung-usb2.h" /* Exynos USB PHY registers */ /* PHY power control */ #define EXYNOS_4x12_UPHYPWR 0x0 #define EXYNOS_4x12_UPHYPWR_PHY0_SUSPEND BIT(0) #define EXYNOS_4x12_UPHYPWR_PHY0_PWR BIT(3) #define EXYNOS_4x12_UPHYPWR_PHY0_OTG_PWR BIT(4) #define EXYNOS_4x12_UPHYPWR_PHY0_SLEEP BIT(5) #define EXYNOS_4x12_UPHYPWR_PHY0 ( \ EXYNOS_4x12_UPHYPWR_PHY0_SUSPEND | \ EXYNOS_4x12_UPHYPWR_PHY0_PWR | \ EXYNOS_4x12_UPHYPWR_PHY0_OTG_PWR | \ EXYNOS_4x12_UPHYPWR_PHY0_SLEEP) #define EXYNOS_4x12_UPHYPWR_PHY1_SUSPEND BIT(6) #define EXYNOS_4x12_UPHYPWR_PHY1_PWR BIT(7) #define EXYNOS_4x12_UPHYPWR_PHY1_SLEEP BIT(8) #define EXYNOS_4x12_UPHYPWR_PHY1 ( \ EXYNOS_4x12_UPHYPWR_PHY1_SUSPEND | \ EXYNOS_4x12_UPHYPWR_PHY1_PWR | \ EXYNOS_4x12_UPHYPWR_PHY1_SLEEP) #define EXYNOS_4x12_UPHYPWR_HSIC0_SUSPEND BIT(9) #define EXYNOS_4x12_UPHYPWR_HSIC0_PWR BIT(10) #define EXYNOS_4x12_UPHYPWR_HSIC0_SLEEP BIT(11) #define EXYNOS_4x12_UPHYPWR_HSIC0 ( \ EXYNOS_4x12_UPHYPWR_HSIC0_SUSPEND | \ EXYNOS_4x12_UPHYPWR_HSIC0_PWR | \ EXYNOS_4x12_UPHYPWR_HSIC0_SLEEP) #define EXYNOS_4x12_UPHYPWR_HSIC1_SUSPEND BIT(12) #define EXYNOS_4x12_UPHYPWR_HSIC1_PWR BIT(13) #define EXYNOS_4x12_UPHYPWR_HSIC1_SLEEP BIT(14) #define EXYNOS_4x12_UPHYPWR_HSIC1 ( \ EXYNOS_4x12_UPHYPWR_HSIC1_SUSPEND | \ EXYNOS_4x12_UPHYPWR_HSIC1_PWR | \ EXYNOS_4x12_UPHYPWR_HSIC1_SLEEP) /* PHY clock control */ #define EXYNOS_4x12_UPHYCLK 0x4 #define EXYNOS_4x12_UPHYCLK_PHYFSEL_MASK (0x7 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_OFFSET 0 #define EXYNOS_4x12_UPHYCLK_PHYFSEL_9MHZ6 (0x0 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_10MHZ (0x1 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_12MHZ (0x2 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_19MHZ2 (0x3 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_20MHZ (0x4 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_24MHZ (0x5 << 0) #define EXYNOS_4x12_UPHYCLK_PHYFSEL_50MHZ (0x7 << 0) #define EXYNOS_4x12_UPHYCLK_PHY0_ID_PULLUP BIT(3) #define EXYNOS_4x12_UPHYCLK_PHY0_COMMON_ON BIT(4) #define EXYNOS_4x12_UPHYCLK_PHY1_COMMON_ON BIT(7) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_MASK (0x7f << 10) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_OFFSET 10 #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_12MHZ (0x24 << 10) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_15MHZ (0x1c << 10) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_16MHZ (0x1a << 10) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_19MHZ2 (0x15 << 10) #define EXYNOS_4x12_UPHYCLK_HSIC_REFCLK_20MHZ (0x14 << 10) /* PHY reset control */ #define EXYNOS_4x12_UPHYRST 0x8 #define EXYNOS_4x12_URSTCON_PHY0 BIT(0) #define EXYNOS_4x12_URSTCON_OTG_HLINK BIT(1) #define EXYNOS_4x12_URSTCON_OTG_PHYLINK BIT(2) #define EXYNOS_4x12_URSTCON_HOST_PHY BIT(3) #define EXYNOS_4x12_URSTCON_PHY1 BIT(4) #define EXYNOS_4x12_URSTCON_HSIC0 BIT(5) #define EXYNOS_4x12_URSTCON_HSIC1 BIT(6) #define EXYNOS_4x12_URSTCON_HOST_LINK_ALL BIT(7) #define EXYNOS_4x12_URSTCON_HOST_LINK_P0 BIT(8) #define EXYNOS_4x12_URSTCON_HOST_LINK_P1 BIT(9) #define EXYNOS_4x12_URSTCON_HOST_LINK_P2 BIT(10) /* Isolation, configured in the power management unit */ #define EXYNOS_4x12_USB_ISOL_OFFSET 0x704 #define EXYNOS_4x12_USB_ISOL_OTG BIT(0) #define EXYNOS_4x12_USB_ISOL_HSIC0_OFFSET 0x708 #define EXYNOS_4x12_USB_ISOL_HSIC0 BIT(0) #define EXYNOS_4x12_USB_ISOL_HSIC1_OFFSET 0x70c #define EXYNOS_4x12_USB_ISOL_HSIC1 BIT(0) /* Mode switching SUB Device <-> Host */ #define EXYNOS_4x12_MODE_SWITCH_OFFSET 0x21c #define EXYNOS_4x12_MODE_SWITCH_MASK 1 #define EXYNOS_4x12_MODE_SWITCH_DEVICE 0 #define EXYNOS_4x12_MODE_SWITCH_HOST 1 enum exynos4x12_phy_id { EXYNOS4x12_DEVICE, EXYNOS4x12_HOST, EXYNOS4x12_HSIC0, EXYNOS4x12_HSIC1, EXYNOS4x12_NUM_PHYS, }; /* * exynos4x12_rate_to_clk() converts the supplied clock rate to the value that * can be written to the phy register. */ static int exynos4x12_rate_to_clk(unsigned long rate, u32 *reg) { /* EXYNOS_4x12_UPHYCLK_PHYFSEL_MASK */ switch (rate) { case 9600 * KHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_9MHZ6; break; case 10 * MHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_10MHZ; break; case 12 * MHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_12MHZ; break; case 19200 * KHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_19MHZ2; break; case 20 * MHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_20MHZ; break; case 24 * MHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_24MHZ; break; case 50 * MHZ: *reg = EXYNOS_4x12_UPHYCLK_PHYFSEL_50MHZ; break; default: return -EINVAL; } return 0; } static void exynos4x12_isol(struct samsung_usb2_phy_instance *inst, bool on) { struct samsung_usb2_phy_driver *drv = inst->drv; u32 offset; u32 mask; switch (inst->cfg->id) { case EXYNOS4x12_DEVICE: case EXYNOS4x12_HOST: offset = EXYNOS_4x12_USB_ISOL_OFFSET; mask = EXYNOS_4x12_USB_ISOL_OTG; break; case EXYNOS4x12_HSIC0: offset = EXYNOS_4x12_USB_ISOL_HSIC0_OFFSET; mask = EXYNOS_4x12_USB_ISOL_HSIC0; break; case EXYNOS4x12_HSIC1: offset = EXYNOS_4x12_USB_ISOL_HSIC1_OFFSET; mask = EXYNOS_4x12_USB_ISOL_HSIC1; break; default: return; }; regmap_update_bits(drv->reg_pmu, offset, mask, on ? 0 : mask); } static void exynos4x12_setup_clk(struct samsung_usb2_phy_instance *inst) { struct samsung_usb2_phy_driver *drv = inst->drv; u32 clk; clk = readl(drv->reg_phy + EXYNOS_4x12_UPHYCLK); clk &= ~EXYNOS_4x12_UPHYCLK_PHYFSEL_MASK; clk |= drv->ref_reg_val << EXYNOS_4x12_UPHYCLK_PHYFSEL_OFFSET; writel(clk, drv->reg_phy + EXYNOS_4x12_UPHYCLK); } static void exynos4x12_phy_pwr(struct samsung_usb2_phy_instance *inst, bool on) { struct samsung_usb2_phy_driver *drv = inst->drv; u32 rstbits = 0; u32 phypwr = 0; u32 rst; u32 pwr; u32 mode = 0; u32 switch_mode = 0; switch (inst->cfg->id) { case EXYNOS4x12_DEVICE: phypwr = EXYNOS_4x12_UPHYPWR_PHY0; rstbits = EXYNOS_4x12_URSTCON_PHY0; mode = EXYNOS_4x12_MODE_SWITCH_DEVICE; switch_mode = 1; break; case EXYNOS4x12_HOST: phypwr = EXYNOS_4x12_UPHYPWR_PHY1; rstbits = EXYNOS_4x12_URSTCON_HOST_PHY; mode = EXYNOS_4x12_MODE_SWITCH_HOST; switch_mode = 1; break; case EXYNOS4x12_HSIC0: phypwr = EXYNOS_4x12_UPHYPWR_HSIC0; rstbits = EXYNOS_4x12_URSTCON_HSIC1 | EXYNOS_4x12_URSTCON_HOST_LINK_P0 | EXYNOS_4x12_URSTCON_HOST_PHY; break; case EXYNOS4x12_HSIC1: phypwr = EXYNOS_4x12_UPHYPWR_HSIC1; rstbits = EXYNOS_4x12_URSTCON_HSIC1 | EXYNOS_4x12_URSTCON_HOST_LINK_P1; break; }; if (on) { if (switch_mode) regmap_update_bits(drv->reg_sys, EXYNOS_4x12_MODE_SWITCH_OFFSET, EXYNOS_4x12_MODE_SWITCH_MASK, mode); pwr = readl(drv->reg_phy + EXYNOS_4x12_UPHYPWR); pwr &= ~phypwr; writel(pwr, drv->reg_phy + EXYNOS_4x12_UPHYPWR); rst = readl(drv->reg_phy + EXYNOS_4x12_UPHYRST); rst |= rstbits; writel(rst, drv->reg_phy + EXYNOS_4x12_UPHYRST); udelay(10); rst &= ~rstbits; writel(rst, drv->reg_phy + EXYNOS_4x12_UPHYRST); /* The following delay is necessary for the reset sequence to be * completed */ udelay(80); } else { pwr = readl(drv->reg_phy + EXYNOS_4x12_UPHYPWR); pwr |= phypwr; writel(pwr, drv->reg_phy + EXYNOS_4x12_UPHYPWR); } } static int exynos4x12_power_on(struct samsung_usb2_phy_instance *inst) { struct samsung_usb2_phy_driver *drv = inst->drv; inst->enabled = 1; exynos4x12_setup_clk(inst); exynos4x12_phy_pwr(inst, 1); exynos4x12_isol(inst, 0); /* Power on the device, as it is necessary for HSIC to work */ if (inst->cfg->id == EXYNOS4x12_HSIC0) { struct samsung_usb2_phy_instance *device = &drv->instances[EXYNOS4x12_DEVICE]; exynos4x12_phy_pwr(device, 1); exynos4x12_isol(device, 0); } return 0; } static int exynos4x12_power_off(struct samsung_usb2_phy_instance *inst) { struct samsung_usb2_phy_driver *drv = inst->drv; struct samsung_usb2_phy_instance *device = &drv->instances[EXYNOS4x12_DEVICE]; inst->enabled = 0; exynos4x12_isol(inst, 1); exynos4x12_phy_pwr(inst, 0); if (inst->cfg->id == EXYNOS4x12_HSIC0 && !device->enabled) { exynos4x12_isol(device, 1); exynos4x12_phy_pwr(device, 0); } return 0; } static const struct samsung_usb2_common_phy exynos4x12_phys[] = { { .label = "device", .id = EXYNOS4x12_DEVICE, .power_on = exynos4x12_power_on, .power_off = exynos4x12_power_off, }, { .label = "host", .id = EXYNOS4x12_HOST, .power_on = exynos4x12_power_on, .power_off = exynos4x12_power_off, }, { .label = "hsic0", .id = EXYNOS4x12_HSIC0, .power_on = exynos4x12_power_on, .power_off = exynos4x12_power_off, }, { .label = "hsic1", .id = EXYNOS4x12_HSIC1, .power_on = exynos4x12_power_on, .power_off = exynos4x12_power_off, }, {}, }; const struct samsung_usb2_phy_config exynos4x12_usb2_phy_config = { .has_mode_switch = 1, .num_phys = EXYNOS4x12_NUM_PHYS, .phys = exynos4x12_phys, .rate_to_clk = exynos4x12_rate_to_clk, };
gpl-3.0
murusu/shadowsocks-android
src/main/jni/openssl/crypto/rc2/rc2ofb64.c
878
4221
/* crypto/rc2/rc2ofb64.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <openssl/rc2.h> #include "rc2_locl.h" /* The input and output encrypted as though 64bit ofb mode is being * used. The extra state information to record how much of the * 64bit block we have used is contained in *num; */ void RC2_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, RC2_KEY *schedule, unsigned char *ivec, int *num) { register unsigned long v0,v1,t; register int n= *num; register long l=length; unsigned char d[8]; register char *dp; unsigned long ti[2]; unsigned char *iv; int save=0; iv=(unsigned char *)ivec; c2l(iv,v0); c2l(iv,v1); ti[0]=v0; ti[1]=v1; dp=(char *)d; l2c(v0,dp); l2c(v1,dp); while (l--) { if (n == 0) { RC2_encrypt((unsigned long *)ti,schedule); dp=(char *)d; t=ti[0]; l2c(t,dp); t=ti[1]; l2c(t,dp); save++; } *(out++)= *(in++)^d[n]; n=(n+1)&0x07; } if (save) { v0=ti[0]; v1=ti[1]; iv=(unsigned char *)ivec; l2c(v0,iv); l2c(v1,iv); } t=v0=v1=ti[0]=ti[1]=0; *num=n; }
gpl-3.0
wvdd007/robomongo
src/third-party/qscintilla/lexers/LexAda.cpp
111
11715
// Scintilla source code edit control /** @file LexAda.cxx ** Lexer for Ada 95 **/ // Copyright 2002 by Sergey Koshcheyev <sergey.k@seznam.cz> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include <string> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif /* * Interface */ static void ColouriseDocument( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler); static const char * const adaWordListDesc[] = { "Keywords", 0 }; LexerModule lmAda(SCLEX_ADA, ColouriseDocument, "ada", NULL, adaWordListDesc); /* * Implementation */ // Functions that have apostropheStartsAttribute as a parameter set it according to whether // an apostrophe encountered after processing the current token will start an attribute or // a character literal. static void ColouriseCharacter(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseComment(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseContext(StyleContext& sc, char chEnd, int stateEOL); static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseLabel(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute); static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseString(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseWhiteSpace(StyleContext& sc, bool& apostropheStartsAttribute); static void ColouriseWord(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute); static inline bool IsDelimiterCharacter(int ch); static inline bool IsSeparatorOrDelimiterCharacter(int ch); static bool IsValidIdentifier(const std::string& identifier); static bool IsValidNumber(const std::string& number); static inline bool IsWordStartCharacter(int ch); static inline bool IsWordCharacter(int ch); static void ColouriseCharacter(StyleContext& sc, bool& apostropheStartsAttribute) { apostropheStartsAttribute = true; sc.SetState(SCE_ADA_CHARACTER); // Skip the apostrophe and one more character (so that '' is shown as non-terminated and ''' // is handled correctly) sc.Forward(); sc.Forward(); ColouriseContext(sc, '\'', SCE_ADA_CHARACTEREOL); } static void ColouriseContext(StyleContext& sc, char chEnd, int stateEOL) { while (!sc.atLineEnd && !sc.Match(chEnd)) { sc.Forward(); } if (!sc.atLineEnd) { sc.ForwardSetState(SCE_ADA_DEFAULT); } else { sc.ChangeState(stateEOL); } } static void ColouriseComment(StyleContext& sc, bool& /*apostropheStartsAttribute*/) { // Apostrophe meaning is not changed, but the parameter is present for uniformity sc.SetState(SCE_ADA_COMMENTLINE); while (!sc.atLineEnd) { sc.Forward(); } } static void ColouriseDelimiter(StyleContext& sc, bool& apostropheStartsAttribute) { apostropheStartsAttribute = sc.Match (')'); sc.SetState(SCE_ADA_DELIMITER); sc.ForwardSetState(SCE_ADA_DEFAULT); } static void ColouriseLabel(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute) { apostropheStartsAttribute = false; sc.SetState(SCE_ADA_LABEL); // Skip "<<" sc.Forward(); sc.Forward(); std::string identifier; while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) { identifier += static_cast<char>(tolower(sc.ch)); sc.Forward(); } // Skip ">>" if (sc.Match('>', '>')) { sc.Forward(); sc.Forward(); } else { sc.ChangeState(SCE_ADA_ILLEGAL); } // If the name is an invalid identifier or a keyword, then make it invalid label if (!IsValidIdentifier(identifier) || keywords.InList(identifier.c_str())) { sc.ChangeState(SCE_ADA_ILLEGAL); } sc.SetState(SCE_ADA_DEFAULT); } static void ColouriseNumber(StyleContext& sc, bool& apostropheStartsAttribute) { apostropheStartsAttribute = true; std::string number; sc.SetState(SCE_ADA_NUMBER); // Get all characters up to a delimiter or a separator, including points, but excluding // double points (ranges). while (!IsSeparatorOrDelimiterCharacter(sc.ch) || (sc.ch == '.' && sc.chNext != '.')) { number += static_cast<char>(sc.ch); sc.Forward(); } // Special case: exponent with sign if ((sc.chPrev == 'e' || sc.chPrev == 'E') && (sc.ch == '+' || sc.ch == '-')) { number += static_cast<char>(sc.ch); sc.Forward (); while (!IsSeparatorOrDelimiterCharacter(sc.ch)) { number += static_cast<char>(sc.ch); sc.Forward(); } } if (!IsValidNumber(number)) { sc.ChangeState(SCE_ADA_ILLEGAL); } sc.SetState(SCE_ADA_DEFAULT); } static void ColouriseString(StyleContext& sc, bool& apostropheStartsAttribute) { apostropheStartsAttribute = true; sc.SetState(SCE_ADA_STRING); sc.Forward(); ColouriseContext(sc, '"', SCE_ADA_STRINGEOL); } static void ColouriseWhiteSpace(StyleContext& sc, bool& /*apostropheStartsAttribute*/) { // Apostrophe meaning is not changed, but the parameter is present for uniformity sc.SetState(SCE_ADA_DEFAULT); sc.ForwardSetState(SCE_ADA_DEFAULT); } static void ColouriseWord(StyleContext& sc, WordList& keywords, bool& apostropheStartsAttribute) { apostropheStartsAttribute = true; sc.SetState(SCE_ADA_IDENTIFIER); std::string word; while (!sc.atLineEnd && !IsSeparatorOrDelimiterCharacter(sc.ch)) { word += static_cast<char>(tolower(sc.ch)); sc.Forward(); } if (!IsValidIdentifier(word)) { sc.ChangeState(SCE_ADA_ILLEGAL); } else if (keywords.InList(word.c_str())) { sc.ChangeState(SCE_ADA_WORD); if (word != "all") { apostropheStartsAttribute = false; } } sc.SetState(SCE_ADA_DEFAULT); } // // ColouriseDocument // static void ColouriseDocument( unsigned int startPos, int length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; StyleContext sc(startPos, length, initStyle, styler); int lineCurrent = styler.GetLine(startPos); bool apostropheStartsAttribute = (styler.GetLineState(lineCurrent) & 1) != 0; while (sc.More()) { if (sc.atLineEnd) { // Go to the next line sc.Forward(); lineCurrent++; // Remember the line state for future incremental lexing styler.SetLineState(lineCurrent, apostropheStartsAttribute); // Don't continue any styles on the next line sc.SetState(SCE_ADA_DEFAULT); } // Comments if (sc.Match('-', '-')) { ColouriseComment(sc, apostropheStartsAttribute); // Strings } else if (sc.Match('"')) { ColouriseString(sc, apostropheStartsAttribute); // Characters } else if (sc.Match('\'') && !apostropheStartsAttribute) { ColouriseCharacter(sc, apostropheStartsAttribute); // Labels } else if (sc.Match('<', '<')) { ColouriseLabel(sc, keywords, apostropheStartsAttribute); // Whitespace } else if (IsASpace(sc.ch)) { ColouriseWhiteSpace(sc, apostropheStartsAttribute); // Delimiters } else if (IsDelimiterCharacter(sc.ch)) { ColouriseDelimiter(sc, apostropheStartsAttribute); // Numbers } else if (IsADigit(sc.ch) || sc.ch == '#') { ColouriseNumber(sc, apostropheStartsAttribute); // Keywords or identifiers } else { ColouriseWord(sc, keywords, apostropheStartsAttribute); } } sc.Complete(); } static inline bool IsDelimiterCharacter(int ch) { switch (ch) { case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '|': return true; default: return false; } } static inline bool IsSeparatorOrDelimiterCharacter(int ch) { return IsASpace(ch) || IsDelimiterCharacter(ch); } static bool IsValidIdentifier(const std::string& identifier) { // First character can't be '_', so initialize the flag to true bool lastWasUnderscore = true; size_t length = identifier.length(); // Zero-length identifiers are not valid (these can occur inside labels) if (length == 0) { return false; } // Check for valid character at the start if (!IsWordStartCharacter(identifier[0])) { return false; } // Check for only valid characters and no double underscores for (size_t i = 0; i < length; i++) { if (!IsWordCharacter(identifier[i]) || (identifier[i] == '_' && lastWasUnderscore)) { return false; } lastWasUnderscore = identifier[i] == '_'; } // Check for underscore at the end if (lastWasUnderscore == true) { return false; } // All checks passed return true; } static bool IsValidNumber(const std::string& number) { size_t hashPos = number.find("#"); bool seenDot = false; size_t i = 0; size_t length = number.length(); if (length == 0) return false; // Just in case // Decimal number if (hashPos == std::string::npos) { bool canBeSpecial = false; for (; i < length; i++) { if (number[i] == '_') { if (!canBeSpecial) { return false; } canBeSpecial = false; } else if (number[i] == '.') { if (!canBeSpecial || seenDot) { return false; } canBeSpecial = false; seenDot = true; } else if (IsADigit(number[i])) { canBeSpecial = true; } else { break; } } if (!canBeSpecial) return false; } else { // Based number bool canBeSpecial = false; int base = 0; // Parse base for (; i < length; i++) { int ch = number[i]; if (ch == '_') { if (!canBeSpecial) return false; canBeSpecial = false; } else if (IsADigit(ch)) { base = base * 10 + (ch - '0'); if (base > 16) return false; canBeSpecial = true; } else if (ch == '#' && canBeSpecial) { break; } else { return false; } } if (base < 2) return false; if (i == length) return false; i++; // Skip over '#' // Parse number canBeSpecial = false; for (; i < length; i++) { int ch = tolower(number[i]); if (ch == '_') { if (!canBeSpecial) { return false; } canBeSpecial = false; } else if (ch == '.') { if (!canBeSpecial || seenDot) { return false; } canBeSpecial = false; seenDot = true; } else if (IsADigit(ch)) { if (ch - '0' >= base) { return false; } canBeSpecial = true; } else if (ch >= 'a' && ch <= 'f') { if (ch - 'a' + 10 >= base) { return false; } canBeSpecial = true; } else if (ch == '#' && canBeSpecial) { break; } else { return false; } } if (i == length) { return false; } i++; } // Exponent (optional) if (i < length) { if (number[i] != 'e' && number[i] != 'E') return false; i++; // Move past 'E' if (i == length) { return false; } if (number[i] == '+') i++; else if (number[i] == '-') { if (seenDot) { i++; } else { return false; // Integer literals should not have negative exponents } } if (i == length) { return false; } bool canBeSpecial = false; for (; i < length; i++) { if (number[i] == '_') { if (!canBeSpecial) { return false; } canBeSpecial = false; } else if (IsADigit(number[i])) { canBeSpecial = true; } else { return false; } } if (!canBeSpecial) return false; } // if i == length, number was parsed successfully. return i == length; } static inline bool IsWordCharacter(int ch) { return IsWordStartCharacter(ch) || IsADigit(ch); } static inline bool IsWordStartCharacter(int ch) { return (IsASCII(ch) && isalpha(ch)) || ch == '_'; }
gpl-3.0
baolfire/shadowsocks-android
src/main/jni/badvpn/dostest/StreamBuffer.c
368
4968
/** * @file StreamBuffer.c * @author Ambroz Bizjak <ambrop7@gmail.com> * * @section LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the author 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 AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <misc/balloc.h> #include <misc/minmax.h> #include "StreamBuffer.h" // called when receive operation is complete static void input_handler_done (void *vo, int data_len) { StreamBuffer *o = (StreamBuffer *)vo; ASSERT(data_len > 0) ASSERT(data_len <= o->buf_size - (o->buf_start + o->buf_used)) // remember if buffer was empty int was_empty = (o->buf_used == 0); // increment buf_used by the amount that was received o->buf_used += data_len; // start another receive operation unless buffer is full if (o->buf_used < o->buf_size - o->buf_start) { int end = o->buf_start + o->buf_used; StreamRecvInterface_Receiver_Recv(o->input, o->buf + end, o->buf_size - end); } else if (o->buf_used < o->buf_size) { // wrap around StreamRecvInterface_Receiver_Recv(o->input, o->buf, o->buf_start); } // if buffer was empty before, start send operation if (was_empty) { StreamPassInterface_Sender_Send(o->output, o->buf + o->buf_start, o->buf_used); } } // called when send operation is complete static void output_handler_done (void *vo, int data_len) { StreamBuffer *o = (StreamBuffer *)vo; ASSERT(data_len > 0) ASSERT(data_len <= o->buf_used) ASSERT(data_len <= o->buf_size - o->buf_start) // remember if buffer was full int was_full = (o->buf_used == o->buf_size); // increment buf_start and decrement buf_used by the // amount that was sent o->buf_start += data_len; o->buf_used -= data_len; // wrap around buf_start if (o->buf_start == o->buf_size) { o->buf_start = 0; } // start receive operation if buffer was full if (was_full) { int end; int avail; if (o->buf_used >= o->buf_size - o->buf_start) { end = o->buf_used - (o->buf_size - o->buf_start); avail = o->buf_start - end; } else { end = o->buf_start + o->buf_used; avail = o->buf_size - end; } StreamRecvInterface_Receiver_Recv(o->input, o->buf + end, avail); } // start another receive send unless buffer is empty if (o->buf_used > 0) { int to_send = bmin_int(o->buf_used, o->buf_size - o->buf_start); StreamPassInterface_Sender_Send(o->output, o->buf + o->buf_start, to_send); } } int StreamBuffer_Init (StreamBuffer *o, int buf_size, StreamRecvInterface *input, StreamPassInterface *output) { ASSERT(buf_size > 0) ASSERT(input) ASSERT(output) // remember arguments o->buf_size = buf_size; o->input = input; o->output = output; // allocate buffer memory o->buf = (uint8_t *)BAllocSize(bsize_fromint(o->buf_size)); if (!o->buf) { goto fail0; } // set initial buffer state o->buf_start = 0; o->buf_used = 0; // set receive and send done callbacks StreamRecvInterface_Receiver_Init(o->input, input_handler_done, o); StreamPassInterface_Sender_Init(o->output, output_handler_done, o); // start receive operation StreamRecvInterface_Receiver_Recv(o->input, o->buf, o->buf_size); DebugObject_Init(&o->d_obj); return 1; fail0: return 0; } void StreamBuffer_Free (StreamBuffer *o) { DebugObject_Free(&o->d_obj); // free buffer memory BFree(o->buf); }
gpl-3.0
yukuilong/Avplayer-old
third_party/android/openssl-1.0.1e/apps/openssl.c
117
20003
/* apps/openssl.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2006 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 * openssl-core@openssl.org. * * 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 * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #define OPENSSL_C /* tells apps.h to use complete apps_startup() */ #include "apps.h" #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/lhash.h> #include <openssl/conf.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif #define USE_SOCKETS /* needed for the _O_BINARY defs in the MS world */ #include "progs.h" #include "s_apps.h" #include <openssl/err.h> #ifdef OPENSSL_FIPS #include <openssl/fips.h> #endif /* The LHASH callbacks ("hash" & "cmp") have been replaced by functions with the * base prototypes (we cast each variable inside the function to the required * type of "FUNCTION*"). This removes the necessity for macro-generated wrapper * functions. */ static LHASH_OF(FUNCTION) *prog_init(void ); static int do_cmd(LHASH_OF(FUNCTION) *prog,int argc,char *argv[]); static void list_pkey(BIO *out); static void list_cipher(BIO *out); static void list_md(BIO *out); char *default_config_file=NULL; /* Make sure there is only one when MONOLITH is defined */ #ifdef MONOLITH CONF *config=NULL; BIO *bio_err=NULL; #endif static void lock_dbg_cb(int mode, int type, const char *file, int line) { static int modes[CRYPTO_NUM_LOCKS]; /* = {0, 0, ... } */ const char *errstr = NULL; int rw; rw = mode & (CRYPTO_READ|CRYPTO_WRITE); if (!((rw == CRYPTO_READ) || (rw == CRYPTO_WRITE))) { errstr = "invalid mode"; goto err; } if (type < 0 || type >= CRYPTO_NUM_LOCKS) { errstr = "type out of bounds"; goto err; } if (mode & CRYPTO_LOCK) { if (modes[type]) { errstr = "already locked"; /* must not happen in a single-threaded program * (would deadlock) */ goto err; } modes[type] = rw; } else if (mode & CRYPTO_UNLOCK) { if (!modes[type]) { errstr = "not locked"; goto err; } if (modes[type] != rw) { errstr = (rw == CRYPTO_READ) ? "CRYPTO_r_unlock on write lock" : "CRYPTO_w_unlock on read lock"; } modes[type] = 0; } else { errstr = "invalid mode"; goto err; } err: if (errstr) { /* we cannot use bio_err here */ fprintf(stderr, "openssl (lock_dbg_cb): %s (mode=%d, type=%d) at %s:%d\n", errstr, mode, type, file, line); } } #if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) # define ARGV _Argv #else # define ARGV Argv #endif int main(int Argc, char *ARGV[]) { ARGS arg; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE+1]; FUNCTION f,*fp; MS_STATIC const char *prompt; MS_STATIC char buf[1024]; char *to_free=NULL; int n,i,ret=0; int argc; char **argv,*p; LHASH_OF(FUNCTION) *prog=NULL; long errline; #if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) /* 2011-03-22 SMS. * If we have 32-bit pointers everywhere, then we're safe, and * we bypass this mess, as on non-VMS systems. (See ARGV, * above.) * Problem 1: Compaq/HP C before V7.3 always used 32-bit * pointers for argv[]. * Fix 1: For a 32-bit argv[], when we're using 64-bit pointers * everywhere else, we always allocate and use a 64-bit * duplicate of argv[]. * Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed * to NULL-terminate a 64-bit argv[]. (As this was written, the * compiler ECO was available only on IA64.) * Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a * 64-bit argv[argc] for NULL, and, if necessary, use a * (properly) NULL-terminated (64-bit) duplicate of argv[]. * The same code is used in either case to duplicate argv[]. * Some of these decisions could be handled in preprocessing, * but the code tends to get even uglier, and the penalty for * deciding at compile- or run-time is tiny. */ char **Argv = NULL; int free_Argv = 0; if ((sizeof( _Argv) < 8) /* 32-bit argv[]. */ # if !defined( VMS_TRUST_ARGV) || (_Argv[ Argc] != NULL) /* Untrusted argv[argc] not NULL. */ # endif ) { int i; Argv = OPENSSL_malloc( (Argc+ 1)* sizeof( char *)); if (Argv == NULL) { ret = -1; goto end; } for(i = 0; i < Argc; i++) Argv[i] = _Argv[i]; Argv[ Argc] = NULL; /* Certain NULL termination. */ free_Argv = 1; } else { /* Use the known-good 32-bit argv[] (which needs the * type cast to satisfy the compiler), or the trusted or * tested-good 64-bit argv[] as-is. */ Argv = (char **)_Argv; } #endif /* defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) */ arg.data=NULL; arg.count=0; if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */ { if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))) { CRYPTO_malloc_debug_init(); CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL); } else { /* OPENSSL_DEBUG_MEMORY=off */ CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0); } } CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #if 0 if (getenv("OPENSSL_DEBUG_LOCKING") != NULL) #endif { CRYPTO_set_locking_callback(lock_dbg_cb); } if(getenv("OPENSSL_FIPS")) { #ifdef OPENSSL_FIPS if (!FIPS_mode_set(1)) { ERR_load_crypto_strings(); ERR_print_errors(BIO_new_fp(stderr,BIO_NOCLOSE)); EXIT(1); } #else fprintf(stderr, "FIPS mode not supported.\n"); EXIT(1); #endif } apps_startup(); /* Lets load up our environment a little */ p=getenv("OPENSSL_CONF"); if (p == NULL) p=getenv("SSLEAY_CONF"); if (p == NULL) p=to_free=make_config_name(); default_config_file=p; config=NCONF_new(NULL); i=NCONF_load(config,p,&errline); if (i == 0) { if (ERR_GET_REASON(ERR_peek_last_error()) == CONF_R_NO_SUCH_FILE) { BIO_printf(bio_err, "WARNING: can't open config file: %s\n",p); ERR_clear_error(); NCONF_free(config); config = NULL; } else { ERR_print_errors(bio_err); NCONF_free(config); exit(1); } } prog=prog_init(); /* first check the program name */ program_name(Argv[0],pname,sizeof pname); f.name=pname; fp=lh_FUNCTION_retrieve(prog,&f); if (fp != NULL) { Argv[0]=pname; ret=fp->func(Argc,Argv); goto end; } /* ok, now check that there are not arguments, if there are, * run with them, shifting the ssleay off the front */ if (Argc != 1) { Argc--; Argv++; ret=do_cmd(prog,Argc,Argv); if (ret < 0) ret=0; goto end; } /* ok, lets enter the old 'OpenSSL>' mode */ for (;;) { ret=0; p=buf; n=sizeof buf; i=0; for (;;) { p[0]='\0'; if (i++) prompt=">"; else prompt="OpenSSL> "; fputs(prompt,stdout); fflush(stdout); if (!fgets(p,n,stdin)) goto end; if (p[0] == '\0') goto end; i=strlen(p); if (i <= 1) break; if (p[i-2] != '\\') break; i-=2; p+=i; n-=i; } if (!chopup_args(&arg,buf,&argc,&argv)) break; ret=do_cmd(prog,argc,argv); if (ret < 0) { ret=0; goto end; } if (ret != 0) BIO_printf(bio_err,"error in %s\n",argv[0]); (void)BIO_flush(bio_err); } BIO_printf(bio_err,"bad exit\n"); ret=1; end: if (to_free) OPENSSL_free(to_free); if (config != NULL) { NCONF_free(config); config=NULL; } if (prog != NULL) lh_FUNCTION_free(prog); if (arg.data != NULL) OPENSSL_free(arg.data); apps_shutdown(); CRYPTO_mem_leaks(bio_err); if (bio_err != NULL) { BIO_free(bio_err); bio_err=NULL; } #if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) /* Free any duplicate Argv[] storage. */ if (free_Argv) { OPENSSL_free(Argv); } #endif OPENSSL_EXIT(ret); } #define LIST_STANDARD_COMMANDS "list-standard-commands" #define LIST_MESSAGE_DIGEST_COMMANDS "list-message-digest-commands" #define LIST_MESSAGE_DIGEST_ALGORITHMS "list-message-digest-algorithms" #define LIST_CIPHER_COMMANDS "list-cipher-commands" #define LIST_CIPHER_ALGORITHMS "list-cipher-algorithms" #define LIST_PUBLIC_KEY_ALGORITHMS "list-public-key-algorithms" static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) { FUNCTION f,*fp; int i,ret=1,tp,nl; if ((argc <= 0) || (argv[0] == NULL)) { ret=0; goto end; } f.name=argv[0]; fp=lh_FUNCTION_retrieve(prog,&f); if (fp == NULL) { if (EVP_get_digestbyname(argv[0])) { f.type = FUNC_TYPE_MD; f.func = dgst_main; fp = &f; } else if (EVP_get_cipherbyname(argv[0])) { f.type = FUNC_TYPE_CIPHER; f.func = enc_main; fp = &f; } } if (fp != NULL) { ret=fp->func(argc,argv); } else if ((strncmp(argv[0],"no-",3)) == 0) { BIO *bio_stdout = BIO_new_fp(stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); bio_stdout = BIO_push(tmpbio, bio_stdout); } #endif f.name=argv[0]+3; ret = (lh_FUNCTION_retrieve(prog,&f) != NULL); if (!ret) BIO_printf(bio_stdout, "%s\n", argv[0]); else BIO_printf(bio_stdout, "%s\n", argv[0]+3); BIO_free_all(bio_stdout); goto end; } else if ((strcmp(argv[0],"quit") == 0) || (strcmp(argv[0],"q") == 0) || (strcmp(argv[0],"exit") == 0) || (strcmp(argv[0],"bye") == 0)) { ret= -1; goto end; } else if ((strcmp(argv[0],LIST_STANDARD_COMMANDS) == 0) || (strcmp(argv[0],LIST_MESSAGE_DIGEST_COMMANDS) == 0) || (strcmp(argv[0],LIST_MESSAGE_DIGEST_ALGORITHMS) == 0) || (strcmp(argv[0],LIST_CIPHER_COMMANDS) == 0) || (strcmp(argv[0],LIST_CIPHER_ALGORITHMS) == 0) || (strcmp(argv[0],LIST_PUBLIC_KEY_ALGORITHMS) == 0)) { int list_type; BIO *bio_stdout; if (strcmp(argv[0],LIST_STANDARD_COMMANDS) == 0) list_type = FUNC_TYPE_GENERAL; else if (strcmp(argv[0],LIST_MESSAGE_DIGEST_COMMANDS) == 0) list_type = FUNC_TYPE_MD; else if (strcmp(argv[0],LIST_MESSAGE_DIGEST_ALGORITHMS) == 0) list_type = FUNC_TYPE_MD_ALG; else if (strcmp(argv[0],LIST_PUBLIC_KEY_ALGORITHMS) == 0) list_type = FUNC_TYPE_PKEY; else if (strcmp(argv[0],LIST_CIPHER_ALGORITHMS) == 0) list_type = FUNC_TYPE_CIPHER_ALG; else /* strcmp(argv[0],LIST_CIPHER_COMMANDS) == 0 */ list_type = FUNC_TYPE_CIPHER; bio_stdout = BIO_new_fp(stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); bio_stdout = BIO_push(tmpbio, bio_stdout); } #endif if (!load_config(bio_err, NULL)) goto end; if (list_type == FUNC_TYPE_PKEY) list_pkey(bio_stdout); if (list_type == FUNC_TYPE_MD_ALG) list_md(bio_stdout); if (list_type == FUNC_TYPE_CIPHER_ALG) list_cipher(bio_stdout); else { for (fp=functions; fp->name != NULL; fp++) if (fp->type == list_type) BIO_printf(bio_stdout, "%s\n", fp->name); } BIO_free_all(bio_stdout); ret=0; goto end; } else { BIO_printf(bio_err,"openssl:Error: '%s' is an invalid command.\n", argv[0]); BIO_printf(bio_err, "\nStandard commands"); i=0; tp=0; for (fp=functions; fp->name != NULL; fp++) { nl=0; #ifdef OPENSSL_NO_CAMELLIA if (((i++) % 5) == 0) #else if (((i++) % 4) == 0) #endif { BIO_printf(bio_err,"\n"); nl=1; } if (fp->type != tp) { tp=fp->type; if (!nl) BIO_printf(bio_err,"\n"); if (tp == FUNC_TYPE_MD) { i=1; BIO_printf(bio_err, "\nMessage Digest commands (see the `dgst' command for more details)\n"); } else if (tp == FUNC_TYPE_CIPHER) { i=1; BIO_printf(bio_err,"\nCipher commands (see the `enc' command for more details)\n"); } } #ifdef OPENSSL_NO_CAMELLIA BIO_printf(bio_err,"%-15s",fp->name); #else BIO_printf(bio_err,"%-18s",fp->name); #endif } BIO_printf(bio_err,"\n\n"); ret=0; } end: return(ret); } static int SortFnByName(const void *_f1,const void *_f2) { const FUNCTION *f1=_f1; const FUNCTION *f2=_f2; if(f1->type != f2->type) return f1->type-f2->type; return strcmp(f1->name,f2->name); } static void list_pkey(BIO *out) { int i; for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { const EVP_PKEY_ASN1_METHOD *ameth; int pkey_id, pkey_base_id, pkey_flags; const char *pinfo, *pem_str; ameth = EVP_PKEY_asn1_get0(i); EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags, &pinfo, &pem_str, ameth); if (pkey_flags & ASN1_PKEY_ALIAS) { BIO_printf(out, "Name: %s\n", OBJ_nid2ln(pkey_id)); BIO_printf(out, "\tType: Alias to %s\n", OBJ_nid2ln(pkey_base_id)); } else { BIO_printf(out, "Name: %s\n", pinfo); BIO_printf(out, "\tType: %s Algorithm\n", pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); BIO_printf(out, "\tOID: %s\n", OBJ_nid2ln(pkey_id)); if (pem_str == NULL) pem_str = "(none)"; BIO_printf(out, "\tPEM string: %s\n", pem_str); } } } static void list_cipher_fn(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { if (c) BIO_printf(arg, "%s\n", EVP_CIPHER_name(c)); else { if (!from) from = "<undefined>"; if (!to) to = "<undefined>"; BIO_printf(arg, "%s => %s\n", from, to); } } static void list_cipher(BIO *out) { EVP_CIPHER_do_all_sorted(list_cipher_fn, out); } static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg) { if (m) BIO_printf(arg, "%s\n", EVP_MD_name(m)); else { if (!from) from = "<undefined>"; if (!to) to = "<undefined>"; BIO_printf(arg, "%s => %s\n", from, to); } } static void list_md(BIO *out) { EVP_MD_do_all_sorted(list_md_fn, out); } static int MS_CALLBACK function_cmp(const FUNCTION *a, const FUNCTION *b) { return strncmp(a->name,b->name,8); } static IMPLEMENT_LHASH_COMP_FN(function, FUNCTION) static unsigned long MS_CALLBACK function_hash(const FUNCTION *a) { return lh_strhash(a->name); } static IMPLEMENT_LHASH_HASH_FN(function, FUNCTION) static LHASH_OF(FUNCTION) *prog_init(void) { LHASH_OF(FUNCTION) *ret; FUNCTION *f; size_t i; /* Purely so it looks nice when the user hits ? */ for(i=0,f=functions ; f->name != NULL ; ++f,++i) ; qsort(functions,i,sizeof *functions,SortFnByName); if ((ret=lh_FUNCTION_new()) == NULL) return(NULL); for (f=functions; f->name != NULL; f++) (void)lh_FUNCTION_insert(ret,f); return(ret); }
gpl-3.0
AdmiralCurtiss/pcsx2
3rdparty/wxwidgets3.0/src/generic/mask.cpp
122
2117
/////////////////////////////////////////////////////////////////////////////// // Name: src/generic/mask.cpp // Purpose: generic wxMask implementation // Author: Vadim Zeitlin // Created: 2006-09-28 // Copyright: (c) 2006 Vadim Zeitlin <vadim@wxwindows.org> // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/bitmap.h" #include "wx/image.h" #endif // WX_PRECOMP #if wxUSE_GENERIC_MASK // ============================================================================ // wxMask implementation // ============================================================================ IMPLEMENT_DYNAMIC_CLASS(wxMask, wxObject) void wxMask::FreeData() { m_bitmap = wxNullBitmap; } bool wxMask::InitFromColour(const wxBitmap& bitmap, const wxColour& colour) { #if wxUSE_IMAGE const wxColour clr(bitmap.QuantizeColour(colour)); wxImage imgSrc(bitmap.ConvertToImage()); imgSrc.SetMask(false); wxImage image(imgSrc.ConvertToMono(clr.Red(), clr.Green(), clr.Blue())); if ( !image.IsOk() ) return false; m_bitmap = wxBitmap(image, 1); return m_bitmap.IsOk(); #else // !wxUSE_IMAGE wxUnusedVar(bitmap); wxUnusedVar(colour); return false; #endif // wxUSE_IMAGE/!wxUSE_IMAGE } bool wxMask::InitFromMonoBitmap(const wxBitmap& bitmap) { wxCHECK_MSG( bitmap.IsOk(), false, wxT("Invalid bitmap") ); wxCHECK_MSG( bitmap.GetDepth() == 1, false, wxT("Cannot create mask from colour bitmap") ); m_bitmap = bitmap; return true; } #endif // wxUSE_GENERIC_MASK
gpl-3.0
VenJie/linux_2.6.36
fs/jffs2/fs.c
128
19780
/* * JFFS2 -- Journalling Flash File System, Version 2. * * Copyright © 2001-2007 Red Hat, Inc. * Copyright © 2004-2010 David Woodhouse <dwmw2@infradead.org> * * Created by David Woodhouse <dwmw2@infradead.org> * * For licensing information, see the file 'LICENCE' in this directory. * */ #include <linux/capability.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/list.h> #include <linux/mtd/mtd.h> #include <linux/pagemap.h> #include <linux/slab.h> #include <linux/vmalloc.h> #include <linux/vfs.h> #include <linux/crc32.h> #include <linux/smp_lock.h> #include "nodelist.h" static int jffs2_flash_setup(struct jffs2_sb_info *c); int jffs2_do_setattr (struct inode *inode, struct iattr *iattr) { struct jffs2_full_dnode *old_metadata, *new_metadata; struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_raw_inode *ri; union jffs2_device_node dev; unsigned char *mdata = NULL; int mdatalen = 0; unsigned int ivalid; uint32_t alloclen; int ret; int alloc_type = ALLOC_NORMAL; D1(printk(KERN_DEBUG "jffs2_setattr(): ino #%lu\n", inode->i_ino)); /* Special cases - we don't want more than one data node for these types on the medium at any time. So setattr must read the original data associated with the node (i.e. the device numbers or the target name) and write it out again with the appropriate data attached */ if (S_ISBLK(inode->i_mode) || S_ISCHR(inode->i_mode)) { /* For these, we don't actually need to read the old node */ mdatalen = jffs2_encode_dev(&dev, inode->i_rdev); mdata = (char *)&dev; D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of kdev_t\n", mdatalen)); } else if (S_ISLNK(inode->i_mode)) { mutex_lock(&f->sem); mdatalen = f->metadata->size; mdata = kmalloc(f->metadata->size, GFP_USER); if (!mdata) { mutex_unlock(&f->sem); return -ENOMEM; } ret = jffs2_read_dnode(c, f, f->metadata, mdata, 0, mdatalen); if (ret) { mutex_unlock(&f->sem); kfree(mdata); return ret; } mutex_unlock(&f->sem); D1(printk(KERN_DEBUG "jffs2_setattr(): Writing %d bytes of symlink target\n", mdatalen)); } ri = jffs2_alloc_raw_inode(); if (!ri) { if (S_ISLNK(inode->i_mode)) kfree(mdata); return -ENOMEM; } ret = jffs2_reserve_space(c, sizeof(*ri) + mdatalen, &alloclen, ALLOC_NORMAL, JFFS2_SUMMARY_INODE_SIZE); if (ret) { jffs2_free_raw_inode(ri); if (S_ISLNK(inode->i_mode & S_IFMT)) kfree(mdata); return ret; } mutex_lock(&f->sem); ivalid = iattr->ia_valid; ri->magic = cpu_to_je16(JFFS2_MAGIC_BITMASK); ri->nodetype = cpu_to_je16(JFFS2_NODETYPE_INODE); ri->totlen = cpu_to_je32(sizeof(*ri) + mdatalen); ri->hdr_crc = cpu_to_je32(crc32(0, ri, sizeof(struct jffs2_unknown_node)-4)); ri->ino = cpu_to_je32(inode->i_ino); ri->version = cpu_to_je32(++f->highest_version); ri->uid = cpu_to_je16((ivalid & ATTR_UID)?iattr->ia_uid:inode->i_uid); ri->gid = cpu_to_je16((ivalid & ATTR_GID)?iattr->ia_gid:inode->i_gid); if (ivalid & ATTR_MODE) ri->mode = cpu_to_jemode(iattr->ia_mode); else ri->mode = cpu_to_jemode(inode->i_mode); ri->isize = cpu_to_je32((ivalid & ATTR_SIZE)?iattr->ia_size:inode->i_size); ri->atime = cpu_to_je32(I_SEC((ivalid & ATTR_ATIME)?iattr->ia_atime:inode->i_atime)); ri->mtime = cpu_to_je32(I_SEC((ivalid & ATTR_MTIME)?iattr->ia_mtime:inode->i_mtime)); ri->ctime = cpu_to_je32(I_SEC((ivalid & ATTR_CTIME)?iattr->ia_ctime:inode->i_ctime)); ri->offset = cpu_to_je32(0); ri->csize = ri->dsize = cpu_to_je32(mdatalen); ri->compr = JFFS2_COMPR_NONE; if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { /* It's an extension. Make it a hole node */ ri->compr = JFFS2_COMPR_ZERO; ri->dsize = cpu_to_je32(iattr->ia_size - inode->i_size); ri->offset = cpu_to_je32(inode->i_size); } else if (ivalid & ATTR_SIZE && !iattr->ia_size) { /* For truncate-to-zero, treat it as deletion because it'll always be obsoleting all previous nodes */ alloc_type = ALLOC_DELETION; } ri->node_crc = cpu_to_je32(crc32(0, ri, sizeof(*ri)-8)); if (mdatalen) ri->data_crc = cpu_to_je32(crc32(0, mdata, mdatalen)); else ri->data_crc = cpu_to_je32(0); new_metadata = jffs2_write_dnode(c, f, ri, mdata, mdatalen, alloc_type); if (S_ISLNK(inode->i_mode)) kfree(mdata); if (IS_ERR(new_metadata)) { jffs2_complete_reservation(c); jffs2_free_raw_inode(ri); mutex_unlock(&f->sem); return PTR_ERR(new_metadata); } /* It worked. Update the inode */ inode->i_atime = ITIME(je32_to_cpu(ri->atime)); inode->i_ctime = ITIME(je32_to_cpu(ri->ctime)); inode->i_mtime = ITIME(je32_to_cpu(ri->mtime)); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_uid = je16_to_cpu(ri->uid); inode->i_gid = je16_to_cpu(ri->gid); old_metadata = f->metadata; if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) jffs2_truncate_fragtree (c, &f->fragtree, iattr->ia_size); if (ivalid & ATTR_SIZE && inode->i_size < iattr->ia_size) { jffs2_add_full_dnode_to_inode(c, f, new_metadata); inode->i_size = iattr->ia_size; inode->i_blocks = (inode->i_size + 511) >> 9; f->metadata = NULL; } else { f->metadata = new_metadata; } if (old_metadata) { jffs2_mark_node_obsolete(c, old_metadata->raw); jffs2_free_full_dnode(old_metadata); } jffs2_free_raw_inode(ri); mutex_unlock(&f->sem); jffs2_complete_reservation(c); /* We have to do the truncate_setsize() without f->sem held, since some pages may be locked and waiting for it in readpage(). We are protected from a simultaneous write() extending i_size back past iattr->ia_size, because do_truncate() holds the generic inode semaphore. */ if (ivalid & ATTR_SIZE && inode->i_size > iattr->ia_size) { truncate_setsize(inode, iattr->ia_size); inode->i_blocks = (inode->i_size + 511) >> 9; } return 0; } int jffs2_setattr(struct dentry *dentry, struct iattr *iattr) { int rc; rc = inode_change_ok(dentry->d_inode, iattr); if (rc) return rc; rc = jffs2_do_setattr(dentry->d_inode, iattr); if (!rc && (iattr->ia_valid & ATTR_MODE)) rc = jffs2_acl_chmod(dentry->d_inode); return rc; } int jffs2_statfs(struct dentry *dentry, struct kstatfs *buf) { struct jffs2_sb_info *c = JFFS2_SB_INFO(dentry->d_sb); unsigned long avail; buf->f_type = JFFS2_SUPER_MAGIC; buf->f_bsize = 1 << PAGE_SHIFT; buf->f_blocks = c->flash_size >> PAGE_SHIFT; buf->f_files = 0; buf->f_ffree = 0; buf->f_namelen = JFFS2_MAX_NAME_LEN; buf->f_fsid.val[0] = JFFS2_SUPER_MAGIC; buf->f_fsid.val[1] = c->mtd->index; spin_lock(&c->erase_completion_lock); avail = c->dirty_size + c->free_size; if (avail > c->sector_size * c->resv_blocks_write) avail -= c->sector_size * c->resv_blocks_write; else avail = 0; spin_unlock(&c->erase_completion_lock); buf->f_bavail = buf->f_bfree = avail >> PAGE_SHIFT; return 0; } void jffs2_evict_inode (struct inode *inode) { /* We can forget about this inode for now - drop all * the nodelists associated with it, etc. */ struct jffs2_sb_info *c = JFFS2_SB_INFO(inode->i_sb); struct jffs2_inode_info *f = JFFS2_INODE_INFO(inode); D1(printk(KERN_DEBUG "jffs2_evict_inode(): ino #%lu mode %o\n", inode->i_ino, inode->i_mode)); truncate_inode_pages(&inode->i_data, 0); end_writeback(inode); jffs2_do_clear_inode(c, f); } struct inode *jffs2_iget(struct super_block *sb, unsigned long ino) { struct jffs2_inode_info *f; struct jffs2_sb_info *c; struct jffs2_raw_inode latest_node; union jffs2_device_node jdev; struct inode *inode; dev_t rdev = 0; int ret; D1(printk(KERN_DEBUG "jffs2_iget(): ino == %lu\n", ino)); inode = iget_locked(sb, ino); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; f = JFFS2_INODE_INFO(inode); c = JFFS2_SB_INFO(inode->i_sb); jffs2_init_inode_info(f); mutex_lock(&f->sem); ret = jffs2_do_read_inode(c, f, inode->i_ino, &latest_node); if (ret) { mutex_unlock(&f->sem); iget_failed(inode); return ERR_PTR(ret); } inode->i_mode = jemode_to_cpu(latest_node.mode); inode->i_uid = je16_to_cpu(latest_node.uid); inode->i_gid = je16_to_cpu(latest_node.gid); inode->i_size = je32_to_cpu(latest_node.isize); inode->i_atime = ITIME(je32_to_cpu(latest_node.atime)); inode->i_mtime = ITIME(je32_to_cpu(latest_node.mtime)); inode->i_ctime = ITIME(je32_to_cpu(latest_node.ctime)); inode->i_nlink = f->inocache->pino_nlink; inode->i_blocks = (inode->i_size + 511) >> 9; switch (inode->i_mode & S_IFMT) { case S_IFLNK: inode->i_op = &jffs2_symlink_inode_operations; break; case S_IFDIR: { struct jffs2_full_dirent *fd; inode->i_nlink = 2; /* parent and '.' */ for (fd=f->dents; fd; fd = fd->next) { if (fd->type == DT_DIR && fd->ino) inc_nlink(inode); } /* Root dir gets i_nlink 3 for some reason */ if (inode->i_ino == 1) inc_nlink(inode); inode->i_op = &jffs2_dir_inode_operations; inode->i_fop = &jffs2_dir_operations; break; } case S_IFREG: inode->i_op = &jffs2_file_inode_operations; inode->i_fop = &jffs2_file_operations; inode->i_mapping->a_ops = &jffs2_file_address_operations; inode->i_mapping->nrpages = 0; break; case S_IFBLK: case S_IFCHR: /* Read the device numbers from the media */ if (f->metadata->size != sizeof(jdev.old_id) && f->metadata->size != sizeof(jdev.new_id)) { printk(KERN_NOTICE "Device node has strange size %d\n", f->metadata->size); goto error_io; } D1(printk(KERN_DEBUG "Reading device numbers from flash\n")); ret = jffs2_read_dnode(c, f, f->metadata, (char *)&jdev, 0, f->metadata->size); if (ret < 0) { /* Eep */ printk(KERN_NOTICE "Read device numbers for inode %lu failed\n", (unsigned long)inode->i_ino); goto error; } if (f->metadata->size == sizeof(jdev.old_id)) rdev = old_decode_dev(je16_to_cpu(jdev.old_id)); else rdev = new_decode_dev(je32_to_cpu(jdev.new_id)); case S_IFSOCK: case S_IFIFO: inode->i_op = &jffs2_file_inode_operations; init_special_inode(inode, inode->i_mode, rdev); break; default: printk(KERN_WARNING "jffs2_read_inode(): Bogus imode %o for ino %lu\n", inode->i_mode, (unsigned long)inode->i_ino); } mutex_unlock(&f->sem); D1(printk(KERN_DEBUG "jffs2_read_inode() returning\n")); unlock_new_inode(inode); return inode; error_io: ret = -EIO; error: mutex_unlock(&f->sem); jffs2_do_clear_inode(c, f); iget_failed(inode); return ERR_PTR(ret); } void jffs2_dirty_inode(struct inode *inode) { struct iattr iattr; if (!(inode->i_state & I_DIRTY_DATASYNC)) { D2(printk(KERN_DEBUG "jffs2_dirty_inode() not calling setattr() for ino #%lu\n", inode->i_ino)); return; } D1(printk(KERN_DEBUG "jffs2_dirty_inode() calling setattr() for ino #%lu\n", inode->i_ino)); iattr.ia_valid = ATTR_MODE|ATTR_UID|ATTR_GID|ATTR_ATIME|ATTR_MTIME|ATTR_CTIME; iattr.ia_mode = inode->i_mode; iattr.ia_uid = inode->i_uid; iattr.ia_gid = inode->i_gid; iattr.ia_atime = inode->i_atime; iattr.ia_mtime = inode->i_mtime; iattr.ia_ctime = inode->i_ctime; jffs2_do_setattr(inode, &iattr); } int jffs2_remount_fs (struct super_block *sb, int *flags, char *data) { struct jffs2_sb_info *c = JFFS2_SB_INFO(sb); if (c->flags & JFFS2_SB_FLAG_RO && !(sb->s_flags & MS_RDONLY)) return -EROFS; /* We stop if it was running, then restart if it needs to. This also catches the case where it was stopped and this is just a remount to restart it. Flush the writebuffer, if neccecary, else we loose it */ lock_kernel(); if (!(sb->s_flags & MS_RDONLY)) { jffs2_stop_garbage_collect_thread(c); mutex_lock(&c->alloc_sem); jffs2_flush_wbuf_pad(c); mutex_unlock(&c->alloc_sem); } if (!(*flags & MS_RDONLY)) jffs2_start_garbage_collect_thread(c); *flags |= MS_NOATIME; unlock_kernel(); return 0; } /* jffs2_new_inode: allocate a new inode and inocache, add it to the hash, fill in the raw_inode while you're at it. */ struct inode *jffs2_new_inode (struct inode *dir_i, int mode, struct jffs2_raw_inode *ri) { struct inode *inode; struct super_block *sb = dir_i->i_sb; struct jffs2_sb_info *c; struct jffs2_inode_info *f; int ret; D1(printk(KERN_DEBUG "jffs2_new_inode(): dir_i %ld, mode 0x%x\n", dir_i->i_ino, mode)); c = JFFS2_SB_INFO(sb); inode = new_inode(sb); if (!inode) return ERR_PTR(-ENOMEM); f = JFFS2_INODE_INFO(inode); jffs2_init_inode_info(f); mutex_lock(&f->sem); memset(ri, 0, sizeof(*ri)); /* Set OS-specific defaults for new inodes */ ri->uid = cpu_to_je16(current_fsuid()); if (dir_i->i_mode & S_ISGID) { ri->gid = cpu_to_je16(dir_i->i_gid); if (S_ISDIR(mode)) mode |= S_ISGID; } else { ri->gid = cpu_to_je16(current_fsgid()); } /* POSIX ACLs have to be processed now, at least partly. The umask is only applied if there's no default ACL */ ret = jffs2_init_acl_pre(dir_i, inode, &mode); if (ret) { make_bad_inode(inode); iput(inode); return ERR_PTR(ret); } ret = jffs2_do_new_inode (c, f, mode, ri); if (ret) { make_bad_inode(inode); iput(inode); return ERR_PTR(ret); } inode->i_nlink = 1; inode->i_ino = je32_to_cpu(ri->ino); inode->i_mode = jemode_to_cpu(ri->mode); inode->i_gid = je16_to_cpu(ri->gid); inode->i_uid = je16_to_cpu(ri->uid); inode->i_atime = inode->i_ctime = inode->i_mtime = CURRENT_TIME_SEC; ri->atime = ri->mtime = ri->ctime = cpu_to_je32(I_SEC(inode->i_mtime)); inode->i_blocks = 0; inode->i_size = 0; if (insert_inode_locked(inode) < 0) { make_bad_inode(inode); unlock_new_inode(inode); iput(inode); return ERR_PTR(-EINVAL); } return inode; } int jffs2_do_fill_super(struct super_block *sb, void *data, int silent) { struct jffs2_sb_info *c; struct inode *root_i; int ret; size_t blocks; c = JFFS2_SB_INFO(sb); #ifndef CONFIG_JFFS2_FS_WRITEBUFFER if (c->mtd->type == MTD_NANDFLASH) { printk(KERN_ERR "jffs2: Cannot operate on NAND flash unless jffs2 NAND support is compiled in.\n"); return -EINVAL; } if (c->mtd->type == MTD_DATAFLASH) { printk(KERN_ERR "jffs2: Cannot operate on DataFlash unless jffs2 DataFlash support is compiled in.\n"); return -EINVAL; } #endif c->flash_size = c->mtd->size; c->sector_size = c->mtd->erasesize; blocks = c->flash_size / c->sector_size; /* * Size alignment check */ if ((c->sector_size * blocks) != c->flash_size) { c->flash_size = c->sector_size * blocks; printk(KERN_INFO "jffs2: Flash size not aligned to erasesize, reducing to %dKiB\n", c->flash_size / 1024); } if (c->flash_size < 5*c->sector_size) { printk(KERN_ERR "jffs2: Too few erase blocks (%d)\n", c->flash_size / c->sector_size); return -EINVAL; } c->cleanmarker_size = sizeof(struct jffs2_unknown_node); /* NAND (or other bizarre) flash... do setup accordingly */ ret = jffs2_flash_setup(c); if (ret) return ret; c->inocache_list = kcalloc(INOCACHE_HASHSIZE, sizeof(struct jffs2_inode_cache *), GFP_KERNEL); if (!c->inocache_list) { ret = -ENOMEM; goto out_wbuf; } jffs2_init_xattr_subsystem(c); if ((ret = jffs2_do_mount_fs(c))) goto out_inohash; D1(printk(KERN_DEBUG "jffs2_do_fill_super(): Getting root inode\n")); root_i = jffs2_iget(sb, 1); if (IS_ERR(root_i)) { D1(printk(KERN_WARNING "get root inode failed\n")); ret = PTR_ERR(root_i); goto out_root; } ret = -ENOMEM; D1(printk(KERN_DEBUG "jffs2_do_fill_super(): d_alloc_root()\n")); sb->s_root = d_alloc_root(root_i); if (!sb->s_root) goto out_root_i; sb->s_maxbytes = 0xFFFFFFFF; sb->s_blocksize = PAGE_CACHE_SIZE; sb->s_blocksize_bits = PAGE_CACHE_SHIFT; sb->s_magic = JFFS2_SUPER_MAGIC; if (!(sb->s_flags & MS_RDONLY)) jffs2_start_garbage_collect_thread(c); return 0; out_root_i: iput(root_i); out_root: jffs2_free_ino_caches(c); jffs2_free_raw_node_refs(c); if (jffs2_blocks_use_vmalloc(c)) vfree(c->blocks); else kfree(c->blocks); out_inohash: jffs2_clear_xattr_subsystem(c); kfree(c->inocache_list); out_wbuf: jffs2_flash_cleanup(c); return ret; } void jffs2_gc_release_inode(struct jffs2_sb_info *c, struct jffs2_inode_info *f) { iput(OFNI_EDONI_2SFFJ(f)); } struct jffs2_inode_info *jffs2_gc_fetch_inode(struct jffs2_sb_info *c, int inum, int unlinked) { struct inode *inode; struct jffs2_inode_cache *ic; if (unlinked) { /* The inode has zero nlink but its nodes weren't yet marked obsolete. This has to be because we're still waiting for the final (close() and) iput() to happen. There's a possibility that the final iput() could have happened while we were contemplating. In order to ensure that we don't cause a new read_inode() (which would fail) for the inode in question, we use ilookup() in this case instead of iget(). The nlink can't _become_ zero at this point because we're holding the alloc_sem, and jffs2_do_unlink() would also need that while decrementing nlink on any inode. */ inode = ilookup(OFNI_BS_2SFFJ(c), inum); if (!inode) { D1(printk(KERN_DEBUG "ilookup() failed for ino #%u; inode is probably deleted.\n", inum)); spin_lock(&c->inocache_lock); ic = jffs2_get_ino_cache(c, inum); if (!ic) { D1(printk(KERN_DEBUG "Inode cache for ino #%u is gone.\n", inum)); spin_unlock(&c->inocache_lock); return NULL; } if (ic->state != INO_STATE_CHECKEDABSENT) { /* Wait for progress. Don't just loop */ D1(printk(KERN_DEBUG "Waiting for ino #%u in state %d\n", ic->ino, ic->state)); sleep_on_spinunlock(&c->inocache_wq, &c->inocache_lock); } else { spin_unlock(&c->inocache_lock); } return NULL; } } else { /* Inode has links to it still; they're not going away because jffs2_do_unlink() would need the alloc_sem and we have it. Just iget() it, and if read_inode() is necessary that's OK. */ inode = jffs2_iget(OFNI_BS_2SFFJ(c), inum); if (IS_ERR(inode)) return ERR_CAST(inode); } if (is_bad_inode(inode)) { printk(KERN_NOTICE "Eep. read_inode() failed for ino #%u. unlinked %d\n", inum, unlinked); /* NB. This will happen again. We need to do something appropriate here. */ iput(inode); return ERR_PTR(-EIO); } return JFFS2_INODE_INFO(inode); } unsigned char *jffs2_gc_fetch_page(struct jffs2_sb_info *c, struct jffs2_inode_info *f, unsigned long offset, unsigned long *priv) { struct inode *inode = OFNI_EDONI_2SFFJ(f); struct page *pg; pg = read_cache_page_async(inode->i_mapping, offset >> PAGE_CACHE_SHIFT, (void *)jffs2_do_readpage_unlock, inode); if (IS_ERR(pg)) return (void *)pg; *priv = (unsigned long)pg; return kmap(pg); } void jffs2_gc_release_page(struct jffs2_sb_info *c, unsigned char *ptr, unsigned long *priv) { struct page *pg = (void *)*priv; kunmap(pg); page_cache_release(pg); } static int jffs2_flash_setup(struct jffs2_sb_info *c) { int ret = 0; if (jffs2_cleanmarker_oob(c)) { /* NAND flash... do setup accordingly */ ret = jffs2_nand_flash_setup(c); if (ret) return ret; } /* and Dataflash */ if (jffs2_dataflash(c)) { ret = jffs2_dataflash_setup(c); if (ret) return ret; } /* and Intel "Sibley" flash */ if (jffs2_nor_wbuf_flash(c)) { ret = jffs2_nor_wbuf_flash_setup(c); if (ret) return ret; } /* and an UBI volume */ if (jffs2_ubivol(c)) { ret = jffs2_ubivol_setup(c); if (ret) return ret; } return ret; } void jffs2_flash_cleanup(struct jffs2_sb_info *c) { if (jffs2_cleanmarker_oob(c)) { jffs2_nand_flash_cleanup(c); } /* and DataFlash */ if (jffs2_dataflash(c)) { jffs2_dataflash_cleanup(c); } /* and Intel "Sibley" flash */ if (jffs2_nor_wbuf_flash(c)) { jffs2_nor_wbuf_flash_cleanup(c); } /* and an UBI volume */ if (jffs2_ubivol(c)) { jffs2_ubivol_cleanup(c); } }
gpl-3.0
box25/Marlin-Firmware
ArduinoAddons/Arduino_0.xx/Gen7/cores/arduino/wiring_digital.c
137
2870
/* wiring_digital.c - digital input and output functions Part of Arduino - http://www.arduino.cc/ Copyright (c) 2005-2006 David A. Mellis 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $ */ #include "wiring_private.h" #include "pins_arduino.h" void pinMode(uint8_t pin, uint8_t mode) { uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *reg; if (port == NOT_A_PIN) return; // JWS: can I let the optimizer do this? reg = portModeRegister(port); if (mode == INPUT) *reg &= ~bit; else *reg |= bit; } // Forcing this inline keeps the callers from having to push their own stuff // on the stack. It is a good performance win and only takes 1 more byte per // user than calling. (It will take more bytes on the 168.) // // But shouldn't this be moved into pinMode? Seems silly to check and do on // each digitalread or write. // static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline)); static inline void turnOffPWM(uint8_t timer) { if (timer == TIMER0A) cbi(TCCR0A, COM0A1); if (timer == TIMER0B) cbi(TCCR0A, COM0B1); if (timer == TIMER1A) cbi(TCCR1A, COM1A1); if (timer == TIMER1B) cbi(TCCR1A, COM1B1); if (timer == TIMER2A) cbi(TCCR2A, COM2A1); if (timer == TIMER2B) cbi(TCCR2A, COM2B1); } void digitalWrite(uint8_t pin, uint8_t val) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); volatile uint8_t *out; if (port == NOT_A_PIN) return; // If the pin that support PWM output, we need to turn it off // before doing a digital write. if (timer != NOT_ON_TIMER) turnOffPWM(timer); out = portOutputRegister(port); if (val == LOW) *out &= ~bit; else *out |= bit; } int digitalRead(uint8_t pin) { uint8_t timer = digitalPinToTimer(pin); uint8_t bit = digitalPinToBitMask(pin); uint8_t port = digitalPinToPort(pin); if (port == NOT_A_PIN) return LOW; // If the pin that support PWM output, we need to turn it off // before getting a digital reading. if (timer != NOT_ON_TIMER) turnOffPWM(timer); if (*portInputRegister(port) & bit) return HIGH; return LOW; }
gpl-3.0
stranostrano/android_kernel_oppo_msm8974
drivers/staging/speakup/serialio.c
4241
5229
#include <linux/interrupt.h> #include <linux/ioport.h> #include "spk_types.h" #include "speakup.h" #include "spk_priv.h" #include "serialio.h" static void start_serial_interrupt(int irq); static const struct old_serial_port rs_table[] = { SERIAL_PORT_DFNS }; static const struct old_serial_port *serstate; static int timeouts; const struct old_serial_port *spk_serial_init(int index) { int baud = 9600, quot = 0; unsigned int cval = 0; int cflag = CREAD | HUPCL | CLOCAL | B9600 | CS8; const struct old_serial_port *ser = rs_table + index; int err; /* Divisor, bytesize and parity */ quot = ser->baud_base / baud; cval = cflag & (CSIZE | CSTOPB); #if defined(__powerpc__) || defined(__alpha__) cval >>= 8; #else /* !__powerpc__ && !__alpha__ */ cval >>= 4; #endif /* !__powerpc__ && !__alpha__ */ if (cflag & PARENB) cval |= UART_LCR_PARITY; if (!(cflag & PARODD)) cval |= UART_LCR_EPAR; if (synth_request_region(ser->port, 8)) { /* try to take it back. */ printk(KERN_INFO "Ports not available, trying to steal them\n"); __release_region(&ioport_resource, ser->port, 8); err = synth_request_region(ser->port, 8); if (err) { pr_warn("Unable to allocate port at %x, errno %i", ser->port, err); return NULL; } } /* Disable UART interrupts, set DTR and RTS high * and set speed. */ outb(cval | UART_LCR_DLAB, ser->port + UART_LCR); /* set DLAB */ outb(quot & 0xff, ser->port + UART_DLL); /* LS of divisor */ outb(quot >> 8, ser->port + UART_DLM); /* MS of divisor */ outb(cval, ser->port + UART_LCR); /* reset DLAB */ /* Turn off Interrupts */ outb(0, ser->port + UART_IER); outb(UART_MCR_DTR | UART_MCR_RTS, ser->port + UART_MCR); /* If we read 0xff from the LSR, there is no UART here. */ if (inb(ser->port + UART_LSR) == 0xff) { synth_release_region(ser->port, 8); serstate = NULL; return NULL; } mdelay(1); speakup_info.port_tts = ser->port; serstate = ser; start_serial_interrupt(ser->irq); return ser; } static irqreturn_t synth_readbuf_handler(int irq, void *dev_id) { unsigned long flags; /*printk(KERN_ERR "in irq\n"); */ /*pr_warn("in IRQ\n"); */ int c; spk_lock(flags); while (inb_p(speakup_info.port_tts + UART_LSR) & UART_LSR_DR) { c = inb_p(speakup_info.port_tts+UART_RX); synth->read_buff_add((u_char) c); /*printk(KERN_ERR "c = %d\n", c); */ /*pr_warn("C = %d\n", c); */ } spk_unlock(flags); return IRQ_HANDLED; } static void start_serial_interrupt(int irq) { int rv; if (synth->read_buff_add == NULL) return; rv = request_irq(irq, synth_readbuf_handler, IRQF_SHARED, "serial", (void *) synth_readbuf_handler); if (rv) printk(KERN_ERR "Unable to request Speakup serial I R Q\n"); /* Set MCR */ outb(UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2, speakup_info.port_tts + UART_MCR); /* Turn on Interrupts */ outb(UART_IER_MSI|UART_IER_RLSI|UART_IER_RDI, speakup_info.port_tts + UART_IER); inb(speakup_info.port_tts+UART_LSR); inb(speakup_info.port_tts+UART_RX); inb(speakup_info.port_tts+UART_IIR); inb(speakup_info.port_tts+UART_MSR); outb(1, speakup_info.port_tts + UART_FCR); /* Turn FIFO On */ } void stop_serial_interrupt(void) { if (speakup_info.port_tts == 0) return; if (synth->read_buff_add == NULL) return; /* Turn off interrupts */ outb(0, speakup_info.port_tts+UART_IER); /* Free IRQ */ free_irq(serstate->irq, (void *) synth_readbuf_handler); } int wait_for_xmitr(void) { int tmout = SPK_XMITR_TIMEOUT; if ((synth->alive) && (timeouts >= NUM_DISABLE_TIMEOUTS)) { pr_warn("%s: too many timeouts, deactivating speakup\n", synth->long_name); synth->alive = 0; /* No synth any more, so nobody will restart TTYs, and we thus * need to do it ourselves. Now that there is no synth we can * let application flood anyway */ speakup_start_ttys(); timeouts = 0; return 0; } while (spk_serial_tx_busy()) { if (--tmout == 0) { pr_warn("%s: timed out (tx busy)\n", synth->long_name); timeouts++; return 0; } udelay(1); } tmout = SPK_CTS_TIMEOUT; while (!((inb_p(speakup_info.port_tts + UART_MSR)) & UART_MSR_CTS)) { /* CTS */ if (--tmout == 0) { /* pr_warn("%s: timed out (cts)\n", * synth->long_name); */ timeouts++; return 0; } udelay(1); } timeouts = 0; return 1; } unsigned char spk_serial_in(void) { int tmout = SPK_SERIAL_TIMEOUT; while (!(inb_p(speakup_info.port_tts + UART_LSR) & UART_LSR_DR)) { if (--tmout == 0) { pr_warn("time out while waiting for input.\n"); return 0xff; } udelay(1); } return inb_p(speakup_info.port_tts + UART_RX); } EXPORT_SYMBOL_GPL(spk_serial_in); unsigned char spk_serial_in_nowait(void) { unsigned char lsr; lsr = inb_p(speakup_info.port_tts + UART_LSR); if (!(lsr & UART_LSR_DR)) return 0; return inb_p(speakup_info.port_tts + UART_RX); } EXPORT_SYMBOL_GPL(spk_serial_in_nowait); int spk_serial_out(const char ch) { if (synth->alive && wait_for_xmitr()) { outb_p(ch, speakup_info.port_tts); return 1; } return 0; } EXPORT_SYMBOL_GPL(spk_serial_out); void spk_serial_release(void) { if (speakup_info.port_tts == 0) return; synth_release_region(speakup_info.port_tts, 8); speakup_info.port_tts = 0; } EXPORT_SYMBOL_GPL(spk_serial_release);
gpl-3.0
Limseunghwan/test
ArduinoAddons/Arduino_1.5.x/hardware/marlin/avr/libraries/U8glib/utility/u8g_dev_st7687_c144mvgd.c
412
13975
/* u8g_dev_st7687_c144mvgd.c (1.44" TFT) Status: Started, but not finished Universal 8bit Graphics Library Copyright (c) 2012, olikraus@gmail.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "u8g.h" #define WIDTH 128 #define HEIGHT 128 #define PAGE_HEIGHT 8 #ifdef FIRST_VERSION /* see also: read.pudn.com/downloads115/sourcecode/app/484503/LCM_Display.c__.htm http://en.pudn.com/downloads115/sourcecode/app/detail484503_en.html */ static const uint8_t u8g_dev_st7687_c144mvgd_init_seq[] PROGMEM = { U8G_ESC_CS(0), /* disable chip */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ U8G_ESC_RST(15), /* do reset low pulse with (15*16)+2 milliseconds (=maximum delay)*/ 0x001, /* A0=0, SW reset */ U8G_ESC_DLY(200), /* delay 200 ms */ 0x0d7, /* EEPROM data auto re-load control */ U8G_ESC_ADR(1), /* data mode */ 0x09f, /* ARD = 1 */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_DLY(100), /* delay 100 ms */ 0x0e0, /* EEPROM control in */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_DLY(100), /* delay 100 ms */ #ifdef NOT_REQUIRED 0x0fa, /* EEPROM function selection 8.1.66 */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_DLY(100), /* delay 100 ms */ #endif 0x0e3, /* Read from EEPROM, 8.1.55 */ U8G_ESC_DLY(100), /* delay 100 ms */ 0x0e1, /* EEPROM control out, 8.1.53 */ U8G_ESC_DLY(100), /* delay 100 ms */ //0x028, /* display off */ 0x011, /* Sleep out & booster on */ U8G_ESC_DLY(100), /* delay 100 ms */ 0x0c0, /* Vop setting, 8.1.42 */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* */ 0x001, /* 3.6 + 256*0.04 = 13.84 Volt */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_DLY(100), /* delay 100 ms */ 0x0c3, /* Bias selection, 8.1.45 */ U8G_ESC_ADR(1), /* data mode */ 0x003, U8G_ESC_ADR(0), /* instruction mode */ 0x0c4, /* Booster setting 8.1.46 */ U8G_ESC_ADR(1), /* data mode */ 0x007, U8G_ESC_ADR(0), /* instruction mode */ 0x0c5, /* ??? */ U8G_ESC_ADR(1), /* data mode */ 0x001, U8G_ESC_ADR(0), /* instruction mode */ 0x0cb, /* FV3 with Booster x2 control, 8.1.47 */ U8G_ESC_ADR(1), /* data mode */ 0x001, U8G_ESC_ADR(0), /* instruction mode */ 0x036, /* Memory data access control, 8.1.28 */ U8G_ESC_ADR(1), /* data mode */ 0x080, U8G_ESC_ADR(0), /* instruction mode */ 0x0b5, /* N-line control, 8.1.37 */ U8G_ESC_ADR(1), /* data mode */ 0x089, U8G_ESC_ADR(0), /* instruction mode */ 0x0d0, /* Analog circuit setting, 8.1.49 */ U8G_ESC_ADR(1), /* data mode */ 0x01d, U8G_ESC_ADR(0), /* instruction mode */ 0x0b7, /* Com/Seg Scan Direction, 8.1.38 */ U8G_ESC_ADR(1), /* data mode */ 0x040, U8G_ESC_ADR(0), /* instruction mode */ 0x025, /* Write contrast, 8.1.17 */ U8G_ESC_ADR(1), /* data mode */ 0x03f, U8G_ESC_ADR(0), /* instruction mode */ 0x03a, /* Interface pixel format, 8.1.32 */ U8G_ESC_ADR(1), /* data mode */ 0x004, /* 3: 12 bit per pixel Type A, 4: 12 bit Type B, 5: 16bit per pixel */ U8G_ESC_ADR(0), /* instruction mode */ 0x0b0, /* Display Duty setting, 8.1.34 */ U8G_ESC_ADR(1), /* data mode */ 0x07f, U8G_ESC_ADR(0), /* instruction mode */ 0x0f0, /* Frame Freq. in Temp range A,B,C and D, 8.1.59 */ U8G_ESC_ADR(1), /* data mode */ 0x007, 0x00c, 0x00c, 0x015, U8G_ESC_ADR(0), /* instruction mode */ 0x0f9, /* Frame RGB Value, 8.1.65 */ U8G_ESC_ADR(1), /* data mode */ 0x000, 0x005, 0x008, 0x00a, 0x00c, 0x00e, 0x010, 0x011, 0x012, 0x013, 0x014, 0x015, 0x016, 0x018, 0x01a, 0x01b, U8G_ESC_ADR(0), /* instruction mode */ 0x0f9, /* Frame RGB Value, 8.1.65 */ U8G_ESC_ADR(1), /* data mode */ 0x000, 0x000, 0x000, 0x000, 0x033, 0x055, 0x055, 0x055, U8G_ESC_ADR(0), /* instruction mode */ 0x029, /* display on */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_END /* end of sequence */ }; #else /* http://www.waitingforfriday.com/images/e/e3/FTM144D01N_test.zip */ static const uint8_t u8g_dev_st7687_c144mvgd_init_seq[] PROGMEM = { U8G_ESC_CS(0), /* disable chip */ U8G_ESC_ADR(0), /* instruction mode */ U8G_ESC_CS(1), /* enable chip */ U8G_ESC_RST(15), /* do reset low pulse with (15*16)+2 milliseconds (=maximum delay)*/ 0x011, /* Sleep out & booster on */ U8G_ESC_DLY(5), /* delay 5 ms */ 0x03a, /* Interface pixel format, 8.1.32 */ U8G_ESC_ADR(1), /* data mode */ 0x004, /* 3: 12 bit per pixel Type A, 4: 12 bit Type B, 5: 16bit per pixel */ U8G_ESC_ADR(0), /* instruction mode */ 0x026, /* SET_GAMMA_CURVE */ U8G_ESC_ADR(1), /* data mode */ 0x004, U8G_ESC_ADR(0), /* instruction mode */ 0x0f2, /* GAM_R_SEL */ U8G_ESC_ADR(1), /* data mode */ 0x001, /* enable gamma adj */ U8G_ESC_ADR(0), /* instruction mode */ 0x0e0, /* POSITIVE_GAMMA_CORRECT */ U8G_ESC_ADR(1), /* data mode */ 0x3f, 0x25, 0x1c, 0x1e, 0x20, 0x12, 0x2a, 0x90, 0x24, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, U8G_ESC_ADR(0), /* instruction mode */ 0x0e1, /* NEGATIVE_GAMMA_CORRECT */ U8G_ESC_ADR(1), /* data mode */ 0x20, 0x20, 0x20, 0x20, 0x05, 0x00, 0x15, 0xa7, 0x3d, 0x18, 0x25, 0x2a, 0x2b, 0x2b, 0x3a, U8G_ESC_ADR(0), /* instruction mode */ 0x0b1, /* FRAME_RATE_CONTROL1 */ U8G_ESC_ADR(1), /* data mode */ 0x008, /* DIVA = 8 */ 0x008, /* VPA = 8 */ U8G_ESC_ADR(0), /* instruction mode */ 0x0b4, /* DISPLAY_INVERSION */ U8G_ESC_ADR(1), /* data mode */ 0x007, /* NLA = 1, NLB = 1, NLC = 1 (all on Frame Inversion) */ U8G_ESC_ADR(0), /* instruction mode */ 0x0c0, /* POWER_CONTROL1 */ U8G_ESC_ADR(1), /* data mode */ 0x00a, /* VRH = 10: GVDD = 4.30 */ 0x002, /* VC = 2: VCI1 = 2.65 */ U8G_ESC_ADR(0), /* instruction mode */ 0x0c1, /* POWER_CONTROL2 */ U8G_ESC_ADR(1), /* data mode */ 0x002, /* BT = 2: AVDD = 2xVCI1, VCL = -1xVCI1, VGH = 5xVCI1, VGL = -2xVCI1 */ U8G_ESC_ADR(0), /* instruction mode */ 0x0c5, /* VCOM_CONTROL1 */ U8G_ESC_ADR(1), /* data mode */ 0x050, /* VMH = 80: VCOMH voltage = 4.5 */ 0x05b, /* VML = 91: VCOML voltage = -0.225 */ U8G_ESC_ADR(0), /* instruction mode */ 0x0c7, /* VCOM_OFFSET_CONTROL */ U8G_ESC_ADR(1), /* data mode */ 0x040, /* nVM = 0, VMF = 64: VCOMH output = VMH, VCOML output = VML */ U8G_ESC_ADR(0), /* instruction mode */ 0x02a, /* SET_COLUMN_ADDRESS */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* */ 0x000, /* */ 0x000, /* */ 0x07f, /* */ U8G_ESC_ADR(0), /* instruction mode */ 0x02b, /* SET_PAGE_ADDRESS */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* */ 0x000, /* */ 0x000, /* */ 0x07f, /* */ U8G_ESC_ADR(0), /* instruction mode */ 0x036, /* SET_ADDRESS_MODE */ U8G_ESC_ADR(1), /* data mode */ 0x000, /* Select display orientation */ U8G_ESC_ADR(0), /* instruction mode */ 0x029, /* display on */ 0x02c, /* write start */ U8G_ESC_CS(0), /* disable chip */ U8G_ESC_END /* end of sequence */ }; #endif /* calculate bytes for Type B 4096 color display */ static uint8_t get_byte_1(uint8_t v) { v >>= 4; v &= 0x0e; return v; } static uint8_t get_byte_2(uint8_t v) { uint8_t w; w = v; w &= 3; w = (w<<2) | w; v <<= 3; v &= 0x0e0; w |= v; return w; } uint8_t u8g_dev_st7687_c144mvgd_fn(u8g_t *u8g, u8g_dev_t *dev, uint8_t msg, void *arg) { switch(msg) { case U8G_DEV_MSG_INIT: u8g_InitCom(u8g, dev); u8g_WriteEscSeqP(u8g, dev, u8g_dev_st7687_c144mvgd_init_seq); break; case U8G_DEV_MSG_STOP: break; case U8G_DEV_MSG_PAGE_NEXT: { uint8_t y, i, j; uint8_t *ptr; u8g_pb_t *pb = (u8g_pb_t *)(dev->dev_mem); u8g_SetAddress(u8g, dev, 0); /* cmd mode */ u8g_SetChipSelect(u8g, dev, 1); y = pb->p.page_y0; ptr = pb->buf; u8g_SetAddress(u8g, dev, 0); /* cmd mode */ u8g_WriteByte(u8g, dev, 0x02a ); /* Column address set 8.1.20 */ u8g_SetAddress(u8g, dev, 1); /* data mode */ u8g_WriteByte(u8g, dev, 0x000 ); /* x0 */ u8g_WriteByte(u8g, dev, WIDTH-1 ); /* x1 */ u8g_SetAddress(u8g, dev, 0); /* cmd mode */ u8g_WriteByte(u8g, dev, 0x02b ); /* Row address set 8.1.21 */ u8g_SetAddress(u8g, dev, 1); /* data mode */ u8g_WriteByte(u8g, dev, y ); /* y0 */ u8g_WriteByte(u8g, dev, y+PAGE_HEIGHT-1 ); /* y1 */ u8g_SetAddress(u8g, dev, 0); /* cmd mode */ u8g_WriteByte(u8g, dev, 0x02c ); /* Memory write 8.1.22 */ u8g_SetAddress(u8g, dev, 1); /* data mode */ for( i = 0; i < PAGE_HEIGHT; i ++ ) { for( j = 0; j < WIDTH; j ++ ) { u8g_WriteByte(u8g, dev, get_byte_1(*ptr) ); u8g_WriteByte(u8g, dev, get_byte_2(*ptr) ); ptr++; } } u8g_SetAddress(u8g, dev, 0); /* cmd mode */ u8g_SetChipSelect(u8g, dev, 0); } break; } return u8g_dev_pb8h8_base_fn(u8g, dev, msg, arg); } uint8_t u8g_st7687_c144mvgd_8h8_buf[WIDTH*8] U8G_NOCOMMON ; u8g_pb_t u8g_st7687_c144mvgd_8h8_pb = { {8, HEIGHT, 0, 0, 0}, WIDTH, u8g_st7687_c144mvgd_8h8_buf}; u8g_dev_t u8g_dev_st7687_c144mvgd_sw_spi = { u8g_dev_st7687_c144mvgd_fn, &u8g_st7687_c144mvgd_8h8_pb, u8g_com_arduino_sw_spi_fn }; u8g_dev_t u8g_dev_st7687_c144mvgd_8bit = { u8g_dev_st7687_c144mvgd_fn, &u8g_st7687_c144mvgd_8h8_pb, U8G_COM_PARALLEL };
gpl-3.0
eabatalov/au-linux-kernel-autumn-2017
linux/drivers/media/i2c/lm3560.c
423
12451
/* * drivers/media/i2c/lm3560.c * General device driver for TI lm3560, FLASH LED Driver * * Copyright (C) 2013 Texas Instruments * * Contact: Daniel Jeong <gshark.jeong@gmail.com> * Ldd-Mlp <ldd-mlp@list.ti.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <linux/delay.h> #include <linux/module.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/mutex.h> #include <linux/regmap.h> #include <linux/videodev2.h> #include <media/i2c/lm3560.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> /* registers definitions */ #define REG_ENABLE 0x10 #define REG_TORCH_BR 0xa0 #define REG_FLASH_BR 0xb0 #define REG_FLASH_TOUT 0xc0 #define REG_FLAG 0xd0 #define REG_CONFIG1 0xe0 /* fault mask */ #define FAULT_TIMEOUT (1<<0) #define FAULT_OVERTEMP (1<<1) #define FAULT_SHORT_CIRCUIT (1<<2) enum led_enable { MODE_SHDN = 0x0, MODE_TORCH = 0x2, MODE_FLASH = 0x3, }; /** * struct lm3560_flash * * @pdata: platform data * @regmap: reg. map for i2c * @lock: muxtex for serial access. * @led_mode: V4L2 LED mode * @ctrls_led: V4L2 contols * @subdev_led: V4L2 subdev */ struct lm3560_flash { struct device *dev; struct lm3560_platform_data *pdata; struct regmap *regmap; struct mutex lock; enum v4l2_flash_led_mode led_mode; struct v4l2_ctrl_handler ctrls_led[LM3560_LED_MAX]; struct v4l2_subdev subdev_led[LM3560_LED_MAX]; }; #define to_lm3560_flash(_ctrl, _no) \ container_of(_ctrl->handler, struct lm3560_flash, ctrls_led[_no]) /* enable mode control */ static int lm3560_mode_ctrl(struct lm3560_flash *flash) { int rval = -EINVAL; switch (flash->led_mode) { case V4L2_FLASH_LED_MODE_NONE: rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x03, MODE_SHDN); break; case V4L2_FLASH_LED_MODE_TORCH: rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x03, MODE_TORCH); break; case V4L2_FLASH_LED_MODE_FLASH: rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x03, MODE_FLASH); break; } return rval; } /* led1/2 enable/disable */ static int lm3560_enable_ctrl(struct lm3560_flash *flash, enum lm3560_led_id led_no, bool on) { int rval; if (led_no == LM3560_LED0) { if (on) rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x08, 0x08); else rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x08, 0x00); } else { if (on) rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x10, 0x10); else rval = regmap_update_bits(flash->regmap, REG_ENABLE, 0x10, 0x00); } return rval; } /* torch1/2 brightness control */ static int lm3560_torch_brt_ctrl(struct lm3560_flash *flash, enum lm3560_led_id led_no, unsigned int brt) { int rval; u8 br_bits; if (brt < LM3560_TORCH_BRT_MIN) return lm3560_enable_ctrl(flash, led_no, false); else rval = lm3560_enable_ctrl(flash, led_no, true); br_bits = LM3560_TORCH_BRT_uA_TO_REG(brt); if (led_no == LM3560_LED0) rval = regmap_update_bits(flash->regmap, REG_TORCH_BR, 0x07, br_bits); else rval = regmap_update_bits(flash->regmap, REG_TORCH_BR, 0x38, br_bits << 3); return rval; } /* flash1/2 brightness control */ static int lm3560_flash_brt_ctrl(struct lm3560_flash *flash, enum lm3560_led_id led_no, unsigned int brt) { int rval; u8 br_bits; if (brt < LM3560_FLASH_BRT_MIN) return lm3560_enable_ctrl(flash, led_no, false); else rval = lm3560_enable_ctrl(flash, led_no, true); br_bits = LM3560_FLASH_BRT_uA_TO_REG(brt); if (led_no == LM3560_LED0) rval = regmap_update_bits(flash->regmap, REG_FLASH_BR, 0x0f, br_bits); else rval = regmap_update_bits(flash->regmap, REG_FLASH_BR, 0xf0, br_bits << 4); return rval; } /* v4l2 controls */ static int lm3560_get_ctrl(struct v4l2_ctrl *ctrl, enum lm3560_led_id led_no) { struct lm3560_flash *flash = to_lm3560_flash(ctrl, led_no); int rval = -EINVAL; mutex_lock(&flash->lock); if (ctrl->id == V4L2_CID_FLASH_FAULT) { s32 fault = 0; unsigned int reg_val; rval = regmap_read(flash->regmap, REG_FLAG, &reg_val); if (rval < 0) goto out; if (reg_val & FAULT_SHORT_CIRCUIT) fault |= V4L2_FLASH_FAULT_SHORT_CIRCUIT; if (reg_val & FAULT_OVERTEMP) fault |= V4L2_FLASH_FAULT_OVER_TEMPERATURE; if (reg_val & FAULT_TIMEOUT) fault |= V4L2_FLASH_FAULT_TIMEOUT; ctrl->cur.val = fault; } out: mutex_unlock(&flash->lock); return rval; } static int lm3560_set_ctrl(struct v4l2_ctrl *ctrl, enum lm3560_led_id led_no) { struct lm3560_flash *flash = to_lm3560_flash(ctrl, led_no); u8 tout_bits; int rval = -EINVAL; mutex_lock(&flash->lock); switch (ctrl->id) { case V4L2_CID_FLASH_LED_MODE: flash->led_mode = ctrl->val; if (flash->led_mode != V4L2_FLASH_LED_MODE_FLASH) rval = lm3560_mode_ctrl(flash); break; case V4L2_CID_FLASH_STROBE_SOURCE: rval = regmap_update_bits(flash->regmap, REG_CONFIG1, 0x04, (ctrl->val) << 2); if (rval < 0) goto err_out; break; case V4L2_CID_FLASH_STROBE: if (flash->led_mode != V4L2_FLASH_LED_MODE_FLASH) { rval = -EBUSY; goto err_out; } flash->led_mode = V4L2_FLASH_LED_MODE_FLASH; rval = lm3560_mode_ctrl(flash); break; case V4L2_CID_FLASH_STROBE_STOP: if (flash->led_mode != V4L2_FLASH_LED_MODE_FLASH) { rval = -EBUSY; goto err_out; } flash->led_mode = V4L2_FLASH_LED_MODE_NONE; rval = lm3560_mode_ctrl(flash); break; case V4L2_CID_FLASH_TIMEOUT: tout_bits = LM3560_FLASH_TOUT_ms_TO_REG(ctrl->val); rval = regmap_update_bits(flash->regmap, REG_FLASH_TOUT, 0x1f, tout_bits); break; case V4L2_CID_FLASH_INTENSITY: rval = lm3560_flash_brt_ctrl(flash, led_no, ctrl->val); break; case V4L2_CID_FLASH_TORCH_INTENSITY: rval = lm3560_torch_brt_ctrl(flash, led_no, ctrl->val); break; } err_out: mutex_unlock(&flash->lock); return rval; } static int lm3560_led1_get_ctrl(struct v4l2_ctrl *ctrl) { return lm3560_get_ctrl(ctrl, LM3560_LED1); } static int lm3560_led1_set_ctrl(struct v4l2_ctrl *ctrl) { return lm3560_set_ctrl(ctrl, LM3560_LED1); } static int lm3560_led0_get_ctrl(struct v4l2_ctrl *ctrl) { return lm3560_get_ctrl(ctrl, LM3560_LED0); } static int lm3560_led0_set_ctrl(struct v4l2_ctrl *ctrl) { return lm3560_set_ctrl(ctrl, LM3560_LED0); } static const struct v4l2_ctrl_ops lm3560_led_ctrl_ops[LM3560_LED_MAX] = { [LM3560_LED0] = { .g_volatile_ctrl = lm3560_led0_get_ctrl, .s_ctrl = lm3560_led0_set_ctrl, }, [LM3560_LED1] = { .g_volatile_ctrl = lm3560_led1_get_ctrl, .s_ctrl = lm3560_led1_set_ctrl, } }; static int lm3560_init_controls(struct lm3560_flash *flash, enum lm3560_led_id led_no) { struct v4l2_ctrl *fault; u32 max_flash_brt = flash->pdata->max_flash_brt[led_no]; u32 max_torch_brt = flash->pdata->max_torch_brt[led_no]; struct v4l2_ctrl_handler *hdl = &flash->ctrls_led[led_no]; const struct v4l2_ctrl_ops *ops = &lm3560_led_ctrl_ops[led_no]; v4l2_ctrl_handler_init(hdl, 8); /* flash mode */ v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_TORCH, ~0x7, V4L2_FLASH_LED_MODE_NONE); flash->led_mode = V4L2_FLASH_LED_MODE_NONE; /* flash source */ v4l2_ctrl_new_std_menu(hdl, ops, V4L2_CID_FLASH_STROBE_SOURCE, 0x1, ~0x3, V4L2_FLASH_STROBE_SOURCE_SOFTWARE); /* flash strobe */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_STROBE, 0, 0, 0, 0); /* flash strobe stop */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_STROBE_STOP, 0, 0, 0, 0); /* flash strobe timeout */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_TIMEOUT, LM3560_FLASH_TOUT_MIN, flash->pdata->max_flash_timeout, LM3560_FLASH_TOUT_STEP, flash->pdata->max_flash_timeout); /* flash brt */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_INTENSITY, LM3560_FLASH_BRT_MIN, max_flash_brt, LM3560_FLASH_BRT_STEP, max_flash_brt); /* torch brt */ v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_TORCH_INTENSITY, LM3560_TORCH_BRT_MIN, max_torch_brt, LM3560_TORCH_BRT_STEP, max_torch_brt); /* fault */ fault = v4l2_ctrl_new_std(hdl, ops, V4L2_CID_FLASH_FAULT, 0, V4L2_FLASH_FAULT_OVER_VOLTAGE | V4L2_FLASH_FAULT_OVER_TEMPERATURE | V4L2_FLASH_FAULT_SHORT_CIRCUIT | V4L2_FLASH_FAULT_TIMEOUT, 0, 0); if (fault != NULL) fault->flags |= V4L2_CTRL_FLAG_VOLATILE; if (hdl->error) return hdl->error; flash->subdev_led[led_no].ctrl_handler = hdl; return 0; } /* initialize device */ static const struct v4l2_subdev_ops lm3560_ops = { .core = NULL, }; static const struct regmap_config lm3560_regmap = { .reg_bits = 8, .val_bits = 8, .max_register = 0xFF, }; static int lm3560_subdev_init(struct lm3560_flash *flash, enum lm3560_led_id led_no, char *led_name) { struct i2c_client *client = to_i2c_client(flash->dev); int rval; v4l2_i2c_subdev_init(&flash->subdev_led[led_no], client, &lm3560_ops); flash->subdev_led[led_no].flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; strcpy(flash->subdev_led[led_no].name, led_name); rval = lm3560_init_controls(flash, led_no); if (rval) goto err_out; rval = media_entity_pads_init(&flash->subdev_led[led_no].entity, 0, NULL); if (rval < 0) goto err_out; flash->subdev_led[led_no].entity.function = MEDIA_ENT_F_FLASH; return rval; err_out: v4l2_ctrl_handler_free(&flash->ctrls_led[led_no]); return rval; } static int lm3560_init_device(struct lm3560_flash *flash) { int rval; unsigned int reg_val; /* set peak current */ rval = regmap_update_bits(flash->regmap, REG_FLASH_TOUT, 0x60, flash->pdata->peak); if (rval < 0) return rval; /* output disable */ flash->led_mode = V4L2_FLASH_LED_MODE_NONE; rval = lm3560_mode_ctrl(flash); if (rval < 0) return rval; /* reset faults */ rval = regmap_read(flash->regmap, REG_FLAG, &reg_val); return rval; } static int lm3560_probe(struct i2c_client *client, const struct i2c_device_id *devid) { struct lm3560_flash *flash; struct lm3560_platform_data *pdata = dev_get_platdata(&client->dev); int rval; flash = devm_kzalloc(&client->dev, sizeof(*flash), GFP_KERNEL); if (flash == NULL) return -ENOMEM; flash->regmap = devm_regmap_init_i2c(client, &lm3560_regmap); if (IS_ERR(flash->regmap)) { rval = PTR_ERR(flash->regmap); return rval; } /* if there is no platform data, use chip default value */ if (pdata == NULL) { pdata = devm_kzalloc(&client->dev, sizeof(*pdata), GFP_KERNEL); if (pdata == NULL) return -ENODEV; pdata->peak = LM3560_PEAK_3600mA; pdata->max_flash_timeout = LM3560_FLASH_TOUT_MAX; /* led 1 */ pdata->max_flash_brt[LM3560_LED0] = LM3560_FLASH_BRT_MAX; pdata->max_torch_brt[LM3560_LED0] = LM3560_TORCH_BRT_MAX; /* led 2 */ pdata->max_flash_brt[LM3560_LED1] = LM3560_FLASH_BRT_MAX; pdata->max_torch_brt[LM3560_LED1] = LM3560_TORCH_BRT_MAX; } flash->pdata = pdata; flash->dev = &client->dev; mutex_init(&flash->lock); rval = lm3560_subdev_init(flash, LM3560_LED0, "lm3560-led0"); if (rval < 0) return rval; rval = lm3560_subdev_init(flash, LM3560_LED1, "lm3560-led1"); if (rval < 0) return rval; rval = lm3560_init_device(flash); if (rval < 0) return rval; i2c_set_clientdata(client, flash); return 0; } static int lm3560_remove(struct i2c_client *client) { struct lm3560_flash *flash = i2c_get_clientdata(client); unsigned int i; for (i = LM3560_LED0; i < LM3560_LED_MAX; i++) { v4l2_device_unregister_subdev(&flash->subdev_led[i]); v4l2_ctrl_handler_free(&flash->ctrls_led[i]); media_entity_cleanup(&flash->subdev_led[i].entity); } return 0; } static const struct i2c_device_id lm3560_id_table[] = { {LM3560_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3560_id_table); static struct i2c_driver lm3560_i2c_driver = { .driver = { .name = LM3560_NAME, .pm = NULL, }, .probe = lm3560_probe, .remove = lm3560_remove, .id_table = lm3560_id_table, }; module_i2c_driver(lm3560_i2c_driver); MODULE_AUTHOR("Daniel Jeong <gshark.jeong@gmail.com>"); MODULE_AUTHOR("Ldd Mlp <ldd-mlp@list.ti.com>"); MODULE_DESCRIPTION("Texas Instruments LM3560 LED flash driver"); MODULE_LICENSE("GPL");
gpl-3.0
swathykrishnan001/owasp-igoat
lib/sqlcipher/ext/fts1/fts1.c
172
101910
/* fts1 has a design flaw which can lead to database corruption (see ** below). It is recommended not to use it any longer, instead use ** fts3 (or higher). If you believe that your use of fts1 is safe, ** add -DSQLITE_ENABLE_BROKEN_FTS1=1 to your CFLAGS. */ #if (!defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1)) \ && !defined(SQLITE_ENABLE_BROKEN_FTS1) #error fts1 has a design flaw and has been deprecated. #endif /* The flaw is that fts1 uses the content table's unaliased rowid as ** the unique docid. fts1 embeds the rowid in the index it builds, ** and expects the rowid to not change. The SQLite VACUUM operation ** will renumber such rowids, thereby breaking fts1. If you are using ** fts1 in a system which has disabled VACUUM, then you can continue ** to use it safely. Note that PRAGMA auto_vacuum does NOT disable ** VACUUM, though systems using auto_vacuum are unlikely to invoke ** VACUUM. ** ** fts1 should be safe even across VACUUM if you only insert documents ** and never delete. */ /* The author disclaims copyright to this source code. * * This is an SQLite module implementing full-text search. */ /* ** The code in this file is only compiled if: ** ** * The FTS1 module is being built as an extension ** (in which case SQLITE_CORE is not defined), or ** ** * The FTS1 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS1 is defined). */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) #if defined(SQLITE_ENABLE_FTS1) && !defined(SQLITE_CORE) # define SQLITE_CORE 1 #endif #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "fts1.h" #include "fts1_hash.h" #include "fts1_tokenizer.h" #include "sqlite3.h" #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #if 0 # define TRACE(A) printf A; fflush(stdout) #else # define TRACE(A) #endif /* utility functions */ typedef struct StringBuffer { int len; /* length, not including null terminator */ int alloced; /* Space allocated for s[] */ char *s; /* Content of the string */ } StringBuffer; static void initStringBuffer(StringBuffer *sb){ sb->len = 0; sb->alloced = 100; sb->s = malloc(100); sb->s[0] = '\0'; } static void nappend(StringBuffer *sb, const char *zFrom, int nFrom){ if( sb->len + nFrom >= sb->alloced ){ sb->alloced = sb->len + nFrom + 100; sb->s = realloc(sb->s, sb->alloced+1); if( sb->s==0 ){ initStringBuffer(sb); return; } } memcpy(sb->s + sb->len, zFrom, nFrom); sb->len += nFrom; sb->s[sb->len] = 0; } static void append(StringBuffer *sb, const char *zFrom){ nappend(sb, zFrom, strlen(zFrom)); } /* We encode variable-length integers in little-endian order using seven bits * per byte as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit ** ** 7 bits - A ** 14 bits - BA ** 21 bits - BBA ** and so on. */ /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */ #define VARINT_MAX 10 /* Write a 64-bit variable-length integer to memory starting at p[0]. * The length of data written will be between 1 and VARINT_MAX bytes. * The number of bytes written is returned. */ static int putVarint(char *p, sqlite_int64 v){ unsigned char *q = (unsigned char *) p; sqlite_uint64 vu = v; do{ *q++ = (unsigned char) ((vu & 0x7f) | 0x80); vu >>= 7; }while( vu!=0 ); q[-1] &= 0x7f; /* turn off high bit in final byte */ assert( q - (unsigned char *)p <= VARINT_MAX ); return (int) (q - (unsigned char *)p); } /* Read a 64-bit variable-length integer from memory starting at p[0]. * Return the number of bytes read, or 0 on error. * The value is stored in *v. */ static int getVarint(const char *p, sqlite_int64 *v){ const unsigned char *q = (const unsigned char *) p; sqlite_uint64 x = 0, y = 1; while( (*q & 0x80) == 0x80 ){ x += y * (*q++ & 0x7f); y <<= 7; if( q - (unsigned char *)p >= VARINT_MAX ){ /* bad data */ assert( 0 ); return 0; } } x += y * (*q++); *v = (sqlite_int64) x; return (int) (q - (unsigned char *)p); } static int getVarint32(const char *p, int *pi){ sqlite_int64 i; int ret = getVarint(p, &i); *pi = (int) i; assert( *pi==i ); return ret; } /*** Document lists *** * * A document list holds a sorted list of varint-encoded document IDs. * * A doclist with type DL_POSITIONS_OFFSETS is stored like this: * * array { * varint docid; * array { * varint position; (delta from previous position plus POS_BASE) * varint startOffset; (delta from previous startOffset) * varint endOffset; (delta from startOffset) * } * } * * Here, array { X } means zero or more occurrences of X, adjacent in memory. * * A position list may hold positions for text in multiple columns. A position * POS_COLUMN is followed by a varint containing the index of the column for * following positions in the list. Any positions appearing before any * occurrences of POS_COLUMN are for column 0. * * A doclist with type DL_POSITIONS is like the above, but holds only docids * and positions without offset information. * * A doclist with type DL_DOCIDS is like the above, but holds only docids * without positions or offset information. * * On disk, every document list has positions and offsets, so we don't bother * to serialize a doclist's type. * * We don't yet delta-encode document IDs; doing so will probably be a * modest win. * * NOTE(shess) I've thought of a slightly (1%) better offset encoding. * After the first offset, estimate the next offset by using the * current token position and the previous token position and offset, * offset to handle some variance. So the estimate would be * (iPosition*w->iStartOffset/w->iPosition-64), which is delta-encoded * as normal. Offsets more than 64 chars from the estimate are * encoded as the delta to the previous start offset + 128. An * additional tiny increment can be gained by using the end offset of * the previous token to make the estimate a tiny bit more precise. */ /* It is not safe to call isspace(), tolower(), or isalnum() on ** hi-bit-set characters. This is the same solution used in the ** tokenizer. */ /* TODO(shess) The snippet-generation code should be using the ** tokenizer-generated tokens rather than doing its own local ** tokenization. */ /* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */ static int safe_isspace(char c){ return (c&0x80)==0 ? isspace(c) : 0; } static int safe_tolower(char c){ return (c&0x80)==0 ? tolower(c) : c; } static int safe_isalnum(char c){ return (c&0x80)==0 ? isalnum(c) : 0; } typedef enum DocListType { DL_DOCIDS, /* docids only */ DL_POSITIONS, /* docids + positions */ DL_POSITIONS_OFFSETS /* docids + positions + offsets */ } DocListType; /* ** By default, only positions and not offsets are stored in the doclists. ** To change this so that offsets are stored too, compile with ** ** -DDL_DEFAULT=DL_POSITIONS_OFFSETS ** */ #ifndef DL_DEFAULT # define DL_DEFAULT DL_POSITIONS #endif typedef struct DocList { char *pData; int nData; DocListType iType; int iLastColumn; /* the last column written */ int iLastPos; /* the last position written */ int iLastOffset; /* the last start offset written */ } DocList; enum { POS_END = 0, /* end of this position list */ POS_COLUMN, /* followed by new column number */ POS_BASE }; /* Initialize a new DocList to hold the given data. */ static void docListInit(DocList *d, DocListType iType, const char *pData, int nData){ d->nData = nData; if( nData>0 ){ d->pData = malloc(nData); memcpy(d->pData, pData, nData); } else { d->pData = NULL; } d->iType = iType; d->iLastColumn = 0; d->iLastPos = d->iLastOffset = 0; } /* Create a new dynamically-allocated DocList. */ static DocList *docListNew(DocListType iType){ DocList *d = (DocList *) malloc(sizeof(DocList)); docListInit(d, iType, 0, 0); return d; } static void docListDestroy(DocList *d){ free(d->pData); #ifndef NDEBUG memset(d, 0x55, sizeof(*d)); #endif } static void docListDelete(DocList *d){ docListDestroy(d); free(d); } static char *docListEnd(DocList *d){ return d->pData + d->nData; } /* Append a varint to a DocList's data. */ static void appendVarint(DocList *d, sqlite_int64 i){ char c[VARINT_MAX]; int n = putVarint(c, i); d->pData = realloc(d->pData, d->nData + n); memcpy(d->pData + d->nData, c, n); d->nData += n; } static void docListAddDocid(DocList *d, sqlite_int64 iDocid){ appendVarint(d, iDocid); if( d->iType>=DL_POSITIONS ){ appendVarint(d, POS_END); /* initially empty position list */ d->iLastColumn = 0; d->iLastPos = d->iLastOffset = 0; } } /* helper function for docListAddPos and docListAddPosOffset */ static void addPos(DocList *d, int iColumn, int iPos){ assert( d->nData>0 ); --d->nData; /* remove previous terminator */ if( iColumn!=d->iLastColumn ){ assert( iColumn>d->iLastColumn ); appendVarint(d, POS_COLUMN); appendVarint(d, iColumn); d->iLastColumn = iColumn; d->iLastPos = d->iLastOffset = 0; } assert( iPos>=d->iLastPos ); appendVarint(d, iPos-d->iLastPos+POS_BASE); d->iLastPos = iPos; } /* Add a position to the last position list in a doclist. */ static void docListAddPos(DocList *d, int iColumn, int iPos){ assert( d->iType==DL_POSITIONS ); addPos(d, iColumn, iPos); appendVarint(d, POS_END); /* add new terminator */ } /* ** Add a position and starting and ending offsets to a doclist. ** ** If the doclist is setup to handle only positions, then insert ** the position only and ignore the offsets. */ static void docListAddPosOffset( DocList *d, /* Doclist under construction */ int iColumn, /* Column the inserted term is part of */ int iPos, /* Position of the inserted term */ int iStartOffset, /* Starting offset of inserted term */ int iEndOffset /* Ending offset of inserted term */ ){ assert( d->iType>=DL_POSITIONS ); addPos(d, iColumn, iPos); if( d->iType==DL_POSITIONS_OFFSETS ){ assert( iStartOffset>=d->iLastOffset ); appendVarint(d, iStartOffset-d->iLastOffset); d->iLastOffset = iStartOffset; assert( iEndOffset>=iStartOffset ); appendVarint(d, iEndOffset-iStartOffset); } appendVarint(d, POS_END); /* add new terminator */ } /* ** A DocListReader object is a cursor into a doclist. Initialize ** the cursor to the beginning of the doclist by calling readerInit(). ** Then use routines ** ** peekDocid() ** readDocid() ** readPosition() ** skipPositionList() ** and so forth... ** ** to read information out of the doclist. When we reach the end ** of the doclist, atEnd() returns TRUE. */ typedef struct DocListReader { DocList *pDoclist; /* The document list we are stepping through */ char *p; /* Pointer to next unread byte in the doclist */ int iLastColumn; int iLastPos; /* the last position read, or -1 when not in a position list */ } DocListReader; /* ** Initialize the DocListReader r to point to the beginning of pDoclist. */ static void readerInit(DocListReader *r, DocList *pDoclist){ r->pDoclist = pDoclist; if( pDoclist!=NULL ){ r->p = pDoclist->pData; } r->iLastColumn = -1; r->iLastPos = -1; } /* ** Return TRUE if we have reached then end of pReader and there is ** nothing else left to read. */ static int atEnd(DocListReader *pReader){ return pReader->pDoclist==0 || (pReader->p >= docListEnd(pReader->pDoclist)); } /* Peek at the next docid without advancing the read pointer. */ static sqlite_int64 peekDocid(DocListReader *pReader){ sqlite_int64 ret; assert( !atEnd(pReader) ); assert( pReader->iLastPos==-1 ); getVarint(pReader->p, &ret); return ret; } /* Read the next docid. See also nextDocid(). */ static sqlite_int64 readDocid(DocListReader *pReader){ sqlite_int64 ret; assert( !atEnd(pReader) ); assert( pReader->iLastPos==-1 ); pReader->p += getVarint(pReader->p, &ret); if( pReader->pDoclist->iType>=DL_POSITIONS ){ pReader->iLastColumn = 0; pReader->iLastPos = 0; } return ret; } /* Read the next position and column index from a position list. * Returns the position, or -1 at the end of the list. */ static int readPosition(DocListReader *pReader, int *iColumn){ int i; int iType = pReader->pDoclist->iType; if( pReader->iLastPos==-1 ){ return -1; } assert( !atEnd(pReader) ); if( iType<DL_POSITIONS ){ return -1; } pReader->p += getVarint32(pReader->p, &i); if( i==POS_END ){ pReader->iLastColumn = pReader->iLastPos = -1; *iColumn = -1; return -1; } if( i==POS_COLUMN ){ pReader->p += getVarint32(pReader->p, &pReader->iLastColumn); pReader->iLastPos = 0; pReader->p += getVarint32(pReader->p, &i); assert( i>=POS_BASE ); } pReader->iLastPos += ((int) i)-POS_BASE; if( iType>=DL_POSITIONS_OFFSETS ){ /* Skip over offsets, ignoring them for now. */ int iStart, iEnd; pReader->p += getVarint32(pReader->p, &iStart); pReader->p += getVarint32(pReader->p, &iEnd); } *iColumn = pReader->iLastColumn; return pReader->iLastPos; } /* Skip past the end of a position list. */ static void skipPositionList(DocListReader *pReader){ DocList *p = pReader->pDoclist; if( p && p->iType>=DL_POSITIONS ){ int iColumn; while( readPosition(pReader, &iColumn)!=-1 ){} } } /* Skip over a docid, including its position list if the doclist has * positions. */ static void skipDocument(DocListReader *pReader){ readDocid(pReader); skipPositionList(pReader); } /* Skip past all docids which are less than [iDocid]. Returns 1 if a docid * matching [iDocid] was found. */ static int skipToDocid(DocListReader *pReader, sqlite_int64 iDocid){ sqlite_int64 d = 0; while( !atEnd(pReader) && (d=peekDocid(pReader))<iDocid ){ skipDocument(pReader); } return !atEnd(pReader) && d==iDocid; } /* Return the first document in a document list. */ static sqlite_int64 firstDocid(DocList *d){ DocListReader r; readerInit(&r, d); return readDocid(&r); } #ifdef SQLITE_DEBUG /* ** This routine is used for debugging purpose only. ** ** Write the content of a doclist to standard output. */ static void printDoclist(DocList *p){ DocListReader r; const char *zSep = ""; readerInit(&r, p); while( !atEnd(&r) ){ sqlite_int64 docid = readDocid(&r); if( docid==0 ){ skipPositionList(&r); continue; } printf("%s%lld", zSep, docid); zSep = ","; if( p->iType>=DL_POSITIONS ){ int iPos, iCol; const char *zDiv = ""; printf("("); while( (iPos = readPosition(&r, &iCol))>=0 ){ printf("%s%d:%d", zDiv, iCol, iPos); zDiv = ":"; } printf(")"); } } printf("\n"); fflush(stdout); } #endif /* SQLITE_DEBUG */ /* Trim the given doclist to contain only positions in column * [iRestrictColumn]. */ static void docListRestrictColumn(DocList *in, int iRestrictColumn){ DocListReader r; DocList out; assert( in->iType>=DL_POSITIONS ); readerInit(&r, in); docListInit(&out, DL_POSITIONS, NULL, 0); while( !atEnd(&r) ){ sqlite_int64 iDocid = readDocid(&r); int iPos, iColumn; docListAddDocid(&out, iDocid); while( (iPos = readPosition(&r, &iColumn)) != -1 ){ if( iColumn==iRestrictColumn ){ docListAddPos(&out, iColumn, iPos); } } } docListDestroy(in); *in = out; } /* Trim the given doclist by discarding any docids without any remaining * positions. */ static void docListDiscardEmpty(DocList *in) { DocListReader r; DocList out; /* TODO: It would be nice to implement this operation in place; that * could save a significant amount of memory in queries with long doclists. */ assert( in->iType>=DL_POSITIONS ); readerInit(&r, in); docListInit(&out, DL_POSITIONS, NULL, 0); while( !atEnd(&r) ){ sqlite_int64 iDocid = readDocid(&r); int match = 0; int iPos, iColumn; while( (iPos = readPosition(&r, &iColumn)) != -1 ){ if( !match ){ docListAddDocid(&out, iDocid); match = 1; } docListAddPos(&out, iColumn, iPos); } } docListDestroy(in); *in = out; } /* Helper function for docListUpdate() and docListAccumulate(). ** Splices a doclist element into the doclist represented by r, ** leaving r pointing after the newly spliced element. */ static void docListSpliceElement(DocListReader *r, sqlite_int64 iDocid, const char *pSource, int nSource){ DocList *d = r->pDoclist; char *pTarget; int nTarget, found; found = skipToDocid(r, iDocid); /* Describe slice in d to place pSource/nSource. */ pTarget = r->p; if( found ){ skipDocument(r); nTarget = r->p-pTarget; }else{ nTarget = 0; } /* The sense of the following is that there are three possibilities. ** If nTarget==nSource, we should not move any memory nor realloc. ** If nTarget>nSource, trim target and realloc. ** If nTarget<nSource, realloc then expand target. */ if( nTarget>nSource ){ memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget)); } if( nTarget!=nSource ){ int iDoclist = pTarget-d->pData; d->pData = realloc(d->pData, d->nData+nSource-nTarget); pTarget = d->pData+iDoclist; } if( nTarget<nSource ){ memmove(pTarget+nSource, pTarget+nTarget, docListEnd(d)-(pTarget+nTarget)); } memcpy(pTarget, pSource, nSource); d->nData += nSource-nTarget; r->p = pTarget+nSource; } /* Insert/update pUpdate into the doclist. */ static void docListUpdate(DocList *d, DocList *pUpdate){ DocListReader reader; assert( d!=NULL && pUpdate!=NULL ); assert( d->iType==pUpdate->iType); readerInit(&reader, d); docListSpliceElement(&reader, firstDocid(pUpdate), pUpdate->pData, pUpdate->nData); } /* Propagate elements from pUpdate to pAcc, overwriting elements with ** matching docids. */ static void docListAccumulate(DocList *pAcc, DocList *pUpdate){ DocListReader accReader, updateReader; /* Handle edge cases where one doclist is empty. */ assert( pAcc!=NULL ); if( pUpdate==NULL || pUpdate->nData==0 ) return; if( pAcc->nData==0 ){ pAcc->pData = malloc(pUpdate->nData); memcpy(pAcc->pData, pUpdate->pData, pUpdate->nData); pAcc->nData = pUpdate->nData; return; } readerInit(&accReader, pAcc); readerInit(&updateReader, pUpdate); while( !atEnd(&updateReader) ){ char *pSource = updateReader.p; sqlite_int64 iDocid = readDocid(&updateReader); skipPositionList(&updateReader); docListSpliceElement(&accReader, iDocid, pSource, updateReader.p-pSource); } } /* ** Read the next docid off of pIn. Return 0 if we reach the end. * * TODO: This assumes that docids are never 0, but they may actually be 0 since * users can choose docids when inserting into a full-text table. Fix this. */ static sqlite_int64 nextDocid(DocListReader *pIn){ skipPositionList(pIn); return atEnd(pIn) ? 0 : readDocid(pIn); } /* ** pLeft and pRight are two DocListReaders that are pointing to ** positions lists of the same document: iDocid. ** ** If there are no instances in pLeft or pRight where the position ** of pLeft is one less than the position of pRight, then this ** routine adds nothing to pOut. ** ** If there are one or more instances where positions from pLeft ** are exactly one less than positions from pRight, then add a new ** document record to pOut. If pOut wants to hold positions, then ** include the positions from pRight that are one more than a ** position in pLeft. In other words: pRight.iPos==pLeft.iPos+1. ** ** pLeft and pRight are left pointing at the next document record. */ static void mergePosList( DocListReader *pLeft, /* Left position list */ DocListReader *pRight, /* Right position list */ sqlite_int64 iDocid, /* The docid from pLeft and pRight */ DocList *pOut /* Write the merged document record here */ ){ int iLeftCol, iLeftPos = readPosition(pLeft, &iLeftCol); int iRightCol, iRightPos = readPosition(pRight, &iRightCol); int match = 0; /* Loop until we've reached the end of both position lists. */ while( iLeftPos!=-1 && iRightPos!=-1 ){ if( iLeftCol==iRightCol && iLeftPos+1==iRightPos ){ if( !match ){ docListAddDocid(pOut, iDocid); match = 1; } if( pOut->iType>=DL_POSITIONS ){ docListAddPos(pOut, iRightCol, iRightPos); } iLeftPos = readPosition(pLeft, &iLeftCol); iRightPos = readPosition(pRight, &iRightCol); }else if( iRightCol<iLeftCol || (iRightCol==iLeftCol && iRightPos<iLeftPos+1) ){ iRightPos = readPosition(pRight, &iRightCol); }else{ iLeftPos = readPosition(pLeft, &iLeftCol); } } if( iLeftPos>=0 ) skipPositionList(pLeft); if( iRightPos>=0 ) skipPositionList(pRight); } /* We have two doclists: pLeft and pRight. ** Write the phrase intersection of these two doclists into pOut. ** ** A phrase intersection means that two documents only match ** if pLeft.iPos+1==pRight.iPos. ** ** The output pOut may or may not contain positions. If pOut ** does contain positions, they are the positions of pRight. */ static void docListPhraseMerge( DocList *pLeft, /* Doclist resulting from the words on the left */ DocList *pRight, /* Doclist for the next word to the right */ DocList *pOut /* Write the combined doclist here */ ){ DocListReader left, right; sqlite_int64 docidLeft, docidRight; readerInit(&left, pLeft); readerInit(&right, pRight); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); while( docidLeft>0 && docidRight>0 ){ if( docidLeft<docidRight ){ docidLeft = nextDocid(&left); }else if( docidRight<docidLeft ){ docidRight = nextDocid(&right); }else{ mergePosList(&left, &right, docidLeft, pOut); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); } } } /* We have two doclists: pLeft and pRight. ** Write the intersection of these two doclists into pOut. ** Only docids are matched. Position information is ignored. ** ** The output pOut never holds positions. */ static void docListAndMerge( DocList *pLeft, /* Doclist resulting from the words on the left */ DocList *pRight, /* Doclist for the next word to the right */ DocList *pOut /* Write the combined doclist here */ ){ DocListReader left, right; sqlite_int64 docidLeft, docidRight; assert( pOut->iType<DL_POSITIONS ); readerInit(&left, pLeft); readerInit(&right, pRight); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); while( docidLeft>0 && docidRight>0 ){ if( docidLeft<docidRight ){ docidLeft = nextDocid(&left); }else if( docidRight<docidLeft ){ docidRight = nextDocid(&right); }else{ docListAddDocid(pOut, docidLeft); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); } } } /* We have two doclists: pLeft and pRight. ** Write the union of these two doclists into pOut. ** Only docids are matched. Position information is ignored. ** ** The output pOut never holds positions. */ static void docListOrMerge( DocList *pLeft, /* Doclist resulting from the words on the left */ DocList *pRight, /* Doclist for the next word to the right */ DocList *pOut /* Write the combined doclist here */ ){ DocListReader left, right; sqlite_int64 docidLeft, docidRight, priorLeft; readerInit(&left, pLeft); readerInit(&right, pRight); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); while( docidLeft>0 && docidRight>0 ){ if( docidLeft<=docidRight ){ docListAddDocid(pOut, docidLeft); }else{ docListAddDocid(pOut, docidRight); } priorLeft = docidLeft; if( docidLeft<=docidRight ){ docidLeft = nextDocid(&left); } if( docidRight>0 && docidRight<=priorLeft ){ docidRight = nextDocid(&right); } } while( docidLeft>0 ){ docListAddDocid(pOut, docidLeft); docidLeft = nextDocid(&left); } while( docidRight>0 ){ docListAddDocid(pOut, docidRight); docidRight = nextDocid(&right); } } /* We have two doclists: pLeft and pRight. ** Write into pOut all documents that occur in pLeft but not ** in pRight. ** ** Only docids are matched. Position information is ignored. ** ** The output pOut never holds positions. */ static void docListExceptMerge( DocList *pLeft, /* Doclist resulting from the words on the left */ DocList *pRight, /* Doclist for the next word to the right */ DocList *pOut /* Write the combined doclist here */ ){ DocListReader left, right; sqlite_int64 docidLeft, docidRight, priorLeft; readerInit(&left, pLeft); readerInit(&right, pRight); docidLeft = nextDocid(&left); docidRight = nextDocid(&right); while( docidLeft>0 && docidRight>0 ){ priorLeft = docidLeft; if( docidLeft<docidRight ){ docListAddDocid(pOut, docidLeft); } if( docidLeft<=docidRight ){ docidLeft = nextDocid(&left); } if( docidRight>0 && docidRight<=priorLeft ){ docidRight = nextDocid(&right); } } while( docidLeft>0 ){ docListAddDocid(pOut, docidLeft); docidLeft = nextDocid(&left); } } static char *string_dup_n(const char *s, int n){ char *str = malloc(n + 1); memcpy(str, s, n); str[n] = '\0'; return str; } /* Duplicate a string; the caller must free() the returned string. * (We don't use strdup() since it is not part of the standard C library and * may not be available everywhere.) */ static char *string_dup(const char *s){ return string_dup_n(s, strlen(s)); } /* Format a string, replacing each occurrence of the % character with * zDb.zName. This may be more convenient than sqlite_mprintf() * when one string is used repeatedly in a format string. * The caller must free() the returned string. */ static char *string_format(const char *zFormat, const char *zDb, const char *zName){ const char *p; size_t len = 0; size_t nDb = strlen(zDb); size_t nName = strlen(zName); size_t nFullTableName = nDb+1+nName; char *result; char *r; /* first compute length needed */ for(p = zFormat ; *p ; ++p){ len += (*p=='%' ? nFullTableName : 1); } len += 1; /* for null terminator */ r = result = malloc(len); for(p = zFormat; *p; ++p){ if( *p=='%' ){ memcpy(r, zDb, nDb); r += nDb; *r++ = '.'; memcpy(r, zName, nName); r += nName; } else { *r++ = *p; } } *r++ = '\0'; assert( r == result + len ); return result; } static int sql_exec(sqlite3 *db, const char *zDb, const char *zName, const char *zFormat){ char *zCommand = string_format(zFormat, zDb, zName); int rc; TRACE(("FTS1 sql: %s\n", zCommand)); rc = sqlite3_exec(db, zCommand, NULL, 0, NULL); free(zCommand); return rc; } static int sql_prepare(sqlite3 *db, const char *zDb, const char *zName, sqlite3_stmt **ppStmt, const char *zFormat){ char *zCommand = string_format(zFormat, zDb, zName); int rc; TRACE(("FTS1 prepare: %s\n", zCommand)); rc = sqlite3_prepare(db, zCommand, -1, ppStmt, NULL); free(zCommand); return rc; } /* end utility functions */ /* Forward reference */ typedef struct fulltext_vtab fulltext_vtab; /* A single term in a query is represented by an instances of ** the following structure. */ typedef struct QueryTerm { short int nPhrase; /* How many following terms are part of the same phrase */ short int iPhrase; /* This is the i-th term of a phrase. */ short int iColumn; /* Column of the index that must match this term */ signed char isOr; /* this term is preceded by "OR" */ signed char isNot; /* this term is preceded by "-" */ char *pTerm; /* text of the term. '\000' terminated. malloced */ int nTerm; /* Number of bytes in pTerm[] */ } QueryTerm; /* A query string is parsed into a Query structure. * * We could, in theory, allow query strings to be complicated * nested expressions with precedence determined by parentheses. * But none of the major search engines do this. (Perhaps the * feeling is that an parenthesized expression is two complex of * an idea for the average user to grasp.) Taking our lead from * the major search engines, we will allow queries to be a list * of terms (with an implied AND operator) or phrases in double-quotes, * with a single optional "-" before each non-phrase term to designate * negation and an optional OR connector. * * OR binds more tightly than the implied AND, which is what the * major search engines seem to do. So, for example: * * [one two OR three] ==> one AND (two OR three) * [one OR two three] ==> (one OR two) AND three * * A "-" before a term matches all entries that lack that term. * The "-" must occur immediately before the term with in intervening * space. This is how the search engines do it. * * A NOT term cannot be the right-hand operand of an OR. If this * occurs in the query string, the NOT is ignored: * * [one OR -two] ==> one OR two * */ typedef struct Query { fulltext_vtab *pFts; /* The full text index */ int nTerms; /* Number of terms in the query */ QueryTerm *pTerms; /* Array of terms. Space obtained from malloc() */ int nextIsOr; /* Set the isOr flag on the next inserted term */ int nextColumn; /* Next word parsed must be in this column */ int dfltColumn; /* The default column */ } Query; /* ** An instance of the following structure keeps track of generated ** matching-word offset information and snippets. */ typedef struct Snippet { int nMatch; /* Total number of matches */ int nAlloc; /* Space allocated for aMatch[] */ struct snippetMatch { /* One entry for each matching term */ char snStatus; /* Status flag for use while constructing snippets */ short int iCol; /* The column that contains the match */ short int iTerm; /* The index in Query.pTerms[] of the matching term */ short int nByte; /* Number of bytes in the term */ int iStart; /* The offset to the first character of the term */ } *aMatch; /* Points to space obtained from malloc */ char *zOffset; /* Text rendering of aMatch[] */ int nOffset; /* strlen(zOffset) */ char *zSnippet; /* Snippet text */ int nSnippet; /* strlen(zSnippet) */ } Snippet; typedef enum QueryType { QUERY_GENERIC, /* table scan */ QUERY_ROWID, /* lookup by rowid */ QUERY_FULLTEXT /* QUERY_FULLTEXT + [i] is a full-text search for column i*/ } QueryType; /* TODO(shess) CHUNK_MAX controls how much data we allow in segment 0 ** before we start aggregating into larger segments. Lower CHUNK_MAX ** means that for a given input we have more individual segments per ** term, which means more rows in the table and a bigger index (due to ** both more rows and bigger rowids). But it also reduces the average ** cost of adding new elements to the segment 0 doclist, and it seems ** to reduce the number of pages read and written during inserts. 256 ** was chosen by measuring insertion times for a certain input (first ** 10k documents of Enron corpus), though including query performance ** in the decision may argue for a larger value. */ #define CHUNK_MAX 256 typedef enum fulltext_statement { CONTENT_INSERT_STMT, CONTENT_SELECT_STMT, CONTENT_UPDATE_STMT, CONTENT_DELETE_STMT, TERM_SELECT_STMT, TERM_SELECT_ALL_STMT, TERM_INSERT_STMT, TERM_UPDATE_STMT, TERM_DELETE_STMT, MAX_STMT /* Always at end! */ } fulltext_statement; /* These must exactly match the enum above. */ /* TODO(adam): Is there some risk that a statement (in particular, ** pTermSelectStmt) will be used in two cursors at once, e.g. if a ** query joins a virtual table to itself? If so perhaps we should ** move some of these to the cursor object. */ static const char *const fulltext_zStatement[MAX_STMT] = { /* CONTENT_INSERT */ NULL, /* generated in contentInsertStatement() */ /* CONTENT_SELECT */ "select * from %_content where rowid = ?", /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */ /* CONTENT_DELETE */ "delete from %_content where rowid = ?", /* TERM_SELECT */ "select rowid, doclist from %_term where term = ? and segment = ?", /* TERM_SELECT_ALL */ "select doclist from %_term where term = ? order by segment", /* TERM_INSERT */ "insert into %_term (rowid, term, segment, doclist) values (?, ?, ?, ?)", /* TERM_UPDATE */ "update %_term set doclist = ? where rowid = ?", /* TERM_DELETE */ "delete from %_term where rowid = ?", }; /* ** A connection to a fulltext index is an instance of the following ** structure. The xCreate and xConnect methods create an instance ** of this structure and xDestroy and xDisconnect free that instance. ** All other methods receive a pointer to the structure as one of their ** arguments. */ struct fulltext_vtab { sqlite3_vtab base; /* Base class used by SQLite core */ sqlite3 *db; /* The database connection */ const char *zDb; /* logical database name */ const char *zName; /* virtual table name */ int nColumn; /* number of columns in virtual table */ char **azColumn; /* column names. malloced */ char **azContentColumn; /* column names in content table; malloced */ sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */ /* Precompiled statements which we keep as long as the table is ** open. */ sqlite3_stmt *pFulltextStatements[MAX_STMT]; }; /* ** When the core wants to do a query, it create a cursor using a ** call to xOpen. This structure is an instance of a cursor. It ** is destroyed by xClose. */ typedef struct fulltext_cursor { sqlite3_vtab_cursor base; /* Base class used by SQLite core */ QueryType iCursorType; /* Copy of sqlite3_index_info.idxNum */ sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */ int eof; /* True if at End Of Results */ Query q; /* Parsed query string */ Snippet snippet; /* Cached snippet for the current row */ int iColumn; /* Column being searched */ DocListReader result; /* used when iCursorType == QUERY_FULLTEXT */ } fulltext_cursor; static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){ return (fulltext_vtab *) c->base.pVtab; } static const sqlite3_module fulltextModule; /* forward declaration */ /* Append a list of strings separated by commas to a StringBuffer. */ static void appendList(StringBuffer *sb, int nString, char **azString){ int i; for(i=0; i<nString; ++i){ if( i>0 ) append(sb, ", "); append(sb, azString[i]); } } /* Return a dynamically generated statement of the form * insert into %_content (rowid, ...) values (?, ...) */ static const char *contentInsertStatement(fulltext_vtab *v){ StringBuffer sb; int i; initStringBuffer(&sb); append(&sb, "insert into %_content (rowid, "); appendList(&sb, v->nColumn, v->azContentColumn); append(&sb, ") values (?"); for(i=0; i<v->nColumn; ++i) append(&sb, ", ?"); append(&sb, ")"); return sb.s; } /* Return a dynamically generated statement of the form * update %_content set [col_0] = ?, [col_1] = ?, ... * where rowid = ? */ static const char *contentUpdateStatement(fulltext_vtab *v){ StringBuffer sb; int i; initStringBuffer(&sb); append(&sb, "update %_content set "); for(i=0; i<v->nColumn; ++i) { if( i>0 ){ append(&sb, ", "); } append(&sb, v->azContentColumn[i]); append(&sb, " = ?"); } append(&sb, " where rowid = ?"); return sb.s; } /* Puts a freshly-prepared statement determined by iStmt in *ppStmt. ** If the indicated statement has never been prepared, it is prepared ** and cached, otherwise the cached version is reset. */ static int sql_get_statement(fulltext_vtab *v, fulltext_statement iStmt, sqlite3_stmt **ppStmt){ assert( iStmt<MAX_STMT ); if( v->pFulltextStatements[iStmt]==NULL ){ const char *zStmt; int rc; switch( iStmt ){ case CONTENT_INSERT_STMT: zStmt = contentInsertStatement(v); break; case CONTENT_UPDATE_STMT: zStmt = contentUpdateStatement(v); break; default: zStmt = fulltext_zStatement[iStmt]; } rc = sql_prepare(v->db, v->zDb, v->zName, &v->pFulltextStatements[iStmt], zStmt); if( zStmt != fulltext_zStatement[iStmt]) free((void *) zStmt); if( rc!=SQLITE_OK ) return rc; } else { int rc = sqlite3_reset(v->pFulltextStatements[iStmt]); if( rc!=SQLITE_OK ) return rc; } *ppStmt = v->pFulltextStatements[iStmt]; return SQLITE_OK; } /* Step the indicated statement, handling errors SQLITE_BUSY (by ** retrying) and SQLITE_SCHEMA (by re-preparing and transferring ** bindings to the new statement). ** TODO(adam): We should extend this function so that it can work with ** statements declared locally, not only globally cached statements. */ static int sql_step_statement(fulltext_vtab *v, fulltext_statement iStmt, sqlite3_stmt **ppStmt){ int rc; sqlite3_stmt *s = *ppStmt; assert( iStmt<MAX_STMT ); assert( s==v->pFulltextStatements[iStmt] ); while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){ if( rc==SQLITE_BUSY ) continue; if( rc!=SQLITE_ERROR ) return rc; /* If an SQLITE_SCHEMA error has occurred, then finalizing this * statement is going to delete the fulltext_vtab structure. If * the statement just executed is in the pFulltextStatements[] * array, it will be finalized twice. So remove it before * calling sqlite3_finalize(). */ v->pFulltextStatements[iStmt] = NULL; rc = sqlite3_finalize(s); break; } return rc; err: sqlite3_finalize(s); return rc; } /* Like sql_step_statement(), but convert SQLITE_DONE to SQLITE_OK. ** Useful for statements like UPDATE, where we expect no results. */ static int sql_single_step_statement(fulltext_vtab *v, fulltext_statement iStmt, sqlite3_stmt **ppStmt){ int rc = sql_step_statement(v, iStmt, ppStmt); return (rc==SQLITE_DONE) ? SQLITE_OK : rc; } /* insert into %_content (rowid, ...) values ([rowid], [pValues]) */ static int content_insert(fulltext_vtab *v, sqlite3_value *rowid, sqlite3_value **pValues){ sqlite3_stmt *s; int i; int rc = sql_get_statement(v, CONTENT_INSERT_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_value(s, 1, rowid); if( rc!=SQLITE_OK ) return rc; for(i=0; i<v->nColumn; ++i){ rc = sqlite3_bind_value(s, 2+i, pValues[i]); if( rc!=SQLITE_OK ) return rc; } return sql_single_step_statement(v, CONTENT_INSERT_STMT, &s); } /* update %_content set col0 = pValues[0], col1 = pValues[1], ... * where rowid = [iRowid] */ static int content_update(fulltext_vtab *v, sqlite3_value **pValues, sqlite_int64 iRowid){ sqlite3_stmt *s; int i; int rc = sql_get_statement(v, CONTENT_UPDATE_STMT, &s); if( rc!=SQLITE_OK ) return rc; for(i=0; i<v->nColumn; ++i){ rc = sqlite3_bind_value(s, 1+i, pValues[i]); if( rc!=SQLITE_OK ) return rc; } rc = sqlite3_bind_int64(s, 1+v->nColumn, iRowid); if( rc!=SQLITE_OK ) return rc; return sql_single_step_statement(v, CONTENT_UPDATE_STMT, &s); } static void freeStringArray(int nString, const char **pString){ int i; for (i=0 ; i < nString ; ++i) { if( pString[i]!=NULL ) free((void *) pString[i]); } free((void *) pString); } /* select * from %_content where rowid = [iRow] * The caller must delete the returned array and all strings in it. * null fields will be NULL in the returned array. * * TODO: Perhaps we should return pointer/length strings here for consistency * with other code which uses pointer/length. */ static int content_select(fulltext_vtab *v, sqlite_int64 iRow, const char ***pValues){ sqlite3_stmt *s; const char **values; int i; int rc; *pValues = NULL; rc = sql_get_statement(v, CONTENT_SELECT_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int64(s, 1, iRow); if( rc!=SQLITE_OK ) return rc; rc = sql_step_statement(v, CONTENT_SELECT_STMT, &s); if( rc!=SQLITE_ROW ) return rc; values = (const char **) malloc(v->nColumn * sizeof(const char *)); for(i=0; i<v->nColumn; ++i){ if( sqlite3_column_type(s, i)==SQLITE_NULL ){ values[i] = NULL; }else{ values[i] = string_dup((char*)sqlite3_column_text(s, i)); } } /* We expect only one row. We must execute another sqlite3_step() * to complete the iteration; otherwise the table will remain locked. */ rc = sqlite3_step(s); if( rc==SQLITE_DONE ){ *pValues = values; return SQLITE_OK; } freeStringArray(v->nColumn, values); return rc; } /* delete from %_content where rowid = [iRow ] */ static int content_delete(fulltext_vtab *v, sqlite_int64 iRow){ sqlite3_stmt *s; int rc = sql_get_statement(v, CONTENT_DELETE_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int64(s, 1, iRow); if( rc!=SQLITE_OK ) return rc; return sql_single_step_statement(v, CONTENT_DELETE_STMT, &s); } /* select rowid, doclist from %_term * where term = [pTerm] and segment = [iSegment] * If found, returns SQLITE_ROW; the caller must free the * returned doclist. If no rows found, returns SQLITE_DONE. */ static int term_select(fulltext_vtab *v, const char *pTerm, int nTerm, int iSegment, sqlite_int64 *rowid, DocList *out){ sqlite3_stmt *s; int rc = sql_get_statement(v, TERM_SELECT_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_text(s, 1, pTerm, nTerm, SQLITE_STATIC); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int(s, 2, iSegment); if( rc!=SQLITE_OK ) return rc; rc = sql_step_statement(v, TERM_SELECT_STMT, &s); if( rc!=SQLITE_ROW ) return rc; *rowid = sqlite3_column_int64(s, 0); docListInit(out, DL_DEFAULT, sqlite3_column_blob(s, 1), sqlite3_column_bytes(s, 1)); /* We expect only one row. We must execute another sqlite3_step() * to complete the iteration; otherwise the table will remain locked. */ rc = sqlite3_step(s); return rc==SQLITE_DONE ? SQLITE_ROW : rc; } /* Load the segment doclists for term pTerm and merge them in ** appropriate order into out. Returns SQLITE_OK if successful. If ** there are no segments for pTerm, successfully returns an empty ** doclist in out. ** ** Each document consists of 1 or more "columns". The number of ** columns is v->nColumn. If iColumn==v->nColumn, then return ** position information about all columns. If iColumn<v->nColumn, ** then only return position information about the iColumn-th column ** (where the first column is 0). */ static int term_select_all( fulltext_vtab *v, /* The fulltext index we are querying against */ int iColumn, /* If <nColumn, only look at the iColumn-th column */ const char *pTerm, /* The term whose posting lists we want */ int nTerm, /* Number of bytes in pTerm */ DocList *out /* Write the resulting doclist here */ ){ DocList doclist; sqlite3_stmt *s; int rc = sql_get_statement(v, TERM_SELECT_ALL_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_text(s, 1, pTerm, nTerm, SQLITE_STATIC); if( rc!=SQLITE_OK ) return rc; docListInit(&doclist, DL_DEFAULT, 0, 0); /* TODO(shess) Handle schema and busy errors. */ while( (rc=sql_step_statement(v, TERM_SELECT_ALL_STMT, &s))==SQLITE_ROW ){ DocList old; /* TODO(shess) If we processed doclists from oldest to newest, we ** could skip the malloc() involved with the following call. For ** now, I'd rather keep this logic similar to index_insert_term(). ** We could additionally drop elements when we see deletes, but ** that would require a distinct version of docListAccumulate(). */ docListInit(&old, DL_DEFAULT, sqlite3_column_blob(s, 0), sqlite3_column_bytes(s, 0)); if( iColumn<v->nColumn ){ /* querying a single column */ docListRestrictColumn(&old, iColumn); } /* doclist contains the newer data, so write it over old. Then ** steal accumulated result for doclist. */ docListAccumulate(&old, &doclist); docListDestroy(&doclist); doclist = old; } if( rc!=SQLITE_DONE ){ docListDestroy(&doclist); return rc; } docListDiscardEmpty(&doclist); *out = doclist; return SQLITE_OK; } /* insert into %_term (rowid, term, segment, doclist) values ([piRowid], [pTerm], [iSegment], [doclist]) ** Lets sqlite select rowid if piRowid is NULL, else uses *piRowid. ** ** NOTE(shess) piRowid is IN, with values of "space of int64" plus ** null, it is not used to pass data back to the caller. */ static int term_insert(fulltext_vtab *v, sqlite_int64 *piRowid, const char *pTerm, int nTerm, int iSegment, DocList *doclist){ sqlite3_stmt *s; int rc = sql_get_statement(v, TERM_INSERT_STMT, &s); if( rc!=SQLITE_OK ) return rc; if( piRowid==NULL ){ rc = sqlite3_bind_null(s, 1); }else{ rc = sqlite3_bind_int64(s, 1, *piRowid); } if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_text(s, 2, pTerm, nTerm, SQLITE_STATIC); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int(s, 3, iSegment); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_blob(s, 4, doclist->pData, doclist->nData, SQLITE_STATIC); if( rc!=SQLITE_OK ) return rc; return sql_single_step_statement(v, TERM_INSERT_STMT, &s); } /* update %_term set doclist = [doclist] where rowid = [rowid] */ static int term_update(fulltext_vtab *v, sqlite_int64 rowid, DocList *doclist){ sqlite3_stmt *s; int rc = sql_get_statement(v, TERM_UPDATE_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_blob(s, 1, doclist->pData, doclist->nData, SQLITE_STATIC); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int64(s, 2, rowid); if( rc!=SQLITE_OK ) return rc; return sql_single_step_statement(v, TERM_UPDATE_STMT, &s); } static int term_delete(fulltext_vtab *v, sqlite_int64 rowid){ sqlite3_stmt *s; int rc = sql_get_statement(v, TERM_DELETE_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int64(s, 1, rowid); if( rc!=SQLITE_OK ) return rc; return sql_single_step_statement(v, TERM_DELETE_STMT, &s); } /* ** Free the memory used to contain a fulltext_vtab structure. */ static void fulltext_vtab_destroy(fulltext_vtab *v){ int iStmt, i; TRACE(("FTS1 Destroy %p\n", v)); for( iStmt=0; iStmt<MAX_STMT; iStmt++ ){ if( v->pFulltextStatements[iStmt]!=NULL ){ sqlite3_finalize(v->pFulltextStatements[iStmt]); v->pFulltextStatements[iStmt] = NULL; } } if( v->pTokenizer!=NULL ){ v->pTokenizer->pModule->xDestroy(v->pTokenizer); v->pTokenizer = NULL; } free(v->azColumn); for(i = 0; i < v->nColumn; ++i) { sqlite3_free(v->azContentColumn[i]); } free(v->azContentColumn); free(v); } /* ** Token types for parsing the arguments to xConnect or xCreate. */ #define TOKEN_EOF 0 /* End of file */ #define TOKEN_SPACE 1 /* Any kind of whitespace */ #define TOKEN_ID 2 /* An identifier */ #define TOKEN_STRING 3 /* A string literal */ #define TOKEN_PUNCT 4 /* A single punctuation character */ /* ** If X is a character that can be used in an identifier then ** IdChar(X) will be true. Otherwise it is false. ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, ** sqlite3IsIdChar[X] must be 1. ** ** Ticket #1066. the SQL standard does not allow '$' in the ** middle of identfiers. But many SQL implementations do. ** SQLite will allow '$' in identifiers for compatibility. ** But the feature is undocumented. */ static const char isIdChar[] = { /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */ }; #define IdChar(C) (((c=C)&0x80)!=0 || (c>0x1f && isIdChar[c-0x20])) /* ** Return the length of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ static int getToken(const char *z, int *tokenType){ int i, c; switch( *z ){ case 0: { *tokenType = TOKEN_EOF; return 0; } case ' ': case '\t': case '\n': case '\f': case '\r': { for(i=1; safe_isspace(z[i]); i++){} *tokenType = TOKEN_SPACE; return i; } case '`': case '\'': case '"': { int delim = z[0]; for(i=1; (c=z[i])!=0; i++){ if( c==delim ){ if( z[i+1]==delim ){ i++; }else{ break; } } } *tokenType = TOKEN_STRING; return i + (c!=0); } case '[': { for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} *tokenType = TOKEN_ID; return i; } default: { if( !IdChar(*z) ){ break; } for(i=1; IdChar(z[i]); i++){} *tokenType = TOKEN_ID; return i; } } *tokenType = TOKEN_PUNCT; return 1; } /* ** A token extracted from a string is an instance of the following ** structure. */ typedef struct Token { const char *z; /* Pointer to token text. Not '\000' terminated */ short int n; /* Length of the token text in bytes. */ } Token; /* ** Given a input string (which is really one of the argv[] parameters ** passed into xConnect or xCreate) split the string up into tokens. ** Return an array of pointers to '\000' terminated strings, one string ** for each non-whitespace token. ** ** The returned array is terminated by a single NULL pointer. ** ** Space to hold the returned array is obtained from a single ** malloc and should be freed by passing the return value to free(). ** The individual strings within the token list are all a part of ** the single memory allocation and will all be freed at once. */ static char **tokenizeString(const char *z, int *pnToken){ int nToken = 0; Token *aToken = malloc( strlen(z) * sizeof(aToken[0]) ); int n = 1; int e, i; int totalSize = 0; char **azToken; char *zCopy; while( n>0 ){ n = getToken(z, &e); if( e!=TOKEN_SPACE ){ aToken[nToken].z = z; aToken[nToken].n = n; nToken++; totalSize += n+1; } z += n; } azToken = (char**)malloc( nToken*sizeof(char*) + totalSize ); zCopy = (char*)&azToken[nToken]; nToken--; for(i=0; i<nToken; i++){ azToken[i] = zCopy; n = aToken[i].n; memcpy(zCopy, aToken[i].z, n); zCopy[n] = 0; zCopy += n+1; } azToken[nToken] = 0; free(aToken); *pnToken = nToken; return azToken; } /* ** Convert an SQL-style quoted string into a normal string by removing ** the quote characters. The conversion is done in-place. If the ** input does not begin with a quote character, then this routine ** is a no-op. ** ** Examples: ** ** "abc" becomes abc ** 'xyz' becomes xyz ** [pqr] becomes pqr ** `mno` becomes mno */ static void dequoteString(char *z){ int quote; int i, j; if( z==0 ) return; quote = z[0]; switch( quote ){ case '\'': break; case '"': break; case '`': break; /* For MySQL compatibility */ case '[': quote = ']'; break; /* For MS SqlServer compatibility */ default: return; } for(i=1, j=0; z[i]; i++){ if( z[i]==quote ){ if( z[i+1]==quote ){ z[j++] = quote; i++; }else{ z[j++] = 0; break; } }else{ z[j++] = z[i]; } } } /* ** The input azIn is a NULL-terminated list of tokens. Remove the first ** token and all punctuation tokens. Remove the quotes from ** around string literal tokens. ** ** Example: ** ** input: tokenize chinese ( 'simplifed' , 'mixed' ) ** output: chinese simplifed mixed ** ** Another example: ** ** input: delimiters ( '[' , ']' , '...' ) ** output: [ ] ... */ static void tokenListToIdList(char **azIn){ int i, j; if( azIn ){ for(i=0, j=-1; azIn[i]; i++){ if( safe_isalnum(azIn[i][0]) || azIn[i][1] ){ dequoteString(azIn[i]); if( j>=0 ){ azIn[j] = azIn[i]; } j++; } } azIn[j] = 0; } } /* ** Find the first alphanumeric token in the string zIn. Null-terminate ** this token. Remove any quotation marks. And return a pointer to ** the result. */ static char *firstToken(char *zIn, char **pzTail){ int n, ttype; while(1){ n = getToken(zIn, &ttype); if( ttype==TOKEN_SPACE ){ zIn += n; }else if( ttype==TOKEN_EOF ){ *pzTail = zIn; return 0; }else{ zIn[n] = 0; *pzTail = &zIn[1]; dequoteString(zIn); return zIn; } } /*NOTREACHED*/ } /* Return true if... ** ** * s begins with the string t, ignoring case ** * s is longer than t ** * The first character of s beyond t is not a alphanumeric ** ** Ignore leading space in *s. ** ** To put it another way, return true if the first token of ** s[] is t[]. */ static int startsWith(const char *s, const char *t){ while( safe_isspace(*s) ){ s++; } while( *t ){ if( safe_tolower(*s++)!=safe_tolower(*t++) ) return 0; } return *s!='_' && !safe_isalnum(*s); } /* ** An instance of this structure defines the "spec" of a ** full text index. This structure is populated by parseSpec ** and use by fulltextConnect and fulltextCreate. */ typedef struct TableSpec { const char *zDb; /* Logical database name */ const char *zName; /* Name of the full-text index */ int nColumn; /* Number of columns to be indexed */ char **azColumn; /* Original names of columns to be indexed */ char **azContentColumn; /* Column names for %_content */ char **azTokenizer; /* Name of tokenizer and its arguments */ } TableSpec; /* ** Reclaim all of the memory used by a TableSpec */ static void clearTableSpec(TableSpec *p) { free(p->azColumn); free(p->azContentColumn); free(p->azTokenizer); } /* Parse a CREATE VIRTUAL TABLE statement, which looks like this: * * CREATE VIRTUAL TABLE email * USING fts1(subject, body, tokenize mytokenizer(myarg)) * * We return parsed information in a TableSpec structure. * */ static int parseSpec(TableSpec *pSpec, int argc, const char *const*argv, char**pzErr){ int i, n; char *z, *zDummy; char **azArg; const char *zTokenizer = 0; /* argv[] entry describing the tokenizer */ assert( argc>=3 ); /* Current interface: ** argv[0] - module name ** argv[1] - database name ** argv[2] - table name ** argv[3..] - columns, optionally followed by tokenizer specification ** and snippet delimiters specification. */ /* Make a copy of the complete argv[][] array in a single allocation. ** The argv[][] array is read-only and transient. We can write to the ** copy in order to modify things and the copy is persistent. */ memset(pSpec, 0, sizeof(*pSpec)); for(i=n=0; i<argc; i++){ n += strlen(argv[i]) + 1; } azArg = malloc( sizeof(char*)*argc + n ); if( azArg==0 ){ return SQLITE_NOMEM; } z = (char*)&azArg[argc]; for(i=0; i<argc; i++){ azArg[i] = z; strcpy(z, argv[i]); z += strlen(z)+1; } /* Identify the column names and the tokenizer and delimiter arguments ** in the argv[][] array. */ pSpec->zDb = azArg[1]; pSpec->zName = azArg[2]; pSpec->nColumn = 0; pSpec->azColumn = azArg; zTokenizer = "tokenize simple"; for(i=3; i<argc; ++i){ if( startsWith(azArg[i],"tokenize") ){ zTokenizer = azArg[i]; }else{ z = azArg[pSpec->nColumn] = firstToken(azArg[i], &zDummy); pSpec->nColumn++; } } if( pSpec->nColumn==0 ){ azArg[0] = "content"; pSpec->nColumn = 1; } /* ** Construct the list of content column names. ** ** Each content column name will be of the form cNNAAAA ** where NN is the column number and AAAA is the sanitized ** column name. "sanitized" means that special characters are ** converted to "_". The cNN prefix guarantees that all column ** names are unique. ** ** The AAAA suffix is not strictly necessary. It is included ** for the convenience of people who might examine the generated ** %_content table and wonder what the columns are used for. */ pSpec->azContentColumn = malloc( pSpec->nColumn * sizeof(char *) ); if( pSpec->azContentColumn==0 ){ clearTableSpec(pSpec); return SQLITE_NOMEM; } for(i=0; i<pSpec->nColumn; i++){ char *p; pSpec->azContentColumn[i] = sqlite3_mprintf("c%d%s", i, azArg[i]); for (p = pSpec->azContentColumn[i]; *p ; ++p) { if( !safe_isalnum(*p) ) *p = '_'; } } /* ** Parse the tokenizer specification string. */ pSpec->azTokenizer = tokenizeString(zTokenizer, &n); tokenListToIdList(pSpec->azTokenizer); return SQLITE_OK; } /* ** Generate a CREATE TABLE statement that describes the schema of ** the virtual table. Return a pointer to this schema string. ** ** Space is obtained from sqlite3_mprintf() and should be freed ** using sqlite3_free(). */ static char *fulltextSchema( int nColumn, /* Number of columns */ const char *const* azColumn, /* List of columns */ const char *zTableName /* Name of the table */ ){ int i; char *zSchema, *zNext; const char *zSep = "("; zSchema = sqlite3_mprintf("CREATE TABLE x"); for(i=0; i<nColumn; i++){ zNext = sqlite3_mprintf("%s%s%Q", zSchema, zSep, azColumn[i]); sqlite3_free(zSchema); zSchema = zNext; zSep = ","; } zNext = sqlite3_mprintf("%s,%Q)", zSchema, zTableName); sqlite3_free(zSchema); return zNext; } /* ** Build a new sqlite3_vtab structure that will describe the ** fulltext index defined by spec. */ static int constructVtab( sqlite3 *db, /* The SQLite database connection */ TableSpec *spec, /* Parsed spec information from parseSpec() */ sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */ char **pzErr /* Write any error message here */ ){ int rc; int n; fulltext_vtab *v = 0; const sqlite3_tokenizer_module *m = NULL; char *schema; v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab)); if( v==0 ) return SQLITE_NOMEM; memset(v, 0, sizeof(*v)); /* sqlite will initialize v->base */ v->db = db; v->zDb = spec->zDb; /* Freed when azColumn is freed */ v->zName = spec->zName; /* Freed when azColumn is freed */ v->nColumn = spec->nColumn; v->azContentColumn = spec->azContentColumn; spec->azContentColumn = 0; v->azColumn = spec->azColumn; spec->azColumn = 0; if( spec->azTokenizer==0 ){ return SQLITE_NOMEM; } /* TODO(shess) For now, add new tokenizers as else if clauses. */ if( spec->azTokenizer[0]==0 || startsWith(spec->azTokenizer[0], "simple") ){ sqlite3Fts1SimpleTokenizerModule(&m); }else if( startsWith(spec->azTokenizer[0], "porter") ){ sqlite3Fts1PorterTokenizerModule(&m); }else{ *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]); rc = SQLITE_ERROR; goto err; } for(n=0; spec->azTokenizer[n]; n++){} if( n ){ rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1], &v->pTokenizer); }else{ rc = m->xCreate(0, 0, &v->pTokenizer); } if( rc!=SQLITE_OK ) goto err; v->pTokenizer->pModule = m; /* TODO: verify the existence of backing tables foo_content, foo_term */ schema = fulltextSchema(v->nColumn, (const char*const*)v->azColumn, spec->zName); rc = sqlite3_declare_vtab(db, schema); sqlite3_free(schema); if( rc!=SQLITE_OK ) goto err; memset(v->pFulltextStatements, 0, sizeof(v->pFulltextStatements)); *ppVTab = &v->base; TRACE(("FTS1 Connect %p\n", v)); return rc; err: fulltext_vtab_destroy(v); return rc; } static int fulltextConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVTab, char **pzErr ){ TableSpec spec; int rc = parseSpec(&spec, argc, argv, pzErr); if( rc!=SQLITE_OK ) return rc; rc = constructVtab(db, &spec, ppVTab, pzErr); clearTableSpec(&spec); return rc; } /* The %_content table holds the text of each document, with ** the rowid used as the docid. ** ** The %_term table maps each term to a document list blob ** containing elements sorted by ascending docid, each element ** encoded as: ** ** docid varint-encoded ** token elements: ** position+1 varint-encoded as delta from previous position ** start offset varint-encoded as delta from previous start offset ** end offset varint-encoded as delta from start offset ** ** The sentinel position of 0 indicates the end of the token list. ** ** Additionally, doclist blobs are chunked into multiple segments, ** using segment to order the segments. New elements are added to ** the segment at segment 0, until it exceeds CHUNK_MAX. Then ** segment 0 is deleted, and the doclist is inserted at segment 1. ** If there is already a doclist at segment 1, the segment 0 doclist ** is merged with it, the segment 1 doclist is deleted, and the ** merged doclist is inserted at segment 2, repeating those ** operations until an insert succeeds. ** ** Since this structure doesn't allow us to update elements in place ** in case of deletion or update, these are simply written to ** segment 0 (with an empty token list in case of deletion), with ** docListAccumulate() taking care to retain lower-segment ** information in preference to higher-segment information. */ /* TODO(shess) Provide a VACUUM type operation which both removes ** deleted elements which are no longer necessary, and duplicated ** elements. I suspect this will probably not be necessary in ** practice, though. */ static int fulltextCreate(sqlite3 *db, void *pAux, int argc, const char * const *argv, sqlite3_vtab **ppVTab, char **pzErr){ int rc; TableSpec spec; StringBuffer schema; TRACE(("FTS1 Create\n")); rc = parseSpec(&spec, argc, argv, pzErr); if( rc!=SQLITE_OK ) return rc; initStringBuffer(&schema); append(&schema, "CREATE TABLE %_content("); appendList(&schema, spec.nColumn, spec.azContentColumn); append(&schema, ")"); rc = sql_exec(db, spec.zDb, spec.zName, schema.s); free(schema.s); if( rc!=SQLITE_OK ) goto out; rc = sql_exec(db, spec.zDb, spec.zName, "create table %_term(term text, segment integer, doclist blob, " "primary key(term, segment));"); if( rc!=SQLITE_OK ) goto out; rc = constructVtab(db, &spec, ppVTab, pzErr); out: clearTableSpec(&spec); return rc; } /* Decide how to handle an SQL query. */ static int fulltextBestIndex(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){ int i; TRACE(("FTS1 BestIndex\n")); for(i=0; i<pInfo->nConstraint; ++i){ const struct sqlite3_index_constraint *pConstraint; pConstraint = &pInfo->aConstraint[i]; if( pConstraint->usable ) { if( pConstraint->iColumn==-1 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){ pInfo->idxNum = QUERY_ROWID; /* lookup by rowid */ TRACE(("FTS1 QUERY_ROWID\n")); } else if( pConstraint->iColumn>=0 && pConstraint->op==SQLITE_INDEX_CONSTRAINT_MATCH ){ /* full-text search */ pInfo->idxNum = QUERY_FULLTEXT + pConstraint->iColumn; TRACE(("FTS1 QUERY_FULLTEXT %d\n", pConstraint->iColumn)); } else continue; pInfo->aConstraintUsage[i].argvIndex = 1; pInfo->aConstraintUsage[i].omit = 1; /* An arbitrary value for now. * TODO: Perhaps rowid matches should be considered cheaper than * full-text searches. */ pInfo->estimatedCost = 1.0; return SQLITE_OK; } } pInfo->idxNum = QUERY_GENERIC; return SQLITE_OK; } static int fulltextDisconnect(sqlite3_vtab *pVTab){ TRACE(("FTS1 Disconnect %p\n", pVTab)); fulltext_vtab_destroy((fulltext_vtab *)pVTab); return SQLITE_OK; } static int fulltextDestroy(sqlite3_vtab *pVTab){ fulltext_vtab *v = (fulltext_vtab *)pVTab; int rc; TRACE(("FTS1 Destroy %p\n", pVTab)); rc = sql_exec(v->db, v->zDb, v->zName, "drop table if exists %_content;" "drop table if exists %_term;" ); if( rc!=SQLITE_OK ) return rc; fulltext_vtab_destroy((fulltext_vtab *)pVTab); return SQLITE_OK; } static int fulltextOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ fulltext_cursor *c; c = (fulltext_cursor *) calloc(sizeof(fulltext_cursor), 1); /* sqlite will initialize c->base */ *ppCursor = &c->base; TRACE(("FTS1 Open %p: %p\n", pVTab, c)); return SQLITE_OK; } /* Free all of the dynamically allocated memory held by *q */ static void queryClear(Query *q){ int i; for(i = 0; i < q->nTerms; ++i){ free(q->pTerms[i].pTerm); } free(q->pTerms); memset(q, 0, sizeof(*q)); } /* Free all of the dynamically allocated memory held by the ** Snippet */ static void snippetClear(Snippet *p){ free(p->aMatch); free(p->zOffset); free(p->zSnippet); memset(p, 0, sizeof(*p)); } /* ** Append a single entry to the p->aMatch[] log. */ static void snippetAppendMatch( Snippet *p, /* Append the entry to this snippet */ int iCol, int iTerm, /* The column and query term */ int iStart, int nByte /* Offset and size of the match */ ){ int i; struct snippetMatch *pMatch; if( p->nMatch+1>=p->nAlloc ){ p->nAlloc = p->nAlloc*2 + 10; p->aMatch = realloc(p->aMatch, p->nAlloc*sizeof(p->aMatch[0]) ); if( p->aMatch==0 ){ p->nMatch = 0; p->nAlloc = 0; return; } } i = p->nMatch++; pMatch = &p->aMatch[i]; pMatch->iCol = iCol; pMatch->iTerm = iTerm; pMatch->iStart = iStart; pMatch->nByte = nByte; } /* ** Sizing information for the circular buffer used in snippetOffsetsOfColumn() */ #define FTS1_ROTOR_SZ (32) #define FTS1_ROTOR_MASK (FTS1_ROTOR_SZ-1) /* ** Add entries to pSnippet->aMatch[] for every match that occurs against ** document zDoc[0..nDoc-1] which is stored in column iColumn. */ static void snippetOffsetsOfColumn( Query *pQuery, Snippet *pSnippet, int iColumn, const char *zDoc, int nDoc ){ const sqlite3_tokenizer_module *pTModule; /* The tokenizer module */ sqlite3_tokenizer *pTokenizer; /* The specific tokenizer */ sqlite3_tokenizer_cursor *pTCursor; /* Tokenizer cursor */ fulltext_vtab *pVtab; /* The full text index */ int nColumn; /* Number of columns in the index */ const QueryTerm *aTerm; /* Query string terms */ int nTerm; /* Number of query string terms */ int i, j; /* Loop counters */ int rc; /* Return code */ unsigned int match, prevMatch; /* Phrase search bitmasks */ const char *zToken; /* Next token from the tokenizer */ int nToken; /* Size of zToken */ int iBegin, iEnd, iPos; /* Offsets of beginning and end */ /* The following variables keep a circular buffer of the last ** few tokens */ unsigned int iRotor = 0; /* Index of current token */ int iRotorBegin[FTS1_ROTOR_SZ]; /* Beginning offset of token */ int iRotorLen[FTS1_ROTOR_SZ]; /* Length of token */ pVtab = pQuery->pFts; nColumn = pVtab->nColumn; pTokenizer = pVtab->pTokenizer; pTModule = pTokenizer->pModule; rc = pTModule->xOpen(pTokenizer, zDoc, nDoc, &pTCursor); if( rc ) return; pTCursor->pTokenizer = pTokenizer; aTerm = pQuery->pTerms; nTerm = pQuery->nTerms; if( nTerm>=FTS1_ROTOR_SZ ){ nTerm = FTS1_ROTOR_SZ - 1; } prevMatch = 0; while(1){ rc = pTModule->xNext(pTCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos); if( rc ) break; iRotorBegin[iRotor&FTS1_ROTOR_MASK] = iBegin; iRotorLen[iRotor&FTS1_ROTOR_MASK] = iEnd-iBegin; match = 0; for(i=0; i<nTerm; i++){ int iCol; iCol = aTerm[i].iColumn; if( iCol>=0 && iCol<nColumn && iCol!=iColumn ) continue; if( aTerm[i].nTerm!=nToken ) continue; if( memcmp(aTerm[i].pTerm, zToken, nToken) ) continue; if( aTerm[i].iPhrase>1 && (prevMatch & (1<<i))==0 ) continue; match |= 1<<i; if( i==nTerm-1 || aTerm[i+1].iPhrase==1 ){ for(j=aTerm[i].iPhrase-1; j>=0; j--){ int k = (iRotor-j) & FTS1_ROTOR_MASK; snippetAppendMatch(pSnippet, iColumn, i-j, iRotorBegin[k], iRotorLen[k]); } } } prevMatch = match<<1; iRotor++; } pTModule->xClose(pTCursor); } /* ** Compute all offsets for the current row of the query. ** If the offsets have already been computed, this routine is a no-op. */ static void snippetAllOffsets(fulltext_cursor *p){ int nColumn; int iColumn, i; int iFirst, iLast; fulltext_vtab *pFts; if( p->snippet.nMatch ) return; if( p->q.nTerms==0 ) return; pFts = p->q.pFts; nColumn = pFts->nColumn; iColumn = p->iCursorType - QUERY_FULLTEXT; if( iColumn<0 || iColumn>=nColumn ){ iFirst = 0; iLast = nColumn-1; }else{ iFirst = iColumn; iLast = iColumn; } for(i=iFirst; i<=iLast; i++){ const char *zDoc; int nDoc; zDoc = (const char*)sqlite3_column_text(p->pStmt, i+1); nDoc = sqlite3_column_bytes(p->pStmt, i+1); snippetOffsetsOfColumn(&p->q, &p->snippet, i, zDoc, nDoc); } } /* ** Convert the information in the aMatch[] array of the snippet ** into the string zOffset[0..nOffset-1]. */ static void snippetOffsetText(Snippet *p){ int i; int cnt = 0; StringBuffer sb; char zBuf[200]; if( p->zOffset ) return; initStringBuffer(&sb); for(i=0; i<p->nMatch; i++){ struct snippetMatch *pMatch = &p->aMatch[i]; zBuf[0] = ' '; sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d", pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte); append(&sb, zBuf); cnt++; } p->zOffset = sb.s; p->nOffset = sb.len; } /* ** zDoc[0..nDoc-1] is phrase of text. aMatch[0..nMatch-1] are a set ** of matching words some of which might be in zDoc. zDoc is column ** number iCol. ** ** iBreak is suggested spot in zDoc where we could begin or end an ** excerpt. Return a value similar to iBreak but possibly adjusted ** to be a little left or right so that the break point is better. */ static int wordBoundary( int iBreak, /* The suggested break point */ const char *zDoc, /* Document text */ int nDoc, /* Number of bytes in zDoc[] */ struct snippetMatch *aMatch, /* Matching words */ int nMatch, /* Number of entries in aMatch[] */ int iCol /* The column number for zDoc[] */ ){ int i; if( iBreak<=10 ){ return 0; } if( iBreak>=nDoc-10 ){ return nDoc; } for(i=0; i<nMatch && aMatch[i].iCol<iCol; i++){} while( i<nMatch && aMatch[i].iStart+aMatch[i].nByte<iBreak ){ i++; } if( i<nMatch ){ if( aMatch[i].iStart<iBreak+10 ){ return aMatch[i].iStart; } if( i>0 && aMatch[i-1].iStart+aMatch[i-1].nByte>=iBreak ){ return aMatch[i-1].iStart; } } for(i=1; i<=10; i++){ if( safe_isspace(zDoc[iBreak-i]) ){ return iBreak - i + 1; } if( safe_isspace(zDoc[iBreak+i]) ){ return iBreak + i + 1; } } return iBreak; } /* ** If the StringBuffer does not end in white space, add a single ** space character to the end. */ static void appendWhiteSpace(StringBuffer *p){ if( p->len==0 ) return; if( safe_isspace(p->s[p->len-1]) ) return; append(p, " "); } /* ** Remove white space from teh end of the StringBuffer */ static void trimWhiteSpace(StringBuffer *p){ while( p->len>0 && safe_isspace(p->s[p->len-1]) ){ p->len--; } } /* ** Allowed values for Snippet.aMatch[].snStatus */ #define SNIPPET_IGNORE 0 /* It is ok to omit this match from the snippet */ #define SNIPPET_DESIRED 1 /* We want to include this match in the snippet */ /* ** Generate the text of a snippet. */ static void snippetText( fulltext_cursor *pCursor, /* The cursor we need the snippet for */ const char *zStartMark, /* Markup to appear before each match */ const char *zEndMark, /* Markup to appear after each match */ const char *zEllipsis /* Ellipsis mark */ ){ int i, j; struct snippetMatch *aMatch; int nMatch; int nDesired; StringBuffer sb; int tailCol; int tailOffset; int iCol; int nDoc; const char *zDoc; int iStart, iEnd; int tailEllipsis = 0; int iMatch; free(pCursor->snippet.zSnippet); pCursor->snippet.zSnippet = 0; aMatch = pCursor->snippet.aMatch; nMatch = pCursor->snippet.nMatch; initStringBuffer(&sb); for(i=0; i<nMatch; i++){ aMatch[i].snStatus = SNIPPET_IGNORE; } nDesired = 0; for(i=0; i<pCursor->q.nTerms; i++){ for(j=0; j<nMatch; j++){ if( aMatch[j].iTerm==i ){ aMatch[j].snStatus = SNIPPET_DESIRED; nDesired++; break; } } } iMatch = 0; tailCol = -1; tailOffset = 0; for(i=0; i<nMatch && nDesired>0; i++){ if( aMatch[i].snStatus!=SNIPPET_DESIRED ) continue; nDesired--; iCol = aMatch[i].iCol; zDoc = (const char*)sqlite3_column_text(pCursor->pStmt, iCol+1); nDoc = sqlite3_column_bytes(pCursor->pStmt, iCol+1); iStart = aMatch[i].iStart - 40; iStart = wordBoundary(iStart, zDoc, nDoc, aMatch, nMatch, iCol); if( iStart<=10 ){ iStart = 0; } if( iCol==tailCol && iStart<=tailOffset+20 ){ iStart = tailOffset; } if( (iCol!=tailCol && tailCol>=0) || iStart!=tailOffset ){ trimWhiteSpace(&sb); appendWhiteSpace(&sb); append(&sb, zEllipsis); appendWhiteSpace(&sb); } iEnd = aMatch[i].iStart + aMatch[i].nByte + 40; iEnd = wordBoundary(iEnd, zDoc, nDoc, aMatch, nMatch, iCol); if( iEnd>=nDoc-10 ){ iEnd = nDoc; tailEllipsis = 0; }else{ tailEllipsis = 1; } while( iMatch<nMatch && aMatch[iMatch].iCol<iCol ){ iMatch++; } while( iStart<iEnd ){ while( iMatch<nMatch && aMatch[iMatch].iStart<iStart && aMatch[iMatch].iCol<=iCol ){ iMatch++; } if( iMatch<nMatch && aMatch[iMatch].iStart<iEnd && aMatch[iMatch].iCol==iCol ){ nappend(&sb, &zDoc[iStart], aMatch[iMatch].iStart - iStart); iStart = aMatch[iMatch].iStart; append(&sb, zStartMark); nappend(&sb, &zDoc[iStart], aMatch[iMatch].nByte); append(&sb, zEndMark); iStart += aMatch[iMatch].nByte; for(j=iMatch+1; j<nMatch; j++){ if( aMatch[j].iTerm==aMatch[iMatch].iTerm && aMatch[j].snStatus==SNIPPET_DESIRED ){ nDesired--; aMatch[j].snStatus = SNIPPET_IGNORE; } } }else{ nappend(&sb, &zDoc[iStart], iEnd - iStart); iStart = iEnd; } } tailCol = iCol; tailOffset = iEnd; } trimWhiteSpace(&sb); if( tailEllipsis ){ appendWhiteSpace(&sb); append(&sb, zEllipsis); } pCursor->snippet.zSnippet = sb.s; pCursor->snippet.nSnippet = sb.len; } /* ** Close the cursor. For additional information see the documentation ** on the xClose method of the virtual table interface. */ static int fulltextClose(sqlite3_vtab_cursor *pCursor){ fulltext_cursor *c = (fulltext_cursor *) pCursor; TRACE(("FTS1 Close %p\n", c)); sqlite3_finalize(c->pStmt); queryClear(&c->q); snippetClear(&c->snippet); if( c->result.pDoclist!=NULL ){ docListDelete(c->result.pDoclist); } free(c); return SQLITE_OK; } static int fulltextNext(sqlite3_vtab_cursor *pCursor){ fulltext_cursor *c = (fulltext_cursor *) pCursor; sqlite_int64 iDocid; int rc; TRACE(("FTS1 Next %p\n", pCursor)); snippetClear(&c->snippet); if( c->iCursorType < QUERY_FULLTEXT ){ /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ rc = sqlite3_step(c->pStmt); switch( rc ){ case SQLITE_ROW: c->eof = 0; return SQLITE_OK; case SQLITE_DONE: c->eof = 1; return SQLITE_OK; default: c->eof = 1; return rc; } } else { /* full-text query */ rc = sqlite3_reset(c->pStmt); if( rc!=SQLITE_OK ) return rc; iDocid = nextDocid(&c->result); if( iDocid==0 ){ c->eof = 1; return SQLITE_OK; } rc = sqlite3_bind_int64(c->pStmt, 1, iDocid); if( rc!=SQLITE_OK ) return rc; /* TODO(shess) Handle SQLITE_SCHEMA AND SQLITE_BUSY. */ rc = sqlite3_step(c->pStmt); if( rc==SQLITE_ROW ){ /* the case we expect */ c->eof = 0; return SQLITE_OK; } /* an error occurred; abort */ return rc==SQLITE_DONE ? SQLITE_ERROR : rc; } } /* Return a DocList corresponding to the query term *pTerm. If *pTerm ** is the first term of a phrase query, go ahead and evaluate the phrase ** query and return the doclist for the entire phrase query. ** ** The result is stored in pTerm->doclist. */ static int docListOfTerm( fulltext_vtab *v, /* The full text index */ int iColumn, /* column to restrict to. No restrition if >=nColumn */ QueryTerm *pQTerm, /* Term we are looking for, or 1st term of a phrase */ DocList **ppResult /* Write the result here */ ){ DocList *pLeft, *pRight, *pNew; int i, rc; pLeft = docListNew(DL_POSITIONS); rc = term_select_all(v, iColumn, pQTerm->pTerm, pQTerm->nTerm, pLeft); if( rc ){ docListDelete(pLeft); return rc; } for(i=1; i<=pQTerm->nPhrase; i++){ pRight = docListNew(DL_POSITIONS); rc = term_select_all(v, iColumn, pQTerm[i].pTerm, pQTerm[i].nTerm, pRight); if( rc ){ docListDelete(pLeft); return rc; } pNew = docListNew(i<pQTerm->nPhrase ? DL_POSITIONS : DL_DOCIDS); docListPhraseMerge(pLeft, pRight, pNew); docListDelete(pLeft); docListDelete(pRight); pLeft = pNew; } *ppResult = pLeft; return SQLITE_OK; } /* Add a new term pTerm[0..nTerm-1] to the query *q. */ static void queryAdd(Query *q, const char *pTerm, int nTerm){ QueryTerm *t; ++q->nTerms; q->pTerms = realloc(q->pTerms, q->nTerms * sizeof(q->pTerms[0])); if( q->pTerms==0 ){ q->nTerms = 0; return; } t = &q->pTerms[q->nTerms - 1]; memset(t, 0, sizeof(*t)); t->pTerm = malloc(nTerm+1); memcpy(t->pTerm, pTerm, nTerm); t->pTerm[nTerm] = 0; t->nTerm = nTerm; t->isOr = q->nextIsOr; q->nextIsOr = 0; t->iColumn = q->nextColumn; q->nextColumn = q->dfltColumn; } /* ** Check to see if the string zToken[0...nToken-1] matches any ** column name in the virtual table. If it does, ** return the zero-indexed column number. If not, return -1. */ static int checkColumnSpecifier( fulltext_vtab *pVtab, /* The virtual table */ const char *zToken, /* Text of the token */ int nToken /* Number of characters in the token */ ){ int i; for(i=0; i<pVtab->nColumn; i++){ if( memcmp(pVtab->azColumn[i], zToken, nToken)==0 && pVtab->azColumn[i][nToken]==0 ){ return i; } } return -1; } /* ** Parse the text at pSegment[0..nSegment-1]. Add additional terms ** to the query being assemblied in pQuery. ** ** inPhrase is true if pSegment[0..nSegement-1] is contained within ** double-quotes. If inPhrase is true, then the first term ** is marked with the number of terms in the phrase less one and ** OR and "-" syntax is ignored. If inPhrase is false, then every ** term found is marked with nPhrase=0 and OR and "-" syntax is significant. */ static int tokenizeSegment( sqlite3_tokenizer *pTokenizer, /* The tokenizer to use */ const char *pSegment, int nSegment, /* Query expression being parsed */ int inPhrase, /* True if within "..." */ Query *pQuery /* Append results here */ ){ const sqlite3_tokenizer_module *pModule = pTokenizer->pModule; sqlite3_tokenizer_cursor *pCursor; int firstIndex = pQuery->nTerms; int iCol; int nTerm = 1; int rc = pModule->xOpen(pTokenizer, pSegment, nSegment, &pCursor); if( rc!=SQLITE_OK ) return rc; pCursor->pTokenizer = pTokenizer; while( 1 ){ const char *pToken; int nToken, iBegin, iEnd, iPos; rc = pModule->xNext(pCursor, &pToken, &nToken, &iBegin, &iEnd, &iPos); if( rc!=SQLITE_OK ) break; if( !inPhrase && pSegment[iEnd]==':' && (iCol = checkColumnSpecifier(pQuery->pFts, pToken, nToken))>=0 ){ pQuery->nextColumn = iCol; continue; } if( !inPhrase && pQuery->nTerms>0 && nToken==2 && pSegment[iBegin]=='O' && pSegment[iBegin+1]=='R' ){ pQuery->nextIsOr = 1; continue; } queryAdd(pQuery, pToken, nToken); if( !inPhrase && iBegin>0 && pSegment[iBegin-1]=='-' ){ pQuery->pTerms[pQuery->nTerms-1].isNot = 1; } pQuery->pTerms[pQuery->nTerms-1].iPhrase = nTerm; if( inPhrase ){ nTerm++; } } if( inPhrase && pQuery->nTerms>firstIndex ){ pQuery->pTerms[firstIndex].nPhrase = pQuery->nTerms - firstIndex - 1; } return pModule->xClose(pCursor); } /* Parse a query string, yielding a Query object pQuery. ** ** The calling function will need to queryClear() to clean up ** the dynamically allocated memory held by pQuery. */ static int parseQuery( fulltext_vtab *v, /* The fulltext index */ const char *zInput, /* Input text of the query string */ int nInput, /* Size of the input text */ int dfltColumn, /* Default column of the index to match against */ Query *pQuery /* Write the parse results here. */ ){ int iInput, inPhrase = 0; if( zInput==0 ) nInput = 0; if( nInput<0 ) nInput = strlen(zInput); pQuery->nTerms = 0; pQuery->pTerms = NULL; pQuery->nextIsOr = 0; pQuery->nextColumn = dfltColumn; pQuery->dfltColumn = dfltColumn; pQuery->pFts = v; for(iInput=0; iInput<nInput; ++iInput){ int i; for(i=iInput; i<nInput && zInput[i]!='"'; ++i){} if( i>iInput ){ tokenizeSegment(v->pTokenizer, zInput+iInput, i-iInput, inPhrase, pQuery); } iInput = i; if( i<nInput ){ assert( zInput[i]=='"' ); inPhrase = !inPhrase; } } if( inPhrase ){ /* unmatched quote */ queryClear(pQuery); return SQLITE_ERROR; } return SQLITE_OK; } /* Perform a full-text query using the search expression in ** zInput[0..nInput-1]. Return a list of matching documents ** in pResult. ** ** Queries must match column iColumn. Or if iColumn>=nColumn ** they are allowed to match against any column. */ static int fulltextQuery( fulltext_vtab *v, /* The full text index */ int iColumn, /* Match against this column by default */ const char *zInput, /* The query string */ int nInput, /* Number of bytes in zInput[] */ DocList **pResult, /* Write the result doclist here */ Query *pQuery /* Put parsed query string here */ ){ int i, iNext, rc; DocList *pLeft = NULL; DocList *pRight, *pNew, *pOr; int nNot = 0; QueryTerm *aTerm; rc = parseQuery(v, zInput, nInput, iColumn, pQuery); if( rc!=SQLITE_OK ) return rc; /* Merge AND terms. */ aTerm = pQuery->pTerms; for(i = 0; i<pQuery->nTerms; i=iNext){ if( aTerm[i].isNot ){ /* Handle all NOT terms in a separate pass */ nNot++; iNext = i + aTerm[i].nPhrase+1; continue; } iNext = i + aTerm[i].nPhrase + 1; rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight); if( rc ){ queryClear(pQuery); return rc; } while( iNext<pQuery->nTerms && aTerm[iNext].isOr ){ rc = docListOfTerm(v, aTerm[iNext].iColumn, &aTerm[iNext], &pOr); iNext += aTerm[iNext].nPhrase + 1; if( rc ){ queryClear(pQuery); return rc; } pNew = docListNew(DL_DOCIDS); docListOrMerge(pRight, pOr, pNew); docListDelete(pRight); docListDelete(pOr); pRight = pNew; } if( pLeft==0 ){ pLeft = pRight; }else{ pNew = docListNew(DL_DOCIDS); docListAndMerge(pLeft, pRight, pNew); docListDelete(pRight); docListDelete(pLeft); pLeft = pNew; } } if( nNot && pLeft==0 ){ /* We do not yet know how to handle a query of only NOT terms */ return SQLITE_ERROR; } /* Do the EXCEPT terms */ for(i=0; i<pQuery->nTerms; i += aTerm[i].nPhrase + 1){ if( !aTerm[i].isNot ) continue; rc = docListOfTerm(v, aTerm[i].iColumn, &aTerm[i], &pRight); if( rc ){ queryClear(pQuery); docListDelete(pLeft); return rc; } pNew = docListNew(DL_DOCIDS); docListExceptMerge(pLeft, pRight, pNew); docListDelete(pRight); docListDelete(pLeft); pLeft = pNew; } *pResult = pLeft; return rc; } /* ** This is the xFilter interface for the virtual table. See ** the virtual table xFilter method documentation for additional ** information. ** ** If idxNum==QUERY_GENERIC then do a full table scan against ** the %_content table. ** ** If idxNum==QUERY_ROWID then do a rowid lookup for a single entry ** in the %_content table. ** ** If idxNum>=QUERY_FULLTEXT then use the full text index. The ** column on the left-hand side of the MATCH operator is column ** number idxNum-QUERY_FULLTEXT, 0 indexed. argv[0] is the right-hand ** side of the MATCH operator. */ /* TODO(shess) Upgrade the cursor initialization and destruction to ** account for fulltextFilter() being called multiple times on the ** same cursor. The current solution is very fragile. Apply fix to ** fts2 as appropriate. */ static int fulltextFilter( sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */ int idxNum, const char *idxStr, /* Which indexing scheme to use */ int argc, sqlite3_value **argv /* Arguments for the indexing scheme */ ){ fulltext_cursor *c = (fulltext_cursor *) pCursor; fulltext_vtab *v = cursor_vtab(c); int rc; char *zSql; TRACE(("FTS1 Filter %p\n",pCursor)); zSql = sqlite3_mprintf("select rowid, * from %%_content %s", idxNum==QUERY_GENERIC ? "" : "where rowid=?"); sqlite3_finalize(c->pStmt); rc = sql_prepare(v->db, v->zDb, v->zName, &c->pStmt, zSql); sqlite3_free(zSql); if( rc!=SQLITE_OK ) return rc; c->iCursorType = idxNum; switch( idxNum ){ case QUERY_GENERIC: break; case QUERY_ROWID: rc = sqlite3_bind_int64(c->pStmt, 1, sqlite3_value_int64(argv[0])); if( rc!=SQLITE_OK ) return rc; break; default: /* full-text search */ { const char *zQuery = (const char *)sqlite3_value_text(argv[0]); DocList *pResult; assert( idxNum<=QUERY_FULLTEXT+v->nColumn); assert( argc==1 ); queryClear(&c->q); rc = fulltextQuery(v, idxNum-QUERY_FULLTEXT, zQuery, -1, &pResult, &c->q); if( rc!=SQLITE_OK ) return rc; if( c->result.pDoclist!=NULL ) docListDelete(c->result.pDoclist); readerInit(&c->result, pResult); break; } } return fulltextNext(pCursor); } /* This is the xEof method of the virtual table. The SQLite core ** calls this routine to find out if it has reached the end of ** a query's results set. */ static int fulltextEof(sqlite3_vtab_cursor *pCursor){ fulltext_cursor *c = (fulltext_cursor *) pCursor; return c->eof; } /* This is the xColumn method of the virtual table. The SQLite ** core calls this method during a query when it needs the value ** of a column from the virtual table. This method needs to use ** one of the sqlite3_result_*() routines to store the requested ** value back in the pContext. */ static int fulltextColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *pContext, int idxCol){ fulltext_cursor *c = (fulltext_cursor *) pCursor; fulltext_vtab *v = cursor_vtab(c); if( idxCol<v->nColumn ){ sqlite3_value *pVal = sqlite3_column_value(c->pStmt, idxCol+1); sqlite3_result_value(pContext, pVal); }else if( idxCol==v->nColumn ){ /* The extra column whose name is the same as the table. ** Return a blob which is a pointer to the cursor */ sqlite3_result_blob(pContext, &c, sizeof(c), SQLITE_TRANSIENT); } return SQLITE_OK; } /* This is the xRowid method. The SQLite core calls this routine to ** retrive the rowid for the current row of the result set. The ** rowid should be written to *pRowid. */ static int fulltextRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ fulltext_cursor *c = (fulltext_cursor *) pCursor; *pRowid = sqlite3_column_int64(c->pStmt, 0); return SQLITE_OK; } /* Add all terms in [zText] to the given hash table. If [iColumn] > 0, * we also store positions and offsets in the hash table using the given * column number. */ static int buildTerms(fulltext_vtab *v, fts1Hash *terms, sqlite_int64 iDocid, const char *zText, int iColumn){ sqlite3_tokenizer *pTokenizer = v->pTokenizer; sqlite3_tokenizer_cursor *pCursor; const char *pToken; int nTokenBytes; int iStartOffset, iEndOffset, iPosition; int rc; rc = pTokenizer->pModule->xOpen(pTokenizer, zText, -1, &pCursor); if( rc!=SQLITE_OK ) return rc; pCursor->pTokenizer = pTokenizer; while( SQLITE_OK==pTokenizer->pModule->xNext(pCursor, &pToken, &nTokenBytes, &iStartOffset, &iEndOffset, &iPosition) ){ DocList *p; /* Positions can't be negative; we use -1 as a terminator internally. */ if( iPosition<0 ){ pTokenizer->pModule->xClose(pCursor); return SQLITE_ERROR; } p = fts1HashFind(terms, pToken, nTokenBytes); if( p==NULL ){ p = docListNew(DL_DEFAULT); docListAddDocid(p, iDocid); fts1HashInsert(terms, pToken, nTokenBytes, p); } if( iColumn>=0 ){ docListAddPosOffset(p, iColumn, iPosition, iStartOffset, iEndOffset); } } /* TODO(shess) Check return? Should this be able to cause errors at ** this point? Actually, same question about sqlite3_finalize(), ** though one could argue that failure there means that the data is ** not durable. *ponder* */ pTokenizer->pModule->xClose(pCursor); return rc; } /* Update the %_terms table to map the term [pTerm] to the given rowid. */ static int index_insert_term(fulltext_vtab *v, const char *pTerm, int nTerm, DocList *d){ sqlite_int64 iIndexRow; DocList doclist; int iSegment = 0, rc; rc = term_select(v, pTerm, nTerm, iSegment, &iIndexRow, &doclist); if( rc==SQLITE_DONE ){ docListInit(&doclist, DL_DEFAULT, 0, 0); docListUpdate(&doclist, d); /* TODO(shess) Consider length(doclist)>CHUNK_MAX? */ rc = term_insert(v, NULL, pTerm, nTerm, iSegment, &doclist); goto err; } if( rc!=SQLITE_ROW ) return SQLITE_ERROR; docListUpdate(&doclist, d); if( doclist.nData<=CHUNK_MAX ){ rc = term_update(v, iIndexRow, &doclist); goto err; } /* Doclist doesn't fit, delete what's there, and accumulate ** forward. */ rc = term_delete(v, iIndexRow); if( rc!=SQLITE_OK ) goto err; /* Try to insert the doclist into a higher segment bucket. On ** failure, accumulate existing doclist with the doclist from that ** bucket, and put results in the next bucket. */ iSegment++; while( (rc=term_insert(v, &iIndexRow, pTerm, nTerm, iSegment, &doclist))!=SQLITE_OK ){ sqlite_int64 iSegmentRow; DocList old; int rc2; /* Retain old error in case the term_insert() error was really an ** error rather than a bounced insert. */ rc2 = term_select(v, pTerm, nTerm, iSegment, &iSegmentRow, &old); if( rc2!=SQLITE_ROW ) goto err; rc = term_delete(v, iSegmentRow); if( rc!=SQLITE_OK ) goto err; /* Reusing lowest-number deleted row keeps the index smaller. */ if( iSegmentRow<iIndexRow ) iIndexRow = iSegmentRow; /* doclist contains the newer data, so accumulate it over old. ** Then steal accumulated data for doclist. */ docListAccumulate(&old, &doclist); docListDestroy(&doclist); doclist = old; iSegment++; } err: docListDestroy(&doclist); return rc; } /* Add doclists for all terms in [pValues] to the hash table [terms]. */ static int insertTerms(fulltext_vtab *v, fts1Hash *terms, sqlite_int64 iRowid, sqlite3_value **pValues){ int i; for(i = 0; i < v->nColumn ; ++i){ char *zText = (char*)sqlite3_value_text(pValues[i]); int rc = buildTerms(v, terms, iRowid, zText, i); if( rc!=SQLITE_OK ) return rc; } return SQLITE_OK; } /* Add empty doclists for all terms in the given row's content to the hash * table [pTerms]. */ static int deleteTerms(fulltext_vtab *v, fts1Hash *pTerms, sqlite_int64 iRowid){ const char **pValues; int i; int rc = content_select(v, iRowid, &pValues); if( rc!=SQLITE_OK ) return rc; for(i = 0 ; i < v->nColumn; ++i) { rc = buildTerms(v, pTerms, iRowid, pValues[i], -1); if( rc!=SQLITE_OK ) break; } freeStringArray(v->nColumn, pValues); return SQLITE_OK; } /* Insert a row into the %_content table; set *piRowid to be the ID of the * new row. Fill [pTerms] with new doclists for the %_term table. */ static int index_insert(fulltext_vtab *v, sqlite3_value *pRequestRowid, sqlite3_value **pValues, sqlite_int64 *piRowid, fts1Hash *pTerms){ int rc; rc = content_insert(v, pRequestRowid, pValues); /* execute an SQL INSERT */ if( rc!=SQLITE_OK ) return rc; *piRowid = sqlite3_last_insert_rowid(v->db); return insertTerms(v, pTerms, *piRowid, pValues); } /* Delete a row from the %_content table; fill [pTerms] with empty doclists * to be written to the %_term table. */ static int index_delete(fulltext_vtab *v, sqlite_int64 iRow, fts1Hash *pTerms){ int rc = deleteTerms(v, pTerms, iRow); if( rc!=SQLITE_OK ) return rc; return content_delete(v, iRow); /* execute an SQL DELETE */ } /* Update a row in the %_content table; fill [pTerms] with new doclists for the * %_term table. */ static int index_update(fulltext_vtab *v, sqlite_int64 iRow, sqlite3_value **pValues, fts1Hash *pTerms){ /* Generate an empty doclist for each term that previously appeared in this * row. */ int rc = deleteTerms(v, pTerms, iRow); if( rc!=SQLITE_OK ) return rc; rc = content_update(v, pValues, iRow); /* execute an SQL UPDATE */ if( rc!=SQLITE_OK ) return rc; /* Now add positions for terms which appear in the updated row. */ return insertTerms(v, pTerms, iRow, pValues); } /* This function implements the xUpdate callback; it is the top-level entry * point for inserting, deleting or updating a row in a full-text table. */ static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, sqlite_int64 *pRowid){ fulltext_vtab *v = (fulltext_vtab *) pVtab; fts1Hash terms; /* maps term string -> PosList */ int rc; fts1HashElem *e; TRACE(("FTS1 Update %p\n", pVtab)); fts1HashInit(&terms, FTS1_HASH_STRING, 1); if( nArg<2 ){ rc = index_delete(v, sqlite3_value_int64(ppArg[0]), &terms); } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){ /* An update: * ppArg[0] = old rowid * ppArg[1] = new rowid * ppArg[2..2+v->nColumn-1] = values * ppArg[2+v->nColumn] = value for magic column (we ignore this) */ sqlite_int64 rowid = sqlite3_value_int64(ppArg[0]); if( sqlite3_value_type(ppArg[1]) != SQLITE_INTEGER || sqlite3_value_int64(ppArg[1]) != rowid ){ rc = SQLITE_ERROR; /* we don't allow changing the rowid */ } else { assert( nArg==2+v->nColumn+1); rc = index_update(v, rowid, &ppArg[2], &terms); } } else { /* An insert: * ppArg[1] = requested rowid * ppArg[2..2+v->nColumn-1] = values * ppArg[2+v->nColumn] = value for magic column (we ignore this) */ assert( nArg==2+v->nColumn+1); rc = index_insert(v, ppArg[1], &ppArg[2], pRowid, &terms); } if( rc==SQLITE_OK ){ /* Write updated doclists to disk. */ for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){ DocList *p = fts1HashData(e); rc = index_insert_term(v, fts1HashKey(e), fts1HashKeysize(e), p); if( rc!=SQLITE_OK ) break; } } /* clean up */ for(e=fts1HashFirst(&terms); e; e=fts1HashNext(e)){ DocList *p = fts1HashData(e); docListDelete(p); } fts1HashClear(&terms); return rc; } /* ** Implementation of the snippet() function for FTS1 */ static void snippetFunc( sqlite3_context *pContext, int argc, sqlite3_value **argv ){ fulltext_cursor *pCursor; if( argc<1 ) return; if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ sqlite3_result_error(pContext, "illegal first argument to html_snippet",-1); }else{ const char *zStart = "<b>"; const char *zEnd = "</b>"; const char *zEllipsis = "<b>...</b>"; memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); if( argc>=2 ){ zStart = (const char*)sqlite3_value_text(argv[1]); if( argc>=3 ){ zEnd = (const char*)sqlite3_value_text(argv[2]); if( argc>=4 ){ zEllipsis = (const char*)sqlite3_value_text(argv[3]); } } } snippetAllOffsets(pCursor); snippetText(pCursor, zStart, zEnd, zEllipsis); sqlite3_result_text(pContext, pCursor->snippet.zSnippet, pCursor->snippet.nSnippet, SQLITE_STATIC); } } /* ** Implementation of the offsets() function for FTS1 */ static void snippetOffsetsFunc( sqlite3_context *pContext, int argc, sqlite3_value **argv ){ fulltext_cursor *pCursor; if( argc<1 ) return; if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ sqlite3_result_error(pContext, "illegal first argument to offsets",-1); }else{ memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); snippetAllOffsets(pCursor); snippetOffsetText(&pCursor->snippet); sqlite3_result_text(pContext, pCursor->snippet.zOffset, pCursor->snippet.nOffset, SQLITE_STATIC); } } /* ** This routine implements the xFindFunction method for the FTS1 ** virtual table. */ static int fulltextFindFunction( sqlite3_vtab *pVtab, int nArg, const char *zName, void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), void **ppArg ){ if( strcmp(zName,"snippet")==0 ){ *pxFunc = snippetFunc; return 1; }else if( strcmp(zName,"offsets")==0 ){ *pxFunc = snippetOffsetsFunc; return 1; } return 0; } /* ** Rename an fts1 table. */ static int fulltextRename( sqlite3_vtab *pVtab, const char *zName ){ fulltext_vtab *p = (fulltext_vtab *)pVtab; int rc = SQLITE_NOMEM; char *zSql = sqlite3_mprintf( "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';" "ALTER TABLE %Q.'%q_term' RENAME TO '%q_term';" , p->zDb, p->zName, zName , p->zDb, p->zName, zName ); if( zSql ){ rc = sqlite3_exec(p->db, zSql, 0, 0, 0); sqlite3_free(zSql); } return rc; } static const sqlite3_module fulltextModule = { /* iVersion */ 0, /* xCreate */ fulltextCreate, /* xConnect */ fulltextConnect, /* xBestIndex */ fulltextBestIndex, /* xDisconnect */ fulltextDisconnect, /* xDestroy */ fulltextDestroy, /* xOpen */ fulltextOpen, /* xClose */ fulltextClose, /* xFilter */ fulltextFilter, /* xNext */ fulltextNext, /* xEof */ fulltextEof, /* xColumn */ fulltextColumn, /* xRowid */ fulltextRowid, /* xUpdate */ fulltextUpdate, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindFunction */ fulltextFindFunction, /* xRename */ fulltextRename, }; int sqlite3Fts1Init(sqlite3 *db){ sqlite3_overload_function(db, "snippet", -1); sqlite3_overload_function(db, "offsets", -1); return sqlite3_create_module(db, "fts1", &fulltextModule, 0); } #if !SQLITE_CORE int sqlite3_extension_init(sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi){ SQLITE_EXTENSION_INIT2(pApi) return sqlite3Fts1Init(db); } #endif #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS1) */
gpl-3.0
pacificIT/u-boot-1
arch/arm/cpu/arm926ejs/mb86r0x/clock.c
200
1281
/* * (C) Copyright 2010 * Matthias Weisser <weisserm@arcor.de> * * See file CREDITS for list of people who contributed to this * project. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA */ #include <common.h> #include <asm/io.h> #include <asm/arch/hardware.h> /* * Get the peripheral bus frequency depending on pll pin settings */ ulong get_bus_freq(ulong dummy) { struct mb86r0x_crg * crg = (struct mb86r0x_crg *) MB86R0x_CRG_BASE; uint32_t pllmode; pllmode = readl(&crg->crpr) & MB86R0x_CRG_CRPR_PLLMODE; if (pllmode == MB86R0x_CRG_CRPR_PLLMODE_X20) return 40000000; return 41164767; }
gpl-3.0
s20121035/rk3288_android5.1_repo
kernel/fs/nilfs2/bmap.c
11482
14761
/* * bmap.c - NILFS block mapping. * * Copyright (C) 2006-2008 Nippon Telegraph and Telephone Corporation. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Written by Koji Sato <koji@osrg.net>. */ #include <linux/fs.h> #include <linux/string.h> #include <linux/errno.h> #include "nilfs.h" #include "bmap.h" #include "btree.h" #include "direct.h" #include "btnode.h" #include "mdt.h" #include "dat.h" #include "alloc.h" struct inode *nilfs_bmap_get_dat(const struct nilfs_bmap *bmap) { struct the_nilfs *nilfs = bmap->b_inode->i_sb->s_fs_info; return nilfs->ns_dat; } static int nilfs_bmap_convert_error(struct nilfs_bmap *bmap, const char *fname, int err) { struct inode *inode = bmap->b_inode; if (err == -EINVAL) { nilfs_error(inode->i_sb, fname, "broken bmap (inode number=%lu)\n", inode->i_ino); err = -EIO; } return err; } /** * nilfs_bmap_lookup_at_level - find a data block or node block * @bmap: bmap * @key: key * @level: level * @ptrp: place to store the value associated to @key * * Description: nilfs_bmap_lookup_at_level() finds a record whose key * matches @key in the block at @level of the bmap. * * Return Value: On success, 0 is returned and the record associated with @key * is stored in the place pointed by @ptrp. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. * * %-ENOENT - A record associated with @key does not exist. */ int nilfs_bmap_lookup_at_level(struct nilfs_bmap *bmap, __u64 key, int level, __u64 *ptrp) { sector_t blocknr; int ret; down_read(&bmap->b_sem); ret = bmap->b_ops->bop_lookup(bmap, key, level, ptrp); if (ret < 0) { ret = nilfs_bmap_convert_error(bmap, __func__, ret); goto out; } if (NILFS_BMAP_USE_VBN(bmap)) { ret = nilfs_dat_translate(nilfs_bmap_get_dat(bmap), *ptrp, &blocknr); if (!ret) *ptrp = blocknr; } out: up_read(&bmap->b_sem); return ret; } int nilfs_bmap_lookup_contig(struct nilfs_bmap *bmap, __u64 key, __u64 *ptrp, unsigned maxblocks) { int ret; down_read(&bmap->b_sem); ret = bmap->b_ops->bop_lookup_contig(bmap, key, ptrp, maxblocks); up_read(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } static int nilfs_bmap_do_insert(struct nilfs_bmap *bmap, __u64 key, __u64 ptr) { __u64 keys[NILFS_BMAP_SMALL_HIGH + 1]; __u64 ptrs[NILFS_BMAP_SMALL_HIGH + 1]; int ret, n; if (bmap->b_ops->bop_check_insert != NULL) { ret = bmap->b_ops->bop_check_insert(bmap, key); if (ret > 0) { n = bmap->b_ops->bop_gather_data( bmap, keys, ptrs, NILFS_BMAP_SMALL_HIGH + 1); if (n < 0) return n; ret = nilfs_btree_convert_and_insert( bmap, key, ptr, keys, ptrs, n); if (ret == 0) bmap->b_u.u_flags |= NILFS_BMAP_LARGE; return ret; } else if (ret < 0) return ret; } return bmap->b_ops->bop_insert(bmap, key, ptr); } /** * nilfs_bmap_insert - insert a new key-record pair into a bmap * @bmap: bmap * @key: key * @rec: record * * Description: nilfs_bmap_insert() inserts the new key-record pair specified * by @key and @rec into @bmap. * * Return Value: On success, 0 is returned. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. * * %-EEXIST - A record associated with @key already exist. */ int nilfs_bmap_insert(struct nilfs_bmap *bmap, unsigned long key, unsigned long rec) { int ret; down_write(&bmap->b_sem); ret = nilfs_bmap_do_insert(bmap, key, rec); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } static int nilfs_bmap_do_delete(struct nilfs_bmap *bmap, __u64 key) { __u64 keys[NILFS_BMAP_LARGE_LOW + 1]; __u64 ptrs[NILFS_BMAP_LARGE_LOW + 1]; int ret, n; if (bmap->b_ops->bop_check_delete != NULL) { ret = bmap->b_ops->bop_check_delete(bmap, key); if (ret > 0) { n = bmap->b_ops->bop_gather_data( bmap, keys, ptrs, NILFS_BMAP_LARGE_LOW + 1); if (n < 0) return n; ret = nilfs_direct_delete_and_convert( bmap, key, keys, ptrs, n); if (ret == 0) bmap->b_u.u_flags &= ~NILFS_BMAP_LARGE; return ret; } else if (ret < 0) return ret; } return bmap->b_ops->bop_delete(bmap, key); } int nilfs_bmap_last_key(struct nilfs_bmap *bmap, unsigned long *key) { __u64 lastkey; int ret; down_read(&bmap->b_sem); ret = bmap->b_ops->bop_last_key(bmap, &lastkey); up_read(&bmap->b_sem); if (ret < 0) ret = nilfs_bmap_convert_error(bmap, __func__, ret); else *key = lastkey; return ret; } /** * nilfs_bmap_delete - delete a key-record pair from a bmap * @bmap: bmap * @key: key * * Description: nilfs_bmap_delete() deletes the key-record pair specified by * @key from @bmap. * * Return Value: On success, 0 is returned. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. * * %-ENOENT - A record associated with @key does not exist. */ int nilfs_bmap_delete(struct nilfs_bmap *bmap, unsigned long key) { int ret; down_write(&bmap->b_sem); ret = nilfs_bmap_do_delete(bmap, key); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } static int nilfs_bmap_do_truncate(struct nilfs_bmap *bmap, unsigned long key) { __u64 lastkey; int ret; ret = bmap->b_ops->bop_last_key(bmap, &lastkey); if (ret < 0) { if (ret == -ENOENT) ret = 0; return ret; } while (key <= lastkey) { ret = nilfs_bmap_do_delete(bmap, lastkey); if (ret < 0) return ret; ret = bmap->b_ops->bop_last_key(bmap, &lastkey); if (ret < 0) { if (ret == -ENOENT) ret = 0; return ret; } } return 0; } /** * nilfs_bmap_truncate - truncate a bmap to a specified key * @bmap: bmap * @key: key * * Description: nilfs_bmap_truncate() removes key-record pairs whose keys are * greater than or equal to @key from @bmap. * * Return Value: On success, 0 is returned. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. */ int nilfs_bmap_truncate(struct nilfs_bmap *bmap, unsigned long key) { int ret; down_write(&bmap->b_sem); ret = nilfs_bmap_do_truncate(bmap, key); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } /** * nilfs_bmap_clear - free resources a bmap holds * @bmap: bmap * * Description: nilfs_bmap_clear() frees resources associated with @bmap. */ void nilfs_bmap_clear(struct nilfs_bmap *bmap) { down_write(&bmap->b_sem); if (bmap->b_ops->bop_clear != NULL) bmap->b_ops->bop_clear(bmap); up_write(&bmap->b_sem); } /** * nilfs_bmap_propagate - propagate dirty state * @bmap: bmap * @bh: buffer head * * Description: nilfs_bmap_propagate() marks the buffers that directly or * indirectly refer to the block specified by @bh dirty. * * Return Value: On success, 0 is returned. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. */ int nilfs_bmap_propagate(struct nilfs_bmap *bmap, struct buffer_head *bh) { int ret; down_write(&bmap->b_sem); ret = bmap->b_ops->bop_propagate(bmap, bh); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } /** * nilfs_bmap_lookup_dirty_buffers - * @bmap: bmap * @listp: pointer to buffer head list */ void nilfs_bmap_lookup_dirty_buffers(struct nilfs_bmap *bmap, struct list_head *listp) { if (bmap->b_ops->bop_lookup_dirty_buffers != NULL) bmap->b_ops->bop_lookup_dirty_buffers(bmap, listp); } /** * nilfs_bmap_assign - assign a new block number to a block * @bmap: bmap * @bhp: pointer to buffer head * @blocknr: block number * @binfo: block information * * Description: nilfs_bmap_assign() assigns the block number @blocknr to the * buffer specified by @bh. * * Return Value: On success, 0 is returned and the buffer head of a newly * create buffer and the block information associated with the buffer are * stored in the place pointed by @bh and @binfo, respectively. On error, one * of the following negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. */ int nilfs_bmap_assign(struct nilfs_bmap *bmap, struct buffer_head **bh, unsigned long blocknr, union nilfs_binfo *binfo) { int ret; down_write(&bmap->b_sem); ret = bmap->b_ops->bop_assign(bmap, bh, blocknr, binfo); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } /** * nilfs_bmap_mark - mark block dirty * @bmap: bmap * @key: key * @level: level * * Description: nilfs_bmap_mark() marks the block specified by @key and @level * as dirty. * * Return Value: On success, 0 is returned. On error, one of the following * negative error codes is returned. * * %-EIO - I/O error. * * %-ENOMEM - Insufficient amount of memory available. */ int nilfs_bmap_mark(struct nilfs_bmap *bmap, __u64 key, int level) { int ret; if (bmap->b_ops->bop_mark == NULL) return 0; down_write(&bmap->b_sem); ret = bmap->b_ops->bop_mark(bmap, key, level); up_write(&bmap->b_sem); return nilfs_bmap_convert_error(bmap, __func__, ret); } /** * nilfs_bmap_test_and_clear_dirty - test and clear a bmap dirty state * @bmap: bmap * * Description: nilfs_test_and_clear() is the atomic operation to test and * clear the dirty state of @bmap. * * Return Value: 1 is returned if @bmap is dirty, or 0 if clear. */ int nilfs_bmap_test_and_clear_dirty(struct nilfs_bmap *bmap) { int ret; down_write(&bmap->b_sem); ret = nilfs_bmap_dirty(bmap); nilfs_bmap_clear_dirty(bmap); up_write(&bmap->b_sem); return ret; } /* * Internal use only */ __u64 nilfs_bmap_data_get_key(const struct nilfs_bmap *bmap, const struct buffer_head *bh) { struct buffer_head *pbh; __u64 key; key = page_index(bh->b_page) << (PAGE_CACHE_SHIFT - bmap->b_inode->i_blkbits); for (pbh = page_buffers(bh->b_page); pbh != bh; pbh = pbh->b_this_page) key++; return key; } __u64 nilfs_bmap_find_target_seq(const struct nilfs_bmap *bmap, __u64 key) { __s64 diff; diff = key - bmap->b_last_allocated_key; if ((nilfs_bmap_keydiff_abs(diff) < NILFS_INODE_BMAP_SIZE) && (bmap->b_last_allocated_ptr != NILFS_BMAP_INVALID_PTR) && (bmap->b_last_allocated_ptr + diff > 0)) return bmap->b_last_allocated_ptr + diff; else return NILFS_BMAP_INVALID_PTR; } #define NILFS_BMAP_GROUP_DIV 8 __u64 nilfs_bmap_find_target_in_group(const struct nilfs_bmap *bmap) { struct inode *dat = nilfs_bmap_get_dat(bmap); unsigned long entries_per_group = nilfs_palloc_entries_per_group(dat); unsigned long group = bmap->b_inode->i_ino / entries_per_group; return group * entries_per_group + (bmap->b_inode->i_ino % NILFS_BMAP_GROUP_DIV) * (entries_per_group / NILFS_BMAP_GROUP_DIV); } static struct lock_class_key nilfs_bmap_dat_lock_key; static struct lock_class_key nilfs_bmap_mdt_lock_key; /** * nilfs_bmap_read - read a bmap from an inode * @bmap: bmap * @raw_inode: on-disk inode * * Description: nilfs_bmap_read() initializes the bmap @bmap. * * Return Value: On success, 0 is returned. On error, the following negative * error code is returned. * * %-ENOMEM - Insufficient amount of memory available. */ int nilfs_bmap_read(struct nilfs_bmap *bmap, struct nilfs_inode *raw_inode) { if (raw_inode == NULL) memset(bmap->b_u.u_data, 0, NILFS_BMAP_SIZE); else memcpy(bmap->b_u.u_data, raw_inode->i_bmap, NILFS_BMAP_SIZE); init_rwsem(&bmap->b_sem); bmap->b_state = 0; bmap->b_inode = &NILFS_BMAP_I(bmap)->vfs_inode; switch (bmap->b_inode->i_ino) { case NILFS_DAT_INO: bmap->b_ptr_type = NILFS_BMAP_PTR_P; bmap->b_last_allocated_key = 0; bmap->b_last_allocated_ptr = NILFS_BMAP_NEW_PTR_INIT; lockdep_set_class(&bmap->b_sem, &nilfs_bmap_dat_lock_key); break; case NILFS_CPFILE_INO: case NILFS_SUFILE_INO: bmap->b_ptr_type = NILFS_BMAP_PTR_VS; bmap->b_last_allocated_key = 0; bmap->b_last_allocated_ptr = NILFS_BMAP_INVALID_PTR; lockdep_set_class(&bmap->b_sem, &nilfs_bmap_mdt_lock_key); break; case NILFS_IFILE_INO: lockdep_set_class(&bmap->b_sem, &nilfs_bmap_mdt_lock_key); /* Fall through */ default: bmap->b_ptr_type = NILFS_BMAP_PTR_VM; bmap->b_last_allocated_key = 0; bmap->b_last_allocated_ptr = NILFS_BMAP_INVALID_PTR; break; } return (bmap->b_u.u_flags & NILFS_BMAP_LARGE) ? nilfs_btree_init(bmap) : nilfs_direct_init(bmap); } /** * nilfs_bmap_write - write back a bmap to an inode * @bmap: bmap * @raw_inode: on-disk inode * * Description: nilfs_bmap_write() stores @bmap in @raw_inode. */ void nilfs_bmap_write(struct nilfs_bmap *bmap, struct nilfs_inode *raw_inode) { down_write(&bmap->b_sem); memcpy(raw_inode->i_bmap, bmap->b_u.u_data, NILFS_INODE_BMAP_SIZE * sizeof(__le64)); if (bmap->b_inode->i_ino == NILFS_DAT_INO) bmap->b_last_allocated_ptr = NILFS_BMAP_NEW_PTR_INIT; up_write(&bmap->b_sem); } void nilfs_bmap_init_gc(struct nilfs_bmap *bmap) { memset(&bmap->b_u, 0, NILFS_BMAP_SIZE); init_rwsem(&bmap->b_sem); bmap->b_inode = &NILFS_BMAP_I(bmap)->vfs_inode; bmap->b_ptr_type = NILFS_BMAP_PTR_U; bmap->b_last_allocated_key = 0; bmap->b_last_allocated_ptr = NILFS_BMAP_INVALID_PTR; bmap->b_state = 0; nilfs_btree_init_gc(bmap); } void nilfs_bmap_save(const struct nilfs_bmap *bmap, struct nilfs_bmap_store *store) { memcpy(store->data, bmap->b_u.u_data, sizeof(store->data)); store->last_allocated_key = bmap->b_last_allocated_key; store->last_allocated_ptr = bmap->b_last_allocated_ptr; store->state = bmap->b_state; } void nilfs_bmap_restore(struct nilfs_bmap *bmap, const struct nilfs_bmap_store *store) { memcpy(bmap->b_u.u_data, store->data, sizeof(store->data)); bmap->b_last_allocated_key = store->last_allocated_key; bmap->b_last_allocated_ptr = store->last_allocated_ptr; bmap->b_state = store->state; }
gpl-3.0
dylanstolte/Teleport-Game
Box2D/Box2d/Dynamics/Joints/b2RevoluteJoint.cpp
502
13089
/* * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/Joints/b2RevoluteJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Motor constraint // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) { bodyA = bA; bodyB = bB; localAnchorA = bodyA->GetLocalPoint(anchor); localAnchorB = bodyB->GetLocalPoint(anchor); referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); } b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) : b2Joint(def) { m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_referenceAngle = def->referenceAngle; m_impulse.SetZero(); m_motorImpulse = 0.0f; m_lowerAngle = def->lowerAngle; m_upperAngle = def->upperAngle; m_maxMotorTorque = def->maxMotorTorque; m_motorSpeed = def->motorSpeed; m_enableLimit = def->enableLimit; m_enableMotor = def->enableMotor; m_limitState = e_inactiveLimit; } void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; m_mass.ex.y = m_mass.ey.x; m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; m_mass.ex.z = m_mass.ez.x; m_mass.ey.z = m_mass.ez.y; m_mass.ez.z = iA + iB; m_motorMass = iA + iB; if (m_motorMass > 0.0f) { m_motorMass = 1.0f / m_motorMass; } if (m_enableMotor == false || fixedRotation) { m_motorImpulse = 0.0f; } if (m_enableLimit && fixedRotation == false) { float32 jointAngle = aB - aA - m_referenceAngle; if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) { m_limitState = e_equalLimits; } else if (jointAngle <= m_lowerAngle) { if (m_limitState != e_atLowerLimit) { m_impulse.z = 0.0f; } m_limitState = e_atLowerLimit; } else if (jointAngle >= m_upperAngle) { if (m_limitState != e_atUpperLimit) { m_impulse.z = 0.0f; } m_limitState = e_atUpperLimit; } else { m_limitState = e_inactiveLimit; m_impulse.z = 0.0f; } } else { m_limitState = e_inactiveLimit; } if (data.step.warmStarting) { // Scale impulses to support a variable time step. m_impulse *= data.step.dtRatio; m_motorImpulse *= data.step.dtRatio; b2Vec2 P(m_impulse.x, m_impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); } else { m_impulse.SetZero(); m_motorImpulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; bool fixedRotation = (iA + iB == 0.0f); // Solve motor constraint. if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) { float32 Cdot = wB - wA - m_motorSpeed; float32 impulse = -m_motorMass * Cdot; float32 oldImpulse = m_motorImpulse; float32 maxImpulse = data.step.dt * m_maxMotorTorque; m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = m_motorImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); float32 Cdot2 = wB - wA; b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); b2Vec3 impulse = -m_mass.Solve33(Cdot); if (m_limitState == e_equalLimits) { m_impulse += impulse; } else if (m_limitState == e_atLowerLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse < 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } else if (m_limitState == e_atUpperLimit) { float32 newImpulse = m_impulse.z + impulse.z; if (newImpulse > 0.0f) { b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); b2Vec2 reduced = m_mass.Solve22(rhs); impulse.x = reduced.x; impulse.y = reduced.y; impulse.z = -m_impulse.z; m_impulse.x += reduced.x; m_impulse.y += reduced.y; m_impulse.z = 0.0f; } else { m_impulse += impulse; } } b2Vec2 P(impulse.x, impulse.y); vA -= mA * P; wA -= iA * (b2Cross(m_rA, P) + impulse.z); vB += mB * P; wB += iB * (b2Cross(m_rB, P) + impulse.z); } else { // Solve point-to-point constraint b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); b2Vec2 impulse = m_mass.Solve22(-Cdot); m_impulse.x += impulse.x; m_impulse.y += impulse.y; vA -= mA * impulse; wA -= iA * b2Cross(m_rA, impulse); vB += mB * impulse; wB += iB * b2Cross(m_rB, impulse); } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); float32 angularError = 0.0f; float32 positionError = 0.0f; bool fixedRotation = (m_invIA + m_invIB == 0.0f); // Solve angular limit constraint. if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) { float32 angle = aB - aA - m_referenceAngle; float32 limitImpulse = 0.0f; if (m_limitState == e_equalLimits) { // Prevent large angular corrections float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; angularError = b2Abs(C); } else if (m_limitState == e_atLowerLimit) { float32 C = angle - m_lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); limitImpulse = -m_motorMass * C; } else if (m_limitState == e_atUpperLimit) { float32 C = angle - m_upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); limitImpulse = -m_motorMass * C; } aA -= m_invIA * limitImpulse; aB += m_invIB * limitImpulse; } // Solve point-to-point constraint. { qA.Set(aA); qB.Set(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); b2Vec2 C = cB + rB - cA - rA; positionError = C.Length(); float32 mA = m_invMassA, mB = m_invMassB; float32 iA = m_invIA, iB = m_invIB; b2Mat22 K; K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; K.ey.x = K.ex.y; K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; b2Vec2 impulse = -K.Solve(C); cA -= mA * impulse; aA -= iA * b2Cross(rA, impulse); cB += mB * impulse; aB += iB * b2Cross(rB, impulse); } data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return positionError <= b2_linearSlop && angularError <= b2_angularSlop; } b2Vec2 b2RevoluteJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2RevoluteJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const { b2Vec2 P(m_impulse.x, m_impulse.y); return inv_dt * P; } float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const { return inv_dt * m_impulse.z; } float32 b2RevoluteJoint::GetJointAngle() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; } float32 b2RevoluteJoint::GetJointSpeed() const { b2Body* bA = m_bodyA; b2Body* bB = m_bodyB; return bB->m_angularVelocity - bA->m_angularVelocity; } bool b2RevoluteJoint::IsMotorEnabled() const { return m_enableMotor; } void b2RevoluteJoint::EnableMotor(bool flag) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableMotor = flag; } float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const { return inv_dt * m_motorImpulse; } void b2RevoluteJoint::SetMotorSpeed(float32 speed) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_motorSpeed = speed; } void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_maxMotorTorque = torque; } bool b2RevoluteJoint::IsLimitEnabled() const { return m_enableLimit; } void b2RevoluteJoint::EnableLimit(bool flag) { if (flag != m_enableLimit) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_enableLimit = flag; m_impulse.z = 0.0f; } } float32 b2RevoluteJoint::GetLowerLimit() const { return m_lowerAngle; } float32 b2RevoluteJoint::GetUpperLimit() const { return m_upperAngle; } void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) { b2Assert(lower <= upper); if (lower != m_lowerAngle || upper != m_upperAngle) { m_bodyA->SetAwake(true); m_bodyB->SetAwake(true); m_impulse.z = 0.0f; m_lowerAngle = lower; m_upperAngle = upper; } } void b2RevoluteJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2RevoluteJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
gpl-3.0
tmhorne/celtx
content/xslt/src/base/txURIUtils.cpp
1
7504
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is TransforMiiX XSLT processor code. * * The Initial Developer of the Original Code is * The MITRE Corporation. * Portions created by the Initial Developer are Copyright (C) 1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Keith Visco <kvisco@ziplink.net> (Original Author) * Larry Fitzpatrick, OpenText <lef@opentext.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "txURIUtils.h" #ifndef TX_EXE #include "nsNetUtil.h" #include "nsIAttribute.h" #include "nsIScriptSecurityManager.h" #include "nsIDocument.h" #include "nsIDOMDocument.h" #include "nsIContent.h" #include "nsIPrincipal.h" #include "nsINodeInfo.h" #endif /** * URIUtils * A set of utilities for handling URIs **/ #ifdef TX_EXE //- Constants -/ const char URIUtils::HREF_PATH_SEP = '/'; /** * Implementation of utility functions for parsing URLs. * Just file paths for now. */ void txParsedURL::init(const nsAFlatString& aSpec) { mPath.Truncate(); mName.Truncate(); mRef.Truncate(); PRUint32 specLength = aSpec.Length(); if (!specLength) { return; } const PRUnichar* start = aSpec.get(); const PRUnichar* end = start + specLength; const PRUnichar* c = end - 1; // check for #ref for (; c >= start; --c) { if (*c == '#') { // we could eventually unescape this, too. mRef = Substring(c + 1, end); end = c; --c; if (c == start) { // we're done, return; } break; } } for (c = end - 1; c >= start; --c) { if (*c == '/') { mName = Substring(c + 1, end); mPath = Substring(start, c + 1); return; } } mName = Substring(start, end); } void txParsedURL::resolve(const txParsedURL& aRef, txParsedURL& aDest) { /* * No handling of absolute URLs now. * These aren't really URLs yet, anyway, but paths with refs */ aDest.mPath = mPath + aRef.mPath; if (aRef.mName.IsEmpty() && aRef.mPath.IsEmpty()) { // the relative URL is just a fragment identifier aDest.mName = mName; if (aRef.mRef.IsEmpty()) { // and not even that, keep the base ref aDest.mRef = mRef; return; } aDest.mRef = aRef.mRef; return; } aDest.mName = aRef.mName; aDest.mRef = aRef.mRef; } /** * Returns an InputStream for the file represented by the href * argument * @param href the href of the file to get the input stream for. * @return an InputStream to the desired resource * @exception java.io.FileNotFoundException when the file could not be * found **/ istream* URIUtils::getInputStream(const nsAString& href, nsAString& errMsg) { return new ifstream(NS_LossyConvertUTF16toASCII(href).get(), ios::in); } //-- getInputStream /** * Returns the document base of the href argument * @return the document base of the given href **/ void URIUtils::getDocumentBase(const nsAFlatString& href, nsAString& dest) { if (href.IsEmpty()) { return; } nsAFlatString::const_char_iterator temp; href.BeginReading(temp); PRUint32 iter = href.Length(); while (iter > 0) { if (temp[--iter] == HREF_PATH_SEP) { dest.Append(StringHead(href, iter)); break; } } } #endif /** * Resolves the given href argument, using the given documentBase * if necessary. * The new resolved href will be appended to the given dest String **/ void URIUtils::resolveHref(const nsAString& href, const nsAString& base, nsAString& dest) { if (base.IsEmpty()) { dest.Append(href); return; } if (href.IsEmpty()) { dest.Append(base); return; } #ifndef TX_EXE nsCOMPtr<nsIURI> pURL; nsAutoString resultHref; nsresult result = NS_NewURI(getter_AddRefs(pURL), base); if (NS_SUCCEEDED(result)) { NS_MakeAbsoluteURI(resultHref, href, pURL); dest.Append(resultHref); } #else nsAutoString documentBase; getDocumentBase(PromiseFlatString(base), documentBase); //-- join document base + href if (!documentBase.IsEmpty()) { dest.Append(documentBase); if (documentBase.CharAt(documentBase.Length()-1) != HREF_PATH_SEP) dest.Append(PRUnichar(HREF_PATH_SEP)); } dest.Append(href); #endif } //-- resolveHref #ifndef TX_EXE // static void URIUtils::ResetWithSource(nsIDocument *aNewDoc, nsIDOMNode *aSourceNode) { nsCOMPtr<nsINode> node = do_QueryInterface(aSourceNode); if (!node) { // XXXbz passing nsnull as the first arg to Reset is illegal aNewDoc->Reset(nsnull, nsnull); return; } nsCOMPtr<nsIDocument> sourceDoc = node->GetOwnerDoc(); if (!sourceDoc) { NS_ERROR("no source document found"); // XXXbz passing nsnull as the first arg to Reset is illegal aNewDoc->Reset(nsnull, nsnull); return; } nsIPrincipal* sourcePrincipal = sourceDoc->NodePrincipal(); // Copy the channel and loadgroup from the source document. nsCOMPtr<nsILoadGroup> loadGroup = sourceDoc->GetDocumentLoadGroup(); nsCOMPtr<nsIChannel> channel = sourceDoc->GetChannel(); if (!channel) { // Need to synthesize one if (NS_FAILED(NS_NewChannel(getter_AddRefs(channel), sourceDoc->GetDocumentURI(), nsnull, loadGroup))) { return; } channel->SetOwner(sourcePrincipal); } aNewDoc->Reset(channel, loadGroup); aNewDoc->SetPrincipal(sourcePrincipal); aNewDoc->SetBaseURI(sourceDoc->GetBaseURI()); // Copy charset aNewDoc->SetDocumentCharacterSetSource( sourceDoc->GetDocumentCharacterSetSource()); aNewDoc->SetDocumentCharacterSet(sourceDoc->GetDocumentCharacterSet()); } #endif /* TX_EXE */
mpl-2.0
dptechnics/Espruino
targetlibs/nrf5x/nrf51_sdk/examples/ant/ant_fs/client/main.c
7
22839
/* This software is subject to the license described in the license.txt file included with this software distribution. You may not use this file except in compliance with this license. Copyright © Dynastream Innovations Inc. 2012 All rights reserved. */ /**@file * This file is based on implementation originally made by Dynastream Innovations Inc. - August 2012 * * @defgroup ant_fs_client_main ANT-FS client device simulator * @{ * @ingroup nrf_ant_fs_client * * @brief The ANT-FS client device simulator. */ #include <stdint.h> #include <stdio.h> #include "ant_parameters.h" #include "antfs.h" #include "nrf.h" #include "nrf_sdm.h" #include "ant_interface.h" #include "mem.h" #include "bsp.h" #include "nordic_common.h" #include "app_error.h" #include "app_timer.h" #include "app_button.h" #include "app_util.h" #include "ant_stack_config.h" #if defined(TRACE_UART) #include "app_uart.h" #define UART_TX_BUF_SIZE 256 /**< UART TX buffer size. */ #define UART_RX_BUF_SIZE 1 /**< UART RX buffer size. */ #endif #define ANT_EVENT_MSG_BUFFER_MIN_SIZE 32u /**< Minimum size of ANT event message buffer. */ #define ANTFS_CLIENT_SERIAL_NUMBER 0xABCDEF12u /**< Serial number of client device. */ #define ANTFS_CLIENT_DEV_TYPE 416u /**< Beacon device type. */ #define ANTFS_CLIENT_MANUF_ID 2u /**< Beacon manufacturer ID. */ #define ANTFS_CLIENT_NAME { "Ref Design" } /**< Client's friendly name. */ #define ANTFS_CLIENT_PASSKEY {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10} /**< Client passkey. */ #define APP_TIMER_MAX_TIMERS (2u + BSP_APP_TIMERS_NUMBER) /**< Maximum number of simultaneously created timers. */ #define APP_TIMER_OP_QUEUE_SIZE 4u /**< Size of timer operation queues. */ /**< Maximum number of users of the GPIOTE handler. */ // Pairing state tracking. typedef enum { PAIRING_OFF = 0, /**< Pairing state not active. */ PAIRING_ACCEPT, /**< Pairing accept. */ PAIRING_DENY /**< Pairing deny. */ } pairing_state_t; static const uint8_t m_friendly_name[] = ANTFS_CLIENT_NAME; /**< Client's friendly name. */ static const uint8_t m_pass_key[] = ANTFS_CLIENT_PASSKEY; /**< Authentication string (passkey). */ static antfs_event_return_t m_antfs_event; /**< ANTFS event queue element. */ static antfs_dir_struct_t m_temp_dir_structure; /**< Current directory file structure. */ static antfs_request_info_t m_response_info; /**< Parameters for response to a download and upload request. */ static uint16_t m_file_index; /**< Index of the current file downloaded/uploaded. */ static uint32_t m_file_offset; /**< Current offset. */ static uint16_t m_current_crc; /**< Current CRC. */ static bool m_upload_success; /**< Upload response. */ static volatile pairing_state_t m_pairing_state; /**< Pairing state. */ /**@brief Function for handling SoftDevice asserts, does not return. * * Traces out the user supplied parameters and busy loops. * * @param[in] pc Value of the program counter. * @param[in] line_num Line number where the assert occurred. * @param[in] p_file_name Pointer to the file name. */ void softdevice_assert_callback(uint32_t pc, uint16_t line_num, const uint8_t * p_file_name) { printf("ASSERT-softdevice_assert_callback\n"); printf("PC: %#x\n", pc); printf("File name: %s\n", (const char*)p_file_name); printf("Line number: %u\n", line_num); for (;;) { // No implementation needed. } } /**@brief Function for handling an error. * * @param[in] error_code Error code supplied to the handler. * @param[in] line_num Line number where the error occurred. * @param[in] p_file_name Pointer to the file name. */ void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name) { printf("ASSERT-app_error_handler\n"); printf("Error code: %u\n", error_code); printf("File name: %s\n", (const char*)p_file_name); printf("Line number: %u\n", line_num); for (;;) { // No implementation needed. } } /**@brief Function for handling protocol stack IRQ. * * Interrupt is generated by the ANT stack upon sending event to the application. */ void SD_EVT_IRQHandler(void) { } /**@brief Function for processing user feedback for ANTFS pairing authentication request. */ static __INLINE void pairing_user_feedback_handle(void) { if (!antfs_pairing_resp_transmit((m_pairing_state == PAIRING_ACCEPT))) { #if defined(ANTFS_AUTH_TYPE_PAIRING) // @note: If pairing is supported by the implementation the only reason this code gets // executed would be if the protocol is in incorrect state, which would imply an error // either in the host or the client implementation. APP_ERROR_HANDLER(0); #endif // ANTFS_AUTH_TYPE_PAIRING } } /**@brief Function for processing ANTFS pairing request event. */ static __INLINE void event_pairing_request_handle(void) { const char * p_name = antfs_hostname_get(); const uint32_t err_code = app_button_enable(); APP_ERROR_CHECK(err_code); if (p_name != NULL) { printf("host name: %s\n", p_name); } } /**@brief Function to execute while waiting for the wait burst busy flag */ static void event_burst_wait_handle(void) { // No implementation needed } /**@brief Function for processing ANTFS download request event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void event_download_request_handle(const antfs_event_return_t * p_event) { uint8_t response = RESPONSE_MESSAGE_OK; // Grab request info. m_file_index = p_event->file_index; // Read file information from directory if (mem_file_info_get(m_file_index, &m_temp_dir_structure)) { // Check permissions. if (!(m_temp_dir_structure.general_flags & ANTFS_DIR_READ_MASK)) { response = RESPONSE_MESSAGE_NOT_AVAILABLE; printf("Download request denied: file n/a for reading\n"); } // Set response parameters. m_response_info.file_index.data = m_file_index; // File size (per directory). m_response_info.file_size.data = m_temp_dir_structure.file_size_in_bytes; // File is being read, so maximum size is the file size. m_response_info.max_file_size = m_temp_dir_structure.file_size_in_bytes; // Send the entire file in a single block if possible. m_response_info.max_burst_block_size.data = m_temp_dir_structure.file_size_in_bytes; } // Index not found. else { response = RESPONSE_MESSAGE_NOT_EXIST; m_response_info.file_index.data = 0; m_response_info.file_size.data = 0; m_response_info.max_file_size = 0; m_response_info.max_burst_block_size.data = 0; printf("Download request denied: file does not exist\n"); } antfs_download_req_resp_prepare(response, &m_response_info); } /**@brief Function for processing ANTFS download data event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void event_download_data_handle(const antfs_event_return_t * p_event) { // This example does not interact with a file system, and it does not account for latency for // reading or writing a file from EEPROM/flash. Prefetching the file might be useful to feed the // data to download in order to maintain the burst timing. if (m_file_index == p_event->file_index) { // Only send data for a file index matching the download request. // Burst data block size * 8 bytes per burst packet. uint8_t buffer[ANTFS_BURST_BLOCK_SIZE * 8]; // Offset specified by client. const uint32_t offset = p_event->offset; // Size of requested block of data. const uint32_t data_bytes = p_event->bytes; // Read block of data from memory. mem_file_read(m_file_index, offset, buffer, data_bytes); // @note: Suppress return value as no use case for handling it exists. UNUSED_VARIABLE(antfs_input_data_download(m_file_index, offset, data_bytes, buffer)); } } /**@brief Function for processing ANTFS upload request data event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void event_upload_request_handle(const antfs_event_return_t * p_event) { uint8_t response = RESPONSE_MESSAGE_OK; if ((p_event->offset == MAX_ULONG)) { // Requesting to resume an upload. if (m_file_index != p_event->file_index) { // We do not have a save point for this file. m_file_offset = 0; m_current_crc = 0; } } else { // This is a new upload. // Use requested offset and reset CRC. m_file_offset = p_event->offset; m_current_crc = 0; } m_file_index = p_event->file_index; // Read file information from directory. if (mem_file_info_get(m_file_index, &m_temp_dir_structure)) { // Check permissions. if (!(m_temp_dir_structure.general_flags & ANTFS_DIR_WRITE_MASK)) { response = RESPONSE_MESSAGE_NOT_AVAILABLE; printf("Upload request denied: file n/a for writing\n"); } // Set response parameters. m_response_info.file_index.data = m_file_index; // Current valid file size is the last offset written to the file. m_response_info.file_size.data = m_file_offset; // Space available for writing is the file size, as specified on directory. m_response_info.max_file_size = m_temp_dir_structure.file_size_in_bytes; // Get the entire file in a single burst if possible. m_response_info.max_burst_block_size.data = m_temp_dir_structure.file_size_in_bytes; // Last valid CRC. m_response_info.file_crc = m_current_crc; } else { // Index not found. response = RESPONSE_MESSAGE_NOT_EXIST; m_response_info.file_index.data = m_file_index; m_response_info.file_size.data = 0; m_response_info.max_file_size = 0; m_response_info.max_burst_block_size.data = 0; m_response_info.file_crc = 0; printf("Upload request denied: file does not exist\n"); } m_upload_success = true; // @note: Suppress return value as no use case for handling it exists. UNUSED_VARIABLE(antfs_upload_req_resp_transmit(response, &m_response_info)); } /**@brief Function for processing ANTFS upload data event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void event_upload_data_handle(const antfs_event_return_t * p_event) { // This example does not interact with a file system, and it does not account for latency for // reading or writing a file from EEPROM/flash. Buffering and other strategies might be useful // to handle a received upload, while maintaining the burst timing. if (m_upload_success && (m_file_index == p_event->file_index)) { // Offset requested for upload. const uint32_t offset = p_event->offset; // Size of current block of data. const uint32_t data_bytes = p_event->bytes; // Write data to file. if (!mem_file_write(m_file_index, offset, p_event->data, data_bytes)) { // Failed to write the data to system; do not attempt to write any more data after this, // and set upload response as FAIL. m_upload_success = false; printf("Failed to write file to system\n"); printf("Current offset %u, ", offset); } else { // Data was written successfully: // - update offset // - update current CRC. m_file_offset = offset + data_bytes; m_current_crc = p_event->crc; } } } /**@brief Function for processing ANTFS upload complete event. */ static __INLINE void event_upload_complete_handle(void) { printf("ANTFS_EVENT_UPLOAD_COMPLETE\n"); // @note: Suppress return value as no use case for handling it exists. UNUSED_VARIABLE(antfs_upload_data_resp_transmit(m_upload_success)); if (m_upload_success) { m_file_offset = 0; } } /**@brief Function for processing ANTFS erase request event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void event_erase_request_handle(const antfs_event_return_t * p_event) { uint8_t response = RESPONSE_MESSAGE_OK; m_file_index = p_event->file_index; if (m_file_index != 0) { // Read file information from directory. if (mem_file_info_get(m_file_index, &m_temp_dir_structure)) { // Check permissions. if (!(m_temp_dir_structure.general_flags & ANTFS_DIR_ERASE_MASK)) { response = RESPONSE_MESSAGE_FAIL; printf("Erase request denied: file n/a for erasing\n"); } else { // Erase file. if (!mem_file_erase(m_file_index)) { response = RESPONSE_MESSAGE_FAIL; } } } else { // Index not found. response = RESPONSE_MESSAGE_FAIL; printf("Erase request denied: file does not exist\n"); } } else { // Should not delete the directory. response = RESPONSE_MESSAGE_FAIL; printf("Erase request denied: can not delete directory\n"); } antfs_erase_req_resp_transmit(response); } /**@brief Function for processing a single ANTFS event. * * @param[in] p_event The event extracted from the queue to be processed. */ static void antfs_event_process(const antfs_event_return_t * p_event) { switch (p_event->event) { case ANTFS_EVENT_OPEN_COMPLETE: printf("ANTFS_EVENT_OPEN_COMPLETE\n"); break; case ANTFS_EVENT_CLOSE_COMPLETE: printf("ANTFS_EVENT_CLOSE_COMPLETE\n"); break; case ANTFS_EVENT_LINK: printf("ANTFS_EVENT_LINK\n"); break; case ANTFS_EVENT_AUTH: printf("ANTFS_EVENT_AUTH\n"); break; case ANTFS_EVENT_TRANS: printf("ANTFS_EVENT_TRANS\n"); break; case ANTFS_EVENT_PAIRING_REQUEST: printf("ANTFS_EVENT_PAIRING_REQUEST\n"); event_pairing_request_handle(); break; case ANTFS_EVENT_PAIRING_TIMEOUT: printf("ANTFS_EVENT_PAIRING_TIMEOUT\n"); break; case ANTFS_EVENT_DOWNLOAD_REQUEST: printf("ANTFS_EVENT_DOWNLOAD_REQUEST\n"); event_download_request_handle(p_event); break; case ANTFS_EVENT_DOWNLOAD_START: printf("ANTFS_EVENT_DOWNLOAD_START\n"); break; case ANTFS_EVENT_DOWNLOAD_REQUEST_DATA: event_download_data_handle(p_event); break; case ANTFS_EVENT_DOWNLOAD_COMPLETE: printf("ANTFS_EVENT_DOWNLOAD_COMPLETE\n"); break; case ANTFS_EVENT_DOWNLOAD_FAIL: printf("ANTFS_EVENT_DOWNLOAD_FAIL\n"); break; case ANTFS_EVENT_UPLOAD_REQUEST: printf("ANTFS_EVENT_UPLOAD_REQUEST\n"); event_upload_request_handle(p_event); break; case ANTFS_EVENT_UPLOAD_START: printf("ANTFS_EVENT_UPLOAD_START\n"); break; case ANTFS_EVENT_UPLOAD_DATA: event_upload_data_handle(p_event); break; case ANTFS_EVENT_UPLOAD_FAIL: printf("ANTFS_EVENT_UPLOAD_FAIL\n"); // @note: Suppress return value as no use case for handling it exists. UNUSED_VARIABLE(antfs_upload_data_resp_transmit(false)); break; case ANTFS_EVENT_UPLOAD_COMPLETE: printf("ANTFS_EVENT_UPLOAD_COMPLETE\n"); event_upload_complete_handle(); break; case ANTFS_EVENT_ERASE_REQUEST: printf("ANTFS_EVENT_ERASE_REQUEST\n"); event_erase_request_handle(p_event); break; default: break; } } #if defined(TRACE_UART) /**@brief Function for handling an UART error. * * @param[in] p_event Event supplied to the handler. */ void uart_error_handle(app_uart_evt_t * p_event) { if ((p_event->evt_type == APP_UART_FIFO_ERROR) || (p_event->evt_type == APP_UART_COMMUNICATION_ERROR)) { // Copy parameters to static variables because parameters are not accessible in the // debugger. static volatile app_uart_evt_t uart_event; uart_event.evt_type = p_event->evt_type; uart_event.data = p_event->data; UNUSED_VARIABLE(uart_event); for (;;) { // No implementation needed. } } } #endif /**@brief Function for handling button events. * * @param[in] event Event generated by button pressed. */ static void button_event_handler(bsp_event_t event) { switch (event) { case BSP_EVENT_KEY_1: m_pairing_state = PAIRING_DENY; break; case BSP_EVENT_KEY_0: m_pairing_state = PAIRING_ACCEPT; break; default: break; } } /**@brief Function for configuring and setting up the SoftDevice. */ static __INLINE void softdevice_setup(void) { printf("softdevice_setup\n"); uint32_t err_code = sd_softdevice_enable(NRF_CLOCK_LFCLKSRC_XTAL_50_PPM, softdevice_assert_callback); APP_ERROR_CHECK(err_code); // Configure application-specific interrupts. Set application IRQ to lowest priority and enable // application IRQ (triggered from ANT protocol stack). err_code = sd_nvic_SetPriority(SD_EVT_IRQn, NRF_APP_PRIORITY_LOW); APP_ERROR_CHECK(err_code); err_code = sd_nvic_EnableIRQ(SD_EVT_IRQn); APP_ERROR_CHECK(err_code); err_code = ant_stack_static_config(); APP_ERROR_CHECK(err_code); } /**@brief Function for application main entry, does not return. */ int main(void) { uint32_t err_code; #ifdef TRACE_UART // Configure and make UART ready for usage. const app_uart_comm_params_t comm_params = { RX_PIN_NUMBER, TX_PIN_NUMBER, RTS_PIN_NUMBER, CTS_PIN_NUMBER, APP_UART_FLOW_CONTROL_DISABLED, false, UART_BAUDRATE_BAUDRATE_Baud38400 }; APP_UART_FIFO_INIT(&comm_params, UART_RX_BUF_SIZE, UART_TX_BUF_SIZE, uart_error_handle, APP_IRQ_PRIORITY_LOW, err_code); APP_ERROR_CHECK(err_code); #endif // Initialize timer module. APP_TIMER_INIT(APP_TIMER_PRESCALER, APP_TIMER_MAX_TIMERS, APP_TIMER_OP_QUEUE_SIZE, NULL); err_code = bsp_init(BSP_INIT_LED | BSP_INIT_BUTTONS, APP_TIMER_TICKS(100, APP_TIMER_PRESCALER), button_event_handler); APP_ERROR_CHECK(err_code); softdevice_setup(); const antfs_params_t params = { ANTFS_CLIENT_SERIAL_NUMBER, ANTFS_CLIENT_DEV_TYPE, ANTFS_CLIENT_MANUF_ID, ANTFS_LINK_FREQ, ANTFS_DEFAULT_BEACON | DATA_AVAILABLE_FLAG_MASK, m_pass_key, m_friendly_name }; antfs_init(&params, event_burst_wait_handle); antfs_channel_setup(); m_pairing_state = PAIRING_OFF; uint8_t event; uint8_t ant_channel; uint8_t event_message_buffer[ANT_EVENT_MSG_BUFFER_MIN_SIZE]; bool allow_sleep; for (;;) { allow_sleep = true; // Process ANT-FS event queue. if (antfs_event_extract(&m_antfs_event)) { antfs_event_process(&m_antfs_event); allow_sleep = false; } // Process ANT event queue. if (sd_ant_event_get(&ant_channel, &event, event_message_buffer) == NRF_SUCCESS) { antfs_message_process(event_message_buffer); allow_sleep = false; } // Process user feedback for pairing authentication request. if (m_pairing_state != PAIRING_OFF) { pairing_user_feedback_handle(); // Reset to default state as been processed. m_pairing_state = PAIRING_OFF; allow_sleep = false; } // Sleep if allowed. if (allow_sleep) { err_code = sd_app_evt_wait(); APP_ERROR_CHECK(err_code); } } } /** *@} **/
mpl-2.0
SummitCore/Summit
src/ascent-world/Object.cpp
1
75724
/* * Ascent MMORPG Server * Copyright (C) 2005-2008 Ascent Team <http://www.ascentemu.com/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" #include "Unit.h" using namespace std; //#define DEG2RAD (M_PI/180.0) #define M_PI 3.14159265358979323846 #define M_H_PI 1.57079632679489661923 #define M_Q_PI 0.785398163397448309615 Object::Object() : m_position(0,0,0,0), m_spawnLocation(0,0,0,0) { m_mapId = 0; m_zoneId = 0; m_uint32Values = 0; m_objectUpdated = false; m_valuesCount = 0; //official Values m_walkSpeed = 2.5f; m_runSpeed = 7.0f; m_base_runSpeed = m_runSpeed; m_base_walkSpeed = m_walkSpeed; m_flySpeed = 7.0f; m_backFlySpeed = 4.5f; m_backWalkSpeed = 4.5f; // this should really be named m_backRunSpeed m_swimSpeed = 4.722222f; m_backSwimSpeed = 2.5f; m_turnRate = 3.141593f; m_mapMgr = 0; m_mapCell = 0; mSemaphoreTeleport = false; m_faction = NULL; m_factionDBC = NULL; m_instanceId = 0; Active = false; m_inQueue = false; m_extensions = NULL; m_loadedFromDB = false; m_loot.gold = 0; m_looted = false; } Object::~Object( ) { if(m_objectTypeId != TYPEID_ITEM) ASSERT(!m_inQueue); if (this->IsInWorld() && m_objectTypeId != TYPEID_ITEM && m_objectTypeId != TYPEID_CONTAINER) { this->RemoveFromWorld(false); } // for linux m_instanceId = -1; m_objectTypeId=TYPEID_UNUSED; if( m_extensions != NULL ) delete m_extensions; } void Object::_Create( uint32 mapid, float x, float y, float z, float ang ) { m_mapId = mapid; m_position.ChangeCoords(x, y, z, ang); m_spawnLocation.ChangeCoords(x, y, z, ang); m_lastMapUpdatePosition.ChangeCoords(x,y,z,ang); } uint32 Object::BuildCreateUpdateBlockForPlayer(ByteBuffer *data, Player *target) { uint8 flags = 0; uint32 flags2 = 0; uint8 updatetype = UPDATETYPE_CREATE_OBJECT; if(m_objectTypeId == TYPEID_CORPSE) { if(m_uint32Values[CORPSE_FIELD_DISPLAY_ID] == 0) return 0; } // any other case switch(m_objectTypeId) { // items + containers: 0x8 case TYPEID_ITEM: case TYPEID_CONTAINER: flags = 0x18; break; // player/unit: 0x68 (except self) case TYPEID_UNIT: flags = 0x70; break; case TYPEID_PLAYER: flags = 0x70; break; // gameobject/dynamicobject case TYPEID_GAMEOBJECT: case TYPEID_DYNAMICOBJECT: case TYPEID_CORPSE: flags = 0x58; break; // anyone else can get fucked and die! } if(target == this) { // player creating self flags |= 0x01; updatetype = UPDATETYPE_CREATE_YOURSELF; } // gameobject stuff if(m_objectTypeId == TYPEID_GAMEOBJECT) { switch(m_uint32Values[GAMEOBJECT_TYPE_ID]) { case GAMEOBJECT_TYPE_MO_TRANSPORT: { if(GetTypeFromGUID() != HIGHGUID_TYPE_TRANSPORTER) return 0; // bad transporter else flags = 0x5A; }break; case GAMEOBJECT_TYPE_TRANSPORT: { /* deeprun tram, etc */ flags = 0x5A; }break; case GAMEOBJECT_TYPE_DUEL_ARBITER: { // duel flags have to stay as updatetype 3, otherwise // it won't animate updatetype = UPDATETYPE_CREATE_YOURSELF; }break; } } // build our actual update *data << updatetype; // we shouldn't be here, under any cercumstances, unless we have a wowguid.. ASSERT(m_wowGuid.GetNewGuidLen()); *data << m_wowGuid; *data << m_objectTypeId; _BuildMovementUpdate(data, flags, flags2, target); // we have dirty data, or are creating for ourself. UpdateMask updateMask; updateMask.SetCount( m_valuesCount ); _SetCreateBits( &updateMask, target ); // this will cache automatically if needed _BuildValuesUpdate( data, &updateMask, target ); // update count: 1 ;) return 1; } //That is dirty fix it actually creates update of 1 field with //the given value ignoring existing changes in fields and so on //usefull if we want update this field for certain players //NOTE: it does not change fields. This is also very fast method WorldPacket *Object::BuildFieldUpdatePacket( uint32 index,uint32 value) { // uint64 guidfields = GetGUID(); // uint8 guidmask = 0; WorldPacket * packet=new WorldPacket(1500); packet->SetOpcode( SMSG_UPDATE_OBJECT ); *packet << (uint32)1;//number of update/create blocks *packet << (uint8)0;//unknown *packet << (uint8) UPDATETYPE_VALUES; // update type == update *packet << GetNewGUID(); uint32 mBlocks = index/32+1; *packet << (uint8)mBlocks; for(uint32 dword_n=mBlocks-1;dword_n;dword_n--) *packet <<(uint32)0; *packet <<(((uint32)(1))<<(index%32)); *packet << value; return packet; } void Object::BuildFieldUpdatePacket(Player* Target, uint32 Index, uint32 Value) { //ByteBuffer buf(500); /*uint8 rbuf[1000]; StackBuffer buf(rbuf, 1000); buf << uint8(UPDATETYPE_VALUES); buf << GetNewGUID(); uint32 mBlocks = Index/32+1; buf << (uint8)mBlocks; for(uint32 dword_n=mBlocks-1;dword_n;dword_n--) buf <<(uint32)0; buf <<(((uint32)(1))<<(Index%32)); buf << Value; Target->PushUpdateData(&buf, 1);*/ uint8 rbuf[1000]; StackPacket buf(SMSG_UPDATE_OBJECT, rbuf, 1000); buf << uint32(1); buf << uint8(0); buf << uint8(UPDATETYPE_VALUES); buf << GetNewGUID(); uint32 mBlocks = Index/32+1; buf << (uint8)mBlocks; for(uint32 dword_n=mBlocks-1;dword_n;dword_n--) buf <<(uint32)0; buf <<(((uint32)(1))<<(Index%32)); buf << Value; Target->GetSession()->SendPacket(&buf); } void Object::BuildFieldUpdatePacket(ByteBuffer * buf, uint32 Index, uint32 Value) { *buf << uint8(UPDATETYPE_VALUES); *buf << GetNewGUID(); uint32 mBlocks = Index/32+1; *buf << (uint8)mBlocks; for(uint32 dword_n=mBlocks-1;dword_n;dword_n--) *buf <<(uint32)0; *buf <<(((uint32)(1))<<(Index%32)); *buf << Value; } uint32 Object::BuildValuesUpdateBlockForPlayer(ByteBuffer *data, Player *target) { UpdateMask updateMask; updateMask.SetCount( m_valuesCount ); _SetUpdateBits( &updateMask, target ); for(uint32 x = 0; x < m_valuesCount; ++x) { if(updateMask.GetBit(x)) { *data << (uint8) UPDATETYPE_VALUES; // update type == update ASSERT(m_wowGuid.GetNewGuidLen()); *data << m_wowGuid; _BuildValuesUpdate( data, &updateMask, target ); return 1; } } return 0; } uint32 Object::BuildValuesUpdateBlockForPlayer(ByteBuffer * buf, UpdateMask * mask ) { // returns: update count *buf << (uint8) UPDATETYPE_VALUES; // update type == update ASSERT(m_wowGuid.GetNewGuidLen()); *buf << m_wowGuid; _BuildValuesUpdate( buf, mask, 0 ); // 1 update. return 1; } void Object::DestroyForPlayer(Player *target) const { if(target->GetSession() == 0) return; ASSERT(target); WorldPacket data(SMSG_DESTROY_OBJECT, 8); data << GetGUID(); target->GetSession()->SendPacket( &data ); } /////////////////////////////////////////////////////////////// /// Build the Movement Data portion of the update packet /// Fills the data with this object's movement/speed info /// TODO: rewrite this stuff, document unknown fields and flags uint32 TimeStamp(); void Object::_BuildMovementUpdate(ByteBuffer * data, uint8 flags, uint32 flags2, Player* target ) { ByteBuffer *splinebuf = (m_objectTypeId == TYPEID_UNIT) ? target->GetAndRemoveSplinePacket(GetGUID()) : 0; *data << (uint8)flags; Player * pThis = 0; if(m_objectTypeId == TYPEID_PLAYER) { pThis = static_cast< Player* >( this ); if(target == this) { // Updating our last speeds. pThis->UpdateLastSpeeds(); } } if (flags & 0x20) { if(pThis && pThis->m_TransporterGUID != 0) flags2 |= 0x200; else if(m_objectTypeId==TYPEID_UNIT && ((Creature*)this)->m_transportGuid != 0 && ((Creature*)this)->m_transportPosition != NULL) flags2 |= 0x200; if(splinebuf) { flags2 |= 0x08000001; //1=move forward if(GetTypeId() == TYPEID_UNIT) { if(static_cast<Unit*>(this)->GetAIInterface()->m_moveRun == false) flags2 |= 0x100; //100=walk } } if(GetTypeId() == TYPEID_UNIT) { // Don't know what this is, but I've only seen it applied to spirit healers. // maybe some sort of invisibility flag? :/ switch(GetEntry()) { case 6491: // Spirit Healer case 13116: // Alliance Spirit Guide case 13117: // Horde Spirit Guide { flags2 |= 0x10000000; }break; } if(static_cast<Unit*>(this)->GetAIInterface()->IsFlying()) // flags2 |= 0x800; //in 2.3 this is some state that i was not able to decode yet flags2 |= 0x400; //Zack : Teribus the Cursed had flag 400 instead of 800 and he is flying all the time if(static_cast<Creature*>(this)->proto && static_cast<Creature*>(this)->proto->extra_a9_flags) { if(!(flags2 & 0x0200)) flags2 |= static_cast<Creature*>(this)->proto->extra_a9_flags; } /* if(GetGUIDHigh() == HIGHGUID_WAYPOINT) { if(GetUInt32Value(UNIT_FIELD_STAT0) == 768) // flying waypoint flags2 |= 0x800; }*/ } *data << (uint32)flags2; *data << (uint8)0; *data << getMSTime(); // this appears to be time in ms but can be any thing // this stuff: // 0x01 -> Enable Swimming? // 0x04 -> ?? // 0x10 -> disables movement compensation and causes players to jump around all the place // 0x40 -> disables movement compensation and causes players to jump around all the place /*static uint8 fl = 0x04; *data << uint8(fl); // wtf? added in 2.3.0*/ /*if(target==this) *data<<uint8(0x53); else *data<<uint8(0);*/ //*data << uint8(0x1); } if (flags & 0x40) { if(flags & 0x2) { *data << (float)m_position.x; *data << (float)m_position.y; *data << (float)m_position.z; *data << (float)m_position.o; } else { *data << m_position; *data << m_position.o; } if(flags & 0x20 && flags2 & 0x0200) { if(pThis) { *data << pThis->m_TransporterGUID; *data << pThis->m_TransporterX << pThis->m_TransporterY << pThis->m_TransporterZ << pThis->m_TransporterO; *data << pThis->m_TransporterUnk; } else if(m_objectTypeId==TYPEID_UNIT && ((Creature*)this)->m_transportPosition != NULL) { *data << ((Creature*)this)->m_transportGuid; *data << uint32(HIGHGUID_TYPE_TRANSPORTER); *data << ((Creature*)this)->m_transportPosition->x << ((Creature*)this)->m_transportPosition->y << ((Creature*)this)->m_transportPosition->z << ((Creature*)this)->m_transportPosition->o; *data << float(0.0f); } } } if (flags & 0x20) { *data << (uint32)0; } if (flags & 0x20 && flags2 & 0x2000) { *data << (float)0; *data << (float)1.0; *data << (float)0; *data << (float)0; } if (flags & 0x20) { *data << m_walkSpeed; // walk speed *data << m_runSpeed; // run speed *data << m_backWalkSpeed; // backwards walk speed *data << m_swimSpeed; // swim speed *data << m_backSwimSpeed; // backwards swim speed *data << m_flySpeed; // fly speed *data << m_backFlySpeed; // back fly speed *data << m_turnRate; // turn rate } if(splinebuf) { data->append(*splinebuf); delete splinebuf; } if(flags & 0x8) { *data << GetUInt32Value(OBJECT_FIELD_GUID); if(flags & 0x10) *data << GetUInt32Value(OBJECT_FIELD_GUID_01); } else if(flags & 0x10) *data << GetUInt32Value(OBJECT_FIELD_GUID); if(flags & 0x2) { if(target) { /*int32 m_time = TimeStamp() - target->GetSession()->m_clientTimeDelay; m_time += target->GetSession()->m_moveDelayTime; *data << m_time;*/ *data << getMSTime(); } else *data << getMSTime(); } } //======================================================================================= // Creates an update block with the values of this object as // determined by the updateMask. //======================================================================================= void Object::_BuildValuesUpdate(ByteBuffer * data, UpdateMask *updateMask, Player* target) { bool reset = false; if(updateMask->GetBit(OBJECT_FIELD_GUID) && target) // We're creating. { Creature *pThis = TO_CREATURE(this); if(m_objectTypeId == TYPEID_UNIT && pThis->m_taggingPlayer) // tagged group will have tagged player { // set tagged visual if( (pThis->m_taggingGroup != 0 && target->m_playerInfo->m_Group != NULL && target->m_playerInfo->m_Group->GetID() == pThis->m_taggingGroup) || (pThis->m_taggingPlayer == target->GetLowGUID()) ) { m_uint32Values[UNIT_DYNAMIC_FLAGS] |= U_DYN_FLAG_TAPPED_BY_PLAYER; if( pThis->m_loot.HasItems() ) m_uint32Values[UNIT_DYNAMIC_FLAGS] |= U_DYN_FLAG_LOOTABLE; } else { m_uint32Values[UNIT_DYNAMIC_FLAGS] |= U_DYN_FLAG_TAGGED_BY_OTHER; } updateMask->SetBit(UNIT_DYNAMIC_FLAGS); reset = true; } if(target && GetTypeId() == TYPEID_GAMEOBJECT) { GameObject *go = ((GameObject*)this); GameObjectInfo *info; info = go->GetInfo(); if(info->InvolvedQuestCount && info->InvolvedQuestIds[0]) { for(uint32 v = 0; v < info->InvolvedQuestCount; ++v) { if( target->GetQuestLogForEntry(info->InvolvedQuestIds[v]) != NULL ) { m_uint32Values[GAMEOBJECT_DYN_FLAGS] = GO_DYNFLAG_QUEST; m_uint32Values[GAMEOBJECT_STATE] = 1; m_uint32Values[GAMEOBJECT_FLAGS] &= ~GO_FLAG_IN_USE; updateMask->SetBit(GAMEOBJECT_STATE); updateMask->SetBit(GAMEOBJECT_DYN_FLAGS); reset = true; break; } } } } } WPAssert( updateMask && updateMask->GetCount() == m_valuesCount ); uint32 bc; uint32 values_count; if( m_valuesCount > ( 2 * 0x20 ) )//if number of blocks > 2-> unit and player+item container { bc = updateMask->GetUpdateBlockCount(); values_count = (uint32)min( bc * 32, m_valuesCount ); } else { bc=updateMask->GetBlockCount(); values_count=m_valuesCount; } *data << (uint8)bc; data->append( updateMask->GetMask(), bc*4 ); for( uint32 index = 0; index < values_count; index ++ ) { if( updateMask->GetBit( index ) ) { switch(index) { case UNIT_FIELD_MAXHEALTH: { if(m_valuesCount < UNIT_END) *data << m_uint32Values[index]; else { switch(m_objectTypeId) { case TYPEID_PLAYER: *data << m_uint32Values[index]; break; case TYPEID_UNIT: { if(IsPet()) { *data << m_uint32Values[index]; break; } else { *data << (uint32)100; } } } } } break; case UNIT_FIELD_HEALTH: { if(m_valuesCount < UNIT_END) *data << m_uint32Values[index]; else { switch(m_objectTypeId) { case TYPEID_PLAYER: *data << m_uint32Values[index]; break; case TYPEID_UNIT: { if(IsPet()) { *data << m_uint32Values[index]; break; } else { uint32 pct = uint32(float( float(m_uint32Values[index]) / float(m_uint32Values[UNIT_FIELD_MAXHEALTH]) * 100.0f)); /* fix case where health value got rounded down and the client sees health as dead */ if(!pct && m_uint32Values[UNIT_FIELD_HEALTH] != 0) ++pct; *data << pct; } } } } } break; default: *data << m_uint32Values[ index ]; break; } } } if(reset) { switch(GetTypeId()) { case TYPEID_UNIT: m_uint32Values[UNIT_DYNAMIC_FLAGS] &= ~(U_DYN_FLAG_TAGGED_BY_OTHER | U_DYN_FLAG_LOOTABLE | U_DYN_FLAG_TAPPED_BY_PLAYER); break; case TYPEID_GAMEOBJECT: m_uint32Values[GAMEOBJECT_DYN_FLAGS] = 0; m_uint32Values[GAMEOBJECT_FLAGS] |= GO_FLAG_IN_USE; m_uint32Values[GAMEOBJECT_STATE] = 0; break; } } } void Object::BuildHeartBeatMsg(WorldPacket *data) const { data->Initialize(MSG_MOVE_HEARTBEAT); *data << GetGUID(); *data << uint32(0); // flags *data << uint32(0); // mysterious value #1 *data << m_position; *data << m_position.o; } WorldPacket * Object::BuildTeleportAckMsg(const LocationVector & v) { /////////////////////////////////////// //Update player on the client with TELEPORT_ACK if( IsInWorld() ) // only send when inworld static_cast< Player* >( this )->SetPlayerStatus( TRANSFER_PENDING ); WorldPacket * data = new WorldPacket(MSG_MOVE_TELEPORT_ACK, 80); *data << GetNewGUID(); //First 4 bytes = no idea what it is *data << uint32(2); // flags *data << uint32(0); // mysterious value #1 *data << uint8(0); *data << float(0); *data << v; *data << v.o; *data << uint16(2); *data << uint8(0); return data; } bool Object::SetPosition(const LocationVector & v, bool allowPorting /* = false */) { bool updateMap = false, result = true; if (m_position.x != v.x || m_position.y != v.y) updateMap = true; m_position = const_cast<LocationVector&>(v); if (!allowPorting && v.z < -500) { m_position.z = 500; DEBUG_LOG( "setPosition: fell through map; height ported" ); result = false; } if (IsInWorld() && updateMap) { m_mapMgr->ChangeObjectLocation(this); } return result; } bool Object::SetPosition( float newX, float newY, float newZ, float newOrientation, bool allowPorting ) { bool updateMap = false, result = true; //if (m_position.x != newX || m_position.y != newY) //updateMap = true; if(m_lastMapUpdatePosition.Distance2DSq(newX, newY) > 4.0f) /* 2.0f */ updateMap = true; m_position.ChangeCoords(newX, newY, newZ, newOrientation); if (!allowPorting && newZ < -500) { m_position.z = 500; DEBUG_LOG( "setPosition: fell through map; height ported" ); result = false; } if (IsInWorld() && updateMap) { m_lastMapUpdatePosition.ChangeCoords(newX,newY,newZ,newOrientation); m_mapMgr->ChangeObjectLocation(this); if( m_objectTypeId == TYPEID_PLAYER && static_cast< Player* >( this )->GetGroup() && static_cast< Player* >( this )->m_last_group_position.Distance2DSq(m_position) > 25.0f ) // distance of 5.0 { static_cast< Player* >( this )->GetGroup()->HandlePartialChange( PARTY_UPDATE_FLAG_POSITION, static_cast< Player* >( this ) ); } } return result; } void Object::SetRotation( uint64 guid ) { WorldPacket data(SMSG_AI_REACTION, 12); data << guid; data << uint32(2); SendMessageToSet(&data, false); } void Object::OutPacketToSet(uint16 Opcode, uint16 Len, const void * Data, bool self) { if(self && m_objectTypeId == TYPEID_PLAYER) static_cast< Player* >( this )->GetSession()->OutPacket(Opcode, Len, Data); if(!IsInWorld()) return; std::set<Player*>::iterator itr = m_inRangePlayers.begin(); std::set<Player*>::iterator it_end = m_inRangePlayers.end(); int gm = ( m_objectTypeId == TYPEID_PLAYER ? static_cast< Player* >( this )->m_isGmInvisible : 0 ); for(; itr != it_end; ++itr) { ASSERT((*itr)->GetSession()); if( gm ) { if( (*itr)->GetSession()->GetPermissionCount() > 0 ) (*itr)->GetSession()->OutPacket(Opcode, Len, Data); } else { (*itr)->GetSession()->OutPacket(Opcode, Len, Data); } } } void Object::SendMessageToSet(WorldPacket *data, bool bToSelf,bool myteam_only) { if(bToSelf && m_objectTypeId == TYPEID_PLAYER) { static_cast< Player* >( this )->GetSession()->SendPacket(data); } if(!IsInWorld()) return; std::set<Player*>::iterator itr = m_inRangePlayers.begin(); std::set<Player*>::iterator it_end = m_inRangePlayers.end(); bool gminvis = (m_objectTypeId == TYPEID_PLAYER ? static_cast< Player* >( this )->m_isGmInvisible : false); //Zehamster: Splitting into if/else allows us to avoid testing "gminvis==true" at each loop... // saving cpu cycles. Chat messages will be sent to everybody even if player is invisible. if(myteam_only) { uint32 myteam=static_cast< Player* >( this )->GetTeam(); if(gminvis && data->GetOpcode()!=SMSG_MESSAGECHAT) { for(; itr != it_end; ++itr) { ASSERT((*itr)->GetSession()); if((*itr)->GetSession()->GetPermissionCount() > 0 && (*itr)->GetTeam()==myteam) (*itr)->GetSession()->SendPacket(data); } } else { for(; itr != it_end; ++itr) { ASSERT((*itr)->GetSession()); if((*itr)->GetTeam()==myteam) (*itr)->GetSession()->SendPacket(data); } } } else { if(gminvis && data->GetOpcode()!=SMSG_MESSAGECHAT) { for(; itr != it_end; ++itr) { ASSERT((*itr)->GetSession()); if((*itr)->GetSession()->GetPermissionCount() > 0) (*itr)->GetSession()->SendPacket(data); } } else { for(; itr != it_end; ++itr) { ASSERT((*itr)->GetSession()); (*itr)->GetSession()->SendPacket(data); } } } } //////////////////////////////////////////////////////////////////////////// /// Fill the object's Update Values from a space deliminated list of values. void Object::LoadValues(const char* data) { // thread-safe ;) strtok is not. std::string ndata = data; std::string::size_type last_pos = 0, pos = 0; uint32 index = 0; uint32 val; do { // prevent overflow if(index >= m_valuesCount) { break; } pos = ndata.find(" ", last_pos); val = atol(ndata.substr(last_pos, (pos-last_pos)).c_str()); if(m_uint32Values[index] == 0) m_uint32Values[index] = val; last_pos = pos+1; ++index; } while(pos != std::string::npos); } void Object::_SetUpdateBits(UpdateMask *updateMask, Player *target) const { *updateMask = m_updateMask; } void Object::_SetCreateBits(UpdateMask *updateMask, Player *target) const { /*for( uint16 index = 0; index < m_valuesCount; index++ ) { if(GetUInt32Value(index) != 0) updateMask->SetBit(index); }*/ for(uint32 i = 0; i < m_valuesCount; ++i) if(m_uint32Values[i] != 0) updateMask->SetBit(i); } void Object::AddToWorld() { MapMgr *mapMgr = sInstanceMgr.GetInstance(this); if(!mapMgr) return; //instance add failed if( IsPlayer() ) { // battleground checks Player *p = TO_PLAYER(this); if( p->m_bg == NULL && mapMgr->m_battleground != NULL ) { // player hasn't been registered in the battleground, ok. // that means we re-logged into one. if it's an arena, don't allow it! // also, don't allow them in if the bg is full. if( /*( mapMgr->m_battleground->IsArena() && mapMgr->m_battleground->HasStarted() ) ||*/ ( !mapMgr->m_battleground->CanPlayerJoin(p) ) && !p->bGMTagOn ) // above check isn't needed, done in Arena::CanPlayerJoin. { //p->EjectFromInstance(); return; } } } m_mapMgr = mapMgr; m_inQueue = true; mapMgr->AddObject(this); // correct incorrect instance id's m_instanceId = m_mapMgr->GetInstanceID(); mSemaphoreTeleport = false; } void Object::AddToWorld(MapMgr * pMapMgr) { if(!pMapMgr) return; //instance add failed m_mapMgr = pMapMgr; m_inQueue = true; pMapMgr->AddObject(this); // correct incorrect instance id's m_instanceId = pMapMgr->GetInstanceID(); mSemaphoreTeleport = false; } //Unlike addtoworld it pushes it directly ignoring add pool //this can only be called from the thread of mapmgr!!! void Object::PushToWorld(MapMgr*mgr) { if(!mgr/* || (m_mapMgr != NULL && m_mapCell != NULL) */) return; //instance add failed m_mapId=mgr->GetMapId(); m_instanceId = mgr->GetInstanceID(); m_mapMgr = mgr; OnPrePushToWorld(); mgr->PushObject(this); // correct incorrect instance id's mSemaphoreTeleport = false; m_inQueue = false; event_Relocate(); // call virtual function to handle stuff.. :P OnPushToWorld(); } void Object::RemoveFromWorld(bool free_guid) { // clear loot ClearLoot(); ASSERT(m_mapMgr); MapMgr * m = m_mapMgr; m_mapMgr = 0; mSemaphoreTeleport = true; m->RemoveObject(this, free_guid); // remove any spells / free memory sEventMgr.RemoveEvents(this, EVENT_UNIT_SPELL_HIT); // update our event holder event_Relocate(); } //! Set uint32 property void Object::SetUInt32Value( const uint32 index, const uint32 value ) { ASSERT( index < m_valuesCount ); // save updating when val isn't changing. if(m_uint32Values[index] == value) return; m_uint32Values[ index ] = value; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } // Group update handling if(m_objectTypeId == TYPEID_PLAYER) { if(IsInWorld()) { Group* pGroup = static_cast< Player* >( this )->GetGroup(); if( pGroup != NULL ) pGroup->HandleUpdateFieldChange( index, static_cast< Player* >( this ) ); } #ifdef OPTIMIZED_PLAYER_SAVING switch(index) { case UNIT_FIELD_LEVEL: case PLAYER_XP: static_cast< Player* >( this )->save_LevelXP(); break; case PLAYER_FIELD_COINAGE: static_cast< Player* >( this )->save_Gold(); break; } #endif } } /* //must be in % void Object::ModPUInt32Value(const uint32 index, const int32 value, bool apply ) { ASSERT( index < m_valuesCount ); int32 basevalue = (int32)m_uint32Values[ index ]; if(apply) m_uint32Values[ index ] += ((basevalue*value)/100); else m_uint32Values[ index ] = (basevalue*100)/(100+value); if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated ) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } */ uint32 Object::GetModPUInt32Value(const uint32 index, const int32 value) { ASSERT( index < m_valuesCount ); int32 basevalue = (int32)m_uint32Values[ index ]; return ((basevalue*value)/100); } void Object::ModUnsigned32Value(uint32 index, int32 mod) { ASSERT( index < m_valuesCount ); if(mod == 0) return; m_uint32Values[ index ] += mod; if( (int32)m_uint32Values[index] < 0 ) m_uint32Values[index] = 0; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } if(m_objectTypeId == TYPEID_PLAYER) { #ifdef OPTIMIZED_PLAYER_SAVING switch(index) { case UNIT_FIELD_LEVEL: case PLAYER_XP: static_cast< Player* >( this )->save_LevelXP(); break; case PLAYER_FIELD_COINAGE: static_cast< Player* >( this )->save_Gold(); break; } #endif } } void Object::ModSignedInt32Value(uint32 index, int32 value ) { ASSERT( index < m_valuesCount ); if(value == 0) return; m_uint32Values[ index ] += value; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } if(m_objectTypeId == TYPEID_PLAYER) { #ifdef OPTIMIZED_PLAYER_SAVING switch(index) { case UNIT_FIELD_LEVEL: case PLAYER_XP: static_cast< Player* >( this )->save_LevelXP(); break; case PLAYER_FIELD_COINAGE: static_cast< Player* >( this )->save_Gold(); break; } #endif } } void Object::ModFloatValue(const uint32 index, const float value ) { ASSERT( index < m_valuesCount ); m_floatValues[ index ] += value; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } //! Set uint64 property void Object::SetUInt64Value( const uint32 index, const uint64 value ) { assert( index + 1 < m_valuesCount ); if(m_uint32Values[index] == GUID_LOPART(value) && m_uint32Values[index+1] == GUID_HIPART(value)) return; m_uint32Values[ index ] = *((uint32*)&value); m_uint32Values[ index + 1 ] = *(((uint32*)&value) + 1); if(IsInWorld()) { m_updateMask.SetBit( index ); m_updateMask.SetBit( index + 1 ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } //! Set float property void Object::SetFloatValue( const uint32 index, const float value ) { ASSERT( index < m_valuesCount ); if(m_floatValues[index] == value) return; m_floatValues[ index ] = value; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } void Object::SetFlag( const uint32 index, uint32 newFlag ) { ASSERT( index < m_valuesCount ); //no change -> no update if((m_uint32Values[ index ] & newFlag)==newFlag) return; m_uint32Values[ index ] |= newFlag; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } void Object::RemoveFlag( const uint32 index, uint32 oldFlag ) { ASSERT( index < m_valuesCount ); //no change -> no update if((m_uint32Values[ index ] & oldFlag)==0) return; m_uint32Values[ index ] &= ~oldFlag; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } //////////////////////////////////////////////////////////// float Object::CalcDistance(Object *Ob) { return CalcDistance(this->GetPositionX(), this->GetPositionY(), this->GetPositionZ(), Ob->GetPositionX(), Ob->GetPositionY(), Ob->GetPositionZ()); } float Object::CalcDistance(float ObX, float ObY, float ObZ) { return CalcDistance(this->GetPositionX(), this->GetPositionY(), this->GetPositionZ(), ObX, ObY, ObZ); } float Object::CalcDistance(Object *Oa, Object *Ob) { return CalcDistance(Oa->GetPositionX(), Oa->GetPositionY(), Oa->GetPositionZ(), Ob->GetPositionX(), Ob->GetPositionY(), Ob->GetPositionZ()); } float Object::CalcDistance(Object *Oa, float ObX, float ObY, float ObZ) { return CalcDistance(Oa->GetPositionX(), Oa->GetPositionY(), Oa->GetPositionZ(), ObX, ObY, ObZ); } float Object::CalcDistance(float OaX, float OaY, float OaZ, float ObX, float ObY, float ObZ) { float xdest = OaX - ObX; float ydest = OaY - ObY; float zdest = OaZ - ObZ; return sqrtf(zdest*zdest + ydest*ydest + xdest*xdest); } float Object::calcAngle( float Position1X, float Position1Y, float Position2X, float Position2Y ) { float dx = Position2X-Position1X; float dy = Position2Y-Position1Y; double angle=0.0f; // Calculate angle if (dx == 0.0) { if (dy == 0.0) angle = 0.0; else if (dy > 0.0) angle = M_PI * 0.5 /* / 2 */; else angle = M_PI * 3.0 * 0.5/* / 2 */; } else if (dy == 0.0) { if (dx > 0.0) angle = 0.0; else angle = M_PI; } else { if (dx < 0.0) angle = atanf(dy/dx) + M_PI; else if (dy < 0.0) angle = atanf(dy/dx) + (2*M_PI); else angle = atanf(dy/dx); } // Convert to degrees angle = angle * float(180 / M_PI); // Return return float(angle); } float Object::calcRadAngle( float Position1X, float Position1Y, float Position2X, float Position2Y ) { double dx = double(Position2X-Position1X); double dy = double(Position2Y-Position1Y); double angle=0.0; // Calculate angle if (dx == 0.0) { if (dy == 0.0) angle = 0.0; else if (dy > 0.0) angle = M_PI * 0.5/*/ 2.0*/; else angle = M_PI * 3.0 * 0.5/*/ 2.0*/; } else if (dy == 0.0) { if (dx > 0.0) angle = 0.0; else angle = M_PI; } else { if (dx < 0.0) angle = atan(dy/dx) + M_PI; else if (dy < 0.0) angle = atan(dy/dx) + (2*M_PI); else angle = atan(dy/dx); } // Return return float(angle); } float Object::getEasyAngle( float angle ) { while ( angle < 0 ) { angle = angle + 360; } while ( angle >= 360 ) { angle = angle - 360; } return angle; } bool Object::inArc(float Position1X, float Position1Y, float FOV, float Orientation, float Position2X, float Position2Y ) { float angle = calcAngle( Position1X, Position1Y, Position2X, Position2Y ); float lborder = getEasyAngle( ( Orientation - (FOV*0.5f/*/2*/) ) ); float rborder = getEasyAngle( ( Orientation + (FOV*0.5f/*/2*/) ) ); //DEBUG_LOG("Orientation: %f Angle: %f LeftBorder: %f RightBorder %f",Orientation,angle,lborder,rborder); if(((angle >= lborder) && (angle <= rborder)) || ((lborder > rborder) && ((angle < rborder) || (angle > lborder)))) { return true; } else { return false; } } bool Object::isInFront(Object* target) { // check if we facing something ( is the object within a 180 degree slice of our positive y axis ) double x = target->GetPositionX() - m_position.x; double y = target->GetPositionY() - m_position.y; double angle = atan2( y, x ); angle = ( angle >= 0.0 ) ? angle : 2.0 * M_PI + angle; angle -= m_position.o; while( angle > M_PI) angle -= 2.0 * M_PI; while(angle < -M_PI) angle += 2.0 * M_PI; // replace M_PI in the two lines below to reduce or increase angle double left = -1.0 * ( M_PI / 2.0 ); double right = ( M_PI / 2.0 ); return( ( angle >= left ) && ( angle <= right ) ); } bool Object::isInBack(Object* target) { // check if we are behind something ( is the object within a 180 degree slice of our negative y axis ) double x = m_position.x - target->GetPositionX(); double y = m_position.y - target->GetPositionY(); double angle = atan2( y, x ); angle = ( angle >= 0.0 ) ? angle : 2.0 * M_PI + angle; // if we are a unit and have a UNIT_FIELD_TARGET then we are always facing them if( m_objectTypeId == TYPEID_UNIT && m_uint32Values[UNIT_FIELD_TARGET] != 0 && static_cast< Unit* >( this )->GetAIInterface()->GetNextTarget() ) { Unit* pTarget = static_cast< Unit* >( this )->GetAIInterface()->GetNextTarget(); angle -= double( Object::calcRadAngle( target->m_position.x, target->m_position.y, pTarget->m_position.x, pTarget->m_position.y ) ); } else angle -= target->GetOrientation(); while( angle > M_PI) angle -= 2.0 * M_PI; while(angle < -M_PI) angle += 2.0 * M_PI; // replace M_H_PI in the two lines below to reduce or increase angle double left = -1.0 * ( M_H_PI / 2.0 ); double right = ( M_H_PI / 2.0 ); return( ( angle <= left ) && ( angle >= right ) ); } bool Object::isInArc(Object* target , float angle) // angle in degrees { return inArc( GetPositionX() , GetPositionY() , angle , GetOrientation() , target->GetPositionX() , target->GetPositionY() ); } bool Object::isInRange(Object* target, float range) { float dist = CalcDistance( target ); return( dist <= range ); } bool Object::IsPet() { if( this->GetTypeId() != TYPEID_UNIT ) return false; if( static_cast< Unit* >( this )->m_isPet && m_uint32Values[UNIT_FIELD_CREATEDBY] != 0 && m_uint32Values[UNIT_FIELD_SUMMONEDBY] != 0 ) return true; return false; } void Object::_setFaction() { FactionTemplateDBC* factT = NULL; if(GetTypeId() == TYPEID_UNIT || GetTypeId() == TYPEID_PLAYER) { factT = dbcFactionTemplate.LookupEntry(GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE)); } else if(GetTypeId() == TYPEID_GAMEOBJECT) { factT = dbcFactionTemplate.LookupEntry(GetUInt32Value(GAMEOBJECT_FACTION)); } if(!factT) { return; } m_faction = factT; m_factionDBC = dbcFaction.LookupEntry(factT->Faction); } void Object::UpdateOppFactionSet() { m_oppFactsInRange.clear(); for(Object::InRangeSet::iterator i = GetInRangeSetBegin(); i != GetInRangeSetEnd(); ++i) { if (((*i)->GetTypeId() == TYPEID_UNIT) || ((*i)->GetTypeId() == TYPEID_PLAYER) || ((*i)->GetTypeId() == TYPEID_GAMEOBJECT)) { if (isHostile(this, (*i))) { if(!(*i)->IsInRangeOppFactSet(this)) (*i)->m_oppFactsInRange.insert(this); if (!IsInRangeOppFactSet((*i))) m_oppFactsInRange.insert((*i)); } else { if((*i)->IsInRangeOppFactSet(this)) (*i)->m_oppFactsInRange.erase(this); if (IsInRangeOppFactSet((*i))) m_oppFactsInRange.erase((*i)); } } } } void Object::EventSetUInt32Value(uint32 index, uint32 value) { SetUInt32Value(index,value); } void Object::DealDamage(Unit *pVictim, uint32 damage, uint32 targetEvent, uint32 unitEvent, uint32 spellId, bool no_remove_auras) { Player* plr = 0; if( !pVictim || !pVictim->isAlive() || !pVictim->IsInWorld() || !IsInWorld() ) return; if( pVictim->GetTypeId() == TYPEID_PLAYER && static_cast< Player* >( pVictim )->GodModeCheat == true ) return; if( pVictim->IsSpiritHealer() ) return; if( pVictim->GetStandState() )//not standing-> standup { pVictim->SetStandState( STANDSTATE_STAND );//probably mobs also must standup } // This one is easy. If we're attacking a hostile target, and we're not flagged, flag us. // Also, you WONT get flagged if you are dueling that person - FiShBaIt if( pVictim->IsPlayer() && IsPlayer() ) { if( isHostile( this, pVictim ) && static_cast< Player* >( pVictim )->DuelingWith != static_cast< Player* >( this ) ) static_cast< Player* >( this )->SetPvPFlag(); } //If our pet attacks - flag us. if( pVictim->IsPlayer() && IsPet() ) { Player* owner = static_cast< Player* >( static_cast< Pet* >( this )->GetPetOwner() ); if( owner != NULL ) if( owner->isAlive() && static_cast< Player* >( pVictim )->DuelingWith != owner ) owner->SetPvPFlag(); } if(!no_remove_auras) { //zack 2007 04 24 : root should not remove self (and also other unknown spells) if(spellId) { pVictim->RemoveAurasByInterruptFlagButSkip(AURA_INTERRUPT_ON_ANY_DAMAGE_TAKEN,spellId); if(Rand(35.0f)) pVictim->RemoveAurasByInterruptFlagButSkip(AURA_INTERRUPT_ON_UNUSED2,spellId); } else { pVictim->RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_ANY_DAMAGE_TAKEN); if(Rand(35.0f)) pVictim->RemoveAurasByInterruptFlag(AURA_INTERRUPT_ON_UNUSED2); } } if(this->IsUnit()) { /* if(!pVictim->isInCombat() && pVictim->IsPlayer()) sHookInterface.OnEnterCombat( static_cast< Player* >( pVictim ), static_cast< Unit* >( this ) ); if(IsPlayer() && ! static_cast< Player* >( this )->isInCombat()) sHookInterface.OnEnterCombat( static_cast< Player* >( this ), static_cast< Player* >( this ) );*/ //the black sheep , no actually it is paladin : Ardent Defender if(static_cast<Unit*>(this)->DamageTakenPctModOnHP35 && HasFlag(UNIT_FIELD_AURASTATE , AURASTATE_FLAG_HEALTH35) ) damage = damage - float2int32(damage * static_cast<Unit*>(this)->DamageTakenPctModOnHP35) / 100 ; if(IsPet()) plr = static_cast<Pet*>(this)->GetPetOwner(); else if(IsPlayer()) plr = static_cast< Player* >( this ); if(plr != NULL && plr->GetTypeId() == TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_UNIT) // Units can't tag.. TO_CREATURE(pVictim)->Tag(plr); if( pVictim != this ) { // Set our attack target to the victim. static_cast< Unit* >( this )->CombatStatus.OnDamageDealt( pVictim, damage ); } } ///Rage float val; if( pVictim->GetPowerType() == POWER_TYPE_RAGE && pVictim != this && pVictim->IsPlayer()) { float level = (float)pVictim->getLevel(); float c = 0.0091107836f * level * level + 3.225598133f * level + 4.2652911f; uint32 rage = pVictim->GetUInt32Value( UNIT_FIELD_POWER2 ); val = 2.5f * damage / c; rage += float2int32(val) * 10; if( rage > pVictim->GetUInt32Value(UNIT_FIELD_MAXPOWER2) ) rage = pVictim->GetUInt32Value(UNIT_FIELD_MAXPOWER2); pVictim->SetUInt32Value(UNIT_FIELD_POWER2, rage); } if( pVictim->IsPlayer() ) { Player *pThis = static_cast< Player* >(pVictim); if(pThis->cannibalize) { sEventMgr.RemoveEvents(pVictim, EVENT_CANNIBALIZE); pThis->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); pThis->cannibalize = false; } } //* BATTLEGROUND DAMAGE COUNTER *// if( pVictim != this ) { if( IsPlayer() ) { plr = static_cast< Player* >( this ); } else if( IsPet() ) { plr = static_cast< Pet* >( this )->GetPetOwner(); if( plr != NULL && plr->GetMapMgr() == GetMapMgr() ) plr = NULL; } if( plr != NULL && plr->m_bg != NULL && plr->GetMapMgr() == GetMapMgr() ) { plr->m_bgScore.DamageDone += damage; plr->m_bg->UpdatePvPData(); } } uint32 health = pVictim->GetUInt32Value(UNIT_FIELD_HEALTH ); if(health <= damage && pVictim->IsPlayer() && pVictim->getClass() == ROGUE && TO_PLAYER(pVictim)->m_lastCheatDeath + 60000 < (uint32)UNIXTIME) { Player * plrVictim = TO_PLAYER(pVictim); uint32 rank = plrVictim->m_cheatDeathRank; uint32 chance = rank == 3 ? 100 : rank * 33; if(Rand(chance)) { // Proc that cheating death! SpellEntry *spellInfo = dbcSpell.LookupEntry(45182); Spell *spell = new Spell(pVictim,spellInfo,true,NULL); SpellCastTargets targets; targets.m_unitTarget = pVictim->GetGUID(); spell->prepare(&targets); TO_PLAYER(pVictim)->m_lastCheatDeath = (uint32)UNIXTIME; // Why return? So this damage isn't counted. ;) // On official, it seems Blizzard applies it's Cheating Death school absorb aura for 1 msec, but it's too late // for us by now. return; } } /*------------------------------------ DUEL HANDLERS --------------------------*/ if((pVictim->IsPlayer()) && (this->IsPlayer()) && static_cast< Player* >(pVictim)->DuelingWith == static_cast< Player* >( this ) ) //Both Players { if((health <= damage) && static_cast< Player* >( this )->DuelingWith != NULL) { //Player in Duel and Player Victim has lost uint32 NewHP = pVictim->GetUInt32Value(UNIT_FIELD_MAXHEALTH)/100; if(NewHP < 5) NewHP = 5; //Set there health to 1% or 5 if 1% is lower then 5 pVictim->SetUInt32Value(UNIT_FIELD_HEALTH, NewHP); //End Duel static_cast< Player* >( this )->EndDuel(DUEL_WINNER_KNOCKOUT); // surrender emote pVictim->Emote(EMOTE_ONESHOT_BEG); // Animation return; } } if((pVictim->IsPlayer()) && (IsPet())) { if((health <= damage) && static_cast< Player* >(pVictim)->DuelingWith == static_cast<Pet*>(this)->GetPetOwner()) { Player *petOwner = static_cast<Pet*>(this)->GetPetOwner(); if(petOwner) { //Player in Duel and Player Victim has lost uint32 NewHP = pVictim->GetUInt32Value(UNIT_FIELD_MAXHEALTH)/100; if(NewHP < 5) NewHP = 5; //Set there health to 1% or 5 if 1% is lower then 5 pVictim->SetUInt32Value(UNIT_FIELD_HEALTH, NewHP); //End Duel petOwner->EndDuel(DUEL_WINNER_KNOCKOUT); return; } } } /*------------------------------------ DUEL HANDLERS END--------------------------*/ bool isCritter = false; if(pVictim->GetTypeId() == TYPEID_UNIT && ((Creature*)pVictim)->GetCreatureName()) { if(((Creature*)pVictim)->GetCreatureName()->Type == CRITTER) isCritter = true; } /* ------------------------------- DAMAGE BUG DETECTION -------------------------------*/ //ASSERT(damage <= 60000); if( IsPlayer() && damage >= 60000 && !TO_PLAYER(this)->GetSession()->HasGMPermissions() ) { TO_PLAYER(this)->BroadcastMessage("Attempting to deal %u damage, we are not allowing this. If this problem persists, please contact Burlex. If you have any information on reproducing this problem, it would be very helpful.", damage); return; } /* -------------------------- HIT THAT CAUSES VICTIM TO DIE ---------------------------*/ if ((isCritter || health <= damage) ) { //warlock - seed of corruption if( IsUnit() ) { if( IsPlayer() && pVictim->IsUnit() && !pVictim->IsPlayer() && m_mapMgr->m_battleground && m_mapMgr->m_battleground->GetType() == BATTLEGROUND_ALTERAC_VALLEY ) static_cast<AlteracValley*>(m_mapMgr->m_battleground)->HookOnUnitKill( TO_PLAYER(this), pVictim ); SpellEntry *killerspell; if( spellId ) killerspell = dbcSpell.LookupEntry( spellId ); else killerspell = NULL; pVictim->HandleProc( PROC_ON_DIE, static_cast< Unit* >( this ), killerspell ); pVictim->m_procCounter = 0; static_cast< Unit* >( this )->HandleProc( PROC_ON_TARGET_DIE, pVictim, killerspell ); static_cast< Unit* >( this )->m_procCounter = 0; } // check if pets owner is combat participant bool owner_participe = false; if( IsPet() ) { Player* owner = static_cast<Pet*>( this )->GetPetOwner(); if( owner != NULL && pVictim->GetAIInterface()->getThreatByPtr( owner ) > 0 ) owner_participe = true; } /* victim died! */ if( pVictim->IsPlayer() ) static_cast< Player* >( pVictim )->KillPlayer(); else { pVictim->setDeathState( JUST_DIED ); pVictim->GetAIInterface()->HandleEvent( EVENT_LEAVECOMBAT, static_cast< Unit* >( this ), 0); } if( pVictim->IsPlayer() && (!IsPlayer() || pVictim == this ) ) { static_cast< Player* >( pVictim )->DeathDurabilityLoss(0.10); } /* Zone Under Attack */ MapInfo * pMapInfo = WorldMapInfoStorage.LookupEntry(GetMapId()); if( pMapInfo && pMapInfo->type == INSTANCE_NULL && !pVictim->IsPlayer() && !pVictim->IsPet() && ( IsPlayer() || IsPet() ) ) { // Only NPCs that bear the PvP flag can be truly representing their faction. if( ((Creature*)pVictim)->HasFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_PVP ) ) { Player * pAttacker = NULL; if( IsPet() ) pAttacker = static_cast< Pet* >( this )->GetPetOwner(); else if(IsPlayer()) pAttacker = static_cast< Player* >( this ); if( pAttacker != NULL) { uint8 teamId = (uint8)pAttacker->GetTeam(); if(teamId == 0) // Swap it. teamId = 1; else teamId = 0; uint32 AreaID = pVictim->GetMapMgr()->GetAreaID(pVictim->GetPositionX(), pVictim->GetPositionY()); if(!AreaID) AreaID = pAttacker->GetZoneId(); // Failsafe for a shitty TerrainMgr if(AreaID) { WorldPacket data(SMSG_ZONE_UNDER_ATTACK, 4); data << AreaID; sWorld.SendFactionMessage(&data, teamId); } } } } if(pVictim->GetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT) > 0) { if(pVictim->GetCurrentSpell()) { Spell *spl = pVictim->GetCurrentSpell(); for(int i = 0; i < 3; i++) { if(spl->m_spellInfo->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA) { DynamicObject *dObj = GetMapMgr()->GetDynamicObject(pVictim->GetUInt32Value(UNIT_FIELD_CHANNEL_OBJECT)); if(!dObj) return; WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8); data << dObj->GetGUID(); dObj->SendMessageToSet(&data, false); dObj->RemoveFromWorld(true); delete dObj; } } if(spl->m_spellInfo->ChannelInterruptFlags == 48140) spl->cancel(); } } /* Remove all Auras */ pVictim->DropAurasOnDeath(); /* Stop victim from attacking */ if( this->IsUnit() ) pVictim->smsg_AttackStop( static_cast< Unit* >( this ) ); if( pVictim->GetTypeId() == TYPEID_PLAYER ) static_cast< Player* >( pVictim )->EventAttackStop(); /* Set victim health to 0 */ pVictim->SetUInt32Value(UNIT_FIELD_HEALTH, 0); if(pVictim->IsPlayer()) { uint32 self_res_spell = static_cast< Player* >( pVictim )->SoulStone; static_cast< Player* >( pVictim )->SoulStone = static_cast< Player* >( pVictim )->SoulStoneReceiver = 0; if( !self_res_spell && static_cast< Player* >( pVictim )->bReincarnation ) { SpellEntry* m_reincarnSpellInfo = dbcSpell.LookupEntry( 20608 ); if( static_cast< Player* >( pVictim )->Cooldown_CanCast( m_reincarnSpellInfo ) ) { uint32 ankh_count = static_cast< Player* >( pVictim )->GetItemInterface()->GetItemCount( 17030 ); if( ankh_count ) self_res_spell = 21169; } } pVictim->SetUInt32Value( PLAYER_SELF_RES_SPELL, self_res_spell ); pVictim->SetUInt32Value( UNIT_FIELD_MOUNTDISPLAYID , 0 ); //pVictim->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI); } // Wipe our attacker set on death Unit * pKiller = pVictim->CombatStatus.GetKiller(); pVictim->CombatStatus.Vanished(); // sent to set. don't send it to the party, becuase if they're out of // range they won't know this guid exists -> possible 132. /*if (this->IsPlayer()) if( static_cast< Player* >( this )->InGroup() ) static_cast< Player* >( this )->GetGroup()->SendPartyKillLog( this, pVictim );*/ /* Stop Unit from attacking */ if( this->IsPlayer() ) static_cast< Player* >( this )->EventAttackStop(); if( this->IsUnit() ) { CALL_SCRIPT_EVENT( this, OnTargetDied )( pVictim ); static_cast< Unit* >( this )->smsg_AttackStop( pVictim ); /* Tell Unit that it's target has Died */ static_cast< Unit* >( this )->addStateFlag( UF_TARGET_DIED ); // We will no longer be attacking this target, as it's dead. //static_cast<Unit*>(this)->setAttackTarget(NULL); } //so now we are completely dead //lets see if we have spirit of redemption if( pVictim->IsPlayer() ) { if( static_cast< Player* >( pVictim)->HasSpell( 20711 ) ) //check for spirit of Redemption { SpellEntry* sorInfo = dbcSpell.LookupEntry(27827); if( sorInfo != NULL ) { Spell *sor = new Spell( pVictim, sorInfo, true, NULL ); SpellCastTargets targets; targets.m_unitTarget = pVictim->GetGUID(); sor->prepare(&targets); } } } /* -------------------------------- HONOR + BATTLEGROUND CHECKS ------------------------ */ plr = NULL; if( pKiller && pKiller->IsPlayer() ) plr = static_cast< Player* >( pKiller ); else if(pKiller && pKiller->IsPet()) plr = static_cast< Pet* >( pKiller )->GetPetOwner(); if( plr != NULL) { if( plr->m_bg != 0 ) plr->m_bg->HookOnPlayerKill( plr, pVictim ); if( pVictim->IsPlayer() ) { sHookInterface.OnKillPlayer( plr, static_cast< Player* >( pVictim ) ); if(plr->getLevel() > pVictim->getLevel()) { unsigned int diff = plr->getLevel() - pVictim->getLevel(); if( diff <= 8 ) { HonorHandler::OnPlayerKilledUnit(plr, pVictim); plr->SetFlag( UNIT_FIELD_AURASTATE, AURASTATE_FLAG_LASTKILLWITHHONOR ); } else plr->RemoveFlag( UNIT_FIELD_AURASTATE, AURASTATE_FLAG_LASTKILLWITHHONOR ); } else { HonorHandler::OnPlayerKilledUnit( plr, pVictim ); plr->SetFlag( UNIT_FIELD_AURASTATE, AURASTATE_FLAG_LASTKILLWITHHONOR ); } } else { // REPUTATION if( !isCritter ) plr->Reputation_OnKilledUnit( pVictim, false ); plr->RemoveFlag( UNIT_FIELD_AURASTATE, AURASTATE_FLAG_LASTKILLWITHHONOR ); } } /* -------------------------------- HONOR + BATTLEGROUND CHECKS END------------------------ */ uint64 victimGuid = pVictim->GetGUID(); // only execute loot code if we were tagged if( pVictim->GetTypeId() == TYPEID_UNIT && TO_CREATURE(pVictim)->m_taggingPlayer != 0 ) { // fill loot vector TO_CREATURE(pVictim)->GenerateLoot(); // update visual. TO_CREATURE(pVictim)->UpdateLootAnimation(); } // player loot for battlegrounds if( pVictim->GetTypeId() == TYPEID_PLAYER ) { // set skinning flag, this is the "remove insignia" if( TO_PLAYER(pVictim)->m_bg != NULL && TO_PLAYER(pVictim)->m_bg->SupportsPlayerLoot() ) { pVictim->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); TO_PLAYER(pVictim)->m_insigniaTaken = false; } } if(pVictim->GetTypeId() == TYPEID_UNIT) { pVictim->GetAIInterface()->OnDeath(this); if(GetTypeId() == TYPEID_PLAYER) { WorldPacket data(SMSG_PARTYKILLLOG, 16); data << GetGUID() << pVictim->GetGUID(); SendMessageToSet(&data, true); } // it Seems that pets some how dont get a name and cause a crash here //bool isCritter = (pVictim->GetCreatureName() != NULL)? pVictim->GetCreatureName()->Type : 0; //---------------------------------looot----------------------------------------- if( GetTypeId() == TYPEID_PLAYER && pVictim->GetUInt64Value( UNIT_FIELD_CREATEDBY ) == 0 && pVictim->GetUInt64Value( OBJECT_FIELD_CREATED_BY ) == 0 && !pVictim->IsPet() ) { // TODO: lots of casts are bad make a temp member pointer to use for batches like this // that way no local loadhitstore and its just one assignment // Is this player part of a group if( static_cast< Player* >( this)->InGroup() ) { //Calc Group XP static_cast< Player* >( this )->GiveGroupXP( pVictim, static_cast< Player* >( this ) ); //TODO: pet xp if player in group } else { uint32 xp = CalculateXpToGive( pVictim, static_cast< Unit* >( this ) ); if( xp > 0 ) { static_cast< Player* >( this )->GiveXP( xp, victimGuid, true ); if( static_cast< Player* >( this )->GetSummon() && static_cast< Player* >( this )->GetSummon()->GetUInt32Value( UNIT_CREATED_BY_SPELL ) == 0 ) { xp = CalculateXpToGive( pVictim, static_cast< Player* >( this )->GetSummon() ); if( xp > 0 ) static_cast< Player* >( this )->GetSummon()->GiveXP( xp ); } } } if( pVictim->GetTypeId() != TYPEID_PLAYER ) sQuestMgr.OnPlayerKill( static_cast< Player* >( this ), static_cast< Creature* >( pVictim ) ); } else /* is Creature or GameObject*/ { /* ----------------------------- PET XP HANDLING -------------- */ if( owner_participe && IsPet() && !pVictim->IsPet() ) { Player* petOwner = static_cast< Pet* >( this )->GetPetOwner(); if( petOwner != NULL && petOwner->GetTypeId() == TYPEID_PLAYER ) { if( petOwner->InGroup() ) { //Calc Group XP static_cast< Unit* >( this )->GiveGroupXP( pVictim, petOwner ); //TODO: pet xp if player in group } else { uint32 xp = CalculateXpToGive( pVictim, petOwner ); if( xp > 0 ) { petOwner->GiveXP( xp, victimGuid, true ); if( !static_cast< Pet* >( this )->IsSummon() ) { xp = CalculateXpToGive( pVictim, static_cast< Pet* >( this ) ); if( xp > 0 ) static_cast< Pet* >( this )->GiveXP( xp ); } } } } if( petOwner != NULL && pVictim->GetTypeId() != TYPEID_PLAYER && pVictim->GetTypeId() == TYPEID_UNIT ) sQuestMgr.OnPlayerKill( petOwner, static_cast< Creature* >( pVictim ) ); } /* ----------------------------- PET XP HANDLING END-------------- */ /* ----------------------------- PET DEATH HANDLING -------------- */ if( pVictim->IsPet() ) { // dying pet looses 1 happiness level if( !static_cast< Pet* >( pVictim )->IsSummon() ) { uint32 hap = static_cast< Pet* >( pVictim )->GetUInt32Value( UNIT_FIELD_POWER5 ); hap = hap - PET_HAPPINESS_UPDATE_VALUE > 0 ? hap - PET_HAPPINESS_UPDATE_VALUE : 0; static_cast< Pet* >( pVictim )->SetUInt32Value( UNIT_FIELD_POWER5, hap ); } static_cast< Pet* >( pVictim )->DelayedRemove( false, true ); //remove owner warlock soul link from caster Player* owner = static_cast<Pet*>( pVictim )->GetPetOwner(); if( owner != NULL ) owner->EventDismissPet(); } /* ----------------------------- PET DEATH HANDLING END -------------- */ else if( pVictim->GetUInt64Value( UNIT_FIELD_CHARMEDBY ) ) { //remove owner warlock soul link from caster Unit *owner=pVictim->GetMapMgr()->GetUnit( pVictim->GetUInt64Value( UNIT_FIELD_CHARMEDBY ) ); if( owner != NULL && owner->IsPlayer()) static_cast< Player* >( owner )->EventDismissPet(); } } } else if( pVictim->GetTypeId() == TYPEID_PLAYER ) { /* -------------------- RESET BREATH STATE ON DEATH -------------- */ static_cast< Player* >( pVictim )->m_UnderwaterTime = 0; static_cast< Player* >( pVictim )->m_UnderwaterState = 0; static_cast< Player* >( pVictim )->m_BreathDamageTimer = 0; static_cast< Player* >( pVictim )->m_SwimmingTime = 0; /* -------------------- KILL PET WHEN PLAYER DIES ---------------*/ if( static_cast< Player* >( pVictim )->GetSummon() != NULL ) { if( pVictim->GetUInt32Value( UNIT_CREATED_BY_SPELL ) > 0 ) static_cast< Player* >( pVictim )->GetSummon()->Dismiss( true ); else static_cast< Player* >( pVictim )->GetSummon()->Remove( true, true, true ); } /* -------------------- KILL PET WHEN PLAYER DIES END---------------*/ } else DEBUG_LOG("DealDamage for Unknown Object."); } else /* ---------- NOT DEAD YET --------- */ { if(pVictim != this /* && updateskill */) { // Send AI Reaction UNIT vs UNIT if( GetTypeId() ==TYPEID_UNIT ) { static_cast< Unit* >( this )->GetAIInterface()->AttackReaction( pVictim, damage, spellId ); } // Send AI Victim Reaction if( this->IsPlayer() || this->GetTypeId() == TYPEID_UNIT ) { if( pVictim->GetTypeId() != TYPEID_PLAYER ) { static_cast< Creature* >( pVictim )->GetAIInterface()->AttackReaction( static_cast< Unit* >( this ), damage, spellId ); } } } // TODO: Mark victim as a HK /*if( static_cast< Player* >( pVictim )->GetCurrentBattleground() != NULL && static_cast< Player* >( this )->GetCurrentBattleground() != NULL) { }*/ pVictim->SetUInt32Value( UNIT_FIELD_HEALTH, health - damage ); } } void Object::SpellNonMeleeDamageLog(Unit *pVictim, uint32 spellID, uint32 damage, bool allowProc, bool static_damage, bool no_remove_auras) { //========================================================================================== //==============================Unacceptable Cases Processing=============================== //========================================================================================== if(!pVictim || !pVictim->isAlive()) return; SpellEntry *spellInfo = dbcSpell.LookupEntry( spellID ); if(!spellInfo) return; if (this->IsPlayer() && !static_cast< Player* >( this )->canCast(spellInfo)) return; //========================================================================================== //==============================Variables Initialization==================================== //========================================================================================== uint32 school = spellInfo->School; float res = float(damage); uint32 aproc = PROC_ON_ANY_HOSTILE_ACTION | PROC_ON_SPELL_LAND; uint32 vproc = PROC_ON_ANY_HOSTILE_ACTION | PROC_ON_ANY_DAMAGE_VICTIM | PROC_ON_SPELL_HIT_VICTIM | PROC_ON_SPELL_LAND_VICTIM; bool critical = false; float dmg_reduction_pct; float res_after_spelldmg; //========================================================================================== //==============================+Spell Damage Bonus Calculations============================ //========================================================================================== //------------------------------by stats---------------------------------------------------- if( this->IsUnit() && !static_damage ) { Unit* caster = static_cast< Unit* >( this ); caster->RemoveAurasByInterruptFlag( AURA_INTERRUPT_ON_START_ATTACK ); res += caster->GetSpellDmgBonus( pVictim, spellInfo, ( int )res, false ); res_after_spelldmg = res; //========================================================================================== //==============================Post +SpellDamage Bonus Modifications======================= //========================================================================================== if( res < 0 ) res = 0; else if( spellInfo->spell_can_crit == true ) { //------------------------------critical strike chance-------------------------------------- // lol ranged spells were using spell crit chance float CritChance; if( spellInfo->is_ranged_spell ) { if( IsPlayer() ) { CritChance = GetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE ); if( pVictim->IsPlayer() ) CritChance += static_cast< Player* >(pVictim)->res_R_crit_get(); CritChance += (float)(pVictim->AttackerCritChanceMod[spellInfo->School]); } else { CritChance = 5.0f; // static value for mobs.. not blizzlike, but an unfinished formula is not fatal :) } if( pVictim->IsPlayer() ) CritChance -= static_cast< Player* >(pVictim)->CalcRating( PLAYER_RATING_MODIFIER_RANGED_CRIT_RESILIENCE ); } else if( spellInfo->is_melee_spell ) { // Same shit with the melee spells, such as Judgement/Seal of Command if( IsPlayer() ) { CritChance = GetFloatValue(PLAYER_CRIT_PERCENTAGE); } if( pVictim->IsPlayer() ) { CritChance += static_cast< Player* >(pVictim)->res_R_crit_get(); //this could be ability but in that case we overwrite the value } // Resilience CritChance -= pVictim->IsPlayer() ? static_cast< Player* >(pVictim)->CalcRating( PLAYER_RATING_MODIFIER_MELEE_CRIT_RESILIENCE ) : 0.0f; // Victim's (!) crit chance mod for physical attacks? CritChance += (float)(pVictim->AttackerCritChanceMod[0]); } else { CritChance = caster->spellcritperc + caster->SpellCritChanceSchool[school] + pVictim->AttackerCritChanceMod[school]; if( caster->IsPlayer() && ( pVictim->m_rooted - pVictim->m_stunned ) ) CritChance += static_cast< Player* >( caster )->m_RootedCritChanceBonus; if( spellInfo->SpellGroupType ) { SM_FFValue(caster->SM_CriticalChance, &CritChance, spellInfo->SpellGroupType); #ifdef COLLECTION_OF_UNTESTED_STUFF_AND_TESTERS float spell_flat_modifers=0; SM_FFValue(caster->SM_CriticalChance,&spell_flat_modifers,spellInfo->SpellGroupType); if(spell_flat_modifers!=0) printf("!!!!spell critchance mod flat %f ,spell group %u\n",spell_flat_modifers,spellInfo->SpellGroupType); #endif } if( pVictim->IsPlayer() ) CritChance -= static_cast< Player* >(pVictim)->CalcRating( PLAYER_RATING_MODIFIER_SPELL_CRIT_RESILIENCE ); } if( CritChance < 0 ) CritChance = 0; if( CritChance > 95 ) CritChance = 95; critical = Rand(CritChance); //sLog.outString( "SpellNonMeleeDamageLog: Crit Chance %f%%, WasCrit = %s" , CritChance , critical ? "Yes" : "No" ); //========================================================================================== //==============================Spell Critical Hit========================================== //========================================================================================== if (critical) { int32 critical_bonus = 100; if( spellInfo->SpellGroupType ) SM_FIValue( caster->SM_PCriticalDamage, &critical_bonus, spellInfo->SpellGroupType ); if( critical_bonus > 0 ) { // the bonuses are halved by 50% (funky blizzard math :S) float b; if( spellInfo->School == 0 || spellInfo->is_melee_spell || spellInfo->is_ranged_spell ) // physical || hackfix SoCommand/JoCommand b = ( ( float(critical_bonus) ) / 100.0f ) + 1.0f; else b = ( ( float(critical_bonus) / 2.0f ) / 100.0f ) + 1.0f; if( pVictim->IsPlayer() ) { dmg_reduction_pct = 2.0f * static_cast< Player* >(pVictim)->CalcRating( PLAYER_RATING_MODIFIER_MELEE_CRIT_RESILIENCE ); if( dmg_reduction_pct < 100.0f ) { dmg_reduction_pct /= 100.0f; dmg_reduction_pct = 1.0f - dmg_reduction_pct; b *= dmg_reduction_pct; res *= b; } } else res *= b; } /*if( pVictim->IsPlayer() ) { //res = res*(1.0f-2.0f*static_cast< Player* >(pVictim)->CalcRating(PLAYER_RATING_MODIFIER_MELEE_CRIT_RESISTANCE)); //Resilience is a special new rating which was created to reduce the effects of critical hits against your character. //It has two components; it reduces the chance you will be critically hit by x%, //and it reduces the damage dealt to you by critical hits by 2x%. x is the percentage resilience granted by a given resilience rating. //It is believed that resilience also functions against spell crits, //though it's worth noting that NPC mobs cannot get critical hits with spells. float dmg_reduction_pct = 2 * static_cast< Player* >(pVictim)->CalcRating( PLAYER_RATING_MODIFIER_MELEE_CRIT_RESILIENCE ) / 100.0f; if( dmg_reduction_pct > 1.0f ) dmg_reduction_pct = 1.0f; //we cannot resist more then he is criticalling us, there is no point of the critical then :P res = res - res * dmg_reduction_pct; }*/ pVictim->Emote( EMOTE_ONESHOT_WOUNDCRITICAL ); aproc |= PROC_ON_SPELL_CRIT_HIT; vproc |= PROC_ON_SPELL_CRIT_HIT_VICTIM; } } } //========================================================================================== //==============================Post Roll Calculations====================================== //========================================================================================== //dirty fix for Ice Lance if( ( pVictim->m_rooted -pVictim->m_stunned) > 0 && spellInfo->NameHash == SPELL_HASH_ICE_LANCE ) //Ice Lance deals 3x damage if target is frozen { res *= 3; } //------------------------------absorption-------------------------------------------------- uint32 ress=(uint32)res; uint32 abs_dmg = pVictim->AbsorbDamage(school, &ress); uint32 ms_abs_dmg= pVictim->ManaShieldAbsorb(ress); if (ms_abs_dmg) { if(ms_abs_dmg > ress) ress = 0; else ress-=ms_abs_dmg; abs_dmg += ms_abs_dmg; } if(ress < 0) ress = 0; res=(float)ress; dealdamage dmg; dmg.school_type = school; dmg.full_damage = ress; dmg.resisted_damage = 0; if(res <= 0) dmg.resisted_damage = dmg.full_damage; //------------------------------resistance reducing----------------------------------------- float res_before_resist = res; if(res > 0 && this->IsUnit()) { static_cast<Unit*>(this)->CalculateResistanceReduction(pVictim,&dmg,spellInfo); if((int32)dmg.resisted_damage > dmg.full_damage) res = 0; else res = float(dmg.full_damage - dmg.resisted_damage); } //------------------------------special states---------------------------------------------- if(pVictim->GetTypeId() == TYPEID_PLAYER && static_cast< Player* >(pVictim)->GodModeCheat == true) { res = 0; dmg.resisted_damage = dmg.full_damage; } //DK:FIXME->SplitDamage //========================================================================================== //==============================Data Sending ProcHandling=================================== //========================================================================================== SendSpellNonMeleeDamageLog(this, pVictim, spellID, float2int32(res), school, abs_dmg, dmg.resisted_damage, false, 0, critical, IsPlayer()); int32 ires = float2int32(res); if( ires > 0 ) { // only deal damage if its >0 DealDamage( pVictim, float2int32( res ), 2, 0, spellID ); } else { // we still have to tell the combat status handler we did damage so we're put in combat if( IsUnit() ) ((Unit*)this)->CombatStatus.OnDamageDealt(pVictim, 1); } if( this->IsUnit() && allowProc && spellInfo->Id != 25501 ) { pVictim->HandleProc( vproc, static_cast< Unit* >( this ), spellInfo, float2int32( res ) ); pVictim->m_procCounter = 0; static_cast< Unit* >( this )->HandleProc( aproc, pVictim, spellInfo, float2int32( res ) ); static_cast< Unit* >( this )->m_procCounter = 0; } if( this->IsPlayer() ) { static_cast< Player* >( this )->m_casted_amount[school] = ( uint32 )res; } if( pVictim->GetCurrentSpell() ) pVictim->GetCurrentSpell()->AddTime( school ); //========================================================================================== //==============================Post Damage Processing====================================== //========================================================================================== if( (int32)dmg.resisted_damage == dmg.full_damage && !abs_dmg ) { //Magic Absorption if( pVictim->IsPlayer() ) { if( static_cast< Player* >( pVictim )->m_RegenManaOnSpellResist ) { Player* pl = static_cast< Player* >( pVictim ); uint32 maxmana = pl->GetUInt32Value( UNIT_FIELD_MAXPOWER1 ); //TODO: wtf is this ugly mess of casting bullshit uint32 amount = uint32(float( float(maxmana)*pl->m_RegenManaOnSpellResist)); pVictim->Energize( pVictim, 29442, amount, POWER_TYPE_MANA ); } } } if( school == SHADOW_DAMAGE ) { if( IsPlayer() && ((Unit*)this)->isAlive() && ((Player*)this)->getClass() == PRIEST ) ((Player*)this)->VampiricSpell(float2int32(res), pVictim); if( pVictim->isAlive() && this->IsUnit() ) { //Shadow Word:Death if( spellID == 32379 || spellID == 32996 ) { uint32 damage = (uint32)( res + abs_dmg ); uint32 absorbed = static_cast< Unit* >( this )->AbsorbDamage( school, &damage ); DealDamage( static_cast< Unit* >( this ), damage, 2, 0, spellID ); SendSpellNonMeleeDamageLog( this, this, spellID, damage, school, absorbed, 0, false, 0, false, this->IsPlayer() ); } } } // Rage /*if( dmg.full_damage && this->IsUnit() && pVictim->IsPlayer() && pVictim->GetPowerType() == POWER_TYPE_RAGE && pVictim->CombatStatus.IsInCombat() ) { float val; float level = (float)TO_UNIT(this)->getLevel(); // Conversion Value float c = 0.0091107836f * level * level + 3.225598133f * level + 4.2652911f; val = 2.5f * dmg.full_damage / c; val *= 10; //DEBUG_LOG( "Rd(%i) d(%i) c(%f) rage = %f", realdamage, dmg.full_damage, c, val ); pVictim->ModUnsigned32Value( UNIT_FIELD_POWER2, (int32)val ); if( pVictim->GetUInt32Value( UNIT_FIELD_POWER2) > 1000 ) pVictim->ModUnsigned32Value( UNIT_FIELD_POWER2, 1000 - pVictim->GetUInt32Value( UNIT_FIELD_POWER2 ) ); }*/ } //***************************************************************************************** //* SpellLog packets just to keep the code cleaner and better to read //***************************************************************************************** void Object::SendSpellLog(Object *Caster, Object *Target,uint32 Ability, uint8 SpellLogType) { if ((!Caster || !Target) && Ability) return; WorldPacket data(SMSG_SPELLLOGMISS,28); data << Ability; // spellid data << Caster->GetGUID(); // caster / player data << (uint8)1; // unknown but I think they are const data << (uint32)1; // unknown but I think they are const data << Target->GetGUID(); // target data << SpellLogType; // spelllogtype Caster->SendMessageToSet(&data, true); } void Object::SendSpellNonMeleeDamageLog( Object* Caster, Object* Target, uint32 SpellID, uint32 Damage, uint8 School, uint32 AbsorbedDamage, uint32 ResistedDamage, bool PhysicalDamage, uint32 BlockedDamage, bool CriticalHit, bool bToset ) { if ((!Caster || !Target) && SpellID) return; WorldPacket data(SMSG_SPELLNONMELEEDAMAGELOG,40); data << Target->GetNewGUID(); data << Caster->GetNewGUID(); data << SpellID; // SpellID / AbilityID data << Damage; // All Damage data << uint8(g_spellSchoolConversionTable[School]); // School data << AbsorbedDamage; // Absorbed Damage data << ResistedDamage; // Resisted Damage data << uint8(PhysicalDamage); // Physical Damage (true/false) data << uint8(0); // unknown or it binds with Physical Damage data << BlockedDamage; // Physical Damage (true/false) data << uint8(CriticalHit ? 7 : 5); // unknown const data << uint32(0); Caster->SendMessageToSet( &data, bToset ); } int32 Object::event_GetInstanceID() { // return -1 for non-inworld.. so we get our shit moved to the right thread if(!IsInWorld()) return -1; else return m_instanceId; } void Object::EventSpellHit(Spell *pSpell) { if( !IsInWorld() ) { delete pSpell; return; } pSpell->cast(false); } bool Object::CanActivate() { switch(m_objectTypeId) { case TYPEID_UNIT: { if(!IsPet()) return true; }break; case TYPEID_GAMEOBJECT: { if(static_cast<GameObject*>(this)->HasAI() && GetUInt32Value(GAMEOBJECT_TYPE_ID) != GAMEOBJECT_TYPE_TRAP) return true; }break; } return false; } void Object::Activate(MapMgr * mgr) { switch(m_objectTypeId) { case TYPEID_UNIT: mgr->activeCreatures.insert((Creature*)this); break; case TYPEID_GAMEOBJECT: mgr->activeGameObjects.insert((GameObject*)this); break; } Active = true; } void Object::Deactivate(MapMgr * mgr) { switch(m_objectTypeId) { case TYPEID_UNIT: // check iterator if( mgr->__creature_iterator != mgr->activeCreatures.end() && (*mgr->__creature_iterator) == TO_CREATURE(this) ) ++mgr->__creature_iterator; mgr->activeCreatures.erase((Creature*)this); break; case TYPEID_GAMEOBJECT: // check iterator if( mgr->__gameobject_iterator != mgr->activeGameObjects.end() && (*mgr->__gameobject_iterator) == TO_GAMEOBJECT(this) ) ++mgr->__gameobject_iterator; mgr->activeGameObjects.erase((GameObject*)this); break; } Active = false; } void Object::SetByte(uint32 index, uint32 index1,uint8 value) { ASSERT( index < m_valuesCount ); // save updating when val isn't changing. uint8 * v =&((uint8*)m_uint32Values)[index*4+index1]; if(*v == value) return; *v = value; if(IsInWorld()) { m_updateMask.SetBit( index ); if(!m_objectUpdated) { m_mapMgr->ObjectUpdated(this); m_objectUpdated = true; } } } void Object::SetZoneId(uint32 newZone) { m_zoneId = newZone; if( m_objectTypeId == TYPEID_PLAYER && static_cast< Player* >( this )->GetGroup() ) static_cast< Player* >( this )->GetGroup()->HandlePartialChange( PARTY_UPDATE_FLAG_ZONEID, static_cast< Player* >( this ) ); } void Object::PlaySoundToSet(uint32 sound_entry) { WorldPacket data(SMSG_PLAY_SOUND, 4); data << sound_entry; SendMessageToSet(&data, true); } void Object::_SetExtension(const string& name, void* ptr) { if( m_extensions == NULL ) m_extensions = new ExtensionSet; m_extensions->insert( make_pair( name, ptr ) ); }
agpl-3.0
nyee32/Senior_Project
lte/MCC.c
1
1614
/* * Generated by asn1c-0.9.28 (http://lionet.info/asn1c) * From ASN.1 module "EUTRA-RRC-Definitions" * found in "36331-ac0.asn" * `asn1c -S /home/nyee/srsLTE/srslte/examples/src/asn1c/skeletons -fcompound-names -fskeletons-copy -gen-PER -pdu=auto` */ #include "MCC.h" static asn_per_constraints_t asn_PER_type_MCC_constr_1 GCC_NOTUSED = { { APC_UNCONSTRAINED, -1, -1, 0, 0 }, { APC_CONSTRAINED, 0, 0, 3, 3 } /* (SIZE(3..3)) */, 0, 0 /* No PER value map */ }; static asn_TYPE_member_t asn_MBR_MCC_1[] = { { ATF_POINTER, 0, 0, (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)), 0, &asn_DEF_MCC_MNC_Digit, 0, /* Defer constraints checking to the member type */ 0, /* No PER visible constraints */ 0, "" }, }; static const ber_tlv_tag_t asn_DEF_MCC_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) }; static asn_SET_OF_specifics_t asn_SPC_MCC_specs_1 = { sizeof(struct MCC), offsetof(struct MCC, _asn_ctx), 0, /* XER encoding is XMLDelimitedItemList */ }; asn_TYPE_descriptor_t asn_DEF_MCC = { "MCC", "MCC", SEQUENCE_OF_free, SEQUENCE_OF_print, SEQUENCE_OF_constraint, SEQUENCE_OF_decode_ber, SEQUENCE_OF_encode_der, SEQUENCE_OF_decode_xer, SEQUENCE_OF_encode_xer, SEQUENCE_OF_decode_uper, SEQUENCE_OF_encode_uper, 0, /* Use generic outmost tag fetcher */ asn_DEF_MCC_tags_1, sizeof(asn_DEF_MCC_tags_1) /sizeof(asn_DEF_MCC_tags_1[0]), /* 1 */ asn_DEF_MCC_tags_1, /* Same as above */ sizeof(asn_DEF_MCC_tags_1) /sizeof(asn_DEF_MCC_tags_1[0]), /* 1 */ &asn_PER_type_MCC_constr_1, asn_MBR_MCC_1, 1, /* Single element */ &asn_SPC_MCC_specs_1 /* Additional specs */ };
agpl-3.0
h2so5/meltage
client/vendor/libvpvl2/src/core/mvd/mvd_AssetSection.cpp
1
3582
/** Copyright (c) 2010-2013 hkrn All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the MMDAI project team 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 "vpvl2/vpvl2.h" #include "vpvl2/internal/util.h" #include "vpvl2/mvd/AssetKeyframe.h" #include "vpvl2/mvd/AssetSection.h" namespace vpvl2 { namespace mvd { #pragma pack(push, 1) struct AssetSectionHeader { int32 reserved; int32 sizeOfKeyframe; int32 countOfKeyframes; int32 reserved2; }; #pragma pack(pop) AssetSection::AssetSection(const Motion *motionRef) : BaseSection(motionRef) { } AssetSection::~AssetSection() { } bool AssetSection::preparse(uint8 *&ptr, vsize &rest, Motion::DataInfo &info) { AssetSectionHeader header; if (!internal::validateSize(ptr, sizeof(header), rest)) { return false; } internal::getData(ptr - sizeof(header), header); if (!internal::validateSize(ptr, header.reserved2, rest)) { return false; } const int32 nkeyframes = header.countOfKeyframes; const vsize reserved = header.sizeOfKeyframe - AssetKeyframe::size(); for (int32 i = 0; i < nkeyframes; i++) { if (!AssetKeyframe::preparse(ptr, rest, reserved, info)) { return false; } } return true; } void AssetSection::read(const uint8 * /* data */) { } void AssetSection::seek(const IKeyframe::TimeIndex &timeIndex) { saveCurrentTimeIndex(timeIndex); } void AssetSection::write(uint8 * /* data */) const { } vsize AssetSection::estimateSize() const { return 0; } vsize AssetSection::countKeyframes() const { return 0; } void AssetSection::addKeyframe(IKeyframe * /* keyframe */) { } void AssetSection::deleteKeyframe(IKeyframe *&keyframe) { delete keyframe; keyframe = 0; } void AssetSection::getKeyframes(const IKeyframe::TimeIndex & /* timeIndex */, const IKeyframe::LayerIndex & /* layerIndex */, Array<IKeyframe *> & /* keyframes */) const { } void AssetSection::getAllKeyframes(Array<IKeyframe *> & /* value */) const { } void AssetSection::setAllKeyframes(const Array<IKeyframe *> & /* value */) { } } /* namespace mvd */ } /* namespace vpvl2 */
agpl-3.0
sobakasu/vanitygen
oclvanitygen.c
3
10973
/* * Vanitygen, vanity bitcoin address generator * Copyright (C) 2011 <samr7@cs.washington.edu> * * Vanitygen is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Vanitygen 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Vanitygen. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <openssl/ec.h> #include <openssl/bn.h> #include <openssl/rand.h> #include "oclengine.h" #include "pattern.h" #include "util.h" const char *version = VANITYGEN_VERSION; const int debug = 0; void usage(const char *name) { fprintf(stderr, "oclVanitygen %s (" OPENSSL_VERSION_TEXT ")\n" "Usage: %s [-vqrik1NTS] [-d <device>] [-f <filename>|-] [<pattern>...]\n" "Generates a bitcoin receiving address matching <pattern>, and outputs the\n" "address and associated private key. The private key may be stored in a safe\n" "location or imported into a bitcoin client to spend any balance received on\n" "the address.\n" "By default, <pattern> is interpreted as an exact prefix.\n" "By default, if no device is specified, and the system has exactly one OpenCL\n" "device, it will be selected automatically, otherwise if the system has\n" "multiple OpenCL devices and no device is specified, an error will be\n" "reported. To use multiple devices simultaneously, specify the -D option for\n" "each device.\n" "\n" "Options:\n" "-v Verbose output\n" "-q Quiet output\n" "-i Case-insensitive prefix search\n" "-k Keep pattern and continue search after finding a match\n" "-1 Stop after first match\n" "-L Generate litecoin address\n" "-N Generate namecoin address\n" "-T Generate bitcoin testnet address\n" "-X <version> Generate address with the given version\n" "-F <format> Generate address with the given format (pubkey, compressed)\n" "-e Encrypt private keys, prompt for password\n" "-E <password> Encrypt private keys with <password> (UNSAFE)\n" "-P <pubkey> Use split-key method with <pubkey> as base public key\n" "-p <platform> Select OpenCL platform\n" "-d <device> Select OpenCL device\n" "-D <devstr> Use OpenCL device, identified by device string\n" " Form: <platform>:<devicenumber>[,<options>]\n" " Example: 0:0,grid=1024x1024\n" "-S Safe mode, disable OpenCL loop unrolling optimizations\n" "-w <worksize> Set work items per thread in a work unit\n" "-t <threads> Set target thread count per multiprocessor\n" "-g <x>x<y> Set grid size\n" "-b <invsize> Set modular inverse ops per thread\n" "-V Enable kernel/OpenCL/hardware verification (SLOW)\n" "-f <file> File containing list of patterns, one per line\n" " (Use \"-\" as the file name for stdin)\n" "-o <file> Write pattern matches to <file>\n" "-s <file> Seed random number generator from <file>\n", version, name); } #define MAX_DEVS 32 #define MAX_FILE 4 int main(int argc, char **argv) { int addrtype = 0; int privtype = 128; int regex = 0; int caseinsensitive = 0; int opt; char pwbuf[128]; int platformidx = -1, deviceidx = -1; int prompt_password = 0; char *seedfile = NULL; char **patterns, *pend; int verbose = 1; int npatterns = 0; int nthreads = 0; int worksize = 0; int nrows = 0, ncols = 0; int invsize = 0; int remove_on_match = 1; int only_one = 0; int verify_mode = 0; int safe_mode = 0; vg_context_t *vcp = NULL; vg_ocl_context_t *vocp = NULL; EC_POINT *pubkey_base = NULL; const char *result_file = NULL; const char *key_password = NULL; char *devstrs[MAX_DEVS]; int ndevstrs = 0; int opened = 0; FILE *pattfp[MAX_FILE], *fp; int pattfpi[MAX_FILE]; int npattfp = 0; int pattstdin = 0; int compressed = 0; int i; while ((opt = getopt(argc, argv, "vqik1LNTX:F:eE:p:P:d:w:t:g:b:VSh?f:o:s:D:")) != -1) { switch (opt) { case 'v': verbose = 2; break; case 'q': verbose = 0; break; case 'i': caseinsensitive = 1; break; case 'k': remove_on_match = 0; break; case '1': only_one = 1; break; case 'L': addrtype = 48; privtype = 176; break; case 'N': addrtype = 52; privtype = 180; break; case 'T': addrtype = 111; privtype = 239; break; case 'X': addrtype = atoi(optarg); privtype = 128 + addrtype; break; case 'F': if (!strcmp(optarg, "compressed")) compressed = 1; else if (strcmp(optarg, "pubkey")) { fprintf(stderr, "Invalid format '%s'\n", optarg); return 1; } break; case 'e': prompt_password = 1; break; case 'E': key_password = optarg; break; case 'p': platformidx = atoi(optarg); break; case 'd': deviceidx = atoi(optarg); break; case 'w': worksize = atoi(optarg); if (worksize == 0) { fprintf(stderr, "Invalid work size '%s'\n", optarg); return 1; } break; case 't': nthreads = atoi(optarg); if (nthreads == 0) { fprintf(stderr, "Invalid thread count '%s'\n", optarg); return 1; } break; case 'g': nrows = 0; ncols = strtol(optarg, &pend, 0); if (pend && *pend == 'x') { nrows = strtol(pend+1, NULL, 0); } if (!nrows || !ncols) { fprintf(stderr, "Invalid grid size '%s'\n", optarg); return 1; } break; case 'b': invsize = atoi(optarg); if (!invsize) { fprintf(stderr, "Invalid modular inverse size '%s'\n", optarg); return 1; } if (invsize & (invsize - 1)) { fprintf(stderr, "Modular inverse size must be " "a power of 2\n"); return 1; } break; case 'V': verify_mode = 1; break; case 'S': safe_mode = 1; break; case 'D': if (ndevstrs >= MAX_DEVS) { fprintf(stderr, "Too many OpenCL devices (limit %d)\n", MAX_DEVS); return 1; } devstrs[ndevstrs++] = optarg; break; case 'P': { if (pubkey_base != NULL) { fprintf(stderr, "Multiple base pubkeys specified\n"); return 1; } EC_KEY *pkey = vg_exec_context_new_key(); pubkey_base = EC_POINT_hex2point( EC_KEY_get0_group(pkey), optarg, NULL, NULL); EC_KEY_free(pkey); if (pubkey_base == NULL) { fprintf(stderr, "Invalid base pubkey\n"); return 1; } break; } case 'f': if (npattfp >= MAX_FILE) { fprintf(stderr, "Too many input files specified\n"); return 1; } if (!strcmp(optarg, "-")) { if (pattstdin) { fprintf(stderr, "ERROR: stdin " "specified multiple times\n"); return 1; } fp = stdin; } else { fp = fopen(optarg, "r"); if (!fp) { fprintf(stderr, "Could not open %s: %s\n", optarg, strerror(errno)); return 1; } } pattfp[npattfp] = fp; pattfpi[npattfp] = caseinsensitive; npattfp++; break; case 'o': if (result_file) { fprintf(stderr, "Multiple output files specified\n"); return 1; } result_file = optarg; break; case 's': if (seedfile != NULL) { fprintf(stderr, "Multiple RNG seeds specified\n"); return 1; } seedfile = optarg; break; default: usage(argv[0]); return 1; } } #if OPENSSL_VERSION_NUMBER < 0x10000000L /* Complain about older versions of OpenSSL */ if (verbose > 0) { fprintf(stderr, "WARNING: Built with " OPENSSL_VERSION_TEXT "\n" "WARNING: Use OpenSSL 1.0.0d+ for best performance\n"); } #endif if (caseinsensitive && regex) fprintf(stderr, "WARNING: case insensitive mode incompatible with " "regular expressions\n"); if (!seedfile) { #if !defined(_WIN32) struct stat st; if (stat("/dev/random", &st) == 0) { seedfile = "/dev/random"; } #endif } if (seedfile) { opt = -1; #if !defined(_WIN32) { struct stat st; if (!stat(seedfile, &st) && (st.st_mode & (S_IFBLK|S_IFCHR))) { opt = 32; } } #endif opt = RAND_load_file(seedfile, opt); if (!opt) { fprintf(stderr, "Could not load RNG seed '%s'\n", seedfile); return 1; } if (verbose > 1) { fprintf(stderr, "Read %d bytes from RNG seed file\n", opt); } } if (regex) { vcp = vg_regex_context_new(addrtype, privtype); } else { vcp = vg_prefix_context_new(addrtype, privtype, caseinsensitive); } vcp->vc_compressed = compressed; vcp->vc_verbose = verbose; vcp->vc_result_file = result_file; vcp->vc_remove_on_match = remove_on_match; vcp->vc_only_one = only_one; vcp->vc_pubkeytype = addrtype; vcp->vc_pubkey_base = pubkey_base; vcp->vc_output_match = vg_output_match_console; vcp->vc_output_timing = vg_output_timing_console; if (!npattfp) { if (optind >= argc) { usage(argv[0]); return 1; } patterns = &argv[optind]; npatterns = argc - optind; if (!vg_context_add_patterns(vcp, (const char ** const) patterns, npatterns)) return 1; } for (i = 0; i < npattfp; i++) { fp = pattfp[i]; if (!vg_read_file(fp, &patterns, &npatterns)) { fprintf(stderr, "Failed to load pattern file\n"); return 1; } if (fp != stdin) fclose(fp); if (!regex) vg_prefix_context_set_case_insensitive(vcp, pattfpi[i]); if (!vg_context_add_patterns(vcp, (const char ** const) patterns, npatterns)) return 1; } if (!vcp->vc_npatterns) { fprintf(stderr, "No patterns to search\n"); return 1; } if (prompt_password) { if (!vg_read_password(pwbuf, sizeof(pwbuf))) return 1; key_password = pwbuf; } vcp->vc_key_protect_pass = key_password; if (key_password) { if (!vg_check_password_complexity(key_password, verbose)) fprintf(stderr, "WARNING: Protecting private keys with " "weak password\n"); } if ((verbose > 0) && regex && (vcp->vc_npatterns > 1)) fprintf(stderr, "Regular expressions: %ld\n", vcp->vc_npatterns); if (ndevstrs) { for (opt = 0; opt < ndevstrs; opt++) { vocp = vg_ocl_context_new_from_devstr(vcp, devstrs[opt], safe_mode, verify_mode); if (!vocp) { fprintf(stderr, "Could not open device '%s', ignoring\n", devstrs[opt]); } else { opened++; } } } else { vocp = vg_ocl_context_new(vcp, platformidx, deviceidx, safe_mode, verify_mode, worksize, nthreads, nrows, ncols, invsize); if (vocp) opened++; } if (!opened) { vg_ocl_enumerate_devices(); return 1; } opt = vg_context_start_threads(vcp); if (opt) return 1; vg_context_wait_for_completion(vcp); vg_ocl_context_free(vocp); return 0; }
agpl-3.0
chbfiv/fabric-engine-old
Native/Core/AST/StatementVector.cpp
4
1893
/* * Copyright 2010-2012 Fabric Engine Inc. All rights reserved. */ #include <Fabric/Core/AST/StatementVector.h> #include <Fabric/Core/AST/Statement.h> #include <Fabric/Core/CG/BasicBlockBuilder.h> #include <Fabric/Base/Util/SimpleString.h> namespace Fabric { namespace AST { RC::ConstHandle<StatementVector> StatementVector::Create( RC::ConstHandle<Statement> const &first, RC::ConstHandle<StatementVector> const &remaining ) { StatementVector *result = new StatementVector; if ( first ) result->push_back( first ); if ( remaining ) { for ( StatementVector::const_iterator it=remaining->begin(); it!=remaining->end(); ++it ) result->push_back( *it ); } return result; } StatementVector::StatementVector() { } void StatementVector::appendJSON( JSON::Encoder const &encoder, bool includeLocation ) const { JSON::ArrayEncoder jsonArrayEncoder = encoder.makeArray(); for ( const_iterator it=begin(); it!=end(); ++it ) (*it)->appendJSON( jsonArrayEncoder.makeElement(), includeLocation ); } void StatementVector::registerTypes( RC::Handle<CG::Manager> const &cgManager, CG::Diagnostics &diagnostics ) const { for ( const_iterator it=begin(); it!=end(); ++it ) (*it)->registerTypes( cgManager, diagnostics ); } void StatementVector::llvmCompileToBuilder( CG::BasicBlockBuilder &basicBlockBuilder, CG::Diagnostics &diagnostics ) const { for ( size_t i=0; i<size(); ++i ) { RC::ConstHandle<Statement> const &statement = get(i); if ( basicBlockBuilder->GetInsertBlock()->getTerminator() ) { statement->addError( diagnostics, "code is unreachable" ); break; } statement->llvmCompileToBuilder( basicBlockBuilder, diagnostics ); } } }; };
agpl-3.0
youfoh/webkit-efl
Source/WebKit2/UIProcess/efl/PageLoadClientEfl.cpp
1
11633
/* * Copyright (C) 2012 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. AND ITS 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 APPLE INC. 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. */ #include "config.h" #include "PageLoadClientEfl.h" #include "EwkViewImpl.h" #include "WKAPICast.h" #include "WKFrame.h" #include "WKPage.h" #include "ewk_back_forward_list_private.h" #include "ewk_error_private.h" #include "ewk_intent_private.h" #include "ewk_intent_service_private.h" #include "ewk_view.h" #if OS(TIZEN) #include "WKRetainPtr.h" #include "ewk_auth_challenge.h" #include "ewk_auth_challenge_private.h" #endif using namespace WebKit; namespace WebKit { static inline PageLoadClientEfl* toPageLoadClientEfl(const void* clientInfo) { return static_cast<PageLoadClientEfl*>(const_cast<void*>(clientInfo)); } void PageLoadClientEfl::didReceiveTitleForFrame(WKPageRef, WKStringRef title, WKFrameRef frame, WKTypeRef, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informTitleChange(toImpl(title)->string()); } #if ENABLE(WEB_INTENTS) void PageLoadClientEfl::didReceiveIntentForFrame(WKPageRef, WKFrameRef, WKIntentDataRef intent, WKTypeRef, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); RefPtr<Ewk_Intent> ewkIntent = Ewk_Intent::create(intent); viewImpl->informIntentRequest(ewkIntent.get()); } #endif #if ENABLE(WEB_INTENTS_TAG) void PageLoadClientEfl::registerIntentServiceForFrame(WKPageRef, WKFrameRef, WKIntentServiceInfoRef serviceInfo, WKTypeRef, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); RefPtr<Ewk_Intent_Service> ewkIntentService = Ewk_Intent_Service::create(serviceInfo); viewImpl->informIntentServiceRegistration(ewkIntentService.get()); } #endif void PageLoadClientEfl::didChangeProgress(WKPageRef page, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informLoadProgress(WKPageGetEstimatedProgress(page)); } void PageLoadClientEfl::didFinishLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informLoadFinished(); } void PageLoadClientEfl::didFailLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); #if ENABLE(TIZEN_WEBKIT2_LOCAL_IMPLEMENTATION_FOR_ERROR) { ewkViewLoadError(viewImpl->view(), error); return; } #endif OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(error); viewImpl->informLoadError(ewkError.get()); viewImpl->informLoadFinished(); } void PageLoadClientEfl::didStartProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informProvisionalLoadStarted(); } void PageLoadClientEfl::didReceiveServerRedirectForProvisionalLoadForFrame(WKPageRef, WKFrameRef frame, WKTypeRef /*userData*/, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informProvisionalLoadRedirect(); } void PageLoadClientEfl::didFailProvisionalLoadWithErrorForFrame(WKPageRef, WKFrameRef frame, WKErrorRef error, WKTypeRef, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); #if ENABLE(TIZEN_WEBKIT2_LOCAL_IMPLEMENTATION_FOR_ERROR) { ewkViewLoadError(viewImpl->view(), error); return; } #endif OwnPtr<Ewk_Error> ewkError = Ewk_Error::create(error); viewImpl->informProvisionalLoadFailed(ewkError.get()); } void PageLoadClientEfl::didChangeBackForwardList(WKPageRef, WKBackForwardListItemRef addedItem, WKArrayRef removedItems, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); ASSERT(viewImpl); Ewk_Back_Forward_List* list = ewk_view_back_forward_list_get(viewImpl->view()); ASSERT(list); list->update(addedItem, removedItems); viewImpl->informBackForwardListChange(); #if ENABLE(TIZEN_SIGNAL_APP_BACK_FORWARD_LIST_CHANGED) ewkViewBackForwardListChanged(viewImpl->view()); #endif } void PageLoadClientEfl::didSameDocumentNavigationForFrame(WKPageRef, WKFrameRef frame, WKSameDocumentNavigationType, WKTypeRef, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informURLChange(); #if OS(TIZEN) viewImpl->informTitleChange(viewImpl->page()->pageTitle()); #endif } #if OS(TIZEN) void PageLoadClientEfl::didCommitLoadForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; Evas_Object* ewkView = toPageLoadClientEfl(clientInfo)->viewImpl()->view(); ewkViewLoadCommitted(ewkView); } void PageLoadClientEfl::didFirstVisuallyNonEmptyLayoutForFrame(WKPageRef page, WKFrameRef frame, WKTypeRef userData, const void* clientInfo) { if (!WKFrameIsMainFrame(frame)) return; Evas_Object* ewkView = toPageLoadClientEfl(clientInfo)->viewImpl()->view(); ewkViewDidFirstVisuallyNonEmptyLayout(ewkView); } #if ENABLE(TIZEN_ON_AUTHENTICATION_REQUESTED) bool PageLoadClientEfl::didReceiveAuthenticationChallengeInFrame(WKPageRef page, WKFrameRef frame, WKAuthenticationChallengeRef authenticationChallenge, const void* clientInfo) { #if !ENABLE(TIZEN_AUTHENTICATION_CHALLENGE_ENABLED_IN_ALL_FRAMES) if (!WKFrameIsMainFrame(frame)) return false; #endif Evas_Object* ewkView = toPageLoadClientEfl(clientInfo)->viewImpl()->view(); Ewk_Auth_Challenge* authChallenge = ewkAuthChallengeCreate(page, authenticationChallenge); ewkViewDidReceiveAuthenticationChallenge(ewkView, authChallenge); if (!ewkAuthChallengeDecided(authChallenge) && !ewkAuthChallengeSuspended(authChallenge)) ewk_auth_challenge_credential_cancel(authChallenge); return true; } #else void PageLoadClientEfl::didReceiveAuthenticationChallengeInFrame(WKPageRef page, WKFrameRef frame, WKAuthenticationChallengeRef authenticationChallenge, const void* clientInfo) { #if !ENABLE(TIZEN_AUTHENTICATION_CHALLENGE_ENABLED_IN_ALL_FRAMES) if (!WKFrameIsMainFrame(frame)) return; #endif Evas_Object* ewkView = toPageLoadClientEfl(clientInfo)->viewImpl()->view(); Ewk_Auth_Challenge* authChallenge = ewkAuthChallengeCreate(authenticationChallenge); ewkViewDidReceiveAuthenticationChallenge(ewkView, authChallenge); if (!ewkAuthChallengeDecided(authChallenge) && !ewkAuthChallengeSuspended(authChallenge)) ewk_auth_challenge_credential_cancel(authChallenge); } #endif void PageLoadClientEfl::processDidCrash(WKPageRef page, const void* clientInfo) { Evas_Object* ewkView = toPageLoadClientEfl(clientInfo)->viewImpl()->view(); ewk_view_process_crashed(ewkView); } #if ENABLE(TIZEN_WEBKIT2_SEPERATE_LOAD_PROGRESS) void PageLoadClientEfl::didStartProgress(WKPageRef page, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informLoadProgressStarted(); } void PageLoadClientEfl::didFinishProgress(WKPageRef page, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); viewImpl->informLoadProgressFinished(); } #endif #if ENABLE(TIZEN_ISF_PORT) void PageLoadClientEfl::willGoToBackForwardListItem(WKPageRef page, WKBackForwardListItemRef, WKTypeRef, const void* clientInfo) { EwkViewImpl* viewImpl = toPageLoadClientEfl(clientInfo)->viewImpl(); InputMethodContextEfl* inputMethodContext = viewImpl->inputMethodContext(); if (inputMethodContext) inputMethodContext->hideIMFContext(); } #endif #endif // #if OS(TIZEN) PageLoadClientEfl::PageLoadClientEfl(EwkViewImpl* viewImpl) : m_viewImpl(viewImpl) { WKPageRef pageRef = m_viewImpl->wkPage(); ASSERT(pageRef); WKPageLoaderClient loadClient; memset(&loadClient, 0, sizeof(WKPageLoaderClient)); loadClient.version = kWKPageLoaderClientCurrentVersion; loadClient.clientInfo = this; loadClient.didReceiveTitleForFrame = didReceiveTitleForFrame; #if ENABLE(WEB_INTENTS) loadClient.didReceiveIntentForFrame = didReceiveIntentForFrame; #endif #if ENABLE(WEB_INTENTS_TAG) loadClient.registerIntentServiceForFrame = registerIntentServiceForFrame; #endif #if ENABLE(TIZEN_WEBKIT2_SEPERATE_LOAD_PROGRESS) loadClient.didStartProgress = didStartProgress; #else loadClient.didStartProgress = didChangeProgress; #endif loadClient.didChangeProgress = didChangeProgress; #if ENABLE(TIZEN_WEBKIT2_SEPERATE_LOAD_PROGRESS) loadClient.didFinishProgress = didFinishProgress; #else loadClient.didFinishProgress = didChangeProgress; #endif loadClient.didFinishLoadForFrame = didFinishLoadForFrame; loadClient.didFailLoadWithErrorForFrame = didFailLoadWithErrorForFrame; loadClient.didStartProvisionalLoadForFrame = didStartProvisionalLoadForFrame; loadClient.didReceiveServerRedirectForProvisionalLoadForFrame = didReceiveServerRedirectForProvisionalLoadForFrame; loadClient.didFailProvisionalLoadWithErrorForFrame = didFailProvisionalLoadWithErrorForFrame; loadClient.didChangeBackForwardList = didChangeBackForwardList; loadClient.didSameDocumentNavigationForFrame = didSameDocumentNavigationForFrame; #if OS(TIZEN) loadClient.didCommitLoadForFrame = didCommitLoadForFrame; loadClient.didFirstVisuallyNonEmptyLayoutForFrame = didFirstVisuallyNonEmptyLayoutForFrame; loadClient.didReceiveAuthenticationChallengeInFrame = didReceiveAuthenticationChallengeInFrame; loadClient.processDidCrash = processDidCrash; #if ENABLE(TIZEN_ISF_PORT) loadClient.willGoToBackForwardListItem = willGoToBackForwardListItem; #endif #endif WKPageSetPageLoaderClient(pageRef, &loadClient); } } // namespace WebKit
lgpl-2.1
Fxrh/libqmatrixclient
lib/csapi/definitions/event_filter.cpp
1
1029
/****************************************************************************** * THIS FILE IS GENERATED - ANY EDITS WILL BE OVERWRITTEN */ #include "event_filter.h" using namespace QMatrixClient; void JsonObjectConverter<EventFilter>::dumpTo( QJsonObject& jo, const EventFilter& pod) { addParam<IfNotEmpty>(jo, QStringLiteral("limit"), pod.limit); addParam<IfNotEmpty>(jo, QStringLiteral("not_senders"), pod.notSenders); addParam<IfNotEmpty>(jo, QStringLiteral("not_types"), pod.notTypes); addParam<IfNotEmpty>(jo, QStringLiteral("senders"), pod.senders); addParam<IfNotEmpty>(jo, QStringLiteral("types"), pod.types); } void JsonObjectConverter<EventFilter>::fillFrom( const QJsonObject& jo, EventFilter& result) { fromJson(jo.value("limit"_ls), result.limit); fromJson(jo.value("not_senders"_ls), result.notSenders); fromJson(jo.value("not_types"_ls), result.notTypes); fromJson(jo.value("senders"_ls), result.senders); fromJson(jo.value("types"_ls), result.types); }
lgpl-2.1
chi9rin/ultramonkey-l7v3
l7vsd/unit_tests/replication_test/parameter_stub.cpp
1
3519
#include "parameter_enum.h" #include "parameter.h" #include "parameter_impl.h" #include "logger.h" #if !defined(LOGGER_PROCESS_VSD) && !defined(LOGGER_PROCESS_ADM) && !defined(LOGGER_PROCESS_SNM) #define LOGGER_PROCESS_VSD #endif #ifdef LOGGER_PROCESS_SNM l7vs::LOG_CATEGORY_TAG param_cat = l7vs::LOG_CAT_SNMPAGENT_PARAMETER; #elif LOGGER_PROCESS_ADM l7vs::LOG_CATEGORY_TAG param_cat = l7vs::LOG_CAT_L7VSADM_PARAMETER; #else l7vs::LOG_CATEGORY_TAG param_cat = l7vs::LOG_CAT_L7VSD_PARAMETER; #endif /*! * Constructor of Parameter class */ l7vs::Parameter::Parameter() { } /*! * Destructor of Parameter class */ l7vs::Parameter::~Parameter() { } /*! * reload config file * @param[in] comp section TAG * @return true = success read file / false = failure read file */ bool l7vs::Parameter::read_file(PARAMETER_COMPONENT_TAG comp, const std::string &) { return true; } /*! * get integer data. * @param[in] comp section TAG * @param[in] key key string * @return value */ int l7vs::Parameter::get_int(const l7vs::PARAMETER_COMPONENT_TAG comp, const std::string &key, l7vs::error_code &err, const std::string &) { int value = 0; if (1000 <= get_int_stubmode) { err.setter(true, "don't find key"); } else if ("interval" == key && 1 != (get_int_stubmode % 100)) { value = get_int_table[0]; } else if ("cmponent_size_00" == key && 2 != (get_int_stubmode % 100)) { value = get_int_table[1]; } else if ("cmponent_size_01" == key && 3 != (get_int_stubmode % 100)) { value = get_int_table[2]; } else if ("cmponent_size_02" == key && 4 != (get_int_stubmode % 100)) { value = get_int_table[3]; } else if ("compulsorily_interval" == key && 5 != (get_int_stubmode % 100)) { value = get_int_table[4]; } else if (100 > get_int_stubmode) { err.setter(true, "don't find key"); } return value; } /*! * get character data. * @param[in] comp section TAG * @param[in] key key string * @return value */ std::string l7vs::Parameter::get_string(const l7vs::PARAMETER_COMPONENT_TAG comp, const std::string &key, l7vs::error_code &err, const std::string &) { std::string str(""); if (1000 <= get_string_stubmode) { err.setter(true, "don't find key"); } else if ("ip_addr" == key && 1 != (get_string_stubmode % 100)) { str = get_string_table[0]; } else if ("service_name" == key && 2 != (get_string_stubmode % 100)) { str = get_string_table[1]; } else if ("recv_ip_addr" == key && 3 != (get_string_stubmode % 100)) { str = get_string_table[2]; } else if ("cmponent_id_00" == key && 4 != (get_string_stubmode % 100)) { str = get_string_table[3]; } else if ("cmponent_id_01" == key && 5 != (get_string_stubmode % 100)) { str = get_string_table[4]; } else if ("cmponent_id_02" == key && 6 != (get_string_stubmode % 100)) { str = get_string_table[5]; } else if (100 > get_string_stubmode) { err.setter(true, "don't find key"); } return str; }
lgpl-2.1
gabeharms/firestorm
indra/media_plugins/gstreamer010/media_plugin_gstreamer010.cpp
1
33496
/** * @file media_plugin_gstreamer010.cpp * @brief GStreamer-0.10 plugin for LLMedia API plugin system * * @cond * $LicenseInfo:firstyear=2007&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * 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; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ * @endcond */ #include "linden_common.h" #include "llgl.h" #include "llplugininstance.h" #include "llpluginmessage.h" #include "llpluginmessageclasses.h" #include "media_plugin_base.h" #if LL_GSTREAMER010_ENABLED extern "C" { #include <gst/gst.h> } #include "llmediaimplgstreamer.h" #include "llmediaimplgstreamertriviallogging.h" #include "llmediaimplgstreamervidplug.h" #include "llmediaimplgstreamer_syms.h" // <FS:ND> extract stream metadata so we can report back into the client what's playing // <ML> Fix this to use llgst symbols so it will work in standard builds struct ndStreamMetadata { std::string mArtist; std::string mTitle; }; static void extractMetadata (const GstTagList * list, const gchar * tag, gpointer user_data) { int i, num; if( !user_data ) return; ndStreamMetadata *pOut( reinterpret_cast< ndStreamMetadata* >( user_data ) ); std::string *pStrOut(0); if( strcmp( tag, "title" ) == 0 ) pStrOut = &pOut->mTitle; else if( strcmp( tag, "artist" ) == 0 ) pStrOut = &pOut->mArtist; if( !pStrOut ) return; num = llgst_tag_list_get_tag_size (list, tag); for (i = 0; i < num; ++i) { const GValue *val( llgst_tag_list_get_value_index (list, tag, i) ); if (G_VALUE_HOLDS_STRING (val)) pStrOut->assign( g_value_get_string(val) ); } } // </FS:ND> ////////////////////////////////////////////////////////////////////////////// // class MediaPluginGStreamer010 : public MediaPluginBase { public: MediaPluginGStreamer010(LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data); ~MediaPluginGStreamer010(); /* virtual */ void receiveMessage(const char *message_string); static bool startup(); static bool closedown(); gboolean processGSTEvents(GstBus *bus, GstMessage *message); private: std::string getVersion(); bool navigateTo( const std::string urlIn ); bool seek( double time_sec ); bool setVolume( float volume ); // misc bool pause(); bool stop(); bool play(double rate); bool getTimePos(double &sec_out); static const double MIN_LOOP_SEC = 1.0F; bool mIsLooping; enum ECommand { COMMAND_NONE, COMMAND_STOP, COMMAND_PLAY, COMMAND_FAST_FORWARD, COMMAND_FAST_REWIND, COMMAND_PAUSE, COMMAND_SEEK, }; ECommand mCommand; private: bool unload(); bool load(); bool update(int milliseconds); void mouseDown( int x, int y ); void mouseUp( int x, int y ); void mouseMove( int x, int y ); void sizeChanged(); static bool mDoneInit; guint mBusWatchID; float mVolume; int mDepth; // media NATURAL size int mNaturalWidth; int mNaturalHeight; // media current size int mCurrentWidth; int mCurrentHeight; int mCurrentRowbytes; // previous media size so we can detect changes int mPreviousWidth; int mPreviousHeight; // desired render size from host int mWidth; int mHeight; // padded texture size we need to write into int mTextureWidth; int mTextureHeight; int mTextureFormatPrimary; int mTextureFormatType; bool mSeekWanted; double mSeekDestination; // Very GStreamer-specific GMainLoop *mPump; // event pump for this media GstElement *mPlaybin; GstElement *mVisualizer; GstSLVideo *mVideoSink; }; //static bool MediaPluginGStreamer010::mDoneInit = false; MediaPluginGStreamer010::MediaPluginGStreamer010( LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data ) : MediaPluginBase(host_send_func, host_user_data), mBusWatchID ( 0 ), mCurrentRowbytes ( 4 ), mTextureFormatPrimary ( GL_RGBA ), mTextureFormatType ( GL_UNSIGNED_INT_8_8_8_8_REV ), mSeekWanted(false), mSeekDestination(0.0), mPump ( NULL ), mPlaybin ( NULL ), mVisualizer ( NULL ), mVideoSink ( NULL ), mCommand ( COMMAND_NONE ) { std::ostringstream str; INFOMSG("MediaPluginGStreamer010 constructor - my PID=%u", U32(getpid())); } /////////////////////////////////////////////////////////////////////////////// // //#define LL_GST_REPORT_STATE_CHANGES #ifdef LL_GST_REPORT_STATE_CHANGES static char* get_gst_state_name(GstState state) { switch (state) { case GST_STATE_VOID_PENDING: return "VOID_PENDING"; case GST_STATE_NULL: return "NULL"; case GST_STATE_READY: return "READY"; case GST_STATE_PAUSED: return "PAUSED"; case GST_STATE_PLAYING: return "PLAYING"; } return "(unknown)"; } #endif // LL_GST_REPORT_STATE_CHANGES gboolean MediaPluginGStreamer010::processGSTEvents(GstBus *bus, GstMessage *message) { if (!message) return TRUE; // shield against GStreamer bug if (GST_MESSAGE_TYPE(message) != GST_MESSAGE_STATE_CHANGED && GST_MESSAGE_TYPE(message) != GST_MESSAGE_BUFFERING) { DEBUGMSG("Got GST message type: %s", LLGST_MESSAGE_TYPE_NAME (message)); } else { // TODO: grok 'duration' message type DEBUGMSG("Got GST message type: %s", LLGST_MESSAGE_TYPE_NAME (message)); } switch (GST_MESSAGE_TYPE (message)) { case GST_MESSAGE_BUFFERING: { // NEEDS GST 0.10.11+ if (llgst_message_parse_buffering) { gint percent = 0; llgst_message_parse_buffering(message, &percent); DEBUGMSG("GST buffering: %d%%", percent); } break; } case GST_MESSAGE_STATE_CHANGED: { GstState old_state; GstState new_state; GstState pending_state; llgst_message_parse_state_changed(message, &old_state, &new_state, &pending_state); #ifdef LL_GST_REPORT_STATE_CHANGES // not generally very useful, and rather spammy. DEBUGMSG("state change (old,<new>,pending): %s,<%s>,%s", get_gst_state_name(old_state), get_gst_state_name(new_state), get_gst_state_name(pending_state)); #endif // LL_GST_REPORT_STATE_CHANGES switch (new_state) { case GST_STATE_VOID_PENDING: break; case GST_STATE_NULL: break; case GST_STATE_READY: setStatus(STATUS_LOADED); break; case GST_STATE_PAUSED: setStatus(STATUS_PAUSED); break; case GST_STATE_PLAYING: setStatus(STATUS_PLAYING); break; } break; } // <FS:ND> In case of metadata upate, extract it, then send it back to the client case GST_MESSAGE_TAG: { ndStreamMetadata oMData; GstTagList *tags(0); llgst_message_parse_tag (message, &tags); llgst_tag_list_foreach (tags, extractMetadata, &oMData ); llgst_tag_list_free (tags); LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "ndMediadata_change"); message.setValue("title", oMData.mTitle ); message.setValue("artist", oMData.mArtist ); sendMessage(message); break; } // </FS:ND> case GST_MESSAGE_ERROR: { GError *err = NULL; gchar *debug = NULL; llgst_message_parse_error (message, &err, &debug); WARNMSG("GST error: %s", err?err->message:"(unknown)"); if (err) g_error_free (err); g_free (debug); mCommand = COMMAND_STOP; setStatus(STATUS_ERROR); break; } case GST_MESSAGE_INFO: { if (llgst_message_parse_info) { GError *err = NULL; gchar *debug = NULL; llgst_message_parse_info (message, &err, &debug); INFOMSG("GST info: %s", err?err->message:"(unknown)"); if (err) g_error_free (err); g_free (debug); } break; } case GST_MESSAGE_WARNING: { GError *err = NULL; gchar *debug = NULL; llgst_message_parse_warning (message, &err, &debug); WARNMSG("GST warning: %s", err?err->message:"(unknown)"); if (err) g_error_free (err); g_free (debug); break; } case GST_MESSAGE_EOS: /* end-of-stream */ DEBUGMSG("GST end-of-stream."); if (mIsLooping) { DEBUGMSG("looping media..."); double eos_pos_sec = 0.0F; bool got_eos_position = getTimePos(eos_pos_sec); if (got_eos_position && eos_pos_sec < MIN_LOOP_SEC) { // if we know that the movie is really short, don't // loop it else it can easily become a time-hog // because of GStreamer spin-up overhead DEBUGMSG("really short movie (%0.3fsec) - not gonna loop this, pausing instead.", eos_pos_sec); // inject a COMMAND_PAUSE mCommand = COMMAND_PAUSE; } else { #undef LLGST_LOOP_BY_SEEKING // loop with a stop-start instead of a seek, because it actually seems rather // faster than seeking on remote streams. #ifdef LLGST_LOOP_BY_SEEKING // first, try looping by an explicit rewind bool seeksuccess = seek(0.0); if (seeksuccess) { play(1.0); } else #endif // LLGST_LOOP_BY_SEEKING { // use clumsy stop-start to loop DEBUGMSG("didn't loop by rewinding - stopping and starting instead..."); stop(); play(1.0); } } } else // not a looping media { // inject a COMMAND_STOP mCommand = COMMAND_STOP; } break; default: /* unhandled message */ break; } /* we want to be notified again the next time there is a message * on the bus, so return true (false means we want to stop watching * for messages on the bus and our callback should not be called again) */ return TRUE; } extern "C" { gboolean llmediaimplgstreamer_bus_callback (GstBus *bus, GstMessage *message, gpointer data) { MediaPluginGStreamer010 *impl = (MediaPluginGStreamer010*)data; return impl->processGSTEvents(bus, message); } } // extern "C" bool MediaPluginGStreamer010::navigateTo ( const std::string urlIn ) { if (!mDoneInit) return false; // error setStatus(STATUS_LOADING); DEBUGMSG("Setting media URI: %s", urlIn.c_str()); mSeekWanted = false; if (NULL == mPump || NULL == mPlaybin) { setStatus(STATUS_ERROR); return false; // error } // set URI g_object_set (G_OBJECT (mPlaybin), "uri", urlIn.c_str(), NULL); //g_object_set (G_OBJECT (mPlaybin), "uri", "file:///tmp/movie", NULL); // navigateTo implicitly plays, too. play(1.0); return true; } bool MediaPluginGStreamer010::update(int milliseconds) { if (!mDoneInit) return false; // error DEBUGMSG("updating media..."); // sanity check if (NULL == mPump || NULL == mPlaybin) { DEBUGMSG("dead media..."); return false; } // see if there's an outstanding seek wanted if (mSeekWanted && // bleh, GST has to be happy that the movie is really truly playing // or it may quietly ignore the seek (with rtsp:// at least). (GST_STATE(mPlaybin) == GST_STATE_PLAYING)) { seek(mSeekDestination); mSeekWanted = false; } // *TODO: time-limit - but there isn't a lot we can do here, most // time is spent in gstreamer's own opaque worker-threads. maybe // we can do something sneaky like only unlock the video object // for 'milliseconds' and otherwise hold the lock. while (g_main_context_pending(g_main_loop_get_context(mPump))) { g_main_context_iteration(g_main_loop_get_context(mPump), FALSE); } // check for availability of a new frame if (mVideoSink) { GST_OBJECT_LOCK(mVideoSink); if (mVideoSink->retained_frame_ready) { DEBUGMSG("NEW FRAME READY"); if (mVideoSink->retained_frame_width != mCurrentWidth || mVideoSink->retained_frame_height != mCurrentHeight) // *TODO: also check for change in format { // just resize container, don't consume frame int neww = mVideoSink->retained_frame_width; int newh = mVideoSink->retained_frame_height; int newd = 4; mTextureFormatPrimary = GL_RGBA; mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV; /* int newd = SLVPixelFormatBytes[mVideoSink->retained_frame_format]; if (SLV_PF_BGRX == mVideoSink->retained_frame_format) { mTextureFormatPrimary = GL_BGRA; mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV; } else { mTextureFormatPrimary = GL_RGBA; mTextureFormatType = GL_UNSIGNED_INT_8_8_8_8_REV; } */ GST_OBJECT_UNLOCK(mVideoSink); mCurrentRowbytes = neww * newd; DEBUGMSG("video container resized to %dx%d", neww, newh); mDepth = newd; mCurrentWidth = neww; mCurrentHeight = newh; sizeChanged(); return true; } if (mPixels && mCurrentHeight <= mHeight && mCurrentWidth <= mWidth && !mTextureSegmentName.empty()) { // we're gonna totally consume this frame - reset 'ready' flag mVideoSink->retained_frame_ready = FALSE; int destination_rowbytes = mWidth * mDepth; for (int row=0; row<mCurrentHeight; ++row) { memcpy(&mPixels [destination_rowbytes * row], &mVideoSink->retained_frame_data [mCurrentRowbytes * row], mCurrentRowbytes); } GST_OBJECT_UNLOCK(mVideoSink); DEBUGMSG("NEW FRAME REALLY TRULY CONSUMED, TELLING HOST"); setDirty(0,0,mCurrentWidth,mCurrentHeight); } else { // new frame ready, but we're not ready to // consume it. GST_OBJECT_UNLOCK(mVideoSink); DEBUGMSG("NEW FRAME not consumed, still waiting for a shm segment and/or shm resize"); } return true; } else { // nothing to do yet. GST_OBJECT_UNLOCK(mVideoSink); return true; } } return true; } void MediaPluginGStreamer010::mouseDown( int x, int y ) { // do nothing } void MediaPluginGStreamer010::mouseUp( int x, int y ) { // do nothing } void MediaPluginGStreamer010::mouseMove( int x, int y ) { // do nothing } bool MediaPluginGStreamer010::pause() { DEBUGMSG("pausing media..."); // todo: error-check this? if (mDoneInit && mPlaybin) { llgst_element_set_state(mPlaybin, GST_STATE_PAUSED); return true; } return false; } bool MediaPluginGStreamer010::stop() { DEBUGMSG("stopping media..."); // todo: error-check this? if (mDoneInit && mPlaybin) { llgst_element_set_state(mPlaybin, GST_STATE_READY); return true; } return false; } bool MediaPluginGStreamer010::play(double rate) { // NOTE: we don't actually support non-natural rate. DEBUGMSG("playing media... rate=%f", rate); // todo: error-check this? if (mDoneInit && mPlaybin) { llgst_element_set_state(mPlaybin, GST_STATE_PLAYING); return true; } return false; } bool MediaPluginGStreamer010::setVolume( float volume ) { // we try to only update volume as conservatively as // possible, as many gst-plugins-base versions up to at least // November 2008 have critical race-conditions in setting volume - sigh if (mVolume == volume) return true; // nothing to do, everything's fine mVolume = volume; if (mDoneInit && mPlaybin) { g_object_set(mPlaybin, "volume", mVolume, NULL); return true; } return false; } bool MediaPluginGStreamer010::seek(double time_sec) { bool success = false; if (mDoneInit && mPlaybin) { success = llgst_element_seek(mPlaybin, 1.0F, GST_FORMAT_TIME, GstSeekFlags(GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT), GST_SEEK_TYPE_SET, gint64(time_sec*GST_SECOND), GST_SEEK_TYPE_NONE, GST_CLOCK_TIME_NONE); } DEBUGMSG("MEDIA SEEK REQUEST to %fsec result was %d", float(time_sec), int(success)); return success; } bool MediaPluginGStreamer010::getTimePos(double &sec_out) { bool got_position = false; if (mDoneInit && mPlaybin) { gint64 pos; GstFormat timefmt = GST_FORMAT_TIME; got_position = llgst_element_query_position && llgst_element_query_position(mPlaybin, &timefmt, &pos); got_position = got_position && (timefmt == GST_FORMAT_TIME); // GStreamer may have other ideas, but we consider the current position // undefined if not PLAYING or PAUSED got_position = got_position && (GST_STATE(mPlaybin) == GST_STATE_PLAYING || GST_STATE(mPlaybin) == GST_STATE_PAUSED); if (got_position && !GST_CLOCK_TIME_IS_VALID(pos)) { if (GST_STATE(mPlaybin) == GST_STATE_PLAYING) { // if we're playing then we treat an invalid clock time // as 0, for complicated reasons (insert reason here) pos = 0; } else { got_position = false; } } // If all the preconditions succeeded... we can trust the result. if (got_position) { sec_out = double(pos) / double(GST_SECOND); // gst to sec } } return got_position; } bool MediaPluginGStreamer010::load() { if (!mDoneInit) return false; // error setStatus(STATUS_LOADING); DEBUGMSG("setting up media..."); mIsLooping = false; mVolume = 0.1234567; // minor hack to force an initial volume update // Create a pumpable main-loop for this media mPump = g_main_loop_new (NULL, FALSE); if (!mPump) { setStatus(STATUS_ERROR); return false; // error } // instantiate a playbin element to do the hard work mPlaybin = llgst_element_factory_make ("playbin", "play"); if (!mPlaybin) { setStatus(STATUS_ERROR); return false; // error } // get playbin's bus GstBus *bus = llgst_pipeline_get_bus (GST_PIPELINE (mPlaybin)); if (!bus) { setStatus(STATUS_ERROR); return false; // error } mBusWatchID = llgst_bus_add_watch (bus, llmediaimplgstreamer_bus_callback, this); llgst_object_unref (bus); #if 0 // not quite stable/correct yet // get a visualizer element (bonus feature!) char* vis_name = getenv("LL_GST_VIS_NAME"); if (!vis_name || (vis_name && std::string(vis_name)!="none")) { if (vis_name) { mVisualizer = llgst_element_factory_make (vis_name, "vis"); } if (!mVisualizer) { mVisualizer = llgst_element_factory_make ("libvisual_jess", "vis"); if (!mVisualizer) { mVisualizer = llgst_element_factory_make ("goom", "vis"); if (!mVisualizer) { mVisualizer = llgst_element_factory_make ("libvisual_lv_scope", "vis"); if (!mVisualizer) { // That's okay, we don't NEED this. } } } } } #endif if (NULL == getenv("LL_GSTREAMER_EXTERNAL")) { // instantiate a custom video sink mVideoSink = GST_SLVIDEO(llgst_element_factory_make ("private-slvideo", "slvideo")); if (!mVideoSink) { WARNMSG("Could not instantiate private-slvideo element."); // todo: cleanup. setStatus(STATUS_ERROR); return false; // error } // connect the pieces g_object_set(mPlaybin, "video-sink", mVideoSink, NULL); } if (mVisualizer) { g_object_set(mPlaybin, "vis-plugin", mVisualizer, NULL); } return true; } bool MediaPluginGStreamer010::unload () { if (!mDoneInit) return false; // error DEBUGMSG("unloading media..."); // stop getting callbacks for this bus g_source_remove(mBusWatchID); mBusWatchID = 0; if (mPlaybin) { llgst_element_set_state (mPlaybin, GST_STATE_NULL); llgst_object_unref (GST_OBJECT (mPlaybin)); mPlaybin = NULL; } if (mVisualizer) { llgst_object_unref (GST_OBJECT (mVisualizer)); mVisualizer = NULL; } if (mPump) { g_main_loop_quit(mPump); mPump = NULL; } mVideoSink = NULL; setStatus(STATUS_NONE); return true; } //static bool MediaPluginGStreamer010::startup() { // first - check if GStreamer is explicitly disabled if (NULL != getenv("LL_DISABLE_GSTREAMER")) return false; // only do global GStreamer initialization once. if (!mDoneInit) { #if ( !defined(GLIB_MAJOR_VERSION) && !defined(GLIB_MINOR_VERSION) ) || ( GLIB_MAJOR_VERSION < 2 ) || ( GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 32 ) g_thread_init(NULL); #endif // Init the glib type system - we need it. #if ( !defined(GLIB_MAJOR_VERSION) && !defined(GLIB_MINOR_VERSION) ) || ( GLIB_MAJOR_VERSION < 2 ) || ( GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 35 ) g_type_init(); #endif // Get symbols! #if LL_DARWIN if (! grab_gst_syms("libgstreamer-0.10.dylib", "libgstvideo-0.10.dylib") ) #elseif LL_WINDOWS if (! grab_gst_syms("libgstreamer-0.10.dll", "libgstvideo-0.10.dll") ) #else // linux or other ELFy unixoid if (! grab_gst_syms("libgstreamer-0.10.so.0", "libgstvideo-0.10.so.0") ) #endif { WARNMSG("Couldn't find suitable GStreamer 0.10 support on this system - video playback disabled."); return false; } if (llgst_segtrap_set_enabled) { llgst_segtrap_set_enabled(FALSE); } else { WARNMSG("gst_segtrap_set_enabled() is not available; plugin crashes won't be caught."); } #if LL_LINUX // Gstreamer tries a fork during init, waitpid-ing on it, // which conflicts with any installed SIGCHLD handler... struct sigaction tmpact, oldact; if (llgst_registry_fork_set_enabled) { // if we can disable SIGCHLD-using forking behaviour, // do it. llgst_registry_fork_set_enabled(false); } else { // else temporarily install default SIGCHLD handler // while GStreamer initialises tmpact.sa_handler = SIG_DFL; sigemptyset( &tmpact.sa_mask ); tmpact.sa_flags = SA_SIGINFO; sigaction(SIGCHLD, &tmpact, &oldact); } #endif // LL_LINUX // Protect against GStreamer resetting the locale, yuck. static std::string saved_locale; saved_locale = setlocale(LC_ALL, NULL); // finally, try to initialize GStreamer! GError *err = NULL; gboolean init_gst_success = llgst_init_check(NULL, NULL, &err); // restore old locale setlocale(LC_ALL, saved_locale.c_str() ); #if LL_LINUX // restore old SIGCHLD handler if (!llgst_registry_fork_set_enabled) sigaction(SIGCHLD, &oldact, NULL); #endif // LL_LINUX if (!init_gst_success) // fail { if (err) { WARNMSG("GST init failed: %s", err->message); g_error_free(err); } else { WARNMSG("GST init failed for unspecified reason."); } return false; } // Init our custom plugins - only really need do this once. gst_slvideo_init_class(); mDoneInit = true; } return true; } void MediaPluginGStreamer010::sizeChanged() { // the shared writing space has possibly changed size/location/whatever // Check to see whether the movie's NATURAL size has been set yet if (1 == mNaturalWidth && 1 == mNaturalHeight) { mNaturalWidth = mCurrentWidth; mNaturalHeight = mCurrentHeight; DEBUGMSG("Media NATURAL size better detected as %dx%d", mNaturalWidth, mNaturalHeight); } // if the size has changed then the shm has changed and the app needs telling if (mCurrentWidth != mPreviousWidth || mCurrentHeight != mPreviousHeight) { mPreviousWidth = mCurrentWidth; mPreviousHeight = mCurrentHeight; LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "size_change_request"); message.setValue("name", mTextureSegmentName); message.setValueS32("width", mNaturalWidth); message.setValueS32("height", mNaturalHeight); DEBUGMSG("<--- Sending size change request to application with name: '%s' - natural size is %d x %d", mTextureSegmentName.c_str(), mNaturalWidth, mNaturalHeight); sendMessage(message); } } //static bool MediaPluginGStreamer010::closedown() { if (!mDoneInit) return false; // error ungrab_gst_syms(); mDoneInit = false; return true; } MediaPluginGStreamer010::~MediaPluginGStreamer010() { DEBUGMSG("MediaPluginGStreamer010 destructor"); closedown(); DEBUGMSG("GStreamer010 closing down"); } std::string MediaPluginGStreamer010::getVersion() { std::string plugin_version = "GStreamer010 media plugin, GStreamer version "; if (mDoneInit && llgst_version) { guint major, minor, micro, nano; llgst_version(&major, &minor, &micro, &nano); plugin_version += llformat("%u.%u.%u.%u (runtime), %u.%u.%u.%u (headers)", (unsigned int)major, (unsigned int)minor, (unsigned int)micro, (unsigned int)nano, (unsigned int)GST_VERSION_MAJOR, (unsigned int)GST_VERSION_MINOR, (unsigned int)GST_VERSION_MICRO, (unsigned int)GST_VERSION_NANO); } else { plugin_version += "(unknown)"; } return plugin_version; } void MediaPluginGStreamer010::receiveMessage(const char *message_string) { //std::cerr << "MediaPluginGStreamer010::receiveMessage: received message: \"" << message_string << "\"" << std::endl; LLPluginMessage message_in; if(message_in.parse(message_string) >= 0) { std::string message_class = message_in.getClass(); std::string message_name = message_in.getName(); if(message_class == LLPLUGIN_MESSAGE_CLASS_BASE) { if(message_name == "init") { LLPluginMessage message("base", "init_response"); LLSD versions = LLSD::emptyMap(); versions[LLPLUGIN_MESSAGE_CLASS_BASE] = LLPLUGIN_MESSAGE_CLASS_BASE_VERSION; versions[LLPLUGIN_MESSAGE_CLASS_MEDIA] = LLPLUGIN_MESSAGE_CLASS_MEDIA_VERSION; versions[LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME] = LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME_VERSION; message.setValueLLSD("versions", versions); if ( load() ) { DEBUGMSG("GStreamer010 media instance set up"); } else { WARNMSG("GStreamer010 media instance failed to set up"); } message.setValue("plugin_version", getVersion()); sendMessage(message); } else if(message_name == "idle") { // no response is necessary here. double time = message_in.getValueReal("time"); // Convert time to milliseconds for update() update((int)(time * 1000.0f)); } else if(message_name == "cleanup") { unload(); closedown(); } else if(message_name == "shm_added") { SharedSegmentInfo info; info.mAddress = message_in.getValuePointer("address"); info.mSize = (size_t)message_in.getValueS32("size"); std::string name = message_in.getValue("name"); std::ostringstream str; INFOMSG("MediaPluginGStreamer010::receiveMessage: shared memory added, name: %s, size: %d, address: %p", name.c_str(), int(info.mSize), info.mAddress); mSharedSegments.insert(SharedSegmentMap::value_type(name, info)); } else if(message_name == "shm_remove") { std::string name = message_in.getValue("name"); DEBUGMSG("MediaPluginGStreamer010::receiveMessage: shared memory remove, name = %s", name.c_str()); SharedSegmentMap::iterator iter = mSharedSegments.find(name); if(iter != mSharedSegments.end()) { if(mPixels == iter->second.mAddress) { // This is the currently active pixel buffer. Make sure we stop drawing to it. mPixels = NULL; mTextureSegmentName.clear(); // Make sure the movie decoder is no longer pointed at the shared segment. sizeChanged(); } mSharedSegments.erase(iter); } else { WARNMSG("MediaPluginGStreamer010::receiveMessage: unknown shared memory region!"); } // Send the response so it can be cleaned up. LLPluginMessage message("base", "shm_remove_response"); message.setValue("name", name); sendMessage(message); } else { std::ostringstream str; INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown base message: %s", message_name.c_str()); } } else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA) { if(message_name == "init") { // Plugin gets to decide the texture parameters to use. LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "texture_params"); // lame to have to decide this now, it depends on the movie. Oh well. mDepth = 4; mCurrentWidth = 1; mCurrentHeight = 1; mPreviousWidth = 1; mPreviousHeight = 1; mNaturalWidth = 1; mNaturalHeight = 1; mWidth = 1; mHeight = 1; mTextureWidth = 1; mTextureHeight = 1; message.setValueU32("format", GL_RGBA); message.setValueU32("type", GL_UNSIGNED_INT_8_8_8_8_REV); message.setValueS32("depth", mDepth); message.setValueS32("default_width", mWidth); message.setValueS32("default_height", mHeight); message.setValueU32("internalformat", GL_RGBA8); message.setValueBoolean("coords_opengl", true); // true == use OpenGL-style coordinates, false == (0,0) is upper left. message.setValueBoolean("allow_downsample", true); // we respond with grace and performance if asked to downscale sendMessage(message); } else if(message_name == "size_change") { std::string name = message_in.getValue("name"); S32 width = message_in.getValueS32("width"); S32 height = message_in.getValueS32("height"); S32 texture_width = message_in.getValueS32("texture_width"); S32 texture_height = message_in.getValueS32("texture_height"); std::ostringstream str; INFOMSG("---->Got size change instruction from application with shm name: %s - size is %d x %d", name.c_str(), width, height); LLPluginMessage message(LLPLUGIN_MESSAGE_CLASS_MEDIA, "size_change_response"); message.setValue("name", name); message.setValueS32("width", width); message.setValueS32("height", height); message.setValueS32("texture_width", texture_width); message.setValueS32("texture_height", texture_height); sendMessage(message); if(!name.empty()) { // Find the shared memory region with this name SharedSegmentMap::iterator iter = mSharedSegments.find(name); if(iter != mSharedSegments.end()) { INFOMSG("*** Got size change with matching shm, new size is %d x %d", width, height); INFOMSG("*** Got size change with matching shm, texture size size is %d x %d", texture_width, texture_height); mPixels = (unsigned char*)iter->second.mAddress; mTextureSegmentName = name; mWidth = width; mHeight = height; if (texture_width > 1 || texture_height > 1) // not a dummy size from the app, a real explicit forced size { INFOMSG("**** = REAL RESIZE REQUEST FROM APP"); GST_OBJECT_LOCK(mVideoSink); mVideoSink->resize_forced_always = true; mVideoSink->resize_try_width = texture_width; mVideoSink->resize_try_height = texture_height; GST_OBJECT_UNLOCK(mVideoSink); } mTextureWidth = texture_width; mTextureHeight = texture_height; } } } else if(message_name == "load_uri") { std::string uri = message_in.getValue("uri"); navigateTo( uri ); sendStatus(); } else if(message_name == "mouse_event") { std::string event = message_in.getValue("event"); S32 x = message_in.getValueS32("x"); S32 y = message_in.getValueS32("y"); if(event == "down") { mouseDown(x, y); } else if(event == "up") { mouseUp(x, y); } else if(event == "move") { mouseMove(x, y); }; }; } else if(message_class == LLPLUGIN_MESSAGE_CLASS_MEDIA_TIME) { if(message_name == "stop") { stop(); } else if(message_name == "start") { double rate = 0.0; if(message_in.hasValue("rate")) { rate = message_in.getValueReal("rate"); } // NOTE: we don't actually support rate. play(rate); } else if(message_name == "pause") { pause(); } else if(message_name == "seek") { double time = message_in.getValueReal("time"); // defer the actual seek in case we haven't // really truly started yet in which case there // is nothing to seek upon mSeekWanted = true; mSeekDestination = time; } else if(message_name == "set_loop") { bool loop = message_in.getValueBoolean("loop"); mIsLooping = loop; } else if(message_name == "set_volume") { double volume = message_in.getValueReal("volume"); setVolume(volume); } } else { INFOMSG("MediaPluginGStreamer010::receiveMessage: unknown message class: %s", message_class.c_str()); } } } int init_media_plugin(LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data, LLPluginInstance::sendMessageFunction *plugin_send_func, void **plugin_user_data) { if (MediaPluginGStreamer010::startup()) { MediaPluginGStreamer010 *self = new MediaPluginGStreamer010(host_send_func, host_user_data); *plugin_send_func = MediaPluginGStreamer010::staticReceiveMessage; *plugin_user_data = (void*)self; return 0; // okay } else { return -1; // failed to init } } #else // LL_GSTREAMER010_ENABLED // Stubbed-out class with constructor/destructor (necessary or windows linker // will just think its dead code and optimize it all out) class MediaPluginGStreamer010 : public MediaPluginBase { public: MediaPluginGStreamer010(LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data); ~MediaPluginGStreamer010(); /* virtual */ void receiveMessage(const char *message_string); }; MediaPluginGStreamer010::MediaPluginGStreamer010( LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data ) : MediaPluginBase(host_send_func, host_user_data) { // no-op } MediaPluginGStreamer010::~MediaPluginGStreamer010() { // no-op } void MediaPluginGStreamer010::receiveMessage(const char *message_string) { // no-op } // We're building without GStreamer enabled. Just refuse to initialize. int init_media_plugin(LLPluginInstance::sendMessageFunction host_send_func, void *host_user_data, LLPluginInstance::sendMessageFunction *plugin_send_func, void **plugin_user_data) { return -1; } #endif // LL_GSTREAMER010_ENABLED
lgpl-2.1
youfoh/webkit-efl
Source/WebKit2/UIProcess/API/efl/ewk_custom_handlers.cpp
1
3908
/* Copyright (C) 2012 Samsung Electronics This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "ewk_custom_handlers.h" #if (ENABLE_TIZEN_REGISTER_PROTOCOL_HANDLER) || (ENABLE_TIZEN_REGISTER_CONTENT_HANDLER) || (ENABLE_TIZEN_CUSTOM_SCHEME_HANDLER) #include "ewk_view_private.h" struct _Ewk_Custom_Handlers_Data { const char* target; const char* base_url; const char* url; const char* title; Ewk_Custom_Handlers_State result; }; const char* ewk_custom_handlers_data_target_get(Ewk_Custom_Handlers_Data* customHandlersData) { EINA_SAFETY_ON_NULL_RETURN_VAL(customHandlersData, 0); return customHandlersData->target; } const char* ewk_custom_handlers_data_base_url_get(Ewk_Custom_Handlers_Data* customHandlersData) { EINA_SAFETY_ON_NULL_RETURN_VAL(customHandlersData, 0); return customHandlersData->base_url; } const char* ewk_custom_handlers_data_url_get(Ewk_Custom_Handlers_Data* customHandlersData) { EINA_SAFETY_ON_NULL_RETURN_VAL(customHandlersData, 0); return customHandlersData->url; } const char* ewk_custom_handlers_data_title_get(Ewk_Custom_Handlers_Data* customHandlersData) { EINA_SAFETY_ON_NULL_RETURN_VAL(customHandlersData, 0); return customHandlersData->title; } void ewk_custom_handlers_data_result_set(Ewk_Custom_Handlers_Data* customHandlersData, Ewk_Custom_Handlers_State result) { EINA_SAFETY_ON_NULL_RETURN(customHandlersData); customHandlersData->result = result; } Ewk_Custom_Handlers_State ewkGetCustomHandlersDataResult(Ewk_Custom_Handlers_Data* customHandlersData) { EINA_SAFETY_ON_NULL_RETURN_VAL(customHandlersData, EWK_CUSTOM_HANDLERS_DECLINED); return customHandlersData->result; } Ewk_Custom_Handlers_Data* ewkCustomHandlersCreateData(const char* target, const char* baseUrl, const char* url, const char* title) { Ewk_Custom_Handlers_Data* customHandlersData = new Ewk_Custom_Handlers_Data; customHandlersData->target = eina_stringshare_add(target); customHandlersData->base_url = eina_stringshare_add(baseUrl); customHandlersData->url = eina_stringshare_add(url); customHandlersData->title = eina_stringshare_add(title); return customHandlersData; } Ewk_Custom_Handlers_Data* ewkCustomHandlersCreateData(const char* target, const char* baseUrl, const char* url) { Ewk_Custom_Handlers_Data* customHandlersData = new Ewk_Custom_Handlers_Data; customHandlersData->target = eina_stringshare_add(target); customHandlersData->base_url = eina_stringshare_add(baseUrl); customHandlersData->url = eina_stringshare_add(url); customHandlersData->title = 0; return customHandlersData; } void ewkCustomHandlersDeleteData(Ewk_Custom_Handlers_Data* customHandlersData) { eina_stringshare_del(customHandlersData->target); eina_stringshare_del(customHandlersData->base_url); eina_stringshare_del(customHandlersData->url); if(customHandlersData->title) eina_stringshare_del(customHandlersData->title); delete customHandlersData; } #endif // #if (ENABLE_TIZEN_REGISTER_PROTOCOL_HANDLER) || (ENABLE_TIZEN_REGISTER_CONTENT_HANDLER) || (ENABLE_TIZEN_CUSTOM_SCHEME_HANDLER)
lgpl-2.1
tmcguire/qt-mobility
src/versitorganizer/qversitorganizerpluginloader_p.cpp
2
5106
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QPluginLoader> #include "qversitorganizerpluginloader_p.h" #include "qmobilitypluginsearch.h" QTM_USE_NAMESPACE /*! A less-than function for factory indices (see QVersitOrganizerHandlerFactory::index()). Positive values come first (ascendingly), then zero, then negative values (ascendingly). */ bool factoryLessThan(QVersitOrganizerHandlerFactory* a, QVersitOrganizerHandlerFactory* b) { if ((a->index() > 0 && b->index() > 0) || (a->index() < 0 && b->index() < 0)) // same sign return a->index() < b->index(); else // a is zero // or b is zero // or opposite sign return b->index() < a->index(); } QVersitOrganizerPluginLoader* QVersitOrganizerPluginLoader::mInstance = NULL; /*! * \class QVersitOrganizerPluginLoader * \internal * This is a singleton class that loads Versit plugins for organizer item processing */ QVersitOrganizerPluginLoader::QVersitOrganizerPluginLoader() : mTimeZoneHandler(NULL) { } /*! * Returns the singleton instance of the QVersitOrganizerPluginLoader. */ QVersitOrganizerPluginLoader* QVersitOrganizerPluginLoader::instance() { if (!mInstance) mInstance = new QVersitOrganizerPluginLoader; return mInstance; } void QVersitOrganizerPluginLoader::loadPlugins() { QStringList plugins = mobilityPlugins(QLatin1String("versit")); if (plugins != mPluginPaths) { mPluginPaths = plugins; foreach (const QString& pluginPath, mPluginPaths) { QPluginLoader qpl(pluginPath); QObject* plugin = qpl.instance(); QVersitOrganizerHandlerFactory* organizerPlugin = qobject_cast<QVersitOrganizerHandlerFactory*>(plugin); if (organizerPlugin && !mLoadedFactories.contains(organizerPlugin->name())) { mLoadedFactories.insert(organizerPlugin->name()); mOrganizerHandlerFactories.append(organizerPlugin); } else if (!mTimeZoneHandler) { QVersitTimeZoneHandler* timeZonePlugin = qobject_cast<QVersitTimeZoneHandler*>(plugin); if (timeZonePlugin) { mTimeZoneHandler = timeZonePlugin; } } } qSort(mOrganizerHandlerFactories.begin(), mOrganizerHandlerFactories.end(), factoryLessThan); } } /*! * Creates and returns handlers from the plugin. If \a profile is the empty string, only handlers * with an empty profile list are returned. If \a profile is nonempty, only handlers with either * an empty profile list or a profile list that contains the given \a profile are returned. * * The caller is responsible for deleting all returned handlers. */ QList<QVersitOrganizerHandler*> QVersitOrganizerPluginLoader::createOrganizerHandlers(const QString& profile) { loadPlugins(); QList<QVersitOrganizerHandler*> handlers; foreach (const QVersitOrganizerHandlerFactory* factory, mOrganizerHandlerFactories) { if (factory->profiles().isEmpty() || (!profile.isEmpty() && factory->profiles().contains(profile))) { QVersitOrganizerHandler* handler = factory->createHandler(); handlers.append(handler); } } return handlers; } QVersitTimeZoneHandler* QVersitOrganizerPluginLoader::timeZoneHandler() { loadPlugins(); return mTimeZoneHandler; }
lgpl-2.1
qtproject/qt-labs-qbs
src/lib/corelib/jsextensions/utilitiesextension.cpp
2
39073
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <api/languageinfo.h> #include <jsextensions/jsextensions.h> #include <language/scriptengine.h> #include <logging/translator.h> #include <tools/architectures.h> #include <tools/hostosinfo.h> #include <tools/stringconstants.h> #include <tools/toolchains.h> #include <tools/version.h> #if defined(Q_OS_MACOS) || defined(Q_OS_OSX) #include <tools/applecodesignutils.h> #endif #ifdef __APPLE__ #include <ar.h> #include <mach/machine.h> #include <mach-o/fat.h> #include <mach-o/loader.h> #ifndef FAT_MAGIC_64 #define FAT_MAGIC_64 0xcafebabf #define FAT_CIGAM_64 0xbfbafeca struct fat_arch_64 { cpu_type_t cputype; cpu_subtype_t cpusubtype; uint64_t offset; uint64_t size; uint32_t align; uint32_t reserved; }; #endif #endif #ifdef Q_OS_WIN #include <tools/clangclinfo.h> #include <tools/msvcinfo.h> #include <tools/vsenvironmentdetector.h> #endif #include <QtCore/qcryptographichash.h> #include <QtCore/qdir.h> #include <QtCore/qendian.h> #include <QtCore/qfile.h> #include <QtCore/qlibrary.h> #include <QtScript/qscriptable.h> #include <QtScript/qscriptengine.h> namespace qbs { namespace Internal { class DummyLogSink : public ILogSink { void doPrintMessage(LoggerLevel, const QString &, const QString &) override { } }; class UtilitiesExtension : public QObject, QScriptable { Q_OBJECT public: static QScriptValue js_ctor(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_canonicalArchitecture(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_canonicalPlatform(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_canonicalTargetArchitecture(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_canonicalToolchain(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_cStringQuote(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_getHash(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_getNativeSetting(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_kernelVersion(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_nativeSettingGroups(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_rfc1034identifier(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_smimeMessageContent(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_certificateInfo(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_signingIdentities(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_msvcCompilerInfo(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_clangClCompilerInfo(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_installedMSVCs(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_installedClangCls(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_versionCompare(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_qmlTypeInfo(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_builtinExtensionNames(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_isSharedLibrary(QScriptContext *context, QScriptEngine *engine); static QScriptValue js_getArchitecturesFromBinary(QScriptContext *context, QScriptEngine *engine); }; QScriptValue UtilitiesExtension::js_ctor(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(engine); return context->throwError(Tr::tr("'Utilities' cannot be instantiated.")); } QScriptValue UtilitiesExtension::js_canonicalPlatform(QScriptContext *context, QScriptEngine *engine) { const QScriptValue value = context->argument(0); if (value.isUndefined() || value.isNull()) return engine->toScriptValue(QStringList()); if (context->argumentCount() == 1 && value.isString()) { return engine->toScriptValue([&value] { QStringList list; for (const auto &s : HostOsInfo::canonicalOSIdentifiers(value.toString().toStdString())) list.push_back(QString::fromStdString(s)); return list; }()); } return context->throwError(QScriptContext::SyntaxError, QStringLiteral("canonicalPlatform expects one argument of type string")); } QScriptValue UtilitiesExtension::js_canonicalTargetArchitecture(QScriptContext *context, QScriptEngine *engine) { const QScriptValue arch = context->argument(0); if (arch.isUndefined() || arch.isNull()) return arch; QScriptValue endianness = context->argument(1); if (endianness.isUndefined() || endianness.isNull()) endianness = QString(); const QScriptValue vendor = context->argument(2); const QScriptValue system = context->argument(3); const QScriptValue abi = context->argument(4); if (!arch.isString() || !endianness.isString() || !vendor.isString() || !system.isString() || !abi.isString()) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("canonicalTargetArchitecture expects 1 to 5 arguments of type string")); return engine->toScriptValue(canonicalTargetArchitecture(arch.toString(), endianness.toString(), vendor.toString(), system.toString(), abi.toString())); } QScriptValue UtilitiesExtension::js_canonicalArchitecture(QScriptContext *context, QScriptEngine *engine) { const QScriptValue value = context->argument(0); if (value.isUndefined() || value.isNull()) return value; if (context->argumentCount() == 1 && value.isString()) return engine->toScriptValue(canonicalArchitecture(value.toString())); return context->throwError(QScriptContext::SyntaxError, QStringLiteral("canonicalArchitecture expects one argument of type string")); } QScriptValue UtilitiesExtension::js_canonicalToolchain(QScriptContext *context, QScriptEngine *engine) { QStringList toolchain; for (int i = 0; i < context->argumentCount(); ++i) toolchain << context->argument(i).toString(); return engine->toScriptValue(canonicalToolchain(toolchain)); } // copied from src/corelib/tools/qtools_p.h Q_DECL_CONSTEXPR inline char toHexUpper(uint value) Q_DECL_NOTHROW { return "0123456789ABCDEF"[value & 0xF]; } Q_DECL_CONSTEXPR inline int fromHex(uint c) Q_DECL_NOTHROW { return ((c >= '0') && (c <= '9')) ? int(c - '0') : ((c >= 'A') && (c <= 'F')) ? int(c - 'A' + 10) : ((c >= 'a') && (c <= 'f')) ? int(c - 'a' + 10) : /* otherwise */ -1; } // copied from src/corelib/io/qdebug.cpp static inline bool isPrintable(uchar c) { return c >= ' ' && c < 0x7f; } // modified template <typename Char> static inline QString escapedString(const Char *begin, int length, bool isUnicode = true) { QChar quote(QLatin1Char('"')); QString out = quote; bool lastWasHexEscape = false; const Char *end = begin + length; for (const Char *p = begin; p != end; ++p) { // check if we need to insert "" to break an hex escape sequence if (Q_UNLIKELY(lastWasHexEscape)) { if (fromHex(*p) != -1) { // yes, insert it out += QLatin1Char('"'); out += QLatin1Char('"'); } lastWasHexEscape = false; } if (sizeof(Char) == sizeof(QChar)) { // Surrogate characters are category Cs (Other_Surrogate), so isPrintable = false for them int runLength = 0; while (p + runLength != end && QChar::isPrint(p[runLength]) && p[runLength] != '\\' && p[runLength] != '"') ++runLength; if (runLength) { out += QString(reinterpret_cast<const QChar *>(p), runLength); p += runLength - 1; continue; } } else if (isPrintable(*p) && *p != '\\' && *p != '"') { QChar c = QLatin1Char(*p); out += c; continue; } // print as an escape sequence (maybe, see below for surrogate pairs) int buflen = 2; ushort buf[sizeof "\\U12345678" - 1]; buf[0] = '\\'; switch (*p) { case '"': case '\\': buf[1] = *p; break; case '\b': buf[1] = 'b'; break; case '\f': buf[1] = 'f'; break; case '\n': buf[1] = 'n'; break; case '\r': buf[1] = 'r'; break; case '\t': buf[1] = 't'; break; default: if (!isUnicode) { // print as hex escape buf[1] = 'x'; buf[2] = toHexUpper(uchar(*p) >> 4); buf[3] = toHexUpper(uchar(*p)); buflen = 4; lastWasHexEscape = true; break; } if (QChar::isHighSurrogate(*p)) { if ((p + 1) != end && QChar::isLowSurrogate(p[1])) { // properly-paired surrogates uint ucs4 = QChar::surrogateToUcs4(*p, p[1]); if (QChar::isPrint(ucs4)) { buf[0] = *p; buf[1] = p[1]; buflen = 2; } else { buf[1] = 'U'; buf[2] = '0'; // toHexUpper(ucs4 >> 32); buf[3] = '0'; // toHexUpper(ucs4 >> 28); buf[4] = toHexUpper(ucs4 >> 20); buf[5] = toHexUpper(ucs4 >> 16); buf[6] = toHexUpper(ucs4 >> 12); buf[7] = toHexUpper(ucs4 >> 8); buf[8] = toHexUpper(ucs4 >> 4); buf[9] = toHexUpper(ucs4); buflen = 10; } ++p; break; } // improperly-paired surrogates, fall through } buf[1] = 'u'; buf[2] = toHexUpper(ushort(*p) >> 12); buf[3] = toHexUpper(ushort(*p) >> 8); buf[4] = toHexUpper(*p >> 4); buf[5] = toHexUpper(*p); buflen = 6; } out += QString(reinterpret_cast<QChar *>(buf), buflen); } out += quote; return out; } QScriptValue UtilitiesExtension::js_cStringQuote(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() < 1)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("cStringQuote expects 1 argument")); } QString value = context->argument(0).toString(); return engine->toScriptValue(escapedString(reinterpret_cast<const ushort *>(value.constData()), value.size())); } QScriptValue UtilitiesExtension::js_getHash(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() < 1)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("getHash expects 1 argument")); } const QByteArray input = context->argument(0).toString().toLatin1(); const QByteArray hash = QCryptographicHash::hash(input, QCryptographicHash::Sha1).toHex().left(16); return engine->toScriptValue(QString::fromLatin1(hash)); } QScriptValue UtilitiesExtension::js_getNativeSetting(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() < 1 || context->argumentCount() > 3)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("getNativeSetting expects between 1 and 3 arguments")); } QString key = context->argumentCount() > 1 ? context->argument(1).toString() : QString(); // We'll let empty string represent the default registry value if (HostOsInfo::isWindowsHost() && key.isEmpty()) key = StringConstants::dot(); QVariant defaultValue = context->argumentCount() > 2 ? context->argument(2).toVariant() : QVariant(); QSettings settings(context->argument(0).toString(), QSettings::NativeFormat); QVariant value = settings.value(key, defaultValue); return value.isNull() ? engine->undefinedValue() : engine->toScriptValue(value); } QScriptValue UtilitiesExtension::js_kernelVersion(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(context); return engine->toScriptValue(QSysInfo::kernelVersion()); } QScriptValue UtilitiesExtension::js_nativeSettingGroups(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() != 1)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("nativeSettingGroups expects 1 argument")); } QSettings settings(context->argument(0).toString(), QSettings::NativeFormat); return engine->toScriptValue(settings.childGroups()); } QScriptValue UtilitiesExtension::js_rfc1034identifier(QScriptContext *context, QScriptEngine *engine) { if (Q_UNLIKELY(context->argumentCount() != 1)) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("rfc1034Identifier expects 1 argument")); const QString identifier = context->argument(0).toString(); return engine->toScriptValue(HostOsInfo::rfc1034Identifier(identifier)); } /** * Reads the contents of the S/MIME message located at \p filePath. * An equivalent command line would be: * \code security cms -D -i <infile> -o <outfile> \endcode * or: * \code openssl smime -verify -noverify -inform DER -in <infile> -out <outfile> \endcode * * \note A provisioning profile is an S/MIME message whose contents are an XML property list, * so this method can be used to read such files. */ QScriptValue UtilitiesExtension::js_smimeMessageContent(QScriptContext *context, QScriptEngine *engine) { #if !defined(Q_OS_MACOS) && !defined(Q_OS_OSX) Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("smimeMessageContent is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() != 1)) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("smimeMessageContent expects 1 argument")); const QString filePath = context->argument(0).toString(); QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) return engine->undefinedValue(); QByteArray content = smimeMessageContent(file.readAll()); if (content.isEmpty()) return engine->undefinedValue(); return engine->toScriptValue(content); #endif } QScriptValue UtilitiesExtension::js_certificateInfo(QScriptContext *context, QScriptEngine *engine) { #if !defined(Q_OS_MACOS) && !defined(Q_OS_OSX) Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("certificateInfo is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() != 1)) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("certificateInfo expects 1 argument")); return engine->toScriptValue(certificateInfo(context->argument(0).toVariant().toByteArray())); #endif } // Rough command line equivalent: security find-identity -p codesigning -v QScriptValue UtilitiesExtension::js_signingIdentities(QScriptContext *context, QScriptEngine *engine) { #if !defined(Q_OS_MACOS) && !defined(Q_OS_OSX) Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("signingIdentities is not available on this platform")); #else Q_UNUSED(context); return engine->toScriptValue(identitiesProperties()); #endif } #ifdef Q_OS_WIN static std::pair<QVariantMap /*result*/, QString /*error*/> msvcCompilerInfoHelper( const QString &compilerFilePath, MSVC::CompilerLanguage language, const QString &vcvarsallPath, const QString &arch, const QString &sdkVersion) { MSVC msvc(compilerFilePath, arch, sdkVersion); VsEnvironmentDetector envdetector(vcvarsallPath); if (!envdetector.start(&msvc)) return { {}, QStringLiteral("Detecting the MSVC build environment failed: ") + envdetector.errorString() }; try { QVariantMap envMap; for (const QString &key : msvc.environment.keys()) envMap.insert(key, msvc.environment.value(key)); return { QVariantMap { {QStringLiteral("buildEnvironment"), envMap}, {QStringLiteral("macros"), msvc.compilerDefines(compilerFilePath, language)}, }, {} }; } catch (const qbs::ErrorInfo &info) { return { {}, info.toString() }; } } #endif QScriptValue UtilitiesExtension::js_msvcCompilerInfo(QScriptContext *context, QScriptEngine *engine) { #ifndef Q_OS_WIN Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("msvcCompilerInfo is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() < 3)) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("msvcCompilerInfo expects 3 arguments")); const QString compilerFilePath = context->argument(0).toString(); const QString compilerLanguage = context->argument(1).toString(); const QString sdkVersion = !context->argument(2).isNull() && !context->argument(2).isUndefined() ? context->argument(2).toString() : QString(); MSVC::CompilerLanguage language; if (compilerLanguage == QStringLiteral("c")) language = MSVC::CLanguage; else if (compilerLanguage == StringConstants::cppLang()) language = MSVC::CPlusPlusLanguage; else return context->throwError(QScriptContext::TypeError, QStringLiteral("msvcCompilerInfo expects \"c\" or \"cpp\" as its second argument")); const auto result = msvcCompilerInfoHelper( compilerFilePath, language, {}, MSVC::architectureFromClPath(compilerFilePath), sdkVersion); if (result.first.isEmpty()) return context->throwError(QScriptContext::UnknownError, result.second); return engine->toScriptValue(result.first); #endif } QScriptValue UtilitiesExtension::js_clangClCompilerInfo(QScriptContext *context, QScriptEngine *engine) { #ifndef Q_OS_WIN Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("clangClCompilerInfo is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() < 5)) return context->throwError(QScriptContext::SyntaxError, QStringLiteral("clangClCompilerInfo expects 5 arguments")); const QString compilerFilePath = context->argument(0).toString(); // architecture cannot be empty as vcvarsall.bat requires at least 1 arg, so fallback // to host architecture if none is present QString arch = !context->argument(1).isNull() && !context->argument(1).isUndefined() ? context->argument(1).toString() : QString::fromStdString(HostOsInfo::hostOSArchitecture()); QString vcvarsallPath = context->argument(2).toString(); const QString compilerLanguage = !context->argument(3).isNull() && !context->argument(3).isUndefined() ? context->argument(3).toString() : QString(); const QString sdkVersion = !context->argument(4).isNull() && !context->argument(4).isUndefined() ? context->argument(4).toString() : QString(); MSVC::CompilerLanguage language; if (compilerLanguage == QStringLiteral("c")) language = MSVC::CLanguage; else if (compilerLanguage == StringConstants::cppLang()) language = MSVC::CPlusPlusLanguage; else return context->throwError(QScriptContext::TypeError, QStringLiteral("clangClCompilerInfo expects \"c\" or \"cpp\" as its fourth argument")); const auto result = msvcCompilerInfoHelper( compilerFilePath, language, vcvarsallPath, arch, sdkVersion); if (result.first.isEmpty()) return context->throwError(QScriptContext::UnknownError, result.second); return engine->toScriptValue(result.first); #endif } QScriptValue UtilitiesExtension::js_installedMSVCs(QScriptContext *context, QScriptEngine *engine) { #ifndef Q_OS_WIN Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("installedMSVCs is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() != 1)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("installedMSVCs expects 1 arguments")); } const auto value0 = context->argument(0); const auto hostArch = QString::fromStdString(HostOsInfo::hostOSArchitecture()); const auto preferredArch = !value0.isNull() && !value0.isUndefined() ? value0.toString() : hostArch; DummyLogSink dummySink; Logger dummyLogger(&dummySink); auto msvcs = MSVC::installedCompilers(dummyLogger); const auto predicate = [&preferredArch, &hostArch](const MSVC &msvc) { auto archPair = MSVC::getHostTargetArchPair(msvc.architecture); return archPair.first != hostArch || preferredArch != archPair.second; }; msvcs.erase(std::remove_if(msvcs.begin(), msvcs.end(), predicate), msvcs.end()); QVariantList result; for (const auto &msvc: msvcs) result.append(msvc.toVariantMap()); return engine->toScriptValue(result); #endif } QScriptValue UtilitiesExtension::js_installedClangCls( QScriptContext *context, QScriptEngine *engine) { #ifndef Q_OS_WIN Q_UNUSED(engine); return context->throwError(QScriptContext::UnknownError, QStringLiteral("installedClangCls is not available on this platform")); #else if (Q_UNLIKELY(context->argumentCount() != 1)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("installedClangCls expects 1 arguments")); } const auto value0 = context->argument(0); const auto path = !value0.isNull() && !value0.isUndefined() ? value0.toString() : QString(); DummyLogSink dummySink; Logger dummyLogger(&dummySink); auto compilers = ClangClInfo::installedCompilers({path}, dummyLogger); QVariantList result; for (const auto &compiler: compilers) result.append(compiler.toVariantMap()); return engine->toScriptValue(result); #endif } QScriptValue UtilitiesExtension::js_versionCompare(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 2) { const QScriptValue value1 = context->argument(0); const QScriptValue value2 = context->argument(1); if (value1.isString() && value2.isString()) { const auto a = Version::fromString(value1.toString()); const auto b = Version::fromString(value2.toString()); return engine->toScriptValue(compare(a, b)); } } return context->throwError(QScriptContext::SyntaxError, QStringLiteral("versionCompare expects two arguments of type string")); } QScriptValue UtilitiesExtension::js_qmlTypeInfo(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(context); return engine->toScriptValue(QString::fromStdString(qbs::LanguageInfo::qmlTypeInfo())); } QScriptValue UtilitiesExtension::js_builtinExtensionNames(QScriptContext *context, QScriptEngine *engine) { Q_UNUSED(context); return engine->toScriptValue(JsExtensions::extensionNames()); } QScriptValue UtilitiesExtension::js_isSharedLibrary(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() == 1) { const QScriptValue value = context->argument(0); if (value.isString()) return engine->toScriptValue(QLibrary::isLibrary(value.toString())); } return context->throwError(QScriptContext::SyntaxError, QStringLiteral("isSharedLibrary expects one argument of type string")); } #ifdef __APPLE__ template <typename T = uint32_t> T readInt(QIODevice *ioDevice, bool *ok, bool swap, bool peek = false) { const auto bytes = peek ? ioDevice->peek(sizeof(T)) : ioDevice->read(sizeof(T)); if (bytes.size() != sizeof(T)) { if (ok) *ok = false; return T(); } if (ok) *ok = true; T n = *reinterpret_cast<const T *>(bytes.constData()); return swap ? qbswap(n) : n; } static QString archName(cpu_type_t cputype, cpu_subtype_t cpusubtype) { switch (cputype) { case CPU_TYPE_X86: switch (cpusubtype) { case CPU_SUBTYPE_X86_ALL: return QStringLiteral("i386"); default: return {}; } case CPU_TYPE_X86_64: switch (cpusubtype) { case CPU_SUBTYPE_X86_64_ALL: return QStringLiteral("x86_64"); case CPU_SUBTYPE_X86_64_H: return QStringLiteral("x86_64h"); default: return {}; } case CPU_TYPE_ARM: switch (cpusubtype) { case CPU_SUBTYPE_ARM_V7: return QStringLiteral("armv7a"); case CPU_SUBTYPE_ARM_V7S: return QStringLiteral("armv7s"); case CPU_SUBTYPE_ARM_V7K: return QStringLiteral("armv7k"); default: return {}; } case CPU_TYPE_ARM64: switch (cpusubtype) { case CPU_SUBTYPE_ARM64_ALL: return QStringLiteral("arm64"); default: return {}; } default: return {}; } } static QStringList detectMachOArchs(QIODevice *device) { bool ok; bool foundMachO = false; qint64 pos = device->pos(); char ar_header[SARMAG]; if (device->read(ar_header, SARMAG) == SARMAG) { if (strncmp(ar_header, ARMAG, SARMAG) == 0) { while (!device->atEnd()) { static_assert(sizeof(ar_hdr) == 60, "sizeof(ar_hdr) != 60"); ar_hdr header; if (device->read(reinterpret_cast<char *>(&header), sizeof(ar_hdr)) != sizeof(ar_hdr)) return {}; // If the file name is stored in the "extended format" manner, // the real filename is prepended to the data section, so skip that many bytes int filenameLength = 0; if (strncmp(header.ar_name, AR_EFMT1, sizeof(AR_EFMT1) - 1) == 0) { char arName[sizeof(header.ar_name)] = { 0 }; memcpy(arName, header.ar_name + sizeof(AR_EFMT1) - 1, sizeof(header.ar_name) - (sizeof(AR_EFMT1) - 1) - 1); filenameLength = strtoul(arName, nullptr, 10); if (device->read(filenameLength).size() != filenameLength) return {}; } switch (readInt(device, nullptr, false, true)) { case MH_CIGAM: case MH_CIGAM_64: case MH_MAGIC: case MH_MAGIC_64: foundMachO = true; break; default: { // Skip the data and go to the next archive member... char szBuf[sizeof(header.ar_size) + 1] = { 0 }; memcpy(szBuf, header.ar_size, sizeof(header.ar_size)); int sz = static_cast<int>(strtoul(szBuf, nullptr, 10)); if (sz % 2 != 0) ++sz; sz -= filenameLength; const auto data = device->read(sz); if (data.size() != sz) return {}; } } if (foundMachO) break; } } } // Wasn't an archive file, so try a fat file if (!foundMachO && !device->seek(pos)) return {}; pos = device->pos(); fat_header fatheader; fatheader.magic = readInt(device, nullptr, false); if (fatheader.magic == FAT_MAGIC || fatheader.magic == FAT_CIGAM || fatheader.magic == FAT_MAGIC_64 || fatheader.magic == FAT_CIGAM_64) { const bool swap = fatheader.magic == FAT_CIGAM || fatheader.magic == FAT_CIGAM_64; const bool is64bit = fatheader.magic == FAT_MAGIC_64 || fatheader.magic == FAT_CIGAM_64; fatheader.nfat_arch = readInt(device, &ok, swap); if (!ok) return {}; QStringList archs; for (uint32_t n = 0; n < fatheader.nfat_arch; ++n) { fat_arch_64 fatarch; static_assert(sizeof(fat_arch_64) == 32, "sizeof(fat_arch_64) != 32"); static_assert(sizeof(fat_arch) == 20, "sizeof(fat_arch) != 20"); const qint64 expectedBytes = is64bit ? sizeof(fat_arch_64) : sizeof(fat_arch); if (device->read(reinterpret_cast<char *>(&fatarch), expectedBytes) != expectedBytes) return {}; if (swap) { fatarch.cputype = qbswap(fatarch.cputype); fatarch.cpusubtype = qbswap(fatarch.cpusubtype); } const QString name = archName(fatarch.cputype, fatarch.cpusubtype); if (name.isEmpty()) { qWarning("Unknown cputype %d and cpusubtype %d", fatarch.cputype, fatarch.cpusubtype); return {}; } archs.push_back(name); } std::sort(archs.begin(), archs.end()); return archs; } // Wasn't a fat file, so we just read a thin Mach-O from the original offset if (!device->seek(pos)) return {}; bool swap = false; mach_header header; header.magic = readInt(device, nullptr, swap); switch (header.magic) { case MH_CIGAM: case MH_CIGAM_64: swap = true; break; case MH_MAGIC: case MH_MAGIC_64: break; default: return {}; } header.cputype = static_cast<cpu_type_t>(readInt(device, &ok, swap)); if (!ok) return {}; header.cpusubtype = static_cast<cpu_subtype_t>(readInt(device, &ok, swap)); if (!ok) return {}; const QString name = archName(header.cputype, header.cpusubtype); if (name.isEmpty()) { qWarning("Unknown cputype %d and cpusubtype %d", header.cputype, header.cpusubtype); return {}; } return {name}; } #endif QScriptValue UtilitiesExtension::js_getArchitecturesFromBinary(QScriptContext *context, QScriptEngine *engine) { if (context->argumentCount() != 1) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("getArchitecturesFromBinary expects exactly one argument")); } const QScriptValue arg = context->argument(0); if (!arg.isString()) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("getArchitecturesFromBinary expects a string argument")); } QStringList archs; #ifdef __APPLE__ QFile file(arg.toString()); if (!file.open(QIODevice::ReadOnly)) { return context->throwError(QScriptContext::SyntaxError, QStringLiteral("Failed to open file '%1': %2") .arg(file.fileName(), file.errorString())); } archs = detectMachOArchs(&file); #endif // __APPLE__ return engine->toScriptValue(archs); } } // namespace Internal } // namespace qbs void initializeJsExtensionUtilities(QScriptValue extensionObject) { using namespace qbs::Internal; QScriptEngine *engine = extensionObject.engine(); QScriptValue environmentObj = engine->newQMetaObject(&UtilitiesExtension::staticMetaObject, engine->newFunction(&UtilitiesExtension::js_ctor)); environmentObj.setProperty(QStringLiteral("canonicalArchitecture"), engine->newFunction(UtilitiesExtension::js_canonicalArchitecture, 1)); environmentObj.setProperty(QStringLiteral("canonicalPlatform"), engine->newFunction(UtilitiesExtension::js_canonicalPlatform, 1)); environmentObj.setProperty(QStringLiteral("canonicalTargetArchitecture"), engine->newFunction( UtilitiesExtension::js_canonicalTargetArchitecture, 4)); environmentObj.setProperty(QStringLiteral("canonicalToolchain"), engine->newFunction(UtilitiesExtension::js_canonicalToolchain)); environmentObj.setProperty(QStringLiteral("cStringQuote"), engine->newFunction(UtilitiesExtension::js_cStringQuote, 1)); environmentObj.setProperty(QStringLiteral("getHash"), engine->newFunction(UtilitiesExtension::js_getHash, 1)); environmentObj.setProperty(QStringLiteral("getNativeSetting"), engine->newFunction(UtilitiesExtension::js_getNativeSetting, 3)); environmentObj.setProperty(QStringLiteral("kernelVersion"), engine->newFunction(UtilitiesExtension::js_kernelVersion, 0)); environmentObj.setProperty(QStringLiteral("nativeSettingGroups"), engine->newFunction(UtilitiesExtension::js_nativeSettingGroups, 1)); environmentObj.setProperty(QStringLiteral("rfc1034Identifier"), engine->newFunction(UtilitiesExtension::js_rfc1034identifier, 1)); environmentObj.setProperty(QStringLiteral("smimeMessageContent"), engine->newFunction(UtilitiesExtension::js_smimeMessageContent, 1)); environmentObj.setProperty(QStringLiteral("certificateInfo"), engine->newFunction(UtilitiesExtension::js_certificateInfo, 1)); environmentObj.setProperty(QStringLiteral("signingIdentities"), engine->newFunction(UtilitiesExtension::js_signingIdentities, 0)); environmentObj.setProperty(QStringLiteral("msvcCompilerInfo"), engine->newFunction(UtilitiesExtension::js_msvcCompilerInfo, 1)); environmentObj.setProperty(QStringLiteral("clangClCompilerInfo"), engine->newFunction(UtilitiesExtension::js_clangClCompilerInfo, 1)); environmentObj.setProperty(QStringLiteral("installedMSVCs"), engine->newFunction(UtilitiesExtension::js_installedMSVCs, 1)); environmentObj.setProperty(QStringLiteral("installedClangCls"), engine->newFunction(UtilitiesExtension::js_installedClangCls, 1)); environmentObj.setProperty(QStringLiteral("versionCompare"), engine->newFunction(UtilitiesExtension::js_versionCompare, 2)); environmentObj.setProperty(QStringLiteral("qmlTypeInfo"), engine->newFunction(UtilitiesExtension::js_qmlTypeInfo, 0)); environmentObj.setProperty(QStringLiteral("builtinExtensionNames"), engine->newFunction(UtilitiesExtension::js_builtinExtensionNames, 0)); environmentObj.setProperty(QStringLiteral("isSharedLibrary"), engine->newFunction(UtilitiesExtension::js_isSharedLibrary, 1)); environmentObj.setProperty(QStringLiteral("getArchitecturesFromBinary"), engine->newFunction(UtilitiesExtension::js_getArchitecturesFromBinary, 1)); extensionObject.setProperty(QStringLiteral("Utilities"), environmentObj); } Q_DECLARE_METATYPE(qbs::Internal::UtilitiesExtension *) #include "utilitiesextension.moc"
lgpl-2.1
pruiz/wkhtmltopdf-qt
demos/sub-attaq/progressitem.cpp
2
2084
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "progressitem.h" #include "pixmapitem.h" ProgressItem::ProgressItem (QGraphicsItem * parent) : QGraphicsTextItem(parent), currentLevel(1), currentScore(0) { setFont(QFont("Comic Sans MS")); setPos(parentItem()->boundingRect().topRight() - QPointF(180, -5)); } void ProgressItem::setLevel(int level) { currentLevel = level; updateProgress(); } void ProgressItem::setScore(int score) { currentScore = score; updateProgress(); } void ProgressItem::updateProgress() { setHtml(QString("Level : %1 Score : %2").arg(currentLevel).arg(currentScore)); }
lgpl-2.1
foss-for-synopsys-dwc-arc-processors/uClibc
libc/inet/rpc/pmap_rmt.c
2
11476
/* @(#)pmap_rmt.c 2.2 88/08/01 4.0 RPCSRC */ /* * Sun RPC is a product of Sun Microsystems, Inc. and is provided for * unrestricted use provided that this legend is included on all tape * media and as a part of the software program in whole or part. Users * may copy or modify Sun RPC without charge, but are not authorized * to license or distribute it to anyone else except as part of a product or * program developed by the user. * * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun RPC is provided with no support and without any obligation on the * part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ #if 0 static char sccsid[] = "@(#)pmap_rmt.c 1.21 87/08/27 Copyr 1984 Sun Micro"; #endif /* * pmap_rmt.c * Client interface to pmap rpc service. * remote call and broadcast service * * Copyright (C) 1984, Sun Microsystems, Inc. */ #include <unistd.h> #include <string.h> #include "rpc_private.h" #include <rpc/pmap_prot.h> #include <rpc/pmap_clnt.h> #include <rpc/pmap_rmt.h> #include <sys/poll.h> #include <sys/socket.h> #include <stdio.h> #include <errno.h> #include <sys/param.h> /* Ultrix needs before net/if --roland@gnu */ #include <net/if.h> #include <sys/ioctl.h> #include <arpa/inet.h> #define MAX_BROADCAST_SIZE 1400 static const struct timeval timeout = {3, 0}; /* * pmapper remote-call-service interface. * This routine is used to call the pmapper remote call service * which will look up a service program in the port maps, and then * remotely call that routine with the given parameters. This allows * programs to do a lookup and call in one step. */ enum clnt_stat pmap_rmtcall (struct sockaddr_in *addr, u_long prog, u_long vers, u_long proc, xdrproc_t xdrargs, caddr_t argsp, xdrproc_t xdrres, caddr_t resp, struct timeval tout, u_long *port_ptr) { int _socket = -1; CLIENT *client; struct rmtcallargs a; struct rmtcallres r; enum clnt_stat stat; addr->sin_port = htons (PMAPPORT); client = clntudp_create (addr, PMAPPROG, PMAPVERS, timeout, &_socket); if (client != (CLIENT *) NULL) { a.prog = prog; a.vers = vers; a.proc = proc; a.args_ptr = argsp; a.xdr_args = xdrargs; r.port_ptr = port_ptr; r.results_ptr = resp; r.xdr_results = xdrres; stat = CLNT_CALL (client, PMAPPROC_CALLIT, (xdrproc_t)xdr_rmtcall_args, (caddr_t)&a, (xdrproc_t)xdr_rmtcallres, (caddr_t)&r, tout); CLNT_DESTROY (client); } else { stat = RPC_FAILED; } /* (void)close(_socket); CLNT_DESTROY already closed it */ addr->sin_port = 0; return stat; } /* * XDR remote call arguments * written for XDR_ENCODE direction only */ bool_t xdr_rmtcall_args (XDR *xdrs, struct rmtcallargs *cap) { u_int lenposition, argposition, position; if (xdr_u_long (xdrs, &(cap->prog)) && xdr_u_long (xdrs, &(cap->vers)) && xdr_u_long (xdrs, &(cap->proc))) { u_long dummy_arglen = 0; lenposition = XDR_GETPOS (xdrs); if (!xdr_u_long (xdrs, &dummy_arglen)) return FALSE; argposition = XDR_GETPOS (xdrs); if (!(*(cap->xdr_args)) (xdrs, cap->args_ptr)) return FALSE; position = XDR_GETPOS (xdrs); cap->arglen = (u_long) position - (u_long) argposition; XDR_SETPOS (xdrs, lenposition); if (!xdr_u_long (xdrs, &(cap->arglen))) return FALSE; XDR_SETPOS (xdrs, position); return TRUE; } return FALSE; } libc_hidden_def(xdr_rmtcall_args) /* * XDR remote call results * written for XDR_DECODE direction only */ bool_t xdr_rmtcallres (XDR *xdrs, struct rmtcallres *crp) { caddr_t port_ptr; port_ptr = (caddr_t) crp->port_ptr; if (xdr_reference (xdrs, &port_ptr, sizeof (u_long), (xdrproc_t) xdr_u_long) && xdr_u_long (xdrs, &crp->resultslen)) { crp->port_ptr = (u_long *) port_ptr; return (*(crp->xdr_results)) (xdrs, crp->results_ptr); } return FALSE; } libc_hidden_def(xdr_rmtcallres) /* * The following is kludged-up support for simple rpc broadcasts. * Someday a large, complicated system will replace these trivial * routines which only support udp/ip . */ static int internal_function getbroadcastnets (struct in_addr *addrs, int sock, char *buf) /* int sock: any valid socket will do */ /* char *buf: why allocate more when we can use existing... */ { struct ifconf ifc; struct ifreq ifreq, *ifr; struct sockaddr_in *sin; int n, i; ifc.ifc_len = UDPMSGSIZE; ifc.ifc_buf = buf; if (ioctl (sock, SIOCGIFCONF, (char *) &ifc) < 0) { perror ("broadcast: ioctl (get interface configuration)"); return (0); } ifr = ifc.ifc_req; for (i = 0, n = ifc.ifc_len / sizeof (struct ifreq); n > 0; n--, ifr++) { ifreq = *ifr; if (ioctl (sock, SIOCGIFFLAGS, (char *) &ifreq) < 0) { perror ("broadcast: ioctl (get interface flags)"); continue; } if ((ifreq.ifr_flags & IFF_BROADCAST) && (ifreq.ifr_flags & IFF_UP) && ifr->ifr_addr.sa_family == AF_INET) { sin = (struct sockaddr_in *) &ifr->ifr_addr; #ifdef SIOCGIFBRDADDR /* 4.3BSD */ if (ioctl (sock, SIOCGIFBRDADDR, (char *) &ifreq) < 0) { addrs[i++] = inet_makeaddr (inet_netof /* Changed to pass struct instead of s_addr member by roland@gnu. */ (sin->sin_addr), INADDR_ANY); } else { addrs[i++] = ((struct sockaddr_in *) &ifreq.ifr_addr)->sin_addr; } #else /* 4.2 BSD */ addrs[i++] = inet_makeaddr (inet_netof (sin->sin_addr.s_addr), INADDR_ANY); #endif } } return i; } enum clnt_stat clnt_broadcast ( u_long prog, /* program number */ u_long vers, /* version number */ u_long proc, /* procedure number */ xdrproc_t xargs, /* xdr routine for args */ caddr_t argsp, /* pointer to args */ xdrproc_t xresults, /* xdr routine for results */ caddr_t resultsp, /* pointer to results */ resultproc_t eachresult /* call with each result obtained */) { enum clnt_stat stat = RPC_FAILED; AUTH *unix_auth = authunix_create_default (); XDR xdr_stream; XDR *xdrs = &xdr_stream; struct timeval t; int outlen, inlen, nets; socklen_t fromlen; int sock; int on = 1; struct pollfd fd; int milliseconds; int i; bool_t done = FALSE; u_long xid; u_long port; struct in_addr addrs[20]; struct sockaddr_in baddr, raddr; /* broadcast and response addresses */ struct rmtcallargs a; struct rmtcallres r; struct rpc_msg msg; char outbuf[MAX_BROADCAST_SIZE], inbuf[UDPMSGSIZE]; /* * initialization: create a socket, a broadcast address, and * preserialize the arguments into a send buffer. */ if ((sock = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror ("Cannot create socket for broadcast rpc"); stat = RPC_CANTSEND; goto done_broad; } #ifdef SO_BROADCAST if (setsockopt (sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof (on)) < 0) { perror ("Cannot set socket option SO_BROADCAST"); stat = RPC_CANTSEND; goto done_broad; } #endif /* def SO_BROADCAST */ fd.fd = sock; fd.events = POLLIN; nets = getbroadcastnets (addrs, sock, inbuf); memset ((char *) &baddr, 0, sizeof (baddr)); baddr.sin_family = AF_INET; baddr.sin_port = htons (PMAPPORT); baddr.sin_addr.s_addr = htonl (INADDR_ANY); /* baddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); */ msg.rm_xid = xid = _create_xid (); t.tv_usec = 0; msg.rm_direction = CALL; msg.rm_call.cb_rpcvers = RPC_MSG_VERSION; msg.rm_call.cb_prog = PMAPPROG; msg.rm_call.cb_vers = PMAPVERS; msg.rm_call.cb_proc = PMAPPROC_CALLIT; msg.rm_call.cb_cred = unix_auth->ah_cred; msg.rm_call.cb_verf = unix_auth->ah_verf; a.prog = prog; a.vers = vers; a.proc = proc; a.xdr_args = xargs; a.args_ptr = argsp; r.port_ptr = &port; r.xdr_results = xresults; r.results_ptr = resultsp; xdrmem_create (xdrs, outbuf, MAX_BROADCAST_SIZE, XDR_ENCODE); if ((!xdr_callmsg (xdrs, &msg)) || (!xdr_rmtcall_args (xdrs, &a))) { stat = RPC_CANTENCODEARGS; goto done_broad; } outlen = (int) xdr_getpos (xdrs); xdr_destroy (xdrs); /* * Basic loop: broadcast a packet and wait a while for response(s). * The response timeout grows larger per iteration. */ for (t.tv_sec = 4; t.tv_sec <= 14; t.tv_sec += 2) { for (i = 0; i < nets; i++) { baddr.sin_addr = addrs[i]; if (sendto (sock, outbuf, outlen, 0, (struct sockaddr *) &baddr, sizeof (struct sockaddr)) != outlen) { perror ("Cannot send broadcast packet"); stat = RPC_CANTSEND; goto done_broad; } } if (eachresult == NULL) { stat = RPC_SUCCESS; goto done_broad; } recv_again: msg.acpted_rply.ar_verf = _null_auth; msg.acpted_rply.ar_results.where = (caddr_t) & r; msg.acpted_rply.ar_results.proc = (xdrproc_t) xdr_rmtcallres; milliseconds = t.tv_sec * 1000 + t.tv_usec / 1000; switch (poll(&fd, 1, milliseconds)) { case 0: /* timed out */ stat = RPC_TIMEDOUT; continue; case -1: /* some kind of error */ if (errno == EINTR) goto recv_again; perror ("Broadcast poll problem"); stat = RPC_CANTRECV; goto done_broad; } /* end of poll results switch */ try_again: fromlen = sizeof (struct sockaddr); inlen = recvfrom (sock, inbuf, UDPMSGSIZE, 0, (struct sockaddr *) &raddr, &fromlen); if (inlen < 0) { if (errno == EINTR) goto try_again; perror ("Cannot receive reply to broadcast"); stat = RPC_CANTRECV; goto done_broad; } if ((size_t) inlen < sizeof (u_long)) goto recv_again; /* * see if reply transaction id matches sent id. * If so, decode the results. */ xdrmem_create (xdrs, inbuf, (u_int) inlen, XDR_DECODE); if (xdr_replymsg (xdrs, &msg)) { if (((u_int32_t) msg.rm_xid == (u_int32_t) xid) && (msg.rm_reply.rp_stat == MSG_ACCEPTED) && (msg.acpted_rply.ar_stat == SUCCESS)) { raddr.sin_port = htons ((u_short) port); done = (*eachresult) (resultsp, &raddr); } /* otherwise, we just ignore the errors ... */ } else { #ifdef notdef /* some kind of deserialization problem ... */ if ((u_int32_t) msg.rm_xid == (u_int32_t) xid) fprintf (stderr, "Broadcast deserialization problem"); /* otherwise, just random garbage */ #endif } xdrs->x_op = XDR_FREE; msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void; (void) xdr_replymsg (xdrs, &msg); (void) (*xresults) (xdrs, resultsp); xdr_destroy (xdrs); if (done) { stat = RPC_SUCCESS; goto done_broad; } else { goto recv_again; } } done_broad: (void) close (sock); AUTH_DESTROY (unix_auth); return stat; }
lgpl-2.1
heartvalve/oce
src/IGESFile/igesread.c
4
3960
/* Copyright (c) 1999-2014 OPEN CASCADE SAS This file is part of Open CASCADE Technology software library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation, with special exception defined in the file OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT distribution for complete text of the license and disclaimer of any warranty. Alternatively, this file may be used under the terms of Open CASCADE commercial license or contractual agreement. */ /* Regroupement des sources "C" pour compilation */ #include <stdio.h> #include "igesread.h" #include <OSD_OpenFile.hxx> /* void IGESFile_Check21 (int mode,char * code, int num, char * str); */ void IGESFile_Check3 (int mode,char * code); void IGESFile_Check2 (int mode,char * code, int num, char * str); /* #include "structiges.c" ... fait par analiges qui en a l'usage ... */ void iges_initfile(); int iges_lire (FILE* lefic, int *numsec, char ligne[100], int modefnes); void iges_newparam(int typarg,int longval, char *parval); void iges_param(int *Pstat,char *ligne,char c_separ,char c_fin,int lonlin); void iges_Dsect (int *Dstat,int numsec,char* ligne); void iges_Psect(int numsec,char ligne[80]); /* Routine de lecture generale d'un fichier IGES Assure l'enchainement des appels necessaires Il en resulte un ensemble de donnees (struct C) interrogeables par routines ad hoc (cf igesread.h qui les recapitule pour appel par C++) Retourne : 0 si OK, 1 si fichier pas pu etre ouvert */ /* MGE 16/06/98*/ /* To use strcpy*/ /*#include <string.h>*/ /* To use Msg class */ /*#include <MoniTool_Msg.hxx>*/ static char sects [] = " SGDPT "; int igesread (char* nomfic, int lesect[6], int modefnes) { /* MGE 16/06/98 */ FILE* lefic; char ligne[100]; int numsec, numl; int i; int i0;int j; char str[2]; int Dstat = 0; int Pstat = 0; char c_separ = ','; char c_fin = ';'; iges_initfile(); lefic = stdin; i0 = numsec = 0; numl = 0; if (nomfic[0] != '\0') lefic = OSD_OpenFile(nomfic,"r"); if (lefic == NULL) return -1; /* fichier pas pu etre ouvert */ for (i = 1; i < 6; i++) lesect[i] = 0; for (j = 0; j < 100; j++) ligne[j] = 0; for(;;) { numl ++; i = iges_lire(lefic,&numsec,ligne,modefnes); if (i <= 0) { if (i == 0) break; /* Sending of message : Syntax error */ { str[1] = '\0'; str[0] = sects[i0]; IGESFile_Check2 (0,"XSTEP_18",numl,str); /* //gka 15 Sep 98: str instead of sects[i0]); */ } if (i0 == 0) return -1; lesect[i0] ++; continue; } lesect[i] ++; i0 = i; if (numsec != lesect[i]) { /* Sending of message : Syntax error */ str[1] = '\0'; str[0] = sects[i0]; IGESFile_Check2 (0,"XSTEP_19",numl,str); /* //gka 15 Sep 98: str instead of sects[i0]); */ } if (i == 1) { /* Start Section (comm.) */ ligne[72] = '\0'; iges_newparam (0,72,ligne); } if (i == 2) { /* Header (Global sect) */ iges_setglobal(); for (;;) { if (lesect[i] == 1) { /* Separation specifique */ int n0 = 0; if (ligne[0] != ',') { c_separ = ligne[2]; n0 = 3; } if (ligne[n0+1] != c_separ) { c_fin = ligne[n0+3]; } } iges_param(&Pstat,ligne,c_separ,c_fin,72); if (Pstat != 2) break; } } if (i == 3) iges_Dsect(&Dstat,numsec,ligne); /* Directory (Dsect) */ if (i == 4) { /* Parametres (Psect) */ iges_Psect(numsec,ligne); for (;;) { iges_param(&Pstat,ligne,c_separ,c_fin,64); if (Pstat != 2) break; } } } /* Sending of message : No Terminal Section */ if (lesect[5] == 0) { IGESFile_Check3 (1, "XSTEP_20"); //return -1; } fclose (lefic); return 0; }
lgpl-2.1
richardmg/qtsensors
src/plugins/sensors/linux/linuxsysaccelerometer.cpp
4
5305
/**************************************************************************** ** ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSensors module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "linuxsysaccelerometer.h" #include <QtCore/QDebug> #include <QtCore/QtGlobal> #include <QtCore/QFile> #include <QtCore/QDebug> #include <QtCore/QTimer> #include <QtCore/QStringList> #include <time.h> #include <errno.h> char const * const LinuxSysAccelerometer::id("linuxsys.accelerometer"); // This plugin reads the accelerometer from a sys interface. // test machine (laptop): // QT_ACCEL_FILEPATH=/sys/devices/platform/lis3lv02d/position // QT_ACCEL_DATADIVISOR=7 // QT_ACCEL_DELIMITER=, quint64 produceTimestamp() { struct timespec tv; int ok; #ifdef CLOCK_MONOTONIC_RAW ok = clock_gettime(CLOCK_MONOTONIC_RAW, &tv); if (ok != 0) #endif ok = clock_gettime(CLOCK_MONOTONIC, &tv); Q_ASSERT(ok == 0); quint64 result = (tv.tv_sec * 1000000ULL) + (tv.tv_nsec * 0.001); // scale to microseconds return result; } // TODO get output template from env and apply // Currently this assumes the output is like: // (x,y,z) or x,y,z LinuxSysAccelerometer::LinuxSysAccelerometer(QSensor *sensor) : QSensorBackend(sensor) , m_timerid(0) , path(QString()) , divisor(0) , delimiter(QString()) { setReading<QAccelerometerReading>(&m_reading); addDataRate(1, 100); // 100Hz addOutputRange(-22.418, 22.418, 0.17651); // 2G // not sure how to retrieve proper range path = QString::fromLatin1(qgetenv("QT_ACCEL_FILEPATH")); bool ok; divisor = QString::fromLatin1(qgetenv("QT_ACCEL_DATADIVISOR")).toInt(&ok); if (divisor == 0 || !ok) { divisor = 1; } delimiter = QString::fromLatin1(qgetenv("QT_ACCEL_DELIMITER")); file.setFileName(path); } LinuxSysAccelerometer::~LinuxSysAccelerometer() { } void LinuxSysAccelerometer::start() { if (m_timerid) return; if (!openFile()) return; int dataRate = sensor()->dataRate(); if (dataRate == 0) { if (sensor()->availableDataRates().count()) dataRate = sensor()->availableDataRates().first().second; else dataRate = 1; } int interval = 1000 / dataRate; if (interval) m_timerid = startTimer(interval); } void LinuxSysAccelerometer::stop() { if (m_timerid) { killTimer(m_timerid); m_timerid = 0; } closeFile(); } void LinuxSysAccelerometer::poll() { if (!file.isOpen()) return; file.seek(0); QString str = file.readLine(); if (str.isEmpty()) { return; } str = str.simplified(); if (!str.at(0).isNumber() && str.at(0) != '-') { str.remove(0,1); } if (!str.at(str.size()-1).isNumber()) { str.chop(1); } QStringList accelDataList = str.split(delimiter); m_reading.setTimestamp(produceTimestamp()); m_reading.setX(-accelDataList.at(0).toFloat() / divisor); m_reading.setY(-accelDataList.at(1).toFloat() / divisor); m_reading.setZ(-accelDataList.at(2).toFloat() / divisor); newReadingAvailable(); } void LinuxSysAccelerometer::timerEvent(QTimerEvent * /*event*/) { poll(); } bool LinuxSysAccelerometer::openFile() { if (!path.isEmpty() && !file.open(QIODevice::ReadOnly)) { qWarning() << "Could not open file" << strerror(errno); return false; } return true; } void LinuxSysAccelerometer::closeFile() { file.close(); }
lgpl-2.1
moses-smt/mosesdecoder
moses/FF/Dsg-Feature/Desegmenter.cpp
5
2334
#include <fstream> #include <iostream> #include<string> #include<sstream> #include<vector> #include<map> #include "Desegmenter.h" #include <boost/algorithm/string/replace.hpp> using namespace std; namespace Moses { void Desegmenter::Load(const string filename) { std::ifstream myFile(filename.c_str() ); if (myFile.is_open()) { cerr << "Desegmentation File open successful." << endl; string line; while (getline(myFile, line)) { stringstream ss(line); string token; vector<string> myline; while (getline(ss, token, '\t')) { myline.push_back(token); } mmDesegTable.insert(pair<string, string>(myline[2], myline[1] )); } myFile.close(); } else cerr << "open() failed: check if Desegmentation file is in right folder" << endl; } vector<string> Desegmenter::Search(string myKey) { multimap<string, string>::const_iterator mmiPairFound = mmDesegTable.find(myKey); vector<string> result; if (mmiPairFound != mmDesegTable.end()) { size_t nNumPairsInMap = mmDesegTable.count(myKey); for (size_t nValuesCounter = 0; nValuesCounter < nNumPairsInMap; ++nValuesCounter) { if (mmiPairFound != mmDesegTable.end()) { result.push_back(mmiPairFound->second); } ++mmiPairFound; } return result; } else { string rule_deseg ; rule_deseg = ApplyRules(myKey); result.push_back(rule_deseg); return result; } } string Desegmenter::ApplyRules(string & segToken) { string desegToken=segToken; if (!simple) { boost::replace_all(desegToken, "l+ All", "ll"); boost::replace_all(desegToken, "l+ Al", "ll"); boost::replace_all(desegToken, "y+ y ", "y"); boost::replace_all(desegToken, "p+ ", "t"); boost::replace_all(desegToken, "' +", "}"); boost::replace_all(desegToken, "y +", "A"); boost::replace_all(desegToken, "n +n", "n"); boost::replace_all(desegToken, "mn +m", "mm"); boost::replace_all(desegToken, "En +m", "Em"); boost::replace_all(desegToken, "An +lA", "Em"); boost::replace_all(desegToken, "-LRB-", "("); boost::replace_all(desegToken, "-RRB-", ")"); } boost::replace_all(desegToken, "+ +", ""); boost::replace_all(desegToken, "+ ", ""); boost::replace_all(desegToken, " +", ""); return desegToken; } Desegmenter::~Desegmenter() {} }
lgpl-2.1
ks156/RIOT
tests/gnrc_netif2/main.c
5
66538
/* * Copyright (C) 2017 Freie Universität Berlin * * 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 tests * @{ * * @file * @brief Tests default configuration of GNRC's Network Information Base * * @author Martine Lenders <m.lenders@fu-berlin.de> * * @} */ #include <errno.h> #include <stdio.h> #include "common.h" #include "embUnit.h" #include "embUnit/embUnit.h" #include "net/ethernet.h" #include "net/ipv6.h" #include "net/gnrc.h" #include "net/gnrc/ipv6/hdr.h" #include "net/gnrc/netif/hdr.h" #include "net/gnrc/netif2.h" #include "net/gnrc/netif2/ethernet.h" #include "net/gnrc/netif2/ieee802154.h" #include "net/gnrc/netif2/internal.h" #include "net/netdev_test.h" #include "utlist.h" #include "xtimer.h" #define ETHERNET_STACKSIZE (THREAD_STACKSIZE_MAIN) #define IEEE802154_STACKSIZE (THREAD_STACKSIZE_MAIN) static gnrc_netif2_t *ethernet_netif = NULL; static gnrc_netif2_t *ieee802154_netif = NULL; static gnrc_netif2_t *netifs[DEFAULT_DEVS_NUMOF]; static char ethernet_netif_stack[ETHERNET_STACKSIZE]; static char ieee802154_netif_stack[ETHERNET_STACKSIZE]; static char netifs_stack[DEFAULT_DEVS_NUMOF][THREAD_STACKSIZE_DEFAULT]; static bool init_called = false; static inline void _test_init(gnrc_netif2_t *netif); static inline int _mock_netif_send(gnrc_netif2_t *netif, gnrc_pktsnip_t *pkt); static inline gnrc_pktsnip_t *_mock_netif_recv(gnrc_netif2_t * netif); static int _get_netdev_address(netdev_t *dev, void *value, size_t max_len); static int _set_netdev_address(netdev_t *dev, const void *value, size_t value_len); static int _get_netdev_address_long(netdev_t *dev, void *value, size_t max_len); static int _set_netdev_address_long(netdev_t *dev, const void *value, size_t value_len); static int _get_netdev_src_len(netdev_t *dev, void *value, size_t max_len); static int _set_netdev_src_len(netdev_t *dev, const void *value, size_t value_len); static const gnrc_netif2_ops_t default_ops = { .init = _test_init, .send = _mock_netif_send, .recv = _mock_netif_recv, .get = gnrc_netif2_get_from_netdev, .set = gnrc_netif2_set_from_netdev, .msg_handler = NULL, }; static void _set_up(void) { msg_t msg; if (ethernet_netif != NULL) { memset(ethernet_netif->ipv6.addrs_flags, 0, sizeof(ethernet_netif->ipv6.addrs_flags)); memset(ethernet_netif->ipv6.addrs, 0, sizeof(ethernet_netif->ipv6.addrs)); memset(ethernet_netif->ipv6.groups, 0, sizeof(ethernet_netif->ipv6.groups)); } if (ieee802154_netif != NULL) { memset(ieee802154_netif->ipv6.addrs_flags, 0, sizeof(ieee802154_netif->ipv6.addrs_flags)); memset(ieee802154_netif->ipv6.addrs, 0, sizeof(ieee802154_netif->ipv6.addrs)); memset(ieee802154_netif->ipv6.groups, 0, sizeof(ieee802154_netif->ipv6.groups)); } for (unsigned i = 0; i < DEFAULT_DEVS_NUMOF; i++) { if (netifs[i] != NULL) { memset(netifs[i]->ipv6.addrs_flags, 0, sizeof(netifs[i]->ipv6.addrs_flags)); memset(netifs[i]->ipv6.addrs, 0, sizeof(netifs[i]->ipv6.addrs)); memset(netifs[i]->ipv6.groups, 0, sizeof(netifs[i]->ipv6.groups)); } } /* empty message queue */ while (msg_try_receive(&msg) > 0) {} } static inline void _test_init(gnrc_netif2_t *netif) { (void)netif; init_called = true; } static void test_creation(void) { gnrc_netif2_t *ptr = NULL; TEST_ASSERT_EQUAL_INT(0, gnrc_netif2_numof()); TEST_ASSERT_NULL(gnrc_netif2_iter(ptr)); TEST_ASSERT_NOT_NULL((ethernet_netif = gnrc_netif2_ethernet_create( ethernet_netif_stack, ETHERNET_STACKSIZE, GNRC_NETIF2_PRIO, "eth", ethernet_dev ))); TEST_ASSERT_EQUAL_INT(1, gnrc_netif2_numof()); TEST_ASSERT_NOT_NULL((ptr = gnrc_netif2_iter(ptr))); TEST_ASSERT_NULL((ptr = gnrc_netif2_iter(ptr))); TEST_ASSERT_NOT_NULL(ethernet_netif->ops); TEST_ASSERT_NOT_NULL(ethernet_netif->dev); TEST_ASSERT_EQUAL_INT(ETHERNET_DATA_LEN, ethernet_netif->ipv6.mtu); TEST_ASSERT_EQUAL_INT(GNRC_NETIF2_DEFAULT_HL, ethernet_netif->cur_hl); TEST_ASSERT_EQUAL_INT(NETDEV_TYPE_ETHERNET, ethernet_netif->device_type); TEST_ASSERT(ethernet_netif->pid > KERNEL_PID_UNDEF); #ifdef DEVELHELP TEST_ASSERT_EQUAL_STRING("eth", sched_threads[ethernet_netif->pid]->name); #endif TEST_ASSERT_NOT_NULL(sched_threads[ethernet_netif->pid]->msg_array); TEST_ASSERT_NOT_NULL((ieee802154_netif = gnrc_netif2_ieee802154_create( ieee802154_netif_stack, IEEE802154_STACKSIZE, GNRC_NETIF2_PRIO, "wpan", ieee802154_dev ))); TEST_ASSERT_EQUAL_INT(2, gnrc_netif2_numof()); TEST_ASSERT_NOT_NULL((ptr = gnrc_netif2_iter(ptr))); TEST_ASSERT_NOT_NULL((ptr = gnrc_netif2_iter(ptr))); TEST_ASSERT_NULL((ptr = gnrc_netif2_iter(ptr))); TEST_ASSERT_NOT_NULL(ieee802154_netif->ops); TEST_ASSERT_NOT_NULL(ieee802154_netif->dev); TEST_ASSERT_EQUAL_INT(IPV6_MIN_MTU, ieee802154_netif->ipv6.mtu); TEST_ASSERT_EQUAL_INT(TEST_IEEE802154_MAX_FRAG_SIZE, ieee802154_netif->sixlo.max_frag_size); TEST_ASSERT_EQUAL_INT(GNRC_NETIF2_DEFAULT_HL, ieee802154_netif->cur_hl); TEST_ASSERT_EQUAL_INT(NETDEV_TYPE_IEEE802154, ieee802154_netif->device_type); TEST_ASSERT(ieee802154_netif->pid > KERNEL_PID_UNDEF); #ifdef DEVELHELP TEST_ASSERT_EQUAL_STRING("wpan", sched_threads[ieee802154_netif->pid]->name); #endif TEST_ASSERT_NOT_NULL(sched_threads[ieee802154_netif->pid]->msg_array); for (unsigned i = 0; i < DEFAULT_DEVS_NUMOF; i++) { TEST_ASSERT_NOT_NULL((netifs[i] = gnrc_netif2_create( netifs_stack[i], THREAD_STACKSIZE_DEFAULT, GNRC_NETIF2_PRIO, "netif", devs[i], &default_ops ))); TEST_ASSERT_NOT_NULL(netifs[i]->ops); TEST_ASSERT_NOT_NULL(netifs[i]->dev); TEST_ASSERT_EQUAL_INT(GNRC_NETIF2_DEFAULT_HL, netifs[i]->cur_hl); TEST_ASSERT_EQUAL_INT(NETDEV_TYPE_UNKNOWN, netifs[i]->device_type); TEST_ASSERT(netifs[i]->pid > KERNEL_PID_UNDEF); TEST_ASSERT_NOT_NULL(sched_threads[netifs[i]->pid]->msg_array); TEST_ASSERT_EQUAL_INT(i + SPECIAL_DEVS + 1, gnrc_netif2_numof()); for (unsigned j = 0; j < (i + SPECIAL_DEVS + 1); j++) { TEST_ASSERT_NOT_NULL((ptr = gnrc_netif2_iter(ptr))); } TEST_ASSERT_NULL((ptr = gnrc_netif2_iter(ptr))); } TEST_ASSERT(init_called); } static void test_get_by_pid(void) { TEST_ASSERT(ethernet_netif == gnrc_netif2_get_by_pid(ethernet_netif->pid)); TEST_ASSERT(ieee802154_netif == gnrc_netif2_get_by_pid(ieee802154_netif->pid)); for (kernel_pid_t i = 0; i < DEFAULT_DEVS_NUMOF; i++) { TEST_ASSERT(netifs[i] == gnrc_netif2_get_by_pid(netifs[i]->pid)); } } static void test_addr_to_str(void) { static const uint8_t ethernet_l2addr[] = ETHERNET_SRC; static const uint8_t ieee802154_l2addr_long[] = IEEE802154_LONG_SRC; static const uint8_t ieee802154_l2addr_short[] = IEEE802154_SHORT_SRC; static const uint8_t netif0_l2addr[] = NETIF0_SRC; char out[sizeof(netif0_l2addr) * 3]; TEST_ASSERT(out == gnrc_netif2_addr_to_str(NULL, 0, out)); TEST_ASSERT_EQUAL_STRING("", &out[0]); TEST_ASSERT(out == gnrc_netif2_addr_to_str(ethernet_l2addr, sizeof(ethernet_l2addr), out)); TEST_ASSERT_EQUAL_STRING("3e:e6:b5:22:fd:0a", &out[0]); TEST_ASSERT(out == gnrc_netif2_addr_to_str(ieee802154_l2addr_long, sizeof(ieee802154_l2addr_long), out)); TEST_ASSERT_EQUAL_STRING("3e:e6:b5:0f:19:22:fd:0a", &out[0]); TEST_ASSERT(out == gnrc_netif2_addr_to_str(ieee802154_l2addr_short, sizeof(ieee802154_l2addr_short), out)); TEST_ASSERT_EQUAL_STRING("fd:0a", &out[0]); TEST_ASSERT(out == gnrc_netif2_addr_to_str(netif0_l2addr, sizeof(netif0_l2addr), out)); TEST_ASSERT_EQUAL_STRING("3e:e7:b5:0f:19:22:fd:0a", &out[0]); } static void test_addr_from_str(void) { static const uint8_t ethernet_l2addr[] = ETHERNET_SRC; static const uint8_t ieee802154_l2addr_long[] = IEEE802154_LONG_SRC; static const uint8_t ieee802154_l2addr_short[] = IEEE802154_SHORT_SRC; uint8_t out[GNRC_NETIF2_L2ADDR_MAXLEN]; TEST_ASSERT_EQUAL_INT(0, gnrc_netif2_addr_from_str("", out)); TEST_ASSERT_EQUAL_INT(sizeof(ethernet_l2addr), gnrc_netif2_addr_from_str("3e:e6:b5:22:fd:0a", out)); TEST_ASSERT_EQUAL_INT(0, memcmp(ethernet_l2addr, out, sizeof(ethernet_l2addr))); TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_long), gnrc_netif2_addr_from_str("3e:e6:b5:0f:19:22:fd:0a", out)); TEST_ASSERT_EQUAL_INT(0, memcmp(ieee802154_l2addr_long, out, sizeof(ieee802154_l2addr_long))); TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_short), gnrc_netif2_addr_from_str("fd:0a", out)); TEST_ASSERT_EQUAL_INT(0, memcmp(ieee802154_l2addr_short, out, sizeof(ieee802154_l2addr_short))); } static void test_ipv6_addr_add__ENOMEM(void) { ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; for (unsigned i = 0; i < GNRC_NETIF2_IPV6_ADDRS_NUMOF; i++, addr.u16[3].u16++) { TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); } TEST_ASSERT_EQUAL_INT(-ENOMEM, gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); } static void test_ipv6_addr_add__success(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; int idx; TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID))); /* check duplicate addition */ TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT_EQUAL_INT(GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID, netifs[0]->ipv6.addrs_flags[idx]); TEST_ASSERT(ipv6_addr_equal(&addr, &netifs[0]->ipv6.addrs[idx])); } static void test_ipv6_addr_add__readd_with_free_entry(void) { /* Tests for possible duplicates (see #2965) */ static const ipv6_addr_t addr1 = { .u8 = NETIF0_IPV6_LL }; static const ipv6_addr_t addr2 = { .u8 = NETIF0_IPV6_G }; int idx; TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr1, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_addr_add(netifs[0], &addr2, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID))); gnrc_netif2_ipv6_addr_remove(netifs[0], &addr1); TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_addr_add(netifs[0], &addr2, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); } static void test_ipv6_addr_remove__not_allocated(void) { static const ipv6_addr_t addr1 = { .u8 = NETIF0_IPV6_LL }; static const ipv6_addr_t addr2 = { .u8 = NETIF0_IPV6_G }; test_ipv6_addr_add__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_idx(netifs[0], &addr1)); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr2, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); gnrc_netif2_ipv6_addr_remove(netifs[0], &addr2); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_idx(netifs[0], &addr1)); } static void test_ipv6_addr_remove__success(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; test_ipv6_addr_add__success(); gnrc_netif2_ipv6_addr_remove(netifs[0], &addr); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_idx(netifs[0], &addr)); } static void test_ipv6_addr_idx__empty(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_idx(netifs[0], &addr)); } static void test_ipv6_addr_idx__wrong_netif(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_idx(netifs[1], &addr)); } static void test_ipv6_addr_idx__wrong_addr(void) { static const ipv6_addr_t addr2 = { .u8 = NETIF0_IPV6_G }; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_idx(netifs[0], &addr2)); } static void test_ipv6_addr_idx__success(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; test_ipv6_addr_add__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_idx(netifs[0], &addr)); } static void test_ipv6_addr_match__empty(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_match(netifs[0], &addr)); } static void test_ipv6_addr_match__wrong_netif(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_match(netifs[1], &addr)); } static void test_ipv6_addr_match__wrong_addr(void) { static const ipv6_addr_t addr2 = { .u8 = NETIF0_IPV6_G }; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_addr_match(netifs[0], &addr2)); } static void test_ipv6_addr_match__success18(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX18 }; int idx; TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID))); TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_addr_match(netifs[0], &pfx)); TEST_ASSERT_EQUAL_INT(18, ipv6_addr_match_prefix(&netifs[0]->ipv6.addrs[idx], &pfx)); } static void test_ipv6_addr_match__success23(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX23 }; int idx; TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID))); TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_addr_match(netifs[0], &pfx)); TEST_ASSERT_EQUAL_INT(23, ipv6_addr_match_prefix(&netifs[0]->ipv6.addrs[idx], &pfx)); } static void test_ipv6_addr_match__success64(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX64 }; int idx; TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID))); TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_addr_match(netifs[0], &pfx)); TEST_ASSERT_EQUAL_INT(64, ipv6_addr_match_prefix(&netifs[0]->ipv6.addrs[idx], &pfx)); } static void test_ipv6_addr_best_src__multicast_input(void) { static const ipv6_addr_t addr1 = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t addr2 = { .u8 = GLOBAL_PFX18 }; ipv6_addr_t *out; /* adds a link-local address */ test_ipv6_addr_add__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr1, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT_NOT_NULL((out = gnrc_netif2_ipv6_addr_best_src(netifs[0], &addr2, false))); TEST_ASSERT(!ipv6_addr_equal(&addr2, out)); TEST_ASSERT(ipv6_addr_equal(&addr1, out)); } static void test_ipv6_addr_best_src__other_subnet(void) { static const ipv6_addr_t mc_addr = IPV6_ADDR_ALL_ROUTERS_SITE_LOCAL; ipv6_addr_t *out = NULL; test_ipv6_addr_add__success(); TEST_ASSERT_NOT_NULL((out = gnrc_netif2_ipv6_addr_best_src(netifs[0], &mc_addr, false))); TEST_ASSERT(!ipv6_addr_equal(&mc_addr, out)); TEST_ASSERT(!ipv6_addr_is_multicast(out)); TEST_ASSERT(!ipv6_addr_is_unspecified(out)); } static void test_get_by_ipv6_addr__empty(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; TEST_ASSERT_NULL(gnrc_netif2_get_by_ipv6_addr(&addr)); } static void test_get_by_ipv6_addr__success(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_LL }; test_ipv6_addr_add__success(); TEST_ASSERT_NOT_NULL(netifs[0]); TEST_ASSERT(netifs[0] == gnrc_netif2_get_by_ipv6_addr(&addr)); } static void test_get_by_prefix__empty(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; TEST_ASSERT_NULL(gnrc_netif2_get_by_prefix(&addr)); } static void test_get_by_prefix__success18(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX18 }; TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT_NOT_NULL(netifs[0]); TEST_ASSERT(netifs[0] == gnrc_netif2_get_by_prefix(&pfx)); test_ipv6_addr_match__success18(); } static void test_get_by_prefix__success23(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX23 }; TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT_NOT_NULL(netifs[0]); TEST_ASSERT(netifs[0] == gnrc_netif2_get_by_prefix(&pfx)); test_ipv6_addr_match__success23(); } static void test_get_by_prefix__success64(void) { static const ipv6_addr_t addr = { .u8 = NETIF0_IPV6_G }; static const ipv6_addr_t pfx = { .u8 = GLOBAL_PFX64 }; TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_add(netifs[0], &addr, 64U, GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID)); TEST_ASSERT_NOT_NULL(netifs[0]); TEST_ASSERT(netifs[0] == gnrc_netif2_get_by_prefix(&pfx)); test_ipv6_addr_match__success64(); } static void test_ipv6_group_join__ENOMEM(void) { ipv6_addr_t addr = IPV6_ADDR_ALL_NODES_LINK_LOCAL; for (unsigned i = 0; i < GNRC_NETIF2_IPV6_ADDRS_NUMOF; i++, addr.u16[7].u16++) { TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_join(netifs[0], &addr)); } TEST_ASSERT_EQUAL_INT(-ENOMEM, gnrc_netif2_ipv6_group_join(netifs[0], &addr)); } static void test_ipv6_group_join__success(void) { int idx; TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_nodes_link_local))); /* check duplicate addition */ TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_nodes_link_local)); TEST_ASSERT(ipv6_addr_equal(&ipv6_addr_all_nodes_link_local, &netifs[0]->ipv6.groups[idx])); } static void test_ipv6_group_join__readd_with_free_entry(void) { /* Tests for possible duplicates (see #2965) */ int idx; TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_nodes_link_local)); TEST_ASSERT(0 <= (idx = gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_routers_link_local))); gnrc_netif2_ipv6_group_leave(netifs[0], &ipv6_addr_all_nodes_link_local); TEST_ASSERT_EQUAL_INT(idx, gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_routers_link_local)); } static void test_ipv6_group_leave__not_allocated(void) { test_ipv6_group_join__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_nodes_link_local)); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_join(netifs[0], &ipv6_addr_all_routers_link_local)); gnrc_netif2_ipv6_group_leave(netifs[0], &ipv6_addr_all_routers_link_local); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_nodes_link_local)); } static void test_ipv6_group_leave__success(void) { test_ipv6_group_join__success(); gnrc_netif2_ipv6_group_leave(netifs[0], &ipv6_addr_all_nodes_link_local); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_nodes_link_local)); } static void test_ipv6_group_idx__empty(void) { TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_nodes_link_local)); } static void test_ipv6_group_idx__wrong_netif(void) { test_ipv6_group_join__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_group_idx(netifs[1], &ipv6_addr_all_nodes_link_local)); } static void test_ipv6_group_idx__wrong_addr(void) { test_ipv6_group_join__success(); TEST_ASSERT_EQUAL_INT(-1, gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_routers_link_local)); } static void test_ipv6_group_idx__success(void) { test_ipv6_group_join__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_idx(netifs[0], &ipv6_addr_all_nodes_link_local)); } static void test_ipv6_get_iid(void) { static const ipv6_addr_t ethernet_ipv6_ll = { .u8 = ETHERNET_IPV6_LL }; static const ipv6_addr_t ieee802154_ipv6_ll_long = { .u8 = IEEE802154_IPV6_LL }; static const uint8_t ieee802154_eui64_short[] = { 0, 0, 0, 0xff, 0xfe, 0, LA7, LA8 }; eui64_t res; uint16_t ieee802154_l2addr_len = 2U; TEST_ASSERT_EQUAL_INT(0, gnrc_netif2_ipv6_get_iid(ethernet_netif, &res)); TEST_ASSERT_EQUAL_INT(0, memcmp(&res, &ethernet_ipv6_ll.u64[1], sizeof(res))); TEST_ASSERT_EQUAL_INT(0, gnrc_netif2_ipv6_get_iid(ieee802154_netif, &res)); TEST_ASSERT_EQUAL_INT(0, memcmp(&res, &ieee802154_ipv6_ll_long.u64[1], sizeof(res))); TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &ieee802154_l2addr_len, sizeof(ieee802154_l2addr_len))); TEST_ASSERT_EQUAL_INT(0, gnrc_netif2_ipv6_get_iid(ieee802154_netif, &res)); TEST_ASSERT_EQUAL_INT(0, memcmp(&res, &ieee802154_eui64_short, sizeof(res))); /* reset to source length 8 */ ieee802154_l2addr_len = 8U; TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &ieee802154_l2addr_len, sizeof(ieee802154_l2addr_len))); for (unsigned i = 0; i < DEFAULT_DEVS_NUMOF; i++) { TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netif2_ipv6_get_iid(netifs[i], &res)); } } static void test_netapi_get__HOP_LIMIT(void) { uint8_t value; TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_get(netifs[0]->pid, NETOPT_HOP_LIMIT, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(netifs[0]->cur_hl, value); } static void test_netapi_get__IPV6_ADDR(void) { static const ipv6_addr_t exp = { NETIF0_IPV6_LL }; ipv6_addr_t value[GNRC_NETIF2_IPV6_ADDRS_NUMOF]; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(sizeof(ipv6_addr_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_IPV6_ADDR, 0, &value, sizeof(value))); TEST_ASSERT(ipv6_addr_equal(&exp, &value[0])); } static void test_netapi_get__IPV6_ADDR_FLAGS(void) { uint8_t value[GNRC_NETIF2_IPV6_ADDRS_NUMOF]; test_ipv6_addr_add__success(); TEST_ASSERT_EQUAL_INT(sizeof(uint8_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_IPV6_ADDR_FLAGS, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID, value[0]); } static void test_netapi_get__IPV6_GROUP(void) { ipv6_addr_t value[GNRC_NETIF2_IPV6_GROUPS_NUMOF]; test_ipv6_group_join__success(); TEST_ASSERT_EQUAL_INT(sizeof(ipv6_addr_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_IPV6_GROUP, 0, &value, sizeof(value))); TEST_ASSERT(ipv6_addr_equal(&ipv6_addr_all_nodes_link_local, &value[0])); } static void test_netapi_get__IPV6_IID(void) { static const ipv6_addr_t ethernet_ipv6_ll = { .u8 = ETHERNET_IPV6_LL }; static const ipv6_addr_t ieee802154_ipv6_ll_long = { .u8 = IEEE802154_IPV6_LL }; static const uint8_t ieee802154_eui64_short[] = { 0, 0, 0, 0xff, 0xfe, 0, LA7, LA8 }; eui64_t value; uint16_t ieee802154_l2addr_len = 2U; TEST_ASSERT_EQUAL_INT(sizeof(eui64_t), gnrc_netapi_get(ethernet_netif->pid, NETOPT_IPV6_IID, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(&value, &ethernet_ipv6_ll.u64[1], sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(eui64_t), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_IPV6_IID, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(&value, &ieee802154_ipv6_ll_long.u64[1], sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &ieee802154_l2addr_len, sizeof(ieee802154_l2addr_len))); TEST_ASSERT_EQUAL_INT(sizeof(eui64_t), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_IPV6_IID, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(&value, &ieee802154_eui64_short, sizeof(value))); /* reset to source length 8 */ ieee802154_l2addr_len = 8U; TEST_ASSERT_EQUAL_INT(sizeof(ieee802154_l2addr_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &ieee802154_l2addr_len, sizeof(ieee802154_l2addr_len))); TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_get(netifs[0]->pid, NETOPT_IPV6_IID, 0, &value, sizeof(value))); } static void test_netapi_get__MAX_PACKET_SIZE(void) { uint16_t value; TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(ethernet_netif->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_IPV6, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(ETHERNET_DATA_LEN, value); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(ethernet_netif->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_NETIF, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(ETHERNET_DATA_LEN, value); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_IPV6, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(IPV6_MIN_MTU, value); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_NETIF, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(TEST_IEEE802154_MAX_FRAG_SIZE, value); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_IPV6, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(IPV6_MIN_MTU, value); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_NETIF, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(IPV6_MIN_MTU, value); } static void test_netapi_get__6LO_IPHC(void) { netopt_enable_t value; TEST_ASSERT_EQUAL_INT(sizeof(netopt_enable_t), gnrc_netapi_get(ethernet_netif->pid, NETOPT_6LO_IPHC, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(NETOPT_DISABLE, value); TEST_ASSERT_EQUAL_INT(sizeof(netopt_enable_t), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_6LO_IPHC, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(NETOPT_ENABLE, value); TEST_ASSERT_EQUAL_INT(sizeof(netopt_enable_t), gnrc_netapi_get(netifs[0]->pid, NETOPT_6LO_IPHC, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(NETOPT_DISABLE, value); } static void test_netapi_get__ADDRESS(void) { static const uint8_t exp_ethernet[] = ETHERNET_SRC; static const uint8_t exp_ieee802154[] = IEEE802154_SHORT_SRC; uint8_t value[GNRC_NETIF2_L2ADDR_MAXLEN]; TEST_ASSERT_EQUAL_INT(sizeof(exp_ethernet), gnrc_netapi_get(ethernet_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(exp_ethernet, value, sizeof(exp_ethernet))); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(exp_ieee802154, value, sizeof(exp_ieee802154))); } static void test_netapi_get__ADDRESS_LONG(void) { static const uint8_t exp_ieee802154[] = IEEE802154_LONG_SRC; uint8_t value[GNRC_NETIF2_L2ADDR_MAXLEN]; TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_get(ethernet_netif->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_get(ieee802154_netif->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(0, memcmp(exp_ieee802154, value, sizeof(exp_ieee802154))); TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_get(netifs[0]->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); } static void test_netapi_set__HOP_LIMIT(void) { uint8_t value = 89; TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_HOP_LIMIT, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(value, netifs[0]->cur_hl); } static void test_netapi_set__IPV6_ADDR(void) { ipv6_addr_t value = { .u8 = NETIF0_IPV6_LL }; static const uint16_t context = (64U << 8) | (GNRC_NETIF2_IPV6_ADDRS_FLAGS_STATE_VALID); TEST_ASSERT(0 > gnrc_netif2_ipv6_addr_idx(netifs[0], &value)); TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_IPV6_ADDR, context, &value, sizeof(value))); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_idx(netifs[0], &value)); } static void test_netapi_set__IPV6_ADDR_REMOVE(void) { ipv6_addr_t value = { .u8 = NETIF0_IPV6_LL }; test_ipv6_addr_add__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_addr_idx(netifs[0], &value)); TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_IPV6_ADDR_REMOVE, 0, &value, sizeof(value))); TEST_ASSERT(0 > gnrc_netif2_ipv6_addr_idx(netifs[0], &value)); } static void test_netapi_set__IPV6_GROUP(void) { ipv6_addr_t value = IPV6_ADDR_ALL_NODES_LINK_LOCAL; TEST_ASSERT(0 > gnrc_netif2_ipv6_group_idx(netifs[0], &value)); TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_IPV6_GROUP, 0, &value, sizeof(value))); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_idx(netifs[0], &value)); } static void test_netapi_set__IPV6_GROUP_LEAVE(void) { ipv6_addr_t value = IPV6_ADDR_ALL_NODES_LINK_LOCAL; test_ipv6_group_join__success(); TEST_ASSERT(0 <= gnrc_netif2_ipv6_group_idx(netifs[0], &value)); TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_IPV6_GROUP_LEAVE, 0, &value, sizeof(value))); TEST_ASSERT(0 > gnrc_netif2_ipv6_group_idx(netifs[0], &value)); } static void test_netapi_set__MAX_PACKET_SIZE(void) { uint16_t value = 57194; TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_MAX_PACKET_SIZE, GNRC_NETTYPE_IPV6, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(value, netifs[0]->ipv6.mtu); TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_set(netifs[0]->pid, NETOPT_MAX_PACKET_SIZE, 0, &value, sizeof(value))); } static void test_netapi_set__6LO_IPHC(void) { netopt_enable_t value = NETOPT_ENABLE; TEST_ASSERT_EQUAL_INT(sizeof(value), gnrc_netapi_set(netifs[0]->pid, NETOPT_6LO_IPHC, 0, &value, sizeof(value))); TEST_ASSERT(netifs[0]->flags & GNRC_NETIF2_FLAGS_6LO_HC); } static void test_netapi_set__ADDRESS(void) { static const uint8_t exp_ethernet[] = ETHERNET_SRC; static const uint8_t exp_ieee802154[] = IEEE802154_SHORT_SRC; static const uint8_t exp_ieee802154_long[] = IEEE802154_LONG_SRC; uint8_t value[] = { LA1 + 1, LA2 + 2, LA3 + 3, LA4 + 4, LA5 + 5, LA6 + 6 }; TEST_ASSERT_EQUAL_INT(sizeof(exp_ethernet), gnrc_netapi_set(ethernet_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(value), ethernet_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(value, ethernet_netif->l2addr, ETHERNET_ADDR_LEN)); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(uint16_t))); /* we did not change NETOPT_SRC_LEN, so this field shouldn't change */ TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154_long), ieee802154_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(exp_ieee802154_long, ieee802154_netif->l2addr, sizeof(exp_ieee802154_long))); /* return addresses to previous state for further testing */ memcpy(value, exp_ethernet, sizeof(exp_ethernet)); TEST_ASSERT_EQUAL_INT(sizeof(exp_ethernet), gnrc_netapi_set(ethernet_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(value), ethernet_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(value, ethernet_netif->l2addr, sizeof(value))); memcpy(value, exp_ieee802154, sizeof(exp_ieee802154)); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_ADDRESS, 0, &value, sizeof(uint16_t))); } static void test_netapi_set__ADDRESS_LONG(void) { static const uint8_t exp_ieee802154[] = IEEE802154_LONG_SRC; uint8_t value[] = { LA1 + 1, LA2 + 2, LA3 + 3, LA4 + 4, LA5 + 5, LA6 + 6, LA7 + 1, LA8 + 2 }; TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_set(ethernet_netif->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(value), ieee802154_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(value, ieee802154_netif->l2addr, sizeof(value))); TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_set(netifs[0]->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); /* return addresses to previous state for further testing */ memcpy(value, exp_ieee802154, sizeof(exp_ieee802154)); TEST_ASSERT_EQUAL_INT(sizeof(exp_ieee802154), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_ADDRESS_LONG, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(value), ieee802154_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(value, ieee802154_netif->l2addr, sizeof(value))); } static void test_netapi_set__SRC_LEN(void) { static const uint8_t exp_l2addr[] = { LA7, LA8 }; static const uint8_t orig_ieee802154[] = IEEE802154_LONG_SRC; uint16_t value = 2U; TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_set(ethernet_netif->pid, NETOPT_SRC_LEN, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(value, ieee802154_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(exp_l2addr, ieee802154_netif->l2addr, sizeof(exp_l2addr))); TEST_ASSERT_EQUAL_INT(-ENOTSUP, gnrc_netapi_set(netifs[0]->pid, NETOPT_SRC_LEN, 0, &value, sizeof(value))); /* return addresses to previous state for further testing */ value = 8U; TEST_ASSERT_EQUAL_INT(sizeof(uint16_t), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &value, sizeof(value))); TEST_ASSERT_EQUAL_INT(value, ieee802154_netif->l2addr_len); TEST_ASSERT_EQUAL_INT(0, memcmp(orig_ieee802154, ieee802154_netif->l2addr, sizeof(orig_ieee802154))); } static void test_netapi_send__raw_unicast_ethernet_packet(void) { uint8_t dst[] = { LA1, LA2, LA3, LA4, LA5, LA6 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ethernet_netif->pid, pkt); } static void test_netapi_send__raw_broadcast_ethernet_packet(void) { gnrc_netif_hdr_t *hdr; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); TEST_ASSERT_NOT_NULL(netif); hdr = netif->data; hdr->flags |= GNRC_NETIF_HDR_FLAGS_BROADCAST; LL_PREPEND(pkt, netif); gnrc_netapi_send(ethernet_netif->pid, pkt); } static void test_netapi_send__raw_unicast_ieee802154_long_long_packet(void) { uint8_t dst[] = { LA1, LA2, LA3, LA4, LA5, LA6, LA7, LA8 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_send__raw_unicast_ieee802154_long_short_packet(void) { uint8_t dst[] = { LA7, LA8 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_send__raw_unicast_ieee802154_short_long_packet1(void) { uint8_t dst[] = { LA1, LA2, LA3, LA4, LA5, LA6, LA7, LA8 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); uint16_t src_len = 2U; TEST_ASSERT_NOT_NULL(pkt); TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); /* reset src_len */ src_len = 8U; TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); } static void test_netapi_send__raw_unicast_ieee802154_short_long_packet2(void) { uint8_t src[] = { LA7, LA8 }; uint8_t dst[] = { LA1, LA2, LA3, LA4, LA5, LA6, LA7, LA8 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(src, sizeof(src), dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_send__raw_unicast_ieee802154_short_short_packet(void) { uint8_t dst[] = { LA7, LA8 + 1 }; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); uint16_t src_len = 2U; TEST_ASSERT_NOT_NULL(pkt); TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst, sizeof(dst)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); /* reset src_len */ src_len = 8U; TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); } static void test_netapi_send__raw_broadcast_ieee802154_long_packet(void) { gnrc_netif_hdr_t *hdr; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(pkt); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); TEST_ASSERT_NOT_NULL(netif); hdr = netif->data; hdr->flags |= GNRC_NETIF_HDR_FLAGS_BROADCAST; LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_send__raw_broadcast_ieee802154_short_packet(void) { gnrc_netif_hdr_t *hdr; gnrc_pktsnip_t *pkt = gnrc_pktbuf_add(NULL, "123ABCDEFG", sizeof("123ABCDEFG"), GNRC_NETTYPE_UNDEF); uint16_t src_len = 2U; TEST_ASSERT_NOT_NULL(pkt); TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); TEST_ASSERT_NOT_NULL(netif); hdr = netif->data; hdr->flags |= GNRC_NETIF_HDR_FLAGS_BROADCAST; LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); /* reset src_len */ src_len = 8U; TEST_ASSERT_EQUAL_INT(sizeof(src_len), gnrc_netapi_set(ieee802154_netif->pid, NETOPT_SRC_LEN, 0, &src_len, sizeof(src_len))); } static void test_netapi_send__ipv6_unicast_ethernet_packet(void) { ipv6_hdr_t *ipv6_hdr; uint8_t dst_netif[] = { LA1, LA2, LA3, LA4, LA5, LA6 + 1 }; static const ipv6_addr_t dst_ipv6 = { .u8 = { LP1, LP2, LP3, LP4, LP5, LP6, LP7, LP8, LA1 ^ 0x2, LA2, LA3, 0xff, 0xfe, LA4, LA5, LA6 + 1} }; static const ipv6_addr_t src_ipv6 = { .u8 = ETHERNET_IPV6_LL }; gnrc_pktsnip_t *payload = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(payload); /* we don't send through gnrc_ipv6 (because we are lazy and don't want * to update the neighbor cache ;-)) so we need to set the IPv6 source * address */ gnrc_pktsnip_t *pkt = gnrc_ipv6_hdr_build(payload, &src_ipv6, &dst_ipv6); TEST_ASSERT_NOT_NULL(pkt); ipv6_hdr = pkt->data; ipv6_hdr->len = byteorder_htons(sizeof("ABCDEFG")); ipv6_hdr->nh = PROTNUM_IPV6_NONXT; ipv6_hdr->hl = ethernet_netif->cur_hl; gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst_netif, sizeof(dst_netif)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ethernet_netif->pid, pkt); } static void test_netapi_send__ipv6_multicast_ethernet_packet(void) { ipv6_hdr_t *ipv6_hdr; gnrc_netif_hdr_t *netif_hdr; static const ipv6_addr_t src_ipv6 = { .u8 = ETHERNET_IPV6_LL }; gnrc_pktsnip_t *payload = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(payload); /* we don't send through gnrc_ipv6 (because we are lazy and don't want * to update the neighbor cache ;-)) so we need to set the IPv6 source * address */ gnrc_pktsnip_t *pkt = gnrc_ipv6_hdr_build(payload, &src_ipv6, &ipv6_addr_all_nodes_link_local); TEST_ASSERT_NOT_NULL(pkt); ipv6_hdr = pkt->data; ipv6_hdr->len = byteorder_htons(sizeof("ABCDEFG")); ipv6_hdr->nh = PROTNUM_IPV6_NONXT; ipv6_hdr->hl = ethernet_netif->cur_hl; gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); TEST_ASSERT_NOT_NULL(netif); netif_hdr = netif->data; netif_hdr->flags |= GNRC_NETIF_HDR_FLAGS_MULTICAST; LL_PREPEND(pkt, netif); gnrc_netapi_send(ethernet_netif->pid, pkt); } static void test_netapi_send__ipv6_unicast_ieee802154_packet(void) { ipv6_hdr_t *ipv6_hdr; uint8_t dst_netif[] = { LA1, LA2, LA3, LA4, LA5, LA6, LA7, LA8 + 1 }; static const ipv6_addr_t dst_ipv6 = { .u8 = { LP1, LP2, LP3, LP4, LP5, LP6, LP7, LP8, LA1 ^ 0x2, LA2, LA3, 0xff, 0xfe, LA4, LA5, LA6 + 1} }; static const ipv6_addr_t src_ipv6 = { .u8 = IEEE802154_IPV6_LL }; gnrc_pktsnip_t *payload = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(payload); /* we don't send through gnrc_ipv6 (because we are lazy and don't want * to update the neighbor cache ;-)) so we need to set the IPv6 source * address */ gnrc_pktsnip_t *pkt = gnrc_ipv6_hdr_build(payload, &src_ipv6, &dst_ipv6); TEST_ASSERT_NOT_NULL(pkt); ipv6_hdr = pkt->data; ipv6_hdr->len = byteorder_htons(sizeof("ABCDEFG")); ipv6_hdr->nh = PROTNUM_IPV6_NONXT; ipv6_hdr->hl = ieee802154_netif->cur_hl; gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, dst_netif, sizeof(dst_netif)); TEST_ASSERT_NOT_NULL(netif); LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_send__ipv6_multicast_ieee802154_packet(void) { ipv6_hdr_t *ipv6_hdr; gnrc_netif_hdr_t *netif_hdr; static const ipv6_addr_t src_ipv6 = { .u8 = IEEE802154_IPV6_LL }; gnrc_pktsnip_t *payload = gnrc_pktbuf_add(NULL, "ABCDEFG", sizeof("ABCDEFG"), GNRC_NETTYPE_UNDEF); TEST_ASSERT_NOT_NULL(payload); /* we don't send through gnrc_ipv6 (because we are lazy and don't want * to update the neighbor cache ;-)) so we need to set the IPv6 source * address */ gnrc_pktsnip_t *pkt = gnrc_ipv6_hdr_build(payload, &src_ipv6, &ipv6_addr_all_nodes_link_local); TEST_ASSERT_NOT_NULL(pkt); ipv6_hdr = pkt->data; ipv6_hdr->len = byteorder_htons(sizeof("ABCDEFG")); ipv6_hdr->nh = PROTNUM_IPV6_NONXT; ipv6_hdr->hl = ieee802154_netif->cur_hl; gnrc_pktsnip_t *netif = gnrc_netif_hdr_build(NULL, 0, NULL, 0); TEST_ASSERT_NOT_NULL(netif); netif_hdr = netif->data; netif_hdr->flags |= GNRC_NETIF_HDR_FLAGS_MULTICAST; LL_PREPEND(pkt, netif); gnrc_netapi_send(ieee802154_netif->pid, pkt); } static void test_netapi_recv__empty_ethernet_payload(void) { static const uint8_t data[] = { LA1, LA2, LA3, LA6, LA7, LA8, LA1, LA2, LA3, LA6, LA7, LA8 + 1, 0xff, 0xff }; puts("pktdump dumping Ethernet packet with empty payload"); _test_trigger_recv(ethernet_netif, data, sizeof(data)); } static void test_netapi_recv__empty_ieee802154_payload(void) { static const uint8_t data[] = { 0x41, 0xdc, /* FCF */ 0x03, /* Sequence number */ 0x00, 0x00, /* Destination PAN */ LA8, LA7, LA6, LA5, LA4, LA3, LA2, LA1, LA8 + 1, LA7, LA6, LA5, LA4, LA3, LA2, LA1 }; puts("pktdump dumping IEEE 802.15.4 packet with empty payload"); _test_trigger_recv(ieee802154_netif, data, sizeof(data)); } static void test_netapi_recv__raw_ethernet_payload(void) { static const uint8_t data[] = { LA1, LA2, LA3, LA6, LA7, LA8, LA1, LA2, LA3, LA6, LA7, LA8 + 1, 0xff, 0xff, 0x12, 0x34, 0x45, 0x56 }; puts("pktdump dumping Ethernet packet with payload 12 34 45 56"); _test_trigger_recv(ethernet_netif, data, sizeof(data)); } static void test_netapi_recv__raw_ieee802154_payload(void) { static const uint8_t data[] = { 0x41, 0xdc, /* FCF */ 0x03, /* Sequence number */ 0x00, 0x00, /* Destination PAN */ LA8, LA7, LA6, LA5, LA4, LA3, LA2, LA1, LA8 + 1, LA7, LA6, LA5, LA4, LA3, LA2, LA1, 0x12, 0x34, 0x45, 0x56 }; puts("pktdump dumping IEEE 802.15.4 packet with payload 12 34 45 56"); _test_trigger_recv(ieee802154_netif, data, sizeof(data)); } static void test_netapi_recv__ipv6_ethernet_payload(void) { static const uint8_t data[] = { LA1, LA2, LA3, LA6, LA7, LA8, LA1, LA2, LA3, LA6, LA7, LA8 + 1, 0x86, 0xdd, /* Ethertype: IPv6 */ 0x60, 0, 0, 0, /* Version + TC + FL */ 0, 1, /* payload length 1 */ 59, /* next header: no next header */ 64, /* hop limit */ /* IPv6 source */ LP1, LP2, LP3, LP4, LP5, LP6, LP7, LP8, LA1 ^ 1, LA2, LA3, 0xff, 0xfe, LA6, LA7, LA8, /* IPv6 destination */ LP1, LP2, LP3, LP4, LP5, LP6, LP7, LP8, LA1 ^ 1, LA2, LA3, 0xff, 0xfe, LA6, LA7, LA8 + 1, 0x01 /* payload */ }; puts("pktdump dumping IPv6 over Ethernet packet with payload 01"); _test_trigger_recv(ethernet_netif, data, sizeof(data)); } static Test *embunit_tests_gnrc_netif2(void) { EMB_UNIT_TESTFIXTURES(fixtures) { new_TestFixture(test_creation), new_TestFixture(test_get_by_pid), new_TestFixture(test_addr_to_str), new_TestFixture(test_addr_from_str), new_TestFixture(test_ipv6_addr_add__ENOMEM), new_TestFixture(test_ipv6_addr_add__success), new_TestFixture(test_ipv6_addr_add__readd_with_free_entry), new_TestFixture(test_ipv6_addr_remove__not_allocated), new_TestFixture(test_ipv6_addr_remove__success), new_TestFixture(test_ipv6_addr_idx__empty), new_TestFixture(test_ipv6_addr_idx__wrong_netif), new_TestFixture(test_ipv6_addr_idx__wrong_addr), new_TestFixture(test_ipv6_addr_idx__success), new_TestFixture(test_ipv6_addr_match__empty), new_TestFixture(test_ipv6_addr_match__wrong_netif), new_TestFixture(test_ipv6_addr_match__wrong_addr), new_TestFixture(test_ipv6_addr_match__success18), new_TestFixture(test_ipv6_addr_match__success23), new_TestFixture(test_ipv6_addr_match__success64), new_TestFixture(test_ipv6_addr_best_src__multicast_input), new_TestFixture(test_ipv6_addr_best_src__other_subnet), new_TestFixture(test_get_by_ipv6_addr__empty), new_TestFixture(test_get_by_ipv6_addr__success), new_TestFixture(test_get_by_prefix__empty), new_TestFixture(test_get_by_prefix__success18), new_TestFixture(test_get_by_prefix__success23), new_TestFixture(test_get_by_prefix__success64), new_TestFixture(test_ipv6_group_join__ENOMEM), new_TestFixture(test_ipv6_group_join__success), new_TestFixture(test_ipv6_group_join__readd_with_free_entry), new_TestFixture(test_ipv6_group_leave__not_allocated), new_TestFixture(test_ipv6_group_leave__success), new_TestFixture(test_ipv6_group_idx__empty), new_TestFixture(test_ipv6_group_idx__wrong_netif), new_TestFixture(test_ipv6_group_idx__wrong_addr), new_TestFixture(test_ipv6_group_idx__success), new_TestFixture(test_ipv6_get_iid), new_TestFixture(test_netapi_get__HOP_LIMIT), new_TestFixture(test_netapi_get__IPV6_ADDR), new_TestFixture(test_netapi_get__IPV6_ADDR_FLAGS), new_TestFixture(test_netapi_get__IPV6_GROUP), new_TestFixture(test_netapi_get__IPV6_IID), new_TestFixture(test_netapi_get__MAX_PACKET_SIZE), new_TestFixture(test_netapi_get__6LO_IPHC), new_TestFixture(test_netapi_get__ADDRESS), new_TestFixture(test_netapi_get__ADDRESS_LONG), new_TestFixture(test_netapi_set__HOP_LIMIT), new_TestFixture(test_netapi_set__IPV6_ADDR), new_TestFixture(test_netapi_set__IPV6_ADDR_REMOVE), new_TestFixture(test_netapi_set__IPV6_GROUP), new_TestFixture(test_netapi_set__IPV6_GROUP_LEAVE), new_TestFixture(test_netapi_set__MAX_PACKET_SIZE), new_TestFixture(test_netapi_set__6LO_IPHC), new_TestFixture(test_netapi_set__ADDRESS), new_TestFixture(test_netapi_set__ADDRESS_LONG), new_TestFixture(test_netapi_set__SRC_LEN), /* only add tests not involving output here */ }; EMB_UNIT_TESTCALLER(tests, _set_up, NULL, fixtures); return (Test *)&tests; } int main(void) { _tests_init(); netdev_test_set_get_cb((netdev_test_t *)ethernet_dev, NETOPT_ADDRESS, _get_netdev_address); netdev_test_set_set_cb((netdev_test_t *)ethernet_dev, NETOPT_ADDRESS, _set_netdev_address); netdev_test_set_get_cb((netdev_test_t *)ieee802154_dev, NETOPT_ADDRESS, _get_netdev_address); netdev_test_set_set_cb((netdev_test_t *)ieee802154_dev, NETOPT_ADDRESS, _set_netdev_address); netdev_test_set_get_cb((netdev_test_t *)ieee802154_dev, NETOPT_ADDRESS_LONG, _get_netdev_address_long); netdev_test_set_set_cb((netdev_test_t *)ieee802154_dev, NETOPT_ADDRESS_LONG, _set_netdev_address_long); netdev_test_set_get_cb((netdev_test_t *)ieee802154_dev, NETOPT_SRC_LEN, _get_netdev_src_len); netdev_test_set_set_cb((netdev_test_t *)ieee802154_dev, NETOPT_SRC_LEN, _set_netdev_src_len); TESTS_START(); TESTS_RUN(embunit_tests_gnrc_netif2()); TESTS_END(); /* add netapi send and receive tests here */ test_netapi_send__raw_unicast_ethernet_packet(); test_netapi_send__raw_broadcast_ethernet_packet(); test_netapi_send__raw_unicast_ieee802154_long_long_packet(); test_netapi_send__raw_unicast_ieee802154_long_short_packet(); test_netapi_send__raw_unicast_ieee802154_short_long_packet1(); test_netapi_send__raw_unicast_ieee802154_short_long_packet2(); test_netapi_send__raw_unicast_ieee802154_short_short_packet(); test_netapi_send__raw_broadcast_ieee802154_long_packet(); test_netapi_send__raw_broadcast_ieee802154_short_packet(); test_netapi_send__ipv6_unicast_ethernet_packet(); test_netapi_send__ipv6_multicast_ethernet_packet(); test_netapi_send__ipv6_unicast_ieee802154_packet(); test_netapi_send__ipv6_multicast_ieee802154_packet(); test_netapi_recv__empty_ethernet_payload(); test_netapi_recv__empty_ieee802154_payload(); test_netapi_recv__raw_ethernet_payload(); test_netapi_recv__raw_ieee802154_payload(); test_netapi_recv__ipv6_ethernet_payload(); return 0; } static inline int _mock_netif_send(gnrc_netif2_t *netif, gnrc_pktsnip_t *pkt) { (void)netif; (void)pkt; return -1; } static inline gnrc_pktsnip_t *_mock_netif_recv(gnrc_netif2_t * netif) { (void)netif; return NULL; } static uint8_t ethernet_l2addr[] = ETHERNET_SRC; static uint8_t ieee802154_l2addr_long[] = IEEE802154_LONG_SRC; static uint8_t ieee802154_l2addr_short[] = IEEE802154_SHORT_SRC; static uint16_t ieee802154_l2addr_len = 8U; static int _get_netdev_address(netdev_t *dev, void *value, size_t max_len) { if (dev == ethernet_dev) { assert(max_len >= sizeof(ethernet_l2addr)); memcpy(value, ethernet_l2addr, sizeof(ethernet_l2addr)); return sizeof(ethernet_l2addr); } else if (dev == ieee802154_dev) { assert(max_len >= sizeof(ieee802154_l2addr_short)); memcpy(value, ieee802154_l2addr_short, sizeof(ieee802154_l2addr_short)); return sizeof(ieee802154_l2addr_short); } return -ENOTSUP; } static int _set_netdev_address(netdev_t *dev, const void *value, size_t value_len) { if (dev == ethernet_dev) { assert(value_len <= sizeof(ethernet_l2addr)); memcpy(ethernet_l2addr, value, value_len); return value_len; } else if (dev == ieee802154_dev) { assert(value_len <= sizeof(ieee802154_l2addr_short)); memcpy(ieee802154_l2addr_short, value, value_len); return value_len; } return -ENOTSUP; } static int _get_netdev_address_long(netdev_t *dev, void *value, size_t max_len) { if (dev == ieee802154_dev) { assert(max_len >= sizeof(ieee802154_l2addr_long)); memcpy(value, ieee802154_l2addr_long, sizeof(ieee802154_l2addr_long)); return sizeof(ieee802154_l2addr_long); } return -ENOTSUP; } static int _set_netdev_address_long(netdev_t *dev, const void *value, size_t value_len) { if (dev == ieee802154_dev) { assert(value_len <= sizeof(ieee802154_l2addr_long)); memcpy(ieee802154_l2addr_long, value, value_len); return value_len; } return -ENOTSUP; } static int _get_netdev_src_len(netdev_t *dev, void *value, size_t max_len) { if (dev == ieee802154_dev) { assert(max_len == sizeof(uint16_t)); *((uint16_t *)value) = ieee802154_l2addr_len; return sizeof(uint16_t); } return -ENOTSUP; } static int _set_netdev_src_len(netdev_t *dev, const void *value, size_t value_len) { if (dev == ieee802154_dev) { assert(value_len == sizeof(uint16_t)); ieee802154_l2addr_len = *((uint16_t *)value); return sizeof(uint16_t); } return -ENOTSUP; }
lgpl-2.1
pelya/commandergenius
project/jni/application/alienblaster/soundDB.cpp
7
2686
/*************************************************************************** alienBlaster Copyright (C) 2004 Paul Grathwohl, Arne Hormann, Daniel Kuehn, Soenke Schwardt 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, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ***************************************************************************/ using namespace std; #include "soundDB.h" #include "SDL_mixer.h" #ifdef ANDROID #include <android/log.h> #endif #include <iostream> SoundDB::SoundDB() {} SoundDB::~SoundDB() { StringSoundMap::iterator pos; // free all Mix_Chunks for ( pos = soundDB.begin(); pos != soundDB.end(); ++pos ) { Mix_FreeChunk( pos->second ); } } Mix_Chunk *SoundDB::loadWav( string fn ) { Mix_Chunk *searchResult = getWav( fn ); if ( searchResult ) { return searchResult; } __android_log_print(ANDROID_LOG_INFO, "Alien Blaster", (string( "Loading sound " ) + fn).c_str() ); string fn1 = fn; // Check if file exist FILE * inputFile = fopen( fn1.c_str(), "rb"); if (!inputFile) { if( fn1.size() > 4 && fn1.find(".wav") != string::npos ) { fn1 = fn1.substr( 0, fn1.size() - 4 ) + ".ogg"; inputFile = fopen( fn1.c_str(), "rb"); } if (!inputFile) { cout << "ERROR: file " << fn1 << " does not exist!" << endl; #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, "Alien Blaster", (string( "Cannot load sound " ) + fn1).c_str() ); #endif exit(1); } } fclose(inputFile); // TODO: error-handling Mix_Chunk *newSound = Mix_LoadWAV( fn1.c_str() ); if( !newSound ) { cout << "ERROR: file " << fn1 << " cannot be loaded!" << endl; #ifdef ANDROID __android_log_print(ANDROID_LOG_ERROR, "Alien Blaster", (string( "Cannot load sound " ) + fn1).c_str() ); #endif exit(1); } soundDB[ fn ] = newSound; return newSound; } Mix_Chunk *SoundDB::getWav( string fn ) { if ( soundDB.empty() ) { return 0; } else { StringSoundMap::iterator pos = soundDB.find( fn ); if ( pos == soundDB.end() ) { return 0; } else { return pos->second; } } }
lgpl-2.1
freedesktop-unofficial-mirror/gstreamer-sdk__gst-plugins-good
sys/oss4/oss4-sink.c
8
20095
/* GStreamer OSS4 audio sink * Copyright (C) 2007-2008 Tim-Philipp Müller <tim centricular net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ /** * SECTION:element-oss4sink * * This element lets you output sound using the Open Sound System (OSS) * version 4. * * Note that you should almost always use generic audio conversion elements * like audioconvert and audioresample in front of an audiosink to make sure * your pipeline works under all circumstances (those conversion elements will * act in passthrough-mode if no conversion is necessary). * * <refsect2> * <title>Example pipelines</title> * |[ * gst-launch -v audiotestsrc ! audioconvert ! volume volume=0.1 ! oss4sink * ]| will output a sine wave (continuous beep sound) to your sound card (with * a very low volume as precaution). * |[ * gst-launch -v filesrc location=music.ogg ! decodebin ! audioconvert ! audioresample ! oss4sink * ]| will play an Ogg/Vorbis audio file and output it using the Open Sound System * version 4. * </refsect2> * * Since: 0.10.7 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <string.h> #include <gst/gst-i18n-plugin.h> #include <gst/interfaces/streamvolume.h> #define NO_LEGACY_MIXER #include "oss4-audio.h" #include "oss4-sink.h" #include "oss4-property-probe.h" #include "oss4-soundcard.h" GST_DEBUG_CATEGORY_EXTERN (oss4sink_debug); #define GST_CAT_DEFAULT oss4sink_debug static void gst_oss4_sink_init_interfaces (GType type); static void gst_oss4_sink_dispose (GObject * object); static void gst_oss4_sink_finalize (GObject * object); static void gst_oss4_sink_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec); static void gst_oss4_sink_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec); static GstCaps *gst_oss4_sink_getcaps (GstBaseSink * bsink); static gboolean gst_oss4_sink_open (GstAudioSink * asink, gboolean silent_errors); static gboolean gst_oss4_sink_open_func (GstAudioSink * asink); static gboolean gst_oss4_sink_close (GstAudioSink * asink); static gboolean gst_oss4_sink_prepare (GstAudioSink * asink, GstRingBufferSpec * spec); static gboolean gst_oss4_sink_unprepare (GstAudioSink * asink); static guint gst_oss4_sink_write (GstAudioSink * asink, gpointer data, guint length); static guint gst_oss4_sink_delay (GstAudioSink * asink); static void gst_oss4_sink_reset (GstAudioSink * asink); #define DEFAULT_DEVICE NULL #define DEFAULT_DEVICE_NAME NULL #define DEFAULT_MUTE FALSE #define DEFAULT_VOLUME 1.0 #define MAX_VOLUME 10.0 enum { PROP_0, PROP_DEVICE, PROP_DEVICE_NAME, PROP_VOLUME, PROP_MUTE, PROP_LAST }; GST_BOILERPLATE_FULL (GstOss4Sink, gst_oss4_sink, GstAudioSink, GST_TYPE_AUDIO_SINK, gst_oss4_sink_init_interfaces); static void gst_oss4_sink_dispose (GObject * object) { GstOss4Sink *osssink = GST_OSS4_SINK (object); if (osssink->probed_caps) { gst_caps_unref (osssink->probed_caps); osssink->probed_caps = NULL; } G_OBJECT_CLASS (parent_class)->dispose (object); } static void gst_oss4_sink_base_init (gpointer g_class) { GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); GstPadTemplate *templ; gst_element_class_set_details_simple (element_class, "OSS v4 Audio Sink", "Sink/Audio", "Output to a sound card via OSS version 4", "Tim-Philipp Müller <tim centricular net>"); templ = gst_pad_template_new ("sink", GST_PAD_SINK, GST_PAD_ALWAYS, gst_oss4_audio_get_template_caps ()); gst_element_class_add_pad_template (element_class, templ); gst_object_unref (templ); } static void gst_oss4_sink_class_init (GstOss4SinkClass * klass) { GstAudioSinkClass *audiosink_class = (GstAudioSinkClass *) klass; GstBaseSinkClass *basesink_class = (GstBaseSinkClass *) klass; GObjectClass *gobject_class = (GObjectClass *) klass; gobject_class->dispose = gst_oss4_sink_dispose; gobject_class->finalize = gst_oss4_sink_finalize; gobject_class->get_property = gst_oss4_sink_get_property; gobject_class->set_property = gst_oss4_sink_set_property; g_object_class_install_property (gobject_class, PROP_DEVICE, g_param_spec_string ("device", "Device", "OSS4 device (e.g. /dev/oss/hdaudio0/pcm0 or /dev/dspN) " "(NULL = use first available playback device)", DEFAULT_DEVICE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_DEVICE_NAME, g_param_spec_string ("device-name", "Device name", "Human-readable name of the sound device", DEFAULT_DEVICE_NAME, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_VOLUME, g_param_spec_double ("volume", "Volume", "Linear volume of this stream, 1.0=100%", 0.0, MAX_VOLUME, DEFAULT_VOLUME, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); g_object_class_install_property (gobject_class, PROP_MUTE, g_param_spec_boolean ("mute", "Mute", "Mute state of this stream", DEFAULT_MUTE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); basesink_class->get_caps = GST_DEBUG_FUNCPTR (gst_oss4_sink_getcaps); audiosink_class->open = GST_DEBUG_FUNCPTR (gst_oss4_sink_open_func); audiosink_class->close = GST_DEBUG_FUNCPTR (gst_oss4_sink_close); audiosink_class->prepare = GST_DEBUG_FUNCPTR (gst_oss4_sink_prepare); audiosink_class->unprepare = GST_DEBUG_FUNCPTR (gst_oss4_sink_unprepare); audiosink_class->write = GST_DEBUG_FUNCPTR (gst_oss4_sink_write); audiosink_class->delay = GST_DEBUG_FUNCPTR (gst_oss4_sink_delay); audiosink_class->reset = GST_DEBUG_FUNCPTR (gst_oss4_sink_reset); } static void gst_oss4_sink_init (GstOss4Sink * osssink, GstOss4SinkClass * klass) { const gchar *device; device = g_getenv ("AUDIODEV"); if (device == NULL) device = DEFAULT_DEVICE; osssink->device = g_strdup (device); osssink->fd = -1; osssink->bytes_per_sample = 0; osssink->probed_caps = NULL; osssink->device_name = NULL; osssink->mute_volume = 100 | (100 << 8); } static void gst_oss4_sink_finalize (GObject * object) { GstOss4Sink *osssink = GST_OSS4_SINK (object); g_free (osssink->device); osssink->device = NULL; g_list_free (osssink->property_probe_list); osssink->property_probe_list = NULL; G_OBJECT_CLASS (parent_class)->finalize (object); } static void gst_oss4_sink_set_volume (GstOss4Sink * oss, gdouble volume) { int ivol; volume = volume * 100.0; ivol = (int) volume | ((int) volume << 8); GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_SETPLAYVOL, &ivol) < 0) { GST_LOG_OBJECT (oss, "SETPLAYVOL failed"); } GST_OBJECT_UNLOCK (oss); } static gdouble gst_oss4_sink_get_volume (GstOss4Sink * oss) { int ivol, lvol, rvol; gdouble dvol = DEFAULT_VOLUME; GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_GETPLAYVOL, &ivol) < 0) { GST_LOG_OBJECT (oss, "GETPLAYVOL failed"); } else { /* Return the higher of the two volume channels, if different */ lvol = ivol & 0xff; rvol = (ivol >> 8) & 0xff; dvol = MAX (lvol, rvol) / 100.0; } GST_OBJECT_UNLOCK (oss); return dvol; } static void gst_oss4_sink_set_mute (GstOss4Sink * oss, gboolean mute) { int ivol; if (mute) { /* * OSSv4 does not have a per-channel mute, so simulate by setting * the value to 0. Save the volume before doing a mute so we can * reset the value when the user un-mutes. */ ivol = 0; GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_GETPLAYVOL, &oss->mute_volume) < 0) { GST_LOG_OBJECT (oss, "GETPLAYVOL failed"); } if (ioctl (oss->fd, SNDCTL_DSP_SETPLAYVOL, &ivol) < 0) { GST_LOG_OBJECT (oss, "SETPLAYVOL failed"); } GST_OBJECT_UNLOCK (oss); } else { /* * If the saved volume is 0, then reset it to 100. Otherwise the mute * can get stuck. This can happen, for example, due to rounding * errors in converting from the float to an integer. */ if (oss->mute_volume == 0) { oss->mute_volume = 100 | (100 << 8); } GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_SETPLAYVOL, &oss->mute_volume) < 0) { GST_LOG_OBJECT (oss, "SETPLAYVOL failed"); } GST_OBJECT_UNLOCK (oss); } } static gboolean gst_oss4_sink_get_mute (GstOss4Sink * oss) { int ivol, lvol, rvol; GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_GETPLAYVOL, &ivol) < 0) { GST_LOG_OBJECT (oss, "GETPLAYVOL failed"); lvol = rvol = 100; } else { lvol = ivol & 0xff; rvol = (ivol >> 8) & 0xff; } GST_OBJECT_UNLOCK (oss); return (lvol == 0 && rvol == 0); } static void gst_oss4_sink_set_property (GObject * object, guint prop_id, const GValue * value, GParamSpec * pspec) { GstOss4Sink *oss = GST_OSS4_SINK (object); switch (prop_id) { case PROP_DEVICE: GST_OBJECT_LOCK (oss); if (oss->fd == -1) { g_free (oss->device); oss->device = g_value_dup_string (value); if (oss->probed_caps) { gst_caps_unref (oss->probed_caps); oss->probed_caps = NULL; } g_free (oss->device_name); oss->device_name = NULL; } else { g_warning ("%s: can't change \"device\" property while audio sink " "is open", GST_OBJECT_NAME (oss)); } GST_OBJECT_UNLOCK (oss); break; case PROP_VOLUME: gst_oss4_sink_set_volume (oss, g_value_get_double (value)); break; case PROP_MUTE: gst_oss4_sink_set_mute (oss, g_value_get_boolean (value)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static void gst_oss4_sink_get_property (GObject * object, guint prop_id, GValue * value, GParamSpec * pspec) { GstOss4Sink *oss = GST_OSS4_SINK (object); switch (prop_id) { case PROP_DEVICE: GST_OBJECT_LOCK (oss); g_value_set_string (value, oss->device); GST_OBJECT_UNLOCK (oss); break; case PROP_DEVICE_NAME: GST_OBJECT_LOCK (oss); if (oss->fd == -1 && oss->device != NULL) { /* If device is set, try to retrieve the name even if we're not open */ if (gst_oss4_sink_open (GST_AUDIO_SINK (oss), TRUE)) { g_value_set_string (value, oss->device_name); gst_oss4_sink_close (GST_AUDIO_SINK (oss)); } else { gchar *name = NULL; gst_oss4_property_probe_find_device_name_nofd (GST_OBJECT (oss), oss->device, &name); g_value_set_string (value, name); g_free (name); } } else { g_value_set_string (value, oss->device_name); } GST_OBJECT_UNLOCK (oss); break; case PROP_VOLUME: g_value_set_double (value, gst_oss4_sink_get_volume (oss)); break; case PROP_MUTE: g_value_set_boolean (value, gst_oss4_sink_get_mute (oss)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); break; } } static GstCaps * gst_oss4_sink_getcaps (GstBaseSink * bsink) { GstOss4Sink *oss; GstCaps *caps; oss = GST_OSS4_SINK (bsink); if (oss->fd == -1) { caps = gst_oss4_audio_get_template_caps (); } else if (oss->probed_caps) { caps = gst_caps_copy (oss->probed_caps); } else { caps = gst_oss4_audio_probe_caps (GST_OBJECT (oss), oss->fd); if (caps != NULL && !gst_caps_is_empty (caps)) { oss->probed_caps = gst_caps_copy (caps); } } return caps; } /* note: we must not take the object lock here unless we fix up get_property */ static gboolean gst_oss4_sink_open (GstAudioSink * asink, gboolean silent_errors) { GstOss4Sink *oss; gchar *device; int mode; oss = GST_OSS4_SINK (asink); if (oss->device) device = g_strdup (oss->device); else device = gst_oss4_audio_find_device (GST_OBJECT_CAST (oss)); /* desperate times, desperate measures */ if (device == NULL) device = g_strdup ("/dev/dsp0"); GST_INFO_OBJECT (oss, "Trying to open OSS4 device '%s'", device); /* we open in non-blocking mode even if we don't really want to do writes * non-blocking because we can't be sure that this is really a genuine * OSS4 device with well-behaved drivers etc. We really don't want to * hang forever under any circumstances. */ oss->fd = open (device, O_WRONLY | O_NONBLOCK, 0); if (oss->fd == -1) { switch (errno) { case EBUSY: goto busy; case EACCES: goto no_permission; default: goto open_failed; } } GST_INFO_OBJECT (oss, "Opened device '%s'", device); /* Make sure it's OSS4. If it's old OSS, let osssink handle it */ if (!gst_oss4_audio_check_version (GST_OBJECT_CAST (oss), oss->fd)) goto legacy_oss; /* now remove the non-blocking flag. */ mode = fcntl (oss->fd, F_GETFL); mode &= ~O_NONBLOCK; if (fcntl (oss->fd, F_SETFL, mode) < 0) { /* some drivers do no support unsetting the non-blocking flag, try to * close/open the device then. This is racy but we error out properly. */ GST_WARNING_OBJECT (oss, "failed to unset O_NONBLOCK (buggy driver?), " "will try to re-open device now"); gst_oss4_sink_close (asink); if ((oss->fd = open (device, O_WRONLY, 0)) == -1) goto non_block; } oss->open_device = device; /* not using ENGINEINFO here because it sometimes returns a different and * less useful name than AUDIOINFO for the same device */ if (!gst_oss4_property_probe_find_device_name (GST_OBJECT (oss), oss->fd, oss->open_device, &oss->device_name)) { oss->device_name = NULL; } /* list output routings, for informational purposes only so far */ { oss_mixer_enuminfo routings = { 0, }; guint i; if (ioctl (oss->fd, SNDCTL_DSP_GET_PLAYTGT_NAMES, &routings) != -1) { GST_LOG_OBJECT (oss, "%u output routings (static list: %d)", routings.nvalues, !!(routings.version == 0)); for (i = 0; i < routings.nvalues; ++i) { GST_LOG_OBJECT (oss, " output routing %d: %s", i, &routings.strings[routings.strindex[i]]); } } } return TRUE; /* ERRORS */ busy: { if (!silent_errors) { GST_ELEMENT_ERROR (oss, RESOURCE, BUSY, (_("Could not open audio device for playback. " "Device is being used by another application.")), (NULL)); } g_free (device); return FALSE; } no_permission: { if (!silent_errors) { GST_ELEMENT_ERROR (oss, RESOURCE, OPEN_WRITE, (_("Could not open audio device for playback. " "You don't have permission to open the device.")), GST_ERROR_SYSTEM); } g_free (device); return FALSE; } open_failed: { if (!silent_errors) { GST_ELEMENT_ERROR (oss, RESOURCE, OPEN_WRITE, (_("Could not open audio device for playback.")), GST_ERROR_SYSTEM); } g_free (device); return FALSE; } legacy_oss: { if (!silent_errors) { GST_ELEMENT_ERROR (oss, RESOURCE, OPEN_WRITE, (_("Could not open audio device for playback. " "This version of the Open Sound System is not supported by this " "element.")), ("Try the 'osssink' element instead")); } gst_oss4_sink_close (asink); g_free (device); return FALSE; } non_block: { if (!silent_errors) { GST_ELEMENT_ERROR (oss, RESOURCE, SETTINGS, (NULL), ("Unable to set device %s into non-blocking mode: %s", oss->device, g_strerror (errno))); } g_free (device); return FALSE; } } static gboolean gst_oss4_sink_open_func (GstAudioSink * asink) { return gst_oss4_sink_open (asink, FALSE); } static gboolean gst_oss4_sink_close (GstAudioSink * asink) { GstOss4Sink *oss = GST_OSS4_SINK (asink); if (oss->fd != -1) { GST_DEBUG_OBJECT (oss, "closing device"); close (oss->fd); oss->fd = -1; } oss->bytes_per_sample = 0; /* we keep the probed caps cached, at least until the device changes */ g_free (oss->open_device); oss->open_device = NULL; g_free (oss->device_name); oss->device_name = NULL; if (oss->probed_caps) { gst_caps_unref (oss->probed_caps); oss->probed_caps = NULL; } return TRUE; } static gboolean gst_oss4_sink_prepare (GstAudioSink * asink, GstRingBufferSpec * spec) { GstOss4Sink *oss; oss = GST_OSS4_SINK (asink); if (!gst_oss4_audio_set_format (GST_OBJECT_CAST (oss), oss->fd, spec)) { GST_WARNING_OBJECT (oss, "Couldn't set requested format %" GST_PTR_FORMAT, spec->caps); return FALSE; } oss->bytes_per_sample = spec->bytes_per_sample; return TRUE; } static gboolean gst_oss4_sink_unprepare (GstAudioSink * asink) { /* could do a SNDCTL_DSP_HALT, but the OSS manual recommends a close/open, * since HALT won't properly reset some devices, apparently */ if (!gst_oss4_sink_close (asink)) goto couldnt_close; if (!gst_oss4_sink_open_func (asink)) goto couldnt_reopen; return TRUE; /* ERRORS */ couldnt_close: { GST_DEBUG_OBJECT (asink, "Couldn't close the audio device"); return FALSE; } couldnt_reopen: { GST_DEBUG_OBJECT (asink, "Couldn't reopen the audio device"); return FALSE; } } static guint gst_oss4_sink_write (GstAudioSink * asink, gpointer data, guint length) { GstOss4Sink *oss; int n; oss = GST_OSS4_SINK_CAST (asink); n = write (oss->fd, data, length); GST_LOG_OBJECT (asink, "wrote %d/%d samples, %d bytes", n / oss->bytes_per_sample, length / oss->bytes_per_sample, n); if (G_UNLIKELY (n < 0)) { switch (errno) { case ENOTSUP: case EACCES:{ /* This is the most likely cause, I think */ GST_ELEMENT_ERROR (asink, RESOURCE, WRITE, (_("Playback is not supported by this audio device.")), ("write: %s (device: %s) (maybe this is an input-only device?)", g_strerror (errno), oss->open_device)); break; } default:{ GST_ELEMENT_ERROR (asink, RESOURCE, WRITE, (_("Audio playback error.")), ("write: %s (device: %s)", g_strerror (errno), oss->open_device)); break; } } } return n; } static guint gst_oss4_sink_delay (GstAudioSink * asink) { GstOss4Sink *oss; gint delay = -1; oss = GST_OSS4_SINK_CAST (asink); GST_OBJECT_LOCK (oss); if (ioctl (oss->fd, SNDCTL_DSP_GETODELAY, &delay) < 0 || delay < 0) { GST_LOG_OBJECT (oss, "GETODELAY failed"); } GST_OBJECT_UNLOCK (oss); if (G_UNLIKELY (delay < 0)) /* error case */ return 0; return delay / oss->bytes_per_sample; } static void gst_oss4_sink_reset (GstAudioSink * asink) { /* There's nothing we can do here really: OSS can't handle access to the * same device/fd from multiple threads and might deadlock or blow up in * other ways if we try an ioctl SNDCTL_DSP_HALT or similar */ } static void gst_oss4_sink_init_interfaces (GType type) { static const GInterfaceInfo svol_iface_info = { NULL, NULL, NULL }; g_type_add_interface_static (type, GST_TYPE_STREAM_VOLUME, &svol_iface_info); gst_oss4_add_property_probe_interface (type); }
lgpl-2.1
alexcrichton/libgit2
src/win32/findfile.c
13
5372
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "utf-conv.h" #include "path.h" #include "findfile.h" #define REG_MSYSGIT_INSTALL_LOCAL L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1" #ifndef _WIN64 #define REG_MSYSGIT_INSTALL REG_MSYSGIT_INSTALL_LOCAL #else #define REG_MSYSGIT_INSTALL L"SOFTWARE\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\Git_is1" #endif typedef struct { git_win32_path path; DWORD len; } _findfile_path; static int git_win32__expand_path(_findfile_path *dest, const wchar_t *src) { dest->len = ExpandEnvironmentStringsW(src, dest->path, ARRAY_SIZE(dest->path)); if (!dest->len || dest->len > ARRAY_SIZE(dest->path)) return -1; return 0; } static int win32_path_to_8(git_buf *dest, const wchar_t *src) { git_win32_utf8_path utf8_path; if (git_win32_path_to_utf8(utf8_path, src) < 0) { giterr_set(GITERR_OS, "Unable to convert path to UTF-8"); return -1; } /* Convert backslashes to forward slashes */ git_path_mkposix(utf8_path); return git_buf_sets(dest, utf8_path); } static wchar_t* win32_walkpath(wchar_t *path, wchar_t *buf, size_t buflen) { wchar_t term, *base = path; assert(path && buf && buflen); term = (*path == L'"') ? *path++ : L';'; for (buflen--; *path && *path != term && buflen; buflen--) *buf++ = *path++; *buf = L'\0'; /* reserved a byte via initial subtract */ while (*path == term || *path == L';') path++; return (path != base) ? path : NULL; } static int win32_find_git_in_path(git_buf *buf, const wchar_t *gitexe, const wchar_t *subdir) { wchar_t *env = _wgetenv(L"PATH"), lastch; _findfile_path root; size_t gitexe_len = wcslen(gitexe); if (!env) return -1; while ((env = win32_walkpath(env, root.path, MAX_PATH-1)) && *root.path) { root.len = (DWORD)wcslen(root.path); lastch = root.path[root.len - 1]; /* ensure trailing slash (MAX_PATH-1 to walkpath guarantees space) */ if (lastch != L'/' && lastch != L'\\') { root.path[root.len++] = L'\\'; root.path[root.len] = L'\0'; } if (root.len + gitexe_len >= MAX_PATH) continue; wcscpy(&root.path[root.len], gitexe); if (_waccess(root.path, F_OK) == 0 && root.len > 5) { /* replace "bin\\" or "cmd\\" with subdir */ wcscpy(&root.path[root.len - 4], subdir); win32_path_to_8(buf, root.path); return 0; } } return GIT_ENOTFOUND; } static int win32_find_git_in_registry( git_buf *buf, const HKEY hive, const wchar_t *key, const wchar_t *subdir) { HKEY hKey; int error = GIT_ENOTFOUND; assert(buf); if (!RegOpenKeyExW(hive, key, 0, KEY_READ, &hKey)) { DWORD dwType, cbData; git_win32_path path; /* Ensure that the buffer is big enough to have the suffix attached * after we receive the result. */ cbData = (DWORD)(sizeof(path) - wcslen(subdir) * sizeof(wchar_t)); /* InstallLocation points to the root of the git directory */ if (!RegQueryValueExW(hKey, L"InstallLocation", NULL, &dwType, (LPBYTE)path, &cbData) && dwType == REG_SZ) { /* Append the suffix */ wcscat(path, subdir); /* Convert to UTF-8, with forward slashes, and output the path * to the provided buffer */ if (!win32_path_to_8(buf, path)) error = 0; } RegCloseKey(hKey); } return error; } static int win32_find_existing_dirs( git_buf *out, const wchar_t *tmpl[]) { _findfile_path path16; git_buf buf = GIT_BUF_INIT; git_buf_clear(out); for (; *tmpl != NULL; tmpl++) { if (!git_win32__expand_path(&path16, *tmpl) && path16.path[0] != L'%' && !_waccess(path16.path, F_OK)) { win32_path_to_8(&buf, path16.path); if (buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); } } git_buf_free(&buf); return (git_buf_oom(out) ? -1 : 0); } int git_win32__find_system_dirs(git_buf *out, const wchar_t *subdir) { git_buf buf = GIT_BUF_INIT; /* directories where git.exe & git.cmd are found */ if (!win32_find_git_in_path(&buf, L"git.exe", subdir) && buf.size) git_buf_set(out, buf.ptr, buf.size); else git_buf_clear(out); if (!win32_find_git_in_path(&buf, L"git.cmd", subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); /* directories where git is installed according to registry */ if (!win32_find_git_in_registry( &buf, HKEY_CURRENT_USER, REG_MSYSGIT_INSTALL_LOCAL, subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); if (!win32_find_git_in_registry( &buf, HKEY_LOCAL_MACHINE, REG_MSYSGIT_INSTALL, subdir) && buf.size) git_buf_join(out, GIT_PATH_LIST_SEPARATOR, out->ptr, buf.ptr); git_buf_free(&buf); return (git_buf_oom(out) ? -1 : 0); } int git_win32__find_global_dirs(git_buf *out) { static const wchar_t *global_tmpls[4] = { L"%HOME%\\", L"%HOMEDRIVE%%HOMEPATH%\\", L"%USERPROFILE%\\", NULL, }; return win32_find_existing_dirs(out, global_tmpls); } int git_win32__find_xdg_dirs(git_buf *out) { static const wchar_t *global_tmpls[7] = { L"%XDG_CONFIG_HOME%\\git", L"%APPDATA%\\git", L"%LOCALAPPDATA%\\git", L"%HOME%\\.config\\git", L"%HOMEDRIVE%%HOMEPATH%\\.config\\git", L"%USERPROFILE%\\.config\\git", NULL, }; return win32_find_existing_dirs(out, global_tmpls); }
lgpl-2.1
Ell-i/RIOT
cpu/cortexm_common/vectors_cortexm.c
13
12126
/* * Copyright (C) 2015 Freie Universität Berlin * * 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 cpu_cortexm_common * @{ * * @file * @brief Default implementations for Cortex-M specific interrupt and * exception handlers * * @author Hauke Petersen <hauke.petersen@fu-berlin.de> * @author Daniel Krebs <github@daniel-krebs.net> * @author Joakim Gebart <joakim.gebart@eistec.se> * * @} */ #include <stdint.h> #include <stdio.h> #include <inttypes.h> #include "cpu.h" #include "kernel_init.h" #include "board.h" #include "mpu.h" #include "panic.h" #include "vectors_cortexm.h" #ifndef SRAM_BASE #define SRAM_BASE 0 #endif /** * @brief Memory markers, defined in the linker script * @{ */ extern uint32_t _sfixed; extern uint32_t _efixed; extern uint32_t _etext; extern uint32_t _srelocate; extern uint32_t _erelocate; extern uint32_t _szero; extern uint32_t _ezero; extern uint32_t _sstack; extern uint32_t _estack; extern uint32_t _sram; extern uint32_t _eram; /** @} */ /** * @brief Allocation of the interrupt stack */ __attribute__((used,section(".isr_stack"))) uint8_t isr_stack[ISR_STACKSIZE]; /** * @brief Pre-start routine for CPU-specific settings */ __attribute__((weak)) void pre_startup (void) { } /** * @brief Post-start routine for CPU-specific settings */ __attribute__((weak)) void post_startup (void) { } void reset_handler_default(void) { uint32_t *dst; uint32_t *src = &_etext; pre_startup(); #ifdef DEVELHELP uint32_t *top; /* Fill stack space with canary values up until the current stack pointer */ /* Read current stack pointer from CPU register */ __asm__ volatile ("mov %[top], sp" : [top] "=r" (top) : : ); dst = &_sstack; while (dst < top) { *(dst++) = STACK_CANARY_WORD; } #endif /* load data section from flash to ram */ for (dst = &_srelocate; dst < &_erelocate; ) { *(dst++) = *(src++); } /* default bss section to zero */ for (dst = &_szero; dst < &_ezero; ) { *(dst++) = 0; } #ifdef MODULE_MPU_STACK_GUARD if (((uintptr_t)&_sstack) != SRAM_BASE) { mpu_configure( 0, /* MPU region 0 */ (uintptr_t)&_sstack + 31, /* Base Address (rounded up) */ MPU_ATTR(1, AP_RO_RO, 0, 1, 0, 1, MPU_SIZE_32B) /* Attributes and Size */ ); mpu_enable(); } #endif post_startup(); /* initialize the board (which also initiates CPU initialization) */ board_init(); #if MODULE_NEWLIB /* initialize std-c library (this must be done after board_init) */ extern void __libc_init_array(void); __libc_init_array(); #endif /* startup the kernel */ kernel_init(); } void nmi_default(void) { core_panic(PANIC_NMI_HANDLER, "NMI HANDLER"); } #ifdef DEVELHELP /* The hard fault handler requires some stack space as a working area for local * variables and printf function calls etc. If the stack pointer is located * closer than HARDFAULT_HANDLER_REQUIRED_STACK_SPACE from the lowest address of * RAM we will reset the stack pointer to the top of available RAM. * Measured from trampoline entry to breakpoint: * - Cortex-M0+ 344 Byte * - Cortex-M4 344 Byte */ #define HARDFAULT_HANDLER_REQUIRED_STACK_SPACE (344U) static inline int _stack_size_left(uint32_t required) { uint32_t* sp; __asm__ volatile ("mov %[sp], sp" : [sp] "=r" (sp) : : ); return ((int)((uint32_t)sp - (uint32_t)&_sstack) - required); } void hard_fault_handler(uint32_t* sp, uint32_t corrupted, uint32_t exc_return, uint32_t* r4_to_r11_stack); /* Trampoline function to save stack pointer before calling hard fault handler */ __attribute__((naked)) void hard_fault_default(void) { /* Get stack pointer where exception stack frame lies */ __asm__ volatile ( /* Check that msp is valid first because we want to stack all the * r4-r11 registers so that we can use r0, r1, r2, r3 for other things. */ "mov r0, sp \n" /* r0 = msp */ "cmp r0, %[eram] \n" /* if(msp > &_eram) { */ "bhi fix_msp \n" /* goto fix_msp } */ "cmp r0, %[sram] \n" /* if(msp <= &_sram) { */ "bls fix_msp \n" /* goto fix_msp } */ "movs r1, #0 \n" /* else { corrupted = false */ "b test_sp \n" /* goto test_sp } */ " fix_msp: \n" /* */ "mov r1, %[estack] \n" /* r1 = _estack */ "mov sp, r1 \n" /* sp = r1 */ "movs r1, #1 \n" /* corrupted = true */ " test_sp: \n" /* */ "movs r0, #4 \n" /* r0 = 0x4 */ "mov r2, lr \n" /* r2 = lr */ "tst r2, r0 \n" /* if(lr & 0x4) */ "bne use_psp \n" /* { */ "mrs r0, msp \n" /* r0 = msp */ "b out \n" /* } */ " use_psp: \n" /* else { */ "mrs r0, psp \n" /* r0 = psp */ " out: \n" /* } */ #if (__CORTEX_M == 0) "push {r4-r7} \n" /* save r4..r7 to the stack */ "mov r3, r8 \n" /* */ "mov r4, r9 \n" /* */ "mov r5, r10 \n" /* */ "mov r6, r11 \n" /* */ "push {r3-r6} \n" /* save r8..r11 to the stack */ #else "push {r4-r11} \n" /* save r4..r11 to the stack */ #endif "mov r3, sp \n" /* r4_to_r11_stack parameter */ "bl hard_fault_handler \n" /* hard_fault_handler(r0) */ : : [sram] "r" (&_sram + HARDFAULT_HANDLER_REQUIRED_STACK_SPACE), [eram] "r" (&_eram), [estack] "r" (&_estack) : "r0","r4","r5","r6","r8","r9","r10","r11","lr" ); } #if (__CORTEX_M == 0) /* Cortex-M0 and Cortex-M0+ lack the extended fault status registers found in * Cortex-M3 and above. */ #define CPU_HAS_EXTENDED_FAULT_REGISTERS 0 #else #define CPU_HAS_EXTENDED_FAULT_REGISTERS 1 #endif __attribute__((used)) void hard_fault_handler(uint32_t* sp, uint32_t corrupted, uint32_t exc_return, uint32_t* r4_to_r11_stack) { #if CPU_HAS_EXTENDED_FAULT_REGISTERS static const uint32_t BFARVALID_MASK = (0x80 << SCB_CFSR_BUSFAULTSR_Pos); static const uint32_t MMARVALID_MASK = (0x80 << SCB_CFSR_MEMFAULTSR_Pos); /* Copy status register contents to local stack storage, this must be * done before any calls to other functions to avoid corrupting the * register contents. */ uint32_t bfar = SCB->BFAR; uint32_t mmfar = SCB->MMFAR; uint32_t cfsr = SCB->CFSR; uint32_t hfsr = SCB->HFSR; uint32_t dfsr = SCB->DFSR; uint32_t afsr = SCB->AFSR; #endif /* Initialize these variables even if they're never used uninitialized. * Fixes wrong compiler warning by gcc < 6.0. */ uint32_t pc = 0; /* cppcheck-suppress variableScope * variable used in assembly-code below */ uint32_t* orig_sp = NULL; /* Check if the ISR stack overflowed previously. Not possible to detect * after output may also have overflowed it. */ if(*(&_sstack) != STACK_CANARY_WORD) { puts("\nISR stack overflowed"); } /* Sanity check stack pointer and give additional feedback about hard fault */ if(corrupted) { puts("Stack pointer corrupted, reset to top of stack"); } else { uint32_t r0 = sp[0]; uint32_t r1 = sp[1]; uint32_t r2 = sp[2]; uint32_t r3 = sp[3]; uint32_t r12 = sp[4]; uint32_t lr = sp[5]; /* Link register. */ pc = sp[6]; /* Program counter. */ uint32_t psr = sp[7]; /* Program status register. */ /* Reconstruct original stack pointer before fault occurred */ orig_sp = sp + 8; if (psr & SCB_CCR_STKALIGN_Msk) { /* Stack was not 8-byte aligned */ orig_sp += 1; } puts("\nContext before hardfault:"); /* TODO: printf in ISR context might be a bad idea */ printf(" r0: 0x%08" PRIx32 "\n" " r1: 0x%08" PRIx32 "\n" " r2: 0x%08" PRIx32 "\n" " r3: 0x%08" PRIx32 "\n", r0, r1, r2, r3); printf(" r12: 0x%08" PRIx32 "\n" " lr: 0x%08" PRIx32 "\n" " pc: 0x%08" PRIx32 "\n" " psr: 0x%08" PRIx32 "\n\n", r12, lr, pc, psr); } #if CPU_HAS_EXTENDED_FAULT_REGISTERS puts("FSR/FAR:"); printf(" CFSR: 0x%08" PRIx32 "\n", cfsr); printf(" HFSR: 0x%08" PRIx32 "\n", hfsr); printf(" DFSR: 0x%08" PRIx32 "\n", dfsr); printf(" AFSR: 0x%08" PRIx32 "\n", afsr); if (cfsr & BFARVALID_MASK) { /* BFAR valid flag set */ printf(" BFAR: 0x%08" PRIx32 "\n", bfar); } if (cfsr & MMARVALID_MASK) { /* MMFAR valid flag set */ printf("MMFAR: 0x%08" PRIx32 "\n", mmfar); } #endif puts("Misc"); printf("EXC_RET: 0x%08" PRIx32 "\n", exc_return); if (!corrupted) { puts("Attempting to reconstruct state for debugging..."); printf("In GDB:\n set $pc=0x%" PRIx32 "\n frame 0\n bt\n", pc); int stack_left = _stack_size_left(HARDFAULT_HANDLER_REQUIRED_STACK_SPACE); if(stack_left < 0) { printf("\nISR stack overflowed by at least %d bytes.\n", (-1 * stack_left)); } __asm__ volatile ( "mov r0, %[sp]\n" "ldr r2, [r0, #8]\n" "ldr r3, [r0, #12]\n" "ldr r1, [r0, #16]\n" "mov r12, r1\n" "ldr r1, [r0, #20]\n" "mov lr, r1\n" "mov sp, %[orig_sp]\n" "mov r1, %[extra_stack]\n" #if (__CORTEX_M == 0) "ldm r1!, {r4-r7}\n" "mov r8, r4\n" "mov r9, r5\n" "mov r10, r6\n" "mov r11, r7\n" "ldm r1!, {r4-r7}\n" #else "ldm r1, {r4-r11}\n" #endif "ldr r1, [r0, #4]\n" "ldr r0, [r0, #0]\n" : : [sp] "r" (sp), [orig_sp] "r" (orig_sp), [extra_stack] "r" (r4_to_r11_stack) : "r0","r1","r2","r3","r12" ); } __BKPT(1); core_panic(PANIC_HARD_FAULT, "HARD FAULT HANDLER"); } #else void hard_fault_default(void) { core_panic(PANIC_HARD_FAULT, "HARD FAULT HANDLER"); } #endif /* DEVELHELP */ #if defined(CPU_ARCH_CORTEX_M3) || defined(CPU_ARCH_CORTEX_M4) || \ defined(CPU_ARCH_CORTEX_M4F) || defined(CPU_ARCH_CORTEX_M7) void mem_manage_default(void) { core_panic(PANIC_MEM_MANAGE, "MEM MANAGE HANDLER"); } void bus_fault_default(void) { core_panic(PANIC_BUS_FAULT, "BUS FAULT HANDLER"); } void usage_fault_default(void) { core_panic(PANIC_USAGE_FAULT, "USAGE FAULT HANDLER"); } void debug_mon_default(void) { core_panic(PANIC_DEBUG_MON, "DEBUG MON HANDLER"); } #endif void dummy_handler_default(void) { core_panic(PANIC_DUMMY_HANDLER, "DUMMY HANDLER"); }
lgpl-2.1
cpollard1001/FreeCAD_sf_master
src/Gui/QSint/actionpanel/actionbox.cpp
16
5206
/*************************************************************************** * * * Copyright: https://code.google.com/p/qsint/ * * License: LGPL * * * ***************************************************************************/ #include "actionbox.h" #include <QtCore/QVariant> namespace QSint { const char* ActionBoxStyle = "QSint--ActionBox {" "background-color: white;" "border: 1px solid white;" "border-radius: 3px;" "text-align: left;" "}" "QSint--ActionBox:hover {" "background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #F9FDFF, stop: 1 #EAF7FF);" "border: 1px solid #DAF2FC;" "}" "QSint--ActionBox QSint--ActionLabel[class='header'] {" "text-align: left;" "font: 14px;" "color: #006600;" "background-color: transparent;" "border: none;" "}" "QSint--ActionBox QSint--ActionLabel[class='header']:hover {" "color: #00cc00;" "text-decoration: underline;" "}" "QSint--ActionBox QSint--ActionLabel[class='action'] {" "background-color: transparent;" "border: none;" "color: #0033ff;" "text-align: left;" "font: 11px;" "}" "QSint--ActionBox QSint--ActionLabel[class='action']:!enabled {" "color: #999999;" "}" "QSint--ActionBox QSint--ActionLabel[class='action']:hover {" "color: #0099ff;" "text-decoration: underline;" "}" "QSint--ActionBox QSint--ActionLabel[class='action']:on {" "background-color: #ddeeff;" "color: #006600;" "}" ; ActionBox::ActionBox(QWidget *parent) : QFrame(parent) { init(); } ActionBox::ActionBox(const QString & headerText, QWidget *parent) : QFrame(parent) { init(); headerLabel->setText(headerText); } ActionBox::ActionBox(const QPixmap & icon, const QString & headerText, QWidget *parent) : QFrame(parent) { init(); headerLabel->setText(headerText); setIcon(icon); } void ActionBox::init() { setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Maximum); setStyleSheet(QString(ActionBoxStyle)); QHBoxLayout *mainLayout = new QHBoxLayout(this); QVBoxLayout *iconLayout = new QVBoxLayout(); mainLayout->addLayout(iconLayout); iconLabel = new QLabel(this); iconLayout->addWidget(iconLabel); iconLayout->addStretch(); dataLayout = new QVBoxLayout(); mainLayout->addLayout(dataLayout); headerLabel = createItem(""); headerLabel->setProperty("class", "header"); } void ActionBox::setIcon(const QPixmap & icon) { iconLabel->setPixmap(icon); iconLabel->setFixedSize(icon.size()); } ActionLabel* ActionBox::createItem(QAction * action, QLayout * l) { if (!action) return 0; ActionLabel *act = createItem("", l); act->setDefaultAction(action); return act; } QList<ActionLabel*> ActionBox::createItems(QList<QAction*> actions) { QList<ActionLabel*> list; if (actions.isEmpty()) return list; QLayout *l = createHBoxLayout(); foreach (QAction *action, actions) { ActionLabel *act = createItem(action, l); if (act) list.append(act); } return list; } ActionLabel* ActionBox::createItem(const QString & text, QLayout * l) { ActionLabel *act = new ActionLabel(this); act->setText(text); act->setProperty("class", "action"); act->setStyleSheet(""); if (l) l->addWidget(act); else { QHBoxLayout *hbl = new QHBoxLayout(); hbl->addWidget(act); createSpacer(hbl); dataLayout->addLayout(hbl); } return act; } ActionLabel* ActionBox::createItem(const QPixmap & icon, const QString & text, QLayout * l) { ActionLabel *act = createItem(text, l); act->setIcon(QIcon(icon)); return act; } QSpacerItem* ActionBox::createSpacer(QLayout * l) { QSpacerItem * spacer; if (l) // add horizontal spacer l->addItem(spacer = new QSpacerItem(1,0,QSizePolicy::MinimumExpanding,QSizePolicy::Ignored)); else // add vertical spacer dataLayout->addItem(spacer = new QSpacerItem(0,1,QSizePolicy::Ignored,QSizePolicy::MinimumExpanding)); return spacer; } QLayout* ActionBox::createHBoxLayout() { QHBoxLayout *hbl = new QHBoxLayout(); dataLayout->addLayout(hbl); QHBoxLayout *hbl1 = new QHBoxLayout(); hbl->addLayout(hbl1); createSpacer(hbl); return hbl1; } void ActionBox::addLayout(QLayout * l) { if (l) { dataLayout->addLayout(l); l->setParent(this); } } void ActionBox::addWidget(QWidget * w, QLayout * l) { if (!w) return; w->setParent(this); if (l) l->addWidget(w); else { QHBoxLayout *hbl = new QHBoxLayout(); hbl->addWidget(w); createSpacer(hbl); dataLayout->addLayout(hbl); } } QSize ActionBox::minimumSizeHint() const { return QSize(150,100); } } // namespace
lgpl-2.1
dd00/commandergenius
project/jni/sdl-1.3/src/timer/wince/SDL_systimer.c
18
2532
/* Simple DirectMedia Layer Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "SDL_config.h" #ifdef SDL_TIMER_WINCE #include "../../core/windows/SDL_windows.h" #include "SDL_timer.h" static Uint64 start_date; static Uint64 start_ticks; static Uint64 wce_ticks(void) { return ((Uint64) GetTickCount()); } static Uint64 wce_date(void) { union { FILETIME ftime; Uint64 itime; } ftime; SYSTEMTIME stime; GetSystemTime(&stime); SystemTimeToFileTime(&stime, &ftime.ftime); ftime.itime /= 10000; // Convert 100ns intervals to 1ms intervals // Remove ms portion, which can't be relied on ftime.itime -= (ftime.itime % 1000); return (ftime.itime); } static Sint32 wce_rel_ticks(void) { return ((Sint32) (wce_ticks() - start_ticks)); } static Sint32 wce_rel_date(void) { return ((Sint32) (wce_date() - start_date)); } /* Recard start-time of application for reference */ void SDL_StartTicks(void) { start_date = wce_date(); start_ticks = wce_ticks(); } /* Return time in ms relative to when SDL was started */ Uint32 SDL_GetTicks() { Sint32 offset = wce_rel_date() - wce_rel_ticks(); if ((offset < -1000) || (offset > 1000)) { // fprintf(stderr,"Time desync(%+d), resyncing\n",offset/1000); start_ticks -= offset; } return ((Uint32) wce_rel_ticks()); } Uint64 SDL_GetPerformanceCounter(void) { return SDL_GetTicks(); } Uint64 SDL_GetPerformanceFrequency(void) { return 1000; } /* Give up approx. givem milliseconds to the OS. */ void SDL_Delay(Uint32 ms) { Sleep(ms); } #endif /* SDL_TIMER_WINCE */ /* vi: set ts=4 sw=4 expandtab: */
lgpl-2.1
sawenzel/root
interpreter/llvm/src/lib/Target/TargetSubtargetInfo.cpp
20
1682
//===-- TargetSubtargetInfo.cpp - General Target Information ---------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file describes the general parts of a Subtarget. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; //--------------------------------------------------------------------------- // TargetSubtargetInfo Class // TargetSubtargetInfo::TargetSubtargetInfo( const Triple &TT, StringRef CPU, StringRef FS, ArrayRef<SubtargetFeatureKV> PF, ArrayRef<SubtargetFeatureKV> PD, const SubtargetInfoKV *ProcSched, const MCWriteProcResEntry *WPR, const MCWriteLatencyEntry *WL, const MCReadAdvanceEntry *RA, const InstrStage *IS, const unsigned *OC, const unsigned *FP) : MCSubtargetInfo(TT, CPU, FS, PF, PD, ProcSched, WPR, WL, RA, IS, OC, FP) { } TargetSubtargetInfo::~TargetSubtargetInfo() {} bool TargetSubtargetInfo::enableAtomicExpand() const { return true; } bool TargetSubtargetInfo::enableMachineScheduler() const { return false; } bool TargetSubtargetInfo::enableJoinGlobalCopies() const { return enableMachineScheduler(); } bool TargetSubtargetInfo::enableRALocalReassignment( CodeGenOpt::Level OptLevel) const { return true; } bool TargetSubtargetInfo::enablePostRAScheduler() const { return getSchedModel().PostRAScheduler; } bool TargetSubtargetInfo::useAA() const { return false; }
lgpl-2.1
hrittich/libmesh
contrib/netcdf/netcdf-c-4.6.2/examples/C/simple_nc4_rd.c
20
2709
/*! \file Read a simple file, with some of the features of netCDF-4. This is a very simple example which demonstrates some of the new features of netCDF-4.0. This example reads a simple file created by simple_nc4_wr.c. This is intended to illustrate the use of the netCDF-4 C API. This is part of the netCDF package. Copyright 2006-2011 University Corporation for Atmospheric Research/Unidata. See COPYRIGHT file for conditions of use. Full documentation of the netCDF can be found at http://www.unidata.ucar.edu/software/netcdf/docs. */ #include <stdlib.h> #include <stdio.h> #include <netcdf.h> /* This is the name of the data file we will read. */ #define FILE_NAME "simple_nc4.nc" /* We are reading 2D data, a 6 x 12 grid. */ #define NX 6 #define NY 12 /* Handle errors by printing an error message and exiting with a * non-zero status. */ #define ERRCODE 2 #define ERR(e) {printf("Error: %s\n", nc_strerror(e)); exit(ERRCODE);} int main() { /* There will be netCDF IDs for the file, each group, and each * variable. */ int ncid, varid1, varid2, grp1id, grp2id; unsigned long long data_in[NX][NY]; /* Loop indexes, and error handling. */ int x, y, retval; /* The following struct is written as a compound type. */ struct s1 { int i1; int i2; }; struct s1 compound_data[NX][NY]; /* Open the file. NC_NOWRITE tells netCDF we want read-only access * to the file.*/ if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid))) ERR(retval); /* Get the group ids of our two groups. */ if ((retval = nc_inq_ncid(ncid, "grp1", &grp1id))) ERR(retval); if ((retval = nc_inq_ncid(ncid, "grp2", &grp2id))) ERR(retval); /* Get the varid of the uint64 data variable, based on its name, in * grp1. */ if ((retval = nc_inq_varid(grp1id, "data", &varid1))) ERR(retval); /* Read the data. */ if ((retval = nc_get_var_ulonglong(grp1id, varid1, &data_in[0][0]))) ERR(retval); /* Get the varid of the compound data variable, based on its name, * in grp2. */ if ((retval = nc_inq_varid(grp2id, "data", &varid2))) ERR(retval); /* Read the data. */ if ((retval = nc_get_var(grp2id, varid2, &compound_data[0][0]))) ERR(retval); /* Check the data. */ for (x = 0; x < NX; x++) for (y = 0; y < NY; y++) { if (data_in[x][y] != x * NY + y || compound_data[x][y].i1 != 42 || compound_data[x][y].i2 != -42) return ERRCODE; } /* Close the file, freeing all resources. */ if ((retval = nc_close(ncid))) ERR(retval); printf("*** SUCCESS reading example file %s!\n", FILE_NAME); return 0; }
lgpl-2.1
strk/libgeos
src/noding/SimpleNoder.cpp
24
1929
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2001-2002 Vivid Solutions Inc. * Copyright (C) 2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: noding/SimpleNoder.java rev. 1.7 (JTS-1.9) * **********************************************************************/ #include <geos/noding/SimpleNoder.h> #include <geos/noding/SegmentString.h> #include <geos/noding/SegmentIntersector.h> #include <geos/geom/CoordinateSequence.h> using namespace geos::geom; namespace geos { namespace noding { // geos.noding /*private*/ void SimpleNoder::computeIntersects(SegmentString* e0, SegmentString* e1) { assert(segInt); // must provide a segment intersector! const CoordinateSequence* pts0 = e0->getCoordinates(); const CoordinateSequence* pts1 = e1->getCoordinates(); for (unsigned int i0=0, n0=pts0->getSize()-1; i0<n0; i0++) { for (unsigned int i1=0, n1=pts1->getSize()-1; i1<n1; i1++) { segInt->processIntersections(e0, i0, e1, i1); } } } /*public*/ void SimpleNoder::computeNodes(SegmentString::NonConstVect* inputSegmentStrings) { nodedSegStrings=inputSegmentStrings; for (SegmentString::NonConstVect::const_iterator i0=inputSegmentStrings->begin(), i0End=inputSegmentStrings->end(); i0!=i0End; ++i0) { SegmentString* edge0 = *i0; for (SegmentString::NonConstVect::iterator i1=inputSegmentStrings->begin(), i1End=inputSegmentStrings->end(); i1!=i1End; ++i1) { SegmentString* edge1 = *i1; computeIntersects(edge0, edge1); } } } } // namespace geos.noding } // namespace geos
lgpl-2.1
Alpistinho/FreeCAD
src/Gui/iisTaskPanel/src/iistaskgroup.cpp
25
1577
/*************************************************************************** * * * Copyright: http://www.ii-system.com * * License: LGPL * * * ***************************************************************************/ #include "iistaskgroup.h" #include "iistaskpanelscheme.h" #include "iisiconlabel.h" iisTaskGroup::iisTaskGroup(QWidget *parent, bool hasHeader) : QFrame(parent), myHasHeader(hasHeader) { //setMinimumHeight(32); setScheme(iisTaskPanelScheme::defaultScheme()); QVBoxLayout *vbl = new QVBoxLayout(); vbl->setMargin(4); vbl->setSpacing(0); setLayout(vbl); } iisTaskGroup::~iisTaskGroup() { } void iisTaskGroup::setScheme(iisTaskPanelScheme *scheme) { if (scheme) { myScheme = scheme; myLabelScheme = &(scheme->taskLabelScheme); update(); } } void iisTaskGroup::addIconLabel(iisIconLabel *label, bool addToLayout) { if (!label) return; if (addToLayout) { layout()->addWidget(label); } label->setSchemePointer(&myLabelScheme); } void iisTaskGroup::paintEvent ( QPaintEvent * event ) { QPainter p(this); //p.setOpacity(/*m_opacity+*/0.7); //p.fillRect(rect(), myScheme->groupBackground); p.setBrush(myScheme->groupBackground); p.setPen(myScheme->groupBorder); p.drawRect(rect().adjusted(0,-(int)myHasHeader,-1,-1)); }
lgpl-2.1
yogo1212/RIOT
sys/net/ble/bluetil/bluetil_addr/bluetil_addr.c
26
2596
/* * Copyright (C) 2019 Freie Universität Berlin * * 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 ble_bluetil_addr * @{ * * @file * @brief Implementation of generic BLE address helper functions * * @author Hauke Petersen <hauke.petersen@fu-berlin.de> * * @} */ #include <string.h> #include <stdio.h> #include "fmt.h" #include "assert.h" #include "net/bluetil/addr.h" static int _is_hex_char(char c) { return (((c >= '0') && (c <= '9')) || ((c >= 'A') && (c <= 'F')) || ((c >= 'a') && (c <= 'f'))); } void bluetil_addr_swapped_cp(const uint8_t *src, uint8_t *dst) { dst[0] = src[5]; dst[1] = src[4]; dst[2] = src[3]; dst[3] = src[2]; dst[4] = src[1]; dst[5] = src[0]; } void bluetil_addr_sprint(char *out, const uint8_t *addr) { assert(out); assert(addr); fmt_byte_hex(out, addr[0]); for (unsigned i = 1; i < BLE_ADDR_LEN; i++) { out += 2; *out++ = ':'; fmt_byte_hex(out, addr[i]); } out += 2; *out = '\0'; } void bluetil_addr_print(const uint8_t *addr) { assert(addr); char str[BLUETIL_ADDR_STRLEN]; bluetil_addr_sprint(str, addr); printf("%s", str); } uint8_t *bluetil_addr_from_str(uint8_t *addr, const char *addr_str) { assert(addr); assert(addr_str); /* check for colons */ for (unsigned i = 2; i < (BLUETIL_ADDR_STRLEN - 1); i += 3) { if (addr_str[i] != ':') { return NULL; } } unsigned pos = 0; for (unsigned i = 0; i < (BLUETIL_ADDR_STRLEN - 1); i += 3) { if (!_is_hex_char(addr_str[i]) || !_is_hex_char(addr_str[i + 1])) { return NULL; } addr[pos++] = fmt_hex_byte(addr_str + i); } return addr; } void bluetil_addr_ipv6_l2ll_sprint(char *out, const uint8_t *addr) { assert(out); assert(addr); memcpy(out, "[FE80::", 7); out += 7; out += fmt_byte_hex(out, addr[0]); out += fmt_byte_hex(out, addr[1]); *out++ = ':'; out += fmt_byte_hex(out, addr[2]); memcpy(out, "FF:FE", 5); out += 5; out += fmt_byte_hex(out, addr[3]); *out++ = ':'; out += fmt_byte_hex(out, addr[4]); out += fmt_byte_hex(out, addr[5]); *out++ = ']'; *out = '\0'; } void bluetil_addr_ipv6_l2ll_print(const uint8_t *addr) { assert(addr); char tmp[BLUETIL_IPV6_IID_STRLEN]; bluetil_addr_ipv6_l2ll_sprint(tmp, addr); printf("%s", tmp); }
lgpl-2.1
BytesGalore/RIOT
cpu/saml21/periph/rtt.c
28
3360
/* * Copyright (C) 2015 Kaspar Schleiser <kaspar@schleiser.de> * 2015 FreshTemp, LLC. * * 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 cpu_saml21 * @ingroup drivers_periph_rtt * @{ * * @file rtt.c * @brief Low-level RTT driver implementation * * @author Kaspar Schleiser <kaspar@schleiser.de> * * @} */ #include <stdint.h> #include "periph/rtt.h" #include "board.h" #define ENABLE_DEBUG 0 #include "debug.h" static rtt_cb_t _overflow_cb; static void* _overflow_arg; static rtt_cb_t _cmp0_cb; static void* _cmp0_arg; void rtt_init(void) { DEBUG("%s:%d\n", __func__, __LINE__); rtt_poweron(); /* reset */ RTC->MODE0.CTRLA.bit.SWRST = 1; while(RTC->MODE0.CTRLA.bit.SWRST) {} /* set 32bit counting mode */ RTC->MODE0.CTRLA.bit.MODE = 0; /* set clock source */ OSC32KCTRL->RTCCTRL.reg = OSC32KCTRL_RTCCTRL_RTCSEL_ULP32K; /* enable */ RTC->MODE0.CTRLA.bit.ENABLE = 1; while(RTC->MODE0.SYNCBUSY.bit.ENABLE) {} /* initially clear flag */ RTC->MODE0.INTFLAG.reg |= RTC_MODE1_INTFLAG_CMP(1 << 0); /* enable RTT IRQ */ NVIC_EnableIRQ(RTC_IRQn); DEBUG("%s:%d %u\n", __func__, __LINE__, (unsigned)rtt_get_counter()); } void rtt_set_overflow_cb(rtt_cb_t cb, void *arg) { DEBUG("%s:%d\n", __func__, __LINE__); /* clear overflow cb to avoid race while assigning */ rtt_clear_overflow_cb(); /* set callback variables */ _overflow_cb = cb; _overflow_arg = arg; /* enable overflow interrupt */ RTC->MODE0.INTENSET.bit.OVF = 1; } void rtt_clear_overflow_cb(void) { DEBUG("%s:%d\n", __func__, __LINE__); /* disable overflow interrupt */ RTC->MODE0.INTENCLR.bit.OVF = 1; } uint32_t rtt_get_counter(void) { DEBUG("%s:%d\n", __func__, __LINE__); while (RTC->MODE0.SYNCBUSY.bit.COUNT) {} return RTC->MODE0.COUNT.reg; } void rtt_set_alarm(uint32_t alarm, rtt_cb_t cb, void *arg) { DEBUG("%s:%d alarm=%u\n", __func__, __LINE__, (unsigned)alarm); /* disable interrupt to avoid race */ rtt_clear_alarm(); /* set COM register */ while (RTC->MODE0.SYNCBUSY.bit.COMP0) {} RTC->MODE0.COMP[0].reg = alarm; /* setup callback */ _cmp0_cb = cb; _cmp0_arg = arg; /* enable compare interrupt */ RTC->MODE0.INTENSET.bit.CMP0 = 1; } void rtt_clear_alarm(void) { DEBUG("%s:%d\n", __func__, __LINE__); /* clear compare interrupt */ RTC->MODE0.INTENCLR.bit.CMP0 = 1; } void rtt_poweron(void) { DEBUG("%s:%d\n", __func__, __LINE__); MCLK->APBAMASK.reg |= MCLK_APBAMASK_RTC; } void rtt_poweroff(void) { DEBUG("%s:%d\n", __func__, __LINE__); MCLK->APBAMASK.reg &= ~MCLK_APBAMASK_RTC; } void isr_rtc(void) { if (RTC->MODE0.INTFLAG.bit.OVF) { RTC->MODE0.INTFLAG.reg |= RTC_MODE0_INTFLAG_OVF; if (_overflow_cb) { _overflow_cb(_overflow_arg); } } if (RTC->MODE0.INTFLAG.bit.CMP0) { /* clear flag */ RTC->MODE0.INTFLAG.reg |= RTC_MODE1_INTFLAG_CMP(1 << 0); /* disable interrupt */ RTC->MODE0.INTENCLR.bit.CMP0 = 1; if (_cmp0_cb) { _cmp0_cb(_cmp0_arg); } } cortexm_isr_end(); }
lgpl-2.1
dfunke/root
interpreter/llvm/src/tools/clang/lib/StaticAnalyzer/Checkers/NSAutoreleasePoolChecker.cpp
29
2755
//=- NSAutoreleasePoolChecker.cpp --------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a NSAutoreleasePoolChecker, a small checker that warns // about subpar uses of NSAutoreleasePool. Note that while the check itself // (in its current form) could be written as a flow-insensitive check, in // can be potentially enhanced in the future with flow-sensitive information. // It is also a good example of the CheckerVisitor interface. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclObjC.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" using namespace clang; using namespace ento; namespace { class NSAutoreleasePoolChecker : public Checker<check::PreObjCMessage> { mutable std::unique_ptr<BugType> BT; mutable Selector releaseS; public: void checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const; }; } // end anonymous namespace void NSAutoreleasePoolChecker::checkPreObjCMessage(const ObjCMethodCall &msg, CheckerContext &C) const { if (!msg.isInstanceMessage()) return; const ObjCInterfaceDecl *OD = msg.getReceiverInterface(); if (!OD) return; if (!OD->getIdentifier()->isStr("NSAutoreleasePool")) return; if (releaseS.isNull()) releaseS = GetNullarySelector("release", C.getASTContext()); // Sending 'release' message? if (msg.getSelector() != releaseS) return; if (!BT) BT.reset(new BugType(this, "Use -drain instead of -release", "API Upgrade (Apple)")); ExplodedNode *N = C.addTransition(); if (!N) { assert(0); return; } BugReport *Report = new BugReport(*BT, "Use -drain instead of -release when " "using NSAutoreleasePool and garbage collection", N); Report->addRange(msg.getSourceRange()); C.emitReport(Report); } void ento::registerNSAutoreleasePoolChecker(CheckerManager &mgr) { if (mgr.getLangOpts().getGC() != LangOptions::NonGC) mgr.registerChecker<NSAutoreleasePoolChecker>(); }
lgpl-2.1
0x0all/ROOT
interpreter/llvm/src/tools/clang/test/SemaTemplate/temp_class_spec_neg.cpp
33
1575
// RUN: %clang_cc1 -fsyntax-only -verify %s template<typename T> struct vector; // C++ [temp.class.spec]p6: namespace N { namespace M { template<typename T> struct A; // expected-note{{here}} } } template<typename T> struct N::M::A<T*> { }; // expected-warning{{C++11 extension}} // C++ [temp.class.spec]p9 // bullet 1 template <int I, int J> struct A {}; template <int I> struct A<I+5, I*2> {}; // expected-error{{depends on}} template <int I, int J> struct B {}; template <int I> struct B<I, I> {}; //OK // bullet 2 template <class T, T t> struct C {}; // expected-note{{declared here}} template <class T> struct C<T, 1>; // expected-error{{specializes}} template <class T, T* t> struct C<T*, t>; // okay template< int X, int (*array_ptr)[X] > class A2 {}; // expected-note{{here}} int array[5]; template< int X > class A2<X, &array> { }; // expected-error{{specializes}} template<typename T, int N, template<typename X> class TT> struct Test0; // bullet 3 template<typename T, int N, template<typename X> class TT> struct Test0<T, N, TT>; // expected-error{{does not specialize}} // C++ [temp.class.spec]p10 template<typename T = int, // expected-error{{default template argument}} int N = 17, // expected-error{{default template argument}} template<typename X> class TT = ::vector> // expected-error{{default template argument}} struct Test0<T*, N, TT> { }; template<typename T> struct Test1; template<typename T, typename U> // expected-note{{non-deducible}} struct Test1<T*> { }; // expected-warning{{never be used}}
lgpl-2.1
jaguarcat79/ILC-with-LinuxCNC
src/emc/usr_intf/sockets.c
37
7496
/******************************************************************** * Description: sockets.c * socket utilites * * Copyright(c) 2001, Joris Robijn * (c) 2003, Rene Wagner * Adapted for EMC by: Eric H. Johnson * License: GPL Version 2 * System: Linux * * Copyright (c) 2007 All rights reserved. * * Last change: ********************************************************************/ #include "config.h" #include <unistd.h> #include <stddef.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <sys/types.h> #ifndef WINSOCK2 #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #else #include <winsock2.h> #endif #include <stdarg.h> #include <fcntl.h> #include "rcs_print.hh" #include "sockets.h" /************************************************** * LCDproc client sockets code... * Note: LCDproc error reporting was replaced * with EMC standard debug reporting. **************************************************/ // Length of longest transmission allowed at once... #define MAXMSG 8192 typedef struct sockaddr_in sockaddr_in; static int sockInitSockaddr(sockaddr_in *name, const char *hostname, unsigned short int port) { struct hostent *hostinfo; memset(name, '\0', sizeof (*name)); name->sin_family = AF_INET; name->sin_port = htons(port); hostinfo = gethostbyname(hostname); if (hostinfo == NULL) { rcs_print_error("sock_init_sockaddr: Unknown host\n"); return -1; } name->sin_addr = *(struct in_addr *) hostinfo->h_addr; return 0; } // Client functions... int sockConnect(char *host, unsigned short int port) { struct sockaddr_in servername; int sock; int err = 0; rcs_print_error("sock_connect: Creating socket\n"); sock = socket(PF_INET, SOCK_STREAM, 0); #ifdef WINSOCK2 if (sock == INVALID_SOCKET) { #else if (sock < 0) { #endif rcs_print_error("sock_connect: Error creating socket\n"); return sock; } rcs_print_error("sock_connect: Created socket\n"); if (sockInitSockaddr(&servername, host, port) < 0) return -1; err = connect(sock, (struct sockaddr *) &servername, sizeof (servername)); #ifdef WINSOCK2 if (err == INVALID_SOCKET) { #else if (err < 0) { #endif rcs_print_error("sock_connect: connect failed\n"); shutdown(sock, SHUT_RDWR); return -1; } #ifndef WINSOCK2 fcntl(sock, F_SETFL, O_NONBLOCK); #else { unsigned long tmp = 1; if (ioctlsocket(sock, FIONBIO, &tmp) == SOCKET_ERROR) rcs_print_error("sock_connect: Error setting socket to non-blocking\n"); } #endif return sock; } int sockClose(int fd) { int err; err = shutdown(fd, SHUT_RDWR); if (!err) close (fd); return err; } /** send printf-like formatted output */ int sockPrintf(int fd, const char *format, .../*args*/ ) { char buf[MAXMSG]; va_list ap; int size = 0; va_start(ap, format); size = vsnprintf(buf, sizeof(buf), format, ap); va_end(ap); if (size < 0) { rcs_print_error("sock_printf: vsnprintf failed\n"); return -1; } if (size > sizeof(buf)) { rcs_print_error("sock_printf: vsnprintf truncated message\n"); } return sockSendString(fd, buf); } // Send/receive lines of text int sockSendString(int fd, const char *string) { return sockSend(fd, string, strlen(string)); } // Recv gives only one line per call... int sockRecvString(int fd, char *dest, size_t maxlen) { char *ptr = dest; int recvBytes = 0; if (!dest) return -1; if (maxlen <= 0) return 0; while (1) { int err = recv(fd, ptr, 1, 0); if (err == -1) { if (errno == EAGAIN) { if (recvBytes) { // We've begun to read a string, but no bytes are // available. Loop. continue; } return 0; } else { rcs_print_error("sock_recv_string: socket read error"); return err; } } else if (err == 0) { return recvBytes; } recvBytes++; // stop at max. bytes allowed, at NUL or at LF if (recvBytes == maxlen || *ptr == '\0' || *ptr == '\n') { *ptr = '\0'; break; } ptr++; } // Don't return an empty string if (recvBytes == 1 && dest[0] == '\0') return 0; if (recvBytes < maxlen - 1) dest[recvBytes] = '\0'; return recvBytes; } // Send/receive raw data int sockSend(int fd, const void *src, size_t size) { int offset = 0; if (!src) return -1; while (offset != size) { // write isn't guaranteed to send the entire string at once, // so we have to sent it in a loop like this #ifndef WINSOCK2 int sent = write(fd, ((const char *) src) + offset, size - offset); #else int sent = send(fd, ((const char *) src) + offset, size - offset, 0); #endif if (sent == -1) { if (errno != EAGAIN) { rcs_print_error("sock_send: socket write error\n"); // shutdown(fd, SHUT_RDWR); return sent; } continue; } else if (sent == 0) return sent + offset; offset += sent; } // while return offset; } int sockRecv(int fd, void *dest, size_t maxlen) { int err; if (!dest) return -1; if (maxlen <= 0) return 0; #ifndef WINSOCK2 err = read (fd, dest, maxlen); #else err = recv(fd, dest, maxlen, 0); #endif if (err < 0) { // rcs_print_error("sock_recv: socket read error\n"); // shutdown(fd, SHUT_RDWR); return err; } return err; } /*****************************************************************************/ char* sockGetError(void) { #ifndef WINSOCK2 return strerror(errno); #else static char retString[256]; long err; char* tmp; err = WSAGetLastError(); sprintf(retString, "Error code %ld: ", err); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, 0, /* Default language */ (LPTSTR) &tmp, 0, NULL); /* append the message text after the error code and ensure a terminating character ends the string */ strncpy(retString + strlen(retString), tmp, sizeof(retString) - strlen(retString) - 1); retString[sizeof(retString) - 1] = '\0'; return retString; #endif } /** prints error to logfile and sends it to the client. * @param fd socket * @param message the message to send (without the "huh? ") */ int sockSendError(int fd, const char* message) { // simple: performance penalty isn't worth more work... return sockPrintfError(fd, "%s", message); } /** prints printf-like formatted output to logfile and sends it to the * client. * @note don't add a the "huh? " to the message. This is done by this * method * @param fd socket * @param format a printf format */ int sockPrintfError(int fd, const char *format, .../*args*/ ) { static const char huh[] = "huh? "; char buf[MAXMSG]; va_list ap; int size = 0; strncpy(buf, huh, sizeof(huh)); // note: sizeof(huh) < MAXMSG va_start(ap, format); size = vsnprintf(buf + (sizeof(huh)-1), sizeof(buf) - (sizeof(huh)-1), format, ap); buf[sizeof(buf)-1] = '\0'; va_end(ap); if (size < 0) { rcs_print_error("sock_printf_error: vsnprintf failed\n"); return -1; } if (size >= sizeof(buf) - (sizeof(huh)-1)) { rcs_print_error("sock_printf_error: vsnprintf truncated message\n"); } return sockSendString(fd, buf); }
lgpl-2.1
krieger-od/gst-plugins-good
gst/rtsp/gstrtspext.c
43
7684
/* GStreamer * Copyright (C) <2006> Wim Taymans <wim@fluendo.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library 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. */ /* * Unless otherwise indicated, Source Code is licensed under MIT license. * See further explanation attached in License Statement (distributed in the file * LICENSE). * * 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 "gstrtspext.h" GST_DEBUG_CATEGORY_STATIC (rtspext_debug); #define GST_CAT_DEFAULT (rtspext_debug) static GList *extensions; static gboolean gst_rtsp_ext_list_filter (GstPluginFeature * feature, gpointer user_data) { GstElementFactory *factory; guint rank; /* we only care about element factories */ if (!GST_IS_ELEMENT_FACTORY (feature)) return FALSE; factory = GST_ELEMENT_FACTORY (feature); if (!gst_element_factory_has_interface (factory, "GstRTSPExtension")) return FALSE; /* only select elements with autoplugging rank */ rank = gst_plugin_feature_get_rank (feature); if (rank < GST_RANK_MARGINAL) return FALSE; return TRUE; } void gst_rtsp_ext_list_init (void) { GST_DEBUG_CATEGORY_INIT (rtspext_debug, "rtspext", 0, "RTSP extension"); /* get a list of all extensions */ extensions = gst_registry_feature_filter (gst_registry_get (), (GstPluginFeatureFilter) gst_rtsp_ext_list_filter, FALSE, NULL); } GstRTSPExtensionList * gst_rtsp_ext_list_get (void) { GstRTSPExtensionList *result; GList *walk; result = g_new0 (GstRTSPExtensionList, 1); for (walk = extensions; walk; walk = g_list_next (walk)) { GstElementFactory *factory = GST_ELEMENT_FACTORY (walk->data); GstElement *element; element = gst_element_factory_create (factory, NULL); if (!element) { GST_ERROR ("could not create extension instance"); continue; } GST_DEBUG ("added extension interface for '%s'", GST_ELEMENT_NAME (element)); result->extensions = g_list_prepend (result->extensions, element); } return result; } void gst_rtsp_ext_list_free (GstRTSPExtensionList * ext) { GList *walk; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; gst_object_unref (GST_OBJECT_CAST (elem)); } g_list_free (ext->extensions); g_free (ext); } gboolean gst_rtsp_ext_list_detect_server (GstRTSPExtensionList * ext, GstRTSPMessage * resp) { GList *walk; gboolean res = TRUE; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_detect_server (elem, resp); } return res; } GstRTSPResult gst_rtsp_ext_list_before_send (GstRTSPExtensionList * ext, GstRTSPMessage * req) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_before_send (elem, req); } return res; } GstRTSPResult gst_rtsp_ext_list_after_send (GstRTSPExtensionList * ext, GstRTSPMessage * req, GstRTSPMessage * resp) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_after_send (elem, req, resp); } return res; } GstRTSPResult gst_rtsp_ext_list_parse_sdp (GstRTSPExtensionList * ext, GstSDPMessage * sdp, GstStructure * s) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_parse_sdp (elem, sdp, s); } return res; } GstRTSPResult gst_rtsp_ext_list_setup_media (GstRTSPExtensionList * ext, GstSDPMedia * media) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_setup_media (elem, media); } return res; } gboolean gst_rtsp_ext_list_configure_stream (GstRTSPExtensionList * ext, GstCaps * caps) { GList *walk; gboolean res = TRUE; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_configure_stream (elem, caps); if (!res) break; } return res; } GstRTSPResult gst_rtsp_ext_list_get_transports (GstRTSPExtensionList * ext, GstRTSPLowerTrans protocols, gchar ** transport) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_get_transports (elem, protocols, transport); } return res; } GstRTSPResult gst_rtsp_ext_list_stream_select (GstRTSPExtensionList * ext, GstRTSPUrl * url) { GList *walk; GstRTSPResult res = GST_RTSP_OK; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_stream_select (elem, url); } return res; } void gst_rtsp_ext_list_connect (GstRTSPExtensionList * ext, const gchar * detailed_signal, GCallback c_handler, gpointer data) { GList *walk; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; g_signal_connect (elem, detailed_signal, c_handler, data); } } GstRTSPResult gst_rtsp_ext_list_receive_request (GstRTSPExtensionList * ext, GstRTSPMessage * req) { GList *walk; GstRTSPResult res = GST_RTSP_ENOTIMPL; for (walk = ext->extensions; walk; walk = g_list_next (walk)) { GstRTSPExtension *elem = (GstRTSPExtension *) walk->data; res = gst_rtsp_extension_receive_request (elem, req); if (res != GST_RTSP_ENOTIMPL) break; } return res; }
lgpl-2.1
01org/android-bluez-glib
glib/tests/utf8-validate.c
58
10035
/* GLIB - Library of useful routines for C programming * Copyright (C) 2001 Matthias Clasen <matthiasc@poet.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include "glib.h" #define UNICODE_VALID(Char) \ ((Char) < 0x110000 && \ (((Char) & 0xFFFFF800) != 0xD800) && \ ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \ ((Char) & 0xFFFE) != 0xFFFE) typedef struct { const gchar *text; gint max_len; gint offset; gboolean valid; } Test; Test test[] = { /* some tests to check max_len handling */ /* length 1 */ { "abcde", -1, 5, TRUE }, { "abcde", 3, 3, TRUE }, { "abcde", 5, 5, TRUE }, { "abcde", 7, 5, FALSE }, /* length 2 */ { "\xc2\xa9\xc2\xa9\xc2\xa9", -1, 6, TRUE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 1, 0, FALSE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 2, 2, TRUE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 3, 2, FALSE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 4, 4, TRUE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 5, 4, FALSE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 6, 6, TRUE }, { "\xc2\xa9\xc2\xa9\xc2\xa9", 7, 6, FALSE }, /* length 3 */ { "\xe2\x89\xa0\xe2\x89\xa0", -1, 6, TRUE }, { "\xe2\x89\xa0\xe2\x89\xa0", 1, 0, FALSE }, { "\xe2\x89\xa0\xe2\x89\xa0", 2, 0, FALSE }, { "\xe2\x89\xa0\xe2\x89\xa0", 3, 3, TRUE }, { "\xe2\x89\xa0\xe2\x89\xa0", 4, 3, FALSE }, { "\xe2\x89\xa0\xe2\x89\xa0", 5, 3, FALSE }, { "\xe2\x89\xa0\xe2\x89\xa0", 6, 6, TRUE }, { "\xe2\x89\xa0\xe2\x89\xa0", 7, 6, FALSE }, /* examples from http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt */ /* greek 'kosme' */ { "\xce\xba\xe1\xbd\xb9\xcf\x83\xce\xbc\xce\xb5", -1, 11, TRUE }, /* first sequence of each length */ { "\x00", -1, 0, TRUE }, { "\xc2\x80", -1, 2, TRUE }, { "\xe0\xa0\x80", -1, 3, TRUE }, { "\xf0\x90\x80\x80", -1, 4, TRUE }, { "\xf8\x88\x80\x80\x80", -1, 0, FALSE }, { "\xfc\x84\x80\x80\x80\x80", -1, 0, FALSE }, /* last sequence of each length */ { "\x7f", -1, 1, TRUE }, { "\xdf\xbf", -1, 2, TRUE }, { "\xef\xbf\xbf", -1, 0, FALSE }, { "\xf7\xbf\xbf\xbf", -1, 0, FALSE }, { "\xfb\xbf\xbf\xbf\xbf", -1, 0, FALSE }, { "\xfd\xbf\xbf\xbf\xbf\xbf", -1, 0, FALSE }, /* other boundary conditions */ { "\xed\x9f\xbf", -1, 3, TRUE }, { "\xee\x80\x80", -1, 3, TRUE }, { "\xef\xbf\xbd", -1, 3, TRUE }, { "\xf4\x8f\xbf\xbf", -1, 0, FALSE }, { "\xf4\x90\x80\x80", -1, 0, FALSE }, /* malformed sequences */ /* continuation bytes */ { "\x80", -1, 0, FALSE }, { "\xbf", -1, 0, FALSE }, { "\x80\xbf", -1, 0, FALSE }, { "\x80\xbf\x80", -1, 0, FALSE }, { "\x80\xbf\x80\xbf", -1, 0, FALSE }, { "\x80\xbf\x80\xbf\x80", -1, 0, FALSE }, { "\x80\xbf\x80\xbf\x80\xbf", -1, 0, FALSE }, { "\x80\xbf\x80\xbf\x80\xbf\x80", -1, 0, FALSE }, /* all possible continuation byte */ { "\x80", -1, 0, FALSE }, { "\x81", -1, 0, FALSE }, { "\x82", -1, 0, FALSE }, { "\x83", -1, 0, FALSE }, { "\x84", -1, 0, FALSE }, { "\x85", -1, 0, FALSE }, { "\x86", -1, 0, FALSE }, { "\x87", -1, 0, FALSE }, { "\x88", -1, 0, FALSE }, { "\x89", -1, 0, FALSE }, { "\x8a", -1, 0, FALSE }, { "\x8b", -1, 0, FALSE }, { "\x8c", -1, 0, FALSE }, { "\x8d", -1, 0, FALSE }, { "\x8e", -1, 0, FALSE }, { "\x8f", -1, 0, FALSE }, { "\x90", -1, 0, FALSE }, { "\x91", -1, 0, FALSE }, { "\x92", -1, 0, FALSE }, { "\x93", -1, 0, FALSE }, { "\x94", -1, 0, FALSE }, { "\x95", -1, 0, FALSE }, { "\x96", -1, 0, FALSE }, { "\x97", -1, 0, FALSE }, { "\x98", -1, 0, FALSE }, { "\x99", -1, 0, FALSE }, { "\x9a", -1, 0, FALSE }, { "\x9b", -1, 0, FALSE }, { "\x9c", -1, 0, FALSE }, { "\x9d", -1, 0, FALSE }, { "\x9e", -1, 0, FALSE }, { "\x9f", -1, 0, FALSE }, { "\xa0", -1, 0, FALSE }, { "\xa1", -1, 0, FALSE }, { "\xa2", -1, 0, FALSE }, { "\xa3", -1, 0, FALSE }, { "\xa4", -1, 0, FALSE }, { "\xa5", -1, 0, FALSE }, { "\xa6", -1, 0, FALSE }, { "\xa7", -1, 0, FALSE }, { "\xa8", -1, 0, FALSE }, { "\xa9", -1, 0, FALSE }, { "\xaa", -1, 0, FALSE }, { "\xab", -1, 0, FALSE }, { "\xac", -1, 0, FALSE }, { "\xad", -1, 0, FALSE }, { "\xae", -1, 0, FALSE }, { "\xaf", -1, 0, FALSE }, { "\xb0", -1, 0, FALSE }, { "\xb1", -1, 0, FALSE }, { "\xb2", -1, 0, FALSE }, { "\xb3", -1, 0, FALSE }, { "\xb4", -1, 0, FALSE }, { "\xb5", -1, 0, FALSE }, { "\xb6", -1, 0, FALSE }, { "\xb7", -1, 0, FALSE }, { "\xb8", -1, 0, FALSE }, { "\xb9", -1, 0, FALSE }, { "\xba", -1, 0, FALSE }, { "\xbb", -1, 0, FALSE }, { "\xbc", -1, 0, FALSE }, { "\xbd", -1, 0, FALSE }, { "\xbe", -1, 0, FALSE }, { "\xbf", -1, 0, FALSE }, /* lone start characters */ { "\xc0\x20", -1, 0, FALSE }, { "\xc1\x20", -1, 0, FALSE }, { "\xc2\x20", -1, 0, FALSE }, { "\xc3\x20", -1, 0, FALSE }, { "\xc4\x20", -1, 0, FALSE }, { "\xc5\x20", -1, 0, FALSE }, { "\xc6\x20", -1, 0, FALSE }, { "\xc7\x20", -1, 0, FALSE }, { "\xc8\x20", -1, 0, FALSE }, { "\xc9\x20", -1, 0, FALSE }, { "\xca\x20", -1, 0, FALSE }, { "\xcb\x20", -1, 0, FALSE }, { "\xcc\x20", -1, 0, FALSE }, { "\xcd\x20", -1, 0, FALSE }, { "\xce\x20", -1, 0, FALSE }, { "\xcf\x20", -1, 0, FALSE }, { "\xd0\x20", -1, 0, FALSE }, { "\xd1\x20", -1, 0, FALSE }, { "\xd2\x20", -1, 0, FALSE }, { "\xd3\x20", -1, 0, FALSE }, { "\xd4\x20", -1, 0, FALSE }, { "\xd5\x20", -1, 0, FALSE }, { "\xd6\x20", -1, 0, FALSE }, { "\xd7\x20", -1, 0, FALSE }, { "\xd8\x20", -1, 0, FALSE }, { "\xd9\x20", -1, 0, FALSE }, { "\xda\x20", -1, 0, FALSE }, { "\xdb\x20", -1, 0, FALSE }, { "\xdc\x20", -1, 0, FALSE }, { "\xdd\x20", -1, 0, FALSE }, { "\xde\x20", -1, 0, FALSE }, { "\xdf\x20", -1, 0, FALSE }, { "\xe0\x20", -1, 0, FALSE }, { "\xe1\x20", -1, 0, FALSE }, { "\xe2\x20", -1, 0, FALSE }, { "\xe3\x20", -1, 0, FALSE }, { "\xe4\x20", -1, 0, FALSE }, { "\xe5\x20", -1, 0, FALSE }, { "\xe6\x20", -1, 0, FALSE }, { "\xe7\x20", -1, 0, FALSE }, { "\xe8\x20", -1, 0, FALSE }, { "\xe9\x20", -1, 0, FALSE }, { "\xea\x20", -1, 0, FALSE }, { "\xeb\x20", -1, 0, FALSE }, { "\xec\x20", -1, 0, FALSE }, { "\xed\x20", -1, 0, FALSE }, { "\xee\x20", -1, 0, FALSE }, { "\xef\x20", -1, 0, FALSE }, { "\xf0\x20", -1, 0, FALSE }, { "\xf1\x20", -1, 0, FALSE }, { "\xf2\x20", -1, 0, FALSE }, { "\xf3\x20", -1, 0, FALSE }, { "\xf4\x20", -1, 0, FALSE }, { "\xf5\x20", -1, 0, FALSE }, { "\xf6\x20", -1, 0, FALSE }, { "\xf7\x20", -1, 0, FALSE }, { "\xf8\x20", -1, 0, FALSE }, { "\xf9\x20", -1, 0, FALSE }, { "\xfa\x20", -1, 0, FALSE }, { "\xfb\x20", -1, 0, FALSE }, { "\xfc\x20", -1, 0, FALSE }, { "\xfd\x20", -1, 0, FALSE }, /* missing continuation bytes */ { "\x20\xc0", -1, 1, FALSE }, { "\x20\xe0\x80", -1, 1, FALSE }, { "\x20\xf0\x80\x80", -1, 1, FALSE }, { "\x20\xf8\x80\x80\x80", -1, 1, FALSE }, { "\x20\xfc\x80\x80\x80\x80", -1, 1, FALSE }, { "\x20\xdf", -1, 1, FALSE }, { "\x20\xef\xbf", -1, 1, FALSE }, { "\x20\xf7\xbf\xbf", -1, 1, FALSE }, { "\x20\xfb\xbf\xbf\xbf", -1, 1, FALSE }, { "\x20\xfd\xbf\xbf\xbf\xbf", -1, 1, FALSE }, /* impossible bytes */ { "\x20\xfe\x20", -1, 1, FALSE }, { "\x20\xff\x20", -1, 1, FALSE }, /* overlong sequences */ { "\x20\xc0\xaf\x20", -1, 1, FALSE }, { "\x20\xe0\x80\xaf\x20", -1, 1, FALSE }, { "\x20\xf0\x80\x80\xaf\x20", -1, 1, FALSE }, { "\x20\xf8\x80\x80\x80\xaf\x20", -1, 1, FALSE }, { "\x20\xfc\x80\x80\x80\x80\xaf\x20", -1, 1, FALSE }, { "\x20\xc1\xbf\x20", -1, 1, FALSE }, { "\x20\xe0\x9f\xbf\x20", -1, 1, FALSE }, { "\x20\xf0\x8f\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xf8\x87\xbf\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xfc\x83\xbf\xbf\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xc0\x80\x20", -1, 1, FALSE }, { "\x20\xe0\x80\x80\x20", -1, 1, FALSE }, { "\x20\xf0\x80\x80\x80\x20", -1, 1, FALSE }, { "\x20\xf8\x80\x80\x80\x80\x20", -1, 1, FALSE }, { "\x20\xfc\x80\x80\x80\x80\x80\x20", -1, 1, FALSE }, /* illegal code positions */ { "\x20\xed\xa0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xad\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xae\x80\x20", -1, 1, FALSE }, { "\x20\xed\xaf\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xb0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xbe\x80\x20", -1, 1, FALSE }, { "\x20\xed\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xa0\x80\xed\xb0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xa0\x80\xed\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xad\xbf\xed\xb0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xad\xbf\xed\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xae\x80\xed\xb0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xae\x80\xed\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xed\xaf\xbf\xed\xb0\x80\x20", -1, 1, FALSE }, { "\x20\xed\xaf\xbf\xed\xbf\xbf\x20", -1, 1, FALSE }, { "\x20\xef\xbf\xbe\x20", -1, 1, FALSE }, { "\x20\xef\xbf\xbf\x20", -1, 1, FALSE }, { NULL, } }; static void do_test (gconstpointer d) { const Test *test = d; const gchar *end; gboolean result; result = g_utf8_validate (test->text, test->max_len, &end); g_assert (result == test->valid); g_assert (end - test->text == test->offset); } int main (int argc, char *argv[]) { gint i; gchar *path; g_test_init (&argc, &argv, NULL); for (i = 0; test[i].text; i++) { path = g_strdup_printf ("/utf8/validate/%d", i); g_test_add_data_func (path, &test[i], do_test); g_free (path); } return g_test_run (); }
lgpl-2.1
KTXSoftware/libgit2
src/win32/pthread.c
65
6020
/* * Copyright (C) the libgit2 contributors. All rights reserved. * * This file is part of libgit2, distributed under the GNU GPL v2 with * a Linking Exception. For full terms see the included COPYING file. */ #include "pthread.h" #include "../global.h" #define CLEAN_THREAD_EXIT 0x6F012842 /* The thread procedure stub used to invoke the caller's procedure * and capture the return value for later collection. Windows will * only hold a DWORD, but we need to be able to store an entire * void pointer. This requires the indirection. */ static DWORD WINAPI git_win32__threadproc(LPVOID lpParameter) { git_win32_thread *thread = lpParameter; thread->result = thread->proc(thread->param); git__free_tls_data(); return CLEAN_THREAD_EXIT; } int git_win32__thread_create( git_win32_thread *GIT_RESTRICT thread, const pthread_attr_t *GIT_RESTRICT attr, void *(*start_routine)(void*), void *GIT_RESTRICT arg) { GIT_UNUSED(attr); thread->result = NULL; thread->param = arg; thread->proc = start_routine; thread->thread = CreateThread( NULL, 0, git_win32__threadproc, thread, 0, NULL); return thread->thread ? 0 : -1; } int git_win32__thread_join( git_win32_thread *thread, void **value_ptr) { DWORD exit; if (WaitForSingleObject(thread->thread, INFINITE) != WAIT_OBJECT_0) return -1; if (!GetExitCodeThread(thread->thread, &exit)) { CloseHandle(thread->thread); return -1; } /* Check for the thread having exited uncleanly. If exit was unclean, * then we don't have a return value to give back to the caller. */ if (exit != CLEAN_THREAD_EXIT) { assert(false); thread->result = NULL; } if (value_ptr) *value_ptr = thread->result; CloseHandle(thread->thread); return 0; } int pthread_mutex_init( pthread_mutex_t *GIT_RESTRICT mutex, const pthread_mutexattr_t *GIT_RESTRICT mutexattr) { GIT_UNUSED(mutexattr); InitializeCriticalSection(mutex); return 0; } int pthread_mutex_destroy(pthread_mutex_t *mutex) { DeleteCriticalSection(mutex); return 0; } int pthread_mutex_lock(pthread_mutex_t *mutex) { EnterCriticalSection(mutex); return 0; } int pthread_mutex_unlock(pthread_mutex_t *mutex) { LeaveCriticalSection(mutex); return 0; } int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr) { /* We don't support non-default attributes. */ if (attr) return EINVAL; /* This is an auto-reset event. */ *cond = CreateEventW(NULL, FALSE, FALSE, NULL); assert(*cond); /* If we can't create the event, claim that the reason was out-of-memory. * The actual reason can be fetched with GetLastError(). */ return *cond ? 0 : ENOMEM; } int pthread_cond_destroy(pthread_cond_t *cond) { BOOL closed; if (!cond) return EINVAL; closed = CloseHandle(*cond); assert(closed); GIT_UNUSED(closed); *cond = NULL; return 0; } int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) { int error; DWORD wait_result; if (!cond || !mutex) return EINVAL; /* The caller must be holding the mutex. */ error = pthread_mutex_unlock(mutex); if (error) return error; wait_result = WaitForSingleObject(*cond, INFINITE); assert(WAIT_OBJECT_0 == wait_result); GIT_UNUSED(wait_result); return pthread_mutex_lock(mutex); } int pthread_cond_signal(pthread_cond_t *cond) { BOOL signaled; if (!cond) return EINVAL; signaled = SetEvent(*cond); assert(signaled); GIT_UNUSED(signaled); return 0; } /* pthread_cond_broadcast is not implemented because doing so with just * Win32 events is quite complicated, and no caller in libgit2 uses it * yet. */ int pthread_num_processors_np(void) { DWORD_PTR p, s; int n = 0; if (GetProcessAffinityMask(GetCurrentProcess(), &p, &s)) for (; p; p >>= 1) n += p&1; return n ? n : 1; } typedef void (WINAPI *win32_srwlock_fn)(GIT_SRWLOCK *); static win32_srwlock_fn win32_srwlock_initialize; static win32_srwlock_fn win32_srwlock_acquire_shared; static win32_srwlock_fn win32_srwlock_release_shared; static win32_srwlock_fn win32_srwlock_acquire_exclusive; static win32_srwlock_fn win32_srwlock_release_exclusive; int pthread_rwlock_init( pthread_rwlock_t *GIT_RESTRICT lock, const pthread_rwlockattr_t *GIT_RESTRICT attr) { GIT_UNUSED(attr); if (win32_srwlock_initialize) win32_srwlock_initialize(&lock->native.srwl); else InitializeCriticalSection(&lock->native.csec); return 0; } int pthread_rwlock_rdlock(pthread_rwlock_t *lock) { if (win32_srwlock_acquire_shared) win32_srwlock_acquire_shared(&lock->native.srwl); else EnterCriticalSection(&lock->native.csec); return 0; } int pthread_rwlock_rdunlock(pthread_rwlock_t *lock) { if (win32_srwlock_release_shared) win32_srwlock_release_shared(&lock->native.srwl); else LeaveCriticalSection(&lock->native.csec); return 0; } int pthread_rwlock_wrlock(pthread_rwlock_t *lock) { if (win32_srwlock_acquire_exclusive) win32_srwlock_acquire_exclusive(&lock->native.srwl); else EnterCriticalSection(&lock->native.csec); return 0; } int pthread_rwlock_wrunlock(pthread_rwlock_t *lock) { if (win32_srwlock_release_exclusive) win32_srwlock_release_exclusive(&lock->native.srwl); else LeaveCriticalSection(&lock->native.csec); return 0; } int pthread_rwlock_destroy(pthread_rwlock_t *lock) { if (!win32_srwlock_initialize) DeleteCriticalSection(&lock->native.csec); git__memzero(lock, sizeof(*lock)); return 0; } int win32_pthread_initialize(void) { HMODULE hModule = GetModuleHandleW(L"kernel32"); if (hModule) { win32_srwlock_initialize = (win32_srwlock_fn) GetProcAddress(hModule, "InitializeSRWLock"); win32_srwlock_acquire_shared = (win32_srwlock_fn) GetProcAddress(hModule, "AcquireSRWLockShared"); win32_srwlock_release_shared = (win32_srwlock_fn) GetProcAddress(hModule, "ReleaseSRWLockShared"); win32_srwlock_acquire_exclusive = (win32_srwlock_fn) GetProcAddress(hModule, "AcquireSRWLockExclusive"); win32_srwlock_release_exclusive = (win32_srwlock_fn) GetProcAddress(hModule, "ReleaseSRWLockExclusive"); } return 0; }
lgpl-2.1
CodeDJ/qt5-hidpi
qt/qtbase/src/widgets/doc/snippets/code/src_gui_dialogs_qfontdialog.cpp
107
3003
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Digia Plc and its Subsidiary(-ies) 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //! [0] bool ok; QFont font = QFontDialog::getFont( &ok, QFont("Helvetica [Cronyx]", 10), this); if (ok) { // the user clicked OK and font is set to the font the user selected } else { // the user canceled the dialog; font is set to the initial // value, in this case Helvetica [Cronyx], 10 } //! [0] //! [1] myWidget.setFont(QFontDialog::getFont(0, myWidget.font())); //! [1] //! [2] bool ok; QFont font = QFontDialog::getFont(&ok, QFont("Times", 12), this); if (ok) { // font is set to the font the user selected } else { // the user canceled the dialog; font is set to the initial // value, in this case Times, 12. } //! [2] //! [3] myWidget.setFont(QFontDialog::getFont(0, myWidget.font())); //! [3] //! [4] bool ok; QFont font = QFontDialog::getFont(&ok, this); if (ok) { // font is set to the font the user selected } else { // the user canceled the dialog; font is set to the default // application font, QApplication::font() } //! [4]
lgpl-2.1
tommyli2014/Arduino
hardware/arduino/sam/cores/arduino/main.cpp
121
1472
/* main.cpp - Main loop for Arduino sketches Copyright (c) 2005-2013 Arduino Team. All right reserved. 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 ARDUINO_MAIN #include "Arduino.h" /* * Cortex-M3 Systick IT handler */ /* extern void SysTick_Handler( void ) { // Increment tick count each ms TimeTick_Increment() ; } */ // Weak empty variant initialization function. // May be redefined by variant files. void initVariant() __attribute__((weak)); void initVariant() { } /* * \brief Main entry point of Arduino application */ int main( void ) { // Initialize watchdog watchdogSetup(); init(); initVariant(); delay(1); #if defined(USBCON) USBDevice.attach(); #endif setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } return 0; }
lgpl-2.1
flutterwireless/ArduinoCodebase
libraries/Bridge/src/Process.cpp
184
3213
/* Copyright (c) 2013 Arduino LLC. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <Process.h> Process::~Process() { close(); } size_t Process::write(uint8_t c) { uint8_t cmd[] = {'I', handle, c}; bridge.transfer(cmd, 3); return 1; } void Process::flush() { } int Process::available() { // Look if there is new data available doBuffer(); return buffered; } int Process::read() { doBuffer(); if (buffered == 0) return -1; // no chars available else { buffered--; return buffer[readPos++]; } } int Process::peek() { doBuffer(); if (buffered == 0) return -1; // no chars available else return buffer[readPos]; } void Process::doBuffer() { // If there are already char in buffer exit if (buffered > 0) return; // Try to buffer up to 32 characters readPos = 0; uint8_t cmd[] = {'O', handle, sizeof(buffer)}; buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); } void Process::begin(const String &command) { close(); cmdline = new String(command); } void Process::addParameter(const String &param) { *cmdline += "\xFE"; *cmdline += param; } void Process::runAsynchronously() { uint8_t cmd[] = {'R'}; uint8_t res[2]; bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); handle = res[1]; delete cmdline; cmdline = NULL; if (res[0] == 0) // res[0] contains error code started = true; } boolean Process::running() { uint8_t cmd[] = {'r', handle}; uint8_t res[1]; bridge.transfer(cmd, 2, res, 1); return (res[0] == 1); } unsigned int Process::exitValue() { uint8_t cmd[] = {'W', handle}; uint8_t res[2]; bridge.transfer(cmd, 2, res, 2); return (res[0] << 8) + res[1]; } unsigned int Process::run() { runAsynchronously(); while (running()) delay(100); return exitValue(); } void Process::close() { if (started) { uint8_t cmd[] = {'w', handle}; bridge.transfer(cmd, 2); } started = false; } unsigned int Process::runShellCommand(const String &command) { runShellCommandAsynchronously(command); while (running()) delay(100); return exitValue(); } void Process::runShellCommandAsynchronously(const String &command) { begin("/bin/ash"); addParameter("-c"); addParameter(command); runAsynchronously(); } // This method is currently unused //static unsigned int __commandOutputAvailable(uint8_t handle) { // uint8_t cmd[] = {'o', handle}; // uint8_t res[1]; // Bridge.transfer(cmd, 2, res, 1); // return res[0]; //}
lgpl-2.1
SmartArduino/Arduino-1
hardware/arduino/sam/system/CMSIS/CMSIS/DSP_Lib/Source/FilteringFunctions/arm_fir_decimate_f32.c
225
12016
/* ---------------------------------------------------------------------- * Copyright (C) 2010 ARM Limited. All rights reserved. * * $Date: 15. July 2011 * $Revision: V1.0.10 * * Project: CMSIS DSP Library * Title: arm_fir_decimate_f32.c * * Description: FIR decimation for floating-point sequences. * * Target Processor: Cortex-M4/Cortex-M3/Cortex-M0 * * Version 1.0.10 2011/7/15 * Big Endian support added and Merged M0 and M3/M4 Source code. * * Version 1.0.3 2010/11/29 * Re-organized the CMSIS folders and updated documentation. * * Version 1.0.2 2010/11/11 * Documentation updated. * * Version 1.0.1 2010/10/05 * Production release and review comments incorporated. * * Version 1.0.0 2010/09/20 * Production release and review comments incorporated * * Version 0.0.7 2010/06/10 * Misra-C changes done * * -------------------------------------------------------------------- */ #include "arm_math.h" /** * @ingroup groupFilters */ /** * @defgroup FIR_decimate Finite Impulse Response (FIR) Decimator * * These functions combine an FIR filter together with a decimator. * They are used in multirate systems for reducing the sample rate of a signal without introducing aliasing distortion. * Conceptually, the functions are equivalent to the block diagram below: * \image html FIRDecimator.gif "Components included in the FIR Decimator functions" * When decimating by a factor of <code>M</code>, the signal should be prefiltered by a lowpass filter with a normalized * cutoff frequency of <code>1/M</code> in order to prevent aliasing distortion. * The user of the function is responsible for providing the filter coefficients. * * The FIR decimator functions provided in the CMSIS DSP Library combine the FIR filter and the decimator in an efficient manner. * Instead of calculating all of the FIR filter outputs and discarding <code>M-1</code> out of every <code>M</code>, only the * samples output by the decimator are computed. * The functions operate on blocks of input and output data. * <code>pSrc</code> points to an array of <code>blockSize</code> input values and * <code>pDst</code> points to an array of <code>blockSize/M</code> output values. * In order to have an integer number of output samples <code>blockSize</code> * must always be a multiple of the decimation factor <code>M</code>. * * The library provides separate functions for Q15, Q31 and floating-point data types. * * \par Algorithm: * The FIR portion of the algorithm uses the standard form filter: * <pre> * y[n] = b[0] * x[n] + b[1] * x[n-1] + b[2] * x[n-2] + ...+ b[numTaps-1] * x[n-numTaps+1] * </pre> * where, <code>b[n]</code> are the filter coefficients. * \par * The <code>pCoeffs</code> points to a coefficient array of size <code>numTaps</code>. * Coefficients are stored in time reversed order. * \par * <pre> * {b[numTaps-1], b[numTaps-2], b[N-2], ..., b[1], b[0]} * </pre> * \par * <code>pState</code> points to a state array of size <code>numTaps + blockSize - 1</code>. * Samples in the state buffer are stored in the order: * \par * <pre> * {x[n-numTaps+1], x[n-numTaps], x[n-numTaps-1], x[n-numTaps-2]....x[0], x[1], ..., x[blockSize-1]} * </pre> * The state variables are updated after each block of data is processed, the coefficients are untouched. * * \par Instance Structure * The coefficients and state variables for a filter are stored together in an instance data structure. * A separate instance structure must be defined for each filter. * Coefficient arrays may be shared among several instances while state variable array should be allocated separately. * There are separate instance structure declarations for each of the 3 supported data types. * * \par Initialization Functions * There is also an associated initialization function for each data type. * The initialization function performs the following operations: * - Sets the values of the internal structure fields. * - Zeros out the values in the state buffer. * - Checks to make sure that the size of the input is a multiple of the decimation factor. * * \par * Use of the initialization function is optional. * However, if the initialization function is used, then the instance structure cannot be placed into a const data section. * To place an instance structure into a const data section, the instance structure must be manually initialized. * The code below statically initializes each of the 3 different data type filter instance structures * <pre> *arm_fir_decimate_instance_f32 S = {M, numTaps, pCoeffs, pState}; *arm_fir_decimate_instance_q31 S = {M, numTaps, pCoeffs, pState}; *arm_fir_decimate_instance_q15 S = {M, numTaps, pCoeffs, pState}; * </pre> * where <code>M</code> is the decimation factor; <code>numTaps</code> is the number of filter coefficients in the filter; * <code>pCoeffs</code> is the address of the coefficient buffer; * <code>pState</code> is the address of the state buffer. * Be sure to set the values in the state buffer to zeros when doing static initialization. * * \par Fixed-Point Behavior * Care must be taken when using the fixed-point versions of the FIR decimate filter functions. * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. * Refer to the function specific documentation below for usage guidelines. */ /** * @addtogroup FIR_decimate * @{ */ /** * @brief Processing function for the floating-point FIR decimator. * @param[in] *S points to an instance of the floating-point FIR decimator structure. * @param[in] *pSrc points to the block of input data. * @param[out] *pDst points to the block of output data. * @param[in] blockSize number of input samples to process per call. * @return none. */ void arm_fir_decimate_f32( const arm_fir_decimate_instance_f32 * S, float32_t * pSrc, float32_t * pDst, uint32_t blockSize) { float32_t *pState = S->pState; /* State pointer */ float32_t *pCoeffs = S->pCoeffs; /* Coefficient pointer */ float32_t *pStateCurnt; /* Points to the current sample of the state */ float32_t *px, *pb; /* Temporary pointers for state and coefficient buffers */ float32_t sum0; /* Accumulator */ float32_t x0, c0; /* Temporary variables to hold state and coefficient values */ uint32_t numTaps = S->numTaps; /* Number of filter coefficients in the filter */ uint32_t i, tapCnt, blkCnt, outBlockSize = blockSize / S->M; /* Loop counters */ #ifndef ARM_MATH_CM0 /* Run the below code for Cortex-M4 and Cortex-M3 */ /* S->pState buffer contains previous frame (numTaps - 1) samples */ /* pStateCurnt points to the location where the new input data should be written */ pStateCurnt = S->pState + (numTaps - 1u); /* Total number of output samples to be computed */ blkCnt = outBlockSize; while(blkCnt > 0u) { /* Copy decimation factor number of new input samples into the state buffer */ i = S->M; do { *pStateCurnt++ = *pSrc++; } while(--i); /* Set accumulator to zero */ sum0 = 0.0f; /* Initialize state pointer */ px = pState; /* Initialize coeff pointer */ pb = pCoeffs; /* Loop unrolling. Process 4 taps at a time. */ tapCnt = numTaps >> 2; /* Loop over the number of taps. Unroll by a factor of 4. ** Repeat until we've computed numTaps-4 coefficients. */ while(tapCnt > 0u) { /* Read the b[numTaps-1] coefficient */ c0 = *(pb++); /* Read x[n-numTaps-1] sample */ x0 = *(px++); /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Read the b[numTaps-2] coefficient */ c0 = *(pb++); /* Read x[n-numTaps-2] sample */ x0 = *(px++); /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Read the b[numTaps-3] coefficient */ c0 = *(pb++); /* Read x[n-numTaps-3] sample */ x0 = *(px++); /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Read the b[numTaps-4] coefficient */ c0 = *(pb++); /* Read x[n-numTaps-4] sample */ x0 = *(px++); /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Decrement the loop counter */ tapCnt--; } /* If the filter length is not a multiple of 4, compute the remaining filter taps */ tapCnt = numTaps % 0x4u; while(tapCnt > 0u) { /* Read coefficients */ c0 = *(pb++); /* Fetch 1 state variable */ x0 = *(px++); /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Decrement the loop counter */ tapCnt--; } /* Advance the state pointer by the decimation factor * to process the next group of decimation factor number samples */ pState = pState + S->M; /* The result is in the accumulator, store in the destination buffer. */ *pDst++ = sum0; /* Decrement the loop counter */ blkCnt--; } /* Processing is complete. ** Now copy the last numTaps - 1 samples to the satrt of the state buffer. ** This prepares the state buffer for the next function call. */ /* Points to the start of the state buffer */ pStateCurnt = S->pState; i = (numTaps - 1u) >> 2; /* copy data */ while(i > 0u) { *pStateCurnt++ = *pState++; *pStateCurnt++ = *pState++; *pStateCurnt++ = *pState++; *pStateCurnt++ = *pState++; /* Decrement the loop counter */ i--; } i = (numTaps - 1u) % 0x04u; /* copy data */ while(i > 0u) { *pStateCurnt++ = *pState++; /* Decrement the loop counter */ i--; } #else /* Run the below code for Cortex-M0 */ /* S->pState buffer contains previous frame (numTaps - 1) samples */ /* pStateCurnt points to the location where the new input data should be written */ pStateCurnt = S->pState + (numTaps - 1u); /* Total number of output samples to be computed */ blkCnt = outBlockSize; while(blkCnt > 0u) { /* Copy decimation factor number of new input samples into the state buffer */ i = S->M; do { *pStateCurnt++ = *pSrc++; } while(--i); /* Set accumulator to zero */ sum0 = 0.0f; /* Initialize state pointer */ px = pState; /* Initialize coeff pointer */ pb = pCoeffs; tapCnt = numTaps; while(tapCnt > 0u) { /* Read coefficients */ c0 = *pb++; /* Fetch 1 state variable */ x0 = *px++; /* Perform the multiply-accumulate */ sum0 += x0 * c0; /* Decrement the loop counter */ tapCnt--; } /* Advance the state pointer by the decimation factor * to process the next group of decimation factor number samples */ pState = pState + S->M; /* The result is in the accumulator, store in the destination buffer. */ *pDst++ = sum0; /* Decrement the loop counter */ blkCnt--; } /* Processing is complete. ** Now copy the last numTaps - 1 samples to the start of the state buffer. ** This prepares the state buffer for the next function call. */ /* Points to the start of the state buffer */ pStateCurnt = S->pState; /* Copy numTaps number of values */ i = (numTaps - 1u); /* copy data */ while(i > 0u) { *pStateCurnt++ = *pState++; /* Decrement the loop counter */ i--; } #endif /* #ifndef ARM_MATH_CM0 */ } /** * @} end of FIR_decimate group */
lgpl-2.1
imasahiro/konohascript
package/konoha.qt4/src/KQMouseEvent.cpp
1
8741
//QMouseEvent QMouseEvent.new(int type, QPoint position, int button, QtMouseButtons buttons, QtKeyboardModifiers modifiers); KMETHOD QMouseEvent_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent::Type type = Int_to(QMouseEvent::Type, sfp[1]); const QPoint position = *RawPtr_to(const QPoint *, sfp[2]); Qt::MouseButton button = Int_to(Qt::MouseButton, sfp[3]); initFlag(buttons, Qt::MouseButtons, sfp[4]); initFlag(modifiers, Qt::KeyboardModifiers, sfp[5]); KQMouseEvent *ret_v = new KQMouseEvent(type, position, button, buttons, modifiers); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } /* //QMouseEvent QMouseEvent.new(int type, QPoint pos, QPoint globalPos, int button, QtMouseButtons buttons, QtKeyboardModifiers modifiers); KMETHOD QMouseEvent_new(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent::Type type = Int_to(QMouseEvent::Type, sfp[1]); const QPoint pos = *RawPtr_to(const QPoint *, sfp[2]); const QPoint globalPos = *RawPtr_to(const QPoint *, sfp[3]); Qt::MouseButton button = Int_to(Qt::MouseButton, sfp[4]); initFlag(buttons, Qt::MouseButtons, sfp[5]); initFlag(modifiers, Qt::KeyboardModifiers, sfp[6]); KQMouseEvent *ret_v = new KQMouseEvent(type, pos, globalPos, button, buttons, modifiers); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v, NULL); ret_v->setSelf(rptr); RETURN_(rptr); } */ //int QMouseEvent.button(); KMETHOD QMouseEvent_button(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { Qt::MouseButton ret_v = qp->button(); RETURNi_(ret_v); } else { RETURNi_(0); } } //QtMouseButtons QMouseEvent.buttons(); KMETHOD QMouseEvent_buttons(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { Qt::MouseButtons ret_v = qp->buttons(); Qt::MouseButtons *ret_v_ = new Qt::MouseButtons(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //QPoint QMouseEvent.globalPos(); KMETHOD QMouseEvent_globalPos(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { const QPoint ret_v = qp->globalPos(); QPoint *ret_v_ = new QPoint(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //int QMouseEvent.globalX(); KMETHOD QMouseEvent_globalX(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { int ret_v = qp->globalX(); RETURNi_(ret_v); } else { RETURNi_(0); } } //int QMouseEvent.globalY(); KMETHOD QMouseEvent_globalY(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { int ret_v = qp->globalY(); RETURNi_(ret_v); } else { RETURNi_(0); } } //QPoint QMouseEvent.pos(); KMETHOD QMouseEvent_pos(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { const QPoint ret_v = qp->pos(); QPoint *ret_v_ = new QPoint(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //QPointF QMouseEvent.posF(); KMETHOD QMouseEvent_posF(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { QPointF ret_v = qp->posF(); QPointF *ret_v_ = new QPointF(ret_v); knh_RawPtr_t *rptr = new_ReturnCppObject(ctx, sfp, ret_v_, NULL); RETURN_(rptr); } else { RETURN_(KNH_NULL); } } //int QMouseEvent.x(); KMETHOD QMouseEvent_x(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { int ret_v = qp->x(); RETURNi_(ret_v); } else { RETURNi_(0); } } //int QMouseEvent.y(); KMETHOD QMouseEvent_y(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; QMouseEvent * qp = RawPtr_to(QMouseEvent *, sfp[0]); if (qp) { int ret_v = qp->y(); RETURNi_(ret_v); } else { RETURNi_(0); } } DummyQMouseEvent::DummyQMouseEvent() { CTX lctx = knh_getCurrentContext(); (void)lctx; self = NULL; event_map = new map<string, knh_Func_t *>(); slot_map = new map<string, knh_Func_t *>(); } DummyQMouseEvent::~DummyQMouseEvent() { delete event_map; delete slot_map; event_map = NULL; slot_map = NULL; } void DummyQMouseEvent::setSelf(knh_RawPtr_t *ptr) { DummyQMouseEvent::self = ptr; DummyQInputEvent::setSelf(ptr); } bool DummyQMouseEvent::eventDispatcher(QEvent *event) { bool ret = true; switch (event->type()) { default: ret = DummyQInputEvent::eventDispatcher(event); break; } return ret; } bool DummyQMouseEvent::addEvent(knh_Func_t *callback_func, string str) { std::map<string, knh_Func_t*>::iterator itr;// = DummyQMouseEvent::event_map->bigin(); if ((itr = DummyQMouseEvent::event_map->find(str)) == DummyQMouseEvent::event_map->end()) { bool ret = false; ret = DummyQInputEvent::addEvent(callback_func, str); return ret; } else { KNH_INITv((*event_map)[str], callback_func); return true; } } bool DummyQMouseEvent::signalConnect(knh_Func_t *callback_func, string str) { std::map<string, knh_Func_t*>::iterator itr;// = DummyQMouseEvent::slot_map->bigin(); if ((itr = DummyQMouseEvent::slot_map->find(str)) == DummyQMouseEvent::slot_map->end()) { bool ret = false; ret = DummyQInputEvent::signalConnect(callback_func, str); return ret; } else { KNH_INITv((*slot_map)[str], callback_func); return true; } } knh_Object_t** DummyQMouseEvent::reftrace(CTX ctx, knh_RawPtr_t *p FTRARG) { (void)ctx; (void)p; (void)tail_; // fprintf(stderr, "DummyQMouseEvent::reftrace p->rawptr=[%p]\n", p->rawptr); tail_ = DummyQInputEvent::reftrace(ctx, p, tail_); return tail_; } void DummyQMouseEvent::connection(QObject *o) { QMouseEvent *p = dynamic_cast<QMouseEvent*>(o); if (p != NULL) { } DummyQInputEvent::connection(o); } KQMouseEvent::KQMouseEvent(QMouseEvent::Type type, const QPoint position, Qt::MouseButton button, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers) : QMouseEvent(type, position, button, buttons, modifiers) { magic_num = G_MAGIC_NUM; self = NULL; dummy = new DummyQMouseEvent(); } KQMouseEvent::~KQMouseEvent() { delete dummy; dummy = NULL; } KMETHOD QMouseEvent_addEvent(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; KQMouseEvent *qp = RawPtr_to(KQMouseEvent *, sfp[0]); const char *event_name = String_to(const char *, sfp[1]); knh_Func_t *callback_func = sfp[2].fo; if (qp != NULL) { // if (qp->event_map->find(event_name) == qp->event_map->end()) { // fprintf(stderr, "WARNING:[QMouseEvent]unknown event name [%s]\n", event_name); // return; // } string str = string(event_name); // KNH_INITv((*(qp->event_map))[event_name], callback_func); if (!qp->dummy->addEvent(callback_func, str)) { fprintf(stderr, "WARNING:[QMouseEvent]unknown event name [%s]\n", event_name); return; } } RETURNvoid_(); } KMETHOD QMouseEvent_signalConnect(CTX ctx, knh_sfp_t *sfp _RIX) { (void)ctx; KQMouseEvent *qp = RawPtr_to(KQMouseEvent *, sfp[0]); const char *signal_name = String_to(const char *, sfp[1]); knh_Func_t *callback_func = sfp[2].fo; if (qp != NULL) { // if (qp->slot_map->find(signal_name) == qp->slot_map->end()) { // fprintf(stderr, "WARNING:[QMouseEvent]unknown signal name [%s]\n", signal_name); // return; // } string str = string(signal_name); // KNH_INITv((*(qp->slot_map))[signal_name], callback_func); if (!qp->dummy->signalConnect(callback_func, str)) { fprintf(stderr, "WARNING:[QMouseEvent]unknown signal name [%s]\n", signal_name); return; } } RETURNvoid_(); } static void QMouseEvent_free(CTX ctx, knh_RawPtr_t *p) { (void)ctx; if (!exec_flag) return; if (p->rawptr != NULL) { KQMouseEvent *qp = (KQMouseEvent *)p->rawptr; if (qp->magic_num == G_MAGIC_NUM) { delete qp; p->rawptr = NULL; } else { delete (QMouseEvent*)qp; p->rawptr = NULL; } } } static void QMouseEvent_reftrace(CTX ctx, knh_RawPtr_t *p FTRARG) { if (p->rawptr != NULL) { // KQMouseEvent *qp = (KQMouseEvent *)p->rawptr; KQMouseEvent *qp = static_cast<KQMouseEvent*>(p->rawptr); qp->dummy->reftrace(ctx, p, tail_); } } static int QMouseEvent_compareTo(knh_RawPtr_t *p1, knh_RawPtr_t *p2) { return (p1->rawptr == p2->rawptr ? 0 : 1); } void KQMouseEvent::setSelf(knh_RawPtr_t *ptr) { self = ptr; dummy->setSelf(ptr); } DEFAPI(void) defQMouseEvent(CTX ctx, knh_class_t cid, knh_ClassDef_t *cdef) { (void)ctx; (void) cid; cdef->name = "QMouseEvent"; cdef->free = QMouseEvent_free; cdef->reftrace = QMouseEvent_reftrace; cdef->compareTo = QMouseEvent_compareTo; }
lgpl-3.0
Torben-D/open62541
src/ua_session.c
1
4262
#include "ua_session.h" #include "ua_util.h" #ifdef UA_ENABLE_SUBSCRIPTIONS #include "server/ua_subscription.h" #endif UA_Session adminSession = { .clientDescription = {.applicationUri = {0, NULL}, .productUri = {0, NULL}, .applicationName = {.locale = {0, NULL}, .text = {0, NULL}}, .applicationType = UA_APPLICATIONTYPE_CLIENT, .gatewayServerUri = {0, NULL}, .discoveryProfileUri = {0, NULL}, .discoveryUrlsSize = 0, .discoveryUrls = NULL}, .sessionName = {sizeof("Administrator Session")-1, (UA_Byte*)"Administrator Session"}, .authenticationToken = {.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 1}, .sessionId = {.namespaceIndex = 0, .identifierType = UA_NODEIDTYPE_NUMERIC, .identifier.numeric = 1}, .maxRequestMessageSize = UA_UINT32_MAX, .maxResponseMessageSize = UA_UINT32_MAX, .timeout = (UA_Double)UA_INT64_MAX, .validTill = UA_INT64_MAX, .channel = NULL, .continuationPoints = {NULL}}; void UA_Session_init(UA_Session *session) { UA_ApplicationDescription_init(&session->clientDescription); session->activated = false; UA_NodeId_init(&session->authenticationToken); UA_NodeId_init(&session->sessionId); UA_String_init(&session->sessionName); session->maxRequestMessageSize = 0; session->maxResponseMessageSize = 0; session->timeout = 0; UA_DateTime_init(&session->validTill); session->channel = NULL; session->availableContinuationPoints = MAXCONTINUATIONPOINTS; LIST_INIT(&session->continuationPoints); #ifdef UA_ENABLE_SUBSCRIPTIONS LIST_INIT(&session->serverSubscriptions); session->lastSubscriptionID = 0; SIMPLEQ_INIT(&session->responseQueue); #endif } void UA_Session_deleteMembersCleanup(UA_Session *session, UA_Server* server) { UA_ApplicationDescription_deleteMembers(&session->clientDescription); UA_NodeId_deleteMembers(&session->authenticationToken); UA_NodeId_deleteMembers(&session->sessionId); UA_String_deleteMembers(&session->sessionName); struct ContinuationPointEntry *cp, *temp; LIST_FOREACH_SAFE(cp, &session->continuationPoints, pointers, temp) { LIST_REMOVE(cp, pointers); UA_ByteString_deleteMembers(&cp->identifier); UA_BrowseDescription_deleteMembers(&cp->browseDescription); UA_free(cp); } if(session->channel) UA_SecureChannel_detachSession(session->channel, session); #ifdef UA_ENABLE_SUBSCRIPTIONS UA_Subscription *currents, *temps; LIST_FOREACH_SAFE(currents, &session->serverSubscriptions, listEntry, temps) { LIST_REMOVE(currents, listEntry); UA_Subscription_deleteMembers(currents, server); UA_free(currents); } UA_PublishResponseEntry *entry; while((entry = SIMPLEQ_FIRST(&session->responseQueue))) { SIMPLEQ_REMOVE_HEAD(&session->responseQueue, listEntry); UA_PublishResponse_deleteMembers(&entry->response); UA_free(entry); } #endif } void UA_Session_updateLifetime(UA_Session *session) { session->validTill = UA_DateTime_now() + (UA_DateTime)(session->timeout * UA_MSEC_TO_DATETIME); } #ifdef UA_ENABLE_SUBSCRIPTIONS void UA_Session_addSubscription(UA_Session *session, UA_Subscription *newSubscription) { LIST_INSERT_HEAD(&session->serverSubscriptions, newSubscription, listEntry); } UA_StatusCode UA_Session_deleteSubscription(UA_Server *server, UA_Session *session, UA_UInt32 subscriptionID) { UA_Subscription *sub = UA_Session_getSubscriptionByID(session, subscriptionID); if(!sub) return UA_STATUSCODE_BADSUBSCRIPTIONIDINVALID; LIST_REMOVE(sub, listEntry); UA_Subscription_deleteMembers(sub, server); UA_free(sub); return UA_STATUSCODE_GOOD; } UA_Subscription * UA_Session_getSubscriptionByID(UA_Session *session, UA_UInt32 subscriptionID) { UA_Subscription *sub; LIST_FOREACH(sub, &session->serverSubscriptions, listEntry) { if(sub->subscriptionID == subscriptionID) break; } return sub; } UA_UInt32 UA_Session_getUniqueSubscriptionID(UA_Session *session) { return ++(session->lastSubscriptionID); } #endif
lgpl-3.0
Stevenwork/Innov_code
v0.9/radioManager_8925/tda7703/radio_hit_data.c
2
3887
typedef struct Band_conststuct { unsigned int BandFreq; unsigned int MemFreq[6]; unsigned char CurrentMem; } BandConstStuct; typedef struct Area_stuct { BandConstStuct Band[6]; unsigned char FMStep; unsigned char FMSeekStep; unsigned int FMMaxFreq; unsigned int FMMinFreq; unsigned char FMStepOirt; unsigned int FMMaxFreqOirt; unsigned int FMMinFreqOirt; unsigned char AMStepMW; unsigned int AMMaxFreqMW; unsigned int AMMinFreqMW; unsigned char AMStepLW; unsigned int AMMaxFreqLW; unsigned int AMMinFreqLW; unsigned int AMStepSW; unsigned int AMMaxFreqSW; unsigned int AMMinFreqSW; unsigned char FMStepWB; unsigned int FMMaxFreqWB; unsigned int FMMinFreqWB; } AreaStuct; static const AreaStuct Area[]= { // USA 8750,8750,9010,9810,10610,10790,8750,0, 8750,8750,9670,10490,10690,10790,8750,0, //162400, 162425, 162450, 162475, 162500, 162525, 62400, 62400, 62425, 62450, 62475, 62500, 62525, 0,//Weather band //8750,8750,9670,10490,10690,10790,8750,0, 530,530,600,1000,1600,1720,530,0, 530,530,600,1000,1600,1720,530,0, //1730KHz,(xxx-1384)*5KHz,..., 25080KHz 1730,1730,2000,3000,4000,5000,6400,0, /* sw frequency */ 20,20,10790,8750, 0,0,0, 10,1720,530, 0,0,0, 1,6400,1730, /* sw step freq(5k), max freq setting(5k), min freq(5k), */ 25,62550,62400, // LATIN 8750,8750,9010,9810,10610,10800,8750,0, 8750,8750,8750,8750,8750,8750,8750,0, ////162400, 162425, 162450, 162475, 162500, 162525 //2400, 2400, 2425, 2450, 2475, 2500, 2525, 0,//Weather band 8750,8750,9010,9810,10610,10800,8750,0, 520,520,600,1000,1400,1620,520,0, 520,520,520,520,520,520,520,0, //1730KHz,(xxx-1384)*5KHz,..., 25080KHz 1730,1730,2000,3000,4000,5000,6400,0, /* sw frequency */ 10,10,10800,8750, 0,0,0, 10,1620,520, 0,0,0, 1,6400,1730, /* sw step freq(5k), max freq setting(5k), min freq(5k), */ 0,0,0, //25,2550,2400, // EUROPE 8750,8750,9510,9810,10610,10800,9120,0, 8780,8780,9180,9390,9710,10300,10430,0, 8750,8750,8750,8750,8750,8750,8750,0, //522,522,603,999,1404,1620,522,0, 522,522,846,999,1404,1620,522,0, //522,522,603,999,1404,1620,522,0, 144,144,171,216,270,288,144,0,//---tempory remove //1730KHz,(xxx-1384)*5KHz,..., 25080KHz 1730,1730,2000,3000,4000,5000,6400,0, /* sw frequency */ 5,10,10800,8750, //5,5,10800,8750, 0,0,0, 9,1620,522, 9,288,144, 1,6400,1730, /* sw step freq(5k), max freq setting(5k), min freq(5k), */ 0,0,0, // OIRT 6500,6500,8750,9000,9800,10600,10800,0, 6500,6500,8750,9000,9800,10600,10800,0, 6500,6500,8750,9000,9800,10600,10800,0, 531,531,603,999,1404,1620,531,0, 531,531,603,999,1404,1620,531,0, //1730KHz,(xxx-1384)*5KHz,..., 25080KHz 1730,1730,2000,3000,4000,5000,6400,0, /* sw frequency */ //144,144,171,216,270,288,144,0, 5,10,10800,8750, 3,7400,6500, 9,1620,522, 9,288,144, 1,6400,1730, /* sw step freq(5k), max freq setting(5k), min freq(5k), */ 0,0,0, // JAPAN 7600,7600,7820,7900,8000,8500,9000,0, 7600,7600,7900,8200,8500,8800,9000,0, 7600,7600,7950,8250,8550,8850,9000,0, 531,531,603,999,1404,1620,531,0, 531,531,603,999,1404,1620,531,0, //144,144,171,216,270,288,144,0, //1730KHz,(xxx-1384)*5KHz,..., 25080KHz 1730,1730,2000,3000,4000,5000,6400,0, /* sw frequency */ 5,10,9000,7600, 0,0,0, 9,1620,522, //9,288,144, 0,0,0, 1,6400,1730, /* sw step freq(5k), max freq setting(5k), min freq(5k), */ 0,0,0, }; #if HIT_ADA//ada version #ifdef HIT_64 //#include "Radio_hit_340data.c" #endif #ifdef HIT_44 // #include "radio_hit44_330rc23_data.c" #endif #endif #if HIT_ADB //adb version #ifdef HIT_64 // #include "Radio_hit64_430data.c" #endif #ifdef HIT_44 #include "Radio_hit44_417data.c" #endif #endif
lgpl-3.0
mdaus/nitro
externals/coda-oss/modules/c++/sys/tests/TestBacktrace.cpp
3
1211
/* ========================================================================= * This file is part of sys-c++ * ========================================================================= * * (C) Copyright 2004 - 2016, MDA Information Systems LLC * * sys-c++ 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 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; If not, * see <http://www.gnu.org/licenses/>. * */ #include <sys/Backtrace.h> #include <iostream> void function0() { std::cout << sys::getBacktrace() << std::endl; } void function1() { function0(); } void function2() { function1(); } void function3() { function2(); } int main() { function3(); return 0; }
lgpl-3.0
florolf/libopencm3
lib/sam/4l/gpio.c
11
2838
/** @addtogroup gpio_defines * * @brief <b>Access functions for the SAM4 I/O Controller</b> * @ingroup SAM4_defines * LGPL License Terms @ref lgpl_license * @author @htmlonly &copy; @endhtmlonly 2016 * Maxim Sloyko <maxims@google.com> * */ /* * This file is part of the libopencm3 project. * * Copyright (C) 2012 Gareth McMullin <gareth@blacksphere.co.nz> * Copyright (C) 2014 Felix Held <felix-libopencm3@felixheld.de> * * 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 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include <libopencm3/sam/gpio.h> /** @brief Atomic set output * * @param[in] gpioport uint32_t: GPIO Port base address * @param[in] gpios uint32_t */ void gpio_set(uint32_t gpioport, uint32_t gpios) { GPIO_OVRS(gpioport) = gpios; } /** @brief Atomic clear output * * @param[in] gpioport uint32_t: GPIO Port base address * @param[in] gpios uint32_t */ void gpio_clear(uint32_t gpioport, uint32_t gpios) { GPIO_OVRC(gpioport) = gpios; } /** @brief Atomic toggle output * * @param[in] gpioport uint32_t: GPIO Port base address * @param[in] gpios uint32_t */ void gpio_toggle(uint32_t gpioport, uint32_t gpios) { GPIO_OVRT(gpioport) = gpios; } /** @brief Enable output pins. * * Onlyc the ones where bits are set to "1" are touched, everything else * remains in the old state. * * @param[in] gpioport uint32_t: GPIO Port base address * @param[in] gpios uint32_t * @param[in] mode enum gpio_mode GPIO mode. IN, OUT or peripheral function. */ void gpio_enable(uint32_t gpioport, uint32_t gpios, enum gpio_mode mode) { if (mode < GPIO_MODE_IN) { GPIO_GPERC(gpioport) = gpios; uint8_t i = 0; for (; i < 3; ++i, mode >>= 1) { GPIO_PMR_SETVAL(gpioport, i, mode & 1) = gpios; } } else if (mode == GPIO_MODE_OUT) { GPIO_GPERS(gpioport) = gpios; GPIO_ODERS(gpioport) = gpios; } else if (mode == GPIO_MODE_IN) { GPIO_GPERS(gpioport) = gpios; GPIO_ODERC(gpioport) = gpios; } } /** @brief Disable output pins. * * Onlyc the ones where bits are set to "1" are touched, everything else * remains in the old state. * * @param[in] gpioport uint32_t: GPIO Port base address * @param[in] gpios uint32_t */ void gpio_disable(uint32_t gpioport, uint32_t gpios) { GPIO_GPERC(gpioport) = gpios; }
lgpl-3.0
mtmosier/wiringPi
wiringPi/softPwm.c
21
4261
/* * softPwm.c: * Provide 2 channels of software driven PWM. * Copyright (c) 2012-2014 Gordon Henderson *********************************************************************** * This file is part of wiringPi: * https://projects.drogon.net/raspberry-pi/wiringpi/ * * wiringPi 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 3 of the * License, or (at your option) any later version. * * wiringPi 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 wiringPi. * If not, see <http://www.gnu.org/licenses/>. *********************************************************************** */ #include <stdio.h> #include <pthread.h> #include "wiringPi.h" #include "softPwm.h" // MAX_PINS: // This is more than the number of Pi pins because we can actually softPwm // pins that are on GPIO expanders. It's not that efficient and more than 1 or // 2 pins on e.g. (SPI) mcp23s17 won't really be that effective, however... #define MAX_PINS 1024 // The PWM Frequency is derived from the "pulse time" below. Essentially, // the frequency is a function of the range and this pulse time. // The total period will be range * pulse time in µS, so a pulse time // of 100 and a range of 100 gives a period of 100 * 100 = 10,000 µS // which is a frequency of 100Hz. // // It's possible to get a higher frequency by lowering the pulse time, // however CPU uage will skyrocket as wiringPi uses a hard-loop to time // periods under 100µS - this is because the Linux timer calls are just // accurate at all, and have an overhead. // // Another way to increase the frequency is to reduce the range - however // that reduces the overall output accuracy... #define PULSE_TIME 100 static int marks [MAX_PINS] ; static int range [MAX_PINS] ; static pthread_t threads [MAX_PINS] ; int newPin = -1 ; /* * softPwmThread: * Thread to do the actual PWM output ********************************************************************************* */ static PI_THREAD (softPwmThread) { int pin, mark, space ; struct sched_param param ; param.sched_priority = sched_get_priority_max (SCHED_RR) ; pthread_setschedparam (pthread_self (), SCHED_RR, &param) ; pin = newPin ; newPin = -1 ; piHiPri (90) ; for (;;) { mark = marks [pin] ; space = range [pin] - mark ; if (mark != 0) digitalWrite (pin, HIGH) ; delayMicroseconds (mark * 100) ; if (space != 0) digitalWrite (pin, LOW) ; delayMicroseconds (space * 100) ; } return NULL ; } /* * softPwmWrite: * Write a PWM value to the given pin ********************************************************************************* */ void softPwmWrite (int pin, int value) { pin &= (MAX_PINS - 1) ; /**/ if (value < 0) value = 0 ; else if (value > range [pin]) value = range [pin] ; marks [pin] = value ; } /* * softPwmCreate: * Create a new softPWM thread. ********************************************************************************* */ int softPwmCreate (int pin, int initialValue, int pwmRange) { int res ; pthread_t myThread ; if (range [pin] != 0) // Already running on this pin return -1 ; if (range <= 0) return -1 ; pinMode (pin, OUTPUT) ; digitalWrite (pin, LOW) ; marks [pin] = initialValue ; range [pin] = pwmRange ; newPin = pin ; res = pthread_create (&myThread, NULL, softPwmThread, NULL) ; while (newPin != -1) delay (1) ; threads [pin] = myThread ; return res ; } /* * softPwmStop: * Stop an existing softPWM thread ********************************************************************************* */ void softPwmStop (int pin) { if (range [pin] != 0) { pthread_cancel (threads [pin]) ; pthread_join (threads [pin], NULL) ; range [pin] = 0 ; digitalWrite (pin, LOW) ; } }
lgpl-3.0
Kiddinglife/kidding-engine
python/Python/compile.c
30
127726
/* * This file compiles an abstract syntax tree (AST) into Python bytecode. * * The primary entry point is PyAST_Compile(), which returns a * PyCodeObject. The compiler makes several passes to build the code * object: * 1. Checks for future statements. See future.c * 2. Builds a symbol table. See symtable.c. * 3. Generate code for basic blocks. See compiler_mod() in this file. * 4. Assemble the basic blocks into final code. See assemble() in * this file. * 5. Optimize the byte code (peephole optimizations). See peephole.c * * Note that compiler_mod() suggests module, but the module ast type * (mod_ty) has cases for expressions and interactive statements. * * CAUTION: The VISIT_* macros abort the current function when they * encounter a problem. So don't invoke them when there is memory * which needs to be released. Code blocks are OK, as the compiler * structure takes care of releasing those. Use the arena to manage * objects. */ #include "Python.h" #include "Python-ast.h" #include "node.h" #include "ast.h" #include "code.h" #include "symtable.h" #include "opcode.h" int Py_OptimizeFlag = 0; #define DEFAULT_BLOCK_SIZE 16 #define DEFAULT_BLOCKS 8 #define DEFAULT_CODE_SIZE 128 #define DEFAULT_LNOTAB_SIZE 16 #define COMP_GENEXP 0 #define COMP_LISTCOMP 1 #define COMP_SETCOMP 2 #define COMP_DICTCOMP 3 struct instr { unsigned i_jabs : 1; unsigned i_jrel : 1; unsigned i_hasarg : 1; unsigned char i_opcode; int i_oparg; struct basicblock_ *i_target; /* target block (if jump instruction) */ int i_lineno; }; typedef struct basicblock_ { /* Each basicblock in a compilation unit is linked via b_list in the reverse order that the block are allocated. b_list points to the next block, not to be confused with b_next, which is next by control flow. */ struct basicblock_ *b_list; /* number of instructions used */ int b_iused; /* length of instruction array (b_instr) */ int b_ialloc; /* pointer to an array of instructions, initially NULL */ struct instr *b_instr; /* If b_next is non-NULL, it is a pointer to the next block reached by normal control flow. */ struct basicblock_ *b_next; /* b_seen is used to perform a DFS of basicblocks. */ unsigned b_seen : 1; /* b_return is true if a RETURN_VALUE opcode is inserted. */ unsigned b_return : 1; /* depth of stack upon entry of block, computed by stackdepth() */ int b_startdepth; /* instruction offset for block, computed by assemble_jump_offsets() */ int b_offset; } basicblock; /* fblockinfo tracks the current frame block. A frame block is used to handle loops, try/except, and try/finally. It's called a frame block to distinguish it from a basic block in the compiler IR. */ enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END }; struct fblockinfo { enum fblocktype fb_type; basicblock *fb_block; }; enum { COMPILER_SCOPE_MODULE, COMPILER_SCOPE_CLASS, COMPILER_SCOPE_FUNCTION, COMPILER_SCOPE_LAMBDA, COMPILER_SCOPE_COMPREHENSION, }; /* The following items change on entry and exit of code blocks. They must be saved and restored when returning to a block. */ struct compiler_unit { PySTEntryObject *u_ste; PyObject *u_name; PyObject *u_qualname; /* dot-separated qualified name (lazy) */ int u_scope_type; /* The following fields are dicts that map objects to the index of them in co_XXX. The index is used as the argument for opcodes that refer to those collections. */ PyObject *u_consts; /* all constants */ PyObject *u_names; /* all names */ PyObject *u_varnames; /* local variables */ PyObject *u_cellvars; /* cell variables */ PyObject *u_freevars; /* free variables */ PyObject *u_private; /* for private name mangling */ Py_ssize_t u_argcount; /* number of arguments for block */ Py_ssize_t u_kwonlyargcount; /* number of keyword only arguments for block */ /* Pointer to the most recently allocated block. By following b_list members, you can reach all early allocated blocks. */ basicblock *u_blocks; basicblock *u_curblock; /* pointer to current block */ int u_nfblocks; struct fblockinfo u_fblock[CO_MAXBLOCKS]; int u_firstlineno; /* the first lineno of the block */ int u_lineno; /* the lineno for the current stmt */ int u_col_offset; /* the offset of the current stmt */ int u_lineno_set; /* boolean to indicate whether instr has been generated with current lineno */ }; /* This struct captures the global state of a compilation. The u pointer points to the current compilation unit, while units for enclosing blocks are stored in c_stack. The u and c_stack are managed by compiler_enter_scope() and compiler_exit_scope(). Note that we don't track recursion levels during compilation - the task of detecting and rejecting excessive levels of nesting is handled by the symbol analysis pass. */ struct compiler { PyObject *c_filename; struct symtable *c_st; PyFutureFeatures *c_future; /* pointer to module's __future__ */ PyCompilerFlags *c_flags; int c_optimize; /* optimization level */ int c_interactive; /* true if in interactive mode */ int c_nestlevel; struct compiler_unit *u; /* compiler state for current block */ PyObject *c_stack; /* Python list holding compiler_unit ptrs */ PyArena *c_arena; /* pointer to memory allocation arena */ }; static int compiler_enter_scope(struct compiler *, identifier, int, void *, int); static void compiler_free(struct compiler *); static basicblock *compiler_new_block(struct compiler *); static int compiler_next_instr(struct compiler *, basicblock *); static int compiler_addop(struct compiler *, int); static int compiler_addop_o(struct compiler *, int, PyObject *, PyObject *); static int compiler_addop_i(struct compiler *, int, Py_ssize_t); static int compiler_addop_j(struct compiler *, int, basicblock *, int); static basicblock *compiler_use_new_block(struct compiler *); static int compiler_error(struct compiler *, const char *); static int compiler_nameop(struct compiler *, identifier, expr_context_ty); static PyCodeObject *compiler_mod(struct compiler *, mod_ty); static int compiler_visit_stmt(struct compiler *, stmt_ty); static int compiler_visit_keyword(struct compiler *, keyword_ty); static int compiler_visit_expr(struct compiler *, expr_ty); static int compiler_augassign(struct compiler *, stmt_ty); static int compiler_visit_slice(struct compiler *, slice_ty, expr_context_ty); static int compiler_push_fblock(struct compiler *, enum fblocktype, basicblock *); static void compiler_pop_fblock(struct compiler *, enum fblocktype, basicblock *); /* Returns true if there is a loop on the fblock stack. */ static int compiler_in_loop(struct compiler *); static int inplace_binop(struct compiler *, operator_ty); static int expr_constant(struct compiler *, expr_ty); static int compiler_with(struct compiler *, stmt_ty, int); static int compiler_call_helper(struct compiler *c, Py_ssize_t n, asdl_seq *args, asdl_seq *keywords, expr_ty starargs, expr_ty kwargs); static int compiler_try_except(struct compiler *, stmt_ty); static int compiler_set_qualname(struct compiler *); static PyCodeObject *assemble(struct compiler *, int addNone); static PyObject *__doc__; #define COMPILER_CAPSULE_NAME_COMPILER_UNIT "compile.c compiler unit" PyObject * _Py_Mangle(PyObject *privateobj, PyObject *ident) { /* Name mangling: __private becomes _classname__private. This is independent from how the name is used. */ PyObject *result; size_t nlen, plen, ipriv; Py_UCS4 maxchar; if (privateobj == NULL || !PyUnicode_Check(privateobj) || PyUnicode_READ_CHAR(ident, 0) != '_' || PyUnicode_READ_CHAR(ident, 1) != '_') { Py_INCREF(ident); return ident; } nlen = PyUnicode_GET_LENGTH(ident); plen = PyUnicode_GET_LENGTH(privateobj); /* Don't mangle __id__ or names with dots. The only time a name with a dot can occur is when we are compiling an import statement that has a package name. TODO(jhylton): Decide whether we want to support mangling of the module name, e.g. __M.X. */ if ((PyUnicode_READ_CHAR(ident, nlen-1) == '_' && PyUnicode_READ_CHAR(ident, nlen-2) == '_') || PyUnicode_FindChar(ident, '.', 0, nlen, 1) != -1) { Py_INCREF(ident); return ident; /* Don't mangle __whatever__ */ } /* Strip leading underscores from class name */ ipriv = 0; while (PyUnicode_READ_CHAR(privateobj, ipriv) == '_') ipriv++; if (ipriv == plen) { Py_INCREF(ident); return ident; /* Don't mangle if class is just underscores */ } plen -= ipriv; if (plen + nlen >= PY_SSIZE_T_MAX - 1) { PyErr_SetString(PyExc_OverflowError, "private identifier too large to be mangled"); return NULL; } maxchar = PyUnicode_MAX_CHAR_VALUE(ident); if (PyUnicode_MAX_CHAR_VALUE(privateobj) > maxchar) maxchar = PyUnicode_MAX_CHAR_VALUE(privateobj); result = PyUnicode_New(1 + nlen + plen, maxchar); if (!result) return 0; /* ident = "_" + priv[ipriv:] + ident # i.e. 1+plen+nlen bytes */ PyUnicode_WRITE(PyUnicode_KIND(result), PyUnicode_DATA(result), 0, '_'); if (PyUnicode_CopyCharacters(result, 1, privateobj, ipriv, plen) < 0) { Py_DECREF(result); return NULL; } if (PyUnicode_CopyCharacters(result, plen+1, ident, 0, nlen) < 0) { Py_DECREF(result); return NULL; } assert(_PyUnicode_CheckConsistency(result, 1)); return result; } static int compiler_init(struct compiler *c) { memset(c, 0, sizeof(struct compiler)); c->c_stack = PyList_New(0); if (!c->c_stack) return 0; return 1; } PyCodeObject * PyAST_CompileObject(mod_ty mod, PyObject *filename, PyCompilerFlags *flags, int optimize, PyArena *arena) { struct compiler c; PyCodeObject *co = NULL; PyCompilerFlags local_flags; int merged; if (!__doc__) { __doc__ = PyUnicode_InternFromString("__doc__"); if (!__doc__) return NULL; } if (!compiler_init(&c)) return NULL; Py_INCREF(filename); c.c_filename = filename; c.c_arena = arena; c.c_future = PyFuture_FromASTObject(mod, filename); if (c.c_future == NULL) goto finally; if (!flags) { local_flags.cf_flags = 0; flags = &local_flags; } merged = c.c_future->ff_features | flags->cf_flags; c.c_future->ff_features = merged; flags->cf_flags = merged; c.c_flags = flags; c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize; c.c_nestlevel = 0; c.c_st = PySymtable_BuildObject(mod, filename, c.c_future); if (c.c_st == NULL) { if (!PyErr_Occurred()) PyErr_SetString(PyExc_SystemError, "no symtable"); goto finally; } co = compiler_mod(&c, mod); finally: compiler_free(&c); assert(co || PyErr_Occurred()); return co; } PyCodeObject * PyAST_CompileEx(mod_ty mod, const char *filename_str, PyCompilerFlags *flags, int optimize, PyArena *arena) { PyObject *filename; PyCodeObject *co; filename = PyUnicode_DecodeFSDefault(filename_str); if (filename == NULL) return NULL; co = PyAST_CompileObject(mod, filename, flags, optimize, arena); Py_DECREF(filename); return co; } PyCodeObject * PyNode_Compile(struct _node *n, const char *filename) { PyCodeObject *co = NULL; mod_ty mod; PyArena *arena = PyArena_New(); if (!arena) return NULL; mod = PyAST_FromNode(n, NULL, filename, arena); if (mod) co = PyAST_Compile(mod, filename, NULL, arena); PyArena_Free(arena); return co; } static void compiler_free(struct compiler *c) { if (c->c_st) PySymtable_Free(c->c_st); if (c->c_future) PyObject_Free(c->c_future); Py_XDECREF(c->c_filename); Py_DECREF(c->c_stack); } static PyObject * list2dict(PyObject *list) { Py_ssize_t i, n; PyObject *v, *k; PyObject *dict = PyDict_New(); if (!dict) return NULL; n = PyList_Size(list); for (i = 0; i < n; i++) { v = PyLong_FromSsize_t(i); if (!v) { Py_DECREF(dict); return NULL; } k = PyList_GET_ITEM(list, i); k = PyTuple_Pack(2, k, k->ob_type); if (k == NULL || PyDict_SetItem(dict, k, v) < 0) { Py_XDECREF(k); Py_DECREF(v); Py_DECREF(dict); return NULL; } Py_DECREF(k); Py_DECREF(v); } return dict; } /* Return new dict containing names from src that match scope(s). src is a symbol table dictionary. If the scope of a name matches either scope_type or flag is set, insert it into the new dict. The values are integers, starting at offset and increasing by one for each key. */ static PyObject * dictbytype(PyObject *src, int scope_type, int flag, Py_ssize_t offset) { Py_ssize_t i = offset, scope, num_keys, key_i; PyObject *k, *v, *dest = PyDict_New(); PyObject *sorted_keys; assert(offset >= 0); if (dest == NULL) return NULL; /* Sort the keys so that we have a deterministic order on the indexes saved in the returned dictionary. These indexes are used as indexes into the free and cell var storage. Therefore if they aren't deterministic, then the generated bytecode is not deterministic. */ sorted_keys = PyDict_Keys(src); if (sorted_keys == NULL) return NULL; if (PyList_Sort(sorted_keys) != 0) { Py_DECREF(sorted_keys); return NULL; } num_keys = PyList_GET_SIZE(sorted_keys); for (key_i = 0; key_i < num_keys; key_i++) { /* XXX this should probably be a macro in symtable.h */ long vi; k = PyList_GET_ITEM(sorted_keys, key_i); v = PyDict_GetItem(src, k); assert(PyLong_Check(v)); vi = PyLong_AS_LONG(v); scope = (vi >> SCOPE_OFFSET) & SCOPE_MASK; if (scope == scope_type || vi & flag) { PyObject *tuple, *item = PyLong_FromSsize_t(i); if (item == NULL) { Py_DECREF(sorted_keys); Py_DECREF(dest); return NULL; } i++; tuple = PyTuple_Pack(2, k, k->ob_type); if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) { Py_DECREF(sorted_keys); Py_DECREF(item); Py_DECREF(dest); Py_XDECREF(tuple); return NULL; } Py_DECREF(item); Py_DECREF(tuple); } } Py_DECREF(sorted_keys); return dest; } static void compiler_unit_check(struct compiler_unit *u) { basicblock *block; for (block = u->u_blocks; block != NULL; block = block->b_list) { assert((void *)block != (void *)0xcbcbcbcb); assert((void *)block != (void *)0xfbfbfbfb); assert((void *)block != (void *)0xdbdbdbdb); if (block->b_instr != NULL) { assert(block->b_ialloc > 0); assert(block->b_iused > 0); assert(block->b_ialloc >= block->b_iused); } else { assert (block->b_iused == 0); assert (block->b_ialloc == 0); } } } static void compiler_unit_free(struct compiler_unit *u) { basicblock *b, *next; compiler_unit_check(u); b = u->u_blocks; while (b != NULL) { if (b->b_instr) PyObject_Free((void *)b->b_instr); next = b->b_list; PyObject_Free((void *)b); b = next; } Py_CLEAR(u->u_ste); Py_CLEAR(u->u_name); Py_CLEAR(u->u_qualname); Py_CLEAR(u->u_consts); Py_CLEAR(u->u_names); Py_CLEAR(u->u_varnames); Py_CLEAR(u->u_freevars); Py_CLEAR(u->u_cellvars); Py_CLEAR(u->u_private); PyObject_Free(u); } static int compiler_enter_scope(struct compiler *c, identifier name, int scope_type, void *key, int lineno) { struct compiler_unit *u; u = (struct compiler_unit *)PyObject_Malloc(sizeof( struct compiler_unit)); if (!u) { PyErr_NoMemory(); return 0; } memset(u, 0, sizeof(struct compiler_unit)); u->u_scope_type = scope_type; u->u_argcount = 0; u->u_kwonlyargcount = 0; u->u_ste = PySymtable_Lookup(c->c_st, key); if (!u->u_ste) { compiler_unit_free(u); return 0; } Py_INCREF(name); u->u_name = name; u->u_varnames = list2dict(u->u_ste->ste_varnames); u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0); if (!u->u_varnames || !u->u_cellvars) { compiler_unit_free(u); return 0; } if (u->u_ste->ste_needs_class_closure) { /* Cook up a implicit __class__ cell. */ _Py_IDENTIFIER(__class__); PyObject *tuple, *name, *zero; int res; assert(u->u_scope_type == COMPILER_SCOPE_CLASS); assert(PyDict_Size(u->u_cellvars) == 0); name = _PyUnicode_FromId(&PyId___class__); if (!name) { compiler_unit_free(u); return 0; } tuple = PyTuple_Pack(2, name, Py_TYPE(name)); if (!tuple) { compiler_unit_free(u); return 0; } zero = PyLong_FromLong(0); if (!zero) { Py_DECREF(tuple); compiler_unit_free(u); return 0; } res = PyDict_SetItem(u->u_cellvars, tuple, zero); Py_DECREF(tuple); Py_DECREF(zero); if (res < 0) { compiler_unit_free(u); return 0; } } u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS, PyDict_Size(u->u_cellvars)); if (!u->u_freevars) { compiler_unit_free(u); return 0; } u->u_blocks = NULL; u->u_nfblocks = 0; u->u_firstlineno = lineno; u->u_lineno = 0; u->u_col_offset = 0; u->u_lineno_set = 0; u->u_consts = PyDict_New(); if (!u->u_consts) { compiler_unit_free(u); return 0; } u->u_names = PyDict_New(); if (!u->u_names) { compiler_unit_free(u); return 0; } u->u_private = NULL; /* Push the old compiler_unit on the stack. */ if (c->u) { PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL); if (!capsule || PyList_Append(c->c_stack, capsule) < 0) { Py_XDECREF(capsule); compiler_unit_free(u); return 0; } Py_DECREF(capsule); u->u_private = c->u->u_private; Py_XINCREF(u->u_private); } c->u = u; c->c_nestlevel++; if (compiler_use_new_block(c) == NULL) return 0; if (u->u_scope_type != COMPILER_SCOPE_MODULE) { if (!compiler_set_qualname(c)) return 0; } return 1; } static void compiler_exit_scope(struct compiler *c) { Py_ssize_t n; PyObject *capsule; c->c_nestlevel--; compiler_unit_free(c->u); /* Restore c->u to the parent unit. */ n = PyList_GET_SIZE(c->c_stack) - 1; if (n >= 0) { capsule = PyList_GET_ITEM(c->c_stack, n); c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); assert(c->u); /* we are deleting from a list so this really shouldn't fail */ if (PySequence_DelItem(c->c_stack, n) < 0) Py_FatalError("compiler_exit_scope()"); compiler_unit_check(c->u); } else c->u = NULL; } static int compiler_set_qualname(struct compiler *c) { _Py_static_string(dot, "."); _Py_static_string(dot_locals, ".<locals>"); Py_ssize_t stack_size; struct compiler_unit *u = c->u; PyObject *name, *base, *dot_str, *dot_locals_str; base = NULL; stack_size = PyList_GET_SIZE(c->c_stack); assert(stack_size >= 1); if (stack_size > 1) { int scope, force_global = 0; struct compiler_unit *parent; PyObject *mangled, *capsule; capsule = PyList_GET_ITEM(c->c_stack, stack_size - 1); parent = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT); assert(parent); if (u->u_scope_type == COMPILER_SCOPE_FUNCTION || u->u_scope_type == COMPILER_SCOPE_CLASS) { assert(u->u_name); mangled = _Py_Mangle(parent->u_private, u->u_name); if (!mangled) return 0; scope = PyST_GetScope(parent->u_ste, mangled); Py_DECREF(mangled); assert(scope != GLOBAL_IMPLICIT); if (scope == GLOBAL_EXPLICIT) force_global = 1; } if (!force_global) { if (parent->u_scope_type == COMPILER_SCOPE_FUNCTION || parent->u_scope_type == COMPILER_SCOPE_LAMBDA) { dot_locals_str = _PyUnicode_FromId(&dot_locals); if (dot_locals_str == NULL) return 0; base = PyUnicode_Concat(parent->u_qualname, dot_locals_str); if (base == NULL) return 0; } else { Py_INCREF(parent->u_qualname); base = parent->u_qualname; } } } if (base != NULL) { dot_str = _PyUnicode_FromId(&dot); if (dot_str == NULL) { Py_DECREF(base); return 0; } name = PyUnicode_Concat(base, dot_str); Py_DECREF(base); if (name == NULL) return 0; PyUnicode_Append(&name, u->u_name); if (name == NULL) return 0; } else { Py_INCREF(u->u_name); name = u->u_name; } u->u_qualname = name; return 1; } /* Allocate a new block and return a pointer to it. Returns NULL on error. */ static basicblock * compiler_new_block(struct compiler *c) { basicblock *b; struct compiler_unit *u; u = c->u; b = (basicblock *)PyObject_Malloc(sizeof(basicblock)); if (b == NULL) { PyErr_NoMemory(); return NULL; } memset((void *)b, 0, sizeof(basicblock)); /* Extend the singly linked list of blocks with new block. */ b->b_list = u->u_blocks; u->u_blocks = b; return b; } static basicblock * compiler_use_new_block(struct compiler *c) { basicblock *block = compiler_new_block(c); if (block == NULL) return NULL; c->u->u_curblock = block; return block; } static basicblock * compiler_next_block(struct compiler *c) { basicblock *block = compiler_new_block(c); if (block == NULL) return NULL; c->u->u_curblock->b_next = block; c->u->u_curblock = block; return block; } static basicblock * compiler_use_next_block(struct compiler *c, basicblock *block) { assert(block != NULL); c->u->u_curblock->b_next = block; c->u->u_curblock = block; return block; } /* Returns the offset of the next instruction in the current block's b_instr array. Resizes the b_instr as necessary. Returns -1 on failure. */ static int compiler_next_instr(struct compiler *c, basicblock *b) { assert(b != NULL); if (b->b_instr == NULL) { b->b_instr = (struct instr *)PyObject_Malloc( sizeof(struct instr) * DEFAULT_BLOCK_SIZE); if (b->b_instr == NULL) { PyErr_NoMemory(); return -1; } b->b_ialloc = DEFAULT_BLOCK_SIZE; memset((char *)b->b_instr, 0, sizeof(struct instr) * DEFAULT_BLOCK_SIZE); } else if (b->b_iused == b->b_ialloc) { struct instr *tmp; size_t oldsize, newsize; oldsize = b->b_ialloc * sizeof(struct instr); newsize = oldsize << 1; if (oldsize > (PY_SIZE_MAX >> 1)) { PyErr_NoMemory(); return -1; } if (newsize == 0) { PyErr_NoMemory(); return -1; } b->b_ialloc <<= 1; tmp = (struct instr *)PyObject_Realloc( (void *)b->b_instr, newsize); if (tmp == NULL) { PyErr_NoMemory(); return -1; } b->b_instr = tmp; memset((char *)b->b_instr + oldsize, 0, newsize - oldsize); } return b->b_iused++; } /* Set the i_lineno member of the instruction at offset off if the line number for the current expression/statement has not already been set. If it has been set, the call has no effect. The line number is reset in the following cases: - when entering a new scope - on each statement - on each expression that start a new line - before the "except" clause - before the "for" and "while" expressions */ static void compiler_set_lineno(struct compiler *c, int off) { basicblock *b; if (c->u->u_lineno_set) return; c->u->u_lineno_set = 1; b = c->u->u_curblock; b->b_instr[off].i_lineno = c->u->u_lineno; } int PyCompile_OpcodeStackEffect(int opcode, int oparg) { switch (opcode) { case POP_TOP: return -1; case ROT_TWO: case ROT_THREE: return 0; case DUP_TOP: return 1; case DUP_TOP_TWO: return 2; case UNARY_POSITIVE: case UNARY_NEGATIVE: case UNARY_NOT: case UNARY_INVERT: return 0; case SET_ADD: case LIST_APPEND: return -1; case MAP_ADD: return -2; case BINARY_POWER: case BINARY_MULTIPLY: case BINARY_MODULO: case BINARY_ADD: case BINARY_SUBTRACT: case BINARY_SUBSCR: case BINARY_FLOOR_DIVIDE: case BINARY_TRUE_DIVIDE: return -1; case INPLACE_FLOOR_DIVIDE: case INPLACE_TRUE_DIVIDE: return -1; case INPLACE_ADD: case INPLACE_SUBTRACT: case INPLACE_MULTIPLY: case INPLACE_MODULO: return -1; case STORE_SUBSCR: return -3; case STORE_MAP: return -2; case DELETE_SUBSCR: return -2; case BINARY_LSHIFT: case BINARY_RSHIFT: case BINARY_AND: case BINARY_XOR: case BINARY_OR: return -1; case INPLACE_POWER: return -1; case GET_ITER: return 0; case PRINT_EXPR: return -1; case LOAD_BUILD_CLASS: return 1; case INPLACE_LSHIFT: case INPLACE_RSHIFT: case INPLACE_AND: case INPLACE_XOR: case INPLACE_OR: return -1; case BREAK_LOOP: return 0; case SETUP_WITH: return 7; case WITH_CLEANUP: return -1; /* XXX Sometimes more */ case RETURN_VALUE: return -1; case IMPORT_STAR: return -1; case YIELD_VALUE: return 0; case YIELD_FROM: return -1; case POP_BLOCK: return 0; case POP_EXCEPT: return 0; /* -3 except if bad bytecode */ case END_FINALLY: return -1; /* or -2 or -3 if exception occurred */ case STORE_NAME: return -1; case DELETE_NAME: return 0; case UNPACK_SEQUENCE: return oparg-1; case UNPACK_EX: return (oparg&0xFF) + (oparg>>8); case FOR_ITER: return 1; /* or -1, at end of iterator */ case STORE_ATTR: return -2; case DELETE_ATTR: return -1; case STORE_GLOBAL: return -1; case DELETE_GLOBAL: return 0; case LOAD_CONST: return 1; case LOAD_NAME: return 1; case BUILD_TUPLE: case BUILD_LIST: case BUILD_SET: return 1-oparg; case BUILD_MAP: return 1; case LOAD_ATTR: return 0; case COMPARE_OP: return -1; case IMPORT_NAME: return -1; case IMPORT_FROM: return 1; case JUMP_FORWARD: case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */ case JUMP_IF_FALSE_OR_POP: /* "" */ case JUMP_ABSOLUTE: return 0; case POP_JUMP_IF_FALSE: case POP_JUMP_IF_TRUE: return -1; case LOAD_GLOBAL: return 1; case CONTINUE_LOOP: return 0; case SETUP_LOOP: return 0; case SETUP_EXCEPT: case SETUP_FINALLY: return 6; /* can push 3 values for the new exception + 3 others for the previous exception state */ case LOAD_FAST: return 1; case STORE_FAST: return -1; case DELETE_FAST: return 0; case RAISE_VARARGS: return -oparg; #define NARGS(o) (((o) % 256) + 2*(((o) / 256) % 256)) case CALL_FUNCTION: return -NARGS(oparg); case CALL_FUNCTION_VAR: case CALL_FUNCTION_KW: return -NARGS(oparg)-1; case CALL_FUNCTION_VAR_KW: return -NARGS(oparg)-2; case MAKE_FUNCTION: return -1 -NARGS(oparg) - ((oparg >> 16) & 0xffff); case MAKE_CLOSURE: return -2 - NARGS(oparg) - ((oparg >> 16) & 0xffff); #undef NARGS case BUILD_SLICE: if (oparg == 3) return -2; else return -1; case LOAD_CLOSURE: return 1; case LOAD_DEREF: case LOAD_CLASSDEREF: return 1; case STORE_DEREF: return -1; case DELETE_DEREF: return 0; default: return PY_INVALID_STACK_EFFECT; } return PY_INVALID_STACK_EFFECT; /* not reachable */ } /* Add an opcode with no argument. Returns 0 on failure, 1 on success. */ static int compiler_addop(struct compiler *c, int opcode) { basicblock *b; struct instr *i; int off; off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; b = c->u->u_curblock; i = &b->b_instr[off]; i->i_opcode = opcode; i->i_hasarg = 0; if (opcode == RETURN_VALUE) b->b_return = 1; compiler_set_lineno(c, off); return 1; } static Py_ssize_t compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o) { PyObject *t, *v; Py_ssize_t arg; double d; /* necessary to make sure types aren't coerced (e.g., float and complex) */ /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */ if (PyFloat_Check(o)) { d = PyFloat_AS_DOUBLE(o); /* all we need is to make the tuple different in either the 0.0 * or -0.0 case from all others, just to avoid the "coercion". */ if (d == 0.0 && copysign(1.0, d) < 0.0) t = PyTuple_Pack(3, o, o->ob_type, Py_None); else t = PyTuple_Pack(2, o, o->ob_type); } else if (PyComplex_Check(o)) { Py_complex z; int real_negzero, imag_negzero; /* For the complex case we must make complex(x, 0.) different from complex(x, -0.) and complex(0., y) different from complex(-0., y), for any x and y. All four complex zeros must be distinguished.*/ z = PyComplex_AsCComplex(o); real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0; imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0; if (real_negzero && imag_negzero) { t = PyTuple_Pack(5, o, o->ob_type, Py_None, Py_None, Py_None); } else if (imag_negzero) { t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None); } else if (real_negzero) { t = PyTuple_Pack(3, o, o->ob_type, Py_None); } else { t = PyTuple_Pack(2, o, o->ob_type); } } else { t = PyTuple_Pack(2, o, o->ob_type); } if (t == NULL) return -1; v = PyDict_GetItem(dict, t); if (!v) { if (PyErr_Occurred()) return -1; arg = PyDict_Size(dict); v = PyLong_FromSsize_t(arg); if (!v) { Py_DECREF(t); return -1; } if (PyDict_SetItem(dict, t, v) < 0) { Py_DECREF(t); Py_DECREF(v); return -1; } Py_DECREF(v); } else arg = PyLong_AsLong(v); Py_DECREF(t); return arg; } static int compiler_addop_o(struct compiler *c, int opcode, PyObject *dict, PyObject *o) { Py_ssize_t arg = compiler_add_o(c, dict, o); if (arg < 0) return 0; return compiler_addop_i(c, opcode, arg); } static int compiler_addop_name(struct compiler *c, int opcode, PyObject *dict, PyObject *o) { Py_ssize_t arg; PyObject *mangled = _Py_Mangle(c->u->u_private, o); if (!mangled) return 0; arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) return 0; return compiler_addop_i(c, opcode, arg); } /* Add an opcode with an integer argument. Returns 0 on failure, 1 on success. */ static int compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg) { struct instr *i; int off; /* Integer arguments are limit to 16-bit. There is an extension for 32-bit integer arguments. */ assert((-2147483647-1) <= oparg); assert(oparg <= 2147483647); off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; i = &c->u->u_curblock->b_instr[off]; i->i_opcode = opcode; i->i_oparg = Py_SAFE_DOWNCAST(oparg, Py_ssize_t, int); i->i_hasarg = 1; compiler_set_lineno(c, off); return 1; } static int compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute) { struct instr *i; int off; assert(b != NULL); off = compiler_next_instr(c, c->u->u_curblock); if (off < 0) return 0; i = &c->u->u_curblock->b_instr[off]; i->i_opcode = opcode; i->i_target = b; i->i_hasarg = 1; if (absolute) i->i_jabs = 1; else i->i_jrel = 1; compiler_set_lineno(c, off); return 1; } /* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd like to find better names.) NEW_BLOCK() creates a new block and sets it as the current block. NEXT_BLOCK() also creates an implicit jump from the current block to the new block. */ /* The returns inside these macros make it impossible to decref objects created in the local function. Local objects should use the arena. */ #define NEW_BLOCK(C) { \ if (compiler_use_new_block((C)) == NULL) \ return 0; \ } #define NEXT_BLOCK(C) { \ if (compiler_next_block((C)) == NULL) \ return 0; \ } #define ADDOP(C, OP) { \ if (!compiler_addop((C), (OP))) \ return 0; \ } #define ADDOP_IN_SCOPE(C, OP) { \ if (!compiler_addop((C), (OP))) { \ compiler_exit_scope(c); \ return 0; \ } \ } #define ADDOP_O(C, OP, O, TYPE) { \ if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \ return 0; \ } #define ADDOP_NAME(C, OP, O, TYPE) { \ if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \ return 0; \ } #define ADDOP_I(C, OP, O) { \ if (!compiler_addop_i((C), (OP), (O))) \ return 0; \ } #define ADDOP_JABS(C, OP, O) { \ if (!compiler_addop_j((C), (OP), (O), 1)) \ return 0; \ } #define ADDOP_JREL(C, OP, O) { \ if (!compiler_addop_j((C), (OP), (O), 0)) \ return 0; \ } /* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use the ASDL name to synthesize the name of the C type and the visit function. */ #define VISIT(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) \ return 0; \ } #define VISIT_IN_SCOPE(C, TYPE, V) {\ if (!compiler_visit_ ## TYPE((C), (V))) { \ compiler_exit_scope(c); \ return 0; \ } \ } #define VISIT_SLICE(C, V, CTX) {\ if (!compiler_visit_slice((C), (V), (CTX))) \ return 0; \ } #define VISIT_SEQ(C, TYPE, SEQ) { \ int _i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ if (!compiler_visit_ ## TYPE((C), elt)) \ return 0; \ } \ } #define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \ int _i; \ asdl_seq *seq = (SEQ); /* avoid variable capture */ \ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \ if (!compiler_visit_ ## TYPE((C), elt)) { \ compiler_exit_scope(c); \ return 0; \ } \ } \ } static int compiler_isdocstring(stmt_ty s) { if (s->kind != Expr_kind) return 0; return s->v.Expr.value->kind == Str_kind; } /* Compile a sequence of statements, checking for a docstring. */ static int compiler_body(struct compiler *c, asdl_seq *stmts) { int i = 0; stmt_ty st; if (!asdl_seq_LEN(stmts)) return 1; st = (stmt_ty)asdl_seq_GET(stmts, 0); if (compiler_isdocstring(st) && c->c_optimize < 2) { /* don't generate docstrings if -OO */ i = 1; VISIT(c, expr, st->v.Expr.value); if (!compiler_nameop(c, __doc__, Store)) return 0; } for (; i < asdl_seq_LEN(stmts); i++) VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i)); return 1; } static PyCodeObject * compiler_mod(struct compiler *c, mod_ty mod) { PyCodeObject *co; int addNone = 1; static PyObject *module; if (!module) { module = PyUnicode_InternFromString("<module>"); if (!module) return NULL; } /* Use 0 for firstlineno initially, will fixup in assemble(). */ if (!compiler_enter_scope(c, module, COMPILER_SCOPE_MODULE, mod, 0)) return NULL; switch (mod->kind) { case Module_kind: if (!compiler_body(c, mod->v.Module.body)) { compiler_exit_scope(c); return 0; } break; case Interactive_kind: c->c_interactive = 1; VISIT_SEQ_IN_SCOPE(c, stmt, mod->v.Interactive.body); break; case Expression_kind: VISIT_IN_SCOPE(c, expr, mod->v.Expression.body); addNone = 0; break; case Suite_kind: PyErr_SetString(PyExc_SystemError, "suite should not be possible"); return 0; default: PyErr_Format(PyExc_SystemError, "module kind %d should not be possible", mod->kind); return 0; } co = assemble(c, addNone); compiler_exit_scope(c); return co; } /* The test for LOCAL must come before the test for FREE in order to handle classes where name is both local and free. The local var is a method and the free var is a free var referenced within a method. */ static int get_ref_type(struct compiler *c, PyObject *name) { int scope; if (c->u->u_scope_type == COMPILER_SCOPE_CLASS && !PyUnicode_CompareWithASCIIString(name, "__class__")) return CELL; scope = PyST_GetScope(c->u->u_ste, name); if (scope == 0) { char buf[350]; PyOS_snprintf(buf, sizeof(buf), "unknown scope for %.100s in %.100s(%s)\n" "symbols: %s\nlocals: %s\nglobals: %s", PyBytes_AS_STRING(name), PyBytes_AS_STRING(c->u->u_name), PyObject_REPR(c->u->u_ste->ste_id), PyObject_REPR(c->u->u_ste->ste_symbols), PyObject_REPR(c->u->u_varnames), PyObject_REPR(c->u->u_names) ); Py_FatalError(buf); } return scope; } static int compiler_lookup_arg(PyObject *dict, PyObject *name) { PyObject *k, *v; k = PyTuple_Pack(2, name, name->ob_type); if (k == NULL) return -1; v = PyDict_GetItem(dict, k); Py_DECREF(k); if (v == NULL) return -1; return PyLong_AS_LONG(v); } static int compiler_make_closure(struct compiler *c, PyCodeObject *co, Py_ssize_t args, PyObject *qualname) { Py_ssize_t i, free = PyCode_GetNumFree(co); if (qualname == NULL) qualname = co->co_name; if (free == 0) { ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); ADDOP_O(c, LOAD_CONST, qualname, consts); ADDOP_I(c, MAKE_FUNCTION, args); return 1; } for (i = 0; i < free; ++i) { /* Bypass com_addop_varname because it will generate LOAD_DEREF but LOAD_CLOSURE is needed. */ PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i); int arg, reftype; /* Special case: If a class contains a method with a free variable that has the same name as a method, the name will be considered free *and* local in the class. It should be handled by the closure, as well as by the normal name loookup logic. */ reftype = get_ref_type(c, name); if (reftype == CELL) arg = compiler_lookup_arg(c->u->u_cellvars, name); else /* (reftype == FREE) */ arg = compiler_lookup_arg(c->u->u_freevars, name); if (arg == -1) { fprintf(stderr, "lookup %s in %s %d %d\n" "freevars of %s: %s\n", PyObject_REPR(name), PyBytes_AS_STRING(c->u->u_name), reftype, arg, _PyUnicode_AsString(co->co_name), PyObject_REPR(co->co_freevars)); Py_FatalError("compiler_make_closure()"); } ADDOP_I(c, LOAD_CLOSURE, arg); } ADDOP_I(c, BUILD_TUPLE, free); ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts); ADDOP_O(c, LOAD_CONST, qualname, consts); ADDOP_I(c, MAKE_CLOSURE, args); return 1; } static int compiler_decorators(struct compiler *c, asdl_seq* decos) { int i; if (!decos) return 1; for (i = 0; i < asdl_seq_LEN(decos); i++) { VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i)); } return 1; } static int compiler_visit_kwonlydefaults(struct compiler *c, asdl_seq *kwonlyargs, asdl_seq *kw_defaults) { int i, default_count = 0; for (i = 0; i < asdl_seq_LEN(kwonlyargs); i++) { arg_ty arg = asdl_seq_GET(kwonlyargs, i); expr_ty default_ = asdl_seq_GET(kw_defaults, i); if (default_) { PyObject *mangled = _Py_Mangle(c->u->u_private, arg->arg); if (!mangled) return -1; ADDOP_O(c, LOAD_CONST, mangled, consts); Py_DECREF(mangled); if (!compiler_visit_expr(c, default_)) { return -1; } default_count++; } } return default_count; } static int compiler_visit_argannotation(struct compiler *c, identifier id, expr_ty annotation, PyObject *names) { if (annotation) { PyObject *mangled; VISIT(c, expr, annotation); mangled = _Py_Mangle(c->u->u_private, id); if (!mangled) return -1; if (PyList_Append(names, mangled) < 0) { Py_DECREF(mangled); return -1; } Py_DECREF(mangled); } return 0; } static int compiler_visit_argannotations(struct compiler *c, asdl_seq* args, PyObject *names) { int i, error; for (i = 0; i < asdl_seq_LEN(args); i++) { arg_ty arg = (arg_ty)asdl_seq_GET(args, i); error = compiler_visit_argannotation( c, arg->arg, arg->annotation, names); if (error) return error; } return 0; } static int compiler_visit_annotations(struct compiler *c, arguments_ty args, expr_ty returns) { /* Push arg annotations and a list of the argument names. Return the # of items pushed. The expressions are evaluated out-of-order wrt the source code. More than 2^16-1 annotations is a SyntaxError. Returns -1 on error. */ static identifier return_str; PyObject *names; Py_ssize_t len; names = PyList_New(0); if (!names) return -1; if (compiler_visit_argannotations(c, args->args, names)) goto error; if (args->vararg && args->vararg->annotation && compiler_visit_argannotation(c, args->vararg->arg, args->vararg->annotation, names)) goto error; if (compiler_visit_argannotations(c, args->kwonlyargs, names)) goto error; if (args->kwarg && args->kwarg->annotation && compiler_visit_argannotation(c, args->kwarg->arg, args->kwarg->annotation, names)) goto error; if (!return_str) { return_str = PyUnicode_InternFromString("return"); if (!return_str) goto error; } if (compiler_visit_argannotation(c, return_str, returns, names)) { goto error; } len = PyList_GET_SIZE(names); if (len > 65534) { /* len must fit in 16 bits, and len is incremented below */ PyErr_SetString(PyExc_SyntaxError, "too many annotations"); goto error; } if (len) { /* convert names to a tuple and place on stack */ PyObject *elt; Py_ssize_t i; PyObject *s = PyTuple_New(len); if (!s) goto error; for (i = 0; i < len; i++) { elt = PyList_GET_ITEM(names, i); Py_INCREF(elt); PyTuple_SET_ITEM(s, i, elt); } ADDOP_O(c, LOAD_CONST, s, consts); Py_DECREF(s); len++; /* include the just-pushed tuple */ } Py_DECREF(names); /* We just checked that len <= 65535, see above */ return Py_SAFE_DOWNCAST(len, Py_ssize_t, int); error: Py_DECREF(names); return -1; } static int compiler_function(struct compiler *c, stmt_ty s) { PyCodeObject *co; PyObject *qualname, *first_const = Py_None; arguments_ty args = s->v.FunctionDef.args; expr_ty returns = s->v.FunctionDef.returns; asdl_seq* decos = s->v.FunctionDef.decorator_list; stmt_ty st; Py_ssize_t i, n, arglength; int docstring, kw_default_count = 0; int num_annotations; assert(s->kind == FunctionDef_kind); if (!compiler_decorators(c, decos)) return 0; if (args->defaults) VISIT_SEQ(c, expr, args->defaults); if (args->kwonlyargs) { int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, args->kw_defaults); if (res < 0) return 0; kw_default_count = res; } num_annotations = compiler_visit_annotations(c, args, returns); if (num_annotations < 0) return 0; assert((num_annotations & 0xFFFF) == num_annotations); if (!compiler_enter_scope(c, s->v.FunctionDef.name, COMPILER_SCOPE_FUNCTION, (void *)s, s->lineno)) return 0; st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0); docstring = compiler_isdocstring(st); if (docstring && c->c_optimize < 2) first_const = st->v.Expr.value->v.Str.s; if (compiler_add_o(c, c->u->u_consts, first_const) < 0) { compiler_exit_scope(c); return 0; } c->u->u_argcount = asdl_seq_LEN(args->args); c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); n = asdl_seq_LEN(s->v.FunctionDef.body); /* if there was a docstring, we need to skip the first statement */ for (i = docstring; i < n; i++) { st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i); VISIT_IN_SCOPE(c, stmt, st); } co = assemble(c, 1); qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) { Py_XDECREF(qualname); Py_XDECREF(co); return 0; } arglength = asdl_seq_LEN(args->defaults); arglength |= kw_default_count << 8; arglength |= num_annotations << 16; compiler_make_closure(c, co, arglength, qualname); Py_DECREF(qualname); Py_DECREF(co); /* decorators */ for (i = 0; i < asdl_seq_LEN(decos); i++) { ADDOP_I(c, CALL_FUNCTION, 1); } return compiler_nameop(c, s->v.FunctionDef.name, Store); } static int compiler_class(struct compiler *c, stmt_ty s) { PyCodeObject *co; PyObject *str; int i; asdl_seq* decos = s->v.ClassDef.decorator_list; if (!compiler_decorators(c, decos)) return 0; /* ultimately generate code for: <name> = __build_class__(<func>, <name>, *<bases>, **<keywords>) where: <func> is a function/closure created from the class body; it has a single argument (__locals__) where the dict (or MutableSequence) representing the locals is passed <name> is the class name <bases> is the positional arguments and *varargs argument <keywords> is the keyword arguments and **kwds argument This borrows from compiler_call. */ /* 1. compile the class body into a code object */ if (!compiler_enter_scope(c, s->v.ClassDef.name, COMPILER_SCOPE_CLASS, (void *)s, s->lineno)) return 0; /* this block represents what we do in the new scope */ { /* use the class name for name mangling */ Py_INCREF(s->v.ClassDef.name); Py_XDECREF(c->u->u_private); c->u->u_private = s->v.ClassDef.name; /* load (global) __name__ ... */ str = PyUnicode_InternFromString("__name__"); if (!str || !compiler_nameop(c, str, Load)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); /* ... and store it as __module__ */ str = PyUnicode_InternFromString("__module__"); if (!str || !compiler_nameop(c, str, Store)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); assert(c->u->u_qualname); ADDOP_O(c, LOAD_CONST, c->u->u_qualname, consts); str = PyUnicode_InternFromString("__qualname__"); if (!str || !compiler_nameop(c, str, Store)) { Py_XDECREF(str); compiler_exit_scope(c); return 0; } Py_DECREF(str); /* compile the body proper */ if (!compiler_body(c, s->v.ClassDef.body)) { compiler_exit_scope(c); return 0; } if (c->u->u_ste->ste_needs_class_closure) { /* return the (empty) __class__ cell */ str = PyUnicode_InternFromString("__class__"); if (str == NULL) { compiler_exit_scope(c); return 0; } i = compiler_lookup_arg(c->u->u_cellvars, str); Py_DECREF(str); if (i < 0) { compiler_exit_scope(c); return 0; } assert(i == 0); /* Return the cell where to store __class__ */ ADDOP_I(c, LOAD_CLOSURE, i); } else { assert(PyDict_Size(c->u->u_cellvars) == 0); /* This happens when nobody references the cell. Return None. */ ADDOP_O(c, LOAD_CONST, Py_None, consts); } ADDOP_IN_SCOPE(c, RETURN_VALUE); /* create the code object */ co = assemble(c, 1); } /* leave the new scope */ compiler_exit_scope(c); if (co == NULL) return 0; /* 2. load the 'build_class' function */ ADDOP(c, LOAD_BUILD_CLASS); /* 3. load a function (or closure) made from the code object */ compiler_make_closure(c, co, 0, NULL); Py_DECREF(co); /* 4. load class name */ ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts); /* 5. generate the rest of the code for the call */ if (!compiler_call_helper(c, 2, s->v.ClassDef.bases, s->v.ClassDef.keywords, s->v.ClassDef.starargs, s->v.ClassDef.kwargs)) return 0; /* 6. apply decorators */ for (i = 0; i < asdl_seq_LEN(decos); i++) { ADDOP_I(c, CALL_FUNCTION, 1); } /* 7. store into <name> */ if (!compiler_nameop(c, s->v.ClassDef.name, Store)) return 0; return 1; } static int compiler_ifexp(struct compiler *c, expr_ty e) { basicblock *end, *next; assert(e->kind == IfExp_kind); end = compiler_new_block(c); if (end == NULL) return 0; next = compiler_new_block(c); if (next == NULL) return 0; VISIT(c, expr, e->v.IfExp.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); VISIT(c, expr, e->v.IfExp.body); ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, next); VISIT(c, expr, e->v.IfExp.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_lambda(struct compiler *c, expr_ty e) { PyCodeObject *co; PyObject *qualname; static identifier name; int kw_default_count = 0; Py_ssize_t arglength; arguments_ty args = e->v.Lambda.args; assert(e->kind == Lambda_kind); if (!name) { name = PyUnicode_InternFromString("<lambda>"); if (!name) return 0; } if (args->defaults) VISIT_SEQ(c, expr, args->defaults); if (args->kwonlyargs) { int res = compiler_visit_kwonlydefaults(c, args->kwonlyargs, args->kw_defaults); if (res < 0) return 0; kw_default_count = res; } if (!compiler_enter_scope(c, name, COMPILER_SCOPE_LAMBDA, (void *)e, e->lineno)) return 0; /* Make None the first constant, so the lambda can't have a docstring. */ if (compiler_add_o(c, c->u->u_consts, Py_None) < 0) return 0; c->u->u_argcount = asdl_seq_LEN(args->args); c->u->u_kwonlyargcount = asdl_seq_LEN(args->kwonlyargs); VISIT_IN_SCOPE(c, expr, e->v.Lambda.body); if (c->u->u_ste->ste_generator) { ADDOP_IN_SCOPE(c, POP_TOP); } else { ADDOP_IN_SCOPE(c, RETURN_VALUE); } co = assemble(c, 1); qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) return 0; arglength = asdl_seq_LEN(args->defaults); arglength |= kw_default_count << 8; compiler_make_closure(c, co, arglength, qualname); Py_DECREF(qualname); Py_DECREF(co); return 1; } static int compiler_if(struct compiler *c, stmt_ty s) { basicblock *end, *next; int constant; assert(s->kind == If_kind); end = compiler_new_block(c); if (end == NULL) return 0; constant = expr_constant(c, s->v.If.test); /* constant = 0: "if 0" * constant = 1: "if 1", "if 2", ... * constant = -1: rest */ if (constant == 0) { if (s->v.If.orelse) VISIT_SEQ(c, stmt, s->v.If.orelse); } else if (constant == 1) { VISIT_SEQ(c, stmt, s->v.If.body); } else { if (s->v.If.orelse) { next = compiler_new_block(c); if (next == NULL) return 0; } else next = end; VISIT(c, expr, s->v.If.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, next); VISIT_SEQ(c, stmt, s->v.If.body); ADDOP_JREL(c, JUMP_FORWARD, end); if (s->v.If.orelse) { compiler_use_next_block(c, next); VISIT_SEQ(c, stmt, s->v.If.orelse); } } compiler_use_next_block(c, end); return 1; } static int compiler_for(struct compiler *c, stmt_ty s) { basicblock *start, *cleanup, *end; start = compiler_new_block(c); cleanup = compiler_new_block(c); end = compiler_new_block(c); if (start == NULL || end == NULL || cleanup == NULL) return 0; ADDOP_JREL(c, SETUP_LOOP, end); if (!compiler_push_fblock(c, LOOP, start)) return 0; VISIT(c, expr, s->v.For.iter); ADDOP(c, GET_ITER); compiler_use_next_block(c, start); ADDOP_JREL(c, FOR_ITER, cleanup); VISIT(c, expr, s->v.For.target); VISIT_SEQ(c, stmt, s->v.For.body); ADDOP_JABS(c, JUMP_ABSOLUTE, start); compiler_use_next_block(c, cleanup); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, LOOP, start); VISIT_SEQ(c, stmt, s->v.For.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_while(struct compiler *c, stmt_ty s) { basicblock *loop, *orelse, *end, *anchor = NULL; int constant = expr_constant(c, s->v.While.test); if (constant == 0) { if (s->v.While.orelse) VISIT_SEQ(c, stmt, s->v.While.orelse); return 1; } loop = compiler_new_block(c); end = compiler_new_block(c); if (constant == -1) { anchor = compiler_new_block(c); if (anchor == NULL) return 0; } if (loop == NULL || end == NULL) return 0; if (s->v.While.orelse) { orelse = compiler_new_block(c); if (orelse == NULL) return 0; } else orelse = NULL; ADDOP_JREL(c, SETUP_LOOP, end); compiler_use_next_block(c, loop); if (!compiler_push_fblock(c, LOOP, loop)) return 0; if (constant == -1) { VISIT(c, expr, s->v.While.test); ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor); } VISIT_SEQ(c, stmt, s->v.While.body); ADDOP_JABS(c, JUMP_ABSOLUTE, loop); /* XXX should the two POP instructions be in a separate block if there is no else clause ? */ if (constant == -1) { compiler_use_next_block(c, anchor); ADDOP(c, POP_BLOCK); } compiler_pop_fblock(c, LOOP, loop); if (orelse != NULL) /* what if orelse is just pass? */ VISIT_SEQ(c, stmt, s->v.While.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_continue(struct compiler *c) { static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop"; static const char IN_FINALLY_ERROR_MSG[] = "'continue' not supported inside 'finally' clause"; int i; if (!c->u->u_nfblocks) return compiler_error(c, LOOP_ERROR_MSG); i = c->u->u_nfblocks - 1; switch (c->u->u_fblock[i].fb_type) { case LOOP: ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block); break; case EXCEPT: case FINALLY_TRY: while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) { /* Prevent continue anywhere under a finally even if hidden in a sub-try or except. */ if (c->u->u_fblock[i].fb_type == FINALLY_END) return compiler_error(c, IN_FINALLY_ERROR_MSG); } if (i == -1) return compiler_error(c, LOOP_ERROR_MSG); ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block); break; case FINALLY_END: return compiler_error(c, IN_FINALLY_ERROR_MSG); } return 1; } /* Code generated for "try: <body> finally: <finalbody>" is as follows: SETUP_FINALLY L <code for body> POP_BLOCK LOAD_CONST <None> L: <code for finalbody> END_FINALLY The special instructions use the block stack. Each block stack entry contains the instruction that created it (here SETUP_FINALLY), the level of the value stack at the time the block stack entry was created, and a label (here L). SETUP_FINALLY: Pushes the current value stack level and the label onto the block stack. POP_BLOCK: Pops en entry from the block stack, and pops the value stack until its level is the same as indicated on the block stack. (The label is ignored.) END_FINALLY: Pops a variable number of entries from the *value* stack and re-raises the exception they specify. The number of entries popped depends on the (pseudo) exception type. The block stack is unwound when an exception is raised: when a SETUP_FINALLY entry is found, the exception is pushed onto the value stack (and the exception condition is cleared), and the interpreter jumps to the label gotten from the block stack. */ static int compiler_try_finally(struct compiler *c, stmt_ty s) { basicblock *body, *end; body = compiler_new_block(c); end = compiler_new_block(c); if (body == NULL || end == NULL) return 0; ADDOP_JREL(c, SETUP_FINALLY, end); compiler_use_next_block(c, body); if (!compiler_push_fblock(c, FINALLY_TRY, body)) return 0; if (s->v.Try.handlers && asdl_seq_LEN(s->v.Try.handlers)) { if (!compiler_try_except(c, s)) return 0; } else { VISIT_SEQ(c, stmt, s->v.Try.body); } ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, body); ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, end); if (!compiler_push_fblock(c, FINALLY_END, end)) return 0; VISIT_SEQ(c, stmt, s->v.Try.finalbody); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, end); return 1; } /* Code generated for "try: S except E1 as V1: S1 except E2 as V2: S2 ...": (The contents of the value stack is shown in [], with the top at the right; 'tb' is trace-back info, 'val' the exception's associated value, and 'exc' the exception.) Value stack Label Instruction Argument [] SETUP_EXCEPT L1 [] <code for S> [] POP_BLOCK [] JUMP_FORWARD L0 [tb, val, exc] L1: DUP ) [tb, val, exc, exc] <evaluate E1> ) [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1 [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 ) [tb, val, exc] POP [tb, val] <assign to V1> (or POP if no V1) [tb] POP [] <code for S1> JUMP_FORWARD L0 [tb, val, exc] L2: DUP .............................etc....................... [tb, val, exc] Ln+1: END_FINALLY # re-raise exception [] L0: <next statement> Of course, parts are not generated if Vi or Ei is not present. */ static int compiler_try_except(struct compiler *c, stmt_ty s) { basicblock *body, *orelse, *except, *end; Py_ssize_t i, n; body = compiler_new_block(c); except = compiler_new_block(c); orelse = compiler_new_block(c); end = compiler_new_block(c); if (body == NULL || except == NULL || orelse == NULL || end == NULL) return 0; ADDOP_JREL(c, SETUP_EXCEPT, except); compiler_use_next_block(c, body); if (!compiler_push_fblock(c, EXCEPT, body)) return 0; VISIT_SEQ(c, stmt, s->v.Try.body); ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, EXCEPT, body); ADDOP_JREL(c, JUMP_FORWARD, orelse); n = asdl_seq_LEN(s->v.Try.handlers); compiler_use_next_block(c, except); for (i = 0; i < n; i++) { excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET( s->v.Try.handlers, i); if (!handler->v.ExceptHandler.type && i < n-1) return compiler_error(c, "default 'except:' must be last"); c->u->u_lineno_set = 0; c->u->u_lineno = handler->lineno; c->u->u_col_offset = handler->col_offset; except = compiler_new_block(c); if (except == NULL) return 0; if (handler->v.ExceptHandler.type) { ADDOP(c, DUP_TOP); VISIT(c, expr, handler->v.ExceptHandler.type); ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH); ADDOP_JABS(c, POP_JUMP_IF_FALSE, except); } ADDOP(c, POP_TOP); if (handler->v.ExceptHandler.name) { basicblock *cleanup_end, *cleanup_body; cleanup_end = compiler_new_block(c); cleanup_body = compiler_new_block(c); if (!(cleanup_end || cleanup_body)) return 0; compiler_nameop(c, handler->v.ExceptHandler.name, Store); ADDOP(c, POP_TOP); /* try: # body except type as name: try: # body finally: name = None del name */ /* second try: */ ADDOP_JREL(c, SETUP_FINALLY, cleanup_end); compiler_use_next_block(c, cleanup_body); if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) return 0; /* second # body */ VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); ADDOP(c, POP_BLOCK); ADDOP(c, POP_EXCEPT); compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); /* finally: */ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, cleanup_end); if (!compiler_push_fblock(c, FINALLY_END, cleanup_end)) return 0; /* name = None */ ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_nameop(c, handler->v.ExceptHandler.name, Store); /* del name */ compiler_nameop(c, handler->v.ExceptHandler.name, Del); ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, cleanup_end); } else { basicblock *cleanup_body; cleanup_body = compiler_new_block(c); if (!cleanup_body) return 0; ADDOP(c, POP_TOP); ADDOP(c, POP_TOP); compiler_use_next_block(c, cleanup_body); if (!compiler_push_fblock(c, FINALLY_TRY, cleanup_body)) return 0; VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body); ADDOP(c, POP_EXCEPT); compiler_pop_fblock(c, FINALLY_TRY, cleanup_body); } ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, except); } ADDOP(c, END_FINALLY); compiler_use_next_block(c, orelse); VISIT_SEQ(c, stmt, s->v.Try.orelse); compiler_use_next_block(c, end); return 1; } static int compiler_try(struct compiler *c, stmt_ty s) { if (s->v.Try.finalbody && asdl_seq_LEN(s->v.Try.finalbody)) return compiler_try_finally(c, s); else return compiler_try_except(c, s); } static int compiler_import_as(struct compiler *c, identifier name, identifier asname) { /* The IMPORT_NAME opcode was already generated. This function merely needs to bind the result to a name. If there is a dot in name, we need to split it and emit a LOAD_ATTR for each name. */ Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0, PyUnicode_GET_LENGTH(name), 1); if (dot == -2) return -1; if (dot != -1) { /* Consume the base module name to get the first attribute */ Py_ssize_t pos = dot + 1; while (dot != -1) { PyObject *attr; dot = PyUnicode_FindChar(name, '.', pos, PyUnicode_GET_LENGTH(name), 1); if (dot == -2) return -1; attr = PyUnicode_Substring(name, pos, (dot != -1) ? dot : PyUnicode_GET_LENGTH(name)); if (!attr) return -1; ADDOP_O(c, LOAD_ATTR, attr, names); Py_DECREF(attr); pos = dot + 1; } } return compiler_nameop(c, asname, Store); } static int compiler_import(struct compiler *c, stmt_ty s) { /* The Import node stores a module name like a.b.c as a single string. This is convenient for all cases except import a.b.c as d where we need to parse that string to extract the individual module names. XXX Perhaps change the representation to make this case simpler? */ Py_ssize_t i, n = asdl_seq_LEN(s->v.Import.names); for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i); int r; PyObject *level; level = PyLong_FromLong(0); if (level == NULL) return 0; ADDOP_O(c, LOAD_CONST, level, consts); Py_DECREF(level); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP_NAME(c, IMPORT_NAME, alias->name, names); if (alias->asname) { r = compiler_import_as(c, alias->name, alias->asname); if (!r) return r; } else { identifier tmp = alias->name; Py_ssize_t dot = PyUnicode_FindChar( alias->name, '.', 0, PyUnicode_GET_LENGTH(alias->name), 1); if (dot != -1) { tmp = PyUnicode_Substring(alias->name, 0, dot); if (tmp == NULL) return 0; } r = compiler_nameop(c, tmp, Store); if (dot != -1) { Py_DECREF(tmp); } if (!r) return r; } } return 1; } static int compiler_from_import(struct compiler *c, stmt_ty s) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ImportFrom.names); PyObject *names = PyTuple_New(n); PyObject *level; static PyObject *empty_string; if (!empty_string) { empty_string = PyUnicode_FromString(""); if (!empty_string) return 0; } if (!names) return 0; level = PyLong_FromLong(s->v.ImportFrom.level); if (!level) { Py_DECREF(names); return 0; } /* build up the names */ for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); Py_INCREF(alias->name); PyTuple_SET_ITEM(names, i, alias->name); } if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module && !PyUnicode_CompareWithASCIIString(s->v.ImportFrom.module, "__future__")) { Py_DECREF(level); Py_DECREF(names); return compiler_error(c, "from __future__ imports must occur " "at the beginning of the file"); } ADDOP_O(c, LOAD_CONST, level, consts); Py_DECREF(level); ADDOP_O(c, LOAD_CONST, names, consts); Py_DECREF(names); if (s->v.ImportFrom.module) { ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names); } else { ADDOP_NAME(c, IMPORT_NAME, empty_string, names); } for (i = 0; i < n; i++) { alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i); identifier store_name; if (i == 0 && PyUnicode_READ_CHAR(alias->name, 0) == '*') { assert(n == 1); ADDOP(c, IMPORT_STAR); return 1; } ADDOP_NAME(c, IMPORT_FROM, alias->name, names); store_name = alias->name; if (alias->asname) store_name = alias->asname; if (!compiler_nameop(c, store_name, Store)) { Py_DECREF(names); return 0; } } /* remove imported module */ ADDOP(c, POP_TOP); return 1; } static int compiler_assert(struct compiler *c, stmt_ty s) { static PyObject *assertion_error = NULL; basicblock *end; PyObject* msg; if (c->c_optimize) return 1; if (assertion_error == NULL) { assertion_error = PyUnicode_InternFromString("AssertionError"); if (assertion_error == NULL) return 0; } if (s->v.Assert.test->kind == Tuple_kind && asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) { msg = PyUnicode_FromString("assertion is always true, " "perhaps remove parentheses?"); if (msg == NULL) return 0; if (PyErr_WarnExplicitObject(PyExc_SyntaxWarning, msg, c->c_filename, c->u->u_lineno, NULL, NULL) == -1) { Py_DECREF(msg); return 0; } Py_DECREF(msg); } VISIT(c, expr, s->v.Assert.test); end = compiler_new_block(c); if (end == NULL) return 0; ADDOP_JABS(c, POP_JUMP_IF_TRUE, end); ADDOP_O(c, LOAD_GLOBAL, assertion_error, names); if (s->v.Assert.msg) { VISIT(c, expr, s->v.Assert.msg); ADDOP_I(c, CALL_FUNCTION, 1); } ADDOP_I(c, RAISE_VARARGS, 1); compiler_use_next_block(c, end); return 1; } static int compiler_visit_stmt(struct compiler *c, stmt_ty s) { Py_ssize_t i, n; /* Always assign a lineno to the next instruction for a stmt. */ c->u->u_lineno = s->lineno; c->u->u_col_offset = s->col_offset; c->u->u_lineno_set = 0; switch (s->kind) { case FunctionDef_kind: return compiler_function(c, s); case ClassDef_kind: return compiler_class(c, s); case Return_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'return' outside function"); if (s->v.Return.value) { VISIT(c, expr, s->v.Return.value); } else ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, RETURN_VALUE); break; case Delete_kind: VISIT_SEQ(c, expr, s->v.Delete.targets) break; case Assign_kind: n = asdl_seq_LEN(s->v.Assign.targets); VISIT(c, expr, s->v.Assign.value); for (i = 0; i < n; i++) { if (i < n - 1) ADDOP(c, DUP_TOP); VISIT(c, expr, (expr_ty)asdl_seq_GET(s->v.Assign.targets, i)); } break; case AugAssign_kind: return compiler_augassign(c, s); case For_kind: return compiler_for(c, s); case While_kind: return compiler_while(c, s); case If_kind: return compiler_if(c, s); case Raise_kind: n = 0; if (s->v.Raise.exc) { VISIT(c, expr, s->v.Raise.exc); n++; if (s->v.Raise.cause) { VISIT(c, expr, s->v.Raise.cause); n++; } } ADDOP_I(c, RAISE_VARARGS, (int)n); break; case Try_kind: return compiler_try(c, s); case Assert_kind: return compiler_assert(c, s); case Import_kind: return compiler_import(c, s); case ImportFrom_kind: return compiler_from_import(c, s); case Global_kind: case Nonlocal_kind: break; case Expr_kind: if (c->c_interactive && c->c_nestlevel <= 1) { VISIT(c, expr, s->v.Expr.value); ADDOP(c, PRINT_EXPR); } else if (s->v.Expr.value->kind != Str_kind && s->v.Expr.value->kind != Num_kind) { VISIT(c, expr, s->v.Expr.value); ADDOP(c, POP_TOP); } break; case Pass_kind: break; case Break_kind: if (!compiler_in_loop(c)) return compiler_error(c, "'break' outside loop"); ADDOP(c, BREAK_LOOP); break; case Continue_kind: return compiler_continue(c); case With_kind: return compiler_with(c, s, 0); } return 1; } static int unaryop(unaryop_ty op) { switch (op) { case Invert: return UNARY_INVERT; case Not: return UNARY_NOT; case UAdd: return UNARY_POSITIVE; case USub: return UNARY_NEGATIVE; default: PyErr_Format(PyExc_SystemError, "unary op %d should not be possible", op); return 0; } } static int binop(struct compiler *c, operator_ty op) { switch (op) { case Add: return BINARY_ADD; case Sub: return BINARY_SUBTRACT; case Mult: return BINARY_MULTIPLY; case Div: return BINARY_TRUE_DIVIDE; case Mod: return BINARY_MODULO; case Pow: return BINARY_POWER; case LShift: return BINARY_LSHIFT; case RShift: return BINARY_RSHIFT; case BitOr: return BINARY_OR; case BitXor: return BINARY_XOR; case BitAnd: return BINARY_AND; case FloorDiv: return BINARY_FLOOR_DIVIDE; default: PyErr_Format(PyExc_SystemError, "binary op %d should not be possible", op); return 0; } } static int cmpop(cmpop_ty op) { switch (op) { case Eq: return PyCmp_EQ; case NotEq: return PyCmp_NE; case Lt: return PyCmp_LT; case LtE: return PyCmp_LE; case Gt: return PyCmp_GT; case GtE: return PyCmp_GE; case Is: return PyCmp_IS; case IsNot: return PyCmp_IS_NOT; case In: return PyCmp_IN; case NotIn: return PyCmp_NOT_IN; default: return PyCmp_BAD; } } static int inplace_binop(struct compiler *c, operator_ty op) { switch (op) { case Add: return INPLACE_ADD; case Sub: return INPLACE_SUBTRACT; case Mult: return INPLACE_MULTIPLY; case Div: return INPLACE_TRUE_DIVIDE; case Mod: return INPLACE_MODULO; case Pow: return INPLACE_POWER; case LShift: return INPLACE_LSHIFT; case RShift: return INPLACE_RSHIFT; case BitOr: return INPLACE_OR; case BitXor: return INPLACE_XOR; case BitAnd: return INPLACE_AND; case FloorDiv: return INPLACE_FLOOR_DIVIDE; default: PyErr_Format(PyExc_SystemError, "inplace binary op %d should not be possible", op); return 0; } } static int compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx) { int op, scope; Py_ssize_t arg; enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype; PyObject *dict = c->u->u_names; PyObject *mangled; /* XXX AugStore isn't used anywhere! */ mangled = _Py_Mangle(c->u->u_private, name); if (!mangled) return 0; assert(PyUnicode_CompareWithASCIIString(name, "None") && PyUnicode_CompareWithASCIIString(name, "True") && PyUnicode_CompareWithASCIIString(name, "False")); op = 0; optype = OP_NAME; scope = PyST_GetScope(c->u->u_ste, mangled); switch (scope) { case FREE: dict = c->u->u_freevars; optype = OP_DEREF; break; case CELL: dict = c->u->u_cellvars; optype = OP_DEREF; break; case LOCAL: if (c->u->u_ste->ste_type == FunctionBlock) optype = OP_FAST; break; case GLOBAL_IMPLICIT: if (c->u->u_ste->ste_type == FunctionBlock && !c->u->u_ste->ste_unoptimized) optype = OP_GLOBAL; break; case GLOBAL_EXPLICIT: optype = OP_GLOBAL; break; default: /* scope can be 0 */ break; } /* XXX Leave assert here, but handle __doc__ and the like better */ assert(scope || PyUnicode_READ_CHAR(name, 0) == '_'); switch (optype) { case OP_DEREF: switch (ctx) { case Load: op = (c->u->u_ste->ste_type == ClassBlock) ? LOAD_CLASSDEREF : LOAD_DEREF; break; case Store: op = STORE_DEREF; break; case AugLoad: case AugStore: break; case Del: op = DELETE_DEREF; break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for deref variable"); return 0; } break; case OP_FAST: switch (ctx) { case Load: op = LOAD_FAST; break; case Store: op = STORE_FAST; break; case Del: op = DELETE_FAST; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for local variable"); return 0; } ADDOP_O(c, op, mangled, varnames); Py_DECREF(mangled); return 1; case OP_GLOBAL: switch (ctx) { case Load: op = LOAD_GLOBAL; break; case Store: op = STORE_GLOBAL; break; case Del: op = DELETE_GLOBAL; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for global variable"); return 0; } break; case OP_NAME: switch (ctx) { case Load: op = LOAD_NAME; break; case Store: op = STORE_NAME; break; case Del: op = DELETE_NAME; break; case AugLoad: case AugStore: break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid for name variable"); return 0; } break; } assert(op); arg = compiler_add_o(c, dict, mangled); Py_DECREF(mangled); if (arg < 0) return 0; return compiler_addop_i(c, op, arg); } static int compiler_boolop(struct compiler *c, expr_ty e) { basicblock *end; int jumpi; Py_ssize_t i, n; asdl_seq *s; assert(e->kind == BoolOp_kind); if (e->v.BoolOp.op == And) jumpi = JUMP_IF_FALSE_OR_POP; else jumpi = JUMP_IF_TRUE_OR_POP; end = compiler_new_block(c); if (end == NULL) return 0; s = e->v.BoolOp.values; n = asdl_seq_LEN(s) - 1; assert(n >= 0); for (i = 0; i < n; ++i) { VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i)); ADDOP_JABS(c, jumpi, end); } VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n)); compiler_use_next_block(c, end); return 1; } static int compiler_list(struct compiler *c, expr_ty e) { Py_ssize_t n = asdl_seq_LEN(e->v.List.elts); if (e->v.List.ctx == Store) { int i, seen_star = 0; for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(e->v.List.elts, i); if (elt->kind == Starred_kind && !seen_star) { if ((i >= (1 << 8)) || (n-i-1 >= (INT_MAX >> 8))) return compiler_error(c, "too many expressions in " "star-unpacking assignment"); ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); seen_star = 1; asdl_seq_SET(e->v.List.elts, i, elt->v.Starred.value); } else if (elt->kind == Starred_kind) { return compiler_error(c, "two starred expressions in assignment"); } } if (!seen_star) { ADDOP_I(c, UNPACK_SEQUENCE, n); } } VISIT_SEQ(c, expr, e->v.List.elts); if (e->v.List.ctx == Load) { ADDOP_I(c, BUILD_LIST, n); } return 1; } static int compiler_tuple(struct compiler *c, expr_ty e) { Py_ssize_t n = asdl_seq_LEN(e->v.Tuple.elts); if (e->v.Tuple.ctx == Store) { int i, seen_star = 0; for (i = 0; i < n; i++) { expr_ty elt = asdl_seq_GET(e->v.Tuple.elts, i); if (elt->kind == Starred_kind && !seen_star) { if ((i >= (1 << 8)) || (n-i-1 >= (INT_MAX >> 8))) return compiler_error(c, "too many expressions in " "star-unpacking assignment"); ADDOP_I(c, UNPACK_EX, (i + ((n-i-1) << 8))); seen_star = 1; asdl_seq_SET(e->v.Tuple.elts, i, elt->v.Starred.value); } else if (elt->kind == Starred_kind) { return compiler_error(c, "two starred expressions in assignment"); } } if (!seen_star) { ADDOP_I(c, UNPACK_SEQUENCE, n); } } VISIT_SEQ(c, expr, e->v.Tuple.elts); if (e->v.Tuple.ctx == Load) { ADDOP_I(c, BUILD_TUPLE, n); } return 1; } static int compiler_compare(struct compiler *c, expr_ty e) { Py_ssize_t i, n; basicblock *cleanup = NULL; /* XXX the logic can be cleaned up for 1 or multiple comparisons */ VISIT(c, expr, e->v.Compare.left); n = asdl_seq_LEN(e->v.Compare.ops); assert(n > 0); if (n > 1) { cleanup = compiler_new_block(c); if (cleanup == NULL) return 0; VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0)); } for (i = 1; i < n; i++) { ADDOP(c, DUP_TOP); ADDOP(c, ROT_THREE); ADDOP_I(c, COMPARE_OP, cmpop((cmpop_ty)(asdl_seq_GET( e->v.Compare.ops, i - 1)))); ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup); NEXT_BLOCK(c); if (i < (n - 1)) VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i)); } VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1)); ADDOP_I(c, COMPARE_OP, cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1)))); if (n > 1) { basicblock *end = compiler_new_block(c); if (end == NULL) return 0; ADDOP_JREL(c, JUMP_FORWARD, end); compiler_use_next_block(c, cleanup); ADDOP(c, ROT_TWO); ADDOP(c, POP_TOP); compiler_use_next_block(c, end); } return 1; } static int compiler_call(struct compiler *c, expr_ty e) { VISIT(c, expr, e->v.Call.func); return compiler_call_helper(c, 0, e->v.Call.args, e->v.Call.keywords, e->v.Call.starargs, e->v.Call.kwargs); } /* shared code between compiler_call and compiler_class */ static int compiler_call_helper(struct compiler *c, Py_ssize_t n, /* Args already pushed */ asdl_seq *args, asdl_seq *keywords, expr_ty starargs, expr_ty kwargs) { int code = 0; n += asdl_seq_LEN(args); VISIT_SEQ(c, expr, args); if (keywords) { VISIT_SEQ(c, keyword, keywords); n |= asdl_seq_LEN(keywords) << 8; } if (starargs) { VISIT(c, expr, starargs); code |= 1; } if (kwargs) { VISIT(c, expr, kwargs); code |= 2; } switch (code) { case 0: ADDOP_I(c, CALL_FUNCTION, n); break; case 1: ADDOP_I(c, CALL_FUNCTION_VAR, n); break; case 2: ADDOP_I(c, CALL_FUNCTION_KW, n); break; case 3: ADDOP_I(c, CALL_FUNCTION_VAR_KW, n); break; } return 1; } /* List and set comprehensions and generator expressions work by creating a nested function to perform the actual iteration. This means that the iteration variables don't leak into the current scope. The defined function is called immediately following its definition, with the result of that call being the result of the expression. The LC/SC version returns the populated container, while the GE version is flagged in symtable.c as a generator, so it returns the generator object when the function is called. This code *knows* that the loop cannot contain break, continue, or return, so it cheats and skips the SETUP_LOOP/POP_BLOCK steps used in normal loops. Possible cleanups: - iterate over the generator sequence instead of using recursion */ static int compiler_comprehension_generator(struct compiler *c, asdl_seq *generators, int gen_index, expr_ty elt, expr_ty val, int type) { /* generate code for the iterator, then each of the ifs, and then write to the element */ comprehension_ty gen; basicblock *start, *anchor, *skip, *if_cleanup; Py_ssize_t i, n; start = compiler_new_block(c); skip = compiler_new_block(c); if_cleanup = compiler_new_block(c); anchor = compiler_new_block(c); if (start == NULL || skip == NULL || if_cleanup == NULL || anchor == NULL) return 0; gen = (comprehension_ty)asdl_seq_GET(generators, gen_index); if (gen_index == 0) { /* Receive outermost iter as an implicit argument */ c->u->u_argcount = 1; ADDOP_I(c, LOAD_FAST, 0); } else { /* Sub-iter - calculate on the fly */ VISIT(c, expr, gen->iter); ADDOP(c, GET_ITER); } compiler_use_next_block(c, start); ADDOP_JREL(c, FOR_ITER, anchor); NEXT_BLOCK(c); VISIT(c, expr, gen->target); /* XXX this needs to be cleaned up...a lot! */ n = asdl_seq_LEN(gen->ifs); for (i = 0; i < n; i++) { expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i); VISIT(c, expr, e); ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup); NEXT_BLOCK(c); } if (++gen_index < asdl_seq_LEN(generators)) if (!compiler_comprehension_generator(c, generators, gen_index, elt, val, type)) return 0; /* only append after the last for generator */ if (gen_index >= asdl_seq_LEN(generators)) { /* comprehension specific code */ switch (type) { case COMP_GENEXP: VISIT(c, expr, elt); ADDOP(c, YIELD_VALUE); ADDOP(c, POP_TOP); break; case COMP_LISTCOMP: VISIT(c, expr, elt); ADDOP_I(c, LIST_APPEND, gen_index + 1); break; case COMP_SETCOMP: VISIT(c, expr, elt); ADDOP_I(c, SET_ADD, gen_index + 1); break; case COMP_DICTCOMP: /* With 'd[k] = v', v is evaluated before k, so we do the same. */ VISIT(c, expr, val); VISIT(c, expr, elt); ADDOP_I(c, MAP_ADD, gen_index + 1); break; default: return 0; } compiler_use_next_block(c, skip); } compiler_use_next_block(c, if_cleanup); ADDOP_JABS(c, JUMP_ABSOLUTE, start); compiler_use_next_block(c, anchor); return 1; } static int compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name, asdl_seq *generators, expr_ty elt, expr_ty val) { PyCodeObject *co = NULL; expr_ty outermost_iter; PyObject *qualname = NULL; outermost_iter = ((comprehension_ty) asdl_seq_GET(generators, 0))->iter; if (!compiler_enter_scope(c, name, COMPILER_SCOPE_COMPREHENSION, (void *)e, e->lineno)) goto error; if (type != COMP_GENEXP) { int op; switch (type) { case COMP_LISTCOMP: op = BUILD_LIST; break; case COMP_SETCOMP: op = BUILD_SET; break; case COMP_DICTCOMP: op = BUILD_MAP; break; default: PyErr_Format(PyExc_SystemError, "unknown comprehension type %d", type); goto error_in_scope; } ADDOP_I(c, op, 0); } if (!compiler_comprehension_generator(c, generators, 0, elt, val, type)) goto error_in_scope; if (type != COMP_GENEXP) { ADDOP(c, RETURN_VALUE); } co = assemble(c, 1); qualname = c->u->u_qualname; Py_INCREF(qualname); compiler_exit_scope(c); if (co == NULL) goto error; if (!compiler_make_closure(c, co, 0, qualname)) goto error; Py_DECREF(qualname); Py_DECREF(co); VISIT(c, expr, outermost_iter); ADDOP(c, GET_ITER); ADDOP_I(c, CALL_FUNCTION, 1); return 1; error_in_scope: compiler_exit_scope(c); error: Py_XDECREF(qualname); Py_XDECREF(co); return 0; } static int compiler_genexp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<genexpr>"); if (!name) return 0; } assert(e->kind == GeneratorExp_kind); return compiler_comprehension(c, e, COMP_GENEXP, name, e->v.GeneratorExp.generators, e->v.GeneratorExp.elt, NULL); } static int compiler_listcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<listcomp>"); if (!name) return 0; } assert(e->kind == ListComp_kind); return compiler_comprehension(c, e, COMP_LISTCOMP, name, e->v.ListComp.generators, e->v.ListComp.elt, NULL); } static int compiler_setcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<setcomp>"); if (!name) return 0; } assert(e->kind == SetComp_kind); return compiler_comprehension(c, e, COMP_SETCOMP, name, e->v.SetComp.generators, e->v.SetComp.elt, NULL); } static int compiler_dictcomp(struct compiler *c, expr_ty e) { static identifier name; if (!name) { name = PyUnicode_FromString("<dictcomp>"); if (!name) return 0; } assert(e->kind == DictComp_kind); return compiler_comprehension(c, e, COMP_DICTCOMP, name, e->v.DictComp.generators, e->v.DictComp.key, e->v.DictComp.value); } static int compiler_visit_keyword(struct compiler *c, keyword_ty k) { ADDOP_O(c, LOAD_CONST, k->arg, consts); VISIT(c, expr, k->value); return 1; } /* Test whether expression is constant. For constants, report whether they are true or false. Return values: 1 for true, 0 for false, -1 for non-constant. */ static int expr_constant(struct compiler *c, expr_ty e) { char *id; switch (e->kind) { case Ellipsis_kind: return 1; case Num_kind: return PyObject_IsTrue(e->v.Num.n); case Str_kind: return PyObject_IsTrue(e->v.Str.s); case Name_kind: /* optimize away names that can't be reassigned */ id = PyUnicode_AsUTF8(e->v.Name.id); if (id && strcmp(id, "__debug__") == 0) return !c->c_optimize; return -1; case NameConstant_kind: { PyObject *o = e->v.NameConstant.value; if (o == Py_None) return 0; else if (o == Py_True) return 1; else if (o == Py_False) return 0; } default: return -1; } } /* Implements the with statement from PEP 343. The semantics outlined in that PEP are as follows: with EXPR as VAR: BLOCK It is implemented roughly as: context = EXPR exit = context.__exit__ # not calling it value = context.__enter__() try: VAR = value # if VAR present in the syntax BLOCK finally: if an exception was raised: exc = copy of (exception, instance, traceback) else: exc = (None, None, None) exit(*exc) */ static int compiler_with(struct compiler *c, stmt_ty s, int pos) { basicblock *block, *finally; withitem_ty item = asdl_seq_GET(s->v.With.items, pos); assert(s->kind == With_kind); block = compiler_new_block(c); finally = compiler_new_block(c); if (!block || !finally) return 0; /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); ADDOP_JREL(c, SETUP_WITH, finally); /* SETUP_WITH pushes a finally block. */ compiler_use_next_block(c, block); if (!compiler_push_fblock(c, FINALLY_TRY, block)) { return 0; } if (item->optional_vars) { VISIT(c, expr, item->optional_vars); } else { /* Discard result from context.__enter__() */ ADDOP(c, POP_TOP); } pos++; if (pos == asdl_seq_LEN(s->v.With.items)) /* BLOCK code */ VISIT_SEQ(c, stmt, s->v.With.body) else if (!compiler_with(c, s, pos)) return 0; /* End of try block; start the finally block */ ADDOP(c, POP_BLOCK); compiler_pop_fblock(c, FINALLY_TRY, block); ADDOP_O(c, LOAD_CONST, Py_None, consts); compiler_use_next_block(c, finally); if (!compiler_push_fblock(c, FINALLY_END, finally)) return 0; /* Finally block starts; context.__exit__ is on the stack under the exception or return information. Just issue our magic opcode. */ ADDOP(c, WITH_CLEANUP); /* Finally block ends. */ ADDOP(c, END_FINALLY); compiler_pop_fblock(c, FINALLY_END, finally); return 1; } static int compiler_visit_expr(struct compiler *c, expr_ty e) { Py_ssize_t i, n; /* If expr e has a different line number than the last expr/stmt, set a new line number for the next instruction. */ if (e->lineno > c->u->u_lineno) { c->u->u_lineno = e->lineno; c->u->u_lineno_set = 0; } /* Updating the column offset is always harmless. */ c->u->u_col_offset = e->col_offset; switch (e->kind) { case BoolOp_kind: return compiler_boolop(c, e); case BinOp_kind: VISIT(c, expr, e->v.BinOp.left); VISIT(c, expr, e->v.BinOp.right); ADDOP(c, binop(c, e->v.BinOp.op)); break; case UnaryOp_kind: VISIT(c, expr, e->v.UnaryOp.operand); ADDOP(c, unaryop(e->v.UnaryOp.op)); break; case Lambda_kind: return compiler_lambda(c, e); case IfExp_kind: return compiler_ifexp(c, e); case Dict_kind: n = asdl_seq_LEN(e->v.Dict.values); /* BUILD_MAP parameter is only used to preallocate the dictionary, it doesn't need to be exact */ ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n)); for (i = 0; i < n; i++) { VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.values, i)); VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); ADDOP(c, STORE_MAP); } break; case Set_kind: n = asdl_seq_LEN(e->v.Set.elts); VISIT_SEQ(c, expr, e->v.Set.elts); ADDOP_I(c, BUILD_SET, n); break; case GeneratorExp_kind: return compiler_genexp(c, e); case ListComp_kind: return compiler_listcomp(c, e); case SetComp_kind: return compiler_setcomp(c, e); case DictComp_kind: return compiler_dictcomp(c, e); case Yield_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'yield' outside function"); if (e->v.Yield.value) { VISIT(c, expr, e->v.Yield.value); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } ADDOP(c, YIELD_VALUE); break; case YieldFrom_kind: if (c->u->u_ste->ste_type != FunctionBlock) return compiler_error(c, "'yield' outside function"); VISIT(c, expr, e->v.YieldFrom.value); ADDOP(c, GET_ITER); ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, YIELD_FROM); break; case Compare_kind: return compiler_compare(c, e); case Call_kind: return compiler_call(c, e); case Num_kind: ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); break; case Str_kind: ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts); break; case Bytes_kind: ADDOP_O(c, LOAD_CONST, e->v.Bytes.s, consts); break; case Ellipsis_kind: ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts); break; case NameConstant_kind: ADDOP_O(c, LOAD_CONST, e->v.NameConstant.value, consts); break; /* The following exprs can be assignment targets. */ case Attribute_kind: if (e->v.Attribute.ctx != AugStore) VISIT(c, expr, e->v.Attribute.value); switch (e->v.Attribute.ctx) { case AugLoad: ADDOP(c, DUP_TOP); /* Fall through to load */ case Load: ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names); break; case AugStore: ADDOP(c, ROT_TWO); /* Fall through to save */ case Store: ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names); break; case Del: ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names); break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid in attribute expression"); return 0; } break; case Subscript_kind: switch (e->v.Subscript.ctx) { case AugLoad: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, AugLoad); break; case Load: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Load); break; case AugStore: VISIT_SLICE(c, e->v.Subscript.slice, AugStore); break; case Store: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Store); break; case Del: VISIT(c, expr, e->v.Subscript.value); VISIT_SLICE(c, e->v.Subscript.slice, Del); break; case Param: default: PyErr_SetString(PyExc_SystemError, "param invalid in subscript expression"); return 0; } break; case Starred_kind: switch (e->v.Starred.ctx) { case Store: /* In all legitimate cases, the Starred node was already replaced * by compiler_list/compiler_tuple. XXX: is that okay? */ return compiler_error(c, "starred assignment target must be in a list or tuple"); default: return compiler_error(c, "can use starred expression only as assignment target"); } break; case Name_kind: return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx); /* child nodes of List and Tuple will have expr_context set */ case List_kind: return compiler_list(c, e); case Tuple_kind: return compiler_tuple(c, e); } return 1; } static int compiler_augassign(struct compiler *c, stmt_ty s) { expr_ty e = s->v.AugAssign.target; expr_ty auge; assert(s->kind == AugAssign_kind); switch (e->kind) { case Attribute_kind: auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr, AugLoad, e->lineno, e->col_offset, c->c_arena); if (auge == NULL) return 0; VISIT(c, expr, auge); VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); auge->v.Attribute.ctx = AugStore; VISIT(c, expr, auge); break; case Subscript_kind: auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice, AugLoad, e->lineno, e->col_offset, c->c_arena); if (auge == NULL) return 0; VISIT(c, expr, auge); VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); auge->v.Subscript.ctx = AugStore; VISIT(c, expr, auge); break; case Name_kind: if (!compiler_nameop(c, e->v.Name.id, Load)) return 0; VISIT(c, expr, s->v.AugAssign.value); ADDOP(c, inplace_binop(c, s->v.AugAssign.op)); return compiler_nameop(c, e->v.Name.id, Store); default: PyErr_Format(PyExc_SystemError, "invalid node type (%d) for augmented assignment", e->kind); return 0; } return 1; } static int compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { struct fblockinfo *f; if (c->u->u_nfblocks >= CO_MAXBLOCKS) { PyErr_SetString(PyExc_SystemError, "too many statically nested blocks"); return 0; } f = &c->u->u_fblock[c->u->u_nfblocks++]; f->fb_type = t; f->fb_block = b; return 1; } static void compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b) { struct compiler_unit *u = c->u; assert(u->u_nfblocks > 0); u->u_nfblocks--; assert(u->u_fblock[u->u_nfblocks].fb_type == t); assert(u->u_fblock[u->u_nfblocks].fb_block == b); } static int compiler_in_loop(struct compiler *c) { int i; struct compiler_unit *u = c->u; for (i = 0; i < u->u_nfblocks; ++i) { if (u->u_fblock[i].fb_type == LOOP) return 1; } return 0; } /* Raises a SyntaxError and returns 0. If something goes wrong, a different exception may be raised. */ static int compiler_error(struct compiler *c, const char *errstr) { PyObject *loc; PyObject *u = NULL, *v = NULL; loc = PyErr_ProgramTextObject(c->c_filename, c->u->u_lineno); if (!loc) { Py_INCREF(Py_None); loc = Py_None; } u = Py_BuildValue("(OiiO)", c->c_filename, c->u->u_lineno, c->u->u_col_offset, loc); if (!u) goto exit; v = Py_BuildValue("(zO)", errstr, u); if (!v) goto exit; PyErr_SetObject(PyExc_SyntaxError, v); exit: Py_DECREF(loc); Py_XDECREF(u); Py_XDECREF(v); return 0; } static int compiler_handle_subscr(struct compiler *c, const char *kind, expr_context_ty ctx) { int op = 0; /* XXX this code is duplicated */ switch (ctx) { case AugLoad: /* fall through to Load */ case Load: op = BINARY_SUBSCR; break; case AugStore:/* fall through to Store */ case Store: op = STORE_SUBSCR; break; case Del: op = DELETE_SUBSCR; break; case Param: PyErr_Format(PyExc_SystemError, "invalid %s kind %d in subscript\n", kind, ctx); return 0; } if (ctx == AugLoad) { ADDOP(c, DUP_TOP_TWO); } else if (ctx == AugStore) { ADDOP(c, ROT_THREE); } ADDOP(c, op); return 1; } static int compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { int n = 2; assert(s->kind == Slice_kind); /* only handles the cases where BUILD_SLICE is emitted */ if (s->v.Slice.lower) { VISIT(c, expr, s->v.Slice.lower); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } if (s->v.Slice.upper) { VISIT(c, expr, s->v.Slice.upper); } else { ADDOP_O(c, LOAD_CONST, Py_None, consts); } if (s->v.Slice.step) { n++; VISIT(c, expr, s->v.Slice.step); } ADDOP_I(c, BUILD_SLICE, n); return 1; } static int compiler_visit_nested_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { switch (s->kind) { case Slice_kind: return compiler_slice(c, s, ctx); case Index_kind: VISIT(c, expr, s->v.Index.value); break; case ExtSlice_kind: default: PyErr_SetString(PyExc_SystemError, "extended slice invalid in nested slice"); return 0; } return 1; } static int compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx) { char * kindname = NULL; switch (s->kind) { case Index_kind: kindname = "index"; if (ctx != AugStore) { VISIT(c, expr, s->v.Index.value); } break; case Slice_kind: kindname = "slice"; if (ctx != AugStore) { if (!compiler_slice(c, s, ctx)) return 0; } break; case ExtSlice_kind: kindname = "extended slice"; if (ctx != AugStore) { Py_ssize_t i, n = asdl_seq_LEN(s->v.ExtSlice.dims); for (i = 0; i < n; i++) { slice_ty sub = (slice_ty)asdl_seq_GET( s->v.ExtSlice.dims, i); if (!compiler_visit_nested_slice(c, sub, ctx)) return 0; } ADDOP_I(c, BUILD_TUPLE, n); } break; default: PyErr_Format(PyExc_SystemError, "invalid subscript kind %d", s->kind); return 0; } return compiler_handle_subscr(c, kindname, ctx); } /* End of the compiler section, beginning of the assembler section */ /* do depth-first search of basic block graph, starting with block. post records the block indices in post-order. XXX must handle implicit jumps from one block to next */ struct assembler { PyObject *a_bytecode; /* string containing bytecode */ int a_offset; /* offset into bytecode */ int a_nblocks; /* number of reachable blocks */ basicblock **a_postorder; /* list of blocks in dfs postorder */ PyObject *a_lnotab; /* string containing lnotab */ int a_lnotab_off; /* offset into lnotab */ int a_lineno; /* last lineno of emitted instruction */ int a_lineno_off; /* bytecode offset of last lineno */ }; static void dfs(struct compiler *c, basicblock *b, struct assembler *a) { int i; struct instr *instr = NULL; if (b->b_seen) return; b->b_seen = 1; if (b->b_next != NULL) dfs(c, b->b_next, a); for (i = 0; i < b->b_iused; i++) { instr = &b->b_instr[i]; if (instr->i_jrel || instr->i_jabs) dfs(c, instr->i_target, a); } a->a_postorder[a->a_nblocks++] = b; } static int stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth) { int i, target_depth, effect; struct instr *instr; if (b->b_seen || b->b_startdepth >= depth) return maxdepth; b->b_seen = 1; b->b_startdepth = depth; for (i = 0; i < b->b_iused; i++) { instr = &b->b_instr[i]; effect = PyCompile_OpcodeStackEffect(instr->i_opcode, instr->i_oparg); if (effect == PY_INVALID_STACK_EFFECT) { fprintf(stderr, "opcode = %d\n", instr->i_opcode); Py_FatalError("PyCompile_OpcodeStackEffect()"); } depth += effect; if (depth > maxdepth) maxdepth = depth; assert(depth >= 0); /* invalid code or bug in stackdepth() */ if (instr->i_jrel || instr->i_jabs) { target_depth = depth; if (instr->i_opcode == FOR_ITER) { target_depth = depth-2; } else if (instr->i_opcode == SETUP_FINALLY || instr->i_opcode == SETUP_EXCEPT) { target_depth = depth+3; if (target_depth > maxdepth) maxdepth = target_depth; } else if (instr->i_opcode == JUMP_IF_TRUE_OR_POP || instr->i_opcode == JUMP_IF_FALSE_OR_POP) depth = depth - 1; maxdepth = stackdepth_walk(c, instr->i_target, target_depth, maxdepth); if (instr->i_opcode == JUMP_ABSOLUTE || instr->i_opcode == JUMP_FORWARD) { goto out; /* remaining code is dead */ } } } if (b->b_next) maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth); out: b->b_seen = 0; return maxdepth; } /* Find the flow path that needs the largest stack. We assume that * cycles in the flow graph have no net effect on the stack depth. */ static int stackdepth(struct compiler *c) { basicblock *b, *entryblock; entryblock = NULL; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { b->b_seen = 0; b->b_startdepth = INT_MIN; entryblock = b; } if (!entryblock) return 0; return stackdepth_walk(c, entryblock, 0, 0); } static int assemble_init(struct assembler *a, int nblocks, int firstlineno) { memset(a, 0, sizeof(struct assembler)); a->a_lineno = firstlineno; a->a_bytecode = PyBytes_FromStringAndSize(NULL, DEFAULT_CODE_SIZE); if (!a->a_bytecode) return 0; a->a_lnotab = PyBytes_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE); if (!a->a_lnotab) return 0; if ((size_t)nblocks > PY_SIZE_MAX / sizeof(basicblock *)) { PyErr_NoMemory(); return 0; } a->a_postorder = (basicblock **)PyObject_Malloc( sizeof(basicblock *) * nblocks); if (!a->a_postorder) { PyErr_NoMemory(); return 0; } return 1; } static void assemble_free(struct assembler *a) { Py_XDECREF(a->a_bytecode); Py_XDECREF(a->a_lnotab); if (a->a_postorder) PyObject_Free(a->a_postorder); } /* Return the size of a basic block in bytes. */ static int instrsize(struct instr *instr) { if (!instr->i_hasarg) return 1; /* 1 byte for the opcode*/ if (instr->i_oparg > 0xffff) return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */ return 3; /* 1 (opcode) + 2 (oparg) */ } static int blocksize(basicblock *b) { int i; int size = 0; for (i = 0; i < b->b_iused; i++) size += instrsize(&b->b_instr[i]); return size; } /* Appends a pair to the end of the line number table, a_lnotab, representing the instruction's bytecode offset and line number. See Objects/lnotab_notes.txt for the description of the line number table. */ static int assemble_lnotab(struct assembler *a, struct instr *i) { int d_bytecode, d_lineno; Py_ssize_t len; unsigned char *lnotab; d_bytecode = a->a_offset - a->a_lineno_off; d_lineno = i->i_lineno - a->a_lineno; assert(d_bytecode >= 0); assert(d_lineno >= 0); if(d_bytecode == 0 && d_lineno == 0) return 1; if (d_bytecode > 255) { int j, nbytes, ncodes = d_bytecode / 255; nbytes = a->a_lnotab_off + 2 * ncodes; len = PyBytes_GET_SIZE(a->a_lnotab); if (nbytes >= len) { if ((len <= INT_MAX / 2) && (len * 2 < nbytes)) len = nbytes; else if (len <= INT_MAX / 2) len *= 2; else { PyErr_NoMemory(); return 0; } if (_PyBytes_Resize(&a->a_lnotab, len) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; for (j = 0; j < ncodes; j++) { *lnotab++ = 255; *lnotab++ = 0; } d_bytecode -= ncodes * 255; a->a_lnotab_off += ncodes * 2; } assert(d_bytecode <= 255); if (d_lineno > 255) { int j, nbytes, ncodes = d_lineno / 255; nbytes = a->a_lnotab_off + 2 * ncodes; len = PyBytes_GET_SIZE(a->a_lnotab); if (nbytes >= len) { if ((len <= INT_MAX / 2) && len * 2 < nbytes) len = nbytes; else if (len <= INT_MAX / 2) len *= 2; else { PyErr_NoMemory(); return 0; } if (_PyBytes_Resize(&a->a_lnotab, len) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; *lnotab++ = d_bytecode; *lnotab++ = 255; d_bytecode = 0; for (j = 1; j < ncodes; j++) { *lnotab++ = 0; *lnotab++ = 255; } d_lineno -= ncodes * 255; a->a_lnotab_off += ncodes * 2; } len = PyBytes_GET_SIZE(a->a_lnotab); if (a->a_lnotab_off + 2 >= len) { if (_PyBytes_Resize(&a->a_lnotab, len * 2) < 0) return 0; } lnotab = (unsigned char *) PyBytes_AS_STRING(a->a_lnotab) + a->a_lnotab_off; a->a_lnotab_off += 2; if (d_bytecode) { *lnotab++ = d_bytecode; *lnotab++ = d_lineno; } else { /* First line of a block; def stmt, etc. */ *lnotab++ = 0; *lnotab++ = d_lineno; } a->a_lineno = i->i_lineno; a->a_lineno_off = a->a_offset; return 1; } /* assemble_emit() Extend the bytecode with a new instruction. Update lnotab if necessary. */ static int assemble_emit(struct assembler *a, struct instr *i) { int size, arg = 0, ext = 0; Py_ssize_t len = PyBytes_GET_SIZE(a->a_bytecode); char *code; size = instrsize(i); if (i->i_hasarg) { arg = i->i_oparg; ext = arg >> 16; } if (i->i_lineno && !assemble_lnotab(a, i)) return 0; if (a->a_offset + size >= len) { if (len > PY_SSIZE_T_MAX / 2) return 0; if (_PyBytes_Resize(&a->a_bytecode, len * 2) < 0) return 0; } code = PyBytes_AS_STRING(a->a_bytecode) + a->a_offset; a->a_offset += size; if (size == 6) { assert(i->i_hasarg); *code++ = (char)EXTENDED_ARG; *code++ = ext & 0xff; *code++ = ext >> 8; arg &= 0xffff; } *code++ = i->i_opcode; if (i->i_hasarg) { assert(size == 3 || size == 6); *code++ = arg & 0xff; *code++ = arg >> 8; } return 1; } static void assemble_jump_offsets(struct assembler *a, struct compiler *c) { basicblock *b; int bsize, totsize, extended_arg_count = 0, last_extended_arg_count; int i; /* Compute the size of each block and fixup jump args. Replace block pointer with position in bytecode. */ do { totsize = 0; for (i = a->a_nblocks - 1; i >= 0; i--) { b = a->a_postorder[i]; bsize = blocksize(b); b->b_offset = totsize; totsize += bsize; } last_extended_arg_count = extended_arg_count; extended_arg_count = 0; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { bsize = b->b_offset; for (i = 0; i < b->b_iused; i++) { struct instr *instr = &b->b_instr[i]; /* Relative jumps are computed relative to the instruction pointer after fetching the jump instruction. */ bsize += instrsize(instr); if (instr->i_jabs) instr->i_oparg = instr->i_target->b_offset; else if (instr->i_jrel) { int delta = instr->i_target->b_offset - bsize; instr->i_oparg = delta; } else continue; if (instr->i_oparg > 0xffff) extended_arg_count++; } } /* XXX: This is an awful hack that could hurt performance, but on the bright side it should work until we come up with a better solution. The issue is that in the first loop blocksize() is called which calls instrsize() which requires i_oparg be set appropriately. There is a bootstrap problem because i_oparg is calculated in the second loop above. So we loop until we stop seeing new EXTENDED_ARGs. The only EXTENDED_ARGs that could be popping up are ones in jump instructions. So this should converge fairly quickly. */ } while (last_extended_arg_count != extended_arg_count); } static PyObject * dict_keys_inorder(PyObject *dict, Py_ssize_t offset) { PyObject *tuple, *k, *v; Py_ssize_t i, pos = 0, size = PyDict_Size(dict); tuple = PyTuple_New(size); if (tuple == NULL) return NULL; while (PyDict_Next(dict, &pos, &k, &v)) { i = PyLong_AS_LONG(v); /* The keys of the dictionary are tuples. (see compiler_add_o) The object we want is always first, though. */ k = PyTuple_GET_ITEM(k, 0); Py_INCREF(k); assert((i - offset) < size); assert((i - offset) >= 0); PyTuple_SET_ITEM(tuple, i - offset, k); } return tuple; } static int compute_code_flags(struct compiler *c) { PySTEntryObject *ste = c->u->u_ste; int flags = 0; Py_ssize_t n; if (ste->ste_type == FunctionBlock) { flags |= CO_NEWLOCALS; if (!ste->ste_unoptimized) flags |= CO_OPTIMIZED; if (ste->ste_nested) flags |= CO_NESTED; if (ste->ste_generator) flags |= CO_GENERATOR; if (ste->ste_varargs) flags |= CO_VARARGS; if (ste->ste_varkeywords) flags |= CO_VARKEYWORDS; } /* (Only) inherit compilerflags in PyCF_MASK */ flags |= (c->c_flags->cf_flags & PyCF_MASK); n = PyDict_Size(c->u->u_freevars); if (n < 0) return -1; if (n == 0) { n = PyDict_Size(c->u->u_cellvars); if (n < 0) return -1; if (n == 0) { flags |= CO_NOFREE; } } return flags; } static PyCodeObject * makecode(struct compiler *c, struct assembler *a) { PyObject *tmp; PyCodeObject *co = NULL; PyObject *consts = NULL; PyObject *names = NULL; PyObject *varnames = NULL; PyObject *name = NULL; PyObject *freevars = NULL; PyObject *cellvars = NULL; PyObject *bytecode = NULL; Py_ssize_t nlocals; int nlocals_int; int flags; int argcount, kwonlyargcount; tmp = dict_keys_inorder(c->u->u_consts, 0); if (!tmp) goto error; consts = PySequence_List(tmp); /* optimize_code requires a list */ Py_DECREF(tmp); names = dict_keys_inorder(c->u->u_names, 0); varnames = dict_keys_inorder(c->u->u_varnames, 0); if (!consts || !names || !varnames) goto error; cellvars = dict_keys_inorder(c->u->u_cellvars, 0); if (!cellvars) goto error; freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars)); if (!freevars) goto error; nlocals = PyDict_Size(c->u->u_varnames); assert(nlocals < INT_MAX); nlocals_int = Py_SAFE_DOWNCAST(nlocals, Py_ssize_t, int); flags = compute_code_flags(c); if (flags < 0) goto error; bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab); if (!bytecode) goto error; tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */ if (!tmp) goto error; Py_DECREF(consts); consts = tmp; argcount = Py_SAFE_DOWNCAST(c->u->u_argcount, Py_ssize_t, int); kwonlyargcount = Py_SAFE_DOWNCAST(c->u->u_kwonlyargcount, Py_ssize_t, int); co = PyCode_New(argcount, kwonlyargcount, nlocals_int, stackdepth(c), flags, bytecode, consts, names, varnames, freevars, cellvars, c->c_filename, c->u->u_name, c->u->u_firstlineno, a->a_lnotab); error: Py_XDECREF(consts); Py_XDECREF(names); Py_XDECREF(varnames); Py_XDECREF(name); Py_XDECREF(freevars); Py_XDECREF(cellvars); Py_XDECREF(bytecode); return co; } /* For debugging purposes only */ #if 0 static void dump_instr(const struct instr *i) { const char *jrel = i->i_jrel ? "jrel " : ""; const char *jabs = i->i_jabs ? "jabs " : ""; char arg[128]; *arg = '\0'; if (i->i_hasarg) sprintf(arg, "arg: %d ", i->i_oparg); fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", i->i_lineno, i->i_opcode, arg, jabs, jrel); } static void dump_basicblock(const basicblock *b) { const char *seen = b->b_seen ? "seen " : ""; const char *b_return = b->b_return ? "return " : ""; fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n", b->b_iused, b->b_startdepth, b->b_offset, seen, b_return); if (b->b_instr) { int i; for (i = 0; i < b->b_iused; i++) { fprintf(stderr, " [%02d] ", i); dump_instr(b->b_instr + i); } } } #endif static PyCodeObject * assemble(struct compiler *c, int addNone) { basicblock *b, *entryblock; struct assembler a; int i, j, nblocks; PyCodeObject *co = NULL; /* Make sure every block that falls off the end returns None. XXX NEXT_BLOCK() isn't quite right, because if the last block ends with a jump or return b_next shouldn't set. */ if (!c->u->u_curblock->b_return) { NEXT_BLOCK(c); if (addNone) ADDOP_O(c, LOAD_CONST, Py_None, consts); ADDOP(c, RETURN_VALUE); } nblocks = 0; entryblock = NULL; for (b = c->u->u_blocks; b != NULL; b = b->b_list) { nblocks++; entryblock = b; } /* Set firstlineno if it wasn't explicitly set. */ if (!c->u->u_firstlineno) { if (entryblock && entryblock->b_instr) c->u->u_firstlineno = entryblock->b_instr->i_lineno; else c->u->u_firstlineno = 1; } if (!assemble_init(&a, nblocks, c->u->u_firstlineno)) goto error; dfs(c, entryblock, &a); /* Can't modify the bytecode after computing jump offsets. */ assemble_jump_offsets(&a, c); /* Emit code in reverse postorder from dfs. */ for (i = a.a_nblocks - 1; i >= 0; i--) { b = a.a_postorder[i]; for (j = 0; j < b->b_iused; j++) if (!assemble_emit(&a, &b->b_instr[j])) goto error; } if (_PyBytes_Resize(&a.a_lnotab, a.a_lnotab_off) < 0) goto error; if (_PyBytes_Resize(&a.a_bytecode, a.a_offset) < 0) goto error; co = makecode(c, &a); error: assemble_free(&a); return co; } #undef PyAST_Compile PyAPI_FUNC(PyCodeObject *) PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags, PyArena *arena) { return PyAST_CompileEx(mod, filename, flags, -1, arena); }
lgpl-3.0