filename
stringlengths
3
9
code
stringlengths
4
1.05M
718378.c
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** ** This notice applies to any and all portions of this file * that are not between comment pairs USER CODE BEGIN and * USER CODE END. Other portions of this file, whether * inserted by the user or by software development tools * are owned by their respective copyright owners. * * COPYRIGHT(c) 2018 STMicroelectronics * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "tim.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include <stdio.h> #include "hcsr04.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ char buf[30]; uint8_t len; float Distance; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); static void MX_NVIC_Init(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); MX_TIM3_Init(); MX_USART2_UART_Init(); /* Initialize interrupts */ MX_NVIC_Init(); /* USER CODE BEGIN 2 */ HCSR04_Init(&htim3); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { HCSR04_Read(&Distance); len = sprintf(buf, "Distance: %.2f\n\r", Distance); HAL_UART_Transmit(&huart2, (uint8_t*)buf, len, 20); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ HAL_Delay(20); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /**Initializes the CPU, AHB and APB busses clocks */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSICalibrationValue = 0; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /**Initializes the CPU, AHB and APB busses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART2; PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } /**Configure the main internal regulator output voltage */ if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) { Error_Handler(); } } /** * @brief NVIC Configuration. * @retval None */ static void MX_NVIC_Init(void) { /* TIM3_IRQn interrupt configuration */ HAL_NVIC_SetPriority(TIM3_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM3_IRQn); } /* USER CODE BEGIN 4 */ void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) { HCSR04_TIM_IC_CaptureCallback(htim); } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(char *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
46890.c
/* * Copyright (c) 2012 Roman Arutyunyan */ #include "ngx_rtmp.h" static void ngx_rtmp_close_connection(ngx_connection_t *c); static u_char * ngx_rtmp_log_error(ngx_log_t *log, u_char *buf, size_t len); void ngx_rtmp_init_connection(ngx_connection_t *c) { ngx_uint_t i; ngx_rtmp_port_t *port; struct sockaddr *sa; struct sockaddr_in *sin; ngx_rtmp_in_addr_t *addr; ngx_rtmp_session_t *s; ngx_rtmp_addr_conf_t *addr_conf; #if (NGX_HAVE_INET6) struct sockaddr_in6 *sin6; ngx_rtmp_in6_addr_t *addr6; #endif /* find the server configuration for the address:port */ /* AF_INET only */ port = c->listening->servers; if (port->naddrs > 1) { /* * There are several addresses on this port and one of them * is the "*:port" wildcard so getsockname() is needed to determine * the server address. * * AcceptEx() already gave this address. */ if (ngx_connection_local_sockaddr(c, NULL, 0) != NGX_OK) { ngx_rtmp_close_connection(c); return; } sa = c->local_sockaddr; switch (sa->sa_family) { #if (NGX_HAVE_INET6) case AF_INET6: sin6 = (struct sockaddr_in6 *) sa; addr6 = port->addrs; /* the last address is "*" */ for (i = 0; i < port->naddrs - 1; i++) { if (ngx_memcmp(&addr6[i].addr6, &sin6->sin6_addr, 16) == 0) { break; } } addr_conf = &addr6[i].conf; break; #endif default: /* AF_INET */ sin = (struct sockaddr_in *) sa; addr = port->addrs; /* the last address is "*" */ for (i = 0; i < port->naddrs - 1; i++) { if (addr[i].addr == sin->sin_addr.s_addr) { break; } } addr_conf = &addr[i].conf; break; } } else { switch (c->local_sockaddr->sa_family) { #if (NGX_HAVE_INET6) case AF_INET6: addr6 = port->addrs; addr_conf = &addr6[0].conf; break; #endif default: /* AF_INET */ addr = port->addrs; addr_conf = &addr[0].conf; break; } } ngx_log_error(NGX_LOG_INFO, c->log, 0, "*%ui client connected", c->number, &c->addr_text); s = ngx_rtmp_init_session(c, addr_conf); if (s) { ngx_rtmp_handshake(s); } } ngx_rtmp_session_t * ngx_rtmp_init_session(ngx_connection_t *c, ngx_rtmp_addr_conf_t *addr_conf) { ngx_rtmp_session_t *s; ngx_rtmp_core_srv_conf_t *cscf; ngx_rtmp_log_ctx_t *ctx; s = ngx_pcalloc(c->pool, sizeof(ngx_rtmp_session_t) + sizeof(ngx_chain_t *) * ((ngx_rtmp_core_srv_conf_t *) addr_conf->ctx-> srv_conf[ngx_rtmp_core_module .ctx_index])->out_queue); if (s == NULL) { ngx_rtmp_close_connection(c); return NULL; } s->main_conf = addr_conf->ctx->main_conf; s->srv_conf = addr_conf->ctx->srv_conf; s->addr_text = &addr_conf->addr_text; c->data = s; s->connection = c; ctx = ngx_palloc(c->pool, sizeof(ngx_rtmp_log_ctx_t)); if (ctx == NULL) { ngx_rtmp_close_connection(c); return NULL; } ctx->client = &c->addr_text; ctx->session = s; c->log->connection = c->number; c->log->handler = ngx_rtmp_log_error; c->log->data = ctx; c->log->action = NULL; c->log_error = NGX_ERROR_INFO; s->ctx = ngx_pcalloc(c->pool, sizeof(void *) * ngx_rtmp_max_module); if (s->ctx == NULL) { ngx_rtmp_close_connection(c); return NULL; } cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module); s->out_queue = cscf->out_queue; s->out_cork = cscf->out_cork; s->in_streams = ngx_pcalloc(c->pool, sizeof(ngx_rtmp_stream_t) * cscf->max_streams); if (s->in_streams == NULL) { ngx_rtmp_close_connection(c); return NULL; } s->epoch = ngx_current_msec; s->timeout = cscf->timeout; ngx_rtmp_set_chunk_size(s, NGX_RTMP_DEFAULT_CHUNK_SIZE); if (ngx_rtmp_fire_event(s, NGX_RTMP_CONNECT, NULL, NULL) != NGX_OK) { ngx_rtmp_finalize_session(s); return NULL; } return s; } static u_char * ngx_rtmp_log_error(ngx_log_t *log, u_char *buf, size_t len) { u_char *p; ngx_rtmp_session_t *s; ngx_rtmp_log_ctx_t *ctx; if (log->action) { p = ngx_snprintf(buf, len, " while %s", log->action); len -= p - buf; buf = p; } ctx = log->data; p = ngx_snprintf(buf, len, ", client: %V", ctx->client); len -= p - buf; buf = p; s = ctx->session; if (s == NULL) { return p; } p = ngx_snprintf(buf, len, ", server: %V", s->addr_text); len -= p - buf; buf = p; return p; } static void ngx_rtmp_close_connection(ngx_connection_t *c) { ngx_pool_t *pool; ngx_log_debug0(NGX_LOG_DEBUG_RTMP, c->log, 0, "close connection"); pool = c->pool; ngx_close_connection(c); ngx_destroy_pool(pool); } static void ngx_rtmp_close_session_handler(ngx_event_t *e) { ngx_rtmp_session_t *s; ngx_connection_t *c; ngx_rtmp_core_srv_conf_t *cscf; s = e->data; c = s->connection; cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module); ngx_log_debug0(NGX_LOG_DEBUG_RTMP, c->log, 0, "close session"); if (s) { ngx_rtmp_fire_event(s, NGX_RTMP_DISCONNECT, NULL, NULL); if (s->ping_evt.timer_set) { ngx_del_timer(&s->ping_evt); } if (s->in_old_pool) { ngx_destroy_pool(s->in_old_pool); } if (s->in_pool) { ngx_destroy_pool(s->in_pool); } ngx_rtmp_free_handshake_buffers(s); while (s->out_pos != s->out_last) { ngx_rtmp_free_shared_chain(cscf, s->out[s->out_pos++]); s->out_pos %= s->out_queue; } } ngx_rtmp_close_connection(c); } void ngx_rtmp_finalize_session(ngx_rtmp_session_t *s) { ngx_event_t *e; ngx_connection_t *c; c = s->connection; ngx_log_debug0(NGX_LOG_DEBUG_RTMP, c->log, 0, "finalize session"); c->destroyed = 1; e = &s->close; e->data = s; e->handler = ngx_rtmp_close_session_handler; e->log = c->log; ngx_post_event(e, &ngx_posted_events); }
340490.c
int foo(void); int bar(void); int puzzle() { /* $begin puzzle */ int x = foo(); /* Arbitrary value */ int y = bar(); /* Arbitrary value */ unsigned ux = x; unsigned uy = y; /* $end puzzle */ return uy+ux; }
666803.c
/*- * Copyright (c) 2009 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Alistair Crooks ([email protected]) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 2005-2008 Nominet UK (www.nic.uk) * All rights reserved. * Contributors: Ben Laurie, Rachel Willmer. The Contributors have asserted * their moral rights under the UK Copyright Design and Patents Act 1988 to * be recorded as the authors of this copyright work. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** \file */ #include "config.h" #ifdef HAVE_SYS_CDEFS_H #include <sys/cdefs.h> #endif #if defined(__NetBSD__) __COPYRIGHT("@(#) Copyright (c) 2009 The NetBSD Foundation, Inc. All rights reserved."); __RCSID("$NetBSD: openssl_crypto.c,v 1.34 2018/02/05 23:56:01 christos Exp $"); #endif #ifdef HAVE_OPENSSL_DSA_H #include <openssl/dsa.h> #endif #ifdef HAVE_OPENSSL_RSA_H #include <openssl/rsa.h> #endif #ifdef HAVE_OPENSSL_ERR_H #include <openssl/err.h> #endif #include <openssl/pem.h> #include <openssl/evp.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #include "crypto.h" #include "keyring.h" #include "readerwriter.h" #include "netpgpdefs.h" #include "netpgpdigest.h" #include "packet.h" static void takeRSA(const RSA *orsa, pgp_rsa_pubkey_t *pk, pgp_rsa_seckey_t *sk) { const BIGNUM *n, *e, *d, *q, *p; #if OPENSSL_VERSION_NUMBER >= 0x10100000L RSA_get0_key(orsa, &n, &e, &d); RSA_get0_factors(orsa, &q, &p); #else n = orsa->n; e = orsa->e; d = orsa->d; p = orsa->p; q = orsa->q; #endif if (sk) { sk->d = BN_dup(d); sk->p = BN_dup(p); sk->q = BN_dup(q); } if (pk) { pk->n = BN_dup(n); pk->e = BN_dup(e); } } static RSA * makeRSA(const pgp_rsa_pubkey_t *pubkey, const pgp_rsa_seckey_t *seckey) { BIGNUM *n, *e, *d, *p, *q; RSA *orsa; orsa = RSA_new(); n = BN_dup(pubkey->n); e = BN_dup(pubkey->e); if (seckey) { d = BN_dup(seckey->d); p = BN_dup(seckey->p); q = BN_dup(seckey->q); } else { d = p = q = NULL; } #if OPENSSL_VERSION_NUMBER >= 0x10100000L RSA_set0_key(orsa, n, e, d); RSA_set0_factors(orsa, p, q); #else BN_free(orsa->n); BN_free(orsa->e); orsa->n = n; orsa->e = e; if (d) { BN_free(orsa->d); orsa->d = d; } if (p) { BN_free(orsa->p); orsa->p = p; } if (q) { BN_free(orsa->q); orsa->q = q; } #endif return orsa; } static DSA_SIG * makeDSA_SIG(const pgp_dsa_sig_t *sig) { DSA_SIG *osig; BIGNUM *r, *s; osig = DSA_SIG_new(); r = BN_dup(sig->r); s = BN_dup(sig->s); #if OPENSSL_VERSION_NUMBER >= 0x10100000L DSA_SIG_set0(osig, r, s); #else BN_free(osig->r); BN_free(osig->s); osig->r = r; osig->s = s; #endif return osig; } static DSA * makeDSA(const pgp_dsa_pubkey_t *dsa, const pgp_dsa_seckey_t *secdsa) { DSA *odsa; BIGNUM *p, *q, *g, *y, *x; odsa = DSA_new(); p = BN_dup(dsa->p); q = BN_dup(dsa->q); g = BN_dup(dsa->g); y = BN_dup(dsa->y); x = secdsa ? secdsa->x : NULL; #if OPENSSL_VERSION_NUMBER >= 0x10100000L DSA_set0_key(odsa, y, x); #else BN_free(odsa->p); BN_free(odsa->q); BN_free(odsa->g); BN_free(odsa->pub_key); odsa->p = p; odsa->q = q; odsa->g = g; odsa->pub_key = y; if (x) { BN_free(odsa->priv_key); odsa->priv_key = x; } #endif return odsa; } static void takeDSA(const DSA *odsa, pgp_dsa_seckey_t *sk) { const BIGNUM *x; #if OPENSSL_VERSION_NUMBER >= 0x10100000L DSA_get0_key(odsa, NULL, &x); #else x = odsa->priv_key; #endif sk->x = BN_dup(x); } static void test_seckey(const pgp_seckey_t *seckey) { RSA *test = makeRSA(&seckey->pubkey.key.rsa, &seckey->key.rsa); if (RSA_check_key(test) != 1) { (void) fprintf(stderr, "test_seckey: RSA_check_key failed\n"); } RSA_free(test); } static int md5_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "md5_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(MD5_CTX))) == NULL) { (void) fprintf(stderr, "md5_init: bad alloc\n"); return 0; } MD5_Init(hash->data); return 1; } static void md5_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { MD5_Update(hash->data, data, length); } static unsigned md5_finish(pgp_hash_t *hash, uint8_t *out) { MD5_Final(out, hash->data); free(hash->data); hash->data = NULL; return 16; } static const pgp_hash_t md5 = { PGP_HASH_MD5, MD5_DIGEST_LENGTH, "MD5", md5_init, md5_add, md5_finish, NULL }; /** \ingroup Core_Crypto \brief Initialise to MD5 \param hash Hash to initialise */ void pgp_hash_md5(pgp_hash_t *hash) { *hash = md5; } static int sha1_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "sha1_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(SHA_CTX))) == NULL) { (void) fprintf(stderr, "sha1_init: bad alloc\n"); return 0; } SHA1_Init(hash->data); return 1; } static void sha1_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha1_add", data, length); } SHA1_Update(hash->data, data, length); } static unsigned sha1_finish(pgp_hash_t *hash, uint8_t *out) { SHA1_Final(out, hash->data); if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha1_finish", out, PGP_SHA1_HASH_SIZE); } free(hash->data); hash->data = NULL; return PGP_SHA1_HASH_SIZE; } static const pgp_hash_t sha1 = { PGP_HASH_SHA1, PGP_SHA1_HASH_SIZE, "SHA1", sha1_init, sha1_add, sha1_finish, NULL }; /** \ingroup Core_Crypto \brief Initialise to SHA1 \param hash Hash to initialise */ void pgp_hash_sha1(pgp_hash_t *hash) { *hash = sha1; } static int sha256_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "sha256_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(SHA256_CTX))) == NULL) { (void) fprintf(stderr, "sha256_init: bad alloc\n"); return 0; } SHA256_Init(hash->data); return 1; } static void sha256_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha256_add", data, length); } SHA256_Update(hash->data, data, length); } static unsigned sha256_finish(pgp_hash_t *hash, uint8_t *out) { SHA256_Final(out, hash->data); if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha1_finish", out, SHA256_DIGEST_LENGTH); } free(hash->data); hash->data = NULL; return SHA256_DIGEST_LENGTH; } static const pgp_hash_t sha256 = { PGP_HASH_SHA256, SHA256_DIGEST_LENGTH, "SHA256", sha256_init, sha256_add, sha256_finish, NULL }; void pgp_hash_sha256(pgp_hash_t *hash) { *hash = sha256; } /* * SHA384 */ static int sha384_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "sha384_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(SHA512_CTX))) == NULL) { (void) fprintf(stderr, "sha384_init: bad alloc\n"); return 0; } SHA384_Init(hash->data); return 1; } static void sha384_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha384_add", data, length); } SHA384_Update(hash->data, data, length); } static unsigned sha384_finish(pgp_hash_t *hash, uint8_t *out) { SHA384_Final(out, hash->data); if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha384_finish", out, SHA384_DIGEST_LENGTH); } free(hash->data); hash->data = NULL; return SHA384_DIGEST_LENGTH; } static const pgp_hash_t sha384 = { PGP_HASH_SHA384, SHA384_DIGEST_LENGTH, "SHA384", sha384_init, sha384_add, sha384_finish, NULL }; void pgp_hash_sha384(pgp_hash_t *hash) { *hash = sha384; } /* * SHA512 */ static int sha512_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "sha512_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(SHA512_CTX))) == NULL) { (void) fprintf(stderr, "sha512_init: bad alloc\n"); return 0; } SHA512_Init(hash->data); return 1; } static void sha512_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha512_add", data, length); } SHA512_Update(hash->data, data, length); } static unsigned sha512_finish(pgp_hash_t *hash, uint8_t *out) { SHA512_Final(out, hash->data); if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha512_finish", out, SHA512_DIGEST_LENGTH); } free(hash->data); hash->data = NULL; return SHA512_DIGEST_LENGTH; } static const pgp_hash_t sha512 = { PGP_HASH_SHA512, SHA512_DIGEST_LENGTH, "SHA512", sha512_init, sha512_add, sha512_finish, NULL }; void pgp_hash_sha512(pgp_hash_t *hash) { *hash = sha512; } /* * SHA224 */ static int sha224_init(pgp_hash_t *hash) { if (hash->data) { (void) fprintf(stderr, "sha224_init: hash data non-null\n"); } if ((hash->data = calloc(1, sizeof(SHA256_CTX))) == NULL) { (void) fprintf(stderr, "sha256_init: bad alloc\n"); return 0; } SHA224_Init(hash->data); return 1; } static void sha224_add(pgp_hash_t *hash, const uint8_t *data, unsigned length) { if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha224_add", data, length); } SHA224_Update(hash->data, data, length); } static unsigned sha224_finish(pgp_hash_t *hash, uint8_t *out) { SHA224_Final(out, hash->data); if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "sha224_finish", out, SHA224_DIGEST_LENGTH); } free(hash->data); hash->data = NULL; return SHA224_DIGEST_LENGTH; } static const pgp_hash_t sha224 = { PGP_HASH_SHA224, SHA224_DIGEST_LENGTH, "SHA224", sha224_init, sha224_add, sha224_finish, NULL }; void pgp_hash_sha224(pgp_hash_t *hash) { *hash = sha224; } unsigned pgp_dsa_verify(const uint8_t *hash, size_t hash_length, const pgp_dsa_sig_t *sig, const pgp_dsa_pubkey_t *dsa) { unsigned qlen; DSA_SIG *osig = makeDSA_SIG(sig); DSA *odsa = makeDSA(dsa, NULL); int ret; if (pgp_get_debug_level(__FILE__)) { hexdump(stderr, "input hash", hash, hash_length); (void) fprintf(stderr, "Q=%d\n", BN_num_bytes(dsa->q)); } if ((qlen = (unsigned)BN_num_bytes(dsa->q)) < hash_length) { hash_length = qlen; } ret = DSA_do_verify(hash, (int)hash_length, osig, odsa); if (pgp_get_debug_level(__FILE__)) { (void) fprintf(stderr, "ret=%d\n", ret); } if (ret < 0) { (void) fprintf(stderr, "pgp_dsa_verify: DSA verification\n"); return 0; } DSA_free(odsa); DSA_SIG_free(osig); return (unsigned)ret; } /** \ingroup Core_Crypto \brief Recovers message digest from the signature \param out Where to write decrypted data to \param in Encrypted data \param length Length of encrypted data \param pubkey RSA public key \return size of recovered message digest */ int pgp_rsa_public_decrypt(uint8_t *out, const uint8_t *in, size_t length, const pgp_rsa_pubkey_t *pubkey) { RSA *orsa = makeRSA(pubkey, NULL); int ret; ret = RSA_public_decrypt((int)length, in, out, orsa, RSA_NO_PADDING); RSA_free(orsa); return ret; } /** \ingroup Core_Crypto \brief Signs data with RSA \param out Where to write signature \param in Data to sign \param length Length of data \param seckey RSA secret key \param pubkey RSA public key \return number of bytes decrypted */ int pgp_rsa_private_encrypt(uint8_t *out, const uint8_t *in, size_t length, const pgp_rsa_seckey_t *seckey, const pgp_rsa_pubkey_t *pubkey) { RSA *orsa = makeRSA(pubkey, seckey); int ret; if (seckey->d == NULL) { (void) fprintf(stderr, "orsa is not set\n"); return 0; } if (RSA_check_key(orsa) != 1) { (void) fprintf(stderr, "RSA_check_key is not set\n"); return 0; } /* end debug */ ret = RSA_private_encrypt((int)length, in, out, orsa, RSA_NO_PADDING); RSA_free(orsa); return ret; } /** \ingroup Core_Crypto \brief Decrypts RSA-encrypted data \param out Where to write the plaintext \param in Encrypted data \param length Length of encrypted data \param seckey RSA secret key \param pubkey RSA public key \return size of recovered plaintext */ int pgp_rsa_private_decrypt(uint8_t *out, const uint8_t *in, size_t length, const pgp_rsa_seckey_t *seckey, const pgp_rsa_pubkey_t *pubkey) { RSA *keypair = makeRSA(pubkey, seckey); int n; char errbuf[1024]; if (RSA_check_key(keypair) != 1) { (void) fprintf(stderr, "RSA_check_key is not set\n"); return 0; } /* end debug */ n = RSA_private_decrypt((int)length, in, out, keypair, RSA_NO_PADDING); if (pgp_get_debug_level(__FILE__)) { printf("pgp_rsa_private_decrypt: n=%d\n",n); } errbuf[0] = '\0'; if (n == -1) { unsigned long err = ERR_get_error(); ERR_error_string(err, &errbuf[0]); (void) fprintf(stderr, "openssl error : %s\n", errbuf); } RSA_free(keypair); return n; } /** \ingroup Core_Crypto \brief RSA-encrypts data \param out Where to write the encrypted data \param in Plaintext \param length Size of plaintext \param pubkey RSA Public Key */ int pgp_rsa_public_encrypt(uint8_t *out, const uint8_t *in, size_t length, const pgp_rsa_pubkey_t *pubkey) { RSA *orsa = makeRSA(pubkey, NULL); int n; /* printf("pgp_rsa_public_encrypt: length=%ld\n", length); */ /* printf("len: %ld\n", length); */ /* pgp_print_bn("n: ", orsa->n); */ /* pgp_print_bn("e: ", orsa->e); */ n = RSA_public_encrypt((int)length, in, out, orsa, RSA_NO_PADDING); if (n == -1) { BIO *fd_out; fd_out = BIO_new_fd(fileno(stderr), BIO_NOCLOSE); ERR_print_errors(fd_out); } RSA_free(orsa); return n; } /** \ingroup Core_Crypto \brief Finalise openssl \note Would usually call pgp_finish() instead \sa pgp_finish() */ void pgp_crypto_finish(void) { CRYPTO_cleanup_all_ex_data(); #if OPENSSL_VERSION_NUMBER < 0x10100000L ERR_remove_state((unsigned long)0); #endif } /** \ingroup Core_Hashes \brief Get Hash name \param hash Hash struct \return Hash name */ const char * pgp_text_from_hash(pgp_hash_t *hash) { return hash->name; } /** \ingroup HighLevel_KeyGenerate \brief Generates an RSA keypair \param numbits Modulus size \param e Public Exponent \param keydata Pointer to keydata struct to hold new key \return 1 if key generated successfully; otherwise 0 \note It is the caller's responsibility to call pgp_keydata_free(keydata) */ static unsigned rsa_generate_keypair(pgp_key_t *keydata, const int numbits, const unsigned long e, const char *hashalg, const char *cipher) { pgp_seckey_t *seckey; RSA *rsa; BN_CTX *ctx; pgp_output_t *output; pgp_memory_t *mem; BIGNUM *bne; pgp_rsa_pubkey_t *pk; pgp_rsa_seckey_t *sk; ctx = BN_CTX_new(); pgp_keydata_init(keydata, PGP_PTAG_CT_SECRET_KEY); seckey = pgp_get_writable_seckey(keydata); pk = &seckey->pubkey.key.rsa; sk = &seckey->key.rsa; /* generate the key pair */ bne = BN_new(); BN_set_word(bne, e); rsa = RSA_new(); RSA_generate_key_ex(rsa, numbits, bne, NULL); BN_free(bne); /* populate pgp key from ssl key */ takeRSA(rsa, pk, sk); seckey->pubkey.version = PGP_V4; seckey->pubkey.birthtime = time(NULL); seckey->pubkey.days_valid = 0; seckey->pubkey.alg = PGP_PKA_RSA; seckey->s2k_usage = PGP_S2KU_ENCRYPTED_AND_HASHED; seckey->s2k_specifier = PGP_S2KS_SALTED; /* seckey->s2k_specifier=PGP_S2KS_SIMPLE; */ if ((seckey->hash_alg = pgp_str_to_hash_alg(hashalg)) == PGP_HASH_UNKNOWN) { seckey->hash_alg = PGP_HASH_SHA1; } seckey->alg = pgp_str_to_cipher(cipher); seckey->octetc = 0; seckey->checksum = 0; sk->u = BN_mod_inverse(NULL, sk->p, sk->q, ctx); if (sk->u == NULL) { (void) fprintf(stderr, "seckey->key.rsa.u is NULL\n"); return 0; } BN_CTX_free(ctx); RSA_free(rsa); pgp_keyid(keydata->sigid, PGP_KEY_ID_SIZE, &keydata->key.seckey.pubkey, seckey->hash_alg); pgp_fingerprint(&keydata->sigfingerprint, &keydata->key.seckey.pubkey, seckey->hash_alg); /* Generate checksum */ output = NULL; mem = NULL; pgp_setup_memory_write(&output, &mem, 128); pgp_push_checksum_writer(output, seckey); switch (seckey->pubkey.alg) { case PGP_PKA_DSA: return pgp_write_mpi(output, seckey->key.dsa.x); case PGP_PKA_RSA: case PGP_PKA_RSA_ENCRYPT_ONLY: case PGP_PKA_RSA_SIGN_ONLY: if (!pgp_write_mpi(output, seckey->key.rsa.d) || !pgp_write_mpi(output, seckey->key.rsa.p) || !pgp_write_mpi(output, seckey->key.rsa.q) || !pgp_write_mpi(output, seckey->key.rsa.u)) { return 0; } break; case PGP_PKA_ELGAMAL: return pgp_write_mpi(output, seckey->key.elgamal.x); default: (void) fprintf(stderr, "Bad seckey->pubkey.alg\n"); return 0; } /* close rather than pop, since its the only one on the stack */ pgp_writer_close(output); pgp_teardown_memory_write(output, mem); /* should now have checksum in seckey struct */ /* test */ if (pgp_get_debug_level(__FILE__)) { test_seckey(seckey); } return 1; } /** \ingroup HighLevel_KeyGenerate \brief Creates a self-signed RSA keypair \param numbits Modulus size \param e Public Exponent \param userid User ID \return The new keypair or NULL \note It is the caller's responsibility to call pgp_keydata_free(keydata) \sa rsa_generate_keypair() \sa pgp_keydata_free() */ pgp_key_t * pgp_rsa_new_selfsign_key(const int numbits, const unsigned long e, uint8_t *userid, const char *hashalg, const char *cipher) { pgp_key_t *keydata; keydata = pgp_keydata_new(); if (!rsa_generate_keypair(keydata, numbits, e, hashalg, cipher) || !pgp_add_selfsigned_userid(keydata, userid)) { pgp_keydata_free(keydata); return NULL; } return keydata; } DSA_SIG * pgp_dsa_sign(uint8_t *hashbuf, unsigned hashsize, const pgp_dsa_seckey_t *secdsa, const pgp_dsa_pubkey_t *pubdsa) { DSA_SIG *dsasig; DSA *odsa = makeDSA(pubdsa, secdsa); dsasig = DSA_do_sign(hashbuf, (int)hashsize, odsa); DSA_free(odsa); return dsasig; } int openssl_read_pem_seckey(const char *f, pgp_key_t *key, const char *type, int verbose) { FILE *fp; char prompt[BUFSIZ]; char *pass; DSA *dsa; RSA *rsa; int ok; OpenSSL_add_all_algorithms(); if ((fp = fopen(f, "r")) == NULL) { if (verbose) { (void) fprintf(stderr, "can't open '%s'\n", f); } return 0; } ok = 1; if (strcmp(type, "ssh-rsa") == 0) { if ((rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) { (void) snprintf(prompt, sizeof(prompt), "netpgp PEM %s passphrase: ", f); do { pass = getpass(prompt); rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, pass); } while (rsa == NULL); } takeRSA(rsa, NULL, &key->key.seckey.key.rsa); } else if (strcmp(type, "ssh-dss") == 0) { if ((dsa = PEM_read_DSAPrivateKey(fp, NULL, NULL, NULL)) == NULL) { ok = 0; } else { takeDSA(dsa, &key->key.seckey.key.dsa); } } else { ok = 0; } (void) fclose(fp); return ok; } /* * Decide the number of bits in the random componont k * * It should be in the same range as p for signing (which * is deprecated), but can be much smaller for encrypting. * * Until I research it further, I just mimic gpg behaviour. * It has a special mapping table, for values <= 5120, * above that it uses 'arbitrary high number'. Following * algorihm hovers 10-70 bits above gpg values. And for * larger p, it uses gpg's algorihm. * * The point is - if k gets large, encryption will be * really slow. It does not matter for decryption. */ static int decide_k_bits(int p_bits) { return (p_bits <= 5120) ? p_bits / 10 + 160 : (p_bits / 8 + 200) * 3 / 2; } int pgp_elgamal_public_encrypt(uint8_t *g_to_k, uint8_t *encm, const uint8_t *in, size_t size, const pgp_elgamal_pubkey_t *pubkey) { int ret = 0; int k_bits; BIGNUM *m; BIGNUM *p; BIGNUM *g; BIGNUM *y; BIGNUM *k; BIGNUM *yk; BIGNUM *c1; BIGNUM *c2; BN_CTX *tmp; m = BN_bin2bn(in, (int)size, NULL); p = pubkey->p; g = pubkey->g; y = pubkey->y; k = BN_new(); yk = BN_new(); c1 = BN_new(); c2 = BN_new(); tmp = BN_CTX_new(); if (!m || !p || !g || !y || !k || !yk || !c1 || !c2 || !tmp) { goto done; } /* * generate k */ k_bits = decide_k_bits(BN_num_bits(p)); if (!BN_rand(k, k_bits, 0, 0)) { goto done; } /* * c1 = g^k c2 = m * y^k */ if (!BN_mod_exp(c1, g, k, p, tmp)) { goto done; } if (!BN_mod_exp(yk, y, k, p, tmp)) { goto done; } if (!BN_mod_mul(c2, m, yk, p, tmp)) { goto done; } /* result */ BN_bn2bin(c1, g_to_k); ret = BN_num_bytes(c1); /* c1 = g^k */ BN_bn2bin(c2, encm); ret += BN_num_bytes(c2); /* c2 = m * y^k */ done: if (tmp) { BN_CTX_free(tmp); } if (c2) { BN_clear_free(c2); } if (c1) { BN_clear_free(c1); } if (yk) { BN_clear_free(yk); } if (k) { BN_clear_free(k); } if (g) { BN_clear_free(g); } return ret; } int pgp_elgamal_private_decrypt(uint8_t *out, const uint8_t *g_to_k, const uint8_t *in, size_t length, const pgp_elgamal_seckey_t *seckey, const pgp_elgamal_pubkey_t *pubkey) { BIGNUM *bndiv; BIGNUM *c1x; BN_CTX *tmp; BIGNUM *c1; BIGNUM *c2; BIGNUM *p; BIGNUM *x; BIGNUM *m; int ret; ret = 0; /* c1 and c2 are in g_to_k and in, respectively*/ c1 = BN_bin2bn(g_to_k, (int)length, NULL); c2 = BN_bin2bn(in, (int)length, NULL); /* other bits */ p = pubkey->p; x = seckey->x; c1x = BN_new(); bndiv = BN_new(); m = BN_new(); tmp = BN_CTX_new(); if (!c1 || !c2 || !p || !x || !c1x || !bndiv || !m || !tmp) { goto done; } /* * m = c2 / (c1^x) */ if (!BN_mod_exp(c1x, c1, x, p, tmp)) { goto done; } if (!BN_mod_inverse(bndiv, c1x, p, tmp)) { goto done; } if (!BN_mod_mul(m, c2, bndiv, p, tmp)) { goto done; } /* result */ ret = BN_bn2bin(m, out); done: if (tmp) { BN_CTX_free(tmp); } if (m) { BN_clear_free(m); } if (bndiv) { BN_clear_free(bndiv); } if (c1x) { BN_clear_free(c1x); } if (x) { BN_clear_free(x); } if (p) { BN_clear_free(p); } if (c1) { BN_clear_free(c1); } if (c2) { BN_clear_free(c2); } return ret; }
489213.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int Find(char* str1, char* str2) { int n, i, j, k,c; if (str1[0] == '\0' || str2[0] == '\0') return -1; n= (int)strlen(str1); k = 0; for (i = 0; i < n; i++){ c = 0; for (j = i; j < n; j++){ if (str1[j] == '\0' || str2[c] == '\0') break; if (str1[j] == str2[c]){ c++; } else{ c = 0; break; }; }; if (c > k) k = c; }; return k; } int main() { int n, i; scanf("%d", &n); char** mass; char* shortest = (char*)calloc(1024,sizeof(char)); mass = (char**)malloc(n*sizeof(char*)); for (i = 0; i < n; i++){ mass[i] = (char*)calloc(1024,sizeof(char)); scanf("%s", mass[i]); }; int a = 0, b = 0, k, j, maxl, l; for (k = 0; k < n; k++){ maxl = -1; for (i = 0; i < n; i++){ for (j = 0; j < n; j++){ if (i == j) continue; l = Find(mass[i], mass[j]); if (l > maxl){ maxl = l; a = i; b = j; }; }; }; if (maxl >= 0){ mass[a][strlen(mass[a]) - maxl] = '\0'; strcat(mass[a], mass[b]); mass[b][0] = '\0'; shortest = mass[a]; }; }; printf("%d\n", strlen(shortest)); for (i = 0; i < n; i++) { free(mass[i]); } free(mass); free(shortest); return 0; }
127184.c
void main() { char b; b = 1 || 2 || 3 || 4; assert(b == 1, "b must be 1"); }
386518.c
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2004-2007 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2018 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2008 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2012 Oak Ridge National Laboratory. All rights reserved. * Copyright (c) 2013 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2015-2020 Research Organization for Information Science * and Technology (RIST). All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include <stdio.h> #include "ompi/mpi/c/bindings.h" #include "ompi/runtime/params.h" #include "ompi/communicator/communicator.h" #include "ompi/errhandler/errhandler.h" #include "ompi/datatype/ompi_datatype.h" #include "ompi/mca/coll/base/coll_base_util.h" #include "ompi/memchecker.h" #include "ompi/runtime/ompi_spc.h" #if OMPI_BUILD_MPI_PROFILING #if OPAL_HAVE_WEAK_SYMBOLS #pragma weak MPI_Iallgather = PMPI_Iallgather #endif #define MPI_Iallgather PMPI_Iallgather #endif static const char FUNC_NAME[] = "MPI_Iallgather"; int MPI_Iallgather(const void *sendbuf, int sendcount, MPI_Datatype sendtype, void *recvbuf, int recvcount, MPI_Datatype recvtype, MPI_Comm comm, MPI_Request *request) { int err; SPC_RECORD(OMPI_SPC_IALLGATHER, 1); MEMCHECKER( int rank; ptrdiff_t ext; rank = ompi_comm_rank(comm); ompi_datatype_type_extent(recvtype, &ext); memchecker_datatype(recvtype); memchecker_comm(comm); /* check whether the actual send buffer is defined. */ if (MPI_IN_PLACE == sendbuf) { memchecker_call(&opal_memchecker_base_isdefined, (char *)(recvbuf)+rank*recvcount*ext, recvcount, recvtype); } else { memchecker_datatype(sendtype); memchecker_call(&opal_memchecker_base_isdefined, sendbuf, sendcount, sendtype); } /* check whether the receive buffer is addressable. */ memchecker_call(&opal_memchecker_base_isaddressable, recvbuf, recvcount, recvtype); ); if (MPI_PARAM_CHECK) { /* Unrooted operation -- same checks for all ranks on both intracommunicators and intercommunicators */ err = MPI_SUCCESS; OMPI_ERR_INIT_FINALIZE(FUNC_NAME); if (ompi_comm_invalid(comm)) { OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_COMM, FUNC_NAME); } else if (MPI_DATATYPE_NULL == recvtype || NULL == recvtype) { err = MPI_ERR_TYPE; } else if (recvcount < 0) { err = MPI_ERR_COUNT; } else if ((MPI_IN_PLACE == sendbuf && OMPI_COMM_IS_INTER(comm)) || MPI_IN_PLACE == recvbuf) { return OMPI_ERRHANDLER_INVOKE(comm, MPI_ERR_ARG, FUNC_NAME); } else if (MPI_IN_PLACE != sendbuf) { OMPI_CHECK_DATATYPE_FOR_SEND(err, sendtype, sendcount); } OMPI_ERRHANDLER_CHECK(err, comm, err, FUNC_NAME); } OPAL_CR_ENTER_LIBRARY(); /* Invoke the coll component to perform the back-end operation */ err = comm->c_coll->coll_iallgather(sendbuf, sendcount, sendtype, recvbuf, recvcount, recvtype, comm, request, comm->c_coll->coll_iallgather_module); if (OPAL_LIKELY(OMPI_SUCCESS == err)) { ompi_coll_base_retain_datatypes(*request, (MPI_IN_PLACE==sendbuf)?NULL:sendtype, recvtype); } OMPI_ERRHANDLER_RETURN(err, comm, err, FUNC_NAME); }
580266.c
/* Copyright(c) 2010-2017 Intel Corporation. Copyright(c) 2016-2018 Viosoft 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <rte_ip.h> #include <rte_mbuf.h> #include <rte_sched.h> #include "prox_lua.h" #include "prox_lua_types.h" #include "etypes.h" #include "stats.h" #include "task_init.h" #include "lconf.h" #include "task_base.h" #include "defines.h" #include "prefetch.h" #include "handle_qos.h" #include "log.h" #include "quit.h" #include "qinq.h" #include "prox_cfg.h" #include "prox_shared.h" struct task_qos { struct task_base base; struct rte_sched_port *sched_port; uint16_t *user_table; uint8_t *dscp; uint32_t nb_buffered_pkts; uint8_t runtime_flags; }; uint32_t task_qos_n_pkts_buffered(struct task_base *tbase) { struct task_qos *task = (struct task_qos *)tbase; return task->nb_buffered_pkts; } static inline int handle_qos_bulk(struct task_base *tbase, struct rte_mbuf **mbufs, uint16_t n_pkts) { struct task_qos *task = (struct task_qos *)tbase; int ret = 0; if (n_pkts) { if (task->runtime_flags & TASK_CLASSIFY) { uint16_t j; #ifdef PROX_PREFETCH_OFFSET for (j = 0; j < PROX_PREFETCH_OFFSET && j < n_pkts; ++j) { prefetch_nta(mbufs[j]); } for (j = 1; j < PROX_PREFETCH_OFFSET && j < n_pkts; ++j) { prefetch_nta(rte_pktmbuf_mtod(mbufs[j - 1], void *)); } #endif uint8_t queue = 0; uint8_t tc = 0; for (j = 0; j + PREFETCH_OFFSET < n_pkts; ++j) { prefetch_nta(mbufs[j + PREFETCH_OFFSET]); prefetch_nta(rte_pktmbuf_mtod(mbufs[j + PREFETCH_OFFSET - 1], void *)); const struct qinq_hdr *pqinq = rte_pktmbuf_mtod(mbufs[j], const struct qinq_hdr *); uint32_t qinq = PKT_TO_LUTQINQ(pqinq->svlan.vlan_tci, pqinq->cvlan.vlan_tci); if (pqinq->ether_type == ETYPE_IPv4) { const struct ipv4_hdr *ipv4_hdr = (const struct ipv4_hdr *)(pqinq + 1); queue = task->dscp[ipv4_hdr->type_of_service >> 2] & 0x3; tc = task->dscp[ipv4_hdr->type_of_service >> 2] >> 2; } else { // Keep queue and tc = 0 for other packet types like ARP queue = 0; tc = 0; } rte_sched_port_pkt_write(mbufs[j], 0, task->user_table[qinq], tc, queue, 0); } #ifdef PROX_PREFETCH_OFFSET prefetch_nta(rte_pktmbuf_mtod(mbufs[n_pkts - 1], void *)); for (; j < n_pkts; ++j) { const struct qinq_hdr *pqinq = rte_pktmbuf_mtod(mbufs[j], const struct qinq_hdr *); uint32_t qinq = PKT_TO_LUTQINQ(pqinq->svlan.vlan_tci, pqinq->cvlan.vlan_tci); if (pqinq->ether_type == ETYPE_IPv4) { const struct ipv4_hdr *ipv4_hdr = (const struct ipv4_hdr *)(pqinq + 1); queue = task->dscp[ipv4_hdr->type_of_service >> 2] & 0x3; tc = task->dscp[ipv4_hdr->type_of_service >> 2] >> 2; } else { // Keep queue and tc = 0 for other packet types like ARP queue = 0; tc = 0; } rte_sched_port_pkt_write(mbufs[j], 0, task->user_table[qinq], tc, queue, 0); } #endif } int16_t ret = rte_sched_port_enqueue(task->sched_port, mbufs, n_pkts); task->nb_buffered_pkts += ret; TASK_STATS_ADD_IDLE(&task->base.aux->stats, n_pkts - ret); } if (task->nb_buffered_pkts) { n_pkts = rte_sched_port_dequeue(task->sched_port, mbufs, 32); if (likely(n_pkts)) { task->nb_buffered_pkts -= n_pkts; ret = task->base.tx_pkt(&task->base, mbufs, n_pkts, NULL); } } return ret; } static void init_task_qos(struct task_base *tbase, struct task_args *targ) { struct task_qos *task = (struct task_qos *)tbase; const int socket_id = rte_lcore_to_socket_id(targ->lconf->id); char name[64]; snprintf(name, sizeof(name), "qos_sched_port_%u_%u", targ->lconf->id, 0); targ->qos_conf.port_params.name = name; targ->qos_conf.port_params.socket = socket_id; task->sched_port = rte_sched_port_config(&targ->qos_conf.port_params); PROX_PANIC(task->sched_port == NULL, "failed to create sched_port"); plog_info("number of pipes: %d\n\n", targ->qos_conf.port_params.n_pipes_per_subport); int err = rte_sched_subport_config(task->sched_port, 0, targ->qos_conf.subport_params); PROX_PANIC(err != 0, "Failed setting up sched_port subport, error: %d", err); /* only single subport and single pipe profile is supported */ for (uint32_t pipe = 0; pipe < targ->qos_conf.port_params.n_pipes_per_subport; ++pipe) { err = rte_sched_pipe_config(task->sched_port, 0 , pipe, 0); PROX_PANIC(err != 0, "failed setting up sched port pipe, error: %d", err); } task->runtime_flags = targ->runtime_flags; task->user_table = prox_sh_find_socket(socket_id, "user_table"); if (!task->user_table) { PROX_PANIC(!strcmp(targ->user_table, ""), "No user table defined\n"); int ret = lua_to_user_table(prox_lua(), GLOBAL, targ->user_table, socket_id, &task->user_table); PROX_PANIC(ret, "Failed to create user table from config:\n%s\n", get_lua_to_errors()); prox_sh_add_socket(socket_id, "user_table", task->user_table); } if (task->runtime_flags & TASK_CLASSIFY) { PROX_PANIC(!strcmp(targ->dscp, ""), "DSCP table not specified\n"); task->dscp = prox_sh_find_socket(socket_id, targ->dscp); if (!task->dscp) { int ret = lua_to_dscp(prox_lua(), GLOBAL, targ->dscp, socket_id, &task->dscp); PROX_PANIC(ret, "Failed to create dscp table from config:\n%s\n", get_lua_to_errors()); prox_sh_add_socket(socket_id, targ->dscp, task->dscp); } } } static struct task_init task_init_qos = { .mode_str = "qos", .init = init_task_qos, .handle = handle_qos_bulk, .flag_features = TASK_FEATURE_CLASSIFY | TASK_FEATURE_NEVER_DISCARDS | TASK_FEATURE_MULTI_RX | TASK_FEATURE_ZERO_RX, .size = sizeof(struct task_qos) }; __attribute__((constructor)) static void reg_task_qos(void) { reg_task(&task_init_qos); }
832158.c
#include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include <errno.h> #include "eon.h" struct Data { char *bytes; size_t size; }; static size_t write_to_memory(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct Data *mem = (struct Data *)userp; mem->bytes = realloc(mem->bytes, mem->size + realsize + 1); if (mem->bytes == NULL) { // out of memory! return 0; } memcpy(&(mem->bytes[mem->size]), contents, realsize); mem->size += realsize; mem->bytes[mem->size] = 0; return realsize; } #ifdef WITH_LIBCURL #include <curl/curl.h> const char * util_get_url(const char * url) { CURL *curl; CURLcode res; struct Data body; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (!curl) { curl_global_cleanup(); return NULL; } body.bytes = malloc(1); // start with 1, will be grown as needed body.size = 0; // no data as this point curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_VERBOSE, 0); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_USERAGENT, "Eon/1.0"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_memory); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&body); res = curl_easy_perform(curl); // send request if (res != CURLE_OK) { fprintf(stderr, "Couldn't get %s: %s\n", url, curl_easy_strerror(res)); return NULL; } curl_easy_cleanup(curl); curl_global_cleanup(); return body.bytes; } #else const char * util_get_url(const char * url) { int status; int len = strlen(url) + 29; char cmd[len]; snprintf(cmd, len, "wget -S -O - '%s' 2> /dev/null", url); FILE *fp; fp = popen(cmd, "r"); if (fp == NULL) return NULL; struct Data body; body.bytes = malloc(1); // start with 1, will be grown as needed body.size = 0; // no data as this point size_t chunk = 1024; char buf[chunk]; while (fgets(buf, sizeof(buf), fp) != NULL) { write_to_memory(buf, strlen(buf), 1, &body); } status = pclose(fp); // if (status == -1) // something went wrong return body.size == 0 ? NULL : body.bytes; } #endif // WITH_LIBCURL size_t util_download_file(const char * url, const char * target) { const char * data = util_get_url(url); if (!data) return -1; FILE *output; output = fopen(target, "wb"); if (!output) return -1; size_t written = fwrite(data, sizeof(char), strlen(data), output); fclose(output); return written; } // Run a shell command, optionally feeding stdin, collecting stdout // Specify timeout_s=-1 for no timeout int util_shell_exec(editor_t* editor, char* cmd, long timeout_s, char* input, size_t input_len, char* opt_shell, char** optret_output, size_t* optret_output_len) { // TODO clean this crap up int rv; int do_read; int do_write; int readfd; int writefd; ssize_t rc; ssize_t nbytes; fd_set readfds; struct timeval timeout; struct timeval* timeoutptr; pid_t pid; str_t readbuf = {0}; readbuf.inc = -2; // double capacity on each allocation do_read = optret_output != NULL ? 1 : 0; do_write = input && input_len > 0 ? 1 : 0; readfd = -1; writefd = -1; pid = -1; nbytes = 0; rv = EON_OK; if (do_read) { *optret_output = NULL; *optret_output_len = 0; } // Open cmd if (!util_popen2(cmd, opt_shell, do_read ? &readfd : NULL, do_write ? &writefd : NULL, &pid)) { EON_RETURN_ERR(editor, "Failed to exec shell cmd: %s", cmd); } // Read-write loop do { // Write to shell cmd if input is remaining if (do_write && writefd >= 0) { rc = write(writefd, input, input_len); if (rc > 0) { input += rc; input_len -= rc; if (input_len < 1) { close(writefd); writefd = -1; } } else { // write err EON_SET_ERR(editor, "write error: %s", strerror(errno)); rv = EON_ERR; break; } } // Read shell cmd, timing out after timeout_sec if (do_read) { if (timeout_s >= 0) { timeout.tv_sec = timeout_s; timeout.tv_usec = 0; timeoutptr = &timeout; } else { timeoutptr = NULL; } FD_ZERO(&readfds); FD_SET(readfd, &readfds); rc = select(readfd + 1, &readfds, NULL, NULL, timeoutptr); if (rc < 0) { // Err on select EON_SET_ERR(editor, "select error: %s", strerror(errno)); rv = EON_ERR; break; } else if (rc == 0) { // Timed out rv = EON_ERR; break; } else { // Read a kilobyte of data str_ensure_cap(&readbuf, readbuf.len + 1024); nbytes = read(readfd, readbuf.data + readbuf.len, 1024); if (nbytes < 0) { // read err or EAGAIN/EWOULDBLOCK EON_SET_ERR(editor, "read error: %s", strerror(errno)); rv = EON_ERR; break; } else if (nbytes > 0) { // Got data readbuf.len += nbytes; } } } } while (nbytes > 0); // until EOF // Close pipes and reap child proc if (readfd >= 0) close(readfd); if (writefd >= 0) close(writefd); waitpid(pid, NULL, do_read ? WNOHANG : 0); if (do_read) { *optret_output = readbuf.data; *optret_output_len = readbuf.len; } return rv; } // Like popen, but more control over pipes. Returns 1 on success, 0 on failure. int util_popen2(char* cmd, char* opt_shell, int* optret_fdread, int* optret_fdwrite, pid_t* optret_pid) { pid_t pid; int do_read; int do_write; int pout[2]; int pin[2]; // Set r/w do_read = optret_fdread != NULL ? 1 : 0; do_write = optret_fdwrite != NULL ? 1 : 0; // Set shell opt_shell = opt_shell ? opt_shell : "sh"; // Make pipes if (do_read) if (pipe(pout)) return 0; if (do_write) if (pipe(pin)) return 0; // Fork pid = fork(); if (pid < 0) { // Fork failed return 0; } else if (pid == 0) { // Child if (do_read) { close(pout[0]); dup2(pout[1], STDOUT_FILENO); close(pout[1]); } if (do_write) { close(pin[1]); dup2(pin[0], STDIN_FILENO); close(pin[0]); } setsid(); execlp(opt_shell, opt_shell, "-c", cmd, NULL); exit(EXIT_FAILURE); } // Parent if (do_read) { close(pout[1]); *optret_fdread = pout[0]; } if (do_write) { close(pin[0]); *optret_fdwrite = pin[1]; } if (optret_pid) *optret_pid = pid; return 1; } // Return paired bracket if ch is a bracket, else return 0 int util_get_bracket_pair(uint32_t ch, int* optret_is_closing) { switch (ch) { case '[': if (optret_is_closing) *optret_is_closing = 0; return ']'; case '(': if (optret_is_closing) *optret_is_closing = 0; return ')'; case '{': if (optret_is_closing) *optret_is_closing = 0; return '}'; case ']': if (optret_is_closing) *optret_is_closing = 1; return '['; case ')': if (optret_is_closing) *optret_is_closing = 1; return '('; case '}': if (optret_is_closing) *optret_is_closing = 1; return '{'; default: return 0; } return 0; } // Return 1 if path is file int util_is_file(char* path, char* opt_mode, FILE** optret_file) { struct stat sb; if (stat(path, &sb) != 0 || !S_ISREG(sb.st_mode)) return 0; if (opt_mode && optret_file) { *optret_file = fopen(path, opt_mode); if (!*optret_file) return 0; } return 1; } // Return 1 if path is dir int util_is_dir(char* path) { struct stat sb; if (stat(path, &sb) != 0 || !S_ISDIR(sb.st_mode)) return 0; return 1; } char * util_read_file(char *filename) { char *buf = NULL; long length; int bytes; FILE *fp = fopen(filename, "rb"); if (fp) { fseek(fp, 0, SEEK_END); length = ftell(fp); fseek(fp, 0, SEEK_SET); buf = malloc(length); if (buf) { bytes = fread(buf, 1, length, fp); fclose(fp); return buf; } fclose(fp); return NULL; } return NULL; } // Attempt to replace leading ~/ with $HOME void util_expand_tilde(char* path, int path_len, char** ret_path) { char* homedir; char* newpath; if (!util_is_file("~", NULL, NULL) && strncmp(path, "~/", 2) == 0 && (homedir = getenv("HOME")) != NULL) { newpath = malloc(strlen(homedir) + 1 + (path_len - 2) + 1); sprintf(newpath, "%s/%.*s", homedir, path_len - 2, path + 2); *ret_path = newpath; return; } *ret_path = strndup(path, path_len); } // autocomplete-like function /* int util_find_starting_with(char * partial, vector list, vector &matches, int min) { vector_clear(matches); // Handle trivial case. unsigned int length = strlen(partial); if (length) { for (i = 0; i < vector_size(list); i++) { item = vector_get(list, i); if (strcmp(item, partial) == 0) { add_vector(matches, item); return 1; } else if (strtr(item, partial)) { add_vector(matches, item); } } return vector_size(matches); } */ // Return 1 if re matches subject int util_pcre_match(char* re, char* subject, int subject_len, char** optret_capture, int* optret_capture_len) { int rc; pcre* cre; const char *error; int erroffset; int ovector[3]; cre = pcre_compile((const char*)re, (optret_capture ? 0 : PCRE_NO_AUTO_CAPTURE) | PCRE_CASELESS, &error, &erroffset, NULL); if (!cre) return 0; rc = pcre_exec(cre, NULL, subject, subject_len, 0, 0, ovector, 3); pcre_free(cre); if (optret_capture) { if (rc >= 0) { *optret_capture = subject + ovector[0]; *optret_capture_len = ovector[1] - ovector[0]; } else { *optret_capture = NULL; *optret_capture_len = 0; } } return rc >= 0 ? 1 : 0; } // Perform a regex replace with back-references. Return number of replacements // made. If regex is invalid, `ret_result` is set to NULL, `ret_result_len` is // set to 0 and 0 is returned. int util_pcre_replace(char* re, char* subj, char* repl, char** ret_result, int* ret_result_len) { int rc; pcre* cre; const char *error; int erroffset; int subj_offset; int subj_offset_z; int subj_len; int subj_look_offset; int last_look_offset; int ovector[30]; int num_repls; int got_match = 0; str_t result = {0}; *ret_result = NULL; *ret_result_len = 0; // Compile regex cre = pcre_compile((const char*)re, PCRE_CASELESS, &error, &erroffset, NULL); if (!cre) return 0; // Start match-replace loop num_repls = 0; subj_len = strlen(subj); subj_offset = 0; subj_offset_z = 0; subj_look_offset = 0; last_look_offset = 0; while (subj_offset < subj_len) { // Find match rc = pcre_exec(cre, NULL, subj, subj_len, subj_look_offset, 0, ovector, 30); if (rc < 0 || ovector[0] < 0) { got_match = 0; subj_offset_z = subj_len; } else { got_match = 1; subj_offset_z = ovector[0]; } // Append part before match str_append_stop(&result, subj + subj_offset, subj + subj_offset_z); subj_offset = ovector[1]; subj_look_offset = subj_offset + (subj_offset > last_look_offset ? 0 : 1); // Prevent infinite loop last_look_offset = subj_look_offset; // Break if no match if (!got_match) break; // Append replacements with backrefs str_append_replace_with_backrefs(&result, subj, repl, rc, ovector, 30); // Increment num_repls num_repls += 1; } // Free regex pcre_free(cre); // Return result *ret_result = result.data ? result.data : strdup(""); *ret_result_len = result.len; // Return number of replacements return num_repls; } // Return 1 if a > b, else return 0. int util_timeval_is_gt(struct timeval* a, struct timeval* b) { if (a->tv_sec > b->tv_sec) { return 1; } else if (a->tv_sec == b->tv_sec) { return a->tv_usec > b->tv_usec ? 1 : 0; } return 0; } // Ported from php_escape_shell_arg // https://github.com/php/php-src/blob/master/ext/standard/exec.c char* util_escape_shell_arg(char* str, int l) { int x, y = 0; char *cmd; cmd = malloc(4 * l + 3); // worst case cmd[y++] = '\''; for (x = 0; x < l; x++) { int mb_len = tb_utf8_char_length(*(str + x)); // skip non-valid multibyte characters if (mb_len < 0) { continue; } else if (mb_len > 1) { memcpy(cmd + y, str + x, mb_len); y += mb_len; x += mb_len - 1; continue; } switch (str[x]) { case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; // fall-through default: cmd[y++] = str[x]; } } cmd[y++] = '\''; cmd[y] = '\0'; return cmd; } // Adapted from termbox src/demo/keyboard.c int rect_printf(bview_rect_t rect, int x, int y, uint16_t fg, uint16_t bg, const char *fmt, ...) { char buf[4096]; va_list vl; va_start(vl, fmt); vsnprintf(buf, sizeof(buf), fmt, vl); va_end(vl); return tb_string(rect.x + x, rect.y + y, fg ? fg : rect.fg, bg ? bg : rect.bg, buf); } // Like rect_printf, but accepts @fg,bg; attributes inside the string. To print // a literal '@', use '@@' in the format string. Specify fg or bg of 0 to // reset that attribute. int rect_printf_attr(bview_rect_t rect, int x, int y, const char *fmt, ...) { char bufo[4096]; char* buf; int fg; int bg; int tfg; int tbg; int c; uint32_t uni; va_list vl; va_start(vl, fmt); vsnprintf(bufo, sizeof(bufo), fmt, vl); va_end(vl); fg = rect.fg; bg = rect.bg; x = rect.x + x; y = rect.y + y; c = 0; buf = bufo; while (*buf) { buf += utf8_char_to_unicode(&uni, buf, NULL); if (uni == '@') { if (!*buf) break; utf8_char_to_unicode(&uni, buf, NULL); if (uni != '@') { tfg = strtol(buf, &buf, 10); if (!*buf) break; utf8_char_to_unicode(&uni, buf, NULL); if (uni == ',') { buf++; if (!*buf) break; tbg = strtol(buf, &buf, 10); fg = tfg <= 0 ? rect.fg : tfg; bg = tbg <= 0 ? rect.bg : tbg; if (!*buf) break; utf8_char_to_unicode(&uni, buf, NULL); if (uni == ';') buf++; continue; } } } tb_char(x, y, fg, bg, uni); x++; c++; } return c; }
387690.c
#include "infra_config.h" #ifdef INFRA_COMPAT #include <string.h> #include "infra_types.h" #include "infra_defs.h" #include "infra_state.h" #include "infra_compat.h" #include "wrappers.h" sdk_impl_ctx_t g_sdk_impl_ctx = {0}; #if !defined(INFRA_LOG) void IOT_SetLogLevel(IOT_LogLevel level) {} #endif #if defined(WIFI_PROVISION_ENABLED) extern void awss_set_press_timeout_ms(unsigned int timeout_ms); extern void awss_set_channel_scan_interval_ms(uint32_t timeout_ms); #endif #ifdef MQTT_COMM_ENABLED #include "dev_sign_api.h" #include "mqtt_api.h" #ifdef INFRA_LOG #include "infra_log.h" #define sdk_err(...) log_err("infra_compat", __VA_ARGS__) #define sdk_info(...) log_info("infra_compat", __VA_ARGS__) #else #define sdk_err(...) #define sdk_info(...) #endif #ifdef INFRA_MEM_STATS #include "infra_mem_stats.h" #endif /* global variable for mqtt construction */ static iotx_conn_info_t g_iotx_conn_info = {0}; static char g_empty_string[1] = ""; int IOT_SetupConnInfo(const char *product_key, const char *device_name, const char *device_secret, void **info_ptr) { if (product_key == NULL || device_name == NULL || device_secret == NULL || strlen(product_key) > IOTX_PRODUCT_KEY_LEN || strlen(device_name) > IOTX_DEVICE_NAME_LEN || strlen(device_secret) > IOTX_DEVICE_SECRET_LEN) { return NULL_VALUE_ERROR; } if (info_ptr) { memset(&g_iotx_conn_info, 0, sizeof(iotx_conn_info_t)); g_iotx_conn_info.host_name = g_empty_string; g_iotx_conn_info.client_id = g_empty_string; g_iotx_conn_info.username = g_empty_string; g_iotx_conn_info.password = g_empty_string; g_iotx_conn_info.pub_key = g_empty_string; *info_ptr = &g_iotx_conn_info; } return SUCCESS_RETURN; } #endif /* #ifdef MQTT_COMM_ENABLED */ #if defined(DEVICE_MODEL_ENABLED) #include "iotx_dm.h" #include "dm_opt.h" #endif #if defined(DEVICE_MODEL_GATEWAY) extern int iot_linkkit_subdev_query_id(char product_key[IOTX_PRODUCT_KEY_LEN + 1], char device_name[IOTX_DEVICE_NAME_LEN + 1]); #endif int IOT_Ioctl(int option, void *data) { int res = SUCCESS_RETURN; sdk_impl_ctx_t *ctx = NULL; ctx = &g_sdk_impl_ctx; if (option < 0 || data == NULL) { return FAIL_RETURN; } switch (option) { case IOTX_IOCTL_SET_REGION: { ctx->domain_type = *(iotx_mqtt_region_types_t *)data; /* iotx_guider_set_region(*(int *)data); */ res = SUCCESS_RETURN; } break; case IOTX_IOCTL_GET_REGION: { *(iotx_mqtt_region_types_t *)data = ctx->domain_type; res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_MQTT_DOMAIN: { ctx->domain_type = IOTX_CLOUD_REGION_CUSTOM; if (strlen(data) > IOTX_DOMAIN_MAX_LEN) { return FAIL_RETURN; } memset(ctx->cloud_custom_domain, 0, strlen((char *)data) + 1); memcpy(ctx->cloud_custom_domain, data, strlen((char *)data)); g_infra_mqtt_domain[IOTX_CLOUD_REGION_CUSTOM] = (const char *)ctx->cloud_custom_domain; res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_HTTP_DOMAIN: { ctx->domain_type = IOTX_HTTP_REGION_CUSTOM; if (strlen(data) > IOTX_DOMAIN_MAX_LEN) { return FAIL_RETURN; } memset(ctx->http_custom_domain, 0, strlen((char *)data) + 1); memcpy(ctx->http_custom_domain, data, strlen((char *)data)); g_infra_http_domain[IOTX_CLOUD_REGION_CUSTOM] = (const char *)ctx->http_custom_domain; res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_DYNAMIC_REGISTER: { ctx->dynamic_register = *(int *)data; res = SUCCESS_RETURN; } break; case IOTX_IOCTL_GET_DYNAMIC_REGISTER: { *(int *)data = ctx->dynamic_register; res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_PRODUCT_KEY: { if ((data != NULL) && (strlen(data) <= IOTX_PRODUCT_KEY_LEN)) { memset(ctx->product_key, 0, IOTX_PRODUCT_KEY_LEN + 1); memcpy(ctx->product_key, data, strlen(data)); res = SUCCESS_RETURN; } else { res = FAIL_RETURN; } } break; case IOTX_IOCTL_GET_PRODUCT_KEY: { memcpy(data, ctx->product_key, strlen(ctx->product_key)); res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_PRODUCT_SECRET: { if ((data != NULL) && (strlen(data) <= IOTX_PRODUCT_SECRET_LEN)) { memset(ctx->product_secret, 0, IOTX_PRODUCT_SECRET_LEN + 1); memcpy(ctx->product_secret, data, strlen(data)); res = SUCCESS_RETURN; } else { res = FAIL_RETURN; } } break; case IOTX_IOCTL_GET_PRODUCT_SECRET: { memcpy(data, ctx->product_secret, strlen(ctx->product_secret)); res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_DEVICE_NAME: { if ((data != NULL) && (strlen(data) <= IOTX_DEVICE_NAME_LEN)) { memset(ctx->device_name, 0, IOTX_DEVICE_NAME_LEN + 1); memcpy(ctx->device_name, data, strlen(data)); res = SUCCESS_RETURN; } else { res = FAIL_RETURN; } } break; case IOTX_IOCTL_GET_DEVICE_NAME: { memcpy(data, ctx->device_name, strlen(ctx->device_name)); res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_DEVICE_SECRET: { if ((data != NULL) && (strlen(data) <= IOTX_DEVICE_SECRET_LEN)) { memset(ctx->device_secret, 0, IOTX_DEVICE_SECRET_LEN + 1); memcpy(ctx->device_secret, data, strlen(data)); res = SUCCESS_RETURN; } else { res = FAIL_RETURN; } } break; case IOTX_IOCTL_GET_DEVICE_SECRET: { memcpy(data, ctx->device_secret, strlen(ctx->device_secret)); res = SUCCESS_RETURN; } break; #if defined(DEVICE_MODEL_ENABLED) && !defined(DEPRECATED_LINKKIT) #if !defined(DEVICE_MODEL_RAWDATA_SOLO) case IOTX_IOCTL_RECV_EVENT_REPLY: case IOTX_IOCTL_RECV_PROP_REPLY: { res = iotx_dm_set_opt(IMPL_LINKKIT_IOCTL_SWITCH_EVENT_POST_REPLY, data); } break; case IOTX_IOCTL_SEND_PROP_SET_REPLY : { res = iotx_dm_set_opt(IMPL_LINKKIT_IOCTL_SWITCH_PROPERTY_SET_REPLY, data); } break; #endif case IOTX_IOCTL_SET_SUBDEV_SIGN: { /* todo */ } break; case IOTX_IOCTL_GET_SUBDEV_LOGIN: { /* todo */ } break; #if defined(DEVICE_MODEL_GATEWAY) #ifdef DEVICE_MODEL_SUBDEV_OTA case IOTX_IOCTL_SET_OTA_DEV_ID: { int devid = *(int *)(data); if (devid < 0) { res = STATE_USER_INPUT_DEVID; } else { res = iotx_dm_ota_switch_device(devid); } } break; #endif #endif #else case IOTX_IOCTL_RECV_EVENT_REPLY: case IOTX_IOCTL_RECV_PROP_REPLY: case IOTX_IOCTL_SEND_PROP_SET_REPLY: case IOTX_IOCTL_GET_SUBDEV_LOGIN: { res = SUCCESS_RETURN; } break; #endif #if defined(DEVICE_MODEL_ENABLED) case IOTX_IOCTL_FOTA_TIMEOUT_MS: { res = iotx_dm_set_opt(DM_OPT_FOTA_RETRY_TIMEOUT_MS, data); } break; #endif case IOTX_IOCTL_SET_CUSTOMIZE_INFO: { if (strlen(data) > IOTX_CUSTOMIZE_INFO_LEN) { return FAIL_RETURN; } memset(ctx->mqtt_customzie_info, 0, strlen((char *)data) + 1); memcpy(ctx->mqtt_customzie_info, data, strlen((char *)data)); res = SUCCESS_RETURN; } break; case IOTX_IOCTL_SET_MQTT_PORT: { ctx->mqtt_port_num = *(uint16_t *)data; res = SUCCESS_RETURN; } break; #if defined(DEVICE_MODEL_GATEWAY) && !defined(DEPRECATED_LINKKIT) case IOTX_IOCTL_SET_PROXY_REGISTER: { res = iotx_dm_set_opt(DM_OPT_PROXY_PRODUCT_REGISTER, data); } break; case IOTX_IOCTL_QUERY_DEVID: { iotx_dev_meta_info_t *dev_info = (iotx_dev_meta_info_t *)data; res = iot_linkkit_subdev_query_id(dev_info->product_key, dev_info->device_name); } break; #endif #if defined(WIFI_PROVISION_ENABLED) case IOTX_IOCTL_SET_AWSS_ENABLE_INTERVAL: { uint32_t timeout = *(uint32_t *) data; awss_set_press_timeout_ms(timeout); } break; case IOTX_IOCTL_SET_AWSS_CHANNEL_SCAN_INTERVAL: { uint32_t timeout = *(uint32_t *) data; awss_set_channel_scan_interval_ms(timeout); } break; #endif #if defined(DEVICE_MODEL_ENABLED) case IOTX_IOCTL_SUB_USER_TOPIC: { iotx_user_subscribe_context *context = (iotx_user_subscribe_context *) data; res = iotx_dm_subscribe_user_topic((char *)context->topic, (void *)context->callback); } break; #endif default: { res = FAIL_RETURN; } break; } return res; } void IOT_DumpMemoryStats(IOT_LogLevel level) { #ifdef INFRA_MEM_STATS int lvl = (int)level; if (lvl > LOG_DEBUG_LEVEL) { lvl = LOG_DEBUG_LEVEL; HAL_Printf("Invalid input level, using default: %d => %d", level, lvl); } LITE_dump_malloc_free_stats(lvl); #endif } static void *g_event_monitor = NULL; int iotx_event_regist_cb(void (*monitor_cb)(int event)) { g_event_monitor = (void *)monitor_cb; return 0; } int iotx_event_post(int event) { if (g_event_monitor == NULL) { return -1; } ((void (*)(int))g_event_monitor)(event); return 0; } typedef struct { int eventid; void *callback; } impl_event_map_t; static impl_event_map_t g_impl_event_map[] = { {ITE_AWSS_STATUS, NULL}, {ITE_CONNECT_SUCC, NULL}, {ITE_CONNECT_FAIL, NULL}, {ITE_DISCONNECTED, NULL}, {ITE_RAWDATA_ARRIVED, NULL}, {ITE_SERVICE_REQUEST, NULL}, {ITE_SERVICE_REQUEST_EXT, NULL}, {ITE_PROPERTY_SET, NULL}, {ITE_PROPERTY_GET, NULL}, #ifdef DEVICE_MODEL_SHADOW {ITE_PROPERTY_DESIRED_GET_REPLY, NULL}, #endif {ITE_REPORT_REPLY, NULL}, {ITE_TRIGGER_EVENT_REPLY, NULL}, {ITE_TIMESTAMP_REPLY, NULL}, {ITE_TOPOLIST_REPLY, NULL}, {ITE_PERMIT_JOIN, NULL}, {ITE_INITIALIZE_COMPLETED, NULL}, {ITE_FOTA, NULL}, {ITE_COTA, NULL}, {ITE_MQTT_CONNECT_SUCC, NULL}, {ITE_CLOUD_ERROR, NULL}, {ITE_DYNREG_DEVICE_SECRET, NULL}, {ITE_IDENTITY_RESPONSE, NULL}, {ITE_STATE_EVERYTHING, NULL}, {ITE_STATE_USER_INPUT, NULL}, {ITE_STATE_SYS_DEPEND, NULL}, {ITE_STATE_MQTT_COMM, NULL}, {ITE_STATE_WIFI_PROV, NULL}, {ITE_STATE_COAP_LOCAL, NULL}, {ITE_STATE_HTTP_COMM, NULL}, {ITE_STATE_OTA, NULL}, {ITE_STATE_DEV_BIND, NULL}, {ITE_STATE_DEV_MODEL, NULL} }; void *iotx_event_callback(int evt) { if (evt < 0 || evt >= sizeof(g_impl_event_map) / sizeof(impl_event_map_t)) { return NULL; } return g_impl_event_map[evt].callback; } DEFINE_EVENT_CALLBACK(ITE_AWSS_STATUS, int (*callback)(int)) DEFINE_EVENT_CALLBACK(ITE_CONNECT_SUCC, int (*callback)(void)) DEFINE_EVENT_CALLBACK(ITE_CONNECT_FAIL, int (*callback)(void)) DEFINE_EVENT_CALLBACK(ITE_DISCONNECTED, int (*callback)(void)) DEFINE_EVENT_CALLBACK(ITE_RAWDATA_ARRIVED, int (*callback)(const int, const unsigned char *, const int)) DEFINE_EVENT_CALLBACK(ITE_SERVICE_REQUEST, int (*callback)(const int, const char *, const int, const char *, const int, char **, int *)) DEFINE_EVENT_CALLBACK(ITE_SERVICE_REQUEST_EXT, int (*callback)(int, const char *, int, const char *, int, const char *, int, void *)) DEFINE_EVENT_CALLBACK(ITE_PROPERTY_SET, int (*callback)(const int, const char *, const int)) #ifdef DEVICE_MODEL_SHADOW DEFINE_EVENT_CALLBACK(ITE_PROPERTY_DESIRED_GET_REPLY, int (*callback)(const char *, const int)) #endif DEFINE_EVENT_CALLBACK(ITE_PROPERTY_GET, int (*callback)(const int, const char *, const int, char **, int *)) DEFINE_EVENT_CALLBACK(ITE_REPORT_REPLY, int (*callback)(const int, const int, const int, const char *, const int)) DEFINE_EVENT_CALLBACK(ITE_TRIGGER_EVENT_REPLY, int (*callback)(const int, const int, const int, const char *, const int, const char *, const int)) DEFINE_EVENT_CALLBACK(ITE_TIMESTAMP_REPLY, int (*callback)(const char *)) DEFINE_EVENT_CALLBACK(ITE_TOPOLIST_REPLY, int (*callback)(const int, const int, const int, const char *, const int)) DEFINE_EVENT_CALLBACK(ITE_PERMIT_JOIN, int (*callback)(const char *, int)) DEFINE_EVENT_CALLBACK(ITE_INITIALIZE_COMPLETED, int (*callback)(const int)) DEFINE_EVENT_CALLBACK(ITE_FOTA, int (*callback)(const int, const char *)) DEFINE_EVENT_CALLBACK(ITE_COTA, int (*callback)(const int, const char *, int, const char *, const char *, const char *, const char *)) DEFINE_EVENT_CALLBACK(ITE_MQTT_CONNECT_SUCC, int (*callback)(void)) DEFINE_EVENT_CALLBACK(ITE_CLOUD_ERROR, int (*callback)(const int, const char *, const char *)) DEFINE_EVENT_CALLBACK(ITE_DYNREG_DEVICE_SECRET, int (*callback)(const char *)) DEFINE_EVENT_CALLBACK(ITE_IDENTITY_RESPONSE, int (*callback)(const char *)) int iotx_register_for_ITE_STATE_EVERYTHING(state_handler_t callback) { int idx = 0; for (idx = ITE_STATE_EVERYTHING; idx <= ITE_STATE_DEV_MODEL; idx++) { g_impl_event_map[idx].callback = (void *)callback; } return 0; } DEFINE_EVENT_CALLBACK(ITE_STATE_USER_INPUT, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_SYS_DEPEND, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_MQTT_COMM, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_WIFI_PROV, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_COAP_LOCAL, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_HTTP_COMM, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_OTA, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_DEV_BIND, state_handler_t callback) DEFINE_EVENT_CALLBACK(ITE_STATE_DEV_MODEL, state_handler_t callback) #if !defined(__APPLE__) extern int vsnprintf(char *str, size_t size, const char *format, va_list ap); #endif #define IOTX_STATE_EVENT_MESSAGE_MAXLEN (64) int iotx_state_event(const int event, const int code, const char *msg_format, ...) { char message[IOTX_STATE_EVENT_MESSAGE_MAXLEN + 1] = {0}; void *everything_state_handler = iotx_event_callback(ITE_STATE_EVERYTHING); void *state_handler = iotx_event_callback(event); va_list args; if (state_handler == NULL) { return -1; } if (msg_format != NULL) { memset(message, 0, sizeof(message)); va_start(args, msg_format); vsnprintf(message, IOTX_STATE_EVENT_MESSAGE_MAXLEN, msg_format, args); va_end(args); } ((state_handler_t)state_handler)(code, message); if (everything_state_handler && everything_state_handler != state_handler) { ((state_handler_t)everything_state_handler)(code, message); } return 0; } #endif
629507.c
// Coded by Lujke. These are the rock devils' leather pants. They are // enchanted to +1, and give a bonus of +1 to cha. // updated cha bonus from the new system. Nienne, 09/07. #include <std.h> #include <move.h> inherit ARMOUR; void create() { ::create(); set_obvious_short("%^BOLD%^%^RED%^A pair of red pants%^RESET%^"); set_name("red pants"); set_short("%^BOLD%^%^RED%^P%^RESET%^%^RED%^a%^BOLD%^%^RED%^nts of the %^BOLD%^%^RED%^r%^BOLD%^%^BLACK%^o%^BOLD%^%^RED%^ck d%^RESET%^%^RED%^e%^BOLD%^%^BLACK%^v%^RED%^i%^BOLD%^%^BLACK%^l%^RESET%^"); set_id(({"pants","devil pants","red pants"})); set_long("%^BOLD%^%^RED%^A pair of f%^YELLOW%^i%^RESET%^%^RED%^e" +"%^BOLD%^%^RED%^ry red leather pants cut tight and low around" +" the h%^YELLOW%^i%^BOLD%^%^RED%^ps, but a little looser lower" +" d%^YELLOW%^o%^BOLD%^%^RED%^wn. Traces of y%^YELLOW%^e" +"%^BOLD%^%^RED%^llow patterning flicker are c%^YELLOW%^u" +"%^BOLD%^%^RED%^t into the leather like random f%^YELLOW%^l" +"%^RESET%^%^RED%^a%^BOLD%^%^RED%^mes There is not a h" +"%^YELLOW%^i%^BOLD%^%^RED%^nt of subtlety about these" +" p%^YELLOW%^a%^BOLD%^%^RED%^nts. They look like they were" +" c%^YELLOW%^u%^BOLD%^%^RED%^t by someone who may not have" +" known what th%^YELLOW%^e%^BOLD%^%^RED%^y wanted to say but" +" just wanted to say it L%^YELLOW%^O%^BOLD%^%^RED%^UD."); set_lore("The pits of the lower hells are places of heat and fire," +" worlds of hurt and damage. The devils who live there are" +" fierce and aggressive, and their dress sense reflects" +" this. The fire design on these pants and the rather strange" +" leather they are made out of makes you suspect that they" +" could be infernal in origin"); set_property("lore difficulty",14); set_weight(8); set_type("leather"); set_limbs(({"left leg","right leg"})); set_ac(0); set_property("enchantment",4); set_value(1000); set_wear((:TO,"wear_func":)); set_remove((:TO,"remove_func":)); switch (random(8)) { case 0: set_size(1); set_lore(query_lore()+"\nThe devil who wore this pair must" +" have been smaller than most!"); break; case 1: set_size(3); set_lore(query_lore()+"\nThe devil who wore this pair must" +" have been rather large!"); break; default: set_size(2); } set_item_bonus("charisma",1); } int wear_func(){ string godtype; if (!objectp(TO)||!objectp(ETO)||!objectp(EETO)){return 0;} if((int)ETO->query_level() < 25) { notify_fail("The pants are too powerful for you at present!"); return 0; } if ((string)ETO->query_gender()=="male"){ godtype = "God"; } else { godtype = "Goddess"; } tell_room(EETO,"BOLD%^%^RED%^"+ETOQCN+" pulls on "+ETO->QP +query_short() + ".",ETO); tell_object(ETO,"%^BOLD%^%^RED%^You pull on the " + query_short() + "%^BOLD%^%^RED%^ and feel like a "+godtype +"!"); return 1; } int remove_func(){ string gender; if (!objectp(TO)||!objectp(ETO)||!objectp(EETO)){return 0;} if ((string)ETO->query_gender()=="male"){ gender = "man"; } else { gender = "woman"; } tell_room(EETO,"%^BOLD%^%^RED%^ shucks off "+ETO->QP+" " + query_short() +" and seems a little less impressive.",ETO); tell_object(ETO,"%^BOLD%^%^RED%^You remove the " + query_short() + " and feel a little less " + gender + "ly"); return 1; }
469755.c
// SPDX-License-Identifier: GPL-2.0 /* * UEFI Common Platform Error Record (CPER) support * * Copyright (C) 2010, Intel Corp. * Author: Huang Ying <[email protected]> * * CPER is the format used to describe platform hardware error by * various tables, such as ERST, BERT and HEST etc. * * For more information about CPER, please refer to Appendix N of UEFI * Specification version 2.4. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/time.h> #include <linux/cper.h> #include <linux/dmi.h> #include <linux/acpi.h> #include <linux/pci.h> #include <linux/aer.h> #include <linux/printk.h> #include <linux/bcd.h> #include <acpi/ghes.h> #include <ras/ras_event.h> static char rcd_decode_str[CPER_REC_LEN]; /* * CPER record ID need to be unique even after reboot, because record * ID is used as index for ERST storage, while CPER records from * multiple boot may co-exist in ERST. */ u64 cper_next_record_id(void) { static atomic64_t seq; if (!atomic64_read(&seq)) { time64_t time = ktime_get_real_seconds(); /* * This code is unlikely to still be needed in year 2106, * but just in case, let's use a few more bits for timestamps * after y2038 to be sure they keep increasing monotonically * for the next few hundred years... */ if (time < 0x80000000) atomic64_set(&seq, (ktime_get_real_seconds()) << 32); else atomic64_set(&seq, 0x8000000000000000ull | ktime_get_real_seconds() << 24); } return atomic64_inc_return(&seq); } EXPORT_SYMBOL_GPL(cper_next_record_id); static const char * const severity_strs[] = { "recoverable", "fatal", "corrected", "info", }; const char *cper_severity_str(unsigned int severity) { return severity < ARRAY_SIZE(severity_strs) ? severity_strs[severity] : "unknown"; } EXPORT_SYMBOL_GPL(cper_severity_str); /* * cper_print_bits - print strings for set bits * @pfx: prefix for each line, including log level and prefix string * @bits: bit mask * @strs: string array, indexed by bit position * @strs_size: size of the string array: @strs * * For each set bit in @bits, print the corresponding string in @strs. * If the output length is longer than 80, multiple line will be * printed, with @pfx is printed at the beginning of each line. */ void cper_print_bits(const char *pfx, unsigned int bits, const char * const strs[], unsigned int strs_size) { int i, len = 0; const char *str; char buf[84]; for (i = 0; i < strs_size; i++) { if (!(bits & (1U << i))) continue; str = strs[i]; if (!str) continue; if (len && len + strlen(str) + 2 > 80) { printk("%s\n", buf); len = 0; } if (!len) len = snprintf(buf, sizeof(buf), "%s%s", pfx, str); else len += scnprintf(buf+len, sizeof(buf)-len, ", %s", str); } if (len) printk("%s\n", buf); } static const char * const proc_type_strs[] = { "IA32/X64", "IA64", "ARM", }; static const char * const proc_isa_strs[] = { "IA32", "IA64", "X64", "ARM A32/T32", "ARM A64", }; const char * const cper_proc_error_type_strs[] = { "cache error", "TLB error", "bus error", "micro-architectural error", }; static const char * const proc_op_strs[] = { "unknown or generic", "data read", "data write", "instruction execution", }; static const char * const proc_flag_strs[] = { "restartable", "precise IP", "overflow", "corrected", }; static void cper_print_proc_generic(const char *pfx, const struct cper_sec_proc_generic *proc) { if (proc->validation_bits & CPER_PROC_VALID_TYPE) printk("%s""processor_type: %d, %s\n", pfx, proc->proc_type, proc->proc_type < ARRAY_SIZE(proc_type_strs) ? proc_type_strs[proc->proc_type] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_ISA) printk("%s""processor_isa: %d, %s\n", pfx, proc->proc_isa, proc->proc_isa < ARRAY_SIZE(proc_isa_strs) ? proc_isa_strs[proc->proc_isa] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_ERROR_TYPE) { printk("%s""error_type: 0x%02x\n", pfx, proc->proc_error_type); cper_print_bits(pfx, proc->proc_error_type, cper_proc_error_type_strs, ARRAY_SIZE(cper_proc_error_type_strs)); } if (proc->validation_bits & CPER_PROC_VALID_OPERATION) printk("%s""operation: %d, %s\n", pfx, proc->operation, proc->operation < ARRAY_SIZE(proc_op_strs) ? proc_op_strs[proc->operation] : "unknown"); if (proc->validation_bits & CPER_PROC_VALID_FLAGS) { printk("%s""flags: 0x%02x\n", pfx, proc->flags); cper_print_bits(pfx, proc->flags, proc_flag_strs, ARRAY_SIZE(proc_flag_strs)); } if (proc->validation_bits & CPER_PROC_VALID_LEVEL) printk("%s""level: %d\n", pfx, proc->level); if (proc->validation_bits & CPER_PROC_VALID_VERSION) printk("%s""version_info: 0x%016llx\n", pfx, proc->cpu_version); if (proc->validation_bits & CPER_PROC_VALID_ID) printk("%s""processor_id: 0x%016llx\n", pfx, proc->proc_id); if (proc->validation_bits & CPER_PROC_VALID_TARGET_ADDRESS) printk("%s""target_address: 0x%016llx\n", pfx, proc->target_addr); if (proc->validation_bits & CPER_PROC_VALID_REQUESTOR_ID) printk("%s""requestor_id: 0x%016llx\n", pfx, proc->requestor_id); if (proc->validation_bits & CPER_PROC_VALID_RESPONDER_ID) printk("%s""responder_id: 0x%016llx\n", pfx, proc->responder_id); if (proc->validation_bits & CPER_PROC_VALID_IP) printk("%s""IP: 0x%016llx\n", pfx, proc->ip); } static const char * const mem_err_type_strs[] = { "unknown", "no error", "single-bit ECC", "multi-bit ECC", "single-symbol chipkill ECC", "multi-symbol chipkill ECC", "master abort", "target abort", "parity error", "watchdog timeout", "invalid address", "mirror Broken", "memory sparing", "scrub corrected error", "scrub uncorrected error", "physical memory map-out event", }; const char *cper_mem_err_type_str(unsigned int etype) { return etype < ARRAY_SIZE(mem_err_type_strs) ? mem_err_type_strs[etype] : "unknown"; } EXPORT_SYMBOL_GPL(cper_mem_err_type_str); static int cper_mem_err_location(struct cper_mem_err_compact *mem, char *msg) { u32 len, n; if (!msg) return 0; n = 0; len = CPER_REC_LEN - 1; if (mem->validation_bits & CPER_MEM_VALID_NODE) n += scnprintf(msg + n, len - n, "node: %d ", mem->node); if (mem->validation_bits & CPER_MEM_VALID_CARD) n += scnprintf(msg + n, len - n, "card: %d ", mem->card); if (mem->validation_bits & CPER_MEM_VALID_MODULE) n += scnprintf(msg + n, len - n, "module: %d ", mem->module); if (mem->validation_bits & CPER_MEM_VALID_RANK_NUMBER) n += scnprintf(msg + n, len - n, "rank: %d ", mem->rank); if (mem->validation_bits & CPER_MEM_VALID_BANK) n += scnprintf(msg + n, len - n, "bank: %d ", mem->bank); if (mem->validation_bits & CPER_MEM_VALID_BANK_GROUP) n += scnprintf(msg + n, len - n, "bank_group: %d ", mem->bank >> CPER_MEM_BANK_GROUP_SHIFT); if (mem->validation_bits & CPER_MEM_VALID_BANK_ADDRESS) n += scnprintf(msg + n, len - n, "bank_address: %d ", mem->bank & CPER_MEM_BANK_ADDRESS_MASK); if (mem->validation_bits & CPER_MEM_VALID_DEVICE) n += scnprintf(msg + n, len - n, "device: %d ", mem->device); if (mem->validation_bits & (CPER_MEM_VALID_ROW | CPER_MEM_VALID_ROW_EXT)) { u32 row = mem->row; row |= cper_get_mem_extension(mem->validation_bits, mem->extended); n += scnprintf(msg + n, len - n, "row: %d ", row); } if (mem->validation_bits & CPER_MEM_VALID_COLUMN) n += scnprintf(msg + n, len - n, "column: %d ", mem->column); if (mem->validation_bits & CPER_MEM_VALID_BIT_POSITION) n += scnprintf(msg + n, len - n, "bit_position: %d ", mem->bit_pos); if (mem->validation_bits & CPER_MEM_VALID_REQUESTOR_ID) n += scnprintf(msg + n, len - n, "requestor_id: 0x%016llx ", mem->requestor_id); if (mem->validation_bits & CPER_MEM_VALID_RESPONDER_ID) n += scnprintf(msg + n, len - n, "responder_id: 0x%016llx ", mem->responder_id); if (mem->validation_bits & CPER_MEM_VALID_TARGET_ID) scnprintf(msg + n, len - n, "target_id: 0x%016llx ", mem->target_id); if (mem->validation_bits & CPER_MEM_VALID_CHIP_ID) scnprintf(msg + n, len - n, "chip_id: %d ", mem->extended >> CPER_MEM_CHIP_ID_SHIFT); msg[n] = '\0'; return n; } static int cper_dimm_err_location(struct cper_mem_err_compact *mem, char *msg) { u32 len, n; const char *bank = NULL, *device = NULL; if (!msg || !(mem->validation_bits & CPER_MEM_VALID_MODULE_HANDLE)) return 0; n = 0; len = CPER_REC_LEN - 1; dmi_memdev_name(mem->mem_dev_handle, &bank, &device); if (bank && device) n = snprintf(msg, len, "DIMM location: %s %s ", bank, device); else n = snprintf(msg, len, "DIMM location: not present. DMI handle: 0x%.4x ", mem->mem_dev_handle); msg[n] = '\0'; return n; } void cper_mem_err_pack(const struct cper_sec_mem_err *mem, struct cper_mem_err_compact *cmem) { cmem->validation_bits = mem->validation_bits; cmem->node = mem->node; cmem->card = mem->card; cmem->module = mem->module; cmem->bank = mem->bank; cmem->device = mem->device; cmem->row = mem->row; cmem->column = mem->column; cmem->bit_pos = mem->bit_pos; cmem->requestor_id = mem->requestor_id; cmem->responder_id = mem->responder_id; cmem->target_id = mem->target_id; cmem->extended = mem->extended; cmem->rank = mem->rank; cmem->mem_array_handle = mem->mem_array_handle; cmem->mem_dev_handle = mem->mem_dev_handle; } const char *cper_mem_err_unpack(struct trace_seq *p, struct cper_mem_err_compact *cmem) { const char *ret = trace_seq_buffer_ptr(p); if (cper_mem_err_location(cmem, rcd_decode_str)) trace_seq_printf(p, "%s", rcd_decode_str); if (cper_dimm_err_location(cmem, rcd_decode_str)) trace_seq_printf(p, "%s", rcd_decode_str); trace_seq_putc(p, '\0'); return ret; } static void cper_print_mem(const char *pfx, const struct cper_sec_mem_err *mem, int len) { struct cper_mem_err_compact cmem; /* Don't trust UEFI 2.1/2.2 structure with bad validation bits */ if (len == sizeof(struct cper_sec_mem_err_old) && (mem->validation_bits & ~(CPER_MEM_VALID_RANK_NUMBER - 1))) { pr_err(FW_WARN "valid bits set for fields beyond structure\n"); return; } if (mem->validation_bits & CPER_MEM_VALID_ERROR_STATUS) printk("%s""error_status: 0x%016llx\n", pfx, mem->error_status); if (mem->validation_bits & CPER_MEM_VALID_PA) printk("%s""physical_address: 0x%016llx\n", pfx, mem->physical_addr); if (mem->validation_bits & CPER_MEM_VALID_PA_MASK) printk("%s""physical_address_mask: 0x%016llx\n", pfx, mem->physical_addr_mask); cper_mem_err_pack(mem, &cmem); if (cper_mem_err_location(&cmem, rcd_decode_str)) printk("%s%s\n", pfx, rcd_decode_str); if (mem->validation_bits & CPER_MEM_VALID_ERROR_TYPE) { u8 etype = mem->error_type; printk("%s""error_type: %d, %s\n", pfx, etype, cper_mem_err_type_str(etype)); } if (cper_dimm_err_location(&cmem, rcd_decode_str)) printk("%s%s\n", pfx, rcd_decode_str); } static const char * const pcie_port_type_strs[] = { "PCIe end point", "legacy PCI end point", "unknown", "unknown", "root port", "upstream switch port", "downstream switch port", "PCIe to PCI/PCI-X bridge", "PCI/PCI-X to PCIe bridge", "root complex integrated endpoint device", "root complex event collector", }; static void cper_print_pcie(const char *pfx, const struct cper_sec_pcie *pcie, const struct acpi_hest_generic_data *gdata) { if (pcie->validation_bits & CPER_PCIE_VALID_PORT_TYPE) printk("%s""port_type: %d, %s\n", pfx, pcie->port_type, pcie->port_type < ARRAY_SIZE(pcie_port_type_strs) ? pcie_port_type_strs[pcie->port_type] : "unknown"); if (pcie->validation_bits & CPER_PCIE_VALID_VERSION) printk("%s""version: %d.%d\n", pfx, pcie->version.major, pcie->version.minor); if (pcie->validation_bits & CPER_PCIE_VALID_COMMAND_STATUS) printk("%s""command: 0x%04x, status: 0x%04x\n", pfx, pcie->command, pcie->status); if (pcie->validation_bits & CPER_PCIE_VALID_DEVICE_ID) { const __u8 *p; printk("%s""device_id: %04x:%02x:%02x.%x\n", pfx, pcie->device_id.segment, pcie->device_id.bus, pcie->device_id.device, pcie->device_id.function); printk("%s""slot: %d\n", pfx, pcie->device_id.slot >> CPER_PCIE_SLOT_SHIFT); printk("%s""secondary_bus: 0x%02x\n", pfx, pcie->device_id.secondary_bus); printk("%s""vendor_id: 0x%04x, device_id: 0x%04x\n", pfx, pcie->device_id.vendor_id, pcie->device_id.device_id); p = pcie->device_id.class_code; printk("%s""class_code: %02x%02x%02x\n", pfx, p[2], p[1], p[0]); } if (pcie->validation_bits & CPER_PCIE_VALID_SERIAL_NUMBER) printk("%s""serial number: 0x%04x, 0x%04x\n", pfx, pcie->serial_number.lower, pcie->serial_number.upper); if (pcie->validation_bits & CPER_PCIE_VALID_BRIDGE_CONTROL_STATUS) printk( "%s""bridge: secondary_status: 0x%04x, control: 0x%04x\n", pfx, pcie->bridge.secondary_status, pcie->bridge.control); /* Fatal errors call __ghes_panic() before AER handler prints this */ if ((pcie->validation_bits & CPER_PCIE_VALID_AER_INFO) && (gdata->error_severity & CPER_SEV_FATAL)) { struct aer_capability_regs *aer; aer = (struct aer_capability_regs *)pcie->aer_info; printk("%saer_uncor_status: 0x%08x, aer_uncor_mask: 0x%08x\n", pfx, aer->uncor_status, aer->uncor_mask); printk("%saer_uncor_severity: 0x%08x\n", pfx, aer->uncor_severity); printk("%sTLP Header: %08x %08x %08x %08x\n", pfx, aer->header_log.dw0, aer->header_log.dw1, aer->header_log.dw2, aer->header_log.dw3); } } static const char * const fw_err_rec_type_strs[] = { "IPF SAL Error Record", "SOC Firmware Error Record Type1 (Legacy CrashLog Support)", "SOC Firmware Error Record Type2", }; static void cper_print_fw_err(const char *pfx, struct acpi_hest_generic_data *gdata, const struct cper_sec_fw_err_rec_ref *fw_err) { void *buf = acpi_hest_get_payload(gdata); u32 offset, length = gdata->error_data_length; printk("%s""Firmware Error Record Type: %s\n", pfx, fw_err->record_type < ARRAY_SIZE(fw_err_rec_type_strs) ? fw_err_rec_type_strs[fw_err->record_type] : "unknown"); printk("%s""Revision: %d\n", pfx, fw_err->revision); /* Record Type based on UEFI 2.7 */ if (fw_err->revision == 0) { printk("%s""Record Identifier: %08llx\n", pfx, fw_err->record_identifier); } else if (fw_err->revision == 2) { printk("%s""Record Identifier: %pUl\n", pfx, &fw_err->record_identifier_guid); } /* * The FW error record may contain trailing data beyond the * structure defined by the specification. As the fields * defined (and hence the offset of any trailing data) vary * with the revision, set the offset to account for this * variation. */ if (fw_err->revision == 0) { /* record_identifier_guid not defined */ offset = offsetof(struct cper_sec_fw_err_rec_ref, record_identifier_guid); } else if (fw_err->revision == 1) { /* record_identifier not defined */ offset = offsetof(struct cper_sec_fw_err_rec_ref, record_identifier); } else { offset = sizeof(*fw_err); } buf += offset; length -= offset; print_hex_dump(pfx, "", DUMP_PREFIX_OFFSET, 16, 4, buf, length, true); } static void cper_print_tstamp(const char *pfx, struct acpi_hest_generic_data_v300 *gdata) { __u8 hour, min, sec, day, mon, year, century, *timestamp; if (gdata->validation_bits & ACPI_HEST_GEN_VALID_TIMESTAMP) { timestamp = (__u8 *)&(gdata->time_stamp); sec = bcd2bin(timestamp[0]); min = bcd2bin(timestamp[1]); hour = bcd2bin(timestamp[2]); day = bcd2bin(timestamp[4]); mon = bcd2bin(timestamp[5]); year = bcd2bin(timestamp[6]); century = bcd2bin(timestamp[7]); printk("%s%ststamp: %02d%02d-%02d-%02d %02d:%02d:%02d\n", pfx, (timestamp[3] & 0x1 ? "precise " : "imprecise "), century, year, mon, day, hour, min, sec); } } static void cper_estatus_print_section(const char *pfx, struct acpi_hest_generic_data *gdata, int sec_no) { guid_t *sec_type = (guid_t *)gdata->section_type; __u16 severity; char newpfx[64]; if (acpi_hest_get_version(gdata) >= 3) cper_print_tstamp(pfx, (struct acpi_hest_generic_data_v300 *)gdata); severity = gdata->error_severity; printk("%s""Error %d, type: %s\n", pfx, sec_no, cper_severity_str(severity)); if (gdata->validation_bits & CPER_SEC_VALID_FRU_ID) printk("%s""fru_id: %pUl\n", pfx, gdata->fru_id); if (gdata->validation_bits & CPER_SEC_VALID_FRU_TEXT) printk("%s""fru_text: %.20s\n", pfx, gdata->fru_text); snprintf(newpfx, sizeof(newpfx), "%s ", pfx); if (guid_equal(sec_type, &CPER_SEC_PROC_GENERIC)) { struct cper_sec_proc_generic *proc_err = acpi_hest_get_payload(gdata); printk("%s""section_type: general processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*proc_err)) cper_print_proc_generic(newpfx, proc_err); else goto err_section_too_small; } else if (guid_equal(sec_type, &CPER_SEC_PLATFORM_MEM)) { struct cper_sec_mem_err *mem_err = acpi_hest_get_payload(gdata); printk("%s""section_type: memory error\n", newpfx); if (gdata->error_data_length >= sizeof(struct cper_sec_mem_err_old)) cper_print_mem(newpfx, mem_err, gdata->error_data_length); else goto err_section_too_small; } else if (guid_equal(sec_type, &CPER_SEC_PCIE)) { struct cper_sec_pcie *pcie = acpi_hest_get_payload(gdata); printk("%s""section_type: PCIe error\n", newpfx); if (gdata->error_data_length >= sizeof(*pcie)) cper_print_pcie(newpfx, pcie, gdata); else goto err_section_too_small; #if defined(CONFIG_ARM64) || defined(CONFIG_ARM) } else if (guid_equal(sec_type, &CPER_SEC_PROC_ARM)) { struct cper_sec_proc_arm *arm_err = acpi_hest_get_payload(gdata); printk("%ssection_type: ARM processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*arm_err)) cper_print_proc_arm(newpfx, arm_err); else goto err_section_too_small; #endif #if defined(CONFIG_UEFI_CPER_X86) } else if (guid_equal(sec_type, &CPER_SEC_PROC_IA)) { struct cper_sec_proc_ia *ia_err = acpi_hest_get_payload(gdata); printk("%ssection_type: IA32/X64 processor error\n", newpfx); if (gdata->error_data_length >= sizeof(*ia_err)) cper_print_proc_ia(newpfx, ia_err); else goto err_section_too_small; #endif } else if (guid_equal(sec_type, &CPER_SEC_FW_ERR_REC_REF)) { struct cper_sec_fw_err_rec_ref *fw_err = acpi_hest_get_payload(gdata); printk("%ssection_type: Firmware Error Record Reference\n", newpfx); /* The minimal FW Error Record contains 16 bytes */ if (gdata->error_data_length >= SZ_16) cper_print_fw_err(newpfx, gdata, fw_err); else goto err_section_too_small; } else { const void *err = acpi_hest_get_payload(gdata); printk("%ssection type: unknown, %pUl\n", newpfx, sec_type); printk("%ssection length: %#x\n", newpfx, gdata->error_data_length); print_hex_dump(newpfx, "", DUMP_PREFIX_OFFSET, 16, 4, err, gdata->error_data_length, true); } return; err_section_too_small: pr_err(FW_WARN "error section length is too small\n"); } void cper_estatus_print(const char *pfx, const struct acpi_hest_generic_status *estatus) { struct acpi_hest_generic_data *gdata; int sec_no = 0; char newpfx[64]; __u16 severity; severity = estatus->error_severity; if (severity == CPER_SEV_CORRECTED) printk("%s%s\n", pfx, "It has been corrected by h/w " "and requires no further action"); printk("%s""event severity: %s\n", pfx, cper_severity_str(severity)); snprintf(newpfx, sizeof(newpfx), "%s ", pfx); apei_estatus_for_each_section(estatus, gdata) { cper_estatus_print_section(newpfx, gdata, sec_no); sec_no++; } } EXPORT_SYMBOL_GPL(cper_estatus_print); int cper_estatus_check_header(const struct acpi_hest_generic_status *estatus) { if (estatus->data_length && estatus->data_length < sizeof(struct acpi_hest_generic_data)) return -EINVAL; if (estatus->raw_data_length && estatus->raw_data_offset < sizeof(*estatus) + estatus->data_length) return -EINVAL; return 0; } EXPORT_SYMBOL_GPL(cper_estatus_check_header); int cper_estatus_check(const struct acpi_hest_generic_status *estatus) { struct acpi_hest_generic_data *gdata; unsigned int data_len, record_size; int rc; rc = cper_estatus_check_header(estatus); if (rc) return rc; data_len = estatus->data_length; apei_estatus_for_each_section(estatus, gdata) { if (sizeof(struct acpi_hest_generic_data) > data_len) return -EINVAL; record_size = acpi_hest_get_record_size(gdata); if (record_size > data_len) return -EINVAL; data_len -= record_size; } if (data_len) return -EINVAL; return 0; } EXPORT_SYMBOL_GPL(cper_estatus_check);
341718.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <assert.h> #include <string.h> #include <stdio.h> #include <errno.h> #include "os/mynewt.h" #include "console/console.h" #include "config/config.h" #include "nimble/ble.h" #include "host/ble_hs.h" #include "services/gap/ble_svc_gap.h" #include "blecsc_sens.h" /* Wheel size for simulation calculations */ #define CSC_SIM_WHEEL_CIRCUMFERENCE_MM 2000 /* Simulated cadence lower limit */ #define CSC_SIM_CRANK_RPM_MIN 20 /* Simulated cadence upper limit */ #define CSC_SIM_CRANK_RPM_MAX 100 /* Simulated speed lower limit */ #define CSC_SIM_SPEED_KPH_MIN 0 /* Simulated speed upper limit */ #define CSC_SIM_SPEED_KPH_MAX 35 /* Noticication status */ static bool notify_state = false; /* Connection handle */ static uint16_t conn_handle; static uint8_t blecsc_addr_type; /* Advertised device name */ static const char *device_name = "blecsc_sensor"; /* Measurement and notification timer */ static struct os_callout blecsc_measure_timer; /* Variable holds current CSC measurement state */ static struct ble_csc_measurement_state csc_measurement_state; /* Variable holds simulted speed (kilometers per hour) */ static uint16_t csc_sim_speed_kph = CSC_SIM_SPEED_KPH_MIN; /* Variable holds simulated cadence (RPM) */ static uint8_t csc_sim_crank_rpm = CSC_SIM_CRANK_RPM_MIN; static int blecsc_gap_event(struct ble_gap_event *event, void *arg); /* * Enables advertising with parameters: * o General discoverable mode * o Undirected connectable mode */ static void blecsc_advertise(void) { struct ble_gap_adv_params adv_params; struct ble_hs_adv_fields fields; int rc; /* * Set the advertisement data included in our advertisements: * o Flags (indicates advertisement type and other general info) * o Advertising tx power * o Device name */ memset(&fields, 0, sizeof(fields)); /* * Advertise two flags: * o Discoverability in forthcoming advertisement (general) * o BLE-only (BR/EDR unsupported) */ fields.flags = BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP; /* * Indicate that the TX power level field should be included; have the * stack fill this value automatically. This is done by assigning the * special value BLE_HS_ADV_TX_PWR_LVL_AUTO. */ fields.tx_pwr_lvl_is_present = 1; fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO; fields.name = (uint8_t *)device_name; fields.name_len = strlen(device_name); fields.name_is_complete = 1; /* * Set appearance. */ fields.appearance = ble_svc_gap_device_appearance(); fields.appearance_is_present = 1; rc = ble_gap_adv_set_fields(&fields); if (rc != 0) { MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc); return; } /* Begin advertising */ memset(&adv_params, 0, sizeof(adv_params)); adv_params.conn_mode = BLE_GAP_CONN_MODE_UND; adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN; rc = ble_gap_adv_start(blecsc_addr_type, NULL, BLE_HS_FOREVER, &adv_params, blecsc_gap_event, NULL); if (rc != 0) { MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc); return; } } /* Update simulated CSC measurements. * Each call increments wheel and crank revolution counters by one and * computes last event time in order to match simulated candence and speed. * Last event time is expressedd in 1/1024th of second units. * * 60 * 1024 * crank_dt = -------------- * cadence[RPM] * * * circumference[mm] * 1024 * 60 * 60 * wheel_dt = ------------------------------------- * 10^6 * speed [kph] */ static void blecsc_simulate_speed_and_cadence() { uint16_t wheel_rev_period; uint16_t crank_rev_period; /* Update simulated crank and wheel rotation speed */ csc_sim_speed_kph++; if (csc_sim_speed_kph >= CSC_SIM_SPEED_KPH_MAX) { csc_sim_speed_kph = CSC_SIM_SPEED_KPH_MIN; } csc_sim_crank_rpm++; if (csc_sim_crank_rpm >= CSC_SIM_CRANK_RPM_MAX) { csc_sim_crank_rpm = CSC_SIM_CRANK_RPM_MIN; } /* Calculate simulated measurement values */ if (csc_sim_speed_kph > 0){ wheel_rev_period = (36*64*CSC_SIM_WHEEL_CIRCUMFERENCE_MM) / (625*csc_sim_speed_kph); csc_measurement_state.cumulative_wheel_rev++; csc_measurement_state.last_wheel_evt_time += wheel_rev_period; } if (csc_sim_crank_rpm > 0){ crank_rev_period = (60*1024) / csc_sim_crank_rpm; csc_measurement_state.cumulative_crank_rev++; csc_measurement_state.last_crank_evt_time += crank_rev_period; } MODLOG_DFLT(INFO, "CSC simulated values: speed = %d kph, cadence = %d \n", csc_sim_speed_kph, csc_sim_crank_rpm); } /* Run CSC measurement simulation and notify it to the client */ static void blecsc_measurement(struct os_event *ev) { int rc; rc = os_callout_reset(&blecsc_measure_timer, OS_TICKS_PER_SEC); assert(rc == 0); blecsc_simulate_speed_and_cadence(); if (notify_state) { rc = gatt_svr_chr_notify_csc_measurement(conn_handle); assert(rc == 0); } } static int blecsc_gap_event(struct ble_gap_event *event, void *arg) { switch (event->type) { case BLE_GAP_EVENT_CONNECT: /* A new connection was established or a connection attempt failed */ MODLOG_DFLT(INFO, "connection %s; status=%d\n", event->connect.status == 0 ? "established" : "failed", event->connect.status); if (event->connect.status != 0) { /* Connection failed; resume advertising */ blecsc_advertise(); conn_handle = 0; } else { conn_handle = event->connect.conn_handle; } break; case BLE_GAP_EVENT_DISCONNECT: MODLOG_DFLT(INFO, "disconnect; reason=%d\n", event->disconnect.reason); conn_handle = 0; /* Connection terminated; resume advertising */ blecsc_advertise(); break; case BLE_GAP_EVENT_ADV_COMPLETE: MODLOG_DFLT(INFO, "adv complete\n"); break; case BLE_GAP_EVENT_SUBSCRIBE: MODLOG_DFLT(INFO, "subscribe event attr_handle=%d\n", event->subscribe.attr_handle); if (event->subscribe.attr_handle == csc_measurement_handle) { notify_state = event->subscribe.cur_notify; MODLOG_DFLT(INFO, "csc measurement notify state = %d\n", notify_state); } else if (event->subscribe.attr_handle == csc_control_point_handle) { gatt_svr_set_cp_indicate(event->subscribe.cur_indicate); MODLOG_DFLT(INFO, "csc control point indicate state = %d\n", event->subscribe.cur_indicate); } break; case BLE_GAP_EVENT_MTU: MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d mtu=%d\n", event->mtu.conn_handle, event->mtu.value); break; } return 0; } static void blecsc_on_sync(void) { int rc; /* Figure out address to use while advertising (no privacy) */ rc = ble_hs_id_infer_auto(0, &blecsc_addr_type); assert(rc == 0); /* Begin advertising */ blecsc_advertise(); } /* * main * * The main task for the project. This function initializes the packages, * then starts serving events from default event queue. * * @return int NOTE: this function should never return! */ int main(void) { int rc; /* Initialize OS */ sysinit(); /* Initialize the NimBLE host configuration */ ble_hs_cfg.sync_cb = blecsc_on_sync; /* Initialize measurement and notification timer */ os_callout_init(&blecsc_measure_timer, os_eventq_dflt_get(), blecsc_measurement, NULL); rc = os_callout_reset(&blecsc_measure_timer, OS_TICKS_PER_SEC); assert(rc == 0); rc = gatt_svr_init(&csc_measurement_state); assert(rc == 0); /* Set the default device name */ rc = ble_svc_gap_device_name_set(device_name); assert(rc == 0); /* As the last thing, process events from default event queue */ while (1) { os_eventq_run(os_eventq_dflt_get()); } return 0; }
17750.c
#include "rb_trees.h" /** * rb_tree_is_valid - valildates RB tree properties * @tree: pointer to root of tree to validate * Return: 1 if valid else 0 */ int rb_tree_is_valid(const rb_tree_t *tree) { size_t b1 = 0, b2 = 0; static int x = 0; if (x == 0 && tree->color != BLACK) return (0); x = 1; if (!tree) return (0); if (tree->color != RED && tree->color != BLACK) return (0); if (tree->color == RED && tree->left && tree->left->color != BLACK) return (0); if (tree->color == RED && tree->right && tree->right->color != BLACK) return (0); b1 = rb_tree_is_valid(tree->left); b2 = rb_tree_is_valid(tree->right); if (b1 != b2) return (0); if (b1 == b2 && tree->color == BLACK) return (1); if (b1 == b2 && tree->color == RED) return (b1); return (0); }
560720.c
/* * Copyright 2014-2019 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <errno.h> #include <inttypes.h> #include "concurrent/aeron_counters_manager.h" #include "concurrent/aeron_logbuffer_unblocker.h" #include "aeron_ipc_publication.h" #include "util/aeron_fileutil.h" #include "aeron_alloc.h" #include "protocol/aeron_udp_protocol.h" #include "aeron_driver_conductor.h" #include "util/aeron_error.h" int aeron_ipc_publication_create( aeron_ipc_publication_t **publication, aeron_driver_context_t *context, int32_t session_id, int32_t stream_id, int64_t registration_id, aeron_position_t *pub_pos_position, aeron_position_t *pub_lmt_position, int32_t initial_term_id, aeron_uri_publication_params_t *params, bool is_exclusive, aeron_system_counters_t *system_counters) { char path[AERON_MAX_PATH]; int path_length = aeron_ipc_publication_location( path, sizeof(path), context->aeron_dir, session_id, stream_id, registration_id); aeron_ipc_publication_t *_pub = NULL; const uint64_t usable_fs_space = context->usable_fs_space_func(context->aeron_dir); const uint64_t log_length = aeron_logbuffer_compute_log_length(params->term_length, context->file_page_size); const int64_t now_ns = context->nano_clock(); *publication = NULL; if (usable_fs_space < log_length) { aeron_set_err( ENOSPC, "Insufficient usable storage for new log of length=%" PRId64 " in %s", log_length, context->aeron_dir); return -1; } if (aeron_alloc((void **)&_pub, sizeof(aeron_ipc_publication_t)) < 0) { aeron_set_err(ENOMEM, "%s", "Could not allocate IPC publication"); return -1; } _pub->log_file_name = NULL; if (aeron_alloc((void **)(&_pub->log_file_name), (size_t)path_length + 1) < 0) { aeron_free(_pub); aeron_set_err(ENOMEM, "%s", "Could not allocate IPC publication log_file_name"); return -1; } if (context->map_raw_log_func( &_pub->mapped_raw_log, path, params->is_sparse, params->term_length, context->file_page_size) < 0) { aeron_free(_pub->log_file_name); aeron_free(_pub); aeron_set_err(aeron_errcode(), "error mapping IPC raw log %s: %s", path, aeron_errmsg()); return -1; } _pub->map_raw_log_close_func = context->map_raw_log_close_func; strncpy(_pub->log_file_name, path, (size_t)path_length); _pub->log_file_name[path_length] = '\0'; _pub->log_file_name_length = (size_t)path_length; _pub->log_meta_data = (aeron_logbuffer_metadata_t *)(_pub->mapped_raw_log.log_meta_data.addr); if (params->is_replay) { int64_t term_id = params->term_id; int32_t term_count = params->term_id - initial_term_id; size_t active_index = aeron_logbuffer_index_by_term_count(term_count); _pub->log_meta_data->term_tail_counters[active_index] = (term_id * ((int64_t)1 << 32)) | params->term_offset; for (int i = 1; i < AERON_LOGBUFFER_PARTITION_COUNT; i++) { int64_t expected_term_id = (term_id + i) - AERON_LOGBUFFER_PARTITION_COUNT; active_index = (active_index + 1) % AERON_LOGBUFFER_PARTITION_COUNT; _pub->log_meta_data->term_tail_counters[active_index] = expected_term_id * ((int64_t)1 << 32); } _pub->log_meta_data->active_term_count = term_count; } else { _pub->log_meta_data->term_tail_counters[0] = initial_term_id * ((int64_t)1 << 32); for (int i = 1; i < AERON_LOGBUFFER_PARTITION_COUNT; i++) { int64_t expected_term_id = (initial_term_id + i) - AERON_LOGBUFFER_PARTITION_COUNT; _pub->log_meta_data->term_tail_counters[i] = expected_term_id * ((int64_t)1 << 32); } _pub->log_meta_data->active_term_count = 0; } _pub->log_meta_data->active_term_count = 0; _pub->log_meta_data->initial_term_id = initial_term_id; _pub->log_meta_data->mtu_length = (int32_t)params->mtu_length; _pub->log_meta_data->term_length = (int32_t)params->term_length; _pub->log_meta_data->page_size = (int32_t)context->file_page_size; _pub->log_meta_data->correlation_id = registration_id; _pub->log_meta_data->is_connected = 0; _pub->log_meta_data->active_transport_count = 0; _pub->log_meta_data->end_of_stream_position = INT64_MAX; aeron_logbuffer_fill_default_header( _pub->mapped_raw_log.log_meta_data.addr, session_id, stream_id, initial_term_id); _pub->nano_clock = context->nano_clock; _pub->conductor_fields.subscribable.array = NULL; _pub->conductor_fields.subscribable.length = 0; _pub->conductor_fields.subscribable.capacity = 0; _pub->conductor_fields.subscribable.add_position_hook_func = aeron_ipc_publication_add_subscriber_hook; _pub->conductor_fields.subscribable.remove_position_hook_func = aeron_ipc_publication_remove_subscriber_hook; _pub->conductor_fields.subscribable.clientd = _pub; _pub->conductor_fields.managed_resource.registration_id = registration_id; _pub->conductor_fields.managed_resource.clientd = _pub; _pub->conductor_fields.managed_resource.incref = aeron_ipc_publication_incref; _pub->conductor_fields.managed_resource.decref = aeron_ipc_publication_decref; _pub->conductor_fields.has_reached_end_of_life = false; _pub->conductor_fields.trip_limit = 0; _pub->conductor_fields.time_of_last_consumer_position_change = now_ns; _pub->conductor_fields.status = AERON_IPC_PUBLICATION_STATUS_ACTIVE; _pub->conductor_fields.refcnt = 1; _pub->session_id = session_id; _pub->stream_id = stream_id; _pub->pub_lmt_position.counter_id = pub_lmt_position->counter_id; _pub->pub_lmt_position.value_addr = pub_lmt_position->value_addr; _pub->pub_pos_position.counter_id = pub_pos_position->counter_id; _pub->pub_pos_position.value_addr = pub_pos_position->value_addr; _pub->initial_term_id = initial_term_id; _pub->position_bits_to_shift = (size_t)aeron_number_of_trailing_zeroes((int32_t)params->term_length); _pub->term_window_length = (int64_t)aeron_producer_window_length( context->ipc_publication_window_length, params->term_length); _pub->trip_gain = _pub->term_window_length / 8; _pub->image_liveness_timeout_ns = (int64_t)context->image_liveness_timeout_ns; _pub->unblock_timeout_ns = (int64_t)context->publication_unblock_timeout_ns; _pub->is_exclusive = is_exclusive; _pub->conductor_fields.consumer_position = aeron_ipc_publication_producer_position(_pub); _pub->conductor_fields.last_consumer_position = _pub->conductor_fields.consumer_position; _pub->conductor_fields.clean_position = _pub->conductor_fields.consumer_position; _pub->unblocked_publications_counter = aeron_system_counter_addr( system_counters, AERON_SYSTEM_COUNTER_UNBLOCKED_PUBLICATIONS); *publication = _pub; return 0; } void aeron_ipc_publication_close(aeron_counters_manager_t *counters_manager, aeron_ipc_publication_t *publication) { aeron_subscribable_t *subscribable = &publication->conductor_fields.subscribable; aeron_counters_manager_free(counters_manager, publication->pub_lmt_position.counter_id); aeron_counters_manager_free(counters_manager, publication->pub_pos_position.counter_id); for (size_t i = 0, length = subscribable->length; i < length; i++) { aeron_counters_manager_free(counters_manager, subscribable->array[i].counter_id); } aeron_free(subscribable->array); if (NULL != publication) { publication->map_raw_log_close_func(&publication->mapped_raw_log, publication->log_file_name); aeron_free(publication->log_file_name); } aeron_free(publication); } int aeron_ipc_publication_update_pub_lmt(aeron_ipc_publication_t *publication) { if (0 == publication->conductor_fields.subscribable.length) { return 0; } int work_count = 0; int64_t min_sub_pos = INT64_MAX; int64_t max_sub_pos = publication->conductor_fields.consumer_position; for (size_t i = 0, length = publication->conductor_fields.subscribable.length; i < length; i++) { aeron_tetherable_position_t *tetherable_position = &publication->conductor_fields.subscribable.array[i]; if (AERON_SUBSCRIPTION_TETHER_RESTING != tetherable_position->state) { int64_t position = aeron_counter_get_volatile(tetherable_position->value_addr); min_sub_pos = position < min_sub_pos ? position : min_sub_pos; max_sub_pos = position > max_sub_pos ? position : max_sub_pos; } } if (0 == publication->conductor_fields.subscribable.length) { aeron_counter_set_ordered(publication->pub_lmt_position.value_addr, max_sub_pos); publication->conductor_fields.trip_limit = max_sub_pos; } else { int64_t proposed_limit = min_sub_pos + publication->term_window_length; if (proposed_limit > publication->conductor_fields.trip_limit) { aeron_ipc_publication_clean_buffer(publication, min_sub_pos); aeron_counter_set_ordered(publication->pub_lmt_position.value_addr, proposed_limit); publication->conductor_fields.trip_limit = proposed_limit + publication->trip_gain; work_count = 1; } publication->conductor_fields.consumer_position = max_sub_pos; } return work_count; } void aeron_ipc_publication_clean_buffer(aeron_ipc_publication_t *publication, int64_t position) { int64_t clean_position = publication->conductor_fields.clean_position; if (position > clean_position) { size_t dirty_index = aeron_logbuffer_index_by_position(clean_position, publication->position_bits_to_shift); size_t bytes_to_clean = position - clean_position; size_t term_length = publication->mapped_raw_log.term_length; size_t term_offset = (size_t)(clean_position & (term_length - 1)); size_t bytes_left_in_term = term_length - term_offset; size_t length = bytes_to_clean < bytes_left_in_term ? bytes_to_clean : bytes_left_in_term; memset( publication->mapped_raw_log.term_buffers[dirty_index].addr + term_offset + sizeof(int64_t), 0, length - sizeof(int64_t)); uint64_t *ptr = (uint64_t *)(publication->mapped_raw_log.term_buffers[dirty_index].addr + term_offset); AERON_PUT_ORDERED(*ptr, (uint64_t)0); publication->conductor_fields.clean_position = clean_position + length; } } void aeron_ipc_publication_check_untethered_subscriptions( aeron_driver_conductor_t *conductor, aeron_ipc_publication_t *publication, int64_t now_ns) { int64_t consumer_position = publication->conductor_fields.consumer_position; int64_t term_window_length = publication->term_window_length; int64_t untethered_window_limit = (consumer_position - term_window_length) + (term_window_length / 8); for (size_t i = 0, length = publication->conductor_fields.subscribable.length; i < length; i++) { aeron_tetherable_position_t *tetherable_position = &publication->conductor_fields.subscribable.array[i]; if (tetherable_position->is_tether) { tetherable_position->time_of_last_update_ns = now_ns; } else { int64_t window_limit_timeout_ns = conductor->context->untethered_window_limit_timeout_ns; int64_t resting_timeout_ns = conductor->context->untethered_resting_timeout_ns; switch (tetherable_position->state) { case AERON_SUBSCRIPTION_TETHER_ACTIVE: if (aeron_counter_get_volatile(tetherable_position->value_addr) > untethered_window_limit) { tetherable_position->time_of_last_update_ns = now_ns; } else if (now_ns > (tetherable_position->time_of_last_update_ns + window_limit_timeout_ns)) { aeron_driver_conductor_on_unavailable_image( conductor, publication->conductor_fields.managed_resource.registration_id, tetherable_position->subscription_registration_id, publication->stream_id, AERON_IPC_CHANNEL, AERON_IPC_CHANNEL_LEN); tetherable_position->state = AERON_SUBSCRIPTION_TETHER_LINGER; tetherable_position->time_of_last_update_ns = now_ns; } break; case AERON_SUBSCRIPTION_TETHER_LINGER: if (now_ns > (tetherable_position->time_of_last_update_ns + window_limit_timeout_ns)) { tetherable_position->state = AERON_SUBSCRIPTION_TETHER_RESTING; tetherable_position->time_of_last_update_ns = now_ns; } break; case AERON_SUBSCRIPTION_TETHER_RESTING: if (now_ns > (tetherable_position->time_of_last_update_ns + resting_timeout_ns)) { aeron_counter_set_ordered(tetherable_position->value_addr, consumer_position); aeron_driver_conductor_on_available_image( conductor, publication->conductor_fields.managed_resource.registration_id, publication->stream_id, publication->session_id, publication->log_file_name, publication->log_file_name_length, tetherable_position->counter_id, tetherable_position->subscription_registration_id, AERON_IPC_CHANNEL, AERON_IPC_CHANNEL_LEN); tetherable_position->state = AERON_SUBSCRIPTION_TETHER_ACTIVE; tetherable_position->time_of_last_update_ns = now_ns; } break; } } } } void aeron_ipc_publication_on_time_event( aeron_driver_conductor_t *conductor, aeron_ipc_publication_t *publication, int64_t now_ns, int64_t now_ms) { const int64_t producer_position = aeron_ipc_publication_producer_position(publication); aeron_counter_set_ordered(publication->pub_pos_position.value_addr, producer_position); switch (publication->conductor_fields.status) { case AERON_IPC_PUBLICATION_STATUS_ACTIVE: aeron_ipc_publication_check_untethered_subscriptions(conductor, publication, now_ns); if (!publication->is_exclusive) { aeron_ipc_publication_check_for_blocked_publisher(publication, producer_position, now_ns); } break; case AERON_IPC_PUBLICATION_STATUS_INACTIVE: if (aeron_ipc_publication_is_drained(publication)) { publication->conductor_fields.status = AERON_IPC_PUBLICATION_STATUS_LINGER; publication->conductor_fields.managed_resource.time_of_last_status_change = now_ns; for (size_t i = 0, size = conductor->ipc_subscriptions.length; i < size; i++) { aeron_subscription_link_t *link = &conductor->ipc_subscriptions.array[i]; if (aeron_driver_conductor_is_subscribable_linked(link, &publication->conductor_fields.subscribable)) { aeron_driver_conductor_on_unavailable_image( conductor, publication->conductor_fields.managed_resource.registration_id, link->registration_id, publication->stream_id, AERON_IPC_CHANNEL, AERON_IPC_CHANNEL_LEN); } } } else if (aeron_logbuffer_unblocker_unblock( publication->mapped_raw_log.term_buffers, publication->log_meta_data, publication->conductor_fields.consumer_position)) { aeron_counter_ordered_increment(publication->unblocked_publications_counter, 1); } break; case AERON_IPC_PUBLICATION_STATUS_LINGER: if (now_ns > (publication->conductor_fields.managed_resource.time_of_last_status_change + publication->image_liveness_timeout_ns)) { publication->conductor_fields.has_reached_end_of_life = true; } break; default: break; } } void aeron_ipc_publication_incref(void *clientd) { aeron_ipc_publication_t *publication = (aeron_ipc_publication_t *)clientd; publication->conductor_fields.refcnt++; } void aeron_ipc_publication_decref(void *clientd) { aeron_ipc_publication_t *publication = (aeron_ipc_publication_t *)clientd; int32_t ref_count = --publication->conductor_fields.refcnt; if (0 == ref_count) { publication->conductor_fields.status = AERON_IPC_PUBLICATION_STATUS_INACTIVE; int64_t producer_position = aeron_ipc_publication_producer_position(publication); if (aeron_counter_get(publication->pub_lmt_position.value_addr) > producer_position) { aeron_counter_set_ordered(publication->pub_lmt_position.value_addr, producer_position); } AERON_PUT_ORDERED(publication->log_meta_data->end_of_stream_position, producer_position); } } void aeron_ipc_publication_check_for_blocked_publisher( aeron_ipc_publication_t *publication, int64_t producer_position, int64_t now_ns) { int64_t consumer_position = publication->conductor_fields.consumer_position; if (consumer_position == publication->conductor_fields.last_consumer_position && aeron_ipc_publication_is_possibly_blocked(publication, producer_position, consumer_position)) { if (now_ns > (publication->conductor_fields.time_of_last_consumer_position_change + publication->unblock_timeout_ns)) { if (aeron_logbuffer_unblocker_unblock( publication->mapped_raw_log.term_buffers, publication->log_meta_data, publication->conductor_fields.consumer_position)) { aeron_counter_ordered_increment(publication->unblocked_publications_counter, 1); } } } else { publication->conductor_fields.time_of_last_consumer_position_change = now_ns; publication->conductor_fields.last_consumer_position = publication->conductor_fields.consumer_position; } } extern void aeron_ipc_publication_add_subscriber_hook(void *clientd, int64_t *value_addr); extern void aeron_ipc_publication_remove_subscriber_hook(void *clientd, int64_t *value_addr); extern bool aeron_ipc_publication_is_possibly_blocked( aeron_ipc_publication_t *publication, int64_t producer_position, int64_t consumer_position); extern int64_t aeron_ipc_publication_producer_position(aeron_ipc_publication_t *publication); extern int64_t aeron_ipc_publication_joining_position(aeron_ipc_publication_t *publication); extern bool aeron_ipc_publication_has_reached_end_of_life(aeron_ipc_publication_t *publication); extern bool aeron_ipc_publication_is_drained(aeron_ipc_publication_t *publication); extern size_t aeron_ipc_publication_num_subscribers(aeron_ipc_publication_t *publication);
547066.c
/* mbed Microcontroller Library * Copyright (c) 2017-2018 Nuvoton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if DEVICE_TRNG #include <stdlib.h> #include <string.h> #include "cmsis.h" #include "us_ticker_api.h" #include "trng_api.h" #include "crypto-misc.h" /* * Get Random number generator. */ #define PRNG_KEY_SIZE (0x20UL) static void trng_get(unsigned char *pConversionData) { uint32_t *p32ConversionData; p32ConversionData = (uint32_t *)pConversionData; PRNG_Open(CRYPTO_MODBASE(), PRNG_KEY_SIZE_256, 1, us_ticker_read()); crypto_prng_prestart(); PRNG_Start(CRYPTO_MODBASE()); crypto_prng_wait(); PRNG_Read(CRYPTO_MODBASE(), p32ConversionData); } void trng_init(trng_t *obj) { (void)obj; /* Init crypto module */ crypto_init(); PRNG_ENABLE_INT(CRYPTO_MODBASE()); } void trng_free(trng_t *obj) { (void)obj; PRNG_DISABLE_INT(CRYPTO_MODBASE()); /* Uninit crypto module */ crypto_uninit(); } int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length) { (void)obj; unsigned char tmpBuff[PRNG_KEY_SIZE]; size_t cur_length = 0; while (length >= sizeof(tmpBuff)) { trng_get(output); output += sizeof(tmpBuff); cur_length += sizeof(tmpBuff); length -= sizeof(tmpBuff); } if (length > 0) { trng_get(tmpBuff); memcpy(output, tmpBuff, length); cur_length += length; crypto_zeroize(tmpBuff, sizeof(tmpBuff)); } *output_length = cur_length; return 0; } #endif
30016.c
/* * Copyright (c) 2019 Alexander Wachter * * SPDX-License-Identifier: Apache-2.0 */ #include <net/can.h> #include <net/net_pkt.h> #include <logging/log.h> LOG_MODULE_REGISTER(net_can, CONFIG_CAN_NET_LOG_LEVEL); struct mcast_filter_mapping { const struct in6_addr *addr; int filter_id; }; struct net_can_context { struct device *can_dev; struct net_if *iface; int recv_filter_id; struct mcast_filter_mapping mcast_mapping[NET_IF_MAX_IPV6_MADDR]; #ifdef CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR int eth_bridge_filter_id; int all_mcast_filter_id; #endif }; static struct net_if_mcast_monitor mcast_monitor; struct mcast_filter_mapping *can_get_mcast_filter(struct net_can_context *ctx, const struct in6_addr *addr) { struct mcast_filter_mapping *map = ctx->mcast_mapping; for (int i = 0; i < NET_IF_MAX_IPV6_MADDR; i++) { if (map[i].addr == addr) { return &map[i]; } } return NULL; } static inline u8_t can_get_frame_datalength(struct zcan_frame *frame) { /* TODO: Needs update when CAN FD support is added */ return frame->dlc; } static inline u16_t can_get_lladdr_src(struct zcan_frame *frame) { return (frame->ext_id >> CAN_NET_IF_ADDR_SRC_POS) & CAN_NET_IF_ADDR_MASK; } static inline u16_t can_get_lladdr_dest(struct zcan_frame *frame) { u16_t addr = (frame->ext_id >> CAN_NET_IF_ADDR_DEST_POS) & CAN_NET_IF_ADDR_MASK; if (frame->ext_id & CAN_NET_IF_ADDR_MCAST_MASK) { addr |= CAN_NET_IF_IS_MCAST_BIT; } return addr; } static inline void can_set_lladdr(struct net_pkt *pkt, struct zcan_frame *frame) { struct net_buf *buf = pkt->buffer; /* Put the destination at the beginning of the pkt. * The net_canbus_lladdr has a size if 14 bits. To convert it to * network byte order, we treat it as 16 bits here. */ net_pkt_lladdr_dst(pkt)->addr = buf->data; net_pkt_lladdr_dst(pkt)->len = sizeof(struct net_canbus_lladdr); net_pkt_lladdr_dst(pkt)->type = NET_LINK_CANBUS; net_buf_add_be16(buf, can_get_lladdr_dest(frame)); net_buf_pull(buf, sizeof(u16_t)); /* Do the same as above for the source address */ net_pkt_lladdr_src(pkt)->addr = buf->data; net_pkt_lladdr_src(pkt)->len = sizeof(struct net_canbus_lladdr); net_pkt_lladdr_src(pkt)->type = NET_LINK_CANBUS; net_buf_add_be16(buf, can_get_lladdr_src(frame)); net_buf_pull(buf, sizeof(u16_t)); } static int net_can_send(struct device *dev, const struct zcan_frame *frame, can_tx_callback_t cb, void *cb_arg, s32_t timeout) { struct net_can_context *ctx = dev->driver_data; NET_ASSERT(frame->id_type == CAN_EXTENDED_IDENTIFIER); return can_send(ctx->can_dev, frame, timeout, cb, cb_arg); } static void net_can_recv(struct zcan_frame *frame, void *arg) { struct net_can_context *ctx = (struct net_can_context *)arg; size_t pkt_size = 2 * sizeof(struct net_canbus_lladdr) + can_get_frame_datalength(frame); struct net_pkt *pkt; int ret; NET_DBG("Frame with ID 0x%x received", frame->ext_id); pkt = net_pkt_rx_alloc_with_buffer(ctx->iface, pkt_size, AF_UNSPEC, 0, K_NO_WAIT); if (!pkt) { LOG_ERR("Failed to obtain net_pkt with size of %d", pkt_size); goto drop; } pkt->canbus_rx_ctx = NULL; can_set_lladdr(pkt, frame); net_pkt_cursor_init(pkt); ret = net_pkt_write(pkt, frame->data, can_get_frame_datalength(frame)); if (ret) { LOG_ERR("Failed to append frame data to net_pkt"); goto drop; } ret = net_recv_data(ctx->iface, pkt); if (ret < 0) { LOG_ERR("Packet dropped by NET stack"); goto drop; } return; drop: NET_INFO("pkt dropped"); if (pkt) { net_pkt_unref(pkt); } } static inline int attach_mcast_filter(struct net_can_context *ctx, const struct in6_addr *addr) { static struct zcan_filter filter = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .rtr_mask = 1, .ext_id_mask = CAN_NET_IF_ADDR_MCAST_MASK | CAN_NET_IF_ADDR_DEST_MASK }; const u16_t group = sys_be16_to_cpu(UNALIGNED_GET((&addr->s6_addr16[7]))); int filter_id; filter.ext_id = CAN_NET_IF_ADDR_MCAST_MASK | ((group & CAN_NET_IF_ADDR_MASK) << CAN_NET_IF_ADDR_DEST_POS); filter_id = can_attach_isr(ctx->can_dev, net_can_recv, ctx, &filter); if (filter_id == CAN_NET_FILTER_NOT_SET) { return CAN_NET_FILTER_NOT_SET; } NET_DBG("Attached mcast filter. Group 0x%04x. Filter:%d", group, filter_id); return filter_id; } static void mcast_cb(struct net_if *iface, const struct in6_addr *addr, bool is_joined) { struct device *dev = net_if_get_device(iface); struct net_can_context *ctx = dev->driver_data; struct mcast_filter_mapping *filter_mapping; int filter_id; if (is_joined) { filter_mapping = can_get_mcast_filter(ctx, NULL); if (!filter_mapping) { NET_ERR("Can't get a free filter_mapping"); } filter_id = attach_mcast_filter(ctx, addr); if (filter_id < 0) { NET_ERR("Can't attach mcast filter"); return; } filter_mapping->addr = addr; filter_mapping->filter_id = filter_id; } else { filter_mapping = can_get_mcast_filter(ctx, addr); if (!filter_mapping) { NET_ERR("No filter mapping found"); return; } can_detach(ctx->can_dev, filter_mapping->filter_id); filter_mapping->addr = NULL; } } static void net_can_iface_init(struct net_if *iface) { struct device *dev = net_if_get_device(iface); struct net_can_context *ctx = dev->driver_data; ctx->iface = iface; NET_DBG("Init CAN network interface %p dev %p", iface, dev); net_6locan_init(iface); net_if_mcast_mon_register(&mcast_monitor, iface, mcast_cb); } static int can_attach_filter(struct device *dev, can_rx_callback_t cb, void *cb_arg, const struct zcan_filter *filter) { struct net_can_context *ctx = dev->driver_data; return can_attach_isr(ctx->can_dev, cb, cb_arg, filter); } static void can_detach_filter(struct device *dev, int filter_id) { struct net_can_context *ctx = dev->driver_data; if (filter_id >= 0) { can_detach(ctx->can_dev, filter_id); } } static inline int can_attach_unicast_filter(struct net_can_context *ctx) { struct zcan_filter filter = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .rtr_mask = 1, .ext_id_mask = CAN_NET_IF_ADDR_DEST_MASK }; const u8_t *link_addr = net_if_get_link_addr(ctx->iface)->addr; const u16_t dest = sys_be16_to_cpu(UNALIGNED_GET((u16_t *) link_addr)); int filter_id; filter.ext_id = (dest << CAN_NET_IF_ADDR_DEST_POS); filter_id = can_attach_isr(ctx->can_dev, net_can_recv, ctx, &filter); if (filter_id == CAN_NET_FILTER_NOT_SET) { NET_ERR("Can't attach FF filter"); return CAN_NET_FILTER_NOT_SET; } NET_DBG("Attached FF filter %d", filter_id); return filter_id; } #ifdef CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR static inline int can_attach_eth_bridge_filter(struct net_can_context *ctx) { const struct zcan_filter filter = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .rtr_mask = 1, .ext_id_mask = CAN_NET_IF_ADDR_DEST_MASK, .ext_id = (NET_CAN_ETH_TRANSLATOR_ADDR << CAN_NET_IF_ADDR_DEST_POS) }; int filter_id; filter_id = can_attach_isr(ctx->can_dev, net_can_recv, ctx, &filter); if (filter_id == CAN_NET_FILTER_NOT_SET) { NET_ERR("Can't attach ETH bridge filter"); return CAN_NET_FILTER_NOT_SET; } NET_DBG("Attached ETH bridge filter %d", filter_id); return filter_id; } static inline int can_attach_all_mcast_filter(struct net_can_context *ctx) { const struct zcan_filter filter = { .id_type = CAN_EXTENDED_IDENTIFIER, .rtr = CAN_DATAFRAME, .rtr_mask = 1, .ext_id_mask = CAN_NET_IF_ADDR_MCAST_MASK, .ext_id = CAN_NET_IF_ADDR_MCAST_MASK }; int filter_id; filter_id = can_attach_isr(ctx->can_dev, net_can_recv, ctx, &filter); if (filter_id == CAN_NET_FILTER_NOT_SET) { NET_ERR("Can't attach all mcast filter"); return CAN_NET_FILTER_NOT_SET; } NET_DBG("Attached all mcast filter %d", filter_id); return filter_id; } #endif /*CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR*/ static int can_enable(struct device *dev, bool enable) { struct net_can_context *ctx = dev->driver_data; if (enable) { if (ctx->recv_filter_id == CAN_NET_FILTER_NOT_SET) { ctx->recv_filter_id = can_attach_unicast_filter(ctx); if (ctx->recv_filter_id < 0) { return -EIO; } } #ifdef CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR if (ctx->eth_bridge_filter_id == CAN_NET_FILTER_NOT_SET) { ctx->eth_bridge_filter_id = can_attach_eth_bridge_filter(ctx); if (ctx->eth_bridge_filter_id < 0) { can_detach(ctx->can_dev, ctx->recv_filter_id); return -EIO; } } if (ctx->all_mcast_filter_id == CAN_NET_FILTER_NOT_SET) { ctx->all_mcast_filter_id = can_attach_all_mcast_filter(ctx); if (ctx->all_mcast_filter_id < 0) { can_detach(ctx->can_dev, ctx->recv_filter_id); can_detach(ctx->can_dev, ctx->eth_bridge_filter_id); return -EIO; } } #endif /*CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR*/ } else { if (ctx->recv_filter_id != CAN_NET_FILTER_NOT_SET) { can_detach(ctx->can_dev, ctx->recv_filter_id); } #ifdef CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR if (ctx->eth_bridge_filter_id != CAN_NET_FILTER_NOT_SET) { can_detach(ctx->can_dev, ctx->eth_bridge_filter_id); } if (ctx->all_mcast_filter_id != CAN_NET_FILTER_NOT_SET) { can_detach(ctx->can_dev, ctx->all_mcast_filter_id); } #endif /*CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR*/ } return 0; } static struct net_can_api net_can_api_inst = { .iface_api.init = net_can_iface_init, .send = net_can_send, .attach_filter = can_attach_filter, .detach_filter = can_detach_filter, .enable = can_enable, }; static int net_can_init(struct device *dev) { struct device *can_dev = device_get_binding(DT_ALIAS_CAN_PRIMARY_LABEL); struct net_can_context *ctx = dev->driver_data; ctx->recv_filter_id = CAN_NET_FILTER_NOT_SET; #ifdef CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR ctx->eth_bridge_filter_id = CAN_NET_FILTER_NOT_SET; ctx->all_mcast_filter_id = CAN_NET_FILTER_NOT_SET; #endif /*CONFIG_NET_L2_CANBUS_ETH_TRANSLATOR*/ if (!can_dev) { NET_ERR("Can't get binding to CAN device %s", DT_ALIAS_CAN_PRIMARY_LABEL); return -EIO; } NET_DBG("Init net CAN device %p (%s) for dev %p (%s)", dev, dev->config->name, can_dev, can_dev->config->name); ctx->can_dev = can_dev; return 0; } static struct net_can_context net_can_context_1; NET_DEVICE_INIT(net_can_1, CONFIG_CAN_NET_NAME, net_can_init, device_pm_control_nop, &net_can_context_1, NULL, CONFIG_CAN_NET_INIT_PRIORITY, &net_can_api_inst, CANBUS_L2, NET_L2_GET_CTX_TYPE(CANBUS_L2), NET_CAN_MTU);
707234.c
/* * cdbfilerepservice.c * * * Copyright 2009-2010 Greenplum Inc. All rights reserved. * */ #include "postgres.h" #include <signal.h> #include <unistd.h> #include "miscadmin.h" #include "catalog/catalog.h" #include "catalog/pg_database.h" #include "catalog/pg_tablespace.h" #include "cdb/cdbfilerepservice.h" #include "cdb/cdbfilerepprimary.h" #include "cdb/cdbfilerepprimaryack.h" #include "cdb/cdbfilerepprimaryrecovery.h" #include "cdb/cdbfilerepmirror.h" #include "cdb/cdbfilerepmirrorack.h" #include "cdb/cdbfilerepresyncmanager.h" #include "cdb/cdbfilerepresyncworker.h" #include "cdb/cdbvars.h" #include "libpq/pqsignal.h" #include "postmaster/postmaster.h" #include "storage/backendid.h" #include "storage/ipc.h" #include "storage/pmsignal.h" #include "storage/proc.h" #include "storage/sinvaladt.h" #include "tcop/tcopprot.h" #include "utils/guc.h" #include "utils/memutils.h" #include "utils/ps_status.h" #include "utils/syscache.h" /* * Initialize external variables. */ FileRepProcessType_e fileRepProcessType = FileRepProcessTypeNotInitialized; static FileRepState_e fileRepState = FileRepStateNotInitialized; /* state of FileRep process */ /* * Parameters set by signal handlers for later service n the main loop */ static volatile sig_atomic_t reloadConfigFile = false; static volatile sig_atomic_t shutdownRequested = false; /* graceful shutdown informed by SIGUSR2 signal from postmaster */ /* state change informed by SIGUSR1 signal from postmaster...when state change request comes in * this counter is incremented. */ static volatile sig_atomic_t stateChangeRequestCounter = 0; /** * This value increases when we process state change requests. There is no pending state change request if * lastChangeRequestProcessCounterValue == stateChangeRequestCounter * * Note that this value is not actually updated in the signal handlers, but must match or exceed the size of * stateChangeRequestCounter so we use its type */ static volatile sig_atomic_t lastChangeRequestProcessCounterValue = 0; /* it is set to TRUE in order to read configuration information at start */ static void FileRepSubProcess_SigHupHandler(SIGNAL_ARGS); static void FileRepSubProcess_ImmediateShutdownHandler(SIGNAL_ARGS); static void FileRepSubProcess_ShutdownHandler(SIGNAL_ARGS); static void FileRepSubProcess_FileRepStateHandler(SIGNAL_ARGS); static void FileRepSubProcess_HandleCrash(SIGNAL_ARGS); static void FileRepSubProcess_ConfigureSignals(void); /* * SIGHUP signal from main file rep process * It re-loads configuration file at next convenient time. */ static void FileRepSubProcess_SigHupHandler(SIGNAL_ARGS) { reloadConfigFile = true; } /* * SIGQUIT signal from main file rep process */ static void FileRepSubProcess_ImmediateShutdownHandler(SIGNAL_ARGS) { quickdie(PASS_SIGNAL_ARGS); } /* * SIGUSR2 signal from main file rep process */ static void FileRepSubProcess_ShutdownHandler(SIGNAL_ARGS) { bool isInTransition = FALSE; DataState_e dataStateTransition; shutdownRequested = true; /* * Exit the process if recv() call is hanging or * compacting is running. Compacting can take many minutes. */ if (fileRepProcessType == FileRepProcessTypePrimaryReceiverAck || fileRepProcessType == FileRepProcessTypeMirrorReceiver || fileRepProcessType == FileRepProcessTypePrimaryRecovery) { /* workaround for gcov testing */ if (Debug_filerep_gcov) { getFileRepRoleAndState(&fileRepRole, &segmentState, &dataState, &isInTransition, &dataStateTransition); if (isInTransition == TRUE && dataStateTransition == DataStateInChangeTracking) { proc_exit(0); return; } } die(PASS_SIGNAL_ARGS); } if ( FileRepIsBackendSubProcess(fileRepProcessType)) { if (FileRepPrimary_IsResyncManagerOrWorker()) { getFileRepRoleAndState(&fileRepRole, &segmentState, &dataState, &isInTransition, &dataStateTransition); if (isInTransition == TRUE && dataStateTransition == DataStateInChangeTracking) { /* * Resync workers and manager may be waiting on lock that is acquired by backend process that is * suspended during transition to Change Tracking and so FileRep backend shutdown may * never be completed. */ if (fileRepProcessType == FileRepProcessTypeResyncManager) { FileRepResync_Cleanup(); } else { LockReleaseAll(DEFAULT_LOCKMETHOD, false); } /* * We remove ourself from LW waiter list (if applicable). * * If the current backend is waiting on a LWLock and exits w/o * any cleanup (remove from waiters list) it can cause a breakage * in the LWlock's waiters linked list after it dies. This can * lead to unpleasant issues causing starvation for subsequent * waiters because the current backend is already dead without * assigning the LWLock to the next waiter. * * XXX Side note - Although implemented here, avoid exiting * inside an signal handler. */ LWLockWaitCancel(); LWLockReleaseAll(); proc_exit(0); return; } } /* call the normal postgres die so that it requests query cancel/procdie */ die(PASS_SIGNAL_ARGS); } } /* * SIGUSR1 signal from main file rep process * It signals about data and/or segment state change. */ static void FileRepSubProcess_FileRepStateHandler(SIGNAL_ARGS) { ++stateChangeRequestCounter; } /* * FileRepSubProcess_ProcessSignals() * */ bool FileRepSubProcess_ProcessSignals() { bool processExit = false; if (reloadConfigFile) { reloadConfigFile = false; ProcessConfigFile(PGC_SIGHUP); FileRep_SetFileRepRetry(); } if (shutdownRequested) { SegmentState_e segmentState; getPrimaryMirrorStatusCodes(NULL, &segmentState, NULL, NULL); shutdownRequested = false; if ( segmentState == SegmentStateShutdownFilerepBackends ) { processExit = FileRepIsBackendSubProcess(fileRepProcessType); FileRepSubProcess_SetState(FileRepStateShutdownBackends); } else { processExit = true; FileRepSubProcess_SetState(FileRepStateShutdown); } } /* * Immediate shutdown if postmaster or main filerep process * (parent) is not alive to avoid manual cleanup. */ if (!PostmasterIsAlive(false /*amDirectChild*/) || !ParentProcIsAlive()) { quickdie_impl(); } for ( ;; ) { /* check to see if change required */ sig_atomic_t curStateChangeRequestCounter = stateChangeRequestCounter; if ( curStateChangeRequestCounter == lastChangeRequestProcessCounterValue ) break; lastChangeRequestProcessCounterValue = curStateChangeRequestCounter; /* do the change in local memory */ getFileRepRoleAndState(&fileRepRole, &segmentState, &dataState, NULL, NULL); switch (segmentState) { case SegmentStateNotInitialized: FileRepSubProcess_SetState(FileRepStateNotInitialized); break; case SegmentStateInitialization: FileRepSubProcess_SetState(FileRepStateInitialization); break; case SegmentStateInResyncTransition: FileRepSubProcess_SetState(FileRepStateInitialization); break; case SegmentStateInChangeTrackingTransition: case SegmentStateInSyncTransition: // fileRepState remains Ready break; case SegmentStateChangeTrackingDisabled: case SegmentStateReady: FileRepSubProcess_SetState(FileRepStateReady); break; case SegmentStateFault: FileRepSubProcess_SetState(FileRepStateFault); break; case SegmentStateShutdownFilerepBackends: if (fileRepRole == FileRepPrimaryRole) { FileRepSubProcess_SetState(FileRepStateShutdownBackends); } else { processExit = true; FileRepSubProcess_SetState(FileRepStateShutdown); } break; case SegmentStateImmediateShutdown: case SegmentStateShutdown: processExit = true; FileRepSubProcess_SetState(FileRepStateShutdown); break; default: Assert(0); break; } // switch() if (processExit == true) { FileRep_IpcSignalAll(); } } return(processExit); } bool FileRepSubProcess_IsStateTransitionRequested(void) { bool isStateTransitionRequested = FALSE; getFileRepRoleAndState(&fileRepRole, &segmentState, &dataState, NULL, NULL); switch (fileRepProcessType) { case FileRepProcessTypeMain: /* Handle Shutdown request */ if (segmentState == SegmentStateImmediateShutdown) { isStateTransitionRequested = TRUE; } break; case FileRepProcessTypeNotInitialized: if (segmentState == SegmentStateShutdownFilerepBackends && fileRepShmemArray[0]->state == FileRepStateFault) { FileRep_InsertConfigLogEntry("failure is detected in segment mirroring during backend shutdown, abort requested"); } /* no break */ default: if (fileRepProcessType != FileRepProcessTypeNotInitialized) { FileRepSubProcess_ProcessSignals(); } if (dataState == DataStateInChangeTracking) { isStateTransitionRequested = TRUE; } switch (segmentState) { case SegmentStateFault: case SegmentStateImmediateShutdown: case SegmentStateShutdown: isStateTransitionRequested = TRUE; break; default: break; } break; } if (isStateTransitionRequested) { FileRep_InsertConfigLogEntry("state transition requested "); } return isStateTransitionRequested; } /* * FileRepSubProcess_GetState() * Return state of FileRep sub-process */ FileRepState_e FileRepSubProcess_GetState(void) { Assert(fileRepState != FileRepStateShutdownBackends ); return fileRepState; } /* * Set state in FileRep process and sent signal to postmaster */ void FileRepSubProcess_SetState(FileRepState_e fileRepStateLocal) { bool doAssignment = true; if ( fileRepStateLocal == FileRepStateShutdownBackends ) { if ( FileRepIsBackendSubProcess(fileRepProcessType)) { /* the current process must shutdown! */ fileRepStateLocal = FileRepStateShutdown; } else { /* the current process doesn't care about shutdown backends -- leave it as shutdown */ doAssignment = false; } } if ( ! doAssignment ) { return; } switch (fileRepState) { case FileRepStateNotInitialized: fileRepState = fileRepStateLocal; break; case FileRepStateInitialization: switch (fileRepStateLocal) { case FileRepStateNotInitialized: ereport(WARNING, (errmsg("mirror failure, " "unexpected filerep state transition from '%s' to '%s' " "failover requested", FileRepStateToString[fileRepState], FileRepStateToString[fileRepStateLocal]), errhint("run gprecoverseg to re-establish mirror connectivity"))); fileRepState = FileRepStateFault; break; default: fileRepState = fileRepStateLocal; break; } break; case FileRepStateReady: switch (fileRepStateLocal) { case FileRepStateFault: case FileRepStateShutdown: fileRepState = fileRepStateLocal; break; case FileRepStateNotInitialized: ereport(WARNING, (errmsg("mirror failure, " "unexpected filerep state transition from '%s' to '%s' " "failover requested", FileRepStateToString[fileRepState], FileRepStateToString[fileRepStateLocal]), errhint("run gprecoverseg to re-establish mirror connectivity"))); fileRepState = FileRepStateFault; break; case FileRepStateInitialization: /* don't do assignment -- this can happen when going from segmentState Ready to InSyncTransition */ doAssignment = false; break; case FileRepStateReady: break; default: Assert(0); break; } break; case FileRepStateFault: switch (fileRepStateLocal) { case FileRepStateFault: case FileRepStateShutdown: fileRepState = fileRepStateLocal; break; case FileRepStateNotInitialized: case FileRepStateInitialization: case FileRepStateReady: ereport(WARNING, (errmsg("mirror failure, " "unexpected filerep state transition from '%s' to '%s' " "failover requested", FileRepStateToString[fileRepState], FileRepStateToString[fileRepStateLocal]), errhint("run gprecoverseg to re-establish mirror connectivity"))); fileRepState = FileRepStateFault; break; default: Assert(0); break; } break; case FileRepStateShutdownBackends: Assert(!"process filerep state should never be in ShutdownBackends"); break; case FileRepStateShutdown: switch (fileRepStateLocal) { case FileRepStateShutdown: fileRepState = fileRepStateLocal; break; case FileRepStateNotInitialized: case FileRepStateInitialization: case FileRepStateReady: ereport(WARNING, (errmsg("mirror failure, " "unexpected filerep state transition from '%s' to '%s' " "failover requested", FileRepStateToString[fileRepState], FileRepStateToString[fileRepStateLocal]), errhint("run gprecoverseg to re-establish mirror connectivity"))); fileRepState = FileRepStateFault; case FileRepStateFault: break; default: Assert(0); break; } break; default: Assert(0); break; } /* check doAssignment again -- may have changed value in the switch above */ if ( ! doAssignment ) { return; } /* now update in shared memory if needed */ switch (fileRepState) { case FileRepStateReady: if (segmentState != SegmentStateChangeTrackingDisabled) { FileRep_SetSegmentState(SegmentStateReady, FaultTypeNotInitialized); } break; case FileRepStateFault: /* update shared memory configuration bool updateSegmentState(FAULT); return TRUE if state was updated; return FALSE if state was already set to FAULT change signal to PMSIGNAL_FILEREP_SEGMENT_STATE_CHANGE */ FileRep_SetSegmentState(SegmentStateFault, FaultTypeMirror); break; case FileRepStateInitialization: case FileRepStateShutdown: case FileRepStateNotInitialized: /* No operation */ break; case FileRepStateShutdownBackends: Assert(0); break; default: Assert(0); break; } /* report the change */ if (fileRepState != FileRepStateShutdown) { FileRep_InsertConfigLogEntry("set filerep state"); } } static void FileRepSubProcess_InitProcess(void) { SetProcessingMode(InitProcessing); /* * Create a resource owner to keep track of our resources */ CurrentResourceOwner = ResourceOwnerCreate(NULL, FileRepProcessTypeToString[fileRepProcessType]); InitXLOGAccess(); SetProcessingMode(NormalProcessing); InitBufferPoolAccess(); /* * Don't add Filerep backend subprocesses to the proc array. * * This avoids any deadlock situations during Filerep transition. E.g. If * a normal backend has acquired ProcArrayLock and is waiting for Filerep * transition to finish, the Filerep backend subprocesses will deadlock * forever as they can't acquire the ProcArray lock to remove themselves * from the ProcArray. This directly causes the transition to stall and thus * the whole system. */ /* * Initialize my entry in the shared-invalidation manager's array of * per-backend data. * * Sets up MyBackendId, a unique backend identifier. */ MyBackendId = InvalidBackendId; SharedInvalBackendInit(false); if (MyBackendId > MaxBackends || MyBackendId <= 0) elog(FATAL, "bad backend id: %d", MyBackendId); /* * bufmgr needs another initialization call too */ InitBufferPoolBackend(); } void FileRepSubProcess_InitHeapAccess(void) { char *fullpath; static bool heapAccessInitialized = false; if (heapAccessInitialized) return; /* heap access requires the rel-cache */ RelationCacheInitialize(); InitCatalogCache(); /* * It's now possible to do real access to the system catalogs. * * Load relcache entries for the system catalogs. This must create at * least the minimum set of "nailed-in" cache entries. */ RelationCacheInitializePhase2(); /* * In order to access the catalog, we need a database, and a * tablespace; our access to the heap is going to be slightly * limited, so we'll just use some defaults. */ MyDatabaseId = TemplateDbOid; MyDatabaseTableSpace = DEFAULTTABLESPACE_OID; /* Now we can mark our PGPROC entry with the database ID */ /* (We assume this is an atomic store so no lock is needed) */ MyProc->databaseId = MyDatabaseId; fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace); SetDatabasePath(fullpath); RelationCacheInitializePhase3(); heapAccessInitialized = true; } static void FileRepSubProcess_HandleCrash(SIGNAL_ARGS) { StandardHandlerForSigillSigsegvSigbus_OnMainThread("a file replication subprocess", PASS_SIGNAL_ARGS); } /* * */ static void FileRepSubProcess_ConfigureSignals(void) { /* Accept Signals */ /* emergency shutdown */ pqsignal(SIGQUIT, FileRepSubProcess_ImmediateShutdownHandler); /* graceful shutdown */ pqsignal(SIGUSR2, FileRepSubProcess_ShutdownHandler); /* reload configuration file */ pqsignal(SIGHUP, FileRepSubProcess_SigHupHandler); /* data or segment state changed */ pqsignal(SIGUSR1, FileRepSubProcess_FileRepStateHandler); /* Ignore Signals */ pqsignal(SIGTERM, SIG_IGN); pqsignal(SIGALRM, SIG_IGN); pqsignal(SIGPIPE, SIG_IGN); /* Use default action */ pqsignal(SIGCHLD, SIG_DFL); pqsignal(SIGINT, SIG_DFL); pqsignal(SIGTTIN, SIG_DFL); pqsignal(SIGTTOU, SIG_DFL); pqsignal(SIGCONT, SIG_DFL); pqsignal(SIGWINCH, SIG_DFL); #ifdef SIGSEGV pqsignal(SIGSEGV, FileRepSubProcess_HandleCrash); #endif #ifdef SIGILL pqsignal(SIGILL, FileRepSubProcess_HandleCrash); #endif #ifdef SIGBUS pqsignal(SIGBUS, FileRepSubProcess_HandleCrash); #endif } /* * */ void FileRepSubProcess_Main() { const char *statmsg; MemoryContext fileRepSubProcessMemoryContext; sigjmp_buf local_sigjmp_buf; MyProcPid = getpid(); MyStartTime = time(NULL); /* * Create a PGPROC so we can use LWLocks in FileRep sub-processes. * The routine also register clean up at process exit */ InitAuxiliaryProcess(); InitBufferPoolBackend(); FileRepSubProcess_ConfigureSignals(); /* * If an exception is encountered, processing resumes here. * * See notes in postgres.c about the design of this coding. */ if (sigsetjmp(local_sigjmp_buf, 1) != 0) { /* Prevents interrupts while cleaning up */ HOLD_INTERRUPTS(); /* Report the error to the server log */ EmitErrorReport(); LWLockReleaseAll(); if (FileRepPrimary_IsResyncManagerOrWorker()) { LockReleaseAll(DEFAULT_LOCKMETHOD, false); } if (FileRepIsBackendSubProcess(fileRepProcessType)) { AbortBufferIO(); UnlockBuffers(); /* buffer pins are released here: */ ResourceOwnerRelease(CurrentResourceOwner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true); } /* * We can now go away. Note that because we'll call InitProcess, a * callback will be registered to do ProcKill, which will clean up * necessary state. */ proc_exit(0); } /* We can now handle ereport(ERROR) */ PG_exception_stack = &local_sigjmp_buf; PG_SETMASK(&UnBlockSig); /* * Identify myself via ps */ statmsg = FileRepProcessTypeToString[fileRepProcessType]; init_ps_display(statmsg, "", "", ""); /* Create the memory context where cross-transaction state is stored */ fileRepSubProcessMemoryContext = AllocSetContextCreate(TopMemoryContext, "filerep subprocess memory context", ALLOCSET_DEFAULT_MINSIZE, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE); MemoryContextSwitchTo(fileRepSubProcessMemoryContext); stateChangeRequestCounter++; FileRepSubProcess_ProcessSignals(); switch (fileRepProcessType) { case FileRepProcessTypePrimarySender: FileRepPrimary_StartSender(); break; case FileRepProcessTypeMirrorReceiver: FileRepMirror_StartReceiver(); break; case FileRepProcessTypeMirrorConsumer: case FileRepProcessTypeMirrorConsumerWriter: case FileRepProcessTypeMirrorConsumerAppendOnly1: FileRepMirror_StartConsumer(); break; case FileRepProcessTypeMirrorSenderAck: FileRepAckMirror_StartSender(); break; case FileRepProcessTypePrimaryReceiverAck: FileRepAckPrimary_StartReceiver(); break; case FileRepProcessTypePrimaryConsumerAck: FileRepAckPrimary_StartConsumer(); break; case FileRepProcessTypePrimaryRecovery: FileRepSubProcess_InitProcess(); /* * At this point, database is starting up and xlog is not * yet replayed. Initializing relcache now is dangerous, * a sequential scan of catalog tables may end up with * incorrect hint bits. E.g. a committed transaction's * dirty heap pages made it to disk but pg_clog update was * still in memory and we crashed. If a tuple inserted by * this transaction is read during relcache * initialization, status of the tuple's xmin will be * incorrectly determined as "not commited" from pg_clog. * And HEAP_XMIN_INVALID hint bit will be set, rendering * the tuple perpetually invisible. Relcache * initialization must be deferred to only after all of * xlog has been replayed. */ FileRepPrimary_StartRecovery(); ResourceOwnerRelease(CurrentResourceOwner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true); break; case FileRepProcessTypeResyncManager: FileRepSubProcess_InitProcess(); FileRepPrimary_StartResyncManager(); ResourceOwnerRelease(CurrentResourceOwner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true); break; case FileRepProcessTypeResyncWorker1: case FileRepProcessTypeResyncWorker2: case FileRepProcessTypeResyncWorker3: case FileRepProcessTypeResyncWorker4: FileRepSubProcess_InitProcess(); FileRepPrimary_StartResyncWorker(); ResourceOwnerRelease(CurrentResourceOwner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true); break; default: elog(PANIC, "unrecognized process type: %s(%d)", statmsg, fileRepProcessType); break; } switch (FileRepSubProcess_GetState()) { case FileRepStateShutdown: case FileRepStateReady: proc_exit(0); break; default: proc_exit(2); break; } }
720572.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* total.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cfelbacq <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/03/21 16:37:24 by cfelbacq #+# #+# */ /* Updated: 2016/03/21 16:39:26 by cfelbacq ### ########.fr */ /* */ /* ************************************************************************** */ #include "ls.h" int round_total(float nb) { int nb_div; nb_div = nb / 512; if (nb / 512 > nb_div) return (nb / 512 + 1); return (nb / 512); } int total(t_l *data) { t_l *tmp; t_stat buf; int total; int count; count = 0; total = 0; tmp = data; while (tmp) { lstat(tmp->path, &buf); total = total + round_total(buf.st_size); tmp = tmp->next; } return (total); }
814596.c
/** * (C) Copyright 2018-2020 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * GOVERNMENT LICENSE RIGHTS-OPEN SOURCE SOFTWARE * The Government's rights to use, modify, reproduce, release, perform, display, * or disclose this software are subject to the terms of the Apache License as * provided in Contract No. B609815. * Any reproduction of computer software, computer software documentation, or * portions thereof marked with this legend must also reproduce the markings. */ /** * This file is part of daos * * vos/vos_io.c */ #define D_LOGFAC DD_FAC(vos) #include <daos/common.h> #include <daos/checksum.h> #include <daos/btree.h> #include <daos_types.h> #include <daos_srv/vos.h> #include <daos.h> #include "vos_internal.h" #include "evt_priv.h" /** I/O context */ struct vos_io_context { daos_epoch_range_t ic_epr; daos_unit_oid_t ic_oid; struct vos_container *ic_cont; daos_iod_t *ic_iods; struct dcs_iod_csums *iod_csums; /** reference on the object */ struct vos_object *ic_obj; /** BIO descriptor, has ic_iod_nr SGLs */ struct bio_desc *ic_biod; struct vos_ts_set *ic_ts_set; /** Checksums for bio_iovs in \ic_biod */ struct dcs_csum_info *ic_biov_csums; uint32_t ic_biov_csums_at; uint32_t ic_biov_csums_nr; /** current dkey info */ struct vos_ilog_info ic_dkey_info; /** current akey info */ struct vos_ilog_info ic_akey_info; /** cursor of SGL & IOV in BIO descriptor */ unsigned int ic_sgl_at; unsigned int ic_iov_at; /** reserved SCM extents */ struct vos_rsrvd_scm *ic_rsrvd_scm; /** reserved offsets for SCM update */ umem_off_t *ic_umoffs; unsigned int ic_umoffs_cnt; unsigned int ic_umoffs_at; /** reserved NVMe extents */ d_list_t ic_blk_exts; daos_size_t ic_space_held[DAOS_MEDIA_MAX]; /** number DAOS IO descriptors */ unsigned int ic_iod_nr; /** deduplication threshold size */ uint32_t ic_dedup_th; /** dedup entries to be inserted after transaction done */ d_list_t ic_dedup_entries; /** flags */ unsigned int ic_update:1, ic_size_fetch:1, ic_save_recx:1, ic_dedup:1, /** candidate for dedup */ ic_read_ts_only:1, ic_check_existence:1, ic_remove:1; /** * Input shadow recx lists, one for each iod. Now only used for degraded * mode EC obj fetch handling. */ struct daos_recx_ep_list *ic_shadows; /** * Output recx/epoch lists, one for each iod. To save the recx list when * vos_fetch_begin() with VOS_OF_FETCH_RECX_LIST flag. User can get it * by vos_ioh2recx_list() and shall free it by daos_recx_ep_list_free(). */ struct daos_recx_ep_list *ic_recx_lists; }; static inline daos_size_t recx_csum_len(daos_recx_t *recx, struct dcs_csum_info *csum, daos_size_t rsize) { if (!ci_is_valid(csum) || rsize == 0) return 0; return csum->cs_len * csum_chunk_count(csum->cs_chunksize, recx->rx_idx, recx->rx_idx + recx->rx_nr - 1, rsize); } struct dedup_entry { d_list_t de_link; uint8_t *de_csum_buf; uint16_t de_csum_type; int de_csum_len; bio_addr_t de_addr; size_t de_data_len; int de_ref; }; static inline struct dedup_entry * dedup_rlink2entry(d_list_t *rlink) { return container_of(rlink, struct dedup_entry, de_link); } static bool dedup_key_cmp(struct d_hash_table *htable, d_list_t *rlink, const void *key, unsigned int csum_len) { struct dedup_entry *entry = dedup_rlink2entry(rlink); struct dcs_csum_info *csum = (struct dcs_csum_info *)key; D_ASSERT(entry->de_csum_len != 0); D_ASSERT(csum_len != 0); /** different containers might use different checksum algorithm */ if (entry->de_csum_type != csum->cs_type) return false; /** overall checksum size (for all chunks) should match */ if (entry->de_csum_len != csum_len) return false; D_ASSERT(csum->cs_csum != NULL); D_ASSERT(entry->de_csum_buf != NULL); return memcmp(entry->de_csum_buf, csum->cs_csum, csum_len) == 0; } static uint32_t dedup_key_hash(struct d_hash_table *htable, const void *key, unsigned int csum_len) { struct dcs_csum_info *csum = (struct dcs_csum_info *)key; D_ASSERT(csum_len != 0); D_ASSERT(csum->cs_csum != NULL); return d_hash_string_u32((const char *)csum->cs_csum, csum_len); } static void dedup_rec_addref(struct d_hash_table *htable, d_list_t *rlink) { struct dedup_entry *entry = dedup_rlink2entry(rlink); entry->de_ref++; } static bool dedup_rec_decref(struct d_hash_table *htable, d_list_t *rlink) { struct dedup_entry *entry = dedup_rlink2entry(rlink); D_ASSERT(entry->de_ref > 0); entry->de_ref--; return entry->de_ref == 0; } static void dedup_rec_free(struct d_hash_table *htable, d_list_t *rlink) { struct dedup_entry *entry = dedup_rlink2entry(rlink); D_ASSERT(entry->de_ref == 0); D_ASSERT(entry->de_csum_buf != NULL); D_FREE(entry->de_csum_buf); D_FREE(entry); } static d_hash_table_ops_t dedup_hash_ops = { .hop_key_cmp = dedup_key_cmp, .hop_key_hash = dedup_key_hash, .hop_rec_addref = dedup_rec_addref, .hop_rec_decref = dedup_rec_decref, .hop_rec_free = dedup_rec_free, }; int vos_dedup_init(struct vos_pool *pool) { int rc; rc = d_hash_table_create(D_HASH_FT_NOLOCK, 13, /* 8k buckets */ NULL, &dedup_hash_ops, &pool->vp_dedup_hash); if (rc) D_ERROR(DF_UUID": Init dedup hash failed. "DF_RC".\n", DP_UUID(pool->vp_id), DP_RC(rc)); return rc; } void vos_dedup_fini(struct vos_pool *pool) { if (pool->vp_dedup_hash) { d_hash_table_destroy(pool->vp_dedup_hash, true); pool->vp_dedup_hash = NULL; } } void vos_dedup_invalidate(struct vos_pool *pool) { vos_dedup_fini(pool); vos_dedup_init(pool); } static bool vos_dedup_lookup(struct vos_pool *pool, struct dcs_csum_info *csum, daos_size_t csum_len, struct bio_iov *biov) { struct dedup_entry *entry; d_list_t *rlink; if (!ci_is_valid(csum)) return false; rlink = d_hash_rec_find(pool->vp_dedup_hash, csum, csum_len); if (rlink == NULL) return false; entry = dedup_rlink2entry(rlink); if (biov) { biov->bi_addr = entry->de_addr; biov->bi_addr.ba_dedup = true; biov->bi_data_len = entry->de_data_len; D_DEBUG(DB_IO, "Found dedup entry\n"); } D_ASSERT(entry->de_ref > 1); d_hash_rec_decref(pool->vp_dedup_hash, rlink); return true; } static void vos_dedup_update(struct vos_pool *pool, struct dcs_csum_info *csum, daos_size_t csum_len, struct bio_iov *biov, d_list_t *list) { struct dedup_entry *entry; if (!ci_is_valid(csum) || csum_len == 0 || biov->bi_addr.ba_dedup) return; if (bio_addr_is_hole(&biov->bi_addr)) return; if (vos_dedup_lookup(pool, csum, csum_len, NULL)) return; D_ALLOC_PTR(entry); if (entry == NULL) { D_ERROR("Failed to allocate dedup entry\n"); return; } D_INIT_LIST_HEAD(&entry->de_link); D_ASSERT(csum_len != 0); D_ALLOC(entry->de_csum_buf, csum_len); if (entry->de_csum_buf == NULL) { D_ERROR("Failed to allocate csum buf "DF_U64"\n", csum_len); D_FREE(entry); return; } entry->de_csum_len = csum_len; entry->de_csum_type = csum->cs_type; entry->de_addr = biov->bi_addr; entry->de_data_len = biov->bi_data_len; memcpy(entry->de_csum_buf, csum->cs_csum, csum_len); d_list_add_tail(&entry->de_link, list); D_DEBUG(DB_IO, "Inserted dedup entry in list\n"); } static void vos_dedup_process(struct vos_pool *pool, d_list_t *list, bool abort) { struct dedup_entry *entry, *tmp; struct dcs_csum_info csum = { 0 }; int rc; d_list_for_each_entry_safe(entry, tmp, list, de_link) { d_list_del_init(&entry->de_link); if (abort) goto free_entry; /* * No yield since vos_dedup_update() is called, so it's safe * to insert entries to hash without checking. */ csum.cs_csum = entry->de_csum_buf; csum.cs_type = entry->de_csum_type; rc = d_hash_rec_insert(pool->vp_dedup_hash, &csum, entry->de_csum_len, &entry->de_link, false); if (rc == 0) { D_DEBUG(DB_IO, "Inserted dedup entry\n"); continue; } D_ERROR("Insert dedup entry failed. "DF_RC"\n", DP_RC(rc)); free_entry: D_FREE(entry->de_csum_buf); D_FREE(entry); } } static inline struct umem_instance * vos_ioc2umm(struct vos_io_context *ioc) { return &ioc->ic_cont->vc_pool->vp_umm; } static struct vos_io_context * vos_ioh2ioc(daos_handle_t ioh) { return (struct vos_io_context *)ioh.cookie; } static daos_handle_t vos_ioc2ioh(struct vos_io_context *ioc) { daos_handle_t ioh; ioh.cookie = (uint64_t)ioc; return ioh; } static struct dcs_csum_info * vos_ioc2csum(struct vos_io_context *ioc) { /** is enabled and has csums (might not for punch) */ if (ioc->iod_csums != NULL && ioc->iod_csums[ioc->ic_sgl_at].ic_nr > 0) return ioc->iod_csums[ioc->ic_sgl_at].ic_data; return NULL; } static void iod_empty_sgl(struct vos_io_context *ioc, unsigned int sgl_at) { struct bio_sglist *bsgl; D_ASSERT(sgl_at < ioc->ic_iod_nr); ioc->ic_iods[sgl_at].iod_size = 0; bsgl = bio_iod_sgl(ioc->ic_biod, sgl_at); bsgl->bs_nr_out = 0; } static void vos_ioc_reserve_fini(struct vos_io_context *ioc) { if (ioc->ic_rsrvd_scm != NULL) { D_ASSERT(ioc->ic_rsrvd_scm->rs_actv_at == 0); D_FREE(ioc->ic_rsrvd_scm); } D_ASSERT(d_list_empty(&ioc->ic_blk_exts)); D_ASSERT(d_list_empty(&ioc->ic_dedup_entries)); if (ioc->ic_umoffs != NULL) { D_FREE(ioc->ic_umoffs); ioc->ic_umoffs = NULL; } } static int vos_ioc_reserve_init(struct vos_io_context *ioc, struct dtx_handle *dth) { struct vos_rsrvd_scm *scm; size_t size; int total_acts = 0; int i; if (!ioc->ic_update) return 0; for (i = 0; i < ioc->ic_iod_nr; i++) { daos_iod_t *iod = &ioc->ic_iods[i]; total_acts += iod->iod_nr; } D_ALLOC_ARRAY(ioc->ic_umoffs, total_acts); if (ioc->ic_umoffs == NULL) return -DER_NOMEM; if (vos_ioc2umm(ioc)->umm_ops->mo_reserve == NULL) return 0; size = sizeof(*ioc->ic_rsrvd_scm) + sizeof(struct pobj_action) * total_acts; D_ALLOC(ioc->ic_rsrvd_scm, size); if (ioc->ic_rsrvd_scm == NULL) return -DER_NOMEM; ioc->ic_rsrvd_scm->rs_actv_cnt = total_acts; if (!dtx_is_valid_handle(dth) || dth->dth_deferred == NULL) return 0; /** Reserve enough space for any deferred actions */ D_ALLOC(scm, size); if (scm == NULL) { D_FREE(ioc->ic_rsrvd_scm); return -DER_NOMEM; } scm->rs_actv_cnt = total_acts; dth->dth_deferred[dth->dth_deferred_cnt++] = scm; return 0; } static void vos_ioc_destroy(struct vos_io_context *ioc, bool evict) { if (ioc->ic_biod != NULL) bio_iod_free(ioc->ic_biod); if (ioc->ic_biov_csums != NULL) D_FREE(ioc->ic_biov_csums); if (ioc->ic_obj) vos_obj_release(vos_obj_cache_current(), ioc->ic_obj, evict); vos_ioc_reserve_fini(ioc); vos_ilog_fetch_finish(&ioc->ic_dkey_info); vos_ilog_fetch_finish(&ioc->ic_akey_info); vos_cont_decref(ioc->ic_cont); vos_ts_set_free(ioc->ic_ts_set); D_FREE(ioc); } static int vos_ioc_create(daos_handle_t coh, daos_unit_oid_t oid, bool read_only, daos_epoch_t epoch, unsigned int iod_nr, daos_iod_t *iods, struct dcs_iod_csums *iod_csums, uint32_t vos_flags, struct daos_recx_ep_list *shadows, bool dedup, uint32_t dedup_th, struct dtx_handle *dth, struct vos_io_context **ioc_pp) { struct vos_container *cont; struct vos_io_context *ioc = NULL; struct bio_io_context *bioc; uint64_t cflags = 0; int i, rc; if (iod_nr == 0 && !(vos_flags & (VOS_OF_FETCH_SET_TS_ONLY | VOS_OF_FETCH_CHECK_EXISTENCE))) { D_ERROR("Invalid iod_nr (0).\n"); rc = -DER_IO_INVAL; goto error; } D_ALLOC_PTR(ioc); if (ioc == NULL) return -DER_NOMEM; ioc->ic_iod_nr = iod_nr; ioc->ic_iods = iods; ioc->ic_epr.epr_hi = dtx_is_valid_handle(dth) ? dth->dth_epoch : epoch; ioc->ic_epr.epr_lo = 0; ioc->ic_oid = oid; ioc->ic_cont = vos_hdl2cont(coh); vos_cont_addref(ioc->ic_cont); ioc->ic_update = !read_only; ioc->ic_size_fetch = ((vos_flags & VOS_OF_FETCH_SIZE_ONLY) != 0); ioc->ic_save_recx = ((vos_flags & VOS_OF_FETCH_RECX_LIST) != 0); ioc->ic_dedup = dedup; ioc->ic_dedup_th = dedup_th; ioc->ic_read_ts_only = ((vos_flags & VOS_OF_FETCH_SET_TS_ONLY) != 0); ioc->ic_check_existence = ((vos_flags & VOS_OF_FETCH_CHECK_EXISTENCE) != 0); ioc->ic_remove = ((vos_flags & VOS_OF_REMOVE) != 0); ioc->ic_umoffs_cnt = ioc->ic_umoffs_at = 0; ioc->iod_csums = iod_csums; vos_ilog_fetch_init(&ioc->ic_dkey_info); vos_ilog_fetch_init(&ioc->ic_akey_info); D_INIT_LIST_HEAD(&ioc->ic_blk_exts); ioc->ic_shadows = shadows; D_INIT_LIST_HEAD(&ioc->ic_dedup_entries); rc = vos_ioc_reserve_init(ioc, dth); if (rc != 0) goto error; if (dtx_is_valid_handle(dth)) { if (read_only) { cflags = VOS_TS_READ_AKEY; if (vos_flags & VOS_OF_COND_DKEY_FETCH) cflags |= VOS_TS_READ_DKEY; } else { cflags = VOS_TS_WRITE_AKEY; if (vos_flags & VOS_COND_AKEY_UPDATE_MASK) cflags |= VOS_TS_READ_AKEY; /** This can be improved but for now, keep it simple. * It will mean updating read timestamps on any akeys * that don't have a condition set. */ if (vos_flags & VOS_OF_COND_PER_AKEY) cflags |= VOS_TS_READ_AKEY; if (vos_flags & VOS_COND_DKEY_UPDATE_MASK) cflags |= VOS_TS_READ_DKEY; } } rc = vos_ts_set_allocate(&ioc->ic_ts_set, vos_flags, cflags, iod_nr, dtx_is_valid_handle(dth) ? &dth->dth_xid : NULL); if (rc != 0) goto error; if (ioc->ic_read_ts_only || ioc->ic_check_existence) { *ioc_pp = ioc; return 0; } cont = vos_hdl2cont(coh); bioc = cont->vc_pool->vp_io_ctxt; D_ASSERT(bioc != NULL); ioc->ic_biod = bio_iod_alloc(bioc, iod_nr, !read_only); if (ioc->ic_biod == NULL) { rc = -DER_NOMEM; goto error; } ioc->ic_biov_csums_nr = 1; ioc->ic_biov_csums_at = 0; D_ALLOC_ARRAY(ioc->ic_biov_csums, ioc->ic_biov_csums_nr); if (ioc->ic_biov_csums == NULL) { rc = -DER_NOMEM; goto error; } for (i = 0; i < iod_nr; i++) { int iov_nr = iods[i].iod_nr; struct bio_sglist *bsgl; if ((iods[i].iod_type == DAOS_IOD_SINGLE && iov_nr != 1) || (iov_nr == 0 && iods[i].iod_recxs != NULL)) { D_ERROR("Invalid iod_nr=%d, iod_type %d.\n", iov_nr, iods[i].iod_type); rc = -DER_IO_INVAL; goto error; } /* Don't bother to initialize SGLs for size fetch */ if (ioc->ic_size_fetch) continue; bsgl = bio_iod_sgl(ioc->ic_biod, i); rc = bio_sgl_init(bsgl, iov_nr); if (rc != 0) goto error; } *ioc_pp = ioc; return 0; error: if (ioc != NULL) vos_ioc_destroy(ioc, false); return rc; } static int iod_fetch(struct vos_io_context *ioc, struct bio_iov *biov) { struct bio_sglist *bsgl; int iov_nr, iov_at; if (ioc->ic_size_fetch) return 0; bsgl = bio_iod_sgl(ioc->ic_biod, ioc->ic_sgl_at); D_ASSERT(bsgl != NULL); iov_nr = bsgl->bs_nr; iov_at = ioc->ic_iov_at; D_ASSERT(iov_nr > iov_at); D_ASSERT(iov_nr >= bsgl->bs_nr_out); if (iov_at == iov_nr - 1) { struct bio_iov *biovs; D_REALLOC_ARRAY(biovs, bsgl->bs_iovs, (iov_nr * 2)); if (biovs == NULL) return -DER_NOMEM; bsgl->bs_iovs = biovs; bsgl->bs_nr = iov_nr * 2; } bsgl->bs_iovs[iov_at] = *biov; bsgl->bs_nr_out++; ioc->ic_iov_at++; return 0; } static int bsgl_csums_resize(struct vos_io_context *ioc) { struct dcs_csum_info *csums = ioc->ic_biov_csums; uint32_t dcb_nr = ioc->ic_biov_csums_nr; if (ioc->ic_size_fetch) return 0; if (ioc->ic_biov_csums_at == dcb_nr - 1) { struct dcs_csum_info *new_infos; uint32_t new_nr = dcb_nr * 2; D_REALLOC_ARRAY(new_infos, csums, new_nr); if (new_infos == NULL) return -DER_NOMEM; ioc->ic_biov_csums = new_infos; ioc->ic_biov_csums_nr = new_nr; } return 0; } /** Save the checksum to a list that can be retrieved later */ static int save_csum(struct vos_io_context *ioc, struct dcs_csum_info *csum_info, struct evt_entry *entry, daos_size_t rec_size) { struct dcs_csum_info *saved_csum_info; int rc; if (ioc->ic_size_fetch) return 0; rc = bsgl_csums_resize(ioc); if (rc != 0) return rc; /** * it's expected that the csum the csum_info points to is in memory * that will persist until fetch is complete ... so memcpy isn't needed */ saved_csum_info = &ioc->ic_biov_csums[ioc->ic_biov_csums_at]; *saved_csum_info = *csum_info; if (entry != NULL) evt_entry_csum_update(&entry->en_ext, &entry->en_sel_ext, saved_csum_info, rec_size); ioc->ic_biov_csums_at++; return 0; } /** Fetch the single value within the specified epoch range of an key */ static int akey_fetch_single(daos_handle_t toh, const daos_epoch_range_t *epr, daos_size_t *rsize, struct vos_io_context *ioc) { struct vos_svt_key key; struct vos_rec_bundle rbund; d_iov_t kiov; /* iov to carry key bundle */ d_iov_t riov; /* iov to carry record bundle */ struct bio_iov biov; /* iov to return data buffer */ int rc; struct dcs_csum_info csum_info = {0}; d_iov_set(&kiov, &key, sizeof(key)); key.sk_epoch = epr->epr_hi; key.sk_minor_epc = VOS_MINOR_EPC_MAX; tree_rec_bundle2iov(&rbund, &riov); memset(&biov, 0, sizeof(biov)); rbund.rb_biov = &biov; rbund.rb_csum = &csum_info; rc = dbtree_fetch(toh, BTR_PROBE_LE, DAOS_INTENT_DEFAULT, &kiov, &kiov, &riov); if (rc == -DER_NONEXIST) { rbund.rb_rsize = 0; bio_addr_set_hole(&biov.bi_addr, 1); rc = 0; } else if (rc != 0) { goto out; } else if (key.sk_epoch < epr->epr_lo) { /* The single value is before the valid epoch range (after a * punch when incarnation log is available */ rc = 0; rbund.rb_rsize = 0; bio_addr_set_hole(&biov.bi_addr, 1); } if (ci_is_valid(&csum_info)) save_csum(ioc, &csum_info, NULL, 0); rc = iod_fetch(ioc, &biov); if (rc != 0) goto out; *rsize = rbund.rb_gsize; out: return rc; } static inline void biov_set_hole(struct bio_iov *biov, ssize_t len) { memset(biov, 0, sizeof(*biov)); bio_iov_set_len(biov, len); bio_addr_set_hole(&biov->bi_addr, 1); } /** * Calculate the bio_iov and extent chunk alignment and set appropriate * prefix & suffix on the biov so that whole chunks are fetched in case needed * for checksum calculation and verification. * Should only be called when the entity has a valid checksum. */ static void biov_align_lens(struct bio_iov *biov, struct evt_entry *ent, daos_size_t rsize) { struct evt_extent aligned_extent; aligned_extent = evt_entry_align_to_csum_chunk(ent, rsize); bio_iov_set_extra(biov, (ent->en_sel_ext.ex_lo - aligned_extent.ex_lo) * rsize, (aligned_extent.ex_hi - ent->en_sel_ext.ex_hi) * rsize); } /** * Save to recx/ep list, user can get it by vos_ioh2recx_list() and then free * the memory. */ static int save_recx(struct vos_io_context *ioc, uint64_t rx_idx, uint64_t rx_nr, daos_epoch_t ep, uint32_t rec_size, int type) { struct daos_recx_ep_list *recx_list; struct daos_recx_ep recx_ep; if (ioc->ic_recx_lists == NULL) { D_ALLOC_ARRAY(ioc->ic_recx_lists, ioc->ic_iod_nr); if (ioc->ic_recx_lists == NULL) return -DER_NOMEM; } recx_list = &ioc->ic_recx_lists[ioc->ic_sgl_at]; recx_ep.re_recx.rx_idx = rx_idx; recx_ep.re_recx.rx_nr = rx_nr; recx_ep.re_ep = ep; recx_ep.re_type = type; recx_ep.re_rec_size = rec_size; return daos_recx_ep_add(recx_list, &recx_ep); } /** Fetch an extent from an akey */ static int akey_fetch_recx(daos_handle_t toh, const daos_epoch_range_t *epr, daos_recx_t *recx, daos_epoch_t shadow_ep, daos_size_t *rsize_p, struct vos_io_context *ioc) { struct evt_entry *ent; /* At present, this is not exposed in interface but passing it toggles * sorting and clipping of rectangles */ struct evt_entry_array ent_array = { 0 }; struct evt_filter filter; struct bio_iov biov = {0}; daos_size_t holes; /* hole width */ daos_size_t rsize; daos_off_t index; daos_off_t end; bool csum_enabled = false; bool with_shadow = (shadow_ep != DAOS_EPOCH_MAX); int rc; index = recx->rx_idx; end = recx->rx_idx + recx->rx_nr; filter.fr_ex.ex_lo = index; filter.fr_ex.ex_hi = end - 1; filter.fr_epr = *epr; filter.fr_punch_epc = ioc->ic_akey_info.ii_prior_punch.pr_epc; filter.fr_punch_minor_epc = ioc->ic_akey_info.ii_prior_punch.pr_minor_epc; evt_ent_array_init(&ent_array); rc = evt_find(toh, &filter, &ent_array); if (rc != 0) goto failed; holes = 0; rsize = 0; evt_ent_array_for_each(ent, &ent_array) { daos_off_t lo = ent->en_sel_ext.ex_lo; daos_off_t hi = ent->en_sel_ext.ex_hi; daos_size_t nr; D_ASSERT(hi >= lo); nr = hi - lo + 1; if (lo != index) { D_ASSERTF(lo > index, DF_U64"/"DF_U64", "DF_EXT", "DF_ENT"\n", lo, index, DP_EXT(&filter.fr_ex), DP_ENT(ent)); holes += lo - index; } /* Hole extent, with_shadow case only used for EC obj */ if (bio_addr_is_hole(&ent->en_addr) || (with_shadow && (ent->en_epoch < shadow_ep))) { index = lo + nr; holes += nr; continue; } if (holes != 0) { if (with_shadow) { rc = save_recx(ioc, lo - holes, holes, shadow_ep, ent_array.ea_inob, DRT_SHADOW); if (rc != 0) goto failed; } biov_set_hole(&biov, holes * ent_array.ea_inob); /* skip the hole */ rc = iod_fetch(ioc, &biov); if (rc != 0) goto failed; holes = 0; } if (rsize == 0) rsize = ent_array.ea_inob; D_ASSERT(rsize == ent_array.ea_inob); if (ioc->ic_save_recx) { rc = save_recx(ioc, lo, nr, ent->en_epoch, ent_array.ea_inob, DRT_NORMAL); if (rc != 0) goto failed; } bio_iov_set(&biov, ent->en_addr, nr * ent_array.ea_inob); if (ci_is_valid(&ent->en_csum)) { rc = save_csum(ioc, &ent->en_csum, ent, rsize); if (rc != 0) return rc; biov_align_lens(&biov, ent, rsize); csum_enabled = true; } else { bio_iov_set_extra(&biov, 0, 0); if (csum_enabled) D_ERROR("Checksum found in some entries, " "but not all\n"); } rc = iod_fetch(ioc, &biov); if (rc != 0) goto failed; index = lo + nr; } D_ASSERT(index <= end); if (index < end) holes += end - index; if (holes != 0) { /* trailing holes */ if (with_shadow) { rc = save_recx(ioc, end - holes, holes, shadow_ep, ent_array.ea_inob, DRT_SHADOW); if (rc != 0) goto failed; } biov_set_hole(&biov, holes * ent_array.ea_inob); rc = iod_fetch(ioc, &biov); if (rc != 0) goto failed; } if (rsize_p && *rsize_p == 0) *rsize_p = rsize; failed: evt_ent_array_fini(&ent_array); return rc; } /* Trim the tail holes for the current sgl */ static void ioc_trim_tail_holes(struct vos_io_context *ioc) { struct bio_sglist *bsgl; struct bio_iov *biov; int i; if (ioc->ic_size_fetch) return; bsgl = bio_iod_sgl(ioc->ic_biod, ioc->ic_sgl_at); for (i = ioc->ic_iov_at - 1; i >= 0; i--) { biov = &bsgl->bs_iovs[i]; if (bio_addr_is_hole(&biov->bi_addr)) bsgl->bs_nr_out--; else break; } if (bsgl->bs_nr_out == 0) iod_empty_sgl(ioc, ioc->ic_sgl_at); } static int key_ilog_check(struct vos_io_context *ioc, struct vos_krec_df *krec, const struct vos_ilog_info *parent, daos_epoch_range_t *epr_out, struct vos_ilog_info *info) { struct umem_instance *umm; daos_epoch_range_t epr = ioc->ic_epr; int rc; umm = vos_obj2umm(ioc->ic_obj); rc = vos_ilog_fetch(umm, vos_cont2hdl(ioc->ic_cont), DAOS_INTENT_DEFAULT, &krec->kr_ilog, epr.epr_hi, 0, parent, info); if (rc != 0) goto out; rc = vos_ilog_check(info, &epr, epr_out, true); out: D_DEBUG(DB_TRACE, "ilog check returned "DF_RC" epr_in="DF_X64"-"DF_X64 " punch="DF_PUNCH" epr_out="DF_X64"-"DF_X64"\n", DP_RC(rc), epr.epr_lo, epr.epr_hi, DP_PUNCH(&info->ii_prior_punch), epr_out ? epr_out->epr_lo : 0, epr_out ? epr_out->epr_hi : 0); return rc; } static void akey_fetch_recx_get(daos_recx_t *iod_recx, struct daos_recx_ep_list *shadow, daos_recx_t *fetch_recx, daos_epoch_t *shadow_ep) { struct daos_recx_ep *recx_ep; daos_recx_t *recx; uint32_t i; if (shadow == NULL) goto no_shadow; for (i = 0; i < shadow->re_nr; i++) { recx_ep = &shadow->re_items[i]; recx = &recx_ep->re_recx; if (!DAOS_RECX_PTR_OVERLAP(iod_recx, recx)) continue; fetch_recx->rx_idx = iod_recx->rx_idx; fetch_recx->rx_nr = min((iod_recx->rx_idx + iod_recx->rx_nr), (recx->rx_idx + recx->rx_nr)) - iod_recx->rx_idx; D_ASSERT(fetch_recx->rx_nr > 0 && fetch_recx->rx_nr <= iod_recx->rx_nr); iod_recx->rx_idx += fetch_recx->rx_nr; iod_recx->rx_nr -= fetch_recx->rx_nr; *shadow_ep = recx_ep->re_ep; return; } no_shadow: *fetch_recx = *iod_recx; iod_recx->rx_idx += fetch_recx->rx_nr; iod_recx->rx_nr -= fetch_recx->rx_nr; *shadow_ep = DAOS_EPOCH_MAX; } static bool stop_on_empty(struct vos_io_context *ioc, uint64_t cond, daos_iod_t *iod, int *rc) { uint64_t flags; if (*rc != -DER_NONEXIST) return false; if (ioc->ic_check_existence) return true; if (ioc->ic_ts_set == NULL) return false; if (ioc->ic_read_ts_only) { *rc = 0; return true; } if (iod != NULL && ioc->ic_ts_set->ts_flags & VOS_OF_COND_PER_AKEY) { /** Per akey flags have been specified */ flags = iod->iod_flags; } else { flags = ioc->ic_ts_set->ts_flags; } if (flags & cond) return true; return false; } static int akey_fetch(struct vos_io_context *ioc, daos_handle_t ak_toh) { daos_iod_t *iod = &ioc->ic_iods[ioc->ic_sgl_at]; struct vos_krec_df *krec = NULL; daos_epoch_range_t val_epr = {0}; daos_handle_t toh = DAOS_HDL_INVAL; int i, rc; int flags = 0; bool is_array = (iod->iod_type == DAOS_IOD_ARRAY); struct daos_recx_ep_list *shadow; D_DEBUG(DB_IO, "akey "DF_KEY" fetch %s epr "DF_X64"-"DF_X64"\n", DP_KEY(&iod->iod_name), iod->iod_type == DAOS_IOD_ARRAY ? "array" : "single", ioc->ic_epr.epr_lo, ioc->ic_epr.epr_hi); if (is_array) flags |= SUBTR_EVT; rc = key_tree_prepare(ioc->ic_obj, ak_toh, VOS_BTR_AKEY, &iod->iod_name, flags, DAOS_INTENT_DEFAULT, &krec, &toh, ioc->ic_ts_set); if (rc != 0) { if (stop_on_empty(ioc, VOS_OF_COND_AKEY_FETCH, iod, &rc)) goto out; if (rc == -DER_NONEXIST) { D_DEBUG(DB_IO, "Nonexistent akey "DF_KEY"\n", DP_KEY(&iod->iod_name)); iod_empty_sgl(ioc, ioc->ic_sgl_at); rc = 0; } else { D_ERROR("Failed to fetch akey: "DF_RC"\n", DP_RC(rc)); } goto out; } rc = key_ilog_check(ioc, krec, &ioc->ic_dkey_info, &val_epr, &ioc->ic_akey_info); if (rc != 0) { if (stop_on_empty(ioc, VOS_OF_COND_AKEY_FETCH, iod, &rc)) goto out; if (rc == -DER_NONEXIST) { iod_empty_sgl(ioc, ioc->ic_sgl_at); D_DEBUG(DB_IO, "Nonexistent akey %.*s\n", (int)iod->iod_name.iov_len, (char *)iod->iod_name.iov_buf); rc = 0; } else { D_CDEBUG(rc == -DER_INPROGRESS, DB_IO, DLOG_ERR, "Fetch akey failed: rc="DF_RC"\n", DP_RC(rc)); } goto out; } if (ioc->ic_read_ts_only || ioc->ic_check_existence) goto out; /* skip value fetch */ if (iod->iod_type == DAOS_IOD_SINGLE) { rc = akey_fetch_single(toh, &val_epr, &iod->iod_size, ioc); goto out; } iod->iod_size = 0; shadow = (ioc->ic_shadows == NULL) ? NULL : &ioc->ic_shadows[ioc->ic_sgl_at]; for (i = 0; i < iod->iod_nr; i++) { daos_recx_t iod_recx; daos_recx_t fetch_recx; daos_epoch_t shadow_ep; daos_size_t rsize = 0; if (iod->iod_recxs[i].rx_nr == 0) { D_DEBUG(DB_IO, "Skip empty read IOD at %d: idx %lu, nr %lu\n", i, (unsigned long)iod->iod_recxs[i].rx_idx, (unsigned long)iod->iod_recxs[i].rx_nr); continue; } iod_recx = iod->iod_recxs[i]; while (iod_recx.rx_nr > 0) { akey_fetch_recx_get(&iod_recx, shadow, &fetch_recx, &shadow_ep); rc = akey_fetch_recx(toh, &val_epr, &fetch_recx, shadow_ep, &rsize, ioc); if (rc != 0) { D_DEBUG(DB_IO, "Failed to fetch index %d: " DF_RC"\n", i, DP_RC(rc)); goto out; } } /* * Empty tree or all holes, DAOS array API relies on zero * iod_size to see if an array cell is empty. */ if (rsize == 0) continue; if (iod->iod_size == DAOS_REC_ANY) iod->iod_size = rsize; if (iod->iod_size != rsize) { D_ERROR("Cannot support mixed record size " DF_U64"/"DF_U64"\n", iod->iod_size, rsize); rc = -DER_INVAL; goto out; } } ioc_trim_tail_holes(ioc); out: if (!daos_handle_is_inval(toh)) key_tree_release(toh, is_array); return rc; } static void iod_set_cursor(struct vos_io_context *ioc, unsigned int sgl_at) { D_ASSERT(sgl_at < ioc->ic_iod_nr); D_ASSERT(ioc->ic_iods != NULL); ioc->ic_sgl_at = sgl_at; ioc->ic_iov_at = 0; } static int dkey_fetch(struct vos_io_context *ioc, daos_key_t *dkey) { struct vos_object *obj = ioc->ic_obj; struct vos_krec_df *krec; daos_handle_t toh = DAOS_HDL_INVAL; int i, rc; rc = obj_tree_init(obj); if (rc != 0) return rc; rc = key_tree_prepare(obj, obj->obj_toh, VOS_BTR_DKEY, dkey, 0, DAOS_INTENT_DEFAULT, &krec, &toh, ioc->ic_ts_set); if (stop_on_empty(ioc, VOS_COND_FETCH_MASK | VOS_OF_COND_PER_AKEY, NULL, &rc)) goto out; if (rc == -DER_NONEXIST) { for (i = 0; i < ioc->ic_iod_nr; i++) iod_empty_sgl(ioc, i); D_DEBUG(DB_IO, "Nonexistent dkey\n"); rc = 0; goto out; } if (rc != 0) { D_ERROR("Failed to prepare subtree: "DF_RC"\n", DP_RC(rc)); goto out; } rc = key_ilog_check(ioc, krec, &obj->obj_ilog_info, &ioc->ic_epr, &ioc->ic_dkey_info); if (rc != 0) { if (stop_on_empty(ioc, VOS_COND_FETCH_MASK | VOS_OF_COND_PER_AKEY, NULL, &rc)) goto out; if (rc == -DER_NONEXIST) { for (i = 0; i < ioc->ic_iod_nr; i++) iod_empty_sgl(ioc, i); D_DEBUG(DB_IO, "Nonexistent dkey\n"); rc = 0; } else { D_CDEBUG(rc == -DER_INPROGRESS, DB_IO, DLOG_ERR, "Fetch dkey failed: rc="DF_RC"\n", DP_RC(rc)); } goto out; } for (i = 0; i < ioc->ic_iod_nr; i++) { iod_set_cursor(ioc, i); rc = akey_fetch(ioc, toh); if (rc != 0) break; } out: if (!daos_handle_is_inval(toh)) key_tree_release(toh, false); return rc; } int vos_fetch_end(daos_handle_t ioh, int err) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); /* NB: it's OK to use the stale ioc->ic_obj for fetch_end */ D_ASSERT(!ioc->ic_update); vos_ioc_destroy(ioc, false); return err; } int vos_fetch_begin(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, uint32_t vos_flags, struct daos_recx_ep_list *shadows, daos_handle_t *ioh, struct dtx_handle *dth) { struct vos_io_context *ioc; int i, rc; D_DEBUG(DB_TRACE, "Fetch "DF_UOID", desc_nr %d, epoch "DF_X64"\n", DP_UOID(oid), iod_nr, epoch); rc = vos_ioc_create(coh, oid, true, epoch, iod_nr, iods, NULL, vos_flags, shadows, false, 0, dth, &ioc); if (rc != 0) return rc; vos_dth_set(dth); rc = vos_ts_set_add(ioc->ic_ts_set, ioc->ic_cont->vc_ts_idx, NULL, 0); D_ASSERT(rc == 0); rc = vos_obj_hold(vos_obj_cache_current(), ioc->ic_cont, oid, &ioc->ic_epr, true, DAOS_INTENT_DEFAULT, true, &ioc->ic_obj, ioc->ic_ts_set); if (rc != -DER_NONEXIST && rc != 0) goto out; if (stop_on_empty(ioc, VOS_COND_FETCH_MASK | VOS_OF_COND_PER_AKEY, NULL, &rc)) { if (rc == 0) goto set_ioc; goto out; } if (rc == -DER_NONEXIST) { rc = 0; for (i = 0; i < iod_nr; i++) iod_empty_sgl(ioc, i); } else { if (dkey == NULL || dkey->iov_len == 0) { if (ioc->ic_read_ts_only) goto set_ioc; D_GOTO(out, rc = -DER_INVAL); } rc = dkey_fetch(ioc, dkey); if (rc != 0) goto out; } set_ioc: *ioh = vos_ioc2ioh(ioc); out: vos_dth_set(NULL); if (rc == -DER_NONEXIST || rc == 0) vos_ts_set_update(ioc->ic_ts_set, ioc->ic_epr.epr_hi); if (rc != 0) { daos_recx_ep_list_free(ioc->ic_recx_lists, ioc->ic_iod_nr); ioc->ic_recx_lists = NULL; return vos_fetch_end(vos_ioc2ioh(ioc), rc); } return 0; } static umem_off_t iod_update_umoff(struct vos_io_context *ioc) { umem_off_t umoff; D_ASSERTF(ioc->ic_umoffs_at < ioc->ic_umoffs_cnt, "Invalid ioc_reserve at/cnt: %u/%u\n", ioc->ic_umoffs_at, ioc->ic_umoffs_cnt); umoff = ioc->ic_umoffs[ioc->ic_umoffs_at]; ioc->ic_umoffs_at++; return umoff; } static struct bio_iov * iod_update_biov(struct vos_io_context *ioc) { struct bio_sglist *bsgl; struct bio_iov *biov; bsgl = bio_iod_sgl(ioc->ic_biod, ioc->ic_sgl_at); D_ASSERT(bsgl->bs_nr_out != 0); D_ASSERT(bsgl->bs_nr_out > ioc->ic_iov_at); biov = &bsgl->bs_iovs[ioc->ic_iov_at]; ioc->ic_iov_at++; return biov; } static int akey_update_single(daos_handle_t toh, uint32_t pm_ver, daos_size_t rsize, daos_size_t gsize, struct vos_io_context *ioc, uint16_t minor_epc) { struct vos_svt_key key; struct vos_rec_bundle rbund; struct dcs_csum_info csum; d_iov_t kiov, riov; struct bio_iov *biov; umem_off_t umoff; daos_epoch_t epoch = ioc->ic_epr.epr_hi; int rc; ci_set_null(&csum); d_iov_set(&kiov, &key, sizeof(key)); key.sk_epoch = epoch; key.sk_minor_epc = minor_epc; umoff = iod_update_umoff(ioc); D_ASSERT(!UMOFF_IS_NULL(umoff)); D_ASSERT(ioc->ic_iov_at == 0); biov = iod_update_biov(ioc); tree_rec_bundle2iov(&rbund, &riov); struct dcs_csum_info *value_csum = vos_ioc2csum(ioc); if (value_csum != NULL) rbund.rb_csum = value_csum; else rbund.rb_csum = &csum; rbund.rb_biov = biov; rbund.rb_rsize = rsize; rbund.rb_gsize = gsize; rbund.rb_off = umoff; rbund.rb_ver = pm_ver; rc = dbtree_update(toh, &kiov, &riov); if (rc != 0) D_ERROR("Failed to update subtree: "DF_RC"\n", DP_RC(rc)); return rc; } /** * Update a record extent. * See comment of vos_recx_fetch for explanation of @off_p. */ static int akey_update_recx(daos_handle_t toh, uint32_t pm_ver, daos_recx_t *recx, struct dcs_csum_info *csum, daos_size_t rsize, struct vos_io_context *ioc, uint16_t minor_epc) { struct evt_entry_in ent; struct bio_iov *biov; daos_epoch_t epoch = ioc->ic_epr.epr_hi; int rc; D_ASSERT(recx->rx_nr > 0); memset(&ent, 0, sizeof(ent)); ent.ei_rect.rc_epc = epoch; ent.ei_rect.rc_ex.ex_lo = recx->rx_idx; ent.ei_rect.rc_ex.ex_hi = recx->rx_idx + recx->rx_nr - 1; ent.ei_rect.rc_minor_epc = minor_epc; ent.ei_ver = pm_ver; ent.ei_inob = rsize; if (csum != NULL) ent.ei_csum = *csum; biov = iod_update_biov(ioc); ent.ei_addr = biov->bi_addr; ent.ei_addr.ba_dedup = false; /* Don't make this flag persistent */ if (ioc->ic_remove) return evt_remove_all(toh, &ent.ei_rect.rc_ex, &ioc->ic_epr); rc = evt_insert(toh, &ent, NULL); if (ioc->ic_dedup && !rc && (rsize * recx->rx_nr) >= ioc->ic_dedup_th) { daos_size_t csum_len = recx_csum_len(recx, csum, rsize); vos_dedup_update(vos_cont2pool(ioc->ic_cont), csum, csum_len, biov, &ioc->ic_dedup_entries); } return rc; } static int akey_update(struct vos_io_context *ioc, uint32_t pm_ver, daos_handle_t ak_toh, uint16_t minor_epc) { struct vos_object *obj = ioc->ic_obj; struct vos_krec_df *krec = NULL; daos_iod_t *iod = &ioc->ic_iods[ioc->ic_sgl_at]; struct dcs_csum_info *iod_csums = vos_ioc2csum(ioc); struct dcs_csum_info *recx_csum = NULL; uint32_t update_cond = 0; bool is_array = (iod->iod_type == DAOS_IOD_ARRAY); int flags = SUBTR_CREATE; daos_handle_t toh = DAOS_HDL_INVAL; int i; int rc = 0; D_DEBUG(DB_TRACE, "akey "DF_KEY" update %s value eph "DF_X64"\n", DP_KEY(&iod->iod_name), is_array ? "array" : "single", ioc->ic_epr.epr_hi); if (is_array) flags |= SUBTR_EVT; rc = key_tree_prepare(obj, ak_toh, VOS_BTR_AKEY, &iod->iod_name, flags, DAOS_INTENT_UPDATE, &krec, &toh, ioc->ic_ts_set); if (rc != 0) return rc; if (ioc->ic_ts_set) { uint64_t akey_flags; if (ioc->ic_ts_set->ts_flags & VOS_OF_COND_PER_AKEY) akey_flags = iod->iod_flags; else akey_flags = ioc->ic_ts_set->ts_flags; switch (akey_flags) { case VOS_OF_COND_AKEY_UPDATE: update_cond = VOS_ILOG_COND_UPDATE; break; case VOS_OF_COND_AKEY_INSERT: update_cond = VOS_ILOG_COND_INSERT; break; default: break; } } rc = vos_ilog_update(ioc->ic_cont, &krec->kr_ilog, &ioc->ic_epr, &ioc->ic_dkey_info, &ioc->ic_akey_info, update_cond, ioc->ic_ts_set); if (update_cond == VOS_ILOG_COND_UPDATE && rc == -DER_NONEXIST) { D_DEBUG(DB_IO, "Conditional update on non-existent akey\n"); goto out; } if (update_cond == VOS_ILOG_COND_INSERT && rc == -DER_EXIST) { D_DEBUG(DB_IO, "Conditional insert on existent akey\n"); goto out; } if (rc != 0) { VOS_TX_LOG_FAIL(rc, "Failed to update akey ilog: "DF_RC"\n", DP_RC(rc)); goto out; } if (iod->iod_type == DAOS_IOD_SINGLE) { uint64_t gsize; gsize = (iod->iod_recxs == NULL) ? iod->iod_size : (uintptr_t)iod->iod_recxs; rc = akey_update_single(toh, pm_ver, iod->iod_size, gsize, ioc, minor_epc); goto out; } /* else: array */ for (i = 0; i < iod->iod_nr; i++) { umem_off_t umoff = iod_update_umoff(ioc); if (iod->iod_recxs[i].rx_nr == 0) { D_ASSERT(UMOFF_IS_NULL(umoff)); D_DEBUG(DB_IO, "Skip empty write IOD at %d: idx %lu, nr %lu\n", i, (unsigned long)iod->iod_recxs[i].rx_idx, (unsigned long)iod->iod_recxs[i].rx_nr); continue; } if (iod_csums != NULL) recx_csum = &iod_csums[i]; rc = akey_update_recx(toh, pm_ver, &iod->iod_recxs[i], recx_csum, iod->iod_size, ioc, minor_epc); if (rc != 0) goto out; } out: if (!daos_handle_is_inval(toh)) key_tree_release(toh, is_array); return rc; } static int dkey_update(struct vos_io_context *ioc, uint32_t pm_ver, daos_key_t *dkey, uint16_t minor_epc) { struct vos_object *obj = ioc->ic_obj; daos_handle_t ak_toh; struct vos_krec_df *krec; uint32_t update_cond = 0; bool subtr_created = false; int i, rc; rc = obj_tree_init(obj); if (rc != 0) return rc; rc = key_tree_prepare(obj, obj->obj_toh, VOS_BTR_DKEY, dkey, SUBTR_CREATE, DAOS_INTENT_UPDATE, &krec, &ak_toh, ioc->ic_ts_set); if (rc != 0) { D_ERROR("Error preparing dkey tree: rc="DF_RC"\n", DP_RC(rc)); goto out; } subtr_created = true; if (ioc->ic_ts_set) { if (ioc->ic_ts_set->ts_flags & VOS_COND_UPDATE_OP_MASK) update_cond = VOS_ILOG_COND_UPDATE; else if (ioc->ic_ts_set->ts_flags & VOS_OF_COND_DKEY_INSERT) update_cond = VOS_ILOG_COND_INSERT; } rc = vos_ilog_update(ioc->ic_cont, &krec->kr_ilog, &ioc->ic_epr, &obj->obj_ilog_info, &ioc->ic_dkey_info, update_cond, ioc->ic_ts_set); if (update_cond == VOS_ILOG_COND_UPDATE && rc == -DER_NONEXIST) { D_DEBUG(DB_IO, "Conditional update on non-existent akey\n"); goto out; } if (update_cond == VOS_ILOG_COND_INSERT && rc == -DER_EXIST) { D_DEBUG(DB_IO, "Conditional insert on existent akey\n"); goto out; } if (rc != 0) { VOS_TX_LOG_FAIL(rc, "Failed to update dkey ilog: "DF_RC"\n", DP_RC(rc)); goto out; } for (i = 0; i < ioc->ic_iod_nr; i++) { iod_set_cursor(ioc, i); rc = akey_update(ioc, pm_ver, ak_toh, minor_epc); if (rc != 0) goto out; } out: if (!subtr_created) return rc; if (rc != 0) goto release; release: key_tree_release(ak_toh, false); return rc; } daos_size_t vos_recx2irec_size(daos_size_t rsize, struct dcs_csum_info *csum) { struct vos_rec_bundle rbund; rbund.rb_csum = csum; rbund.rb_rsize = rsize; return vos_irec_size(&rbund); } umem_off_t vos_reserve_scm(struct vos_container *cont, struct vos_rsrvd_scm *rsrvd_scm, daos_size_t size) { umem_off_t umoff; D_ASSERT(size > 0); if (vos_cont2umm(cont)->umm_ops->mo_reserve != NULL) { struct pobj_action *act; D_ASSERT(rsrvd_scm != NULL); D_ASSERT(rsrvd_scm->rs_actv_cnt > rsrvd_scm->rs_actv_at); act = &rsrvd_scm->rs_actv[rsrvd_scm->rs_actv_at]; umoff = umem_reserve(vos_cont2umm(cont), act, size); if (!UMOFF_IS_NULL(umoff)) rsrvd_scm->rs_actv_at++; } else { umoff = umem_alloc(vos_cont2umm(cont), size); } return umoff; } int vos_reserve_blocks(struct vos_container *cont, d_list_t *rsrvd_nvme, daos_size_t size, enum vos_io_stream ios, uint64_t *off) { struct vea_space_info *vsi; struct vea_hint_context *hint_ctxt; struct vea_resrvd_ext *ext; uint32_t blk_cnt; int rc; vsi = vos_cont2pool(cont)->vp_vea_info; D_ASSERT(vsi); hint_ctxt = cont->vc_hint_ctxt[ios]; D_ASSERT(hint_ctxt); blk_cnt = vos_byte2blkcnt(size); rc = vea_reserve(vsi, blk_cnt, hint_ctxt, rsrvd_nvme); if (rc) return rc; ext = d_list_entry(rsrvd_nvme->prev, struct vea_resrvd_ext, vre_link); D_ASSERTF(ext->vre_blk_cnt == blk_cnt, "%u != %u\n", ext->vre_blk_cnt, blk_cnt); D_ASSERT(ext->vre_blk_off != 0); *off = ext->vre_blk_off << VOS_BLK_SHIFT; return 0; } static int reserve_space(struct vos_io_context *ioc, uint16_t media, daos_size_t size, uint64_t *off) { int rc; if (media == DAOS_MEDIA_SCM) { umem_off_t umoff; umoff = vos_reserve_scm(ioc->ic_cont, ioc->ic_rsrvd_scm, size); if (!UMOFF_IS_NULL(umoff)) { ioc->ic_umoffs[ioc->ic_umoffs_cnt] = umoff; ioc->ic_umoffs_cnt++; *off = umoff; return 0; } D_ERROR("Reserve "DF_U64" from SCM failed.\n", size); return -DER_NOSPACE; } D_ASSERT(media == DAOS_MEDIA_NVME); rc = vos_reserve_blocks(ioc->ic_cont, &ioc->ic_blk_exts, size, VOS_IOS_GENERIC, off); if (rc) D_ERROR("Reserve "DF_U64" from NVMe failed. "DF_RC"\n", size, DP_RC(rc)); return rc; } static int iod_reserve(struct vos_io_context *ioc, struct bio_iov *biov) { struct bio_sglist *bsgl; bsgl = bio_iod_sgl(ioc->ic_biod, ioc->ic_sgl_at); D_ASSERT(bsgl->bs_nr != 0); D_ASSERT(bsgl->bs_nr > bsgl->bs_nr_out); D_ASSERT(bsgl->bs_nr > ioc->ic_iov_at); bsgl->bs_iovs[ioc->ic_iov_at] = *biov; ioc->ic_iov_at++; bsgl->bs_nr_out++; D_DEBUG(DB_TRACE, "media %hu offset "DF_U64" size %zd\n", biov->bi_addr.ba_type, biov->bi_addr.ba_off, bio_iov2len(biov)); return 0; } /* Reserve single value record on specified media */ static int vos_reserve_single(struct vos_io_context *ioc, uint16_t media, daos_size_t size) { struct vos_irec_df *irec; daos_size_t scm_size; umem_off_t umoff; struct bio_iov biov; uint64_t off = 0; int rc; struct dcs_csum_info *value_csum = vos_ioc2csum(ioc); /* * TODO: * To eliminate internal fragmentaion, misaligned record (record size * isn't aligned with 4K) on NVMe could be split into two parts, large * aligned part will be stored on NVMe and being referenced by * vos_irec_df->ir_ex_addr, small unaligned part will be stored on SCM * along with vos_irec_df, being referenced by vos_irec_df->ir_body. */ scm_size = (media == DAOS_MEDIA_SCM) ? vos_recx2irec_size(size, value_csum) : vos_recx2irec_size(0, value_csum); rc = reserve_space(ioc, DAOS_MEDIA_SCM, scm_size, &off); if (rc) { D_ERROR("Reserve SCM for SV failed. "DF_RC"\n", DP_RC(rc)); return rc; } D_ASSERT(ioc->ic_umoffs_cnt > 0); umoff = ioc->ic_umoffs[ioc->ic_umoffs_cnt - 1]; irec = (struct vos_irec_df *) umem_off2ptr(vos_ioc2umm(ioc), umoff); vos_irec_init_csum(irec, value_csum); memset(&biov, 0, sizeof(biov)); if (size == 0) { /* punch */ bio_addr_set_hole(&biov.bi_addr, 1); goto done; } if (media == DAOS_MEDIA_SCM) { char *payload_addr; /* Get the record payload offset */ payload_addr = vos_irec2data(irec); D_ASSERT(payload_addr >= (char *)irec); off = umoff + (payload_addr - (char *)irec); } else { rc = reserve_space(ioc, DAOS_MEDIA_NVME, size, &off); if (rc) { D_ERROR("Reserve NVMe for SV failed. "DF_RC"\n", DP_RC(rc)); return rc; } } done: bio_addr_set(&biov.bi_addr, media, off); bio_iov_set_len(&biov, size); rc = iod_reserve(ioc, &biov); return rc; } static int vos_reserve_recx(struct vos_io_context *ioc, uint16_t media, daos_size_t size, struct dcs_csum_info *csum, daos_size_t csum_len) { struct bio_iov biov; uint64_t off = 0; int rc; memset(&biov, 0, sizeof(biov)); /* recx punch */ if (size == 0 || media != DAOS_MEDIA_SCM) { ioc->ic_umoffs[ioc->ic_umoffs_cnt] = UMOFF_NULL; ioc->ic_umoffs_cnt++; if (size == 0) { bio_addr_set_hole(&biov.bi_addr, 1); goto done; } } if (ioc->ic_dedup && size >= ioc->ic_dedup_th && vos_dedup_lookup(vos_cont2pool(ioc->ic_cont), csum, csum_len, &biov)) { if (biov.bi_data_len == size) { D_ASSERT(biov.bi_addr.ba_off != 0); ioc->ic_umoffs[ioc->ic_umoffs_cnt] = biov.bi_addr.ba_off; ioc->ic_umoffs_cnt++; return iod_reserve(ioc, &biov); } memset(&biov, 0, sizeof(biov)); } /* * TODO: * To eliminate internal fragmentaion, misaligned recx (total recx size * isn't aligned with 4K) on NVMe could be split into two evtree rects, * larger rect will be stored on NVMe and small reminder on SCM. */ rc = reserve_space(ioc, media, size, &off); if (rc) { D_ERROR("Reserve recx failed. "DF_RC"\n", DP_RC(rc)); return rc; } done: bio_addr_set(&biov.bi_addr, media, off); bio_iov_set_len(&biov, size); rc = iod_reserve(ioc, &biov); return rc; } static int akey_update_begin(struct vos_io_context *ioc) { struct dcs_csum_info *iod_csums = vos_ioc2csum(ioc); struct dcs_csum_info *recx_csum; daos_iod_t *iod = &ioc->ic_iods[ioc->ic_sgl_at]; int i, rc; if (iod->iod_type == DAOS_IOD_SINGLE && iod->iod_nr != 1) { D_ERROR("Invalid sv iod_nr=%d\n", iod->iod_nr); return -DER_IO_INVAL; } for (i = 0; i < iod->iod_nr; i++) { daos_size_t size; uint16_t media; size = (iod->iod_type == DAOS_IOD_SINGLE) ? iod->iod_size : iod->iod_recxs[i].rx_nr * iod->iod_size; media = vos_media_select(vos_cont2pool(ioc->ic_cont), iod->iod_type, size); recx_csum = (iod_csums != NULL) ? &iod_csums[i] : NULL; if (iod->iod_type == DAOS_IOD_SINGLE) { rc = vos_reserve_single(ioc, media, size); } else { daos_size_t csum_len; csum_len = recx_csum_len(&iod->iod_recxs[i], recx_csum, iod->iod_size); rc = vos_reserve_recx(ioc, media, size, recx_csum, csum_len); } if (rc) return rc; } return 0; } static int dkey_update_begin(struct vos_io_context *ioc) { int i, rc = 0; for (i = 0; i < ioc->ic_iod_nr; i++) { iod_set_cursor(ioc, i); rc = akey_update_begin(ioc); if (rc != 0) break; } return rc; } int vos_publish_scm(struct vos_container *cont, struct vos_rsrvd_scm *rsrvd_scm, bool publish) { int rc = 0; if (rsrvd_scm == NULL || rsrvd_scm->rs_actv_at == 0) return 0; D_ASSERT(rsrvd_scm->rs_actv_at <= rsrvd_scm->rs_actv_cnt); if (publish) rc = umem_tx_publish(vos_cont2umm(cont), rsrvd_scm->rs_actv, rsrvd_scm->rs_actv_at); else umem_cancel(vos_cont2umm(cont), rsrvd_scm->rs_actv, rsrvd_scm->rs_actv_at); rsrvd_scm->rs_actv_at = 0; return rc; } /* Publish or cancel the NVMe block reservations */ int vos_publish_blocks(struct vos_container *cont, d_list_t *blk_list, bool publish, enum vos_io_stream ios) { struct vea_space_info *vsi; struct vea_hint_context *hint_ctxt; int rc; if (d_list_empty(blk_list)) return 0; vsi = cont->vc_pool->vp_vea_info; D_ASSERT(vsi); hint_ctxt = cont->vc_hint_ctxt[ios]; D_ASSERT(hint_ctxt); rc = publish ? vea_tx_publish(vsi, hint_ctxt, blk_list) : vea_cancel(vsi, hint_ctxt, blk_list); if (rc) D_ERROR("Error on %s NVMe reservations. "DF_RC"\n", publish ? "publish" : "cancel", DP_RC(rc)); return rc; } static void update_cancel(struct vos_io_context *ioc) { /* Cancel SCM reservations or free persistent allocations */ if (vos_cont2umm(ioc->ic_cont)->umm_ops->mo_reserve != NULL) return; if (ioc->ic_umoffs_cnt != 0) { struct umem_instance *umem = vos_ioc2umm(ioc); int i; D_ASSERT(umem->umm_id == UMEM_CLASS_VMEM); for (i = 0; i < ioc->ic_umoffs_cnt; i++) { if (!UMOFF_IS_NULL(ioc->ic_umoffs[i])) /* Ignore umem_free failure. */ umem_free(umem, ioc->ic_umoffs[i]); } } /* Abort dedup entries */ vos_dedup_process(vos_cont2pool(ioc->ic_cont), &ioc->ic_dedup_entries, true /* abort */); } int vos_update_end(daos_handle_t ioh, uint32_t pm_ver, daos_key_t *dkey, int err, struct dtx_handle *dth) { struct vos_dtx_act_ent **daes = NULL; struct vos_io_context *ioc = vos_ioh2ioc(ioh); struct umem_instance *umem; uint64_t time = 0; bool tx_started = false; VOS_TIME_START(time, VOS_UPDATE_END); D_ASSERT(ioc->ic_update); if (err != 0) goto abort; err = vos_ts_set_add(ioc->ic_ts_set, ioc->ic_cont->vc_ts_idx, NULL, 0); D_ASSERT(err == 0); umem = vos_ioc2umm(ioc); err = vos_tx_begin(dth, umem); if (err != 0) goto abort; tx_started = true; vos_dth_set(dth); /* Commit the CoS DTXs via the IO PMDK transaction. */ if (dtx_is_valid_handle(dth) && dth->dth_dti_cos_count > 0) { D_ALLOC_ARRAY(daes, dth->dth_dti_cos_count); if (daes == NULL) D_GOTO(abort, err = -DER_NOMEM); err = vos_dtx_commit_internal(ioc->ic_cont, dth->dth_dti_cos, dth->dth_dti_cos_count, 0, NULL, daes); if (err <= 0) D_FREE(daes); } err = vos_obj_hold(vos_obj_cache_current(), ioc->ic_cont, ioc->ic_oid, &ioc->ic_epr, false, DAOS_INTENT_UPDATE, true, &ioc->ic_obj, ioc->ic_ts_set); if (err != 0) goto abort; /* Update tree index */ err = dkey_update(ioc, pm_ver, dkey, dtx_is_valid_handle(dth) ? dth->dth_op_seq : VOS_MINOR_EPC_MAX); if (err) { VOS_TX_LOG_FAIL(err, "Failed to update tree index: "DF_RC"\n", DP_RC(err)); goto abort; } /** Now that we are past the existence checks, ensure there isn't a * read conflict */ if (vos_ts_set_check_conflict(ioc->ic_ts_set, ioc->ic_epr.epr_hi)) { err = -DER_TX_RESTART; goto abort; } abort: err = vos_tx_end(ioc->ic_cont, dth, &ioc->ic_rsrvd_scm, &ioc->ic_blk_exts, tx_started, err); if (err == 0) { if (daes != NULL) vos_dtx_post_handle(ioc->ic_cont, daes, dth->dth_dti_cos_count, false); vos_dedup_process(vos_cont2pool(ioc->ic_cont), &ioc->ic_dedup_entries, false); } else { update_cancel(ioc); } D_FREE(daes); if (err == 0) vos_ts_set_upgrade(ioc->ic_ts_set); if (err == -DER_NONEXIST || err == -DER_EXIST || err == 0) vos_ts_set_update(ioc->ic_ts_set, ioc->ic_epr.epr_hi); VOS_TIME_END(time, VOS_UPDATE_END); vos_space_unhold(vos_cont2pool(ioc->ic_cont), &ioc->ic_space_held[0]); vos_ioc_destroy(ioc, err != 0); vos_dth_set(NULL); return err; } int vos_update_begin(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, uint64_t flags, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, struct dcs_iod_csums *iods_csums, bool dedup, uint32_t dedup_th, daos_handle_t *ioh, struct dtx_handle *dth) { struct vos_io_context *ioc; int rc; D_DEBUG(DB_TRACE, "Prepare IOC for "DF_UOID", iod_nr %d, epc "DF_X64 ", flags="DF_X64"\n", DP_UOID(oid), iod_nr, dtx_is_valid_handle(dth) ? dth->dth_epoch : epoch, flags); rc = vos_ioc_create(coh, oid, false, epoch, iod_nr, iods, iods_csums, flags, NULL, dedup, dedup_th, dth, &ioc); if (rc != 0) return rc; /* flags may have VOS_OF_CRIT to skip sys/held checks here */ rc = vos_space_hold(vos_cont2pool(ioc->ic_cont), flags, dkey, iod_nr, iods, iods_csums, &ioc->ic_space_held[0]); if (rc != 0) { D_ERROR(DF_UOID": Hold space failed. "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); goto error; } rc = dkey_update_begin(ioc); if (rc != 0) { D_ERROR(DF_UOID"dkey update begin failed. %d\n", DP_UOID(oid), rc); goto error; } *ioh = vos_ioc2ioh(ioc); return 0; error: vos_update_end(vos_ioc2ioh(ioc), 0, dkey, rc, dth); return rc; } struct daos_recx_ep_list * vos_ioh2recx_list(daos_handle_t ioh) { return vos_ioh2ioc(ioh)->ic_recx_lists; } struct bio_desc * vos_ioh2desc(daos_handle_t ioh) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); D_ASSERT(ioc->ic_biod != NULL); return ioc->ic_biod; } struct dcs_csum_info * vos_ioh2ci(daos_handle_t ioh) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); return ioc->ic_biov_csums; } uint32_t vos_ioh2ci_nr(daos_handle_t ioh) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); return ioc->ic_biov_csums_at; } struct bio_sglist * vos_iod_sgl_at(daos_handle_t ioh, unsigned int idx) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); if (idx > ioc->ic_iod_nr) { D_ERROR("Invalid SGL index %d >= %d\n", idx, ioc->ic_iod_nr); return NULL; } return bio_iod_sgl(ioc->ic_biod, idx); } /* * XXX Dup these two helper functions for this moment, implement * non-transactional umem_alloc/free() later. */ static inline umem_off_t umem_id2off(const struct umem_instance *umm, PMEMoid oid) { if (OID_IS_NULL(oid)) return UMOFF_NULL; return oid.off; } static inline PMEMoid umem_off2id(const struct umem_instance *umm, umem_off_t umoff) { PMEMoid oid; if (UMOFF_IS_NULL(umoff)) return OID_NULL; oid.pool_uuid_lo = umm->umm_pool_uuid_lo; oid.off = umem_off2offset(umoff); return oid; } /* Duplicate bio_sglist for landing RDMA transfer data */ int vos_dedup_dup_bsgl(daos_handle_t ioh, struct bio_sglist *bsgl, struct bio_sglist *bsgl_dup) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); int i, rc; D_ASSERT(!daos_handle_is_inval(ioh)); D_ASSERT(bsgl != NULL); D_ASSERT(bsgl_dup != NULL); rc = bio_sgl_init(bsgl_dup, bsgl->bs_nr_out); if (rc != 0) return -DER_NOMEM; bsgl_dup->bs_nr_out = bsgl->bs_nr_out; for (i = 0; i < bsgl->bs_nr_out; i++) { struct bio_iov *biov = &bsgl->bs_iovs[i]; struct bio_iov *biov_dup = &bsgl_dup->bs_iovs[i]; PMEMoid oid; if (bio_iov2buf(biov) == NULL) continue; *biov_dup = *biov; /* Original biov isn't deduped, don't duplicate buffer */ if (!biov->bi_addr.ba_dedup) continue; D_ASSERT(bio_iov2len(biov) != 0); /* Support SCM only for this moment */ rc = pmemobj_alloc(vos_ioc2umm(ioc)->umm_pool, &oid, bio_iov2len(biov), UMEM_TYPE_ANY, NULL, NULL); if (rc) { D_ERROR("Failed to alloc "DF_U64" bytes SCM\n", bio_iov2len(biov)); return -DER_NOMEM; } biov_dup->bi_addr.ba_off = umem_id2off(vos_ioc2umm(ioc), oid); biov_dup->bi_buf = umem_off2ptr(vos_ioc2umm(ioc), bio_iov2off(biov_dup)); } return 0; } void vos_dedup_free_bsgl(daos_handle_t ioh, struct bio_sglist *bsgl) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); int i; D_ASSERT(!daos_handle_is_inval(ioh)); for (i = 0; i < bsgl->bs_nr_out; i++) { struct bio_iov *biov = &bsgl->bs_iovs[i]; PMEMoid oid; if (UMOFF_IS_NULL(bio_iov2off(biov))) continue; /* Not duplicated buffer, don't free it */ if (!biov->bi_addr.ba_dedup) continue; oid = umem_off2id(vos_ioc2umm(ioc), bio_iov2off(biov)); pmemobj_free(&oid); } } /** * @defgroup vos_obj_update() & vos_obj_fetch() functions * @{ */ /** * vos_obj_update() & vos_obj_fetch() are two helper functions used * for inline update and fetch, so far it's used by rdb, rebuild and * some test programs (daos_perf, vos tests, etc). * * Caveat: These two functions may yield, please use with caution. */ static int vos_obj_copy(struct vos_io_context *ioc, d_sg_list_t *sgls, unsigned int sgl_nr) { int rc, err; D_ASSERT(sgl_nr == ioc->ic_iod_nr); rc = bio_iod_prep(ioc->ic_biod); if (rc) return rc; err = bio_iod_copy(ioc->ic_biod, sgls, sgl_nr); rc = bio_iod_post(ioc->ic_biod); return err ? err : rc; } int vos_obj_update_ex(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, uint32_t pm_ver, uint64_t flags, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, struct dcs_iod_csums *iods_csums, d_sg_list_t *sgls, struct dtx_handle *dth) { daos_handle_t ioh; int rc; rc = vos_update_begin(coh, oid, epoch, flags, dkey, iod_nr, iods, iods_csums, false, 0, &ioh, dth); if (rc) { D_ERROR("Update "DF_UOID" failed "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); return rc; } if (sgls) { rc = vos_obj_copy(vos_ioh2ioc(ioh), sgls, iod_nr); if (rc) D_ERROR("Copy "DF_UOID" failed "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); } rc = vos_update_end(ioh, pm_ver, dkey, rc, dth); return rc; } int vos_obj_update(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, uint32_t pm_ver, uint64_t flags, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, struct dcs_iod_csums *iods_csums, d_sg_list_t *sgls) { return vos_obj_update_ex(coh, oid, epoch, pm_ver, flags, dkey, iod_nr, iods, iods_csums, sgls, NULL); } int vos_obj_array_remove(daos_handle_t coh, daos_unit_oid_t oid, const daos_epoch_range_t *epr, const daos_key_t *dkey, const daos_key_t *akey, const daos_recx_t *recx) { struct vos_io_context *ioc; daos_iod_t iod; daos_handle_t ioh; int rc; iod.iod_type = DAOS_IOD_ARRAY; iod.iod_recxs = (daos_recx_t *)recx; iod.iod_nr = 1; iod.iod_name = *akey; iod.iod_size = 0; rc = vos_update_begin(coh, oid, epr->epr_hi, VOS_OF_REMOVE, (daos_key_t *)dkey, 1, &iod, NULL, false, 0, &ioh, NULL); if (rc) { D_ERROR("Update "DF_UOID" failed "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); return rc; } ioc = vos_ioh2ioc(ioh); /** Set lower bound of epoch range */ ioc->ic_epr.epr_lo = epr->epr_lo; rc = vos_update_end(ioh, 0 /* don't care */, (daos_key_t *)dkey, rc, NULL); return rc; } int vos_obj_fetch_ex(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, uint64_t flags, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, d_sg_list_t *sgls, struct dtx_handle *dth) { daos_handle_t ioh; bool size_fetch = (sgls == NULL); uint32_t fetch_flags = size_fetch ? VOS_OF_FETCH_SIZE_ONLY : 0; uint32_t vos_flags = flags | fetch_flags; int rc; rc = vos_fetch_begin(coh, oid, epoch, dkey, iod_nr, iods, vos_flags, NULL, &ioh, dth); if (rc) { VOS_TX_TRACE_FAIL(rc, "Cannot fetch "DF_UOID": "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); return rc; } if (!size_fetch) { struct vos_io_context *ioc = vos_ioh2ioc(ioh); int i, j; for (i = 0; i < iod_nr; i++) { struct bio_sglist *bsgl = bio_iod_sgl(ioc->ic_biod, i); d_sg_list_t *sgl = &sgls[i]; /* Inform caller the nonexistent of object/key */ if (bsgl->bs_nr_out == 0) { for (j = 0; j < sgl->sg_nr; j++) sgl->sg_iovs[j].iov_len = 0; } } rc = vos_obj_copy(ioc, sgls, iod_nr); if (rc) D_ERROR("Copy "DF_UOID" failed "DF_RC"\n", DP_UOID(oid), DP_RC(rc)); } rc = vos_fetch_end(ioh, rc); return rc; } int vos_obj_fetch(daos_handle_t coh, daos_unit_oid_t oid, daos_epoch_t epoch, uint64_t flags, daos_key_t *dkey, unsigned int iod_nr, daos_iod_t *iods, d_sg_list_t *sgls) { return vos_obj_fetch_ex(coh, oid, epoch, flags, dkey, iod_nr, iods, sgls, NULL); } /** * @} vos_obj_update() & vos_obj_fetch() functions */
441005.c
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "src/core/ext/client_channel/uri_parser.h" #include <string.h> #include <grpc/support/log.h> #include "test/core/util/test_config.h" static void test_succeeds(const char *uri_text, const char *scheme, const char *authority, const char *path, const char *query, const char *fragment) { grpc_uri *uri = grpc_uri_parse(uri_text, 0); GPR_ASSERT(uri); GPR_ASSERT(0 == strcmp(scheme, uri->scheme)); GPR_ASSERT(0 == strcmp(authority, uri->authority)); GPR_ASSERT(0 == strcmp(path, uri->path)); GPR_ASSERT(0 == strcmp(query, uri->query)); GPR_ASSERT(0 == strcmp(fragment, uri->fragment)); grpc_uri_destroy(uri); } static void test_fails(const char *uri_text) { GPR_ASSERT(NULL == grpc_uri_parse(uri_text, 0)); } static void test_query_parts() { { const char *uri_text = "http://foo/path?a&b=B&c=&#frag"; grpc_uri *uri = grpc_uri_parse(uri_text, 0); GPR_ASSERT(uri); GPR_ASSERT(0 == strcmp("http", uri->scheme)); GPR_ASSERT(0 == strcmp("foo", uri->authority)); GPR_ASSERT(0 == strcmp("/path", uri->path)); GPR_ASSERT(0 == strcmp("a&b=B&c=&", uri->query)); GPR_ASSERT(4 == uri->num_query_parts); GPR_ASSERT(0 == strcmp("a", uri->query_parts[0])); GPR_ASSERT(NULL == uri->query_parts_values[0]); GPR_ASSERT(0 == strcmp("b", uri->query_parts[1])); GPR_ASSERT(0 == strcmp("B", uri->query_parts_values[1])); GPR_ASSERT(0 == strcmp("c", uri->query_parts[2])); GPR_ASSERT(0 == strcmp("", uri->query_parts_values[2])); GPR_ASSERT(0 == strcmp("", uri->query_parts[3])); GPR_ASSERT(NULL == uri->query_parts_values[3]); GPR_ASSERT(NULL == grpc_uri_get_query_arg(uri, "a")); GPR_ASSERT(0 == strcmp("B", grpc_uri_get_query_arg(uri, "b"))); GPR_ASSERT(0 == strcmp("", grpc_uri_get_query_arg(uri, "c"))); GPR_ASSERT(NULL == grpc_uri_get_query_arg(uri, "")); GPR_ASSERT(0 == strcmp("frag", uri->fragment)); grpc_uri_destroy(uri); } { /* test the current behavior of multiple query part values */ const char *uri_text = "http://auth/path?foo=bar=baz&foobar=="; grpc_uri *uri = grpc_uri_parse(uri_text, 0); GPR_ASSERT(uri); GPR_ASSERT(0 == strcmp("http", uri->scheme)); GPR_ASSERT(0 == strcmp("auth", uri->authority)); GPR_ASSERT(0 == strcmp("/path", uri->path)); GPR_ASSERT(0 == strcmp("foo=bar=baz&foobar==", uri->query)); GPR_ASSERT(2 == uri->num_query_parts); GPR_ASSERT(0 == strcmp("bar", grpc_uri_get_query_arg(uri, "foo"))); GPR_ASSERT(0 == strcmp("", grpc_uri_get_query_arg(uri, "foobar"))); grpc_uri_destroy(uri); } { /* empty query */ const char *uri_text = "http://foo/path"; grpc_uri *uri = grpc_uri_parse(uri_text, 0); GPR_ASSERT(uri); GPR_ASSERT(0 == strcmp("http", uri->scheme)); GPR_ASSERT(0 == strcmp("foo", uri->authority)); GPR_ASSERT(0 == strcmp("/path", uri->path)); GPR_ASSERT(0 == strcmp("", uri->query)); GPR_ASSERT(0 == uri->num_query_parts); GPR_ASSERT(NULL == uri->query_parts); GPR_ASSERT(NULL == uri->query_parts_values); GPR_ASSERT(0 == strcmp("", uri->fragment)); grpc_uri_destroy(uri); } } int main(int argc, char **argv) { grpc_test_init(argc, argv); test_succeeds("http://www.google.com", "http", "www.google.com", "", "", ""); test_succeeds("dns:///foo", "dns", "", "/foo", "", ""); test_succeeds("http://www.google.com:90", "http", "www.google.com:90", "", "", ""); test_succeeds("a192.4-df:foo.coom", "a192.4-df", "", "foo.coom", "", ""); test_succeeds("a+b:foo.coom", "a+b", "", "foo.coom", "", ""); test_succeeds("zookeeper://127.0.0.1:2181/foo/bar", "zookeeper", "127.0.0.1:2181", "/foo/bar", "", ""); test_succeeds("http://www.google.com?yay-i'm-using-queries", "http", "www.google.com", "", "yay-i'm-using-queries", ""); test_succeeds("dns:foo.com#fragment-all-the-things", "dns", "", "foo.com", "", "fragment-all-the-things"); test_succeeds("http:?legit", "http", "", "", "legit", ""); test_succeeds("unix:#this-is-ok-too", "unix", "", "", "", "this-is-ok-too"); test_succeeds("http:?legit#twice", "http", "", "", "legit", "twice"); test_succeeds("http://foo?bar#lol?", "http", "foo", "", "bar", "lol?"); test_succeeds("http://foo?bar#lol?/", "http", "foo", "", "bar", "lol?/"); test_fails("xyz"); test_fails("http:?dangling-pct-%0"); test_fails("http://foo?[bar]"); test_fails("http://foo?x[bar]"); test_fails("http://foo?bar#lol#"); test_query_parts(); return 0; }
369048.c
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/edger8r/enclave.h> #include <openenclave/enclave.h> #include <openssl/engine.h> #include <sys/mount.h> #include "openssl_t.h" #include "tu_local.h" /* Header from openssl/test/testutil */ extern char** __environ; extern int main(int argc, char* argv[]); int enc_test(int argc, char** argv, char** env) { int ret = 1; ENGINE* eng = NULL; const BIO_METHOD* tap = NULL; /* Directly use environ from host. */ __environ = env; /* Initialize socket and host fs. */ if (oe_load_module_host_socket_interface() != OE_OK) goto done; if (oe_load_module_host_resolver() != OE_OK) goto done; #ifndef CODE_COVERAGE /* * When enabling code coverage analysis, libgcov should initialize the host * fs already so we do not do it again here. Otherwise, the * oe_load_module_host_file_system will fail. */ if (oe_load_module_host_file_system() != OE_OK) goto done; if (mount("/", "/", OE_HOST_FILE_SYSTEM, 0, NULL)) goto done; #endif /* * Initialize and opt-in the rdrand engine. This is necessary to use opensl * RNG functionality inside the enclave. */ ENGINE_load_rdrand(); eng = ENGINE_by_id("rdrand"); if (eng == NULL) { goto done; } if (ENGINE_init(eng) == 0) { goto done; } if (ENGINE_set_default(eng, ENGINE_METHOD_RAND) == 0) { goto done; } /* * Hold the reference to the tap method that is used by the OpenSSL test * framework such that we can free it (which the framework does not do * that). Without doing this, DEBUG_MALLOC will report memory leaks. */ tap = BIO_f_tap(); /* Perform the test. */ ret = main(argc, argv); done: #ifndef CODE_COVERAGE // Avoid conflicts with libgcov. umount("/"); #endif if (__environ) __environ = NULL; if (eng) { ENGINE_finish(eng); ENGINE_free(eng); ENGINE_cleanup(); } if (tap) BIO_meth_free((BIO_METHOD*)tap); return ret; } OE_SET_ENCLAVE_SGX( 1, /* ProductID */ 1, /* SecurityVersion */ true, /* AllowDebug */ 6144, /* HeapPageCount */ 128, /* StackPageCount */ 1); /* TCSCount */
466743.c
/* $RCSfile: csuEBGMSimilarity.c,v $ $Author: teixeira $ $Date: 2003/04/23 14:02:31 $ */ /* Copyright (c) 2003 Colorado State University 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 <csuEBGMSimilarity.h> #include <csuEBGMUtil.h> /********************** Compute the similarity between jets *****************/ /* Compute a phase invariant corrilation like similarity */ double JetSimilarityMag(GaborJet j1, GaborJet j2){ double j12 = 0; double j11 = 0; double j22 = 0; int i; assert(j1 && j2 && j1->length && j1->length==j2->length); for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]; j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } return j12/sqrt(j11*j22); } /* Compute a similarity score as above only with a term added for the cos(Phase) */ double JetSimilarityPhase(GaborJet j1, GaborJet j2){ double j12 = 0; double j11 = 0; double j22 = 0; int i; assert(j1 && j2 && j1->length && j1->length==j2->length); for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]*cos(j1->ang[i] - j2->ang[i]); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } return j12/sqrt(j11*j22); } double JetSimilarityDEGridSample(GaborJet j1, GaborJet j2){ double dx = 0, dy = 0; return DEGridSample(j1, j2, &dx, &dy); } double JetSimilarityDEPredictiveStep(GaborJet j1, GaborJet j2){ double dx = 0.0, dy = 0.0; return DEPredictiveStep(j1, j2, &dx, &dy); } double JetSimilarityDEPredictiveIter(GaborJet j1, GaborJet j2){ double dx = 0.0, dy = 0.0; return DEPredictiveIter(j1, j2, &dx, &dy); } double SIM_DISPLACE(GaborJet j1, GaborJet j2, double dx, double dy) { double j12 = 0.0; double j11 = 0.0; double j22 = 0.0; int i; for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]* cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } return j12/sqrt(j11*j22); } /* Compute a similarity score as above only with phase using an exaustive estimated displacement to correct for phase - similar to Auto Correlation (i.e. search a displacemet grid for peaks) */ double JetSimilarityDEFixedLocalSearch(GaborJet j1, GaborJet j2){ double dx = 0.0, dy = 0.0; return DEFixedLocalSearch(j1, j2, &dx, &dy); } /* Compute a similarity score as above only with phase using a fast estimated displacement to correct for phase - similar to Wiscott*/ double JetSimilarityDENarrowingLocalSearch(GaborJet j1, GaborJet j2){ double dx = 0, dy = 0; return DENarrowingLocalSearch(j1, j2, &dx, &dy); } /* Compute a similarity score based on the City Block distance measure */ double JetSimilarityCityBlock(GaborJet j1, GaborJet j2){ double sim = 0; int i; assert(j1 && j2 && j1->length && j1->length==j2->length); for(i = 0; i < j1->length; i++){ /* compute the negitive so that greater values are more simillar */ sim -= ABS(j1->realPart[i]-j2->realPart[i]); sim -= ABS(j1->imagPart[i]-j2->imagPart[i]); } return sim; } /* Compute a similarity score based on the Correlation distance measure */ double JetSimilarityCorrelation(GaborJet j1, GaborJet j2){ int i; double corrilation = 0.0; double j1mean = 0.0, j2mean = 0.0; double j1scale = 0.0, j2scale = 0.0; assert(j1 && j2 && j1->length && j1->length == j2->length); /* Pass one: compute the pixel mean. */ for(i = 0; i < j1->length; i++){ j1mean += j1->realPart[i]; j1mean += j1->imagPart[i]; j2mean += j2->realPart[i]; j2mean += j2->imagPart[i]; } j1mean = j1mean/(2*j1->length); j2mean = j2mean/(2*j1->length); /* Pass two: compute the unscaled corrilation value and the associated scale parameter. */ for(i = 0; i < j1->length; i++){ corrilation += (j1->realPart[i]-j1mean)*(j2->realPart[i]-j2mean); corrilation += (j1->imagPart[i]-j1mean)*(j2->imagPart[i]-j2mean); j1scale += SQR(j1->realPart[i]-j1mean); j1scale += SQR(j1->imagPart[i]-j1mean); j2scale += SQR(j2->realPart[i]-j2mean); j2scale += SQR(j2->imagPart[i]-j2mean); } corrilation = corrilation / (sqrt(j1scale)*sqrt(j2scale)); return corrilation; } /* Compute a similarity score based on the Covariance distance measure */ double JetSimilarityCovariance(GaborJet j1, GaborJet j2){ int i; double magi = 0.0, magj = 0.0, dot = 0.0; assert(j1 && j2 && j1->length && j1->length==j2->length); for (i = 0; i < j1->length; i++) { magi += SQR(j1->realPart[i]) + SQR(j1->imagPart[i]); magj += SQR(j2->realPart[i]) + SQR(j2->imagPart[i]); dot += j1->realPart[i] * j2->realPart[i]; dot += j1->imagPart[i] * j2->imagPart[i]; } return (dot / (sqrt(magi) * sqrt(magj))); } double JetSimilarityDisplacementCheckMag(GaborJet j1, GaborJet j2){ double sim = 0.0; int i; for(i = 0; i < j1->length; i++){ sim += exp(-0.1*SQR(j1->mag[i]-j2->mag[i])); } return sim; } double JetSimilarityDisplacementCheckPhase(GaborJet j1, GaborJet j2){ double sim = 0.0; double dx = j1->x - j2->x; double dy = j1->y - j2->y; int i; for(i = 0; i < j1->length; i++){ sim += cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); } return sim; } double JetSimilarityResponseMag(GaborJet j1, GaborJet j2){ double sim = 0.0; int i; for(i = 0; i < j1->length; i++){ sim += j1->mag[i]; } return sim; } double JetSimilarityResponsePhase(GaborJet j1, GaborJet j2){ double sim = 0.0; int i; for(i = 0; i < j1->length; i++){ sim += j1->ang[i]; } return sim; } /***************************************************************************** Displacement estimators are used to find the displacement between two jets. These functions optimize a similarity function for a displacement vector. For more info see DSB. *****************************************************************************/ /* This displacement estimator uses the taylor expansion method. Wiskott 96 */ double estimateDisplacementRandom(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double j12 = 0; double j11 = 0; double j22 = 0; int i; double sim = 0.0; double dx = randBM(), dy = randBM(); assert(j1 && j1->length && j2 && j1->length==j2->length); /* Compute the similarity with the estimated displacement. */ j12 = 0.0; j11 = 0.0; j22 = 0.0; for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]*cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } sim = j12/sqrt(j11*j22); /* Return the proper values */ *tdx = dx; *tdy = dy; return sim; } double DEGridSample(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double j12 = 0; double j11 = 0; double j22 = 0; int i; int first = 1; double sim = 0.0; double dx, dy; assert(j1 && j1->length && j2 && j1->length==j2->length); for(dx = -16.0; dx < 16.0; dx += 0.5){ for(dy = -16.0; dy < 16.0; dy += 0.5){ j12 = 0.0; j11 = 0.0; j22 = 0.0; for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]*cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } if(first || sim < j12/sqrt(j11*j22)){ sim = j12/sqrt(j11*j22); *tdx = dx; *tdy = dy; first = 0; } } } return sim; } double DEPredictiveStep(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double j12 = 0; double j11 = 0; double j22 = 0; int i; double sim = 0.0; double dx = 0.0, dy = 0.0; double Gxx, Gxy, Gyx, Gyy; double Px, Py; assert(j1 && j1->length && j2 && j1->length==j2->length); Gxx = 0; Gxy = 0; Gyx = 0; Gyy = 0; Px = 0; Py = 0; for(i = 0; i < j1->length; i++){ double ang = j1->ang[i] - j2->ang[i]; /* Scale the angle such that it is closest to zero displacement. */ while(ang > PI){ ang -= 2*PI; } while(ang < -PI){ ang += 2*PI; } Gxx += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->kx[2*i]; Gxy += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->ky[2*i]; Gyx += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->ky[2*i]; Gyy += j1->mag[i]*j2->mag[i]*j1->params->ky[2*i]*j1->params->ky[2*i]; Px += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*(ang); Py += j1->mag[i]*j2->mag[i]*j1->params->ky[2*i]*(ang); } /* Catch any divide by zero errors */ if(Gxx*Gyy-Gxy*Gyx != 0.0){ dx = (Gyy*Px-Gyx*Py)/(Gxx*Gyy-Gxy*Gyx); dy = (-Gxy*Px+Gxx*Py)/(Gxx*Gyy-Gxy*Gyx); } else { /* Divide by zero occured - display warning */ DEBUG(-1, "Warning: Divide by zero -- Attempting to recover"); dx = 0.0; dy = 0.0; } /* Compute the similarity with the estimated displacement. */ j12 = 0.0; j11 = 0.0; j22 = 0.0; for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]*cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } sim = j12/sqrt(j11*j22); /* Return the proper values */ *tdx = dx; *tdy = dy; return sim; } double DEPredictiveIter(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double j12 = 0; double j11 = 0; double j22 = 0; int i,n; double sim = 0.0; double dx = 0.0, dy = 0.0; double ddx, ddy; double Gxx, Gxy, Gyx, Gyy; double Px, Py; assert(j1 && j1->length && j2 && j1->length==j2->length); for(n = 0; n < 10; n++){ Gxx = 0; Gxy = 0; Gyx = 0; Gyy = 0; Px = 0; Py = 0; for(i = 0; i < j1->length; i++){ double ang = j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i]); /* Scale the angle such that it is closest to zero displacement. */ while(ang > PI){ ang -= 2*PI; } while(ang < -PI){ ang += 2*PI; } Gxx += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->kx[2*i]; Gxy += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->ky[2*i]; Gyx += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*j1->params->ky[2*i]; Gyy += j1->mag[i]*j2->mag[i]*j1->params->ky[2*i]*j1->params->ky[2*i]; Px += j1->mag[i]*j2->mag[i]*j1->params->kx[2*i]*(ang); Py += j1->mag[i]*j2->mag[i]*j1->params->ky[2*i]*(ang); } /* Catch any divide by zero errors */ if(Gxx*Gyy-Gxy*Gyx != 0.0){ ddx = (Gyy*Px-Gyx*Py)/(Gxx*Gyy-Gxy*Gyx); ddy = (-Gxy*Px+Gxx*Py)/(Gxx*Gyy-Gxy*Gyx); dx += ddx; dy += ddy; if( (ddx*ddx+ddy+ddy < .001) ) break; } else { /* Divide by zero occured - display warning */ DEBUG(-1, "Warning: Divide by zero -- Attempting to recover"); dx += 0.0; dy += 0.0; } } /* Compute the similarity with the estimated displacement. */ j12 = 0.0; j11 = 0.0; j22 = 0.0; for(i = 0; i < j1->length; i++){ j12 += j1->mag[i]*j2->mag[i]*cos(j1->ang[i] - j2->ang[i] - (dx * j1->params->kx[2*i] + dy * j1->params->ky[2*i])); j11 += j1->mag[i]*j1->mag[i]; j22 += j2->mag[i]*j2->mag[i]; } sim = j12/sqrt(j11*j22); /* Return the proper values */ *tdx = dx; *tdy = dy; return sim; } /* This displacement estimator performs a nearest neighbor search for the maximum similarity. */ double DEFixedLocalSearch(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double sim = 0.0; double dx = 0.0, dy = 0.0; int change = 1, iter = 50; double nextx, nexty; double bestsim = 0.0; assert(j1 && j1->length && j2 && j1->length==j2->length); sim = SIM_DISPLACE(j1, j2, dx,dy); bestsim = sim; nextx = dx; nexty = dy; while(change && iter--){ dx = nextx; dy = nexty; change = 0; sim = SIM_DISPLACE(j1, j2, dx+0.5,dy+0.5); if( bestsim < sim ){ bestsim = sim; nextx = dx+0.5; nexty = dy+0.5; change = 1; } sim = SIM_DISPLACE(j1, j2, dx+0.5,dy-0.5); if( bestsim < sim ){ bestsim = sim; nextx = dx+0.5; nexty = dy-0.5; change = 1; } sim = SIM_DISPLACE(j1, j2, dx-0.5,dy-0.5); if( bestsim < sim ){ bestsim = sim; nextx = dx-0.5; nexty = dy-0.5; change = 1; } sim = SIM_DISPLACE(j1, j2, dx-0.5,dy+0.5); if( bestsim < sim ){ bestsim = sim; nextx = dx-0.5; nexty = dy+0.5; change = 1; } dx = nextx; dy = nexty; } *tdx = dx; *tdy = dy; return bestsim; } double DENarrowingLocalSearch(GaborJet j1, GaborJet j2, double *tdx, double *tdy){ double sim = 0.0; double dx = 0.0, dy = 0.0; int change = 1, iter = 50; double nextx, nexty; double bestsim = 0.0; double tol = .2; double step = 1.0; assert(j1 && j1->length && j2 && j1->length==j2->length); sim = SIM_DISPLACE(j1, j2, dx,dy); bestsim = sim; *tdx = 0.0; *tdy = 0.0; change = 1; sim = SIM_DISPLACE(j1, j2, dx,dy); bestsim = sim; nextx = dx; nexty = dy; while(change && iter--){ dx = nextx; dy = nexty; change = 0; sim = SIM_DISPLACE(j1, j2, dx+step,dy+step); if( bestsim < sim ){ bestsim = sim; nextx = dx+step; nexty = dy+step; change = 1; } sim = SIM_DISPLACE(j1, j2, dx+step,dy-step); if( bestsim < sim ){ bestsim = sim; nextx = dx+step; nexty = dy-step; change = 1; } sim = SIM_DISPLACE(j1, j2, dx-step,dy-step); if( bestsim < sim ){ bestsim = sim; nextx = dx-step; nexty = dy-step; change = 1; } sim = SIM_DISPLACE(j1, j2, dx-step,dy+step); if( bestsim < sim ){ bestsim = sim; nextx = dx-step; nexty = dy+step; change = 1; } dx = nextx; dy = nexty; if(change == 0 && step > tol){ change = 1; step = step * 0.5; } } *tdx = dx; *tdy = dy; /*printf("BestSim: %f\n",bestsim); */ return bestsim; } /* This function performs a simple L2 distance measurement on the geometry of the face graph */ double GeometrySimL2(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->geosize; i++){ totalSim += sqrt(SQR(f1->jets[i]->x - f2->jets[i]->x)+SQR(f1->jets[i]->y - f2->jets[i]->y)); } return totalSim; } /* This function performs a correlation based distance measurement on the geometry of the face graph */ double GeometrySimCorrelation(FaceGraph f1, FaceGraph f2){ int i; double sum1 = 0.0, sum2 = 0.0; double mean1 = 0.0, mean2 = 0.0; double len1 = 0.0, len2 = 0.0; double sqsum1 = 0.0, sqsum2 = 0.0; double corr = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); NOT_IMPLEMENTED; for (i = 0; i < g1->row_dim; i++) { ME(g1,i,0) = (i%2) ? f1->jets[i/2]->y : f1->jets[i/2]->x ; ME(g2,i,0) = (i%2) ? f2->jets[i/2]->y : f2->jets[i/2]->x ; } for (i = 0; i < g1->row_dim; i++) { sum1 += ME(g1,i,0); sum2 += ME(g2,i,0); } mean1 = sum1 / g1->row_dim; mean2 = sum2 / g2->row_dim; for (i = 0; i < g1->row_dim; i++) { ME(g1,i,0) -= mean1; ME(g2,i,0) -= mean2; sqsum1 += ME(g1,i,0)*ME(g1,i,0); sqsum2 += ME(g2,i,0)*ME(g2,i,0); } len1 = 1.0/sqrt(sqsum1); len2 = 1.0/sqrt(sqsum2); for (i = 0; i < g1->row_dim; i++) { ME(g1,i,0) = ME(g1,i,0)*len1; ME(g2,i,0) = ME(g2,i,0)*len2; corr += ME(g1,i,0)*ME(g2,i,0); } freeMatrix(g1); freeMatrix(g2); return (- corr); } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ void TransformLeastSquares(Matrix g1, Matrix g2){ int i; double dist = 0.0; Matrix A = makeMatrix(g1->row_dim,4); Matrix v; double b, a, dx, dy; dist = 0.0; for (i = 0; i < g1->row_dim/2; i++) { ME(A,2*i,0 ) = ME(g1,2*i,0); ME(A,2*i,1 ) = -ME(g1,2*i+1,0); ME(A,2*i,2 ) = 1; ME(A,2*i,3 ) = 0; ME(A,2*i+1,0) = ME(g1,2*i+1,0); ME(A,2*i+1,1) = ME(g1,2*i,0); ME(A,2*i+1,2) = 0; ME(A,2*i+1,3) = 1; } v = leastSquares(A, g2); a = ME(v,0,0); b = ME(v,1,0); dx = ME(v,2,0); dy = ME(v,3,0); dist = 0.0; for (i = 0; i < g1->row_dim/2; i++) { double x = ME(g1,2*i ,0); double y = ME(g1,2*i+1,0); ME(g1,2*i ,0) = a*x - b*y + dx; ME(g1,2*i+1,0) = b*x + a*y + dy; } freeMatrix(v); freeMatrix(A); } double L2Dist(Matrix g1, Matrix g2){ double dist = 0.0; int i; for (i = 0; i < g1->row_dim/2; i++) { dist += SQR(ME(g1,2*i,0) - ME(g2,2*i,0)); dist += SQR(ME(g1,2*i+1,0) - ME(g2,2*i+1,0)); } return sqrt(dist); } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ double GeometrySimLeastSquares(FaceGraph f1, FaceGraph f2){ int i; double dist = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); for (i = 0; i < g1->row_dim; i++) { ME(g1,i,0) = (i%2) ? f1->jets[i/2]->y : f1->jets[i/2]->x ; ME(g2,i,0) = (i%2) ? f2->jets[i/2]->y : f2->jets[i/2]->x ; } TransformLeastSquares(g1,g2); dist = L2Dist(g1, g2); freeMatrix(g1); freeMatrix(g2); return dist; } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ double GeometrySimLeastSquaresPS(FaceGraph f1, FaceGraph f2){ int i; double dist = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); for (i = 0; i < f1->geosize; i++) { double dedx=0, dedy=0; DEPredictiveStep(f1->jets[i],f2->jets[i],&dedx,&dedy); ME(g1,2*i,0) = f1->jets[i]->x ; ME(g1,2*i+1,0) = f1->jets[i]->y ; ME(g2,2*i,0) = f2->jets[i]->x + dedx; ME(g2,2*i+1,0) = f2->jets[i]->y + dedy; } TransformLeastSquares(g1,g2); dist = L2Dist(g1, g2); freeMatrix(g1); freeMatrix(g2); return dist; } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ double GeometrySimLeastSquaresPI(FaceGraph f1, FaceGraph f2){ int i; double dist = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); for (i = 0; i < f1->geosize; i++) { double dedx=0, dedy=0; DEPredictiveIter(f1->jets[i],f2->jets[i],&dedx,&dedy); ME(g1,2*i,0) = f1->jets[i]->x ; ME(g1,2*i+1,0) = f1->jets[i]->y ; ME(g2,2*i,0) = f2->jets[i]->x + dedx; ME(g2,2*i+1,0) = f2->jets[i]->y + dedy; } TransformLeastSquares(g1,g2); dist = L2Dist(g1, g2); freeMatrix(g1); freeMatrix(g2); return dist; } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ double GeometrySimLeastSquaresFLS(FaceGraph f1, FaceGraph f2){ int i; double dist = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); for (i = 0; i < f1->geosize; i++) { double dedx=0, dedy=0; DEFixedLocalSearch(f1->jets[i],f2->jets[i],&dedx,&dedy); ME(g1,2*i,0) = f1->jets[i]->x ; ME(g1,2*i+1,0) = f1->jets[i]->y ; ME(g2,2*i,0) = f2->jets[i]->x + dedx; ME(g2,2*i+1,0) = f2->jets[i]->y + dedy; } TransformLeastSquares(g1,g2); dist = L2Dist(g1, g2); freeMatrix(g1); freeMatrix(g2); return dist; } /* This method performs an L2 based distance measure after solving for a best fit transformation. The best fit transformation is a combination of a 2D scale, rotation and translation. The algorithm solves for this transformation using a least squares solution to a set of transformation aproximations. */ double GeometrySimLeastSquaresNLS(FaceGraph f1, FaceGraph f2){ int i; double dist = 0.0; Matrix g1 = makeMatrix(f1->geosize*2,1); Matrix g2 = makeMatrix(f1->geosize*2,1); for (i = 0; i < f1->geosize; i++) { double dedx=0, dedy=0; DENarrowingLocalSearch(f1->jets[i],f2->jets[i],&dedx,&dedy); ME(g1,2*i,0) = f1->jets[i]->x ; ME(g1,2*i+1,0) = f1->jets[i]->y ; ME(g2,2*i,0) = f2->jets[i]->x + dedx; ME(g2,2*i+1,0) = f2->jets[i]->y + dedy; } TransformLeastSquares(g1,g2); dist = L2Dist(g1, g2); freeMatrix(g1); freeMatrix(g2); return dist; } /***************************************************************************** Face graph similarity measures determine the similarity between face graphs. The similarity measures are based on the geometry of the graph and the values of the Gabor Jets. *****************************************************************************/ /* Magnitude only similarity measure */ double fgSimMagnitude(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityMag( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase based similarity measure */ double fgSimPhase01(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityPhase( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase with displacement estimation */ double fgSimPhase02(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEPredictiveStep( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase with displacement estimation */ double fgSimPhase03(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEGridSample( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase with displacement estimation */ double fgSimPhase04(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEFixedLocalSearch( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase with displacement estimation */ double fgSimPhase05(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDENarrowingLocalSearch( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } /* Phase with displacement estimation */ double fgSimPhase06(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEPredictiveIter( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhase(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityPhase( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhaseGridSample(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEGridSample( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhasePredictiveStep(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEPredictiveStep( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhasePredictiveIter(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEPredictiveIter( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhaseFixedLocalSearch(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDEFixedLocalSearch( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; } double fgSimPhaseNarrowingLocalSearch(FaceGraph f1, FaceGraph f2){ double totalSim = 0.0; int i; for(i = 0; i < f1->totalsize; i++){ totalSim += JetSimilarityDENarrowingLocalSearch( f1->jets[i], f2->jets[i] ); } totalSim = totalSim / f1->totalsize; return -totalSim; }
388686.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2017, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curlcheck.h" #include "urldata.h" #include "progress.h" static int usec_magnitude = 1000000; static bool unit_setup(void) { return CURLE_OK; } static void unit_stop(void) { } /* * Invoke Curl_pgrsTime for TIMER_STARTSINGLE to trigger the behavior that * manages is_t_startransfer_set, but fake the t_startsingle time for purposes * of the test. */ static void fake_t_startsingle_time(struct Curl_easy *data, struct curltime fake_now, int seconds_offset) { Curl_pgrsTime(data, TIMER_STARTSINGLE); data->progress.t_startsingle.tv_sec = fake_now.tv_sec + seconds_offset; data->progress.t_startsingle.tv_usec = fake_now.tv_usec; } static bool usec_matches_seconds(time_t time_usec, int expected_seconds) { int time_sec = (int)(time_usec / usec_magnitude); bool same = (time_sec == expected_seconds); fprintf(stderr, "is %d us same as %d seconds? %s\n", (int)time_usec, expected_seconds, same?"Yes":"No"); return same; } static void expect_timer_seconds(struct Curl_easy *data, int seconds) { char msg[64]; snprintf(msg, sizeof(msg), "about %d seconds should have passed", seconds); fail_unless(usec_matches_seconds(data->progress.t_nslookup, seconds), msg); fail_unless(usec_matches_seconds(data->progress.t_connect, seconds), msg); fail_unless(usec_matches_seconds(data->progress.t_appconnect, seconds), msg); fail_unless(usec_matches_seconds(data->progress.t_pretransfer, seconds), msg); fail_unless(usec_matches_seconds(data->progress.t_starttransfer, seconds), msg); } /* Scenario: simulate a redirect. When a redirect occurs, t_nslookup, * t_connect, t_appconnect, t_pretransfer, and t_starttransfer are addative. * E.g., if t_starttransfer took 2 seconds initially and took another 1 * second for the redirect request, then the resulting t_starttransfer should * be 3 seconds. */ UNITTEST_START struct Curl_easy data; struct curltime now = Curl_now(); data.progress.t_nslookup = 0; data.progress.t_connect = 0; data.progress.t_appconnect = 0; data.progress.t_pretransfer = 0; data.progress.t_starttransfer = 0; data.progress.t_redirect = 0; data.progress.start.tv_sec = now.tv_sec - 2; data.progress.start.tv_usec = now.tv_usec; fake_t_startsingle_time(&data, now, -2); Curl_pgrsTime(&data, TIMER_NAMELOOKUP); Curl_pgrsTime(&data, TIMER_CONNECT); Curl_pgrsTime(&data, TIMER_APPCONNECT); Curl_pgrsTime(&data, TIMER_PRETRANSFER); Curl_pgrsTime(&data, TIMER_STARTTRANSFER); expect_timer_seconds(&data, 2); /* now simulate the redirect */ data.progress.t_redirect = data.progress.t_starttransfer + 1; fake_t_startsingle_time(&data, now, -1); Curl_pgrsTime(&data, TIMER_NAMELOOKUP); Curl_pgrsTime(&data, TIMER_CONNECT); Curl_pgrsTime(&data, TIMER_APPCONNECT); Curl_pgrsTime(&data, TIMER_PRETRANSFER); /* ensure t_starttransfer is only set on the first invocation by attempting * to set it twice */ Curl_pgrsTime(&data, TIMER_STARTTRANSFER); Curl_pgrsTime(&data, TIMER_STARTTRANSFER); expect_timer_seconds(&data, 3); UNITTEST_STOP
626511.c
#include <std.h> #include <spell.h> inherit SPELL; void create() { ::create(); set_spell_name("resurrection"); set_spell_level(([ "cleric" : 9,"druid":9 ])); set_spell_sphere("healing"); set_domains("renewal"); set_syntax("cast CLASS resurrection on TARGET"); set_description("Praying to their diety for a miracle, a priest can attempt to resurrect a slainally back to life. The resurrection, if successful, will restore the corpseback to life and full of health. The spell is somewhat draining on the priest,for channeling large ammounts of divine power can be exhausting. The targetwill suffer significantly less from the death due to theintervention of the priest. Unlike lower spells this spell will work on targets whose corpse is not present. This spell will not work on a victim of player kill, use raise dead or other spells. The TARGET must be the recognized name of the dead player or their corpse. You don't need to know the name to use this spell on a corpse."); set_verbal_comp(); set_somatic_comp(); set_arg_needed(); set_non_living_ok(1); set_helpful_spell(1); } string what_alignment(int align) { string alignment; switch(align) { case 1: alignment = "Lawful Good"; break; case 2: alignment = "Lawful Neutral"; break; case 3: alignment = "Lawful Evil"; break; case 4: alignment = "Neutral Good"; break; case 5: alignment = "True Neutral"; break; case 6: alignment = "Neutral Evil"; break; case 7: alignment = "Chaotic Good"; break; case 8: alignment = "Chaotic Neutral"; break; case 9: alignment = "Chaotic Evil"; break; } return alignment; } spell_effect(int prof) { string what, theirname; object corpse, targ; ::spell_effect(); if(objectp(corpse=present(arg,place))) theirname = corpse->query_original_name(); else theirname = caster->realName(lower_case(arg)); targ = find_player(theirname); what = "corpse of $&$"+theirname+"$&$"; if (!targ) { tell_object(caster,"You can only revive interactive players."); dest_effect(); return; } if (!interactive(targ)) { tell_object(caster,"You can only revive interactive players."); dest_effect(); return; } if (interactive(caster) ) { set_cast_string("%^CYAN%^"+caster->QCN+" draws upon the"+ " power of "+caster->QP+" god for a miracle.\n"); tell_object(caster, "%^CYAN%^You attempt to resurrect"+ " "+capitalize(arg)+" from the dead."); tell_room(environment(CASTER), "%^CYAN%^"+caster->QCN+" draws upon"+ " the power of "+caster->QP+" deity to resurrect "+ ""+capitalize(arg)+".", ({ CASTER, TARGET})); } else { set_cast_string("%^CYAN%^"+caster->QCN+" prays to "+caster->QP+" "+ "deity to resurrect "+capitalize(arg)+".\n"); } if (targ->query("just_been_pkilled")) { tell_object(caster,capitalize(arg)+" is dead forever and can't be revived."); dest_effect(); return; } if (!targ->query_ghost()) { tell_object(caster,capitalize(arg)+" does not need to be revived."); dest_effect(); return; } tell_object(caster,"You can feel the power of "+capitalize((string)caster->query_diety())+" flow out " "to "+targ->QCN+"'s soul, and know that "+targ->QS+" life is in "+targ->QP+" own hands now."); tell_room(environment(caster),"The power of "+caster->QCN+"'s spell flows through the area as "+caster->QS+" " "tries to bring "+targ->QCN+" back to life!",caster); targ->set("RaisingPriestGod",caster->query_diety()); targ->set("RaisingPriestAlignment",caster->query_alignment()); targ->set("RaisingRoom",base_name(environment(caster))); targ->set("RaisingExpLoss",(-5)); targ->set("RaisingType","resurrection"); tell_object(targ,"%^RESET%^%^BOLD%^%^WHITE%^You can feel a pull on your soul. You sense " "that a "+capitalize(what_alignment((int)caster->query_alignment()))+" faithful " "of "+capitalize((string)caster->query_diety())+" is trying to return you to " "life!\nType %^ORANGE%^<accept>%^WHITE%^ to return to life, or %^ORANGE%^<cancel>%^WHITE%^ to leave your " "fate to a chance.%^RESET%^"); //targ->revive(-5); //targ->set_heart_beat(1); //targ->cease_all_attacks(); //targ->move_player(environment(caster)); //targ->set_hp(targ->query_max_hp()); caster->use_stamina(25); dest_effect(); } void dest_effect(){ ::dest_effect(); if(objectp(TO)) TO->remove(); }
601257.c
/* * STevie - ST editor for VI enthusiasts. ...Tim Thompson...twitch!tjt... */ #include "ctype.h" #include "stevie.h" /* * normal * * Execute a command in normal mode. */ normal(c) int c; { char *p, *q; int nchar, n; switch(c){ case '\014': screenclear(); updatescreen(); break; case 04: /* control-d */ if ( ! onedown(10) ) beep(); break; case 025: /* control-u */ if ( ! oneup(10) ) beep(); break; case 06: /* control-f */ if ( ! onedown(Rows) ) beep(); break; case 02: /* control-b */ if ( ! oneup(Rows) ) beep(); break; case '\007': fileinfo(); break; case 'G': gotoline(Prenum); break; case 'l': if ( ! oneright() ) beep(); break; case 'h': if ( ! oneleft() ) beep(); break; case 'k': if ( ! oneup(1) ) beep(); break; case 'j': if ( ! onedown(1) ) beep(); break; case 'b': /* If we're on the first character of a word, force */ /* an initial backup. */ if ( ! issepchar(*Curschar) && Curschar>Filemem && issepchar(*(Curschar-1)) ) Curschar--; if ( ! issepchar(*Curschar) ) { /* If we start in the middle of a word, back */ /* up until we hit a separator. */ while ( Curschar>Filemem && !issepchar(*Curschar)) Curschar--; if ( issepchar(*Curschar) ) Curschar++; } else { /* back up past all separators. */ while ( Curschar>Filemem && issepchar(*Curschar)) Curschar--; /* back up past all non-separators. */ while (Curschar>Filemem && !issepchar(*Curschar)){ Curschar--; } if ( issepchar(*Curschar) ) Curschar++; } break; case 'w': if ( issepchar(*Curschar) ) { /* If we're on a separator, we advance to */ /* the next non-separator char. */ while ( (p=Curschar+1) < Fileend ) { Curschar = p; if ( ! issepchar(*Curschar) ) break; } } else { /* If we're in the middle of a word, we */ /* advance to the next word-separator. */ while ( (p=Curschar+1) < Fileend ) { Curschar = p; if ( issepchar(*Curschar) ) break; } /* Now go past any trailing white space */ while (isspace(*Curschar) && (Curschar+1)<Fileend) Curschar++; } break; case '$': while ( oneright() ) ; break; case '0': case '^': beginline(); break; case 'x': /* Can't do it if we're on a blank line. (Actually it */ /* does work, but we want to match the real 'vi'...) */ if ( *Curschar == '\n' ) beep(); else { addtobuff(Redobuff,'x',NULL); /* To undo it, we insert the same character back. */ resetundo(); addtobuff(Undobuff,'i',*Curschar,'\033',NULL); Uncurschar = Curschar; delchar(); updatescreen(); } break; case 'a': /* Works just like an 'i'nsert on the next character. */ if ( Curschar < (Fileend-1) ) Curschar++; resetundo(); startinsert("a"); break; case 'i': resetundo(); startinsert("i"); break; case 'o': opencmd(); updatescreen(); resetundo(); startinsert("o"); break; case 'd': nchar = vgetc(); n = (Prenum==0?1:Prenum); switch(nchar){ case 'd': sprintf(Redobuff,"%ddd",n); /* addtobuff(Redobuff,'d','d',NULL); */ beginline(); resetundo(); Uncurschar = Curschar; yankline(n); delline(n); beginline(); updatescreen(); /* If we have backed xyzzy, then we deleted the */ /* last line(s) in the file. */ if ( Curschar < Uncurschar ) { Uncurschar = Curschar; nchar = 'p'; } else nchar = 'P'; addtobuff(Undobuff,nchar,NULL); break; case 'w': addtobuff(Redobuff,'d','w',NULL); resetundo(); delword(1); Uncurschar = Curschar; updatescreen(); break; } break; case 'c': nchar = vgetc(); switch(nchar){ case 'c': resetundo(); /* Go to the beginning of the line */ beginline(); yankline(1); /* delete everything but the newline */ while ( *Curschar != '\n' ) delchar(); startinsert("cc"); updatescreen(); break; case 'w': resetundo(); delword(0); startinsert("cw"); updatescreen(); break; } break; case 'y': nchar = vgetc(); switch(nchar){ case 'y': yankline(Prenum==0?1:Prenum); break; default: beep(); } break; case '>': nchar = vgetc(); n = (Prenum==0?1:Prenum); switch(nchar){ case '>': tabinout(0,n); updatescreen(); break; default: beep(); } break; case '<': nchar = vgetc(); n = (Prenum==0?1:Prenum); switch(nchar){ case '<': tabinout(1,n); updatescreen(); break; default: beep(); } break; case '?': case '/': case ':': readcmdline(c); break; case 'n': repsearch(); break; case 'C': case 'D': p = Curschar; while ( Curschar >= p ) delchar(); updatescreen(); resetundo(); /* This should really go above the */ /* delchars above, and the undobuff should */ /* be constructed by them. */ if ( c == 'C' ) { Curschar++; startinsert("C"); } break; case 'r': nchar = vgetc(); resetundo(); if ( nchar=='\n' || (!Binary && nchar=='\r') ) { /* Replacing a char with a newline breaks the */ /* line in two, and is special. */ nchar = '\n'; /* convert \r to \n */ /* Save stuff necessary to undo it, by joining */ Uncurschar = Curschar-1; addtobuff(Undobuff,'J','i',*Curschar,'\033',NULL); /* Change current character. */ *Curschar = nchar; /* We don't want to end up on the '\n' */ if ( Curschar > Filemem ) Curschar--; else if (Curschar < Fileend ) Curschar++; } else { /* Replacing with a normal character */ addtobuff(Undobuff,'r',*Curschar,NULL); Uncurschar = Curschar; /* Change current character. */ *Curschar = nchar; } /* Save stuff necessary to redo it */ addtobuff(Redobuff,'r',nchar,NULL); updatescreen(); break; case 'p': putline(0); break; case 'P': putline(1); break; case 'J': for ( p=Curschar; *p!= '\n' && p<(Fileend-1) ; p++ ) ; if ( p >= (Fileend-1) ) { beep(); break; } Curschar = p; delchar(); resetundo(); Uncurschar = Curschar; addtobuff(Undobuff,'i','\n','\033',NULL); addtobuff(Redobuff,'J',NULL); updatescreen(); break; case '.': stuffin(Redobuff); break; case 'u': if ( Uncurschar != NULL && *Undobuff != '\0' ) { Curschar = Uncurschar; stuffin(Undobuff); *Undobuff = '\0'; } if ( Undelchars > 0 ) { Curschar = Uncurschar; /* construct the next Undobuff and Redobuff, which */ /* will re-insert the characters we're deleting. */ p = Undobuff; q = Redobuff; *p++ = *q++ = 'i'; while ( Undelchars-- > 0 ) { *p++ = *q++ = *Curschar; delchar(); } /* Finish constructing Uncursbuff, and Uncurschar */ /* is left unchanged. */ *p++ = *q++ = '\033'; *p = *q = '\0'; /* Undelchars has been reset to 0 */ updatescreen(); } break; default: beep(); break; } } /* * tabinout(inout,num) * * If inout==0, add a tab to the begining of the next num lines. * If inout==1, delete a tab from the begining of the next num lines. */ tabinout(inout,num) { int ntodo = num; char *savecurs, *p; beginline(); savecurs = Curschar; while ( ntodo-- > 0 ) { beginline(); if ( inout == 0 ) inschar('\t'); else { if ( *Curschar == '\t' ) delchar(); } if ( ntodo > 0 ) { if ( (p=nextline(Curschar)) != NULL ) Curschar = p; else break; } } /* We want to end up where we started */ Curschar = savecurs; updatescreen(); /* Construct re-do and un-do stuff */ sprintf(Redobuff,"%d%s",num,inout==0?">>":"<<"); resetundo(); Uncurschar = savecurs; sprintf(Undobuff,"%d%s",num,inout==0?"<<":">>"); } startinsert(initstr) char *initstr; { char *p, c; Insstart = Curschar; Ninsert = 0; Insptr = Insbuff; for (p=initstr; (c=(*p++))!='\0'; ) *Insptr++ = c; State = INSERT; windrefresh(); } resetundo() { Undelchars = 0; *Undobuff = '\0'; Uncurschar = NULL; }
300982.c
#ifndef v1beta1_eviction_TEST #define v1beta1_eviction_TEST // the following is to include only the main from the first c file #ifndef TEST_MAIN #define TEST_MAIN #define v1beta1_eviction_MAIN #endif // TEST_MAIN #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdbool.h> #include "../external/cJSON.h" #include "../model/v1beta1_eviction.h" v1beta1_eviction_t* instantiate_v1beta1_eviction(int include_optional); #include "test_v1_delete_options.c" #include "test_v1_object_meta.c" v1beta1_eviction_t* instantiate_v1beta1_eviction(int include_optional) { v1beta1_eviction_t* v1beta1_eviction = NULL; if (include_optional) { v1beta1_eviction = v1beta1_eviction_create( "0", // false, not to have infinite recursion instantiate_v1_delete_options(0), "0", // false, not to have infinite recursion instantiate_v1_object_meta(0) ); } else { v1beta1_eviction = v1beta1_eviction_create( "0", NULL, "0", NULL ); } return v1beta1_eviction; } #ifdef v1beta1_eviction_MAIN void test_v1beta1_eviction(int include_optional) { v1beta1_eviction_t* v1beta1_eviction_1 = instantiate_v1beta1_eviction(include_optional); cJSON* jsonv1beta1_eviction_1 = v1beta1_eviction_convertToJSON(v1beta1_eviction_1); printf("v1beta1_eviction :\n%s\n", cJSON_Print(jsonv1beta1_eviction_1)); v1beta1_eviction_t* v1beta1_eviction_2 = v1beta1_eviction_parseFromJSON(jsonv1beta1_eviction_1); cJSON* jsonv1beta1_eviction_2 = v1beta1_eviction_convertToJSON(v1beta1_eviction_2); printf("repeating v1beta1_eviction:\n%s\n", cJSON_Print(jsonv1beta1_eviction_2)); } int main() { test_v1beta1_eviction(1); test_v1beta1_eviction(0); printf("Hello world \n"); return 0; } #endif // v1beta1_eviction_MAIN #endif // v1beta1_eviction_TEST
708222.c
#include <stdlib.h> #define SIZE 123 int main (void) { // Allocate an array on heap. int *array = (int *) malloc (sizeof (int) * SIZE); // Release the array. free (array); // Write into released array. array [0] = 0; }
548070.c
/* * runsuite.c: C program to run libxml2 againts published testsuites * * See Copyright for the status of this software. * * [email protected] */ #ifdef HAVE_CONFIG_H #include "libxml.h" #else #include <stdio.h> #endif #ifdef LIBXML_XPATH_ENABLED #if !defined(_WIN32) || defined(__CYGWIN__) #include <unistd.h> #endif #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <libxml/parser.h> #include <libxml/parserInternals.h> #include <libxml/tree.h> #include <libxml/uri.h> #include <libxml/xmlreader.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #define LOGFILE "runxmlconf.log" static FILE *logfile = NULL; static int verbose = 0; #define NB_EXPECTED_ERRORS 15 #if defined(_WIN32) && !defined(__CYGWIN__) #define vsnprintf _vsnprintf #define snprintf _snprintf #endif const char *skipped_tests[] = { /* http://lists.w3.org/Archives/Public/public-xml-testsuite/2008Jul/0000.html */ "rmt-ns10-035", NULL }; /************************************************************************ * * * File name and path utilities * * * ************************************************************************/ static int checkTestFile(const char *filename) { struct stat buf; if (stat(filename, &buf) == -1) return(0); #if defined(_WIN32) && !defined(__CYGWIN__) if (!(buf.st_mode & _S_IFREG)) return(0); #else if (!S_ISREG(buf.st_mode)) return(0); #endif return(1); } static xmlChar *composeDir(const xmlChar *dir, const xmlChar *path) { char buf[500]; if (dir == NULL) return(xmlStrdup(path)); if (path == NULL) return(NULL); snprintf(buf, 500, "%s/%s", (const char *) dir, (const char *) path); return(xmlStrdup((const xmlChar *) buf)); } /************************************************************************ * * * Libxml2 specific routines * * * ************************************************************************/ static int nb_skipped = 0; static int nb_tests = 0; static int nb_errors = 0; static int nb_leaks = 0; /* * We need to trap calls to the resolver to not account memory for the catalog * and not rely on any external resources. */ static xmlParserInputPtr testExternalEntityLoader(const char *URL, const char *ID ATTRIBUTE_UNUSED, xmlParserCtxtPtr ctxt) { xmlParserInputPtr ret; ret = xmlNewInputFromFile(ctxt, (const char *) URL); return(ret); } /* * Trapping the error messages at the generic level to grab the equivalent of * stderr messages on CLI tools. */ static char testErrors[32769]; static int testErrorsSize = 0; static int nbError = 0; static int nbFatal = 0; static void test_log(const char *msg, ...) { va_list args; if (logfile != NULL) { fprintf(logfile, "\n------------\n"); va_start(args, msg); vfprintf(logfile, msg, args); va_end(args); fprintf(logfile, "%s", testErrors); testErrorsSize = 0; testErrors[0] = 0; } if (verbose) { va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); } } static void testErrorHandler(void *userData ATTRIBUTE_UNUSED, xmlErrorPtr error) { int res; if (testErrorsSize >= 32768) return; res = snprintf(&testErrors[testErrorsSize], 32768 - testErrorsSize, "%s:%d: %s\n", (error->file ? error->file : "entity"), error->line, error->message); if (error->level == XML_ERR_FATAL) nbFatal++; else if (error->level == XML_ERR_ERROR) nbError++; if (testErrorsSize + res >= 32768) { /* buffer is full */ testErrorsSize = 32768; testErrors[testErrorsSize] = 0; } else { testErrorsSize += res; } testErrors[testErrorsSize] = 0; } static xmlXPathContextPtr ctxtXPath; static void initializeLibxml2(void) { xmlGetWarningsDefaultValue = 0; xmlPedanticParserDefault(0); xmlMemSetup(xmlMemFree, xmlMemMalloc, xmlMemRealloc, xmlMemoryStrdup); xmlInitParser(); xmlSetExternalEntityLoader(testExternalEntityLoader); ctxtXPath = xmlXPathNewContext(NULL); /* * Deactivate the cache if created; otherwise we have to create/free it * for every test, since it will confuse the memory leak detection. * Note that normally this need not be done, since the cache is not * created until set explicitely with xmlXPathContextSetCache(); * but for test purposes it is sometimes usefull to activate the * cache by default for the whole library. */ if (ctxtXPath->cache != NULL) xmlXPathContextSetCache(ctxtXPath, 0, -1, 0); xmlSetStructuredErrorFunc(NULL, testErrorHandler); } /************************************************************************ * * * Run the xmlconf test if found * * * ************************************************************************/ static int xmlconfTestInvalid(const char *id, const char *filename, int options) { xmlDocPtr doc; xmlParserCtxtPtr ctxt; int ret = 1; ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { test_log("test %s : %s out of memory\n", id, filename); return(0); } doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (doc == NULL) { test_log("test %s : %s invalid document turned not well-formed too\n", id, filename); } else { /* invalidity should be reported both in the context and in the document */ if ((ctxt->valid != 0) || (doc->properties & XML_DOC_DTDVALID)) { test_log("test %s : %s failed to detect invalid document\n", id, filename); nb_errors++; ret = 0; } xmlFreeDoc(doc); } xmlFreeParserCtxt(ctxt); return(ret); } static int xmlconfTestValid(const char *id, const char *filename, int options) { xmlDocPtr doc; xmlParserCtxtPtr ctxt; int ret = 1; ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { test_log("test %s : %s out of memory\n", id, filename); return(0); } doc = xmlCtxtReadFile(ctxt, filename, NULL, options); if (doc == NULL) { test_log("test %s : %s failed to parse a valid document\n", id, filename); nb_errors++; ret = 0; } else { /* validity should be reported both in the context and in the document */ if ((ctxt->valid == 0) || ((doc->properties & XML_DOC_DTDVALID) == 0)) { test_log("test %s : %s failed to validate a valid document\n", id, filename); nb_errors++; ret = 0; } xmlFreeDoc(doc); } xmlFreeParserCtxt(ctxt); return(ret); } static int xmlconfTestNotNSWF(const char *id, const char *filename, int options) { xmlDocPtr doc; int ret = 1; /* * In case of Namespace errors, libxml2 will still parse the document * but log a Namesapce error. */ doc = xmlReadFile(filename, NULL, options); if (doc == NULL) { test_log("test %s : %s failed to parse the XML\n", id, filename); nb_errors++; ret = 0; } else { if ((xmlLastError.code == XML_ERR_OK) || (xmlLastError.domain != XML_FROM_NAMESPACE)) { test_log("test %s : %s failed to detect namespace error\n", id, filename); nb_errors++; ret = 0; } xmlFreeDoc(doc); } return(ret); } static int xmlconfTestNotWF(const char *id, const char *filename, int options) { xmlDocPtr doc; int ret = 1; doc = xmlReadFile(filename, NULL, options); if (doc != NULL) { test_log("test %s : %s failed to detect not well formedness\n", id, filename); nb_errors++; xmlFreeDoc(doc); ret = 0; } return(ret); } static int xmlconfTestItem(xmlDocPtr doc, xmlNodePtr cur) { int ret = -1; xmlChar *type = NULL; xmlChar *filename = NULL; xmlChar *uri = NULL; xmlChar *base = NULL; xmlChar *id = NULL; xmlChar *rec = NULL; xmlChar *version = NULL; xmlChar *entities = NULL; xmlChar *edition = NULL; int options = 0; int nstest = 0; int mem, final; int i; testErrorsSize = 0; testErrors[0] = 0; nbError = 0; nbFatal = 0; id = xmlGetProp(cur, BAD_CAST "ID"); if (id == NULL) { test_log("test missing ID, line %ld\n", xmlGetLineNo(cur)); goto error; } for (i = 0;skipped_tests[i] != NULL;i++) { if (!strcmp(skipped_tests[i], (char *) id)) { test_log("Skipping test %s from skipped list\n", (char *) id); ret = 0; nb_skipped++; goto error; } } type = xmlGetProp(cur, BAD_CAST "TYPE"); if (type == NULL) { test_log("test %s missing TYPE\n", (char *) id); goto error; } uri = xmlGetProp(cur, BAD_CAST "URI"); if (uri == NULL) { test_log("test %s missing URI\n", (char *) id); goto error; } base = xmlNodeGetBase(doc, cur); filename = composeDir(base, uri); if (!checkTestFile((char *) filename)) { test_log("test %s missing file %s \n", id, (filename ? (char *)filename : "NULL")); goto error; } version = xmlGetProp(cur, BAD_CAST "VERSION"); entities = xmlGetProp(cur, BAD_CAST "ENTITIES"); if (!xmlStrEqual(entities, BAD_CAST "none")) { options |= XML_PARSE_DTDLOAD; options |= XML_PARSE_NOENT; } rec = xmlGetProp(cur, BAD_CAST "RECOMMENDATION"); if ((rec == NULL) || (xmlStrEqual(rec, BAD_CAST "XML1.0")) || (xmlStrEqual(rec, BAD_CAST "XML1.0-errata2e")) || (xmlStrEqual(rec, BAD_CAST "XML1.0-errata3e")) || (xmlStrEqual(rec, BAD_CAST "XML1.0-errata4e"))) { if ((version != NULL) && (!xmlStrEqual(version, BAD_CAST "1.0"))) { test_log("Skipping test %s for %s\n", (char *) id, (char *) version); ret = 0; nb_skipped++; goto error; } ret = 1; } else if ((xmlStrEqual(rec, BAD_CAST "NS1.0")) || (xmlStrEqual(rec, BAD_CAST "NS1.0-errata1e"))) { ret = 1; nstest = 1; } else { test_log("Skipping test %s for REC %s\n", (char *) id, (char *) rec); ret = 0; nb_skipped++; goto error; } edition = xmlGetProp(cur, BAD_CAST "EDITION"); if ((edition != NULL) && (xmlStrchr(edition, '5') == NULL)) { /* test limited to all versions before 5th */ options |= XML_PARSE_OLD10; } /* * Reset errors and check memory usage before the test */ xmlResetLastError(); testErrorsSize = 0; testErrors[0] = 0; mem = xmlMemUsed(); if (xmlStrEqual(type, BAD_CAST "not-wf")) { if (nstest == 0) xmlconfTestNotWF((char *) id, (char *) filename, options); else xmlconfTestNotNSWF((char *) id, (char *) filename, options); } else if (xmlStrEqual(type, BAD_CAST "valid")) { options |= XML_PARSE_DTDVALID; xmlconfTestValid((char *) id, (char *) filename, options); } else if (xmlStrEqual(type, BAD_CAST "invalid")) { options |= XML_PARSE_DTDVALID; xmlconfTestInvalid((char *) id, (char *) filename, options); } else if (xmlStrEqual(type, BAD_CAST "error")) { test_log("Skipping error test %s \n", (char *) id); ret = 0; nb_skipped++; goto error; } else { test_log("test %s unknown TYPE value %s\n", (char *) id, (char *)type); ret = -1; goto error; } /* * Reset errors and check memory usage after the test */ xmlResetLastError(); final = xmlMemUsed(); if (final > mem) { test_log("test %s : %s leaked %d bytes\n", id, filename, final - mem); nb_leaks++; xmlMemDisplayLast(logfile, final - mem); } nb_tests++; error: if (type != NULL) xmlFree(type); if (entities != NULL) xmlFree(entities); if (edition != NULL) xmlFree(edition); if (version != NULL) xmlFree(version); if (filename != NULL) xmlFree(filename); if (uri != NULL) xmlFree(uri); if (base != NULL) xmlFree(base); if (id != NULL) xmlFree(id); if (rec != NULL) xmlFree(rec); return(ret); } static int xmlconfTestCases(xmlDocPtr doc, xmlNodePtr cur, int level) { xmlChar *profile; int ret = 0; int tests = 0; int output = 0; if (level == 1) { profile = xmlGetProp(cur, BAD_CAST "PROFILE"); if (profile != NULL) { output = 1; level++; printf("Test cases: %s\n", (char *) profile); xmlFree(profile); } } cur = cur->children; while (cur != NULL) { /* look only at elements we ignore everything else */ if (cur->type == XML_ELEMENT_NODE) { if (xmlStrEqual(cur->name, BAD_CAST "TESTCASES")) { ret += xmlconfTestCases(doc, cur, level); } else if (xmlStrEqual(cur->name, BAD_CAST "TEST")) { if (xmlconfTestItem(doc, cur) >= 0) ret++; tests++; } else { fprintf(stderr, "Unhandled element %s\n", (char *)cur->name); } } cur = cur->next; } if (output == 1) { if (tests > 0) printf("Test cases: %d tests\n", tests); } return(ret); } static int xmlconfTestSuite(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *profile; int ret = 0; profile = xmlGetProp(cur, BAD_CAST "PROFILE"); if (profile != NULL) { printf("Test suite: %s\n", (char *) profile); xmlFree(profile); } else printf("Test suite\n"); cur = cur->children; while (cur != NULL) { /* look only at elements we ignore everything else */ if (cur->type == XML_ELEMENT_NODE) { if (xmlStrEqual(cur->name, BAD_CAST "TESTCASES")) { ret += xmlconfTestCases(doc, cur, 1); } else { fprintf(stderr, "Unhandled element %s\n", (char *)cur->name); } } cur = cur->next; } return(ret); } static void xmlconfInfo(void) { fprintf(stderr, " you need to fetch and extract the\n"); fprintf(stderr, " latest XML Conformance Test Suites\n"); fprintf(stderr, " http://www.w3.org/XML/Test/xmlts20080205.tar.gz\n"); fprintf(stderr, " see http://www.w3.org/XML/Test/ for informations\n"); } static int xmlconfTest(void) { const char *confxml = "xmlconf/xmlconf.xml"; xmlDocPtr doc; xmlNodePtr cur; int ret = 0; if (!checkTestFile(confxml)) { fprintf(stderr, "%s is missing \n", confxml); xmlconfInfo(); return(-1); } doc = xmlReadFile(confxml, NULL, XML_PARSE_NOENT); if (doc == NULL) { fprintf(stderr, "%s is corrupted \n", confxml); xmlconfInfo(); return(-1); } cur = xmlDocGetRootElement(doc); if ((cur == NULL) || (!xmlStrEqual(cur->name, BAD_CAST "TESTSUITE"))) { fprintf(stderr, "Unexpected format %s\n", confxml); xmlconfInfo(); ret = -1; } else { ret = xmlconfTestSuite(doc, cur); } xmlFreeDoc(doc); return(ret); } /************************************************************************ * * * The driver for the tests * * * ************************************************************************/ int main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED) { int ret = 0; int old_errors, old_tests, old_leaks; logfile = fopen(LOGFILE, "w"); if (logfile == NULL) { fprintf(stderr, "Could not open the log file, running in verbose mode\n"); verbose = 1; } initializeLibxml2(); if ((argc >= 2) && (!strcmp(argv[1], "-v"))) verbose = 1; old_errors = nb_errors; old_tests = nb_tests; old_leaks = nb_leaks; xmlconfTest(); if ((nb_errors == old_errors) && (nb_leaks == old_leaks)) printf("Ran %d tests, no errors\n", nb_tests - old_tests); else printf("Ran %d tests, %d errors, %d leaks\n", nb_tests - old_tests, nb_errors - old_errors, nb_leaks - old_leaks); if ((nb_errors == 0) && (nb_leaks == 0)) { ret = 0; printf("Total %d tests, no errors\n", nb_tests); } else { ret = 1; printf("Total %d tests, %d errors, %d leaks\n", nb_tests, nb_errors, nb_leaks); printf("See %s for detailed output\n", LOGFILE); if ((nb_leaks == 0) && (nb_errors == NB_EXPECTED_ERRORS)) { printf("%d errors were expected\n", nb_errors); ret = 0; } } xmlXPathFreeContext(ctxtXPath); xmlCleanupParser(); xmlMemoryDump(); if (logfile != NULL) fclose(logfile); return(ret); } #else /* ! LIBXML_XPATH_ENABLED */ #include <stdio.h> int main(int argc, char **argv) { fprintf(stderr, "%s need XPath support\n", argv[0]); } #endif
90842.c
#include <stdlib.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_log.h" #include "app_wifi.h" #include "app_hw.h" #include "app_aws.h" #define TAG "app" static void handle_wifi_connect(void) { xTaskCreatePinnedToCore(appaws_connect, "appaws_connect", 15 * configMINIMAL_STACK_SIZE, NULL, 5, NULL, 0); } static void handle_wifi_failed(void) { ESP_LOGE(TAG, "wifi failed"); } void app_main() { apphw_init(appaws_publish); appaws_init(apphw_set_state); connect_wifi_params_t cbs = { .on_connected = handle_wifi_connect, .on_failed = handle_wifi_failed}; appwifi_connect(cbs); }
18746.c
#include "ntddk.h" #include "port.h" //Port-Driver Data Structures ADAPTER_EXTENSION AdapterExtension; LOGICAL_UNIT_EXTENSION LogicalUnitExtension; SCSI_REQUEST_BLOCK Srb; COMMON_EXTENSION CommonExtension; REMOVE_TRACKING_BLOCK RemoveTrackingBlock; INTERRUPT_DATA InterruptData; SRB_DATA SrbData; PORT_CONFIGURATION_INFORMATION PortConfigInfo; int __cdecl main() { return 0; }
627699.c
/* * u8g2_port.c * * Created on: Apr 24, 2021 * Author: hector */ #include <string.h> #include <stdio.h> #include "FreeRTOS.h" #include "cmsis_os2.h" #include "task.h" #include "u8g2.h" #include "i2c.h" extern uint8_t *i2c_buffer; uint8_t u8x8_stm32_gpio_and_delay(U8X8_UNUSED u8x8_t *u8x8, U8X8_UNUSED uint8_t msg, U8X8_UNUSED uint8_t arg_int, U8X8_UNUSED void *arg_ptr){ switch (msg) { case U8X8_MSG_GPIO_AND_DELAY_INIT: osDelay(pdMS_TO_TICKS(1)); //vTaskDelay(pdMS_TO_TICKS(1)); break; case U8X8_MSG_DELAY_MILLI: osDelay(pdMS_TO_TICKS(arg_int)); break; case U8X8_MSG_GPIO_DC: break; case U8X8_MSG_GPIO_RESET: break; } return 1; } uint8_t u8x8_byte_stm32_hw_i2c(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) { // static uint8_t buffer[32]; /* u8g2/u8x8 will never send more than 32 bytes between START_TRANSFER and END_TRANSFER */ static uint8_t buf_idx; uint8_t *data; uint8_t res = 1; switch(msg) { case U8X8_MSG_BYTE_SEND: data = (uint8_t *)arg_ptr; while( arg_int > 0 ) { i2c_buffer[buf_idx++] = *data; data++; arg_int--; } break; case U8X8_MSG_BYTE_INIT: /* add your custom code to init i2c subsystem */ break; case U8X8_MSG_BYTE_SET_DC: /* ignored for i2c */ break; case U8X8_MSG_BYTE_START_TRANSFER: buf_idx = 0; break; case U8X8_MSG_BYTE_END_TRANSFER: res = HAL_I2C_Master_Transmit(&hi2c3, u8x8_GetI2CAddress(u8x8) << 1, i2c_buffer, buf_idx, 100); res = (res == HAL_OK) ? 1 : 0; break; default: return 0; } return res; }
486205.c
/**************************************************************************** * arch/arm/src/lpc17xx_40xx/lpc17_40_clockconfig.c * arch/arm/src/chip/lpc17_40_clockconfig.c * * Copyright (C) 2010, 2013 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> /* This file is only a thin shell that includes the correct clock * configuration logic for the selected LPC17xx/LPC40xx family. The correct * file cannot be selected by the make system because it needs the * intelligence that only exists in chip.h that can associate an * LPC17xx/LPC40xx part number with an LPC17xx/LPC40xx family. * * The LPC176x and LPC178x_40xx system control block is *nearly* identical * but we have found that the LPC178x_40xx is more sensitive to the ordering * of certain operations. So, although the hardware seems very similar, the * safer thing to do is to separate the LPC176x and LPC178x_40xx into * separate files. */ #include <arch/lpc17xx_40xx/chip.h> #if defined(LPC176x) # include "lpc176x_clockconfig.c" #elif defined(LPC178x_40xx) # include "lpc178x_40xx_clockconfig.c" #else # error "Unrecognized LPC17xx/LPC40xx family" #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/
128192.c
// Copyright 2015 The Weave Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/macaroon_encoding.h" #include <string.h> #define MAJOR_TYPE_MASK 0xE0 // 0b11100000 #define ADDITIONAL_DATA_MASK 0x1F // 0b00011111 #define FLAG_1BYTE_UINT 24 #define FLAG_2BYTE_UINT 25 #define FLAG_4BYTE_UINT 26 // #define FLAG_8BYTE_UINT 27 // Do not support 8-byte typedef enum { kCborMajorTypeUint = 0, // type 0 -- unsigned integers kCborMajorTypeByteStr = 2 << 5, // type 2 -- byte strings kCborMajorTypeTextStr = 3 << 5, // type 3 -- text strings kCborMajorTypeArray = 4 << 5, // type 4 -- arrays } CborMajorType; static inline CborMajorType get_type_(const uint8_t* cbor); static inline uint8_t get_addtl_data_(const uint8_t* cbor); static inline void set_type_(CborMajorType type, uint8_t* cbor); static inline void set_addtl_data_(uint8_t addtl_data, uint8_t* cbor); /** Computes the minimum number of bytes to store the unsigned integer. */ static inline size_t uint_min_len_(uint32_t unsigned_int); /** Encoding or decoding without checking types */ static bool blindly_encode_uint_(uint32_t unsigned_int, uint8_t* buffer, size_t buffer_size, size_t* result_len); static bool blindly_encode_str_(const uint8_t* str, size_t str_len, uint8_t* buffer, size_t buffer_size, size_t* result_len); static bool blindly_decode_uint_(const uint8_t* cbor, size_t cbor_len, uint32_t* unsigned_int); static bool blindly_decode_str_(const uint8_t* cbor, size_t cbor_len, const uint8_t** out_str, size_t* out_str_len); bool uw_macaroon_encoding_get_item_len_(const uint8_t* cbor, size_t cbor_len, size_t* first_item_len) { if (cbor == NULL || cbor_len == 0 || first_item_len == NULL) { return false; } CborMajorType type = get_type_(cbor); if (type != kCborMajorTypeUint && type != kCborMajorTypeByteStr && type != kCborMajorTypeTextStr && type != kCborMajorTypeArray) { // Other types are not supported return false; } uint32_t unsigned_int; if (!blindly_decode_uint_(cbor, cbor_len, &unsigned_int)) { return false; } *first_item_len = uint_min_len_(unsigned_int) + 1; // For arrays, it returns only the length of the array length portion, not the // length of the whole array if (type == kCborMajorTypeByteStr || type == kCborMajorTypeTextStr) { *first_item_len += (size_t)unsigned_int; } if (*first_item_len > cbor_len) { // Something is wrong. The CBOR string isn't long enough. return false; } return true; } bool uw_macaroon_encoding_encode_uint_(const uint32_t unsigned_int, uint8_t* buffer, size_t buffer_size, size_t* resulting_cbor_len) { if (buffer == NULL || buffer_size == 0 || resulting_cbor_len == NULL) { return false; } set_type_(kCborMajorTypeUint, buffer); return blindly_encode_uint_(unsigned_int, buffer, buffer_size, resulting_cbor_len); } bool uw_macaroon_encoding_encode_array_len_(const uint32_t array_len, uint8_t* buffer, size_t buffer_size, size_t* resulting_cbor_len) { if (buffer == NULL || buffer_size == 0 || resulting_cbor_len == NULL) { return false; } set_type_(kCborMajorTypeArray, buffer); return blindly_encode_uint_(array_len, buffer, buffer_size, resulting_cbor_len); } bool uw_macaroon_encoding_encode_byte_str_(const uint8_t* str, size_t str_len, uint8_t* buffer, size_t buffer_size, size_t* resulting_cbor_len) { if (buffer == NULL || buffer_size == 0 || resulting_cbor_len == NULL) { return false; } set_type_(kCborMajorTypeByteStr, buffer); return blindly_encode_str_(str, str_len, buffer, buffer_size, resulting_cbor_len); } bool uw_macaroon_encoding_encode_text_str_(const uint8_t* str, size_t str_len, uint8_t* buffer, size_t buffer_size, size_t* resulting_cbor_len) { if (buffer == NULL || buffer_size == 0 || resulting_cbor_len == NULL) { return false; } set_type_(kCborMajorTypeTextStr, buffer); return blindly_encode_str_(str, str_len, buffer, buffer_size, resulting_cbor_len); } bool uw_macaroon_encoding_encode_byte_str_len_(size_t str_len, uint8_t* buffer, size_t buffer_size, size_t* resulting_cbor_len) { if (buffer == NULL || buffer_size == 0 || resulting_cbor_len == NULL) { return false; } set_type_(kCborMajorTypeByteStr, buffer); return blindly_encode_uint_(str_len, buffer, buffer_size, resulting_cbor_len); } bool uw_macaroon_encoding_decode_uint_(const uint8_t* cbor, size_t cbor_len, uint32_t* unsigned_int) { if (cbor == NULL || cbor_len == 0 || unsigned_int == NULL || get_type_(cbor) != kCborMajorTypeUint) { return false; } return blindly_decode_uint_(cbor, cbor_len, unsigned_int); } bool uw_macaroon_encoding_decode_array_len_(const uint8_t* cbor, size_t cbor_len, uint32_t* array_len) { if (cbor == NULL || cbor_len == 0 || array_len == NULL || get_type_(cbor) != kCborMajorTypeArray) { return false; } return blindly_decode_uint_(cbor, cbor_len, array_len); } bool uw_macaroon_encoding_decode_byte_str_(const uint8_t* cbor, size_t cbor_len, const uint8_t** out_str, size_t* out_str_len) { if (cbor == NULL || cbor_len == 0 || out_str == NULL || out_str_len == NULL || get_type_(cbor) != kCborMajorTypeByteStr) { return false; } return blindly_decode_str_(cbor, cbor_len, out_str, out_str_len); } bool uw_macaroon_encoding_decode_text_str_(const uint8_t* cbor, size_t cbor_len, const uint8_t** out_str, size_t* out_str_len) { if (cbor == NULL || cbor_len == 0 || out_str == NULL || out_str_len == NULL || get_type_(cbor) != kCborMajorTypeTextStr) { return false; } return blindly_decode_str_(cbor, cbor_len, out_str, out_str_len); } static inline CborMajorType get_type_(const uint8_t* cbor) { return (CborMajorType)((*cbor) & MAJOR_TYPE_MASK); } static inline uint8_t get_addtl_data_(const uint8_t* cbor) { return (*cbor) & ADDITIONAL_DATA_MASK; } static inline void set_type_(CborMajorType type, uint8_t* cbor) { *cbor = ((uint8_t)type) | ((*cbor) & ADDITIONAL_DATA_MASK); } static inline void set_addtl_data_(uint8_t addtl_data, uint8_t* cbor) { *cbor = ((*cbor) & MAJOR_TYPE_MASK) | (addtl_data & ADDITIONAL_DATA_MASK); } static inline size_t uint_min_len_(uint32_t unsigned_int) { if (unsigned_int < FLAG_1BYTE_UINT) { return 0; // Should be stored in the 5-bit additional data part } else if (unsigned_int <= 0xFF) { return 1; } else if (unsigned_int <= 0xFFFF) { return 2; } return 4; } /** * Writes the unsigned int in the big-endian fashion by using the minimum number * of bytes in CBOR */ static inline bool write_uint_big_endian_(uint32_t unsigned_int, uint8_t* buff, size_t buff_len) { if (buff == NULL || buff_len == 0) { return false; } size_t num_bytes = uint_min_len_(unsigned_int); if (num_bytes > buff_len) { // Not enough memory return false; } switch (num_bytes) { // Falling through intentionally case 4: *(buff++) = (uint8_t)(0xFF & (unsigned_int >> 24)); *(buff++) = (uint8_t)(0xFF & (unsigned_int >> 16)); case 2: *(buff++) = (uint8_t)(0xFF & (unsigned_int >> 8)); case 1: *(buff++) = (uint8_t)(0xFF & (unsigned_int)); break; default: return false; } return true; } /** Reads the unsigned int written in big-endian. */ static inline bool read_uint_big_endian_(const uint8_t* bytes, size_t num_bytes, uint32_t* unsigned_int) { if (bytes == NULL || num_bytes == 0 || num_bytes > 4 || unsigned_int == NULL) { return false; } *unsigned_int = 0; switch (num_bytes) { // Falling through intentionally case 4: *unsigned_int |= ((uint32_t)(*(bytes++))) << 24; *unsigned_int |= ((uint32_t)(*(bytes++))) << 16; case 2: *unsigned_int |= ((uint32_t)(*(bytes++))) << 8; case 1: *unsigned_int |= ((uint32_t)(*(bytes++))); break; default: return false; } return true; } static bool blindly_encode_uint_(uint32_t unsigned_int, uint8_t* buffer, size_t buffer_size, size_t* result_len) { if (buffer == NULL || buffer_size == 0 || result_len == NULL) { return false; } // Don't need to set the data type in this function *result_len = uint_min_len_(unsigned_int) + 1; if (*result_len > buffer_size) { // Not enough memory return false; } switch (*result_len) { case 1: set_addtl_data_(unsigned_int, buffer); return true; case 2: // 1 + 1 set_addtl_data_(FLAG_1BYTE_UINT, buffer); break; case 3: // 1 + 2 set_addtl_data_(FLAG_2BYTE_UINT, buffer); break; case 5: // 1 + 4 set_addtl_data_(FLAG_4BYTE_UINT, buffer); break; default: // Wrong length return false; } return write_uint_big_endian_(unsigned_int, buffer + 1, buffer_size - 1); } static bool blindly_encode_str_(const uint8_t* str, size_t str_len, uint8_t* buffer, size_t buffer_size, size_t* result_len) { if (buffer == NULL || buffer_size == 0) { return false; } if (str == NULL && str_len != 0) { // str_len should be 0 for empty strings return false; } // Don't need to set the data type in this function if (!blindly_encode_uint_((uint32_t)str_len, buffer, buffer_size, result_len)) { return false; } if (str_len == 0) { return true; } if (str_len + (*result_len) > buffer_size) { // Not enough memory return false; } memcpy(buffer + (*result_len), str, str_len); *result_len += str_len; return true; } static bool blindly_decode_uint_(const uint8_t* cbor, size_t cbor_len, uint32_t* unsigned_int) { if (cbor == NULL || cbor_len == 0 || unsigned_int == NULL) { return false; } uint8_t addtl_data = get_addtl_data_(cbor); if (addtl_data < FLAG_1BYTE_UINT) { *unsigned_int = (uint32_t)addtl_data; return true; } if (addtl_data > FLAG_4BYTE_UINT) { return false; } size_t uint_num_bytes = 1 << (addtl_data - (uint8_t)FLAG_1BYTE_UINT); if (uint_num_bytes + 1 > cbor_len) { // The CBOR string isn't long enough. return false; } return read_uint_big_endian_(cbor + 1, uint_num_bytes, unsigned_int); } static bool blindly_decode_str_(const uint8_t* cbor, size_t cbor_len, const uint8_t** out_str, size_t* out_str_len) { if (cbor == NULL || cbor_len == 0 || out_str == NULL || out_str_len == NULL) { return false; } uint32_t unsigned_int; if (!blindly_decode_uint_(cbor, cbor_len, &unsigned_int)) { return false; } size_t offset = 1 + uint_min_len_(unsigned_int); if (unsigned_int > (uint32_t)(cbor_len - offset)) { // The CBOR string isn't long enough return false; } *out_str = cbor + offset; *out_str_len = unsigned_int; return true; }
669815.c
/** \file * \brief Text Control * * See Copyright Notice in "iup.h" */ #include <gtk/gtk.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <memory.h> #include <stdarg.h> #include "iup.h" #include "iupcbs.h" #include "iup_object.h" #include "iup_layout.h" #include "iup_attrib.h" #include "iup_str.h" #include "iup_image.h" #include "iup_mask.h" #include "iup_drv.h" #include "iup_drvfont.h" #include "iup_image.h" #include "iup_key.h" #include "iup_array.h" #include "iup_text.h" #include "iupgtk_drv.h" #ifndef PANGO_WEIGHT_SEMIBOLD #define PANGO_WEIGHT_SEMIBOLD 600 #endif void iupdrvTextAddSpin(int *w, int h) { #if GTK_CHECK_VERSION(3, 0, 0) int spin_size = 2*22; #else int spin_size = 16; #endif *w += spin_size; (void)h; } void iupdrvTextAddBorders(int *x, int *y) { int border_size = 2*5; (*x) += border_size; (*y) += border_size; } static void gtkTextParseParagraphFormat(Ihandle* formattag, GtkTextTag* tag) { int val; char* format; format = iupAttribGet(formattag, "INDENT"); if (format && iupStrToInt(format, &val)) g_object_set(G_OBJECT(tag), "indent", val, NULL); format = iupAttribGet(formattag, "ALIGNMENT"); if (format) { if (iupStrEqualNoCase(format, "JUSTIFY")) val = GTK_JUSTIFY_FILL; else if (iupStrEqualNoCase(format, "RIGHT")) val = GTK_JUSTIFY_RIGHT; else if (iupStrEqualNoCase(format, "CENTER")) val = GTK_JUSTIFY_CENTER; else /* "LEFT" */ val = GTK_JUSTIFY_LEFT; g_object_set(G_OBJECT(tag), "justification", val, NULL); } format = iupAttribGet(formattag, "TABSARRAY"); { PangoTabArray *tabs; int pos, i = 0; PangoTabAlign align; char* str; tabs = pango_tab_array_new(32, FALSE); while (format) { str = iupStrDupUntil((char**)&format, ' '); if (!str) break; pos = atoi(str); free(str); str = iupStrDupUntil((char**)&format, ' '); if (!str) break; /* if (iupStrEqualNoCase(str, "DECIMAL")) unsupported for now align = PANGO_TAB_NUMERIC; else if (iupStrEqualNoCase(str, "RIGHT")) align = PANGO_TAB_RIGHT; else if (iupStrEqualNoCase(str, "CENTER")) align = PANGO_TAB_CENTER; else */ /* "LEFT" */ align = PANGO_TAB_LEFT; free(str); pango_tab_array_set_tab(tabs, i, align, iupGTK_PIXELS2PANGOUNITS(pos)); i++; if (i == 32) break; } g_object_set(G_OBJECT(tag), "tabs", tabs, NULL); pango_tab_array_free(tabs); } format = iupAttribGet(formattag, "SPACEBEFORE"); if (format && iupStrToInt(format, &val)) g_object_set(G_OBJECT(tag), "pixels-above-lines", val, NULL); format = iupAttribGet(formattag, "SPACEAFTER"); if (format && iupStrToInt(format, &val)) g_object_set(G_OBJECT(tag), "pixels-below-lines", val, NULL); format = iupAttribGet(formattag, "LINESPACING"); if (format && iupStrToInt(format, &val)) g_object_set(G_OBJECT(tag), "pixels-inside-wrap", val, NULL); } static void gtkTextParseCharacterFormat(Ihandle* formattag, GtkTextTag* tag) { int val; char* format; format = iupAttribGet(formattag, "LANGUAGE"); if (format) g_object_set(G_OBJECT(tag), "language", format, NULL); format = iupAttribGet(formattag, "STRETCH"); if (format) { if (iupStrEqualNoCase(format, "EXTRA_CONDENSED")) val = PANGO_STRETCH_EXTRA_CONDENSED; else if (iupStrEqualNoCase(format, "CONDENSED")) val = PANGO_STRETCH_CONDENSED; else if (iupStrEqualNoCase(format, "SEMI_CONDENSED")) val = PANGO_STRETCH_SEMI_CONDENSED; else if (iupStrEqualNoCase(format, "SEMI_EXPANDED")) val = PANGO_STRETCH_SEMI_EXPANDED; else if (iupStrEqualNoCase(format, "EXPANDED")) val = PANGO_STRETCH_EXPANDED; else if (iupStrEqualNoCase(format, "EXTRA_EXPANDED")) val = PANGO_STRETCH_EXTRA_EXPANDED; else /* "NORMAL" */ val = PANGO_STRETCH_NORMAL; g_object_set(G_OBJECT(tag), "stretch", val, NULL); } format = iupAttribGet(formattag, "RISE"); if (format) { val = 0; if (iupStrEqualNoCase(format, "SUPERSCRIPT")) { g_object_set(G_OBJECT(tag), "scale", PANGO_SCALE_X_SMALL, NULL); val = 10; /* 10 pixels up */ } else if (iupStrEqualNoCase(format, "SUBSCRIPT")) { g_object_set(G_OBJECT(tag), "scale", PANGO_SCALE_X_SMALL, NULL); val = -10; /* 10 pixels down */ } else iupStrToInt(format, &val); val = iupGTK_PIXELS2PANGOUNITS(val); g_object_set(G_OBJECT(tag), "rise", val, NULL); } format = iupAttribGet(formattag, "SMALLCAPS"); if (format) { if (iupStrBoolean(format)) val = PANGO_VARIANT_SMALL_CAPS; else val = PANGO_VARIANT_NORMAL; g_object_set(G_OBJECT(tag), "variant", val, NULL); } format = iupAttribGet(formattag, "ITALIC"); if (format) { if (iupStrBoolean(format)) val = PANGO_STYLE_ITALIC; else val = PANGO_STYLE_NORMAL; g_object_set(G_OBJECT(tag), "style", val, NULL); } format = iupAttribGet(formattag, "STRIKEOUT"); if (format) { val = iupStrBoolean(format); g_object_set(G_OBJECT(tag), "strikethrough", val, NULL); } format = iupAttribGet(formattag, "PROTECTED"); if (format) { val = iupStrBoolean(format); g_object_set(G_OBJECT(tag), "editable", val, NULL); } format = iupAttribGet(formattag, "FONTSIZE"); if (format && iupStrToInt(format, &val)) { if (val < 0) /* in pixels */ { val = iupGTK_PIXELS2PANGOUNITS(-val); g_object_set(G_OBJECT(tag), "size", val, NULL); } else /* in points */ g_object_set(G_OBJECT(tag), "size-points", (double)val, NULL); } format = iupAttribGet(formattag, "FONTSCALE"); if (format) { float fval = 0; if (iupStrEqualNoCase(format, "XX-SMALL")) fval = (float)PANGO_SCALE_XX_SMALL; else if (iupStrEqualNoCase(format, "X-SMALL")) fval = (float)PANGO_SCALE_X_SMALL; else if (iupStrEqualNoCase(format, "SMALL")) fval = (float)PANGO_SCALE_SMALL; else if (iupStrEqualNoCase(format, "MEDIUM")) fval = (float)PANGO_SCALE_MEDIUM; else if (iupStrEqualNoCase(format, "LARGE")) fval = (float)PANGO_SCALE_LARGE; else if (iupStrEqualNoCase(format, "X-LARGE")) fval = (float)PANGO_SCALE_X_LARGE; else if (iupStrEqualNoCase(format, "XX-LARGE")) fval = (float)PANGO_SCALE_XX_LARGE; else iupStrToFloat(format, &fval); if (fval > 0) g_object_set(G_OBJECT(tag), "scale", (double)fval, NULL); } format = iupAttribGet(formattag, "FONTFACE"); if (format) { /* Map standard names to native names */ const char* mapped_name = iupFontGetPangoName(format); if (mapped_name) g_object_set(G_OBJECT(tag), "family", mapped_name, NULL); else g_object_set(G_OBJECT(tag), "family", format, NULL); } format = iupAttribGet(formattag, "FGCOLOR"); if (format) { unsigned char r, g, b; if (iupStrToRGB(format, &r, &g, &b)) { GdkColor color; iupgdkColorSet(&color, r, g, b); g_object_set(G_OBJECT(tag), "foreground-gdk", &color, NULL); } } format = iupAttribGet(formattag, "BGCOLOR"); if (format) { unsigned char r, g, b; if (iupStrToRGB(format, &r, &g, &b)) { GdkColor color; iupgdkColorSet(&color, r, g, b); g_object_set(G_OBJECT(tag), "background-gdk", &color, NULL); } } format = iupAttribGet(formattag, "UNDERLINE"); if (format) { if (iupStrEqualNoCase(format, "SINGLE")) val = PANGO_UNDERLINE_SINGLE; else if (iupStrEqualNoCase(format, "DOUBLE")) val = PANGO_UNDERLINE_DOUBLE; else /* "NONE" */ val = PANGO_UNDERLINE_NONE; g_object_set(G_OBJECT(tag), "underline", val, NULL); } format = iupAttribGet(formattag, "WEIGHT"); if (format) { if (iupStrEqualNoCase(format, "EXTRALIGHT")) val = PANGO_WEIGHT_ULTRALIGHT; else if (iupStrEqualNoCase(format, "LIGHT")) val = PANGO_WEIGHT_LIGHT; else if (iupStrEqualNoCase(format, "SEMIBOLD")) val = PANGO_WEIGHT_SEMIBOLD; else if (iupStrEqualNoCase(format, "BOLD")) val = PANGO_WEIGHT_BOLD; else if (iupStrEqualNoCase(format, "EXTRABOLD")) val = PANGO_WEIGHT_ULTRABOLD; else if (iupStrEqualNoCase(format, "HEAVY")) val = PANGO_WEIGHT_HEAVY; else /* "NORMAL" */ val = PANGO_WEIGHT_NORMAL; g_object_set(G_OBJECT(tag), "weight", val, NULL); } } static void gtkTextMoveIterToLinCol(GtkTextBuffer *buffer, GtkTextIter *iter, int lin, int col) { int line_count, line_length; lin--; /* IUP starts at 1 */ col--; line_count = gtk_text_buffer_get_line_count(buffer); if (lin < 0) lin = 0; if (lin >= line_count) lin = line_count-1; gtk_text_buffer_get_iter_at_line(buffer, iter, lin); line_length = gtk_text_iter_get_chars_in_line(iter); if (col < 0) col = 0; if (col > line_length) col = line_length; /* after the last character */ gtk_text_iter_set_line_offset(iter, col); } static void gtkTextGetLinColFromPosition(const GtkTextIter *iter, int *lin, int *col) { *lin = gtk_text_iter_get_line(iter); *col = gtk_text_iter_get_line_offset(iter); (*lin)++; /* IUP starts at 1 */ (*col)++; } static int gtkTextGetCharSize(Ihandle* ih) { int charwidth; PangoFontMetrics* metrics; PangoContext* context; PangoFontDescription* fontdesc = (PangoFontDescription*)iupgtkGetPangoFontDescAttrib(ih); if (!fontdesc) return 0; context = gdk_pango_context_get(); metrics = pango_context_get_metrics(context, fontdesc, pango_context_get_language(context)); charwidth = pango_font_metrics_get_approximate_char_width(metrics); pango_font_metrics_unref(metrics); return charwidth; } void iupdrvTextConvertLinColToPos(Ihandle* ih, int lin, int col, int *pos) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtkTextMoveIterToLinCol(buffer, &iter, lin, col); *pos = gtk_text_iter_get_offset(&iter); } void iupdrvTextConvertPosToLinCol(Ihandle* ih, int pos, int *lin, int *col) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_offset(buffer, &iter, pos); gtkTextGetLinColFromPosition(&iter, lin, col); } static int gtkTextConvertXYToPos(Ihandle* ih, int x, int y) { if (ih->data->is_multiline) { GtkTextIter iter; gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(ih->handle), GTK_TEXT_WINDOW_WIDGET, x, y, &x, &y); gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(ih->handle), &iter, x, y); return gtk_text_iter_get_offset(&iter); } else { int trailing, off_x, off_y, pos; /* transform to Layout coordinates */ gtk_entry_get_layout_offsets(GTK_ENTRY(ih->handle), &off_x, &off_y); x = iupGTK_PIXELS2PANGOUNITS(x - off_x); y = iupGTK_PIXELS2PANGOUNITS(y - off_y); pango_layout_xy_to_index(gtk_entry_get_layout(GTK_ENTRY(ih->handle)), x, y, &pos, &trailing); return pos; } } static void gtkTextScrollToVisible(Ihandle* ih) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); GtkTextMark* mark = gtk_text_buffer_get_insert(buffer); gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(ih->handle), mark); } /*******************************************************************************************/ static int gtkTextSelectionGetIter(Ihandle* ih, const char* value, GtkTextIter* start_iter, GtkTextIter* end_iter) { int lin_start=1, col_start=1, lin_end=1, col_end=1; GtkTextBuffer *buffer; /* Used only when MULTILINE=YES */ buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (!value || iupStrEqualNoCase(value, "NONE")) { gtk_text_buffer_get_start_iter(buffer, start_iter); *end_iter = *start_iter; return 1; } if (iupStrEqualNoCase(value, "ALL")) { gtk_text_buffer_get_start_iter(buffer, start_iter); gtk_text_buffer_get_end_iter(buffer, end_iter); return 1; } if (sscanf(value, "%d,%d:%d,%d", &lin_start, &col_start, &lin_end, &col_end)!=4) return 0; if (lin_start<1 || col_start<1 || lin_end<1 || col_end<1) return 0; gtkTextMoveIterToLinCol(buffer, start_iter, lin_start, col_start); gtkTextMoveIterToLinCol(buffer, end_iter, lin_end, col_end); return 1; } static int gtkTextSelectionPosGetIter(Ihandle* ih, const char* value, GtkTextIter* start_iter, GtkTextIter* end_iter) { int start=0, end=0; GtkTextBuffer *buffer; /* Used only when MULTILINE=YES */ buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (!value || iupStrEqualNoCase(value, "NONE")) { gtk_text_buffer_get_start_iter(buffer, start_iter); *end_iter = *start_iter; return 1; } if (iupStrEqualNoCase(value, "ALL")) { gtk_text_buffer_get_start_iter(buffer, start_iter); gtk_text_buffer_get_end_iter(buffer, end_iter); return 1; } if (iupStrToIntInt(value, &start, &end, ':')!=2) return 0; if(start<0 || end<0) return 0; gtk_text_buffer_get_iter_at_offset(buffer, start_iter, start); gtk_text_buffer_get_iter_at_offset(buffer, end_iter, end); return 1; } static int gtkTextSetSelectionAttrib(Ihandle* ih, const char* value) { if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter; if (gtkTextSelectionGetIter(ih, value, &start_iter, &end_iter)) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_select_range(buffer, &start_iter, &end_iter); } } else { int start, end; if (!value || iupStrEqualNoCase(value, "NONE")) { start = 0; end = 0; } else if (iupStrEqualNoCase(value, "ALL")) { start = 0; end = -1; /* a negative value means all */ } else { start=1, end=1; if (iupStrToIntInt(value, &start, &end, ':')!=2) return 0; if(start<1 || end<1) return 0; start--; /* IUP starts at 1 */ end--; } gtk_editable_select_region(GTK_EDITABLE(ih->handle), start, end); } return 0; } static char* gtkTextGetSelectionAttrib(Ihandle* ih) { if (ih->data->is_multiline) { int start_col, start_lin, end_col, end_lin; GtkTextIter start_iter, end_iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (gtk_text_buffer_get_selection_bounds(buffer, &start_iter, &end_iter)) { gtkTextGetLinColFromPosition(&start_iter, &start_lin, &start_col); gtkTextGetLinColFromPosition(&end_iter, &end_lin, &end_col); return iupStrReturnStrf("%d,%d:%d,%d", start_lin, start_col, end_lin, end_col); } } else { int start, end; if (gtk_editable_get_selection_bounds(GTK_EDITABLE(ih->handle), &start, &end)) { start++; /* IUP starts at 1 */ end++; return iupStrReturnIntInt((int)start, (int)end, ':'); } } return NULL; } static int gtkTextSetSelectionPosAttrib(Ihandle* ih, const char* value) { if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter; if (gtkTextSelectionPosGetIter(ih, value, &start_iter, &end_iter)) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_select_range(buffer, &start_iter, &end_iter); } } else { int start, end; if (!value || iupStrEqualNoCase(value, "NONE")) { start = 0; end = 0; } else if (iupStrEqualNoCase(value, "ALL")) { start = 0; end = -1; /* a negative value means all */ } else { start=0, end=0; if (iupStrToIntInt(value, &start, &end, ':')!=2) return 0; if(start<0 || end<0) return 0; } gtk_editable_select_region(GTK_EDITABLE(ih->handle), start, end); } return 0; } static char* gtkTextGetSelectionPosAttrib(Ihandle* ih) { int start, end; if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (gtk_text_buffer_get_selection_bounds(buffer, &start_iter, &end_iter)) { start = gtk_text_iter_get_offset(&start_iter); end = gtk_text_iter_get_offset(&end_iter); return iupStrReturnIntInt((int)start, (int)end, ':'); } } else { if (gtk_editable_get_selection_bounds(GTK_EDITABLE(ih->handle), &start, &end)) return iupStrReturnIntInt((int)start, (int)end, ':'); } return NULL; } static int gtkTextSetSelectedTextAttrib(Ihandle* ih, const char* value) { if (!value) return 0; if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (gtk_text_buffer_get_selection_bounds(buffer, &start_iter, &end_iter)) { ih->data->disable_callbacks = 1; gtk_text_buffer_delete(buffer, &start_iter, &end_iter); gtk_text_buffer_insert(buffer, &start_iter, iupgtkStrConvertToSystem(value), -1); ih->data->disable_callbacks = 0; } } else { int start, end; if (gtk_editable_get_selection_bounds(GTK_EDITABLE(ih->handle), &start, &end)) { ih->data->disable_callbacks = 1; gtk_editable_delete_selection(GTK_EDITABLE(ih->handle)); gtk_editable_insert_text(GTK_EDITABLE(ih->handle), iupgtkStrConvertToSystem(value), -1, &start); ih->data->disable_callbacks = 0; } } return 0; } static char* gtkTextGetCountAttrib(Ihandle* ih) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); int count = gtk_text_buffer_get_char_count(buffer); return iupStrReturnInt(count); } static char* gtkTextGetLineCountAttrib(Ihandle* ih) { if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); int linecount = gtk_text_buffer_get_line_count(buffer); return iupStrReturnInt(linecount); } else return "1"; } static char* gtkTextGetSelectedTextAttrib(Ihandle* ih) { if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (gtk_text_buffer_get_selection_bounds(buffer, &start_iter, &end_iter)) return iupStrReturnStr(iupgtkStrConvertFromSystem(gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, TRUE))); } else { int start, end; if (gtk_editable_get_selection_bounds(GTK_EDITABLE(ih->handle), &start, &end)) { char* selectedtext = gtk_editable_get_chars(GTK_EDITABLE(ih->handle), start, end); char* str = iupStrReturnStr(iupgtkStrConvertFromSystem(selectedtext)); g_free(selectedtext); return str; } } return NULL; } static int gtkTextSetCaretAttrib(Ihandle* ih, const char* value) { int pos = 1; if (!value) return 0; if (ih->data->is_multiline) { int lin = 1, col = 1; GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); iupStrToIntInt(value, &lin, &col, ','); gtkTextMoveIterToLinCol(buffer, &iter, lin, col); gtk_text_buffer_place_cursor(buffer, &iter); gtkTextScrollToVisible(ih); } else { iupStrToInt(value, &pos); pos--; /* IUP starts at 1 */ if (pos < 0) pos = 0; gtk_editable_set_position(GTK_EDITABLE(ih->handle), pos); } return 0; } static char* gtkTextGetCaretAttrib(Ihandle* ih) { if (ih->data->is_multiline) { int col, lin; GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_mark(buffer, &iter, gtk_text_buffer_get_insert(buffer)); gtkTextGetLinColFromPosition(&iter, &lin, &col); return iupStrReturnIntInt(lin, col, ','); } else { int pos = gtk_editable_get_position(GTK_EDITABLE(ih->handle)); pos++; /* IUP starts at 1 */ return iupStrReturnInt(pos); } } static int gtkTextSetCaretPosAttrib(Ihandle* ih, const char* value) { int pos = 0; if (!value) return 0; iupStrToInt(value, &pos); if (pos < 0) pos = 0; if (ih->data->is_multiline) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_offset(buffer, &iter, pos); gtk_text_buffer_place_cursor(buffer, &iter); gtkTextScrollToVisible(ih); } else gtk_editable_set_position(GTK_EDITABLE(ih->handle), pos); return 0; } static char* gtkTextGetCaretPosAttrib(Ihandle* ih) { int pos; if (ih->data->is_multiline) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_mark(buffer, &iter, gtk_text_buffer_get_insert(buffer)); pos = gtk_text_iter_get_offset(&iter); } else pos = gtk_editable_get_position(GTK_EDITABLE(ih->handle)); return iupStrReturnInt(pos); } static int gtkTextSetScrollToAttrib(Ihandle* ih, const char* value) { if (!value) return 0; if (ih->data->is_multiline) { int lin = 1, col = 1; GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); iupStrToIntInt(value, &lin, &col, ','); if (lin < 1) lin = 1; if (col < 1) col = 1; gtkTextMoveIterToLinCol(buffer, &iter, lin, col); gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(ih->handle), &iter, 0, FALSE, 0, 0); } else { int pos = 1; iupStrToInt(value, &pos); if (pos < 1) pos = 1; pos--; /* return to GTK referece */ gtk_editable_set_position(GTK_EDITABLE(ih->handle), pos); } return 0; } static int gtkTextSetScrollToPosAttrib(Ihandle* ih, const char* value) { int pos = 0; if (!value) return 0; iupStrToInt(value, &pos); if (pos < 0) pos = 0; if (ih->data->is_multiline) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_offset(buffer, &iter, pos); gtk_text_view_scroll_to_iter(GTK_TEXT_VIEW(ih->handle), &iter, 0, FALSE, 0, 0); } else gtk_editable_set_position(GTK_EDITABLE(ih->handle), pos); return 0; } static int gtkTextSetValueAttrib(Ihandle* ih, const char* value) { if (!value) value = ""; ih->data->disable_callbacks = 1; if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_set_text(buffer, iupgtkStrConvertToSystem(value), -1); } else gtk_entry_set_text(GTK_ENTRY(ih->handle), iupgtkStrConvertToSystem(value)); ih->data->disable_callbacks = 0; return 0; } static char* gtkTextGetValueAttrib(Ihandle* ih) { char* value; if (ih->data->is_multiline) { GtkTextIter start_iter; GtkTextIter end_iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_start_iter(buffer, &start_iter); gtk_text_buffer_get_end_iter(buffer, &end_iter); value = iupStrReturnStr(iupgtkStrConvertFromSystem(gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, TRUE))); } else value = iupStrReturnStr(iupgtkStrConvertFromSystem(gtk_entry_get_text(GTK_ENTRY(ih->handle)))); if (!value) value = ""; return value; } static char* gtkTextGetLineValueAttrib(Ihandle* ih) { if (ih->data->is_multiline) { GtkTextIter start_iter, end_iter, iter; int lin; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_mark(buffer, &iter, gtk_text_buffer_get_insert(buffer)); lin = gtk_text_iter_get_line(&iter); gtk_text_buffer_get_iter_at_line(buffer, &start_iter, lin); gtk_text_buffer_get_iter_at_line(buffer, &end_iter, lin); gtk_text_iter_forward_to_line_end(&end_iter); return iupStrReturnStr(iupgtkStrConvertFromSystem(gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, TRUE))); } else return gtkTextGetValueAttrib(ih); } static int gtkTextSetInsertAttrib(Ihandle* ih, const char* value) { if (!ih->handle) /* do not do the action before map */ return 0; if (!value) return 0; ih->data->disable_callbacks = 1; if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_insert_at_cursor(buffer, iupgtkStrConvertToSystem(value), -1); } else { gint pos = gtk_editable_get_position(GTK_EDITABLE(ih->handle)); gtk_editable_insert_text(GTK_EDITABLE(ih->handle), iupgtkStrConvertToSystem(value), -1, &pos); } ih->data->disable_callbacks = 0; return 0; } static int gtkTextSetAppendAttrib(Ihandle* ih, const char* value) { gint pos; if (!ih->handle) /* do not do the action before map */ return 0; ih->data->disable_callbacks = 1; if (ih->data->is_multiline) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_end_iter(buffer, &iter); pos = gtk_text_buffer_get_char_count(buffer); if (ih->data->append_newline && pos!=0) gtk_text_buffer_insert(buffer, &iter, "\n", 1); gtk_text_buffer_insert(buffer, &iter, iupgtkStrConvertToSystem(value), -1); } else { #if GTK_CHECK_VERSION(2, 14, 0) pos = gtk_entry_get_text_length(GTK_ENTRY(ih->handle))+1; #else pos = strlen(gtk_entry_get_text(GTK_ENTRY(ih->handle)))+1; #endif gtk_editable_insert_text(GTK_EDITABLE(ih->handle), iupgtkStrConvertToSystem(value), -1, &pos); } ih->data->disable_callbacks = 0; return 0; } static int gtkTextSetAlignmentAttrib(Ihandle* ih, const char* value) { float xalign; GtkJustification justification; if (iupStrEqualNoCase(value, "ARIGHT")) { xalign = 1.0f; justification = GTK_JUSTIFY_RIGHT; } else if (iupStrEqualNoCase(value, "ACENTER")) { xalign = 0.5f; justification = GTK_JUSTIFY_CENTER; } else /* "ALEFT" */ { xalign = 0; justification = GTK_JUSTIFY_LEFT; } if (ih->data->is_multiline) gtk_text_view_set_justification(GTK_TEXT_VIEW(ih->handle), justification); else gtk_entry_set_alignment(GTK_ENTRY(ih->handle), xalign); return 1; } static int gtkTextSetPaddingAttrib(Ihandle* ih, const char* value) { iupStrToIntInt(value, &ih->data->horiz_padding, &ih->data->vert_padding, 'x'); if (ih->handle) { if (ih->data->is_multiline) { gtk_text_view_set_left_margin(GTK_TEXT_VIEW(ih->handle), ih->data->horiz_padding); gtk_text_view_set_right_margin(GTK_TEXT_VIEW(ih->handle), ih->data->horiz_padding); ih->data->vert_padding = 0; } else { #if GTK_CHECK_VERSION(2, 10, 0) GtkBorder border; border.bottom = border.top = (gint16)ih->data->vert_padding; border.left = border.right = (gint16)ih->data->horiz_padding; gtk_entry_set_inner_border(GTK_ENTRY(ih->handle), &border); #endif } return 0; } else return 1; /* store until not mapped, when mapped will be set again */ } static int gtkTextSetNCAttrib(Ihandle* ih, const char* value) { if (!iupStrToInt(value, &ih->data->nc)) ih->data->nc = INT_MAX; if (ih->handle) { if (!ih->data->is_multiline) gtk_entry_set_max_length(GTK_ENTRY(ih->handle), ih->data->nc); return 0; } else return 1; /* store until not mapped, when mapped will be set again */ } static int gtkTextSetClipboardAttrib(Ihandle *ih, const char *value) { ih->data->disable_callbacks = 1; if (iupStrEqualNoCase(value, "COPY")) { if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); GtkClipboard *clipboard = gtk_clipboard_get(gdk_atom_intern("CLIPBOARD", FALSE)); gtk_text_buffer_copy_clipboard(buffer, clipboard); } else gtk_editable_copy_clipboard(GTK_EDITABLE(ih->handle)); } else if (iupStrEqualNoCase(value, "CUT")) { if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); GtkClipboard *clipboard = gtk_clipboard_get(gdk_atom_intern("CLIPBOARD", FALSE)); gtk_text_buffer_cut_clipboard(buffer, clipboard, TRUE); } else gtk_editable_cut_clipboard(GTK_EDITABLE(ih->handle)); } else if (iupStrEqualNoCase(value, "PASTE")) { if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); GtkClipboard *clipboard = gtk_clipboard_get(gdk_atom_intern("CLIPBOARD", FALSE)); gtk_text_buffer_paste_clipboard(buffer, clipboard, NULL, TRUE); } else gtk_editable_paste_clipboard(GTK_EDITABLE(ih->handle)); } else if (iupStrEqualNoCase(value, "CLEAR")) { if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_delete_selection(buffer, FALSE, TRUE); } else gtk_editable_delete_selection(GTK_EDITABLE(ih->handle)); } ih->data->disable_callbacks = 0; return 0; } static int gtkTextSetReadOnlyAttrib(Ihandle* ih, const char* value) { if (ih->data->is_multiline) gtk_text_view_set_editable(GTK_TEXT_VIEW(ih->handle), !iupStrBoolean(value)); else gtk_editable_set_editable(GTK_EDITABLE(ih->handle), !iupStrBoolean(value)); return 0; } static char* gtkTextGetReadOnlyAttrib(Ihandle* ih) { int editable; if (ih->data->is_multiline) editable = gtk_text_view_get_editable(GTK_TEXT_VIEW(ih->handle)); else editable = gtk_editable_get_editable(GTK_EDITABLE(ih->handle)); return iupStrReturnBoolean (!editable); } static int gtkTextSetBgColorAttrib(Ihandle* ih, const char* value) { if (ih->data->is_multiline) { GtkScrolledWindow* scrolled_window = (GtkScrolledWindow*)iupAttribGet(ih, "_IUP_EXTRAPARENT"); unsigned char r, g, b; /* ignore given value, must use only from parent for the scrollbars */ char* parent_value = iupBaseNativeParentGetBgColor(ih); if (iupStrToRGB(parent_value, &r, &g, &b)) { GtkWidget* sb; iupgtkSetBgColor((GtkWidget*)scrolled_window, r, g, b); #if GTK_CHECK_VERSION(2, 8, 0) sb = gtk_scrolled_window_get_hscrollbar(scrolled_window); if (sb) iupgtkSetBgColor(sb, r, g, b); sb = gtk_scrolled_window_get_vscrollbar(scrolled_window); if (sb) iupgtkSetBgColor(sb, r, g, b); #endif } } return iupdrvBaseSetBgColorAttrib(ih, value); } static int gtkTextSetTabSizeAttrib(Ihandle* ih, const char* value) { PangoTabArray *tabs; int tabsize, charwidth; if (!ih->data->is_multiline) return 0; iupStrToInt(value, &tabsize); charwidth = gtkTextGetCharSize(ih); tabsize *= charwidth; tabs = pango_tab_array_new_with_positions(1, FALSE, PANGO_TAB_LEFT, tabsize); gtk_text_view_set_tabs(GTK_TEXT_VIEW(ih->handle), tabs); pango_tab_array_free(tabs); return 1; } static int gtkTextSetOverwriteAttrib(Ihandle* ih, const char* value) { if (!ih->data->is_multiline) return 0; gtk_text_view_set_overwrite(GTK_TEXT_VIEW(ih->handle), iupStrBoolean(value)); return 0; } static char* gtkTextGetOverwriteAttrib(Ihandle* ih) { if (!ih->data->is_multiline) return NULL; return iupStrReturnChecked(gtk_text_view_get_overwrite(GTK_TEXT_VIEW(ih->handle))); } void* iupdrvTextAddFormatTagStartBulk(Ihandle* ih) { GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_begin_user_action(buffer); return NULL; } void iupdrvTextAddFormatTagStopBulk(Ihandle* ih, void* state) { GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_end_user_action(buffer); (void)state; } void iupdrvTextAddFormatTag(Ihandle* ih, Ihandle* formattag, int bulk) { GtkTextBuffer *buffer; GtkTextIter start_iter, end_iter; GtkTextTag* tag; char *selection; (void)bulk; if (!ih->data->is_multiline) return; buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); selection = iupAttribGet(formattag, "SELECTION"); if (selection) { if (!gtkTextSelectionGetIter(ih, selection, &start_iter, &end_iter)) return; } else { char* selectionpos = iupAttribGet(formattag, "SELECTIONPOS"); if (selectionpos) { if (!gtkTextSelectionPosGetIter(ih, selectionpos, &start_iter, &end_iter)) return; } else { GtkTextMark* mark = gtk_text_buffer_get_insert(buffer); gtk_text_buffer_get_iter_at_mark(buffer, &start_iter, mark); gtk_text_buffer_get_iter_at_mark(buffer, &end_iter, mark); } } tag = gtk_text_buffer_create_tag(buffer, NULL, NULL); gtkTextParseParagraphFormat(formattag, tag); gtkTextParseCharacterFormat(formattag, tag); gtk_text_buffer_apply_tag(buffer, tag, &start_iter, &end_iter); } static int gtkTextSetRemoveFormattingAttrib(Ihandle* ih, const char* value) { GtkTextBuffer *buffer; GtkTextIter start_iter, end_iter; if (!ih->data->is_multiline) return 0; buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); if (iupStrEqualNoCase(value, "ALL")) { gtk_text_buffer_get_start_iter(buffer, &start_iter); gtk_text_buffer_get_end_iter(buffer, &end_iter); gtk_text_buffer_remove_all_tags(buffer, &start_iter, &end_iter); } else { if (gtk_text_buffer_get_selection_bounds(buffer, &start_iter, &end_iter)) gtk_text_buffer_remove_all_tags(buffer, &start_iter, &end_iter); } return 0; } /************************************************************************************************/ static gint gtkTextSpinInput(GtkSpinButton *spin, gdouble *val, Ihandle* ih) { (void)spin; *val = (double)iupAttribGetInt(ih, "_IUPGTK_SPIN_VALUE"); /* called only when SPINAUTO=NO */ return TRUE; /* disable input update */ } static gboolean gtkTextSpinOutput(GtkSpinButton *spin, Ihandle* ih) { if (iupAttribGet(ih, "_IUPGTK_SPIN_NOAUTO")) { GtkAdjustment* adjustment = gtk_spin_button_get_adjustment(spin); iupAttribSetInt(ih, "_IUPGTK_SPIN_VALUE", (int)gtk_adjustment_get_value(adjustment)); return TRUE; /* disable output update */ } else { if (ih->data->disable_callbacks==0) ih->data->disable_callbacks = 2; /* disable other text callbacks processing, but allow spin */ return FALSE; /* let the system update the display */ } } static void gtkTextSpinValueChanged(GtkSpinButton* spin, Ihandle* ih) { IFni cb; (void)spin; if (ih->data->disable_callbacks == 1) return; ih->data->disable_callbacks = 0; /* enable other text callbacks processing */ cb = (IFni)IupGetCallback(ih, "SPIN_CB"); if (cb) { int pos, ret; if (iupAttribGet(ih, "_IUPGTK_SPIN_NOAUTO")) pos = iupAttribGetInt(ih, "_IUPGTK_SPIN_VALUE"); else pos = gtk_spin_button_get_value_as_int((GtkSpinButton*)ih->handle); ret = cb(ih, pos); if (ret == IUP_IGNORE) { pos = iupAttribGetInt(ih, "_IUPGTK_SPIN_OLDVALUE"); /* restore previous value */ ih->data->disable_callbacks = 1; gtk_spin_button_set_value((GtkSpinButton*)ih->handle, (double)pos); ih->data->disable_callbacks = 0; if (iupAttribGet(ih, "_IUPGTK_SPIN_NOAUTO")) iupAttribSetInt(ih, "_IUPGTK_SPIN_VALUE", pos); ih->data->disable_callbacks = 0; return; } } iupBaseCallValueChangedCb(ih); iupAttribSetInt(ih, "_IUPGTK_SPIN_OLDVALUE", gtk_spin_button_get_value_as_int((GtkSpinButton*)ih->handle)); } static int gtkTextSetSpinMinAttrib(Ihandle* ih, const char* value) { if (GTK_IS_SPIN_BUTTON(ih->handle)) { int min; if (iupStrToInt(value, &min)) { int max = iupAttribGetInt(ih, "SPINMAX"); ih->data->disable_callbacks = 1; gtk_spin_button_set_range((GtkSpinButton*)ih->handle, (double)min, (double)max); ih->data->disable_callbacks = 0; } } return 1; } static int gtkTextSetSpinMaxAttrib(Ihandle* ih, const char* value) { if (GTK_IS_SPIN_BUTTON(ih->handle)) { int max; if (iupStrToInt(value, &max)) { int min = iupAttribGetInt(ih, "SPINMIN"); ih->data->disable_callbacks = 1; gtk_spin_button_set_range((GtkSpinButton*)ih->handle, (double)min, (double)max); ih->data->disable_callbacks = 0; } } return 1; } static int gtkTextSetSpinIncAttrib(Ihandle* ih, const char* value) { if (GTK_IS_SPIN_BUTTON(ih->handle)) { int inc; if (iupStrToInt(value, &inc)) gtk_spin_button_set_increments((GtkSpinButton*)ih->handle, (double)inc, (double)(inc*10)); } return 1; } static int gtkTextSetSpinValueAttrib(Ihandle* ih, const char* value) { if (GTK_IS_SPIN_BUTTON(ih->handle)) { int pos; if (iupStrToInt(value, &pos)) { ih->data->disable_callbacks = 1; gtk_spin_button_set_value((GtkSpinButton*)ih->handle, (double)pos); ih->data->disable_callbacks = 0; if (iupAttribGet(ih, "_IUPGTK_SPIN_NOAUTO")) iupAttribSetInt(ih, "_IUPGTK_SPIN_VALUE", pos); } } return 1; } static char* gtkTextGetSpinValueAttrib(Ihandle* ih) { if (GTK_IS_SPIN_BUTTON(ih->handle)) { int pos; if (iupAttribGet(ih, "_IUPGTK_SPIN_NOAUTO")) pos = iupAttribGetInt(ih, "_IUPGTK_SPIN_VALUE"); else pos = gtk_spin_button_get_value_as_int((GtkSpinButton*)ih->handle); return iupStrReturnInt(pos); } return NULL; } /**********************************************************************************************************/ static void gtkTextMoveCursor(GtkWidget *w, GtkMovementStep step, gint count, gboolean extend_selection, Ihandle* ih) { int col, lin, pos; IFniii cb = (IFniii)IupGetCallback(ih, "CARET_CB"); if (!cb) return; if (ih->data->is_multiline) { GtkTextIter iter; GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); gtk_text_buffer_get_iter_at_mark(buffer, &iter, gtk_text_buffer_get_insert(buffer)); gtkTextGetLinColFromPosition(&iter, &lin, &col); pos = gtk_text_iter_get_offset(&iter); } else { pos = gtk_editable_get_position(GTK_EDITABLE(ih->handle)); col = pos; col++; /* IUP starts at 1 */ lin = 1; } if (pos != ih->data->last_caret_pos) { ih->data->last_caret_pos = pos; cb(ih, lin, col, pos); } (void)w; (void)step; (void)count; (void)extend_selection; } static gboolean gtkTextKeyReleaseEvent(GtkWidget *widget, GdkEventKey *evt, Ihandle *ih) { gtkTextMoveCursor(NULL, 0, 0, 0, ih); (void)widget; (void)evt; return FALSE; } static gboolean gtkTextButtonEvent(GtkWidget *widget, GdkEventButton *evt, Ihandle *ih) { gtkTextMoveCursor(NULL, 0, 0, 0, ih); return iupgtkButtonEvent(widget, evt, ih); } static void gtkTextEntryDeleteText(GtkEditable *editable, int start, int end, Ihandle* ih) { IFnis cb = (IFnis)IupGetCallback(ih, "ACTION"); if (ih->data->disable_callbacks) return; if (iupEditCallActionCb(ih, cb, NULL, start, end, ih->data->mask, ih->data->nc, 1, iupgtkStrGetUTF8Mode())==0) g_signal_stop_emission_by_name (editable, "delete_text"); } static void gtkTextEntryInsertText(GtkEditable *editable, char *insert_value, int len, int *pos, Ihandle* ih) { IFnis cb = (IFnis)IupGetCallback(ih, "ACTION"); int ret; if (ih->data->disable_callbacks) return; ret = iupEditCallActionCb(ih, cb, iupgtkStrConvertFromSystem(insert_value), *pos, *pos, ih->data->mask, ih->data->nc, 0, iupgtkStrGetUTF8Mode()); if (ret == 0) g_signal_stop_emission_by_name(editable, "insert_text"); else if (ret != -1) { insert_value[0] = (char)ret; /* replace key */ ih->data->disable_callbacks = 1; gtk_editable_insert_text(editable, insert_value, 1, pos); ih->data->disable_callbacks = 0; g_signal_stop_emission_by_name(editable, "insert_text"); } (void)len; } static void gtkTextBufferDeleteRange(GtkTextBuffer *textbuffer, GtkTextIter *start_iter, GtkTextIter *end_iter, Ihandle* ih) { IFnis cb = (IFnis)IupGetCallback(ih, "ACTION"); int start, end; if (ih->data->disable_callbacks) return; start = gtk_text_iter_get_offset(start_iter); end = gtk_text_iter_get_offset(end_iter); if (iupEditCallActionCb(ih, cb, NULL, start, end, ih->data->mask, ih->data->nc, 1, iupgtkStrGetUTF8Mode())==0) g_signal_stop_emission_by_name (textbuffer, "delete_range"); } static void gtkTextBufferInsertText(GtkTextBuffer *textbuffer, GtkTextIter *pos_iter, gchar *insert_value, gint len, Ihandle* ih) { IFnis cb = (IFnis)IupGetCallback(ih, "ACTION"); int ret, pos; if (ih->data->disable_callbacks) return; pos = gtk_text_iter_get_offset(pos_iter); ret = iupEditCallActionCb(ih, cb, iupgtkStrConvertFromSystem(insert_value), pos, pos, ih->data->mask, ih->data->nc, 0, iupgtkStrGetUTF8Mode()); if (ret == 0) g_signal_stop_emission_by_name(textbuffer, "insert_text"); else if (ret != -1) { insert_value[0] = (char)ret; /* replace key */ ih->data->disable_callbacks = 1; gtk_text_buffer_insert(textbuffer, pos_iter, insert_value, 1); ih->data->disable_callbacks = 0; g_signal_stop_emission_by_name(textbuffer, "insert_text"); } (void)len; } static void gtkTextChanged(void* dummy, Ihandle* ih) { if (ih->data->disable_callbacks) return; iupBaseCallValueChangedCb(ih); (void)dummy; } /**********************************************************************************************************/ static int gtkTextMapMethod(Ihandle* ih) { GtkScrolledWindow* scrolled_window = NULL; if (ih->data->is_multiline) { GtkPolicyType hscrollbar_policy, vscrollbar_policy; int wordwrap = 0; ih->handle = gtk_text_view_new(); if (!ih->handle) return IUP_ERROR; scrolled_window = (GtkScrolledWindow*)gtk_scrolled_window_new(NULL, NULL); if (!scrolled_window) return IUP_ERROR; gtk_container_add((GtkContainer*)scrolled_window, ih->handle); gtk_widget_show((GtkWidget*)scrolled_window); iupAttribSet(ih, "_IUP_EXTRAPARENT", (char*)scrolled_window); /* formatting is always supported when MULTILINE=YES */ ih->data->has_formatting = 1; if (iupAttribGetBoolean(ih, "WORDWRAP")) { wordwrap = 1; ih->data->sb &= ~IUP_SB_HORIZ; /* must remove the horizontal scroolbar */ } if (iupAttribGetBoolean(ih, "BORDER")) gtk_scrolled_window_set_shadow_type(scrolled_window, GTK_SHADOW_IN); else gtk_scrolled_window_set_shadow_type(scrolled_window, GTK_SHADOW_NONE); if (ih->data->sb & IUP_SB_HORIZ) { if (iupAttribGetBoolean(ih, "AUTOHIDE")) hscrollbar_policy = GTK_POLICY_AUTOMATIC; else hscrollbar_policy = GTK_POLICY_ALWAYS; } else hscrollbar_policy = GTK_POLICY_NEVER; if (ih->data->sb & IUP_SB_VERT) { if (iupAttribGetBoolean(ih, "AUTOHIDE")) vscrollbar_policy = GTK_POLICY_AUTOMATIC; else vscrollbar_policy = GTK_POLICY_ALWAYS; } else vscrollbar_policy = GTK_POLICY_NEVER; gtk_scrolled_window_set_policy(scrolled_window, hscrollbar_policy, vscrollbar_policy); if (wordwrap) gtk_text_view_set_wrap_mode((GtkTextView*)ih->handle, GTK_WRAP_WORD); gtk_widget_add_events(ih->handle, GDK_ENTER_NOTIFY_MASK|GDK_LEAVE_NOTIFY_MASK); } else { if (iupAttribGetBoolean(ih, "SPIN")) ih->handle = gtk_spin_button_new_with_range((double)iupAttribGetInt(ih, "SPINMIN"), (double)iupAttribGetInt(ih, "SPINMAX"), (double)iupAttribGetInt(ih, "SPININC")); /* It inherits from GtkEntry */ else ih->handle = gtk_entry_new(); if (!ih->handle) return IUP_ERROR; /* formatting is never supported when MULTILINE=NO */ ih->data->has_formatting = 0; gtk_entry_set_has_frame((GtkEntry*)ih->handle, IupGetInt(ih, "BORDER")); gtk_entry_set_width_chars((GtkEntry*)ih->handle, 1); /* minimum size */ if (iupAttribGetBoolean(ih, "PASSWORD")) gtk_entry_set_visibility((GtkEntry*)ih->handle, FALSE); if (GTK_IS_SPIN_BUTTON(ih->handle)) { gtk_spin_button_set_numeric((GtkSpinButton*)ih->handle, FALSE); gtk_spin_button_set_digits((GtkSpinButton*)ih->handle, 0); gtk_spin_button_set_wrap((GtkSpinButton*)ih->handle, iupAttribGetBoolean(ih, "SPINWRAP")); g_signal_connect(G_OBJECT(ih->handle), "value-changed", G_CALLBACK(gtkTextSpinValueChanged), ih); g_signal_connect(G_OBJECT(ih->handle), "output", G_CALLBACK(gtkTextSpinOutput), ih); if (!iupAttribGetBoolean(ih, "SPINAUTO")) { g_signal_connect(G_OBJECT(ih->handle), "input", G_CALLBACK(gtkTextSpinInput), ih); iupAttribSet(ih, "_IUPGTK_SPIN_NOAUTO", "1"); } } } /* add to the parent, all GTK controls must call this. */ iupgtkAddToParent(ih); if (!iupAttribGetBoolean(ih, "CANFOCUS")) iupgtkSetCanFocus(ih->handle, 0); g_signal_connect(G_OBJECT(ih->handle), "enter-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "leave-notify-event", G_CALLBACK(iupgtkEnterLeaveEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "focus-in-event", G_CALLBACK(iupgtkFocusInOutEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "focus-out-event", G_CALLBACK(iupgtkFocusInOutEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "key-press-event", G_CALLBACK(iupgtkKeyPressEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "show-help", G_CALLBACK(iupgtkShowHelp), ih); g_signal_connect_after(G_OBJECT(ih->handle), "move-cursor", G_CALLBACK(gtkTextMoveCursor), ih); /* only report some caret movements */ g_signal_connect_after(G_OBJECT(ih->handle), "key-release-event", G_CALLBACK(gtkTextKeyReleaseEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "button-press-event", G_CALLBACK(gtkTextButtonEvent), ih); /* if connected "after" then it is ignored */ g_signal_connect(G_OBJECT(ih->handle), "button-release-event",G_CALLBACK(gtkTextButtonEvent), ih); g_signal_connect(G_OBJECT(ih->handle), "motion-notify-event",G_CALLBACK(iupgtkMotionNotifyEvent), ih); if (ih->data->is_multiline) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(ih->handle)); g_signal_connect(G_OBJECT(buffer), "delete-range", G_CALLBACK(gtkTextBufferDeleteRange), ih); g_signal_connect(G_OBJECT(buffer), "insert-text", G_CALLBACK(gtkTextBufferInsertText), ih); g_signal_connect(G_OBJECT(buffer), "changed", G_CALLBACK(gtkTextChanged), ih); } else { g_signal_connect(G_OBJECT(ih->handle), "delete-text", G_CALLBACK(gtkTextEntryDeleteText), ih); g_signal_connect(G_OBJECT(ih->handle), "insert-text", G_CALLBACK(gtkTextEntryInsertText), ih); g_signal_connect(G_OBJECT(ih->handle), "changed", G_CALLBACK(gtkTextChanged), ih); } if (scrolled_window) gtk_widget_realize((GtkWidget*)scrolled_window); gtk_widget_realize(ih->handle); /* configure for DRAG&DROP */ if (IupGetCallback(ih, "DROPFILES_CB")) iupAttribSet(ih, "DROPFILESTARGET", "YES"); /* update a mnemonic in a label if necessary */ iupgtkUpdateMnemonic(ih); if (ih->data->formattags) iupTextUpdateFormatTags(ih); IupSetCallback(ih, "_IUP_XY2POS_CB", (Icallback)gtkTextConvertXYToPos); return IUP_NOERROR; } void iupdrvTextInitClass(Iclass* ic) { /* Driver Dependent Class functions */ ic->Map = gtkTextMapMethod; /* Driver Dependent Attribute functions */ /* Visual */ iupClassRegisterAttribute(ic, "BGCOLOR", NULL, gtkTextSetBgColorAttrib, IUPAF_SAMEASSYSTEM, "TXTBGCOLOR", IUPAF_DEFAULT); /* Special */ iupClassRegisterAttribute(ic, "FGCOLOR", NULL, iupdrvBaseSetFgColorAttrib, IUPAF_SAMEASSYSTEM, "TXTFGCOLOR", IUPAF_DEFAULT); /* IupText only */ iupClassRegisterAttribute(ic, "PADDING", iupTextGetPaddingAttrib, gtkTextSetPaddingAttrib, IUPAF_SAMEASSYSTEM, "0x0", IUPAF_NOT_MAPPED); iupClassRegisterAttribute(ic, "VALUE", gtkTextGetValueAttrib, gtkTextSetValueAttrib, NULL, NULL, IUPAF_NO_DEFAULTVALUE|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "LINEVALUE", gtkTextGetLineValueAttrib, NULL, NULL, NULL, IUPAF_READONLY|IUPAF_NO_DEFAULTVALUE|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SELECTEDTEXT", gtkTextGetSelectedTextAttrib, gtkTextSetSelectedTextAttrib, NULL, NULL, IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SELECTION", gtkTextGetSelectionAttrib, gtkTextSetSelectionAttrib, NULL, NULL, IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SELECTIONPOS", gtkTextGetSelectionPosAttrib, gtkTextSetSelectionPosAttrib, NULL, NULL, IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "CARET", gtkTextGetCaretAttrib, gtkTextSetCaretAttrib, NULL, NULL, IUPAF_NO_SAVE|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "CARETPOS", gtkTextGetCaretPosAttrib, gtkTextSetCaretPosAttrib, IUPAF_SAMEASSYSTEM, "0", IUPAF_NO_SAVE|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "INSERT", NULL, gtkTextSetInsertAttrib, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_WRITEONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "APPEND", NULL, gtkTextSetAppendAttrib, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_WRITEONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "READONLY", gtkTextGetReadOnlyAttrib, gtkTextSetReadOnlyAttrib, NULL, NULL, IUPAF_DEFAULT); iupClassRegisterAttribute(ic, "NC", iupTextGetNCAttrib, gtkTextSetNCAttrib, IUPAF_SAMEASSYSTEM, "0", IUPAF_NOT_MAPPED); iupClassRegisterAttribute(ic, "CLIPBOARD", NULL, gtkTextSetClipboardAttrib, NULL, NULL, IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SCROLLTO", NULL, gtkTextSetScrollToAttrib, NULL, NULL, IUPAF_WRITEONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SCROLLTOPOS", NULL, gtkTextSetScrollToPosAttrib, NULL, NULL, IUPAF_WRITEONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SPINMIN", NULL, gtkTextSetSpinMinAttrib, IUPAF_SAMEASSYSTEM, "0", IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SPINMAX", NULL, gtkTextSetSpinMaxAttrib, IUPAF_SAMEASSYSTEM, "100", IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SPININC", NULL, gtkTextSetSpinIncAttrib, IUPAF_SAMEASSYSTEM, "1", IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "SPINVALUE", gtkTextGetSpinValueAttrib, gtkTextSetSpinValueAttrib, IUPAF_SAMEASSYSTEM, "0", IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "COUNT", gtkTextGetCountAttrib, NULL, NULL, NULL, IUPAF_READONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "LINECOUNT", gtkTextGetLineCountAttrib, NULL, NULL, NULL, IUPAF_READONLY|IUPAF_NO_INHERIT); /* IupText Windows and GTK only */ iupClassRegisterAttribute(ic, "ADDFORMATTAG", NULL, iupTextSetAddFormatTagAttrib, NULL, NULL, IUPAF_IHANDLENAME|IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "ADDFORMATTAG_HANDLE", NULL, iupTextSetAddFormatTagHandleAttrib, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "ALIGNMENT", NULL, gtkTextSetAlignmentAttrib, IUPAF_SAMEASSYSTEM, "ALEFT", IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "FORMATTING", iupTextGetFormattingAttrib, iupTextSetFormattingAttrib, NULL, NULL, IUPAF_NOT_MAPPED|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "OVERWRITE", gtkTextGetOverwriteAttrib, gtkTextSetOverwriteAttrib, NULL, NULL, IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "REMOVEFORMATTING", NULL, gtkTextSetRemoveFormattingAttrib, NULL, NULL, IUPAF_WRITEONLY|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "TABSIZE", NULL, gtkTextSetTabSizeAttrib, "8", NULL, IUPAF_DEFAULT); /* force new default value */ iupClassRegisterAttribute(ic, "PASSWORD", NULL, NULL, NULL, NULL, IUPAF_NO_INHERIT); /* Not Supported */ iupClassRegisterAttribute(ic, "CUEBANNER", NULL, NULL, NULL, NULL, IUPAF_NOT_SUPPORTED|IUPAF_NO_INHERIT); iupClassRegisterAttribute(ic, "FILTER", NULL, NULL, NULL, NULL, IUPAF_NOT_SUPPORTED|IUPAF_NO_INHERIT); }
141858.c
/* * phy-da8xx-usb - TI DaVinci DA8xx USB PHY driver * * Copyright (C) 2016 David Lechner <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * 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/clk.h> #include <linux/io.h> #include <linux/of.h> #include <linux/mfd/da8xx-cfgchip.h> #include <linux/mfd/syscon.h> #include <linux/module.h> #include <linux/phy/phy.h> #include <linux/platform_device.h> #include <linux/regmap.h> struct da8xx_usb_phy { struct phy_provider *phy_provider; struct phy *usb11_phy; struct phy *usb20_phy; struct clk *usb11_clk; struct clk *usb20_clk; struct regmap *regmap; }; static int da8xx_usb11_phy_power_on(struct phy *phy) { struct da8xx_usb_phy *d_phy = phy_get_drvdata(phy); int ret; ret = clk_prepare_enable(d_phy->usb11_clk); if (ret) return ret; regmap_write_bits(d_phy->regmap, CFGCHIP(2), CFGCHIP2_USB1SUSPENDM, CFGCHIP2_USB1SUSPENDM); return 0; } static int da8xx_usb11_phy_power_off(struct phy *phy) { struct da8xx_usb_phy *d_phy = phy_get_drvdata(phy); regmap_write_bits(d_phy->regmap, CFGCHIP(2), CFGCHIP2_USB1SUSPENDM, 0); clk_disable_unprepare(d_phy->usb11_clk); return 0; } static const struct phy_ops da8xx_usb11_phy_ops = { .power_on = da8xx_usb11_phy_power_on, .power_off = da8xx_usb11_phy_power_off, .owner = THIS_MODULE, }; static int da8xx_usb20_phy_power_on(struct phy *phy) { struct da8xx_usb_phy *d_phy = phy_get_drvdata(phy); int ret; ret = clk_prepare_enable(d_phy->usb20_clk); if (ret) return ret; regmap_write_bits(d_phy->regmap, CFGCHIP(2), CFGCHIP2_OTGPWRDN, 0); return 0; } static int da8xx_usb20_phy_power_off(struct phy *phy) { struct da8xx_usb_phy *d_phy = phy_get_drvdata(phy); regmap_write_bits(d_phy->regmap, CFGCHIP(2), CFGCHIP2_OTGPWRDN, CFGCHIP2_OTGPWRDN); clk_disable_unprepare(d_phy->usb20_clk); return 0; } static int da8xx_usb20_phy_set_mode(struct phy *phy, enum phy_mode mode) { struct da8xx_usb_phy *d_phy = phy_get_drvdata(phy); u32 val; switch (mode) { case PHY_MODE_USB_HOST: /* Force VBUS valid, ID = 0 */ val = CFGCHIP2_OTGMODE_FORCE_HOST; break; case PHY_MODE_USB_DEVICE: /* Force VBUS valid, ID = 1 */ val = CFGCHIP2_OTGMODE_FORCE_DEVICE; break; case PHY_MODE_USB_OTG: /* Don't override the VBUS/ID comparators */ val = CFGCHIP2_OTGMODE_NO_OVERRIDE; break; default: return -EINVAL; } regmap_write_bits(d_phy->regmap, CFGCHIP(2), CFGCHIP2_OTGMODE_MASK, val); return 0; } static const struct phy_ops da8xx_usb20_phy_ops = { .power_on = da8xx_usb20_phy_power_on, .power_off = da8xx_usb20_phy_power_off, .set_mode = da8xx_usb20_phy_set_mode, .owner = THIS_MODULE, }; static struct phy *da8xx_usb_phy_of_xlate(struct device *dev, struct of_phandle_args *args) { struct da8xx_usb_phy *d_phy = dev_get_drvdata(dev); if (!d_phy) return ERR_PTR(-ENODEV); switch (args->args[0]) { case 0: return d_phy->usb20_phy; case 1: return d_phy->usb11_phy; default: return ERR_PTR(-EINVAL); } } static int da8xx_usb_phy_probe(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct device_node *node = dev->of_node; struct da8xx_usb_phy *d_phy; d_phy = devm_kzalloc(dev, sizeof(*d_phy), GFP_KERNEL); if (!d_phy) return -ENOMEM; if (node) d_phy->regmap = syscon_regmap_lookup_by_compatible( "ti,da830-cfgchip"); else d_phy->regmap = syscon_regmap_lookup_by_pdevname("syscon"); if (IS_ERR(d_phy->regmap)) { dev_err(dev, "Failed to get syscon\n"); return PTR_ERR(d_phy->regmap); } d_phy->usb11_clk = devm_clk_get(dev, "usb11_phy"); if (IS_ERR(d_phy->usb11_clk)) { dev_err(dev, "Failed to get usb11_phy clock\n"); return PTR_ERR(d_phy->usb11_clk); } d_phy->usb20_clk = devm_clk_get(dev, "usb20_phy"); if (IS_ERR(d_phy->usb20_clk)) { dev_err(dev, "Failed to get usb20_phy clock\n"); return PTR_ERR(d_phy->usb20_clk); } d_phy->usb11_phy = devm_phy_create(dev, node, &da8xx_usb11_phy_ops); if (IS_ERR(d_phy->usb11_phy)) { dev_err(dev, "Failed to create usb11 phy\n"); return PTR_ERR(d_phy->usb11_phy); } d_phy->usb20_phy = devm_phy_create(dev, node, &da8xx_usb20_phy_ops); if (IS_ERR(d_phy->usb20_phy)) { dev_err(dev, "Failed to create usb20 phy\n"); return PTR_ERR(d_phy->usb20_phy); } platform_set_drvdata(pdev, d_phy); phy_set_drvdata(d_phy->usb11_phy, d_phy); phy_set_drvdata(d_phy->usb20_phy, d_phy); if (node) { d_phy->phy_provider = devm_of_phy_provider_register(dev, da8xx_usb_phy_of_xlate); if (IS_ERR(d_phy->phy_provider)) { dev_err(dev, "Failed to create phy provider\n"); return PTR_ERR(d_phy->phy_provider); } } else { int ret; ret = phy_create_lookup(d_phy->usb11_phy, "usb-phy", "ohci-da8xx"); if (ret) dev_warn(dev, "Failed to create usb11 phy lookup\n"); ret = phy_create_lookup(d_phy->usb20_phy, "usb-phy", "musb-da8xx"); if (ret) dev_warn(dev, "Failed to create usb20 phy lookup\n"); } return 0; } static int da8xx_usb_phy_remove(struct platform_device *pdev) { struct da8xx_usb_phy *d_phy = platform_get_drvdata(pdev); if (!pdev->dev.of_node) { phy_remove_lookup(d_phy->usb20_phy, "usb-phy", "musb-da8xx"); phy_remove_lookup(d_phy->usb11_phy, "usb-phy", "ohci-da8xx"); } return 0; } static const struct of_device_id da8xx_usb_phy_ids[] = { { .compatible = "ti,da830-usb-phy" }, { } }; MODULE_DEVICE_TABLE(of, da8xx_usb_phy_ids); static struct platform_driver da8xx_usb_phy_driver = { .probe = da8xx_usb_phy_probe, .remove = da8xx_usb_phy_remove, .driver = { .name = "da8xx-usb-phy", .of_match_table = da8xx_usb_phy_ids, }, }; module_platform_driver(da8xx_usb_phy_driver); MODULE_ALIAS("platform:da8xx-usb-phy"); MODULE_AUTHOR("David Lechner <[email protected]>"); MODULE_DESCRIPTION("TI DA8xx USB PHY driver"); MODULE_LICENSE("GPL v2");
760860.c
/* * PCI Express Hot Plug Controller Driver * * Copyright (C) 1995,2001 Compaq Computer Corporation * Copyright (C) 2001 Greg Kroah-Hartman ([email protected]) * Copyright (C) 2001 IBM Corp. * Copyright (C) 2003-2004 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, GOOD TITLE or * NON INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * Send feedback to <[email protected]>, <[email protected]> * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/pci.h> #include "../pci.h" #include "pciehp.h" static void interrupt_event_handler(struct work_struct *work); void pciehp_queue_interrupt_event(struct slot *p_slot, u32 event_type) { struct event_info *info; info = kmalloc(sizeof(*info), GFP_ATOMIC); if (!info) { ctrl_err(p_slot->ctrl, "dropped event %d (ENOMEM)\n", event_type); return; } INIT_WORK(&info->work, interrupt_event_handler); info->event_type = event_type; info->p_slot = p_slot; queue_work(p_slot->wq, &info->work); } /* The following routines constitute the bulk of the hotplug controller logic */ static void set_slot_off(struct controller *ctrl, struct slot *pslot) { /* turn off slot, turn on Amber LED, turn off Green LED if supported*/ if (POWER_CTRL(ctrl)) { pciehp_power_off_slot(pslot); /* * After turning power off, we must wait for at least 1 second * before taking any action that relies on power having been * removed from the slot/adapter. */ msleep(1000); } pciehp_green_led_off(pslot); pciehp_set_attention_status(pslot, 1); } /** * board_added - Called after a board has been added to the system. * @p_slot: &slot where board is added * * Turns power on for the board. * Configures board. */ static int board_added(struct slot *p_slot) { int retval = 0; struct controller *ctrl = p_slot->ctrl; struct pci_bus *parent = ctrl->pcie->port->subordinate; if (POWER_CTRL(ctrl)) { /* Power on slot */ retval = pciehp_power_on_slot(p_slot); if (retval) return retval; } pciehp_green_led_blink(p_slot); /* Check link training status */ retval = pciehp_check_link_status(ctrl); if (retval) { ctrl_err(ctrl, "Failed to check link status\n"); goto err_exit; } /* Check for a power fault */ if (ctrl->power_fault_detected || pciehp_query_power_fault(p_slot)) { ctrl_err(ctrl, "Slot(%s): Power fault\n", slot_name(p_slot)); retval = -EIO; goto err_exit; } retval = pciehp_configure_device(p_slot); if (retval) { ctrl_err(ctrl, "Cannot add device at %04x:%02x:00\n", pci_domain_nr(parent), parent->number); if (retval != -EEXIST) goto err_exit; } pciehp_green_led_on(p_slot); pciehp_set_attention_status(p_slot, 0); return 0; err_exit: set_slot_off(ctrl, p_slot); return retval; } /** * remove_board - Turns off slot and LEDs * @p_slot: slot where board is being removed */ static int remove_board(struct slot *p_slot) { int retval; struct controller *ctrl = p_slot->ctrl; retval = pciehp_unconfigure_device(p_slot); if (retval) return retval; if (POWER_CTRL(ctrl)) { pciehp_power_off_slot(p_slot); /* * After turning power off, we must wait for at least 1 second * before taking any action that relies on power having been * removed from the slot/adapter. */ msleep(1000); } /* turn off Green LED */ pciehp_green_led_off(p_slot); return 0; } struct power_work_info { struct slot *p_slot; struct work_struct work; unsigned int req; #define DISABLE_REQ 0 #define ENABLE_REQ 1 }; /** * pciehp_power_thread - handle pushbutton events * @work: &struct work_struct describing work to be done * * Scheduled procedure to handle blocking stuff for the pushbuttons. * Handles all pending events and exits. */ static void pciehp_power_thread(struct work_struct *work) { struct power_work_info *info = container_of(work, struct power_work_info, work); struct slot *p_slot = info->p_slot; int ret; switch (info->req) { case DISABLE_REQ: mutex_lock(&p_slot->hotplug_lock); pciehp_disable_slot(p_slot); mutex_unlock(&p_slot->hotplug_lock); mutex_lock(&p_slot->lock); p_slot->state = STATIC_STATE; mutex_unlock(&p_slot->lock); break; case ENABLE_REQ: mutex_lock(&p_slot->hotplug_lock); ret = pciehp_enable_slot(p_slot); mutex_unlock(&p_slot->hotplug_lock); if (ret) pciehp_green_led_off(p_slot); mutex_lock(&p_slot->lock); p_slot->state = STATIC_STATE; mutex_unlock(&p_slot->lock); break; default: break; } kfree(info); } static void pciehp_queue_power_work(struct slot *p_slot, int req) { struct power_work_info *info; p_slot->state = (req == ENABLE_REQ) ? POWERON_STATE : POWEROFF_STATE; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) { ctrl_err(p_slot->ctrl, "no memory to queue %s request\n", (req == ENABLE_REQ) ? "poweron" : "poweroff"); return; } info->p_slot = p_slot; INIT_WORK(&info->work, pciehp_power_thread); info->req = req; queue_work(p_slot->wq, &info->work); } void pciehp_queue_pushbutton_work(struct work_struct *work) { struct slot *p_slot = container_of(work, struct slot, work.work); mutex_lock(&p_slot->lock); switch (p_slot->state) { case BLINKINGOFF_STATE: pciehp_queue_power_work(p_slot, DISABLE_REQ); break; case BLINKINGON_STATE: pciehp_queue_power_work(p_slot, ENABLE_REQ); break; default: break; } mutex_unlock(&p_slot->lock); } /* * Note: This function must be called with slot->lock held */ static void handle_button_press_event(struct slot *p_slot) { struct controller *ctrl = p_slot->ctrl; u8 getstatus; switch (p_slot->state) { case STATIC_STATE: pciehp_get_power_status(p_slot, &getstatus); if (getstatus) { p_slot->state = BLINKINGOFF_STATE; ctrl_info(ctrl, "Slot(%s): Powering off due to button press\n", slot_name(p_slot)); } else { p_slot->state = BLINKINGON_STATE; ctrl_info(ctrl, "Slot(%s) Powering on due to button press\n", slot_name(p_slot)); } /* blink green LED and turn off amber */ pciehp_green_led_blink(p_slot); pciehp_set_attention_status(p_slot, 0); queue_delayed_work(p_slot->wq, &p_slot->work, 5*HZ); break; case BLINKINGOFF_STATE: case BLINKINGON_STATE: /* * Cancel if we are still blinking; this means that we * press the attention again before the 5 sec. limit * expires to cancel hot-add or hot-remove */ ctrl_info(ctrl, "Slot(%s): Button cancel\n", slot_name(p_slot)); cancel_delayed_work(&p_slot->work); if (p_slot->state == BLINKINGOFF_STATE) pciehp_green_led_on(p_slot); else pciehp_green_led_off(p_slot); pciehp_set_attention_status(p_slot, 0); ctrl_info(ctrl, "Slot(%s): Action canceled due to button press\n", slot_name(p_slot)); p_slot->state = STATIC_STATE; break; case POWEROFF_STATE: case POWERON_STATE: /* * Ignore if the slot is on power-on or power-off state; * this means that the previous attention button action * to hot-add or hot-remove is undergoing */ ctrl_info(ctrl, "Slot(%s): Button ignored\n", slot_name(p_slot)); break; default: ctrl_err(ctrl, "Slot(%s): Ignoring invalid state %#x\n", slot_name(p_slot), p_slot->state); break; } } /* * Note: This function must be called with slot->lock held */ static void handle_link_event(struct slot *p_slot, u32 event) { struct controller *ctrl = p_slot->ctrl; switch (p_slot->state) { case BLINKINGON_STATE: case BLINKINGOFF_STATE: cancel_delayed_work(&p_slot->work); /* Fall through */ case STATIC_STATE: pciehp_queue_power_work(p_slot, event == INT_LINK_UP ? ENABLE_REQ : DISABLE_REQ); break; case POWERON_STATE: if (event == INT_LINK_UP) { ctrl_info(ctrl, "Slot(%s): Link Up event ignored; already powering on\n", slot_name(p_slot)); } else { ctrl_info(ctrl, "Slot(%s): Link Down event queued; currently getting powered on\n", slot_name(p_slot)); pciehp_queue_power_work(p_slot, DISABLE_REQ); } break; case POWEROFF_STATE: if (event == INT_LINK_UP) { ctrl_info(ctrl, "Slot(%s): Link Up event queued; currently getting powered off\n", slot_name(p_slot)); pciehp_queue_power_work(p_slot, ENABLE_REQ); } else { ctrl_info(ctrl, "Slot(%s): Link Down event ignored; already powering off\n", slot_name(p_slot)); } break; default: ctrl_err(ctrl, "Slot(%s): Ignoring invalid state %#x\n", slot_name(p_slot), p_slot->state); break; } } static void interrupt_event_handler(struct work_struct *work) { struct event_info *info = container_of(work, struct event_info, work); struct slot *p_slot = info->p_slot; struct controller *ctrl = p_slot->ctrl; mutex_lock(&p_slot->lock); switch (info->event_type) { case INT_BUTTON_PRESS: handle_button_press_event(p_slot); break; case INT_POWER_FAULT: if (!POWER_CTRL(ctrl)) break; pciehp_set_attention_status(p_slot, 1); pciehp_green_led_off(p_slot); break; case INT_PRESENCE_ON: pciehp_queue_power_work(p_slot, ENABLE_REQ); break; case INT_PRESENCE_OFF: /* * Regardless of surprise capability, we need to * definitely remove a card that has been pulled out! */ pciehp_queue_power_work(p_slot, DISABLE_REQ); break; case INT_LINK_UP: case INT_LINK_DOWN: handle_link_event(p_slot, info->event_type); break; default: break; } mutex_unlock(&p_slot->lock); kfree(info); } /* * Note: This function must be called with slot->hotplug_lock held */ int pciehp_enable_slot(struct slot *p_slot) { u8 getstatus = 0; struct controller *ctrl = p_slot->ctrl; pciehp_get_adapter_status(p_slot, &getstatus); if (!getstatus) { ctrl_info(ctrl, "Slot(%s): No adapter\n", slot_name(p_slot)); return -ENODEV; } if (MRL_SENS(p_slot->ctrl)) { pciehp_get_latch_status(p_slot, &getstatus); if (getstatus) { ctrl_info(ctrl, "Slot(%s): Latch open\n", slot_name(p_slot)); return -ENODEV; } } if (POWER_CTRL(p_slot->ctrl)) { pciehp_get_power_status(p_slot, &getstatus); if (getstatus) { ctrl_info(ctrl, "Slot(%s): Already enabled\n", slot_name(p_slot)); return 0; } } return board_added(p_slot); } /* * Note: This function must be called with slot->hotplug_lock held */ int pciehp_disable_slot(struct slot *p_slot) { u8 getstatus = 0; struct controller *ctrl = p_slot->ctrl; if (!p_slot->ctrl) return 1; if (POWER_CTRL(p_slot->ctrl)) { pciehp_get_power_status(p_slot, &getstatus); if (!getstatus) { ctrl_info(ctrl, "Slot(%s): Already disabled\n", slot_name(p_slot)); return -EINVAL; } } return remove_board(p_slot); } int pciehp_sysfs_enable_slot(struct slot *p_slot) { int retval = -ENODEV; struct controller *ctrl = p_slot->ctrl; mutex_lock(&p_slot->lock); switch (p_slot->state) { case BLINKINGON_STATE: cancel_delayed_work(&p_slot->work); case STATIC_STATE: p_slot->state = POWERON_STATE; mutex_unlock(&p_slot->lock); mutex_lock(&p_slot->hotplug_lock); retval = pciehp_enable_slot(p_slot); mutex_unlock(&p_slot->hotplug_lock); mutex_lock(&p_slot->lock); p_slot->state = STATIC_STATE; break; case POWERON_STATE: ctrl_info(ctrl, "Slot(%s): Already in powering on state\n", slot_name(p_slot)); break; case BLINKINGOFF_STATE: case POWEROFF_STATE: ctrl_info(ctrl, "Slot(%s): Already enabled\n", slot_name(p_slot)); break; default: ctrl_err(ctrl, "Slot(%s): Invalid state %#x\n", slot_name(p_slot), p_slot->state); break; } mutex_unlock(&p_slot->lock); return retval; } int pciehp_sysfs_disable_slot(struct slot *p_slot) { int retval = -ENODEV; struct controller *ctrl = p_slot->ctrl; mutex_lock(&p_slot->lock); switch (p_slot->state) { case BLINKINGOFF_STATE: cancel_delayed_work(&p_slot->work); case STATIC_STATE: p_slot->state = POWEROFF_STATE; mutex_unlock(&p_slot->lock); mutex_lock(&p_slot->hotplug_lock); retval = pciehp_disable_slot(p_slot); mutex_unlock(&p_slot->hotplug_lock); mutex_lock(&p_slot->lock); p_slot->state = STATIC_STATE; break; case POWEROFF_STATE: ctrl_info(ctrl, "Slot(%s): Already in powering off state\n", slot_name(p_slot)); break; case BLINKINGON_STATE: case POWERON_STATE: ctrl_info(ctrl, "Slot(%s): Already disabled\n", slot_name(p_slot)); break; default: ctrl_err(ctrl, "Slot(%s): Invalid state %#x\n", slot_name(p_slot), p_slot->state); break; } mutex_unlock(&p_slot->lock); return retval; }
854884.c
/* Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "header.h" int ia[128] ALIGNED16; int A[128][128]; int B[128][128]; __attribute__((noinline)) void example13(int A[][128], int B[][128], int *out) { int i,j; for (i = 0; i < 128; i++) { int mul = 0; for (j = 0; j < 128; j+=8) { mul += (A[i][j] *B[i][j]); } out[i] = mul; } } int main(int argc,char* argv[]){ init_memory(&ia[0], &ia[128]); init_memory(&A[0][0], &A[0][128]); init_memory(&B[0][0],&B[0][128]); BENCH("Example13", example13(A,B,ia), 131072, digest_memory(&ia[0], &ia[128])); return 0; }
351642.c
/*=== top: 12 index 0: length 0 index 1: length 0 index 2: length 0 index 3: length 0 index 4: length 0 index 5: length 0 index 6: length 0 index 7: length 0 index 8: length 0 index 9: length 1024, ptr-is-NULL 0 index 10: length 0 index 11: length 2048, ptr-is-NULL 0 ===*/ void test(duk_context *ctx) { duk_idx_t i, n; duk_push_undefined(ctx); duk_push_null(ctx); duk_push_true(ctx); duk_push_false(ctx); duk_push_string(ctx, ""); duk_push_string(ctx, "foo"); duk_push_int(ctx, 123); duk_push_object(ctx); duk_push_fixed_buffer(ctx, 0); duk_push_fixed_buffer(ctx, 1024); duk_push_dynamic_buffer(ctx, 0); duk_push_dynamic_buffer(ctx, 2048); n = duk_get_top(ctx); printf("top: %ld\n", (long) n); for (i = 0; i < n; i++) { void *buf; duk_size_t len; len = (duk_size_t) 0xdeadbeef; buf = duk_get_buffer(ctx, i, &len); if (len == 0) { /* avoid printing 'buf' if len is zero, as it is not predictable */ printf("index %ld: length 0\n", (long) i); } else { printf("index %ld: length %lu, ptr-is-NULL %d\n", (long) i, (unsigned long) len, (buf == NULL ? 1 : 0)); } } }
376104.c
/* * Ioctl handler * Linux ethernet bridge * * Authors: * Lennert Buytenhek <[email protected]> * * $Id: br_ioctl.c,v 1.4 2000/11/08 05:16:40 davem Exp $ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/capability.h> #include <linux/kernel.h> #include <linux/if_bridge.h> #include <linux/netdevice.h> #include <linux/times.h> #include <asm/uaccess.h> #include "br_private.h" /* called with RTNL */ static int get_bridge_ifindices(int *indices, int num) { struct net_device *dev; int i = 0; for_each_netdev(dev) { if (i >= num) break; if (dev->priv_flags & IFF_EBRIDGE) indices[i++] = dev->ifindex; } return i; } /* called with RTNL */ static void get_port_ifindices(struct net_bridge *br, int *ifindices, int num) { struct net_bridge_port *p; list_for_each_entry(p, &br->port_list, list) { if (p->port_no < num) ifindices[p->port_no] = p->dev->ifindex; } } /* * Format up to a page worth of forwarding table entries * userbuf -- where to copy result * maxnum -- maximum number of entries desired * (limited to a page for sanity) * offset -- number of records to skip */ static int get_fdb_entries(struct net_bridge *br, void __user *userbuf, unsigned long maxnum, unsigned long offset) { int num; void *buf; size_t size; /* Clamp size to PAGE_SIZE, test maxnum to avoid overflow */ if (maxnum > PAGE_SIZE/sizeof(struct __fdb_entry)) maxnum = PAGE_SIZE/sizeof(struct __fdb_entry); size = maxnum * sizeof(struct __fdb_entry); buf = kmalloc(size, GFP_USER); if (!buf) return -ENOMEM; num = br_fdb_fillbuf(br, buf, maxnum, offset); if (num > 0) { if (copy_to_user(userbuf, buf, num*sizeof(struct __fdb_entry))) num = -EFAULT; } kfree(buf); return num; } static int add_del_if(struct net_bridge *br, int ifindex, int isadd) { struct net_device *dev; int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; dev = dev_get_by_index(ifindex); if (dev == NULL) return -EINVAL; if (isadd) ret = br_add_if(br, dev); else ret = br_del_if(br, dev); dev_put(dev); return ret; } /* * Legacy ioctl's through SIOCDEVPRIVATE * This interface is deprecated because it was too difficult to * to do the translation for 32/64bit ioctl compatability. */ static int old_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); unsigned long args[4]; if (copy_from_user(args, rq->ifr_data, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_ADD_IF: case BRCTL_DEL_IF: return add_del_if(br, args[1], args[0] == BRCTL_ADD_IF); case BRCTL_GET_BRIDGE_INFO: { struct __bridge_info b; memset(&b, 0, sizeof(struct __bridge_info)); rcu_read_lock(); memcpy(&b.designated_root, &br->designated_root, 8); memcpy(&b.bridge_id, &br->bridge_id, 8); b.root_path_cost = br->root_path_cost; b.max_age = jiffies_to_clock_t(br->max_age); b.hello_time = jiffies_to_clock_t(br->hello_time); b.forward_delay = br->forward_delay; b.bridge_max_age = br->bridge_max_age; b.bridge_hello_time = br->bridge_hello_time; b.bridge_forward_delay = jiffies_to_clock_t(br->bridge_forward_delay); b.topology_change = br->topology_change; b.topology_change_detected = br->topology_change_detected; b.root_port = br->root_port; b.stp_enabled = (br->stp_enabled != BR_NO_STP); b.ageing_time = jiffies_to_clock_t(br->ageing_time); b.hello_timer_value = br_timer_value(&br->hello_timer); b.tcn_timer_value = br_timer_value(&br->tcn_timer); b.topology_change_timer_value = br_timer_value(&br->topology_change_timer); b.gc_timer_value = br_timer_value(&br->gc_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &b, sizeof(b))) return -EFAULT; return 0; } case BRCTL_GET_PORT_LIST: { int num, *indices; num = args[2]; if (num < 0) return -EINVAL; if (num == 0) num = 256; if (num > BR_MAX_PORTS) num = BR_MAX_PORTS; indices = kcalloc(num, sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; get_port_ifindices(br, indices, num); if (copy_to_user((void __user *)args[1], indices, num*sizeof(int))) num = -EFAULT; kfree(indices); return num; } case BRCTL_SET_BRIDGE_FORWARD_DELAY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_forward_delay = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->forward_delay = br->bridge_forward_delay; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_BRIDGE_HELLO_TIME: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_hello_time = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->hello_time = br->bridge_hello_time; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_BRIDGE_MAX_AGE: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br->bridge_max_age = clock_t_to_jiffies(args[1]); if (br_is_root_bridge(br)) br->max_age = br->bridge_max_age; spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_AGEING_TIME: if (!capable(CAP_NET_ADMIN)) return -EPERM; br->ageing_time = clock_t_to_jiffies(args[1]); return 0; case BRCTL_GET_PORT_INFO: { struct __port_info p; struct net_bridge_port *pt; rcu_read_lock(); if ((pt = br_get_port(br, args[2])) == NULL) { rcu_read_unlock(); return -EINVAL; } memset(&p, 0, sizeof(struct __port_info)); memcpy(&p.designated_root, &pt->designated_root, 8); memcpy(&p.designated_bridge, &pt->designated_bridge, 8); p.port_id = pt->port_id; p.designated_port = pt->designated_port; p.path_cost = pt->path_cost; p.designated_cost = pt->designated_cost; p.state = pt->state; p.top_change_ack = pt->topology_change_ack; p.config_pending = pt->config_pending; p.message_age_timer_value = br_timer_value(&pt->message_age_timer); p.forward_delay_timer_value = br_timer_value(&pt->forward_delay_timer); p.hold_timer_value = br_timer_value(&pt->hold_timer); rcu_read_unlock(); if (copy_to_user((void __user *)args[1], &p, sizeof(p))) return -EFAULT; return 0; } case BRCTL_SET_BRIDGE_STP_STATE: if (!capable(CAP_NET_ADMIN)) return -EPERM; br_stp_set_enabled(br, args[1]); return 0; case BRCTL_SET_BRIDGE_PRIORITY: if (!capable(CAP_NET_ADMIN)) return -EPERM; spin_lock_bh(&br->lock); br_stp_set_bridge_priority(br, args[1]); spin_unlock_bh(&br->lock); return 0; case BRCTL_SET_PORT_PRIORITY: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (args[2] >= (1<<(16-BR_PORT_BITS))) return -ERANGE; spin_lock_bh(&br->lock); if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_port_priority(p, args[2]); spin_unlock_bh(&br->lock); return ret; } case BRCTL_SET_PATH_COST: { struct net_bridge_port *p; int ret = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((p = br_get_port(br, args[1])) == NULL) ret = -EINVAL; else br_stp_set_path_cost(p, args[2]); return ret; } case BRCTL_GET_FDB_ENTRIES: return get_fdb_entries(br, (void __user *)args[1], args[2], args[3]); } return -EOPNOTSUPP; } static int old_deviceless(void __user *uarg) { unsigned long args[3]; if (copy_from_user(args, uarg, sizeof(args))) return -EFAULT; switch (args[0]) { case BRCTL_GET_VERSION: return BRCTL_VERSION; case BRCTL_GET_BRIDGES: { int *indices; int ret = 0; if (args[2] >= 2048) return -ENOMEM; indices = kcalloc(args[2], sizeof(int), GFP_KERNEL); if (indices == NULL) return -ENOMEM; args[2] = get_bridge_ifindices(indices, args[2]); ret = copy_to_user((void __user *)args[1], indices, args[2]*sizeof(int)) ? -EFAULT : args[2]; kfree(indices); return ret; } case BRCTL_ADD_BRIDGE: case BRCTL_DEL_BRIDGE: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, (void __user *)args[1], IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (args[0] == BRCTL_ADD_BRIDGE) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int br_ioctl_deviceless_stub(unsigned int cmd, void __user *uarg) { switch (cmd) { case SIOCGIFBR: case SIOCSIFBR: return old_deviceless(uarg); case SIOCBRADDBR: case SIOCBRDELBR: { char buf[IFNAMSIZ]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(buf, uarg, IFNAMSIZ)) return -EFAULT; buf[IFNAMSIZ-1] = 0; if (cmd == SIOCBRADDBR) return br_add_bridge(buf); return br_del_bridge(buf); } } return -EOPNOTSUPP; } int br_dev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct net_bridge *br = netdev_priv(dev); switch(cmd) { case SIOCDEVPRIVATE: return old_dev_ioctl(dev, rq, cmd); case SIOCBRADDIF: case SIOCBRDELIF: return add_del_if(br, rq->ifr_ifindex, cmd == SIOCBRADDIF); } pr_debug("Bridge does not support ioctl 0x%x\n", cmd); return -EOPNOTSUPP; }
437883.c
/* * Copyright 2009-2010 Pengutronix * Uwe Kleine-Koenig <[email protected]> * * loosely based on an earlier driver that has * Copyright 2009 Pengutronix, Sascha Hauer <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. */ #include <linux/slab.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/mutex.h> #include <linux/interrupt.h> #include <linux/mfd/core.h> #include <linux/mfd/mc13xxx.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_gpio.h> #include <linux/err.h> #include <linux/spi/spi.h> #include "mc13xxx.h" static const struct spi_device_id mc13xxx_device_id[] = { { .name = "mc13783", .driver_data = (kernel_ulong_t)&mc13xxx_variant_mc13783, }, { .name = "mc13892", .driver_data = (kernel_ulong_t)&mc13xxx_variant_mc13892, }, { .name = "mc34708", .driver_data = (kernel_ulong_t)&mc13xxx_variant_mc34708, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(spi, mc13xxx_device_id); static const struct of_device_id mc13xxx_dt_ids[] = { { .compatible = "fsl,mc13783", .data = &mc13xxx_variant_mc13783, }, { .compatible = "fsl,mc13892", .data = &mc13xxx_variant_mc13892, }, { .compatible = "fsl,mc34708", .data = &mc13xxx_variant_mc34708, }, { /* sentinel */ } }; MODULE_DEVICE_TABLE(of, mc13xxx_dt_ids); static struct regmap_config mc13xxx_regmap_spi_config = { .reg_bits = 7, .pad_bits = 1, .val_bits = 24, .write_flag_mask = 0x80, .max_register = MC13XXX_NUMREGS, .cache_type = REGCACHE_NONE, .use_single_rw = 1, }; static int mc13xxx_spi_read(void *context, const void *reg, size_t reg_size, void *val, size_t val_size) { unsigned char w[4] = { *((unsigned char *) reg), 0, 0, 0}; unsigned char r[4]; unsigned char *p = val; struct device *dev = context; struct spi_device *spi = to_spi_device(dev); struct spi_transfer t = { .tx_buf = w, .rx_buf = r, .len = 4, }; struct spi_message m; int ret; if (val_size != 3 || reg_size != 1) return -ENOTSUPP; spi_message_init(&m); spi_message_add_tail(&t, &m); ret = spi_sync(spi, &m); memcpy(p, &r[1], 3); return ret; } static int mc13xxx_spi_write(void *context, const void *data, size_t count) { struct device *dev = context; struct spi_device *spi = to_spi_device(dev); const char *reg = data; if (count != 4) return -ENOTSUPP; /* include errata fix for spi audio problems */ if (*reg == MC13783_AUDIO_CODEC || *reg == MC13783_AUDIO_DAC) spi_write(spi, data, count); return spi_write(spi, data, count); } /* * We cannot use regmap-spi generic bus implementation here. * The MC13783 chip will get corrupted if CS signal is deasserted * and on i.Mx31 SoC (the target SoC for MC13783 PMIC) the SPI controller * has the following errata (DSPhl22960): * "The CSPI negates SS when the FIFO becomes empty with * SSCTL= 0. Software cannot guarantee that the FIFO will not * drain because of higher priority interrupts and the * non-realtime characteristics of the operating system. As a * result, the SS will negate before all of the data has been * transferred to/from the peripheral." * We workaround this by accessing the SPI controller with a * single transfert. */ static struct regmap_bus regmap_mc13xxx_bus = { .write = mc13xxx_spi_write, .read = mc13xxx_spi_read, }; static int mc13xxx_spi_probe(struct spi_device *spi) { struct mc13xxx *mc13xxx; struct mc13xxx_platform_data *pdata = dev_get_platdata(&spi->dev); int ret; mc13xxx = devm_kzalloc(&spi->dev, sizeof(*mc13xxx), GFP_KERNEL); if (!mc13xxx) return -ENOMEM; spi_set_drvdata(spi, mc13xxx); spi->mode = SPI_MODE_0 | SPI_CS_HIGH; mc13xxx->dev = &spi->dev; mutex_init(&mc13xxx->lock); mc13xxx->regmap = devm_regmap_init(&spi->dev, &regmap_mc13xxx_bus, &spi->dev, &mc13xxx_regmap_spi_config); if (IS_ERR(mc13xxx->regmap)) { ret = PTR_ERR(mc13xxx->regmap); dev_err(mc13xxx->dev, "Failed to initialize register map: %d\n", ret); spi_set_drvdata(spi, NULL); return ret; } if (spi->dev.of_node) { const struct of_device_id *of_id = of_match_device(mc13xxx_dt_ids, &spi->dev); mc13xxx->variant = of_id->data; } else { const struct spi_device_id *id_entry = spi_get_device_id(spi); mc13xxx->variant = (void *)id_entry->driver_data; } return mc13xxx_common_init(mc13xxx, pdata, spi->irq); } static int mc13xxx_spi_remove(struct spi_device *spi) { struct mc13xxx *mc13xxx = spi_get_drvdata(spi); mc13xxx_common_cleanup(mc13xxx); return 0; } static struct spi_driver mc13xxx_spi_driver = { .id_table = mc13xxx_device_id, .driver = { .name = "mc13xxx", .owner = THIS_MODULE, .of_match_table = mc13xxx_dt_ids, }, .probe = mc13xxx_spi_probe, .remove = mc13xxx_spi_remove, }; static int __init mc13xxx_init(void) { return spi_register_driver(&mc13xxx_spi_driver); } subsys_initcall(mc13xxx_init); static void __exit mc13xxx_exit(void) { spi_unregister_driver(&mc13xxx_spi_driver); } module_exit(mc13xxx_exit); MODULE_DESCRIPTION("Core driver for Freescale MC13XXX PMIC"); MODULE_AUTHOR("Uwe Kleine-Koenig <[email protected]>"); MODULE_LICENSE("GPL v2");
136356.c
/*============================================================ ** ** Source: test.c ** ** Purpose: Test for CloseHandle function ** ** ** Copyright (c) 2006 Microsoft Corporation. All rights reserved. ** ** The use and distribution terms for this software are contained in the file ** named license.txt, which can be found in the root of this distribution. ** By using this software in any fashion, you are agreeing to be bound by the ** terms of this license. ** ** You must not remove this notice, or any other, from this software. ** ** **=========================================================*/ /* Depends on: CreateFile and WriteFile */ #include <palsuite.h> int __cdecl main(int argc, char *argv[]) { HANDLE FileHandle = NULL; LPDWORD WriteBuffer; /* Used with WriteFile */ /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } WriteBuffer = malloc(sizeof(WORD)); if ( WriteBuffer == NULL ) { Fail("ERROR: Failed to allocate memory for WriteBuffer pointer. " "Can't properly exec test case without this.\n"); } /* Create a file, since this returns to us a HANDLE we can use */ FileHandle = CreateFile("testfile", GENERIC_READ | GENERIC_WRITE,0,NULL,CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); /* Should be able to close this handle */ if(CloseHandle(FileHandle) == 0) { free(WriteBuffer); Fail("ERROR: (Test 1) Attempted to close a HANDLE on a file, but the " "return value was <=0, indicating failure.\n"); } free(WriteBuffer); PAL_Terminate(); return PASS; }
111410.c
#include "apue.h" #include <fcntl.h> int main(void) { if (open("tempfile", O_RDWR) < 0) err_sys("open error"); if (unlink("tempfile") < 0) err_sys("unlink error"); printf("file unlinked\n"); sleep(15); printf("done\n"); exit(0); }
49886.c
// KMSAN: uninit-value in tcf_exts_change // https://syzkaller.appspot.com/bug?id=a37cda34d2b8b740a5f1 // status:6 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <sched.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/capability.h> unsigned long long procid; static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } #define MAX_FDS 30 static void setup_common() { if (mount(0, "/sys/fs/fuse/connections", "fusectl", 0, 0)) { } } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = (200 << 20); setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 32 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); rlim.rlim_cur = rlim.rlim_max = 256; setrlimit(RLIMIT_NOFILE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } typedef struct { const char* name; const char* value; } sysctl_t; static const sysctl_t sysctls[] = { {"/proc/sys/kernel/shmmax", "16777216"}, {"/proc/sys/kernel/shmall", "536870912"}, {"/proc/sys/kernel/shmmni", "1024"}, {"/proc/sys/kernel/msgmax", "8192"}, {"/proc/sys/kernel/msgmni", "1024"}, {"/proc/sys/kernel/msgmnb", "1024"}, {"/proc/sys/kernel/sem", "1024 1048576 500 1024"}, }; unsigned i; for (i = 0; i < sizeof(sysctls) / sizeof(sysctls[0]); i++) write_file(sysctls[i].name, sysctls[i].value); } int wait_for_loop(int pid) { if (pid < 0) exit(1); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static void drop_caps(void) { struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) exit(1); const int drop = (1 << CAP_SYS_PTRACE) | (1 << CAP_SYS_NICE); cap_data[0].effective &= ~drop; cap_data[0].permitted &= ~drop; cap_data[0].inheritable &= ~drop; if (syscall(SYS_capset, &cap_hdr, &cap_data)) exit(1); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_common(); sandbox_common(); drop_caps(); if (unshare(CLONE_NEWNET)) { } loop(); exit(1); } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); int i; for (i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void close_fds() { int fd; for (fd = 3; fd < MAX_FDS; fd++) close(fd); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter; for (iter = 0;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { setup_test(); execute_one(); close_fds(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5 * 1000) continue; kill_and_wait(pid, &status); break; } } } uint64_t r[5] = {0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0xffffffffffffffff, 0x0}; void execute_one(void) { intptr_t res = 0; res = syscall(__NR_socket, 0x10ul, 3ul, 0ul); if (res != -1) r[0] = res; res = syscall(__NR_socket, 0x10ul, 3ul, 0ul); if (res != -1) r[1] = res; res = syscall(__NR_socket, 0x10ul, 3ul, 0ul); if (res != -1) r[2] = res; res = syscall(__NR_socket, 0x10ul, 0x803ul, 0); if (res != -1) r[3] = res; *(uint64_t*)0x20000280 = 0; *(uint32_t*)0x20000288 = 0; *(uint64_t*)0x20000290 = 0x20000180; *(uint64_t*)0x20000180 = 0; *(uint64_t*)0x20000188 = 0; *(uint64_t*)0x20000298 = 1; *(uint64_t*)0x200002a0 = 0; *(uint64_t*)0x200002a8 = 0; *(uint32_t*)0x200002b0 = 0; syscall(__NR_sendmsg, r[3], 0x20000280ul, 0ul); *(uint32_t*)0x200002c0 = 0x14; res = syscall(__NR_getsockname, r[3], 0x20000100ul, 0x200002c0ul); if (res != -1) r[4] = *(uint32_t*)0x20000104; *(uint64_t*)0x20000240 = 0; *(uint32_t*)0x20000248 = 0; *(uint64_t*)0x20000250 = 0x20000140; *(uint64_t*)0x20000140 = 0x200003c0; memcpy((void*)0x200003c0, "\x38\x00\x00\x00\x24\x00\x07\x05\x00\x00\x00\x40" "\x07\xa2\xa3\x00\x05\x00\x00\x00", 20); *(uint32_t*)0x200003d4 = r[4]; memcpy((void*)0x200003d8, "\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x00" "\x09\x00\x01\x00\x68\x66\x73\x63\x00\x00\x00\x00" "\x08\x00\x02\x00\x00\x00\x00\x00", 32); *(uint64_t*)0x20000148 = 0x38; *(uint64_t*)0x20000258 = 1; *(uint64_t*)0x20000260 = 0; *(uint64_t*)0x20000268 = 0; *(uint32_t*)0x20000270 = 0; syscall(__NR_sendmsg, r[2], 0x20000240ul, 0ul); *(uint64_t*)0x200001c0 = 0; *(uint32_t*)0x200001c8 = 0; *(uint64_t*)0x200001d0 = 0x20000180; *(uint64_t*)0x20000180 = 0x20000580; *(uint32_t*)0x20000580 = 0x3c; *(uint16_t*)0x20000584 = 0x2c; *(uint16_t*)0x20000586 = 0xd27; *(uint32_t*)0x20000588 = 0; *(uint32_t*)0x2000058c = 0; *(uint8_t*)0x20000590 = 0; *(uint8_t*)0x20000591 = 0; *(uint16_t*)0x20000592 = 0; *(uint32_t*)0x20000594 = r[4]; *(uint16_t*)0x20000598 = 0; *(uint16_t*)0x2000059a = 0; *(uint16_t*)0x2000059c = 0; *(uint16_t*)0x2000059e = 0; *(uint16_t*)0x200005a0 = 4; *(uint16_t*)0x200005a2 = 0xfff1; *(uint16_t*)0x200005a4 = 0xc; *(uint16_t*)0x200005a6 = 1; memcpy((void*)0x200005a8, "tcindex\000", 8); *(uint16_t*)0x200005b0 = 0xc; *(uint16_t*)0x200005b2 = 2; *(uint16_t*)0x200005b4 = 6; *(uint16_t*)0x200005b6 = 2; *(uint16_t*)0x200005b8 = 0; *(uint64_t*)0x20000188 = 0x3c; *(uint64_t*)0x200001d8 = 1; *(uint64_t*)0x200001e0 = 0; *(uint64_t*)0x200001e8 = 0; *(uint32_t*)0x200001f0 = 0; syscall(__NR_sendmsg, r[1], 0x200001c0ul, 0ul); *(uint64_t*)0x200001c0 = 0; *(uint32_t*)0x200001c8 = 0; *(uint64_t*)0x200001d0 = 0x20000180; *(uint64_t*)0x20000180 = 0x20000400; *(uint32_t*)0x20000400 = 0x3c; *(uint16_t*)0x20000404 = 0x2c; *(uint16_t*)0x20000406 = 0xd27; *(uint32_t*)0x20000408 = 0; *(uint32_t*)0x2000040c = 0; *(uint8_t*)0x20000410 = 0; *(uint8_t*)0x20000411 = 0; *(uint16_t*)0x20000412 = 0xf0; *(uint32_t*)0x20000414 = r[4]; *(uint16_t*)0x20000418 = 3; *(uint16_t*)0x2000041a = 0; *(uint16_t*)0x2000041c = 0; *(uint16_t*)0x2000041e = 0; *(uint16_t*)0x20000420 = 0; *(uint16_t*)0x20000422 = 0xfff1; *(uint16_t*)0x20000424 = 0xc; *(uint16_t*)0x20000426 = 1; memcpy((void*)0x20000428, "tcindex\000", 8); *(uint16_t*)0x20000430 = 0xc; *(uint16_t*)0x20000432 = 2; *(uint16_t*)0x20000434 = 8; *(uint16_t*)0x20000436 = 1; *(uint32_t*)0x20000438 = 0; *(uint64_t*)0x20000188 = 0x3c; *(uint64_t*)0x200001d8 = 1; *(uint64_t*)0x200001e0 = 0; *(uint64_t*)0x200001e8 = 0; *(uint32_t*)0x200001f0 = 0; syscall(__NR_sendmsg, r[0], 0x200001c0ul, 0ul); } int main(void) { syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 3ul, 0x32ul, -1, 0); for (procid = 0; procid < 6; procid++) { if (fork() == 0) { do_sandbox_none(); } } sleep(1000000); return 0; }
730428.c
/* * Copyright 2018 GoPro Inc. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <string.h> #include "log.h" #include "gctx.h" #include "nodes.h" #include "backend.h" #include "glcontext.h" #include "memory.h" #if defined(TARGET_IPHONE) #include <CoreVideo/CoreVideo.h> #endif #if defined(HAVE_VAAPI_X11) #include "vaapi.h" #endif static int offscreen_rendertarget_init(struct ngl_ctx *s) { struct glcontext *gl = s->glcontext; struct ngl_config *config = &s->config; if (!(gl->features & NGLI_FEATURE_FRAMEBUFFER_OBJECT) && config->samples > 0) { LOG(WARNING, "context does not support the framebuffer object feature, " "multisample anti-aliasing will be disabled"); config->samples = 0; } struct texture_params attachment_params = NGLI_TEXTURE_PARAM_DEFAULTS; attachment_params.format = NGLI_FORMAT_R8G8B8A8_UNORM; attachment_params.width = config->width; attachment_params.height = config->height; attachment_params.samples = config->samples; attachment_params.usage = NGLI_TEXTURE_USAGE_ATTACHMENT_ONLY; int ret = ngli_texture_init(&s->rt_color, s, &attachment_params); if (ret < 0) return ret; attachment_params.format = NGLI_FORMAT_D24_UNORM_S8_UINT; ret = ngli_texture_init(&s->rt_depth, s, &attachment_params); if (ret < 0) return ret; const struct texture *attachments[] = {&s->rt_color, &s->rt_depth}; const int nb_attachments = NGLI_ARRAY_NB(attachments); struct rendertarget_params rt_params = { .width = config->width, .height = config->height, .nb_attachments = nb_attachments, .attachments = attachments, }; ret = ngli_rendertarget_init(&s->rt, s, &rt_params); if (ret < 0) return ret; ngli_gctx_set_rendertarget(s, &s->rt); const int vp[4] = {0, 0, config->width, config->height}; ngli_gctx_set_viewport(s, vp); return 0; } static void offscreen_rendertarget_reset(struct ngl_ctx *s) { ngli_rendertarget_reset(&s->rt); ngli_texture_reset(&s->rt_color); ngli_texture_reset(&s->rt_depth); } static void capture_default(struct ngl_ctx *s) { struct ngl_config *config = &s->config; struct rendertarget *rt = &s->rt; struct rendertarget *capture_rt = &s->capture_rt; ngli_rendertarget_blit(rt, capture_rt, 1); ngli_rendertarget_read_pixels(capture_rt, config->capture_buffer); } static void capture_ios(struct ngl_ctx *s) { struct glcontext *gl = s->glcontext; struct rendertarget *rt = &s->rt; struct rendertarget *capture_rt = &s->capture_rt; ngli_rendertarget_blit(rt, capture_rt, 1); ngli_glFinish(gl); } static void capture_gles_msaa(struct ngl_ctx *s) { struct ngl_config *config = &s->config; struct rendertarget *rt = &s->rt; struct rendertarget *capture_rt = &s->capture_rt; struct rendertarget *oes_resolve_rt = &s->oes_resolve_rt; ngli_rendertarget_blit(rt, oes_resolve_rt, 0); ngli_rendertarget_blit(oes_resolve_rt, capture_rt, 1); ngli_rendertarget_read_pixels(capture_rt, config->capture_buffer); } static void capture_ios_msaa(struct ngl_ctx *s) { struct glcontext *gl = s->glcontext; struct rendertarget *rt = &s->rt; struct rendertarget *capture_rt = &s->capture_rt; struct rendertarget *oes_resolve_rt = &s->oes_resolve_rt; ngli_rendertarget_blit(rt, oes_resolve_rt, 0); ngli_rendertarget_blit(oes_resolve_rt, capture_rt, 1); ngli_glFinish(gl); } static void capture_cpu_fallback(struct ngl_ctx *s) { struct ngl_config *config = &s->config; struct rendertarget *rt = &s->rt; ngli_rendertarget_read_pixels(rt, s->capture_buffer); const int step = config->width * 4; const uint8_t *src = s->capture_buffer + (config->height - 1) * step; uint8_t *dst = config->capture_buffer; for (int i = 0; i < config->height; i++) { memcpy(dst, src, step); dst += step; src -= step; } } static int capture_init(struct ngl_ctx *s) { struct glcontext *gl = s->glcontext; struct ngl_config *config = &s->config; const int ios_capture = gl->platform == NGL_PLATFORM_IOS && config->window; if (!config->capture_buffer && !ios_capture) return 0; if (gl->features & NGLI_FEATURE_FRAMEBUFFER_OBJECT) { if (ios_capture) { #if defined(TARGET_IPHONE) CVPixelBufferRef capture_cvbuffer = (CVPixelBufferRef)config->window; s->capture_cvbuffer = (CVPixelBufferRef)CFRetain(capture_cvbuffer); if (!s->capture_cvbuffer) return NGL_ERROR_MEMORY; CVOpenGLESTextureCacheRef *cache = ngli_glcontext_get_texture_cache(gl); int width = CVPixelBufferGetWidth(s->capture_cvbuffer); int height = CVPixelBufferGetHeight(s->capture_cvbuffer); CVReturn err = CVOpenGLESTextureCacheCreateTextureFromImage(kCFAllocatorDefault, *cache, s->capture_cvbuffer, NULL, GL_TEXTURE_2D, GL_RGBA, width, height, GL_BGRA, GL_UNSIGNED_BYTE, 0, &s->capture_cvtexture); if (err != noErr) { LOG(ERROR, "could not create CoreVideo texture from CVPixelBuffer: 0x%x", err); return NGL_ERROR_EXTERNAL; } GLuint id = CVOpenGLESTextureGetName(s->capture_cvtexture); ngli_glBindTexture(gl, GL_TEXTURE_2D, id); ngli_glTexParameteri(gl, GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); ngli_glTexParameteri(gl, GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); ngli_glBindTexture(gl, GL_TEXTURE_2D, 0); struct texture_params attachment_params = NGLI_TEXTURE_PARAM_DEFAULTS; attachment_params.format = NGLI_FORMAT_B8G8R8A8_UNORM; attachment_params.width = width; attachment_params.height = height; int ret = ngli_texture_wrap(&s->capture_rt_color, s, &attachment_params, id); if (ret < 0) return ret; #endif } else { struct texture_params attachment_params = NGLI_TEXTURE_PARAM_DEFAULTS; attachment_params.format = NGLI_FORMAT_R8G8B8A8_UNORM; attachment_params.width = config->width; attachment_params.height = config->height; attachment_params.usage = NGLI_TEXTURE_USAGE_ATTACHMENT_ONLY; int ret = ngli_texture_init(&s->capture_rt_color, s, &attachment_params); if (ret < 0) return ret; } const struct texture *attachments[] = {&s->capture_rt_color}; const int nb_attachments = NGLI_ARRAY_NB(attachments); struct rendertarget_params rt_params = { .width = config->width, .height = config->height, .nb_attachments = nb_attachments, .attachments = attachments, }; int ret = ngli_rendertarget_init(&s->capture_rt, s, &rt_params); if (ret < 0) return ret; if (gl->backend == NGL_BACKEND_OPENGLES && config->samples > 0) { struct texture_params attachment_params = NGLI_TEXTURE_PARAM_DEFAULTS; attachment_params.format = NGLI_FORMAT_R8G8B8A8_UNORM; attachment_params.width = config->width; attachment_params.height = config->height; attachment_params.samples = 0; attachment_params.usage = NGLI_TEXTURE_USAGE_ATTACHMENT_ONLY; int ret = ngli_texture_init(&s->oes_resolve_rt_color, s, &attachment_params); if (ret < 0) return ret; const struct texture *attachments[] = {&s->oes_resolve_rt_color}; const int nb_attachments = NGLI_ARRAY_NB(attachments); struct rendertarget_params rt_params = { .width = config->width, .height = config->height, .nb_attachments = nb_attachments, .attachments = attachments, }; ret = ngli_rendertarget_init(&s->oes_resolve_rt, s, &rt_params); if (ret < 0) return ret; s->capture_func = config->capture_buffer ? capture_gles_msaa : capture_ios_msaa; } else { s->capture_func = config->capture_buffer ? capture_default : capture_ios; } } else { if (ios_capture) { LOG(WARNING, "context does not support the framebuffer object feature, " "capturing to a CVPixelBuffer is not supported"); return NGL_ERROR_UNSUPPORTED; } s->capture_buffer = ngli_calloc(config->width * config->height, 4 /* RGBA */); if (!s->capture_buffer) return NGL_ERROR_MEMORY; s->capture_func = capture_cpu_fallback; } ngli_assert(s->capture_func); return 0; } static void capture_reset(struct ngl_ctx *s) { ngli_rendertarget_reset(&s->capture_rt); ngli_texture_reset(&s->capture_rt_color); ngli_rendertarget_reset(&s->oes_resolve_rt); ngli_texture_reset(&s->oes_resolve_rt_color); ngli_free(s->capture_buffer); s->capture_buffer = NULL; #if defined(TARGET_IPHONE) if (s->capture_cvbuffer) { CFRelease(s->capture_cvbuffer); s->capture_cvbuffer = NULL; } if (s->capture_cvtexture) { CFRelease(s->capture_cvtexture); s->capture_cvtexture = NULL; } #endif s->capture_func = NULL; } static int gl_reconfigure(struct ngl_ctx *s, const struct ngl_config *config) { struct glcontext *gl = s->glcontext; struct ngl_config *current_config = &s->config; ngli_glcontext_set_swap_interval(gl, config->swap_interval); current_config->swap_interval = config->swap_interval; current_config->set_surface_pts = config->set_surface_pts; const int update_dimensions = current_config->width != config->width || current_config->height != config->height; current_config->width = config->width; current_config->height = config->height; const int update_capture = !current_config->capture_buffer != !config->capture_buffer; current_config->capture_buffer = config->capture_buffer; if (config->offscreen) { if (update_dimensions) { offscreen_rendertarget_reset(s); int ret = offscreen_rendertarget_init(s); if (ret < 0) return ret; } if (update_dimensions || update_capture) { capture_reset(s); int ret = capture_init(s); if (ret < 0) return ret; } } else { int ret = ngli_glcontext_resize(gl); if (ret < 0) return ret; } const int *viewport = config->viewport; if (viewport[2] > 0 && viewport[3] > 0) { ngli_gctx_set_viewport(s, viewport); memcpy(current_config->viewport, config->viewport, sizeof(config->viewport)); } else { struct glcontext *gl = s->glcontext; const int default_viewport[] = {0, 0, gl->width, gl->height}; ngli_gctx_set_viewport(s, default_viewport); } ngli_gctx_set_clear_color(s, config->clear_color); memcpy(current_config->clear_color, config->clear_color, sizeof(config->clear_color)); const int scissor[] = {0, 0, gl->width, gl->height}; struct graphicconfig *graphicconfig = &s->graphicconfig; memcpy(graphicconfig->scissor, scissor, sizeof(scissor)); return 0; } static int gl_configure(struct ngl_ctx *s, const struct ngl_config *config) { memcpy(&s->config, config, sizeof(s->config)); s->glcontext = ngli_glcontext_new(&s->config); if (!s->glcontext) return NGL_ERROR_MEMORY; if (s->glcontext->offscreen) { int ret = offscreen_rendertarget_init(s); if (ret < 0) return ret; ret = capture_init(s); if (ret < 0) return ret; } ngli_glstate_probe(s->glcontext, &s->glstate); /* This field is used by the pipeline API in order to reduce the total * number of GL program switches. This means pipeline draw calls may alter * this value, but we don't want it to be hard-reconfigure resilient (the * value is specific to a given GL context). As a result, we need to make * sure the value is always reset. */ s->program_id = 0; const int *viewport = config->viewport; if (viewport[2] > 0 && viewport[3] > 0) { ngli_gctx_set_viewport(s, viewport); } else { struct glcontext *gl = s->glcontext; const int default_viewport[] = {0, 0, gl->width, gl->height}; ngli_gctx_set_viewport(s, default_viewport); } ngli_gctx_set_clear_color(s, config->clear_color); struct graphicconfig *graphicconfig = &s->graphicconfig; ngli_graphicconfig_init(graphicconfig); const GLint scissor[] = {0, 0, config->width, config->height}; memcpy(graphicconfig->scissor, scissor, sizeof(scissor)); #if defined(HAVE_VAAPI_X11) int ret = ngli_vaapi_init(s); if (ret < 0) LOG(WARNING, "could not initialize vaapi"); #endif return 0; } static int gl_pre_draw(struct ngl_ctx *s, double t) { ngli_gctx_clear_color(s); ngli_gctx_clear_depth_stencil(s); return 0; } static int gl_post_draw(struct ngl_ctx *s, double t) { struct glcontext *gl = s->glcontext; struct ngl_config *config = &s->config; ngli_honor_pending_glstate(s); if (s->capture_func) s->capture_func(s); int ret = 0; if (ngli_glcontext_check_gl_error(gl, __FUNCTION__)) ret = -1; if (config->set_surface_pts) ngli_glcontext_set_surface_pts(gl, t); ngli_glcontext_swap_buffers(gl); return ret; } static void gl_destroy(struct ngl_ctx *s) { capture_reset(s); offscreen_rendertarget_reset(s); #if defined(HAVE_VAAPI_X11) ngli_vaapi_reset(s); #endif ngli_glcontext_freep(&s->glcontext); } const struct backend ngli_backend_gl = { .name = "OpenGL", .reconfigure = gl_reconfigure, .configure = gl_configure, .pre_draw = gl_pre_draw, .post_draw = gl_post_draw, .destroy = gl_destroy, }; const struct backend ngli_backend_gles = { .name = "OpenGL ES", .reconfigure = gl_reconfigure, .configure = gl_configure, .pre_draw = gl_pre_draw, .post_draw = gl_post_draw, .destroy = gl_destroy, };
258637.c
/******************************************************** * Added as part of the memcached-1.4.24_RDMA project. * Implementing backup system via BSD sockets. * BackupClient method receives the address to connect too, * connects to the Memcached Backup Server in connectToServer method, and runs a RunBackupClient thread. * The client thread samples the queue every 2 seconds, and when there is an item in the queue, * starts the backup process. * BackupServer method receives an address to listen too, * creates a RunBackupServer thread, and on each incoming connection starts connection_handler thread. * After the connection with the client is establisged, the backup receives the memory backup, and closes the connection. ********************************************************/ #include "backup.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <pthread.h> #include <assert.h> #include "queue.h" #include "sharedmalloc.h" #include "memcached.h" #define MAXDATASIZE 10000 // max number of bytes we can get at once /* * get sockaddr, IPv4 or IPv6: */ void *get_in_addr(struct sockaddr *sa); /* * Closes the socket */ int closeSocket(int sockfd); /* * Handels SIGCHLD Signal */ void sigchld_handler(int s); /* * Server connection handler thread. * Receives the memory backup within 3 steps - assoc, slabs and slabs_lists. */ void *connection_handler(void *socket_desc); /* * Server backup thread. Waits for incoming communication. */ void *RunBackupServer(void *arg); /* * Samples the queue every 2 seconds. When the queue is not empty, * starts the backup process - sebds the assoc, slabs and slab_lists memory sections. */ void *RunBackupClient(void *arg); /* * Connects via BSD Socket to the given server. */ int connectToServer(char *clientHostname, char *clientPort, int *sockfd); /* * Load the given file into memory (RAM) and sends it in chunks via BSD Socket */ int sendBackupToClients(char *fileToSend, char *msg, int msgSize); static pthread_t g_serverThread; static int g_backups_count = 0; static int g_client_socketfd[MAX_BACKUPS]; /* * Loads the given file into the memory (RAM) */ long ae_load_file_to_memory(const char *filename, char **result) { long size = 0; FILE *f = fopen(filename, "rb"); if (f == NULL) { *result = NULL; return -1; // -1 means file opening fail } fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); *result = (char *)malloc(size+1); if (size != fread(*result, sizeof(char), size, f)) { free(*result); return -2; // -2 means file reading fail } fclose(f); (*result)[size] = 0; return size; } /* * Loads the given data into a file. */ long ae_load_memory_to_file(const char *filename, const char *data, const int size) { FILE *f = fopen(filename, "wb"); if (f == NULL) { return -1; } if (fwrite(data, sizeof(char), size, f) == 0) { fclose(f); return -1; } fclose(f); return 1; } /* * splits string accroding to the given delimiter */ char** str_split(char* a_str, const char a_delim) { char** result = 0; size_t count = 0; char* tmp = a_str; char* last_comma = 0; char delim[2]; delim[0] = a_delim; delim[1] = 0; /* Count how many elements will be extracted. */ while (*tmp) { if (a_delim == *tmp) { count++; last_comma = tmp; } tmp++; } /* Add space for trailing token. */ count += last_comma < (a_str + strlen(a_str) - 1); /* Add space for terminating null string so caller knows where the list of returned strings ends. */ count++; result = malloc(sizeof(char*) * count); if (result) { size_t idx = 0; char* token = strtok(a_str, delim); while (token) { assert(idx < count); *(result + idx++) = strdup(token); token = strtok(0, delim); } assert(idx == count - 1); *(result + idx) = 0; } return result; } /* * get sockaddr, IPv4 or IPv6: */ void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } /* * Connects via BSD Socket to the given server. */ int connectToServer(char *clientHostname, char *clientPort, int *sockfd) { struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; rv = getaddrinfo(clientHostname, clientPort, &hints, &servinfo); if (rv != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { *sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (*sockfd == -1) { perror("client: socket\n"); continue; } rv = connect(*sockfd, p->ai_addr, p->ai_addrlen); if (rv == -1) { close(*sockfd); perror("client: connect\n"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure return 0; } /* * receivs data from sockfd, and returns it in buf. * numbytes is the number of received bytes. * The received data is null terminated. */ int receive(int sockfd, char *buf, int *numbytes) { *numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0); if (*numbytes == -1) { perror("recv\n"); exit(1); } buf[*numbytes] = '\0'; printf("client: received '%s'\n",buf); return 0; } /* * Closes the socket */ int closeSocket(int sockfd) { close(sockfd); return 0; } #define BACKLOG 10 // how many pending connections queue will hold /* * Handels SIGCHLD Signal */ void sigchld_handler(int s) { // waitpid() might overwrite errno, so we save and restore it: int saved_errno = errno; while(waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } /* * Load the given file into memory (RAM) and sends it in chunks via BSD Socket */ int sendBackupToClients(char *fileToSend, char *msg, int msgSize) { int i; char *content; char *content_temp; long size, size_temp; ssize_t n; size = ae_load_file_to_memory(fileToSend, &content); if (size < 0) { puts("Error loading file"); return 1; } for (i = 0; i < g_backups_count; i++) { size_temp = size; content_temp = content; send((g_client_socketfd[i]), msg, msgSize, 0); send((g_client_socketfd[i]), &size_temp, sizeof(long), 0); do { n = send((g_client_socketfd[i]), content_temp, size_temp, 0); content_temp += n; size_temp -= n; } while(size_temp > 0); } free(content); return 0; } int BackupClient(char *clientHostnamePortwithPort) { int rv; char** hostAndPort = str_split(clientHostnamePortwithPort, ':'); struct addr *addr = (struct addr*)malloc(sizeof(struct addr)); addr->ip = hostAndPort[0]; addr->port = hostAndPort[1]; if (g_backups_count >= MAX_BACKUPS) { printf("Maximal number of backups reached\n"); return -1; } if (connectToServer(hostAndPort[0], hostAndPort[1] , &g_client_socketfd[g_backups_count]) != 0) { printf("Error creating client connection\n"); return -1; } g_backups_count++; //Create backup server thread rv = pthread_create(&g_serverThread, NULL, RunBackupClient, (void*) addr); if(rv < 0) { printf("Error creating backup client thread\n"); return -1; } return 0; } int BackupServer(char *clientHostnamePortwithPort) { int rv; char** hostAndPort = str_split(clientHostnamePortwithPort, ':'); struct addr *addr = (struct addr*)malloc(sizeof(struct addr)); addr->ip = hostAndPort[0]; addr->port = hostAndPort[1]; //Create backup server thread rv = pthread_create(&g_serverThread, NULL, RunBackupServer, (void*) addr); if(rv < 0) { printf("Error creating backup server thread\n"); } return 0; } /* * Samples the queue every 2 seconds. When the queue is not empty, * starts the backup process - sebds the assoc, slabs and slab_lists memory sections. */ void *RunBackupClient(void *arg) { int queue_val; char *path; while (1) { //check if there a message waiting in the queue if (!queue_empty()) { queue_val = queue_frontelement(); printf("Got something in the queue! value = %d\n",queue_val); queue_deq(); path = gen_full_path(settings.shared_malloc_assoc_key, KEYPATH); sendBackupToClients(path,"queue data step 1 sending", 25); free(path); path = gen_full_path(settings.shared_malloc_slabs_key, KEYPATH); sendBackupToClients(path,"queue data step 2 sending", 25); free(path); path = gen_full_path(settings.shared_malloc_slabs_lists_key, KEYPATH); sendBackupToClients(path,"queue data step 3 sending", 25); free(path); } sleep(2); } } /* * Server backup thread. Waits for incoming communication. */ void *RunBackupServer(void *arg) { int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; struct addr *addr = (struct addr*)arg; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP rv = getaddrinfo(NULL, addr->port, &hints, &servinfo); if (rv != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } // loop through all the results and bind to the first we can for (p = servinfo; p != NULL; p = p->ai_next) { sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (sockfd == -1) { perror("server: socket\n"); continue; } rv = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (rv == -1) { perror("setsockopt\n"); exit(1); } rv = bind(sockfd, p->ai_addr, p->ai_addrlen); if (rv == -1) { close(sockfd); perror("server: bind\n"); continue; } break; } freeaddrinfo(servinfo); // all done with this structure if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } rv = listen(sockfd, BACKLOG); if (rv == -1) { perror("listen\n"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; rv = sigaction(SIGCHLD, &sa, NULL); if (rv == -1) { perror("sigaction\n"); exit(1); } printf("server: waiting for connections...\n"); while(1) // main accept() loop { sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept\n"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("server: got connection from %s\n", s); //Create receive thread pthread_t thread; rv = pthread_create(&thread, NULL , connection_handler, (void*) &new_fd); if(rv < 0) { printf("Error creating receive thread\n"); } } exit(0); } /* * Server connection handler thread. * Receives the memory backup within 3 steps - assoc, slabs and slabs_lists. */ void *connection_handler(void *socket_desc) { int received = 0; int sock = *(int*)socket_desc; long data_size = 0; long original_data_size = 0; char msg[25]; char data[MAXDATASIZE]; int step = 0; data_size = 0; void *memcached1_slabs = NULL; void *memcached1_slabs_lists = NULL; void *memcached1_assoc = NULL; while (1) { received = 0; memset(data, 0, MAXDATASIZE); memset(msg, 0, 25); if (step == 0) { received = recv(sock, &msg, sizeof(char) * 25, 0); if (received == -1 || received != 25) { printf("error0\n"); } if (strncmp(msg,"queue data step 1 sending",25) == 0) { received = recv(sock, &data_size, sizeof(long), 0); if (received == -1) { printf("error1\n"); } original_data_size = data_size; step = 1; memcached1_assoc = shared_malloc(NULL, original_data_size,settings.shared_malloc_assoc_key,NO_LOCK); printf("Moving to step 1\n"); } } if (step == 1 && data_size != 0) { while (data_size > 0) { memset(data, 0, MAXDATASIZE); if (data_size < MAXDATASIZE) { received = recv(sock, data, data_size, 0); } else { received = recv(sock, data, MAXDATASIZE, 0); } if (received == -1) { printf("error3\n"); } memcpy((char *)memcached1_assoc + original_data_size - data_size, data,received); data_size -= received; } shared_free(memcached1_assoc, original_data_size); original_data_size = 0; printf("Finished step 1\n"); } if (step == 1 && data_size == 0) { received = recv(sock, &msg, sizeof(char) * 25, 0); if (received == -1 || received != 25) { printf("error5\n"); } if (strncmp(msg,"queue data step 2 sending",25) == 0) { received = recv(sock, &data_size, sizeof(long), 0); if (received == -1) { printf("error6\n"); } original_data_size = data_size; step = 2; memcached1_slabs = shared_malloc(NULL, original_data_size, settings.shared_malloc_slabs_key, NO_LOCK); } printf("Moving to step 2\n"); } if (step == 2 && data_size != 0) { while (data_size > 0) { memset(data, 0, MAXDATASIZE); if (data_size < MAXDATASIZE) { received = recv(sock, data, data_size, 0); } else { received = recv(sock, data, MAXDATASIZE, 0); } if (received == -1) { printf("error8\n"); } memcpy((char *)memcached1_slabs + original_data_size - data_size, data,received); data_size -= received; } shared_free(memcached1_slabs, original_data_size); original_data_size = 0; printf("Finished step 2\n"); } if (step == 2 && data_size == 0) { received = recv(sock, &msg, sizeof(char) * 25, 0); if (received == -1 || received != 25) { printf("error10\n"); } if (strncmp(msg,"queue data step 3 sending",25) == 0) { received = recv(sock, &data_size, sizeof(long), 0); original_data_size = data_size; if (received == -1) { printf("error11\n"); } step = 3; memcached1_slabs_lists = shared_malloc(NULL, original_data_size, settings.shared_malloc_slabs_lists_key, NO_LOCK); } printf("Moving to step 3\n"); } if (step == 3 && data_size != 0) { while (data_size > 0) { memset(data, 0, MAXDATASIZE); if (data_size < MAXDATASIZE) { received = recv(sock, data, data_size, 0); } else { received = recv(sock, data, MAXDATASIZE, 0); } if (received == -1) { printf("error13\n"); } memcpy((char *)memcached1_slabs_lists + original_data_size - data_size, data,received); data_size -= received; } shared_free(memcached1_slabs_lists, original_data_size); original_data_size = 0; printf("Finished step 3\n"); } step = 0; } close(sock); printf("Downloaded backup successfully\n"); return 0; }
984835.c
///////////////////////////////////////////// // // // Copyright (C) 2019-2019 Julian Uy // // https://sites.google.com/site/awertyb // // // // See details of license at "LICENSE" // // // ///////////////////////////////////////////// #include "extractor.h" #include <stdio.h> #include <string.h> #include <webp/decode.h> const char *plugin_info[4] = { "00IN", "WebP Plugin for Susie Image Viewer", "*.webp", "WebP file (*.webp)", }; const int header_size = 64; int getBMPFromWebP(uint8_t *input_data, long file_size, BITMAPFILEHEADER *bitmap_file_header, BITMAPINFOHEADER *bitmap_info_header, uint8_t **data) { int width, height; unsigned long bit_length, bit_width; uint8_t *bitmap_data; *data = WebPDecodeBGRA(input_data, file_size, &width, &height); bit_width = width * 4; bit_length = bit_width; bitmap_data = (uint8_t *)malloc(sizeof(uint8_t) * bit_length * height); memset(bitmap_data, 0, bit_length * height); for (int i = 0; i < height; i++) { memcpy(bitmap_data + i * bit_length, *data + (height - i - 1) * bit_width, bit_width); } free(*data); *data = bitmap_data; memset(bitmap_file_header, 0, sizeof(BITMAPFILEHEADER)); memset(bitmap_info_header, 0, sizeof(BITMAPINFOHEADER)); bitmap_file_header->bfType = 'M' * 256 + 'B'; bitmap_file_header->bfSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + sizeof(uint8_t) * bit_length * height; bitmap_file_header->bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); bitmap_file_header->bfReserved1 = 0; bitmap_file_header->bfReserved2 = 0; bitmap_info_header->biSize = 40; bitmap_info_header->biWidth = width; bitmap_info_header->biHeight = height; bitmap_info_header->biPlanes = 1; bitmap_info_header->biBitCount = 32; bitmap_info_header->biCompression = 0; bitmap_info_header->biSizeImage = bitmap_file_header->bfSize; bitmap_info_header->biXPelsPerMeter = bitmap_info_header->biYPelsPerMeter = 0; bitmap_info_header->biClrUsed = 0; bitmap_info_header->biClrImportant = 0; return 0; } BOOL IsSupportedEx(char *filename, char *data) { const char header[] = {'R', 'I', 'F', 'F', 0x00, 0x00, 0x00, 0x00, 'W', 'E', 'B', 'P', 'V', 'P', '8'}; for (int i = 0; i < sizeof(header); i++) { if (header[i] == 0x00) continue; if (data[i] != header[i]) return FALSE; } return TRUE; } int GetPictureInfoEx(long data_size, char *data, struct PictureInfo *picture_info) { int width, height; WebPGetInfo((uint8_t *)data, data_size, &width, &height); picture_info->left = 0; picture_info->top = 0; picture_info->width = width; picture_info->height = height; picture_info->x_density = 0; picture_info->y_density = 0; picture_info->colorDepth = 32; picture_info->hInfo = NULL; return SPI_ALL_RIGHT; } int GetPictureEx(long data_size, HANDLE *bitmap_info, HANDLE *bitmap_data, SPI_PROGRESS progress_callback, long user_data, char *data) { uint8_t *data_u8; BITMAPINFOHEADER bitmap_info_header; BITMAPFILEHEADER bitmap_file_header; BITMAPINFO *bitmap_info_locked; unsigned char *bitmap_data_locked; if (progress_callback != NULL) if (progress_callback(1, 1, user_data)) return SPI_ABORT; getBMPFromWebP((uint8_t *)data, data_size, &bitmap_file_header, &bitmap_info_header, &data_u8); *bitmap_info = LocalAlloc(LMEM_MOVEABLE, sizeof(BITMAPINFOHEADER)); *bitmap_data = LocalAlloc(LMEM_MOVEABLE, bitmap_file_header.bfSize - bitmap_file_header.bfOffBits); if (*bitmap_info == NULL || *bitmap_data == NULL) { if (*bitmap_info != NULL) LocalFree(*bitmap_info); if (*bitmap_data != NULL) LocalFree(*bitmap_data); return SPI_NO_MEMORY; } bitmap_info_locked = (BITMAPINFO *)LocalLock(*bitmap_info); bitmap_data_locked = (unsigned char *)LocalLock(*bitmap_data); if (bitmap_info_locked == NULL || bitmap_data_locked == NULL) { LocalFree(*bitmap_info); LocalFree(*bitmap_data); return SPI_MEMORY_ERROR; } bitmap_info_locked->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmap_info_locked->bmiHeader.biWidth = bitmap_info_header.biWidth; bitmap_info_locked->bmiHeader.biHeight = bitmap_info_header.biHeight; bitmap_info_locked->bmiHeader.biPlanes = 1; bitmap_info_locked->bmiHeader.biBitCount = 32; bitmap_info_locked->bmiHeader.biCompression = BI_RGB; bitmap_info_locked->bmiHeader.biSizeImage = 0; bitmap_info_locked->bmiHeader.biXPelsPerMeter = 0; bitmap_info_locked->bmiHeader.biYPelsPerMeter = 0; bitmap_info_locked->bmiHeader.biClrUsed = 0; bitmap_info_locked->bmiHeader.biClrImportant = 0; memcpy(bitmap_data_locked, data_u8, bitmap_file_header.bfSize - bitmap_file_header.bfOffBits); LocalUnlock(*bitmap_info); LocalUnlock(*bitmap_data); free(data_u8); if (progress_callback != NULL) if (progress_callback(1, 1, user_data)) return SPI_ABORT; return SPI_ALL_RIGHT; }
110798.c
/* * This file is part of libdom. * Licensed under the MIT License, * http://www.opensource.org/licenses/mit-license.php * Copyright 2007 John-Mark Bell <[email protected]> * Copyright 2009 Bo Yang <[email protected]> */ #include <assert.h> #include <stdlib.h> #include <dom/core/characterdata.h> #include <dom/core/string.h> #include <dom/events/events.h> #include "core/characterdata.h" #include "core/document.h" #include "core/node.h" #include "utils/utils.h" #include "events/mutation_event.h" /* The virtual functions for dom_characterdata, we make this vtable * public to each child class */ const struct dom_characterdata_vtable characterdata_vtable = { { { DOM_NODE_EVENT_TARGET_VTABLE }, DOM_NODE_VTABLE_CHARACTERDATA }, DOM_CHARACTERDATA_VTABLE }; /* Create a DOM characterdata node and compose the vtable */ dom_characterdata *_dom_characterdata_create(void) { dom_characterdata *cdata = malloc(sizeof(struct dom_characterdata)); if (cdata == NULL) return NULL; cdata->base.base.vtable = &characterdata_vtable; cdata->base.vtable = NULL; return cdata; } /** * Initialise a character data node * * \param cdata The character data node to initialise * \param doc The document which owns the node * \param type The node type required * \param name The node name, or NULL * \param value The node value, or NULL * \return DOM_NO_ERR on success. * * \p doc, \p name and \p value will have their reference counts increased. */ dom_exception _dom_characterdata_initialise(struct dom_characterdata *cdata, struct dom_document *doc, dom_node_type type, dom_string *name, dom_string *value) { return _dom_node_initialise(&cdata->base, doc, type, name, value, NULL, NULL); } /** * Finalise a character data node * * \param cdata The node to finalise * * The contents of \p cdata will be cleaned up. \p cdata will not be freed. */ void _dom_characterdata_finalise(struct dom_characterdata *cdata) { _dom_node_finalise(&cdata->base); } /*----------------------------------------------------------------------*/ /* The public virtual functions */ /** * Retrieve data from a character data node * * \param cdata Character data node to retrieve data from * \param data Pointer to location to receive data * \return DOM_NO_ERR. * * The returned string will have its reference count increased. It is * the responsibility of the caller to unref the string once it has * finished with it. * * DOM3Core states that this can raise DOMSTRING_SIZE_ERR. It will not in * this implementation; dom_strings are unbounded. */ dom_exception _dom_characterdata_get_data(struct dom_characterdata *cdata, dom_string **data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; if (c->value != NULL) { dom_string_ref(c->value); } *data = c->value; return DOM_NO_ERR; } /** * Set the content of a character data node * * \param cdata Node to set the content of * \param data New value for node * \return DOM_NO_ERR on success, * DOM_NO_MODIFICATION_ALLOWED_ERR if \p cdata is readonly. * * The new content will have its reference count increased, so the caller * should unref it after the call (as the caller should have already claimed * a reference on the string). The node's existing content will be unrefed. */ dom_exception _dom_characterdata_set_data(struct dom_characterdata *cdata, dom_string *data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; dom_exception err; struct dom_document *doc; bool success = true; if (_dom_node_readonly(c)) { return DOM_NO_MODIFICATION_ALLOWED_ERR; } /* Dispatch a DOMCharacterDataModified event */ doc = dom_node_get_owner(cdata); err = _dom_dispatch_characterdata_modified_event(doc, c, c->value, data, &success); if (err != DOM_NO_ERR) return err; if (c->value != NULL) { dom_string_unref(c->value); } dom_string_ref(data); c->value = data; success = true; return _dom_dispatch_subtree_modified_event(doc, c->parent, &success); } /** * Get the length (in characters) of a character data node's content * * \param cdata Node to read content length of * \param length Pointer to location to receive character length of content * \return DOM_NO_ERR. */ dom_exception _dom_characterdata_get_length(struct dom_characterdata *cdata, uint32_t *length) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; if (c->value != NULL) { *length = dom_string_length(c->value); } else { *length = 0; } return DOM_NO_ERR; } /** * Extract a range of data from a character data node * * \param cdata The node to extract data from * \param offset The character offset of substring to extract * \param count The number of characters to extract * \param data Pointer to location to receive substring * \return DOM_NO_ERR on success, * DOM_INDEX_SIZE_ERR if \p offset is negative or greater than the * number of characters in \p cdata or * \p count is negative. * * The returned string will have its reference count increased. It is * the responsibility of the caller to unref the string once it has * finished with it. * * DOM3Core states that this can raise DOMSTRING_SIZE_ERR. It will not in * this implementation; dom_strings are unbounded. */ dom_exception _dom_characterdata_substring_data( struct dom_characterdata *cdata, uint32_t offset, uint32_t count, dom_string **data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; uint32_t len, end; if ((int32_t) offset < 0 || (int32_t) count < 0) { return DOM_INDEX_SIZE_ERR; } if (c->value != NULL) { len = dom_string_length(c->value); } else { len = 0; } if (offset > len) { return DOM_INDEX_SIZE_ERR; } end = (offset + count) >= len ? len : offset + count; return dom_string_substr(c->value, offset, end, data); } /** * Append data to the end of a character data node's content * * \param cdata The node to append data to * \param data The data to append * \return DOM_NO_ERR on success, * DOM_NO_MODIFICATION_ALLOWED_ERR if \p cdata is readonly. */ dom_exception _dom_characterdata_append_data(struct dom_characterdata *cdata, dom_string *data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; dom_string *temp; dom_exception err; struct dom_document *doc; bool success = true; if (_dom_node_readonly(c)) { return DOM_NO_MODIFICATION_ALLOWED_ERR; } err = dom_string_concat(c->value, data, &temp); if (err != DOM_NO_ERR) { return err; } /* Dispatch a DOMCharacterDataModified event */ doc = dom_node_get_owner(cdata); err = _dom_dispatch_characterdata_modified_event(doc, c, c->value, temp, &success); if (err != DOM_NO_ERR) { dom_string_unref(temp); return err; } if (c->value != NULL) { dom_string_unref(c->value); } c->value = temp; success = true; return _dom_dispatch_subtree_modified_event(doc, c->parent, &success); } /** * Insert data into a character data node's content * * \param cdata The node to insert into * \param offset The character offset to insert at * \param data The data to insert * \return DOM_NO_ERR on success, * DOM_INDEX_SIZE_ERR if \p offset is negative or greater * than the number of characters in * \p cdata, * DOM_NO_MODIFICATION_ALLOWED_ERR if \p cdata is readonly. */ dom_exception _dom_characterdata_insert_data(struct dom_characterdata *cdata, uint32_t offset, dom_string *data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; dom_string *temp; uint32_t len; dom_exception err; struct dom_document *doc; bool success = true; if (_dom_node_readonly(c)) { return DOM_NO_MODIFICATION_ALLOWED_ERR; } if ((int32_t) offset < 0) { return DOM_INDEX_SIZE_ERR; } if (c->value != NULL) { len = dom_string_length(c->value); } else { len = 0; } if (offset > len) { return DOM_INDEX_SIZE_ERR; } err = dom_string_insert(c->value, data, offset, &temp); if (err != DOM_NO_ERR) { return err; } /* Dispatch a DOMCharacterDataModified event */ doc = dom_node_get_owner(cdata); err = _dom_dispatch_characterdata_modified_event(doc, c, c->value, temp, &success); if (err != DOM_NO_ERR) return err; if (c->value != NULL) { dom_string_unref(c->value); } c->value = temp; success = true; return _dom_dispatch_subtree_modified_event(doc, c->parent, &success); } /** * Delete data from a character data node's content * * \param cdata The node to delete from * \param offset The character offset to start deletion from * \param count The number of characters to delete * \return DOM_NO_ERR on success, * DOM_INDEX_SIZE_ERR if \p offset is negative or greater * than the number of characters in * \p cdata or \p count is negative, * DOM_NO_MODIFICATION_ALLOWED_ERR if \p cdata is readonly. */ dom_exception _dom_characterdata_delete_data(struct dom_characterdata *cdata, uint32_t offset, uint32_t count) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; dom_string *temp; uint32_t len, end; dom_exception err; struct dom_document *doc; bool success = true; dom_string *empty; if (_dom_node_readonly(c)) { return DOM_NO_MODIFICATION_ALLOWED_ERR; } if ((int32_t) offset < 0 || (int32_t) count < 0) { return DOM_INDEX_SIZE_ERR; } if (c->value != NULL) { len = dom_string_length(c->value); } else { len = 0; } if (offset > len) { return DOM_INDEX_SIZE_ERR; } end = (offset + count) >= len ? len : offset + count; empty = ((struct dom_document *) ((struct dom_node_internal *)c)->owner)->_memo_empty; err = dom_string_replace(c->value, empty, offset, end, &temp); if (err != DOM_NO_ERR) { return err; } /* Dispatch a DOMCharacterDataModified event */ doc = dom_node_get_owner(cdata); err = _dom_dispatch_characterdata_modified_event(doc, c, c->value, temp, &success); if (err != DOM_NO_ERR) return err; if (c->value != NULL) { dom_string_unref(c->value); } c->value = temp; success = true; return _dom_dispatch_subtree_modified_event(doc, c->parent, &success); } /** * Replace a section of a character data node's content * * \param cdata The node to modify * \param offset The character offset of the sequence to replace * \param count The number of characters to replace * \param data The replacement data * \return DOM_NO_ERR on success, * DOM_INDEX_SIZE_ERR if \p offset is negative or greater * than the number of characters in * \p cdata or \p count is negative, * DOM_NO_MODIFICATION_ALLOWED_ERR if \p cdata is readonly. */ dom_exception _dom_characterdata_replace_data(struct dom_characterdata *cdata, uint32_t offset, uint32_t count, dom_string *data) { struct dom_node_internal *c = (struct dom_node_internal *) cdata; dom_string *temp; uint32_t len, end; dom_exception err; struct dom_document *doc; bool success = true; if (_dom_node_readonly(c)) { return DOM_NO_MODIFICATION_ALLOWED_ERR; } if ((int32_t) offset < 0 || (int32_t) count < 0) { return DOM_INDEX_SIZE_ERR; } if (c->value != NULL) { len = dom_string_length(c->value); } else { len = 0; } if (offset > len) { return DOM_INDEX_SIZE_ERR; } end = (offset + count) >= len ? len : offset + count; err = dom_string_replace(c->value, data, offset, end, &temp); if (err != DOM_NO_ERR) { return err; } /* Dispatch a DOMCharacterDataModified event */ doc = dom_node_get_owner(cdata); err = _dom_dispatch_characterdata_modified_event(doc, c, c->value, temp, &success); if (err != DOM_NO_ERR) return err; if (c->value != NULL) { dom_string_unref(c->value); } c->value = temp; success = true; return _dom_dispatch_subtree_modified_event(doc, c->parent, &success); } dom_exception _dom_characterdata_get_text_content(dom_node_internal *node, dom_string **result) { dom_characterdata *cdata = (dom_characterdata *)node; return dom_characterdata_get_data(cdata, result); } dom_exception _dom_characterdata_set_text_content(dom_node_internal *node, dom_string *content) { dom_characterdata *cdata = (dom_characterdata *)node; return dom_characterdata_set_data(cdata, content); } /*----------------------------------------------------------------------*/ /* The protected virtual functions of Node, see core/node.h for details */ void _dom_characterdata_destroy(struct dom_node_internal *node) { assert("Should never be here" == NULL); UNUSED(node); } /* The copy constructor of this class */ dom_exception _dom_characterdata_copy(dom_node_internal *old, dom_node_internal **copy) { dom_characterdata *new_node; dom_exception err; new_node = malloc(sizeof(dom_characterdata)); if (new_node == NULL) return DOM_NO_MEM_ERR; err = dom_characterdata_copy_internal(old, new_node); if (err != DOM_NO_ERR) { free(new_node); return err; } *copy = (dom_node_internal *) new_node; return DOM_NO_ERR; } dom_exception _dom_characterdata_copy_internal(dom_characterdata *old, dom_characterdata *new) { return dom_node_copy_internal(old, new); }
396442.c
/* Driver for the Infinite Noise Multiplier USB stick */ // Required to include clock_gettime #define _POSIX_C_SOURCE 200809L #include <stdlib.h> #include <share.h> #include <stdint.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <time.h> #include "VisualStudio\ftdi\ftd2xx.h" #include "infnoise.h" #include "Keccak\KeccakF-1600-interface.h" // Pipes in Windows basically don't work, so if you want output from a program to redirect to a file // you are forced to write to the file directly, rather than do infnoise > foo. FILE *outFile; // Convert an address value 0 to 15 to an 8-bit value using ADDR0 .. ADDR3. static uint8_t makeAddress(uint8_t addr) { uint8_t value = 0; if(addr & 1) { value |= 1 << ADDR0; } if(addr & 2) { value |= 1 << ADDR1; } if(addr & 4) { value |= 1 << ADDR2; } if(addr & 8) { value |= 1 << ADDR3; } return value; } // Extract a value form 0 to 15 from the ADDR0 .. ADDR3 bits. static uint8_t extractAddress(uint8_t value) { uint8_t addr = 0; if(value & (1 << ADDR0)) { addr |= 1; } if(value & (1 << ADDR1)) { addr |= 2; } if(value & (1 << ADDR2)) { addr |= 4; } if(value & (1 << ADDR3)) { addr |= 8; } return addr; } // Extract the INM output from the data received. Basically, either COMP1 or COMP2 // changes, not both, so alternate reading bits from them. We get 1 INM bit of output // per byte read. Feed bits from the INM to the health checker. Return the expected // bits of entropy. static uint32_t extractBytes(uint8_t *bytes, uint8_t *inBuf, bool raw) { inmClearEntropyLevel(); //printf("New batch\n"); uint32_t i; for(i = 0; i < BUFLEN/8; i++) { uint32_t j; uint8_t byte = 0; for(j = 0; j < 8; j++) { //printf("%x ", inBuf[i*8 + j] & ~MASK); uint8_t val = inBuf[i*8 + j]; uint8_t evenBit = (val >> COMP2) & 1; uint8_t oddBit = (val >> COMP1) & 1; bool even = j & 1; // Use the even bit if j is odd uint8_t bit = even? oddBit : evenBit; byte = (byte << 1) | bit; // This is a good place to feed the bit from the INM to the health checker. uint8_t addr = extractAddress(val); //printf("Address: %u, adding evenBit:%u oddBit:%u even:%u\n", addr, evenBit, oddBit, even); if(!inmHealthCheckAddBit(evenBit, oddBit, even, addr)) { fputs("Health check of Infinite Noise Multiplier failed!\n", stderr); exit(1); } } //printf("extracted byte:%x\n", byte); bytes[i] = byte; } return inmGetEntropyLevel(); } // Write the bytes to either stdout, or /dev/random. Use the lower of the measured // entropy and the provable lower bound on average entropy. static void outputBytes(uint8_t *bytes, uint32_t length, uint32_t entropy, bool writeDevRandom) { if(entropy > inmExpectedEntropyPerBit*BUFLEN/INM_ACCURACY) { entropy = (uint32_t)(inmExpectedEntropyPerBit*BUFLEN/INM_ACCURACY); } if(!writeDevRandom) { if(fwrite(bytes, 1, length, outFile) != length) { fputs("Unable to write output from Infinite Noise Multiplier\n", stderr); exit(1); } fflush(outFile); } else { fprintf(stderr, "/dev/random not supported in Windows"); exit(1); } } // Whiten the output, if requested, with a Keccak sponge. Output bytes only if the health // checker says it's OK. Using outputMultiplier > 1 is a nice way to generate a lot more // cryptographically secure pseudo-random data than the INM generates. This allows a user // to generate hundreds of MiB per second if needed, for use as cryptogrpahic keys. static void processBytes(uint8_t *keccakState, uint8_t *bytes, uint32_t entropy, bool raw, bool writeDevRandom, uint32_t outputMultiplier) { if(raw) { // In raw mode, we just output raw data from the INM. outputBytes(bytes, BUFLEN/8, entropy, writeDevRandom); return; } // Note that BUFLEN has to be less than 1600 by enough to make the sponge secure, // since outputting all 1600 bits would tell an attacker the Keccak state, allowing // him to predict any further output, when outputMultiplier > 1, until the next call // to processBytes. All 512 bits are absorbed before sqeezing data out to insure that // we instantly recover (reseed) from a state compromise, which is when an attacker // gets a snapshot of the keccak state. BUFLEN must be a multiple of 64, since // Keccak-1600 uses 64-bit "lanes". KeccakAbsorb(keccakState, bytes, BUFLEN/64); uint8_t dataOut[16*8]; while(outputMultiplier > 0) { // Write up to 1024 bits at a time. uint32_t numLanes = 16; if(outputMultiplier < 4) { numLanes = outputMultiplier*4; } KeccakExtract(keccakState, dataOut, numLanes); // Extract does not do a permute, so do it here. KeccakPermutation(keccakState); uint32_t entropyThisTime = entropy; if(entropyThisTime > numLanes*64) { entropyThisTime = numLanes*64; } outputBytes(dataOut, numLanes*8, entropyThisTime, writeDevRandom); outputMultiplier -= numLanes/4; entropy -= entropyThisTime; } } // Initialize the Infinite Noise Multiplier USB ineterface. static bool initializeUSB(FT_HANDLE *ftdic, char **message) { *message = NULL; // Open FTDI device based on FT240X vendor & product IDs if (FT_Open(0, ftdic) != FT_OK) { *message = "Can't find Infinite Noise Multiplier\n"; return false; } // Set high baud rate if (FT_SetBaudRate(*ftdic, 30000) != FT_OK) { *message = "Setting baud rate failed\n"; return false; } // Enable syncrhonous bitbang mode if (FT_SetBitMode(*ftdic, MASK, BITMODE_SYNCBB) != FT_OK) { *message = "Can't enable bit-bang mode\n"; return false; } // Just test to see that we can write and read. uint8_t buf[64] = {0,}; uint32_t bytesWritten; if(FT_Write(*ftdic, buf, 64, &bytesWritten) != FT_OK || bytesWritten != 64) { *message = "USB write failed\n"; return false; } uint32_t bytesRead; if(FT_Read(*ftdic, buf, 64, &bytesRead) != FT_OK || bytesRead != 64) { *message = "USB read failed\n"; return false; } return true; } /* // Return the differnece in the times as a double in microseconds. static double diffTime(struct timespec *start, struct timespec *end) { uint32_t seconds = end->tv_sec - start->tv_sec; int32_t nanoseconds = end->tv_nsec - start->tv_nsec; return seconds*1e6 + nanoseconds/1000.0; } */ int main(int argc, char **argv) { FT_HANDLE ftdic; bool raw = false; bool debug = false; bool writeDevRandom = false; bool noOutput = false; uint32_t outputMultiplier = 2; uint32_t xArg; // Process arguments for(xArg = 1; xArg < (uint32_t)(argc-1); xArg++) { if(!strcmp(argv[xArg], "--raw")) { raw = true; } else if(!strcmp(argv[xArg], "--debug")) { debug = true; } else if(!strcmp(argv[xArg], "--dev-random")) { writeDevRandom = true; } else if(!strcmp(argv[xArg], "--no-output")) { noOutput = true; } else if(!strcmp(argv[xArg], "--multiplier") && xArg+1 < (uint32_t)argc) { xArg++; outputMultiplier = atoi(argv[xArg]); if(outputMultiplier == 0) { fputs("Multiplier must be > 0\n", stderr); return 1; } } else { fputs("Usage: infnoise [options] outFile\n" "Options are:\n" " --debug - turn on some debug output\n" " --dev-random - write entropy to /dev/random instead of stdout\n" " --raw - do not whiten the output\n" " --multiplier <value> - write 256 bits * value for each 512 bits written to\n" " the Keccak sponge\n" " --no-output - do not write random output data\n", stderr); return 1; } } if (argc < 2) { fprintf(stderr, "No output file specified\n"); return 1; } outFile = _fsopen(argv[xArg], "wb", _SH_DENYWR); if(outFile == NULL) { fprintf(stderr, "Unable to open file %s\n", argv[xArg]); return 1; } /* if(writeDevRandom) { inmWriteEntropyStart(BUFLEN/8, debug); } */ if(!inmHealthCheckStart(PREDICTION_BITS, DESIGN_K, debug)) { fputs("Can't initialize health checker\n", stderr); return 1; } uint8_t keccakState[KeccakPermutationSizeInBytes]; KeccakInitializeState(keccakState); char *message; if(!initializeUSB(&ftdic, &message)) { // Sometimes have to do it twice - not sure why //ftdi_usb_close(&ftdic); if(!initializeUSB(&ftdic, &message)) { fputs(message, stderr); return 1; } } // Endless loop: set SW1EN and SW2EN alternately uint32_t i; uint8_t outBuf[BUFLEN], inBuf[BUFLEN]; for(i = 0; i < BUFLEN; i++) { // Alternate Ph1 and Ph2 - maybe should have both off in between outBuf[i] = i & 1? (1 << SWEN2) : (1 << SWEN1); outBuf[i] |= makeAddress(i & 0xf); } uint64_t good = 0, bad = 0; while(true) { /* struct timespec start; clock_gettime(CLOCK_REALTIME, &start); */ uint32_t numBytes; if(FT_Write(ftdic, outBuf, BUFLEN, &numBytes) != FT_OK || numBytes != BUFLEN) { fputs("USB write failed\n", stderr); return -1; } if(FT_Read(ftdic, inBuf, BUFLEN, &numBytes) != FT_OK || numBytes != BUFLEN) { fputs("USB read failed\n", stderr); return -1; } /* struct timespec end; clock_gettime(CLOCK_REALTIME, &end); uint32_t us = diffTime(&start, &end); //printf("diffTime:%u us\n", us); */ // if(us <= MAX_MICROSEC_FOR_SAMPLES) { uint8_t bytes[BUFLEN/8]; uint32_t entropy = extractBytes(bytes, inBuf, raw); if(!noOutput && inmHealthCheckOkToUseData() && inmEntropyOnTarget(entropy, BUFLEN)) { processBytes(keccakState, bytes, entropy, raw, writeDevRandom, outputMultiplier); } good++; /* } else { bad++; } */ //if(((good + bad) & 0xff) == 0) { //printf("Good %lu, bad %lu\n", good, bad); //} fflush(stdout); fflush(stderr); } return 0; }
499349.c
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2005 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2008 UT-Battelle, LLC. All rights reserved. * Copyright (c) 2012 Los Alamos National Security, LLC. All rights * reserved. * Copyright (c) 2013 Sandia National Laboratories. All rights reserved. * Copyright (c) 2014 Bull SAS. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "opal_config.h" #include "opal/constants.h" #include "opal/datatype/opal_convertor.h" #include "btl_portals4.h" int mca_btl_portals4_send(struct mca_btl_base_module_t* btl_base, struct mca_btl_base_endpoint_t* endpoint, struct mca_btl_base_descriptor_t* descriptor, mca_btl_base_tag_t tag) { struct mca_btl_portals4_module_t* portals4_btl = (struct mca_btl_portals4_module_t*) btl_base; mca_btl_portals4_frag_t *frag = (mca_btl_portals4_frag_t*) descriptor; ptl_match_bits_t match_bits, msglen_type; ptl_size_t put_length; int64_t offset; ptl_handle_md_t md_h; void *base; int ret; frag->endpoint = endpoint; frag->hdr.tag = tag; put_length = frag->segments[0].base.seg_len; if (put_length > portals4_btl->super.btl_eager_limit) msglen_type = BTL_PORTALS4_LONG_MSG; else msglen_type = BTL_PORTALS4_SHORT_MSG; BTL_PORTALS4_SET_SEND_BITS(match_bits, 0, 0, tag, msglen_type); opal_btl_portals4_get_md(frag->segments[0].base.seg_addr.pval, &md_h, &base, portals4_btl); offset = (ptl_size_t) ((char*) frag->segments[0].base.seg_addr.pval - (char*) base); /* reserve space in the event queue for rdma operations immediately */ while (OPAL_THREAD_ADD32(&portals4_btl->portals_outstanding_ops, 1) > portals4_btl->portals_max_outstanding_ops) { OPAL_THREAD_ADD32(&portals4_btl->portals_outstanding_ops, -1); OPAL_OUTPUT_VERBOSE((90, opal_btl_base_framework.framework_output, "Call to mca_btl_portals4_component_progress (4)\n")); mca_btl_portals4_component_progress(); } OPAL_OUTPUT_VERBOSE((90, opal_btl_base_framework.framework_output, "mca_btl_portals4_send: Incrementing portals_outstanding_ops=%d\n", portals4_btl->portals_outstanding_ops)); OPAL_OUTPUT_VERBOSE((50, opal_btl_base_framework.framework_output, "PtlPut frag=%p rank=%x pid=%x tag=%x len=%ld match_bits=%lx\n", (void*)frag, endpoint->ptl_proc.rank, endpoint->ptl_proc.phys.pid, tag, put_length, (uint64_t)match_bits)); ret = PtlPut(md_h, (ptl_size_t) offset, put_length, /* fragment length */ (mca_btl_portals4_component.portals_need_ack ? PTL_ACK_REQ : PTL_NO_ACK_REQ), endpoint->ptl_proc, portals4_btl->recv_idx, match_bits, /* match bits */ 0, /* remote offset - not used */ (void *) frag, /* user ptr */ tag); /* hdr_data: tag */ if (ret != PTL_OK) { opal_output(opal_btl_base_framework.framework_output, "mca_btl_portals4_send: PtlPut failed with error %d", ret); return OPAL_ERROR; } OPAL_OUTPUT_VERBOSE((90, opal_btl_base_framework.framework_output, "PtlPut frag=%p rank=%x pid=%x tag=%x addr=%p len=%ld match_bits=%lx\n", (void*)frag, endpoint->ptl_proc.rank, endpoint->ptl_proc.phys.pid, tag, (void *)offset, put_length, (uint64_t)match_bits)); return OPAL_SUCCESS; } /* NOT IMPLEMENTED */ int mca_btl_portals4_sendi(struct mca_btl_base_module_t* btl_base, struct mca_btl_base_endpoint_t* endpoint, struct opal_convertor_t* convertor, void* header, size_t header_size, size_t payload_size, uint8_t order, uint32_t flags, mca_btl_base_tag_t tag, mca_btl_base_descriptor_t** des) { opal_output(opal_btl_base_framework.framework_output, "mca_btl_portals_sendi is not implemented"); BTL_ERROR(("mca_btl_portals_sendi is not implemented")); return OPAL_SUCCESS; }
676959.c
/** * MADE BY SELCUK COSKUN 041801079 * ASSEMBLY TO MACHINE CODE ASSEMBLER * * COMP206 DUAL CORE CPU PROJECT * THIS CODE TAKES AN ASSEMBLY TEXT FILE AND CONVERTS IT INTO TWO SEPERATE TEXT * FILES TO BE UTILIZED BY THE DUAL CORE CPU MADE IN LOGISIM * * */ #include <stdio.h> #include <string.h> #include <ctype.h> #define NEG_FILTER 0x00000FFF char *op_codes_str[16] = { "BRZ", "BRN", "LDI", "LDM", "STR", "XOR", "NOT", "AND", "ORR", "ADD", "SUB", "MUL", "DIV", "NEG", "LSL", "LSR" }; int main() { printf("COMP206 - Dual Core Assembler\n\n"); FILE* fin; FILE* fcore0; FILE* fcore1; char buff[255]; fin = fopen("ASM.txt", "r"); //INPUT fcore0 = fopen("ASCII0.txt", "w"); //OUTPUT FOR CORE0 fcore1 = fopen("ASCII1.txt", "w"); //OUTPUT FOR CORE1 fprintf(fcore0, "v2.0 raw\n"); fprintf(fcore1, "v2.0 raw\n"); printf("Reading assembly file as....\n\n"); while (fgets(buff, 255, (FILE*)fin)) { int instruction = 0; char op[3]; char file_con; int y, x; /* * CMU 1 YYYYYYYYYYYY XXXXXXXXXXXX * CPU 0 00000000PPPP YYYYYYYYYYYY * */ if (strstr(buff, "MOV")) { sscanf(buff, "%s %s %d %d", op, &file_con, &y, &x); printf("%s %c %d %d\n", op, file_con, y, x); y &= NEG_FILTER; x &= NEG_FILTER; instruction = 0x1000000; instruction |= y << 12 | x; printf("\t %X\n", instruction); } else { sscanf(buff, "%s %s %d", op, &file_con, &y); printf("%s %c %d\n", op, file_con, y); int i = 0; for (; i < 16; i++) { if (strstr(op, op_codes_str[i])) { break; } } y &= NEG_FILTER; instruction = i << 12; instruction |= y; printf("\t %X\n", instruction); } //Core0 if (file_con == '0') { fprintf(fcore0, "%X\n", instruction); } //Core 1 if (file_con == '1') { fprintf(fcore1, "%X\n", instruction); } //Operation is for Both Cores, write to both files. if (file_con == 'X' || file_con == 'x') { fprintf(fcore0, "%X\n", instruction); fprintf(fcore1, "%X\n", instruction); } } printf("\n\nASCII file for Core #0 created as...'ASCII0.txt'...\n"); printf("\nASCII file for Core #1 created as...'ASCII1.txt'...\n\n"); //Close file pointers fclose(fin); fclose(fcore0); fclose(fcore1); return 0; }
478587.c
/* $OpenBSD: tty_tty.c,v 1.8 2003/09/23 16:51:12 millert Exp $ */ /* $NetBSD: tty_tty.c,v 1.13 1996/03/30 22:24:46 christos Exp $ */ /*- * Copyright (c) 1982, 1986, 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)tty_tty.c 8.2 (Berkeley) 9/23/93 */ /* * Indirect driver for controlling tty. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/ioctl.h> #include <sys/proc.h> #include <sys/tty.h> #include <sys/vnode.h> #include <sys/file.h> #include <sys/conf.h> #define cttyvp(p) ((p)->p_flag & P_CONTROLT ? (p)->p_session->s_ttyvp : NULL) /*ARGSUSED*/ int cttyopen(dev, flag, mode, p) dev_t dev; int flag, mode; struct proc *p; { struct vnode *ttyvp = cttyvp(p); int error; if (ttyvp == NULL) return (ENXIO); vn_lock(ttyvp, LK_EXCLUSIVE | LK_RETRY, p); #ifdef PARANOID /* * Since group is tty and mode is 620 on most terminal lines * and since sessions protect terminals from processes outside * your session, this check is probably no longer necessary. * Since it inhibits setuid root programs that later switch * to another user from accessing /dev/tty, we have decided * to delete this test. (mckusick 5/93) */ error = VOP_ACCESS(ttyvp, (flag&FREAD ? VREAD : 0) | (flag&FWRITE ? VWRITE : 0), p->p_ucred, p); if (!error) #endif /* PARANOID */ error = VOP_OPEN(ttyvp, flag, NOCRED, p); VOP_UNLOCK(ttyvp, 0, p); return (error); } /*ARGSUSED*/ int cttyread(dev, uio, flag) dev_t dev; struct uio *uio; int flag; { struct proc *p = uio->uio_procp; register struct vnode *ttyvp = cttyvp(uio->uio_procp); int error; if (ttyvp == NULL) return (EIO); vn_lock(ttyvp, LK_EXCLUSIVE | LK_RETRY, p); error = VOP_READ(ttyvp, uio, flag, NOCRED); VOP_UNLOCK(ttyvp, 0, p); return (error); } /*ARGSUSED*/ int cttywrite(dev, uio, flag) dev_t dev; struct uio *uio; int flag; { struct proc *p = uio->uio_procp; register struct vnode *ttyvp = cttyvp(uio->uio_procp); int error; if (ttyvp == NULL) return (EIO); vn_lock(ttyvp, LK_EXCLUSIVE | LK_RETRY, p); error = VOP_WRITE(ttyvp, uio, flag, NOCRED); VOP_UNLOCK(ttyvp, 0, p); return (error); } /*ARGSUSED*/ int cttyioctl(dev, cmd, addr, flag, p) dev_t dev; u_long cmd; caddr_t addr; int flag; struct proc *p; { struct vnode *ttyvp = cttyvp(p); if (ttyvp == NULL) return (EIO); if (cmd == TIOCSCTTY) /* XXX */ return (EINVAL); if (cmd == TIOCNOTTY) { if (!SESS_LEADER(p)) { p->p_flag &= ~P_CONTROLT; return (0); } else return (EINVAL); } return (VOP_IOCTL(ttyvp, cmd, addr, flag, NOCRED, p)); } /*ARGSUSED*/ int cttypoll(dev, events, p) dev_t dev; int events; struct proc *p; { struct vnode *ttyvp = cttyvp(p); if (ttyvp == NULL) /* try operation to get EOF/failure */ return (seltrue(dev, events, p)); return (VOP_POLL(ttyvp, events, p)); }
822002.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2012, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H #include <netinet/in.h> #endif #ifdef HAVE_NETDB_H #include <netdb.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef __VMS #include <in.h> #include <inet.h> #endif #ifdef HAVE_PROCESS_H #include <process.h> #endif #include "urldata.h" #include "sendf.h" #include "hostip.h" #include "hash.h" #include "share.h" #include "strerror.h" #include "url.h" #include "inet_pton.h" #include "connect.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /*********************************************************************** * Only for ipv6-enabled builds **********************************************************************/ #ifdef CURLRES_IPV6 #if defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO) /* These are strictly for memory tracing and are using the same style as the * family otherwise present in memdebug.c. I put these ones here since they * require a bunch of structs I didn't want to include in memdebug.c */ /* * For CURLRES_ARS, this should be written using ares_gethostbyaddr() * (ignoring the fact c-ares doesn't return 'serv'). */ int curl_dogetnameinfo(GETNAMEINFO_QUAL_ARG1 GETNAMEINFO_TYPE_ARG1 sa, GETNAMEINFO_TYPE_ARG2 salen, char *host, GETNAMEINFO_TYPE_ARG46 hostlen, char *serv, GETNAMEINFO_TYPE_ARG46 servlen, GETNAMEINFO_TYPE_ARG7 flags, int line, const char *source) { int res = (getnameinfo)(sa, salen, host, hostlen, serv, servlen, flags); if(0 == res) /* success */ curl_memlog("GETNAME %s:%d getnameinfo()\n", source, line); else curl_memlog("GETNAME %s:%d getnameinfo() failed = %d\n", source, line, res); return res; } #endif /* defined(CURLDEBUG) && defined(HAVE_GETNAMEINFO) */ /* * Curl_ipv6works() returns TRUE if ipv6 seems to work. */ bool Curl_ipv6works(void) { /* the nature of most system is that IPv6 status doesn't come and go during a program's lifetime so we only probe the first time and then we have the info kept for fast re-use */ static int ipv6_works = -1; if(-1 == ipv6_works) { /* probe to see if we have a working IPv6 stack */ curl_socket_t s = socket(PF_INET6, SOCK_DGRAM, 0); if(s == CURL_SOCKET_BAD) /* an ipv6 address was requested but we can't get/use one */ ipv6_works = 0; else { ipv6_works = 1; Curl_closesocket(NULL, s); } } return (ipv6_works>0)?TRUE:FALSE; } /* * Curl_ipvalid() checks what CURL_IPRESOLVE_* requirements that might've * been set and returns TRUE if they are OK. */ bool Curl_ipvalid(struct connectdata *conn) { if(conn->ip_version == CURL_IPRESOLVE_V6) return Curl_ipv6works(); return TRUE; } #if defined(CURLRES_SYNCH) #ifdef DEBUG_ADDRINFO static void dump_addrinfo(struct connectdata *conn, const Curl_addrinfo *ai) { printf("dump_addrinfo:\n"); for(; ai; ai = ai->ai_next) { char buf[INET6_ADDRSTRLEN]; printf(" fam %2d, CNAME %s, ", ai->ai_family, ai->ai_canonname ? ai->ai_canonname : "<none>"); if(Curl_printable_address(ai, buf, sizeof(buf))) printf("%s\n", buf); else printf("failed; %s\n", Curl_strerror(conn, SOCKERRNO)); } } #else #define dump_addrinfo(x,y) Curl_nop_stmt #endif /* * Curl_getaddrinfo() when built ipv6-enabled (non-threading and * non-ares version). * * Returns name information about the given hostname and port number. If * successful, the 'addrinfo' is returned and the forth argument will point to * memory we need to free after use. That memory *MUST* be freed with * Curl_freeaddrinfo(), nothing else. */ Curl_addrinfo *Curl_getaddrinfo(struct connectdata *conn, const char *hostname, int port, int *waitp) { struct addrinfo hints; Curl_addrinfo *res; int error; char sbuf[NI_MAXSERV]; char *sbufptr = NULL; char addrbuf[128]; int pf; struct SessionHandle *data = conn->data; *waitp = 0; /* synchronous response only */ /* * Check if a limited name resolve has been requested. */ switch(conn->ip_version) { case CURL_IPRESOLVE_V4: pf = PF_INET; break; case CURL_IPRESOLVE_V6: pf = PF_INET6; break; default: pf = PF_UNSPEC; break; } if((pf != PF_INET) && !Curl_ipv6works()) /* the stack seems to be a non-ipv6 one */ pf = PF_INET; memset(&hints, 0, sizeof(hints)); hints.ai_family = pf; hints.ai_socktype = conn->socktype; if((1 == Curl_inet_pton(AF_INET, hostname, addrbuf)) || (1 == Curl_inet_pton(AF_INET6, hostname, addrbuf))) { /* the given address is numerical only, prevent a reverse lookup */ hints.ai_flags = AI_NUMERICHOST; } if(port) { snprintf(sbuf, sizeof(sbuf), "%d", port); sbufptr=sbuf; } error = Curl_getaddrinfo_ex(hostname, sbufptr, &hints, &res); if(error) { infof(data, "getaddrinfo(3) failed for %s:%d\n", hostname, port); return NULL; } dump_addrinfo(conn, res); return res; } #endif /* CURLRES_SYNCH */ #endif /* CURLRES_IPV6 */
805744.c
/*====================================================================* * * Copyright (c) 2011, 2012, Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL * THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * *--------------------------------------------------------------------*/ /*====================================================================* * * qca_framing.c * * Atheros ethernet framing. Every Ethernet frame is surrounded * by an atheros frame while transmitted over a serial channel; * *--------------------------------------------------------------------*/ #include <linux/kernel.h> #include <linux/if_ether.h> #include "qca_framing.h" /*====================================================================* * * QcaFrmCreateHeader * * Fills a provided buffer with the Atheros frame header. * * Return: The number of bytes written in header. * *--------------------------------------------------------------------*/ int32_t QcaFrmCreateHeader(uint8_t *buf, uint16_t len) { len = __cpu_to_le16(len); buf[0] = 0xAA; buf[1] = 0xAA; buf[2] = 0xAA; buf[3] = 0xAA; buf[4] = (uint8_t)((len >> 0) & 0xFF); buf[5] = (uint8_t)((len >> 8) & 0xFF); buf[6] = 0; buf[7] = 0; return QCAFRM_HEADER_LEN; } /*====================================================================* * * QcaFrmCreateFooter * * Fills a provided buffer with the Atheros frame footer. * * Return: The number of bytes written in footer. * *--------------------------------------------------------------------*/ int32_t QcaFrmCreateFooter(uint8_t *buf) { buf[0] = 0x55; buf[1] = 0x55; return QCAFRM_FOOTER_LEN; } /*====================================================================* * * QcaFrmFsmInit * * Initialize the framing handle. To be called at initialization for new QcaFrmHdl allocated. * *--------------------------------------------------------------------*/ void QcaFrmFsmInit(QcaFrmHdl *frmHdl) { frmHdl->state = QCAFRM_WAIT_AA1; } /*====================================================================* * * QcaFrmFsmDecode * * Gather received bytes and try to extract a full ethernet frame by following a simple state machine. * * Return: QCAFRM_GATHER No ethernet frame fully received yet. * QCAFRM_NOHEAD Header expected but not found. * QCAFRM_INVLEN Atheros frame length is invalid * QCAFRM_NOTAIL Footer expected but not found. * > 0 Number of byte in the fully received Ethernet frame * *--------------------------------------------------------------------*/ int32_t QcaFrmFsmDecode(QcaFrmHdl *frmHdl, uint8_t *buf, uint16_t buf_len, uint8_t recvByte) { int32_t ret = QCAFRM_GATHER; uint16_t len; switch(frmHdl->state) { /* 4 bytes header pattern */ case QCAFRM_WAIT_AA1: case QCAFRM_WAIT_AA2: case QCAFRM_WAIT_AA3: case QCAFRM_WAIT_AA4: if (recvByte != 0xAA) { ret = QCAFRM_NOHEAD; frmHdl->state = QCAFRM_WAIT_AA1; } else { frmHdl->state--; } break; /* 2 bytes length. */ /* Borrow offset field to hold length for now. */ case QCAFRM_WAIT_LEN_BYTE0: frmHdl->offset = recvByte; frmHdl->state--; break; case QCAFRM_WAIT_LEN_BYTE1: frmHdl->offset = frmHdl->offset | (recvByte << 8); frmHdl->state--; break; case QCAFRM_WAIT_RSVD_BYTE1: frmHdl->state--; break; case QCAFRM_WAIT_RSVD_BYTE2: frmHdl->state--; len = frmHdl->offset; if (len > buf_len || len < QCAFRM_ETHMINLEN) { ret = QCAFRM_INVLEN; frmHdl->state = QCAFRM_WAIT_AA1; } else { frmHdl->state = (QcaFrmState)(len + 1); /* Remaining number of bytes. */ frmHdl->offset = 0; } break; default: /* Receiving Ethernet frame itself. */ buf[frmHdl->offset++] = recvByte; frmHdl->state--; break; case QCAFRM_WAIT_551: if (recvByte != 0x55) { ret = QCAFRM_NOTAIL; frmHdl->state = QCAFRM_WAIT_AA1; } else { frmHdl->state--; } break; case QCAFRM_WAIT_552: if (recvByte != 0x55) { ret = QCAFRM_NOTAIL; frmHdl->state = QCAFRM_WAIT_AA1; } else { ret = frmHdl->offset; /* Frame is fully received. */ frmHdl->state = QCAFRM_WAIT_AA1; } break; } return ret; } /*====================================================================* * *--------------------------------------------------------------------*/
848713.c
// Minimal struct - array of struct - near pointer math indexing struct Point { byte x; byte y; }; struct Point points[4]; const byte SIZEOF_POINT = 2; const byte OFFS_X = 0; const byte OFFS_Y = 1; void main() { for( byte i: 0..3) { *((byte*)points+OFFS_X+i*SIZEOF_POINT) = i; // points[i].x = i; *((byte*)points+OFFS_Y+i*SIZEOF_POINT) = i+4; // points[i].y = i+4; } byte* const SCREEN = (char*)0x0400; for( byte i: 0..3) { SCREEN[i] = *((byte*)points+OFFS_X+i*SIZEOF_POINT); // SCREEN[i] = points[i].x; (SCREEN+40)[i] = *((byte*)points+OFFS_Y+i*SIZEOF_POINT); // (SCREEN+40)[i] = points[i].y; } }
113943.c
/* See LICENSE file for copyright and license details. */ #include <stdio.h> #include <stdlib.h> #include "../util.h" const char * load_avg(void) { double avgs[1]; if (getloadavg(avgs, 1) < 1) { warn("getloadavg: Failed to obtain load average"); return NULL; } return bprintf("%.2f", avgs[0]); }
412296.c
/****************************************************************************** * Copyright (c) 2011, Universal Air Ltd. All rights reserved. * Source and binaries are released under the BSD 3-Clause license * See readme_forebrain.txt files for the text of the license ******************************************************************************/ #include "LPC13xx.h" #include "uafunc.h" #include "config.h" #define WEAK_ALIAS(f) __attribute__ ((weak, alias (#f))); #define WEAK __attribute__ ((weak)) // *** some locations provided by the linker extern void* __stack_top; extern unsigned long _etext; extern unsigned long __data; extern unsigned long __edata; extern unsigned long __bss; extern unsigned long __ebss; // *** these are the user's functions extern WEAK int main(void); extern WEAK int setup(void); extern WEAK int loop(void); // *** GeneralFault function will flash the LEDs when there is a fault void GeneralFault(void) { volatile unsigned int i; LPC_GPIO3->DIR |= 0b1111; while(1) { for(i=0; i<1000000; i++); LPC_GPIO3->DATA = 0b1100; for(i=0; i<1000000; i++); LPC_GPIO3->DATA = 0b0011; } } void EmptyFunction(void) { return; } // *** Alias interrupt handlers to the empty function in case the interrupt // *** is enabled and no interrupt function is supplied void I2C_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void TIMER16_0_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void TIMER16_1_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void TIMER32_0_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void TIMER32_1_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void SSP_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void UART_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void USB_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void USB_FIQHandler(void) WEAK_ALIAS(EmptyFunction); void ADC_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void WDT_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void BOD_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void FMC_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void PIOINT3_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void PIOINT2_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void PIOINT1_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void PIOINT0_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void WAKEUP_IRQHandler(void) WEAK_ALIAS(EmptyFunction); void SysTick_Handler(void) WEAK_ALIAS(EmptyFunction); void NMI_Handler(void) WEAK_ALIAS(GeneralFault); void HardFault_Handler(void) WEAK_ALIAS(GeneralFault); void MemManage_Handler(void) WEAK_ALIAS(GeneralFault); void BusFault_Handler(void) WEAK_ALIAS(GeneralFault); void UsageFault_Handler(void) WEAK_ALIAS(GeneralFault); void SVCall_Handler(void) WEAK_ALIAS(GeneralFault); void DebugMon_Handler(void) WEAK_ALIAS(GeneralFault); void PendSV_Handler(void) WEAK_ALIAS(GeneralFault); // *** This is the startup code void Reset_Handler(void) { unsigned long *pSrc, *pDest; unsigned int i; // Initialise RAM pSrc = &_etext; for(pDest=&__data; pDest<&__edata; ) { *pDest++ = *pSrc++; } for(pDest=&__bss; pDest<&__ebss; ) { *pDest++ = 0; } // Initialise the uninitialised variable described in section 19.2.1 of UM10365 *((uint32_t *)(0x10000054)) = 0x0; #if STARTUP_DELAY for(i=0; i<STARTUP_DELAY; i++); #endif // Set clock mode, DEFAULT_CLOCK is defined in config.h, and the default behaviour // is to set the clock to 72MHz from the external crystal. Using defines here to // reduce code space #if DEFAULT_CLOCK == XTAL LPC_SYSCON->PDRUNCFG &= ~(1 << 5); // Power up system oscillator for(i = 0; i < 100; i++); // Brief delay LPC_SYSCON->SYSOSCCTRL = 0; // System oscillator setup - not bypass, 1-20MHz range LPC_SYSCON->SYSPLLCLKSEL = 0x01; // Select system oscillator as PLL source LPC_SYSCON->SYSPLLCLKUEN = 0x00; // Update clock source LPC_SYSCON->SYSPLLCLKUEN = 0x01; while(!(LPC_SYSCON->SYSPLLCLKUEN & 0x01)); // Wait for update LPC_SYSCON->MAINCLKSEL = 0x01; // Select sys osc as main clock source LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update LPC_SYSCON->SYSPLLCTRL = 0x25; // Select PLL divider to 6 (12MHz - 72MHz) LPC_SYSCON->PDRUNCFG &= ~(1 << 7); // Power up PLL while(!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock LPC_SYSCON->MAINCLKSEL = 0x03; // Select PLL as main clock source LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update #elif DEFAULT_CLOCK == IRC72 LPC_SYSCON->PDRUNCFG &= ~((1<<0) | (1<<1)); // Power up IRC oscillator for(i = 0; i < 100; i++); // Brief delay LPC_SYSCON->MAINCLKSEL = 0x00; // Select IRC as main clock source LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update LPC_SYSCON->SYSPLLCLKSEL = 0x00; // Select IRC as PLL source LPC_SYSCON->SYSPLLCLKUEN = 0x00; // Update clock source LPC_SYSCON->SYSPLLCLKUEN = 0x01; while(!(LPC_SYSCON->SYSPLLCLKUEN & 0x01)); // Wait for update LPC_SYSCON->SYSPLLCTRL = 0x25; // Select PLL divider to 6 (12MHz - 72MHz) LPC_SYSCON->PDRUNCFG &= ~(1<<7); // Power up PLL while(!(LPC_SYSCON->SYSPLLSTAT & 0x01)); // Wait for PLL lock LPC_SYSCON->MAINCLKSEL = 0x03; // Select PLL as main clock source LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update LPC_SYSCON->PDRUNCFG |= (1<<5); // Power down system oscillator #elif DEFAULT_CLOCK == IRC12 LPC_SYSCON->PDRUNCFG &= ~((1<<0) | (1<<1)); // Power up IRC oscillator for(i = 0; i < 100; i++); // Brief delay LPC_SYSCON->MAINCLKSEL = 0x00; // Select IRC as main clock source LPC_SYSCON->MAINCLKUEN = 0x00; // Update clock source LPC_SYSCON->MAINCLKUEN = 0x01; while (!(LPC_SYSCON->MAINCLKUEN & 0x01)); // Wait for clock update LPC_SYSCON->PDRUNCFG |= ((1<<5) | (1<<7)); // Power down system oscillator and IRC #endif // Set all pins to digital inputs (except P0[0] which is the reset button) #if PORT_STARTUP_INIT Port0Init(ALL & ~PIN0); Port1Init(ALL); Port2Init(ALL); Port3Init(ALL); #endif // Initialise and start the system tick timer if allowed by the SYSTICK_EN // definition in config.h, if the system tick timer is running, then the Delay() // function will use it, otherwise Delay() will use a fixed loop which is not // accurate when there are interrupts running, as any interrupt would stop the // loop and cuase the delay to be longer than expected #if SYSTICK_EN && SYSTICK_STARTUP SysTickInit(); #endif // Run the user-supplied setup() function if it exists if(setup) { setup(); } // Run the user-supplied main() function if it exists if(main) { main(); } // Loop the user-supplied setup() function if it exists if(loop) { while(1) loop(); } // Do nothing (except handle interrupts) while(1); } // *** Vector table __attribute__ ((section(".vectors"), used)) const void *vectors[] = { &__stack_top, Reset_Handler, NMI_Handler, HardFault_Handler, MemManage_Handler, BusFault_Handler, UsageFault_Handler, 0, 0, 0, 0, SVCall_Handler, DebugMon_Handler, 0, PendSV_Handler, SysTick_Handler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, WAKEUP_IRQHandler, I2C_IRQHandler, TIMER16_0_IRQHandler, TIMER16_1_IRQHandler, TIMER32_0_IRQHandler, TIMER32_1_IRQHandler, SSP_IRQHandler, UART_IRQHandler, USB_IRQHandler, USB_FIQHandler, ADC_IRQHandler, WDT_IRQHandler, BOD_IRQHandler, FMC_IRQHandler, PIOINT3_IRQHandler, PIOINT2_IRQHandler, PIOINT1_IRQHandler, PIOINT0_IRQHandler, };
966020.c
/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, [email protected], http://libtomcrypt.com */ #include "tomcrypt.h" /** @file crypt_register_prng.c Register a PRNG, Tom St Denis */ /** Register a PRNG with the descriptor table @param prng The PRNG you wish to register @return value >= 0 if successfully added (or already present), -1 if unsuccessful */ int register_prng(const struct ltc_prng_descriptor *prng) { int x; LTC_ARGCHK(prng != NULL); /* is it already registered? */ LTC_MUTEX_LOCK(&ltc_prng_mutex); for (x = 0; x < TAB_SIZE; x++) { if (XMEMCMP(&prng_descriptor[x], prng, sizeof(struct ltc_prng_descriptor)) == 0) { LTC_MUTEX_UNLOCK(&ltc_prng_mutex); return x; } } /* find a blank spot */ for (x = 0; x < TAB_SIZE; x++) { if (prng_descriptor[x].name == NULL) { XMEMCPY(&prng_descriptor[x], prng, sizeof(struct ltc_prng_descriptor)); LTC_MUTEX_UNLOCK(&ltc_prng_mutex); return x; } } /* no spot */ LTC_MUTEX_UNLOCK(&ltc_prng_mutex); return -1; } /* $Source$ */ /* $Revision: 24838 $ */ /* $Date: 2007-01-23 23:16:57 -0600 (Tue, 23 Jan 2007) $ */
941766.c
/* * libbergen/preprocessor.c * Copyright (C) 2015 Kyle Edwards <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <bergen/preprocessor.h> #include <bergen/libc.h> void pp_macro_definition_init(struct pp_macro_definition *macro, const char *name, size_t length, int have_args) { macro->name = bergen_strndup_null(name, length); macro->num_args = 0; if (have_args) { macro->args_buffer_size = 32; macro->args = bergen_malloc(sizeof(*macro->args) * macro->args_buffer_size); } else { macro->args_buffer_size = 0; macro->args = NULL; } } void pp_macro_definition_destroy(struct pp_macro_definition *macro) { size_t i; for (i = 0; i < macro->num_args; i++) bergen_free(macro->args[i]); bergen_free(macro->args); bergen_free(macro->name); } struct error *pp_macro_definition_add_arg(struct pp_macro_definition *macro, const char *name, size_t length) { size_t i; if (!macro->args) return error_create("Cannot add arguments to a macro that has no arguments"); for (i = 0; i < macro->num_args; i++) { if (length == bergen_strlen(macro->args[i]) && !bergen_strncmp(macro->args[i], name, length)) return error_create("Argument \"%s\" already exists", macro->args[i]); } if (macro->num_args >= macro->args_buffer_size) { macro->args_buffer_size *= 2; macro->args = bergen_realloc(macro->args, sizeof(*macro->args) * macro->args_buffer_size); } macro->args[macro->num_args++] = bergen_strndup_null(name, length); return NULL; } struct error *pp_macro_definition_parse(struct pp_macro_definition *macro, const char *str, size_t length) { int have_args; size_t name_length, arg_index; const char *ptr; char *buf; struct error *err; if ((ptr = bergen_memchr(str, '(', length))) { arg_index = ptr - str + 1; name_length = arg_index - 1; have_args = 1; } else { have_args = 0; name_length = length; } pp_macro_definition_init(macro, str, name_length, have_args); if (have_args) { for (;;) { if ((ptr = bergen_memchr(str + arg_index, ',', length - arg_index))) { pp_macro_definition_add_arg(macro, str + arg_index, ptr - (str + arg_index)); arg_index = ptr - str + 1; } else if ((ptr = bergen_memchr(str + arg_index, ')', length - arg_index))) { pp_macro_definition_add_arg(macro, str + arg_index, ptr - (str + arg_index)); break; } else { pp_macro_definition_destroy(macro); buf = bergen_strndup_null(str, length); err = error_create("Invalid macro definition: \"%s\"", buf); bergen_free(buf); return err; } } } return NULL; }
675782.c
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2010, Daniel Stenberg, <[email protected]>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_CRYPTO_AUTH) /* -- WIN32 approved -- */ #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <ctype.h> #include "urldata.h" #include "sendf.h" #include "rawstr.h" #include "curl_base64.h" #include "curl_md5.h" #include "http_digest.h" #include "strtok.h" #include "url.h" /* for Curl_safefree() */ #include "curl_memory.h" #include "easyif.h" /* included for Curl_convert_... prototypes */ #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> /* The last #include file should be: */ #include "memdebug.h" #define MAX_VALUE_LENGTH 256 #define MAX_CONTENT_LENGTH 1024 /* * Return 0 on success and then the buffers are filled in fine. * * Non-zero means failure to parse. */ static int get_pair(const char *str, char *value, char *content, const char **endptr) { int c; bool starts_with_quote = FALSE; bool escape = FALSE; for(c=MAX_VALUE_LENGTH-1; (*str && (*str != '=') && c--); ) *value++ = *str++; *value=0; if('=' != *str++) /* eek, no match */ return 1; if('\"' == *str) { /* this starts with a quote so it must end with one as well! */ str++; starts_with_quote = TRUE; } for(c=MAX_CONTENT_LENGTH-1; *str && c--; str++) { switch(*str) { case '\\': if(!escape) { /* possibly the start of an escaped quote */ escape = TRUE; *content++ = '\\'; /* even though this is an escape character, we still store it as-is in the target buffer */ continue; } break; case ',': if(!starts_with_quote) { /* this signals the end of the content if we didn't get a starting quote and then we do "sloppy" parsing */ c=0; /* the end */ continue; } break; case '\r': case '\n': /* end of string */ c=0; continue; case '\"': if(!escape && starts_with_quote) { /* end of string */ c=0; continue; } break; } escape = FALSE; *content++ = *str; } *content=0; *endptr = str; return 0; /* all is fine! */ } /* Test example headers: WWW-Authenticate: Digest realm="testrealm", nonce="1053604598" Proxy-Authenticate: Digest realm="testrealm", nonce="1053604598" */ CURLdigest Curl_input_digest(struct connectdata *conn, bool proxy, const char *header) /* rest of the *-authenticate: header */ { char *token = NULL; char *tmp = NULL; bool foundAuth = FALSE; bool foundAuthInt = FALSE; struct SessionHandle *data=conn->data; bool before = FALSE; /* got a nonce before */ struct digestdata *d; if(proxy) { d = &data->state.proxydigest; } else { d = &data->state.digest; } /* skip initial whitespaces */ while(*header && ISSPACE(*header)) header++; if(checkprefix("Digest", header)) { header += strlen("Digest"); /* If we already have received a nonce, keep that in mind */ if(d->nonce) before = TRUE; /* clear off any former leftovers and init to defaults */ Curl_digest_cleanup_one(d); for(;;) { char value[MAX_VALUE_LENGTH]; char content[MAX_CONTENT_LENGTH]; while(*header && ISSPACE(*header)) header++; /* extract a value=content pair */ if(!get_pair(header, value, content, &header)) { if(Curl_raw_equal(value, "nonce")) { d->nonce = strdup(content); if(!d->nonce) return CURLDIGEST_NOMEM; } else if(Curl_raw_equal(value, "stale")) { if(Curl_raw_equal(content, "true")) { d->stale = TRUE; d->nc = 1; /* we make a new nonce now */ } } else if(Curl_raw_equal(value, "realm")) { d->realm = strdup(content); if(!d->realm) return CURLDIGEST_NOMEM; } else if(Curl_raw_equal(value, "opaque")) { d->opaque = strdup(content); if(!d->opaque) return CURLDIGEST_NOMEM; } else if(Curl_raw_equal(value, "qop")) { char *tok_buf; /* tokenize the list and choose auth if possible, use a temporary clone of the buffer since strtok_r() ruins it */ tmp = strdup(content); if(!tmp) return CURLDIGEST_NOMEM; token = strtok_r(tmp, ",", &tok_buf); while(token != NULL) { if(Curl_raw_equal(token, "auth")) { foundAuth = TRUE; } else if(Curl_raw_equal(token, "auth-int")) { foundAuthInt = TRUE; } token = strtok_r(NULL, ",", &tok_buf); } free(tmp); /*select only auth o auth-int. Otherwise, ignore*/ if(foundAuth) { d->qop = strdup("auth"); if(!d->qop) return CURLDIGEST_NOMEM; } else if(foundAuthInt) { d->qop = strdup("auth-int"); if(!d->qop) return CURLDIGEST_NOMEM; } } else if(Curl_raw_equal(value, "algorithm")) { d->algorithm = strdup(content); if(!d->algorithm) return CURLDIGEST_NOMEM; if(Curl_raw_equal(content, "MD5-sess")) d->algo = CURLDIGESTALGO_MD5SESS; else if(Curl_raw_equal(content, "MD5")) d->algo = CURLDIGESTALGO_MD5; else return CURLDIGEST_BADALGO; } else { /* unknown specifier, ignore it! */ } } else break; /* we're done here */ /* pass all additional spaces here */ while(*header && ISSPACE(*header)) header++; if(',' == *header) /* allow the list to be comma-separated */ header++; } /* We had a nonce since before, and we got another one now without 'stale=true'. This means we provided bad credentials in the previous request */ if(before && !d->stale) return CURLDIGEST_BAD; /* We got this header without a nonce, that's a bad Digest line! */ if(!d->nonce) return CURLDIGEST_BAD; } else /* else not a digest, get out */ return CURLDIGEST_NONE; return CURLDIGEST_FINE; } /* convert md5 chunk to RFC2617 (section 3.1.3) -suitable ascii string*/ static void md5_to_ascii(unsigned char *source, /* 16 bytes */ unsigned char *dest) /* 33 bytes */ { int i; for(i=0; i<16; i++) snprintf((char *)&dest[i*2], 3, "%02x", source[i]); } CURLcode Curl_output_digest(struct connectdata *conn, bool proxy, const unsigned char *request, const unsigned char *uripath) { /* We have a Digest setup for this, use it! Now, to get all the details for this sorted out, I must urge you dear friend to read up on the RFC2617 section 3.2.2, */ unsigned char md5buf[16]; /* 16 bytes/128 bits */ unsigned char request_digest[33]; unsigned char *md5this; unsigned char *ha1; unsigned char ha2[33];/* 32 digits and 1 zero byte */ char cnoncebuf[7]; char *cnonce; char *tmp = NULL; struct timeval now; char **allocuserpwd; const char *userp; const char *passwdp; struct auth *authp; struct SessionHandle *data = conn->data; struct digestdata *d; #ifdef CURL_DOES_CONVERSIONS CURLcode rc; /* The CURL_OUTPUT_DIGEST_CONV macro below is for non-ASCII machines. It converts digest text to ASCII so the MD5 will be correct for what ultimately goes over the network. */ #define CURL_OUTPUT_DIGEST_CONV(a, b) \ rc = Curl_convert_to_network(a, (char *)b, strlen((const char*)b)); \ if(rc != CURLE_OK) { \ free(b); \ return rc; \ } #else #define CURL_OUTPUT_DIGEST_CONV(a, b) #endif /* CURL_DOES_CONVERSIONS */ if(proxy) { d = &data->state.proxydigest; allocuserpwd = &conn->allocptr.proxyuserpwd; userp = conn->proxyuser; passwdp = conn->proxypasswd; authp = &data->state.authproxy; } else { d = &data->state.digest; allocuserpwd = &conn->allocptr.userpwd; userp = conn->user; passwdp = conn->passwd; authp = &data->state.authhost; } if(*allocuserpwd) { Curl_safefree(*allocuserpwd); *allocuserpwd = NULL; } /* not set means empty */ if(!userp) userp=""; if(!passwdp) passwdp=""; if(!d->nonce) { authp->done = FALSE; return CURLE_OK; } authp->done = TRUE; if(!d->nc) d->nc = 1; if(!d->cnonce) { /* Generate a cnonce */ now = Curl_tvnow(); snprintf(cnoncebuf, sizeof(cnoncebuf), "%06ld", (long)now.tv_sec); if(Curl_base64_encode(data, cnoncebuf, strlen(cnoncebuf), &cnonce)) d->cnonce = cnonce; else return CURLE_OUT_OF_MEMORY; } /* if the algorithm is "MD5" or unspecified (which then defaults to MD5): A1 = unq(username-value) ":" unq(realm-value) ":" passwd if the algorithm is "MD5-sess" then: A1 = H( unq(username-value) ":" unq(realm-value) ":" passwd ) ":" unq(nonce-value) ":" unq(cnonce-value) */ md5this = (unsigned char *) aprintf("%s:%s:%s", userp, d->realm, passwdp); if(!md5this) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); /* free this again */ ha1 = malloc(33); /* 32 digits and 1 zero byte */ if(!ha1) return CURLE_OUT_OF_MEMORY; md5_to_ascii(md5buf, ha1); if(d->algo == CURLDIGESTALGO_MD5SESS) { /* nonce and cnonce are OUTSIDE the hash */ tmp = aprintf("%s:%s:%s", ha1, d->nonce, d->cnonce); if(!tmp) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, tmp); /* convert on non-ASCII machines */ Curl_md5it(md5buf, (unsigned char *)tmp); free(tmp); /* free this again */ md5_to_ascii(md5buf, ha1); } /* If the "qop" directive's value is "auth" or is unspecified, then A2 is: A2 = Method ":" digest-uri-value If the "qop" value is "auth-int", then A2 is: A2 = Method ":" digest-uri-value ":" H(entity-body) (The "Method" value is the HTTP request method as specified in section 5.1.1 of RFC 2616) */ /* So IE browsers < v7 cut off the URI part at the query part when they evaluate the MD5 and some (IIS?) servers work with them so we may need to do the Digest IE-style. Note that the different ways cause different MD5 sums to get sent. Apache servers can be set to do the Digest IE-style automatically using the BrowserMatch feature: http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html#msie Further details on Digest implementation differences: http://www.fngtps.com/2006/09/http-authentication */ if(authp->iestyle && ((tmp = strchr((char *)uripath, '?')) != NULL)) { md5this = (unsigned char *)aprintf("%s:%.*s", request, (int)(tmp - (char *)uripath), uripath); } else md5this = (unsigned char *)aprintf("%s:%s", request, uripath); if(!md5this) { free(ha1); return CURLE_OUT_OF_MEMORY; } if(d->qop && Curl_raw_equal(d->qop, "auth-int")) { /* We don't support auth-int at the moment. I can't see a easy way to get entity-body here */ /* TODO: Append H(entity-body)*/ } CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); /* free this again */ md5_to_ascii(md5buf, ha2); if(d->qop) { md5this = (unsigned char *)aprintf("%s:%s:%08x:%s:%s:%s", ha1, d->nonce, d->nc, d->cnonce, d->qop, ha2); } else { md5this = (unsigned char *)aprintf("%s:%s:%s", ha1, d->nonce, ha2); } free(ha1); if(!md5this) return CURLE_OUT_OF_MEMORY; CURL_OUTPUT_DIGEST_CONV(data, md5this); /* convert on non-ASCII machines */ Curl_md5it(md5buf, md5this); free(md5this); /* free this again */ md5_to_ascii(md5buf, request_digest); /* for test case 64 (snooped from a Mozilla 1.3a request) Authorization: Digest username="testuser", realm="testrealm", \ nonce="1053604145", uri="/64", response="c55f7f30d83d774a3d2dcacf725abaca" */ if(d->qop) { *allocuserpwd = aprintf( "%sAuthorization: Digest " "username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "cnonce=\"%s\", " "nc=%08x, " "qop=\"%s\", " "response=\"%s\"", proxy?"Proxy-":"", userp, d->realm, d->nonce, uripath, /* this is the PATH part of the URL */ d->cnonce, d->nc, d->qop, request_digest); if(Curl_raw_equal(d->qop, "auth")) d->nc++; /* The nc (from RFC) has to be a 8 hex digit number 0 padded which tells to the server how many times you are using the same nonce in the qop=auth mode. */ } else { *allocuserpwd = aprintf( "%sAuthorization: Digest " "username=\"%s\", " "realm=\"%s\", " "nonce=\"%s\", " "uri=\"%s\", " "response=\"%s\"", proxy?"Proxy-":"", userp, d->realm, d->nonce, uripath, /* this is the PATH part of the URL */ request_digest); } if(!*allocuserpwd) return CURLE_OUT_OF_MEMORY; /* Add optional fields */ if(d->opaque) { /* append opaque */ tmp = aprintf("%s, opaque=\"%s\"", *allocuserpwd, d->opaque); if(!tmp) return CURLE_OUT_OF_MEMORY; free(*allocuserpwd); *allocuserpwd = tmp; } if(d->algorithm) { /* append algorithm */ tmp = aprintf("%s, algorithm=\"%s\"", *allocuserpwd, d->algorithm); if(!tmp) return CURLE_OUT_OF_MEMORY; free(*allocuserpwd); *allocuserpwd = tmp; } /* append CRLF + zero (3 bytes) to the userpwd header */ tmp = realloc(*allocuserpwd, strlen(*allocuserpwd) + 3); if(!tmp) return CURLE_OUT_OF_MEMORY; strcat(tmp, "\r\n"); *allocuserpwd = tmp; return CURLE_OK; } void Curl_digest_cleanup_one(struct digestdata *d) { if(d->nonce) free(d->nonce); d->nonce = NULL; if(d->cnonce) free(d->cnonce); d->cnonce = NULL; if(d->realm) free(d->realm); d->realm = NULL; if(d->opaque) free(d->opaque); d->opaque = NULL; if(d->qop) free(d->qop); d->qop = NULL; if(d->algorithm) free(d->algorithm); d->algorithm = NULL; d->nc = 0; d->algo = CURLDIGESTALGO_MD5; /* default algorithm */ d->stale = FALSE; /* default means normal, not stale */ } void Curl_digest_cleanup(struct SessionHandle *data) { Curl_digest_cleanup_one(&data->state.digest); Curl_digest_cleanup_one(&data->state.proxydigest); } #endif
215660.c
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <pwd.h> int main (int argc, const char *argv[]) { const uid_t uid = getuid(); struct passwd *pw_uid = getpwuid(uid); const char *name = pw_uid->pw_name; struct passwd *pw_nam = getpwnam(name); if (pw_uid->pw_gid == pw_nam->pw_gid) { printf("%lu\n", (unsigned long int) pw_uid->pw_gid); return EXIT_SUCCESS; } else { printf("%s\n", "Returns from getpwuid and getpwnam did not match!"); printf("%s: %lu\n", "getpwuid", (unsigned long int) pw_uid->pw_gid); printf("%s: %lu\n", "getpwnam", (unsigned long int) pw_nam->pw_gid); return EXIT_FAILURE; } }
232126.c
#include "drivers/screen/screen.h" #include "drivers/keyboard/keyboard.h" #include "shell.h" #include "gdt/gdt.h" #include "idt/idt.h" #include "fs/vfs.h" #include "fs/initrd/initrd.h" #include "multiboot.h" #include "drivers/serial/serial.h" #include "drivers/pci/pci.h" void find_files(){ int i = 0; struct dirent *node = 0; while ( (node = readdir_fs(fs_root, i)) != 0) { print_string("Found file "); print_string(node->name); fs_node_t *fsnode = finddir_fs(fs_root, node->name); if ((fsnode->flags&0x7) == FS_DIRECTORY) print_string("\n\t(directory)\n"); else { print_string("\n\t contents: \""); char buf[256]; uint32 sz = read_fs(fsnode, 0, 256, buf); int j; for (j = 0; j < sz; j++) print_char(buf[j]); print_string("\"\n"); } i++; } } void kernel_entry(struct multiboot *mboot_ptr) { uint32 initrd_location = *((uint32 *) mboot_ptr->mods_addr); init_vga(WHITE, BLACK); init_gdt(); print_string("GDT Initialised\n"); init_idt(); print_string("IDT Initialised\n"); serial_init(); print_string("Serial Initialised\n"); pci_init(); print_string("PCI Initialised\n"); fs_root = initialise_initrd (initrd_location); print_string("Loaded Initial RAMDISK\n"); find_files(); print_string("Welcome to SimpleOS!\nPlease enter a command\n"); print_string("Enter 'help' for commands\n"); launch_shell(0); }
352899.c
/* Copyright (c) 2019, Ameer Haj Ali (UC Berkeley), and 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "header.h" int assign[64][256]; __attribute__((noinline)) void example8 (int y) { int i,j; /* feature: support for multidimensional arrays */ for (i=0; i<64-1; i+=2) { for (j=0; j<256-1; j+=2) { assign[i][j] = y; assign[i+1][j] = y; assign[i][j+1] = y; assign[i+1][j+1] = y; } } } int main(int argc,char* argv[]){ init_memory(&assign[0][0], &assign[0][256]); BENCH("Example8", example8(8), 65536, digest_memory(&assign[0][0], &assign[0][256])); return 0; }
986566.c
/**************************************************************************** * libs/libc/locale/lib_localeconv.c * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <locale.h> #ifdef CONFIG_LIBC_LOCALE /**************************************************************************** * Private Data ****************************************************************************/ static struct lconv g_c_lconv = { ".", "", "", "", "", "", "", "", "", "", CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX, CHAR_MAX }; /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: localeconv * * Description: * locales are not supported by NuttX * * Input Parameters: * category and locale - Select the appropriate piece of the program's * locale. * ****************************************************************************/ FAR struct lconv *localeconv(void) { return &g_c_lconv; } #endif
394911.c
/* * mini-mips.c: MIPS backend for the Mono code generator * * Authors: * Mark Mason ([email protected]) * * Based on mini-ppc.c by * Paolo Molaro ([email protected]) * Dietmar Maurer ([email protected]) * * (C) 2006 Broadcom * (C) 2003 Ximian, Inc. */ #include "mini.h" #include <string.h> #include <asm/cachectl.h> #include <mono/metadata/abi-details.h> #include <mono/metadata/appdomain.h> #include <mono/metadata/debug-helpers.h> #include <mono/utils/mono-mmap.h> #include <mono/utils/mono-hwcap-mips.h> #include <mono/arch/mips/mips-codegen.h> #include "mini-mips.h" #include "cpu-mips.h" #include "trace.h" #include "ir-emit.h" #define SAVE_FP_REGS 0 #define ALWAYS_SAVE_RA 1 /* call-handler & switch currently clobber ra */ #define PROMOTE_R4_TO_R8 1 /* promote single values in registers to doubles */ #define USE_MUL 0 /* use mul instead of mult/mflo for multiply remember to update cpu-mips.md if you change this */ /* Emit a call sequence to 'v', using 'D' as a scratch register if necessary */ #define mips_call(c,D,v) do { \ guint32 _target = (guint32)(v); \ if (1 || ((v) == NULL) || ((_target & 0xfc000000) != (((guint32)(c)) & 0xfc000000))) { \ mips_load_const (c, D, _target); \ mips_jalr (c, D, mips_ra); \ } \ else { \ mips_jumpl (c, _target >> 2); \ } \ mips_nop (c); \ } while (0) enum { TLS_MODE_DETECT, TLS_MODE_FAILED, TLS_MODE_LTHREADS, TLS_MODE_NPTL }; /* This mutex protects architecture specific caches */ #define mono_mini_arch_lock() mono_mutex_lock (&mini_arch_mutex) #define mono_mini_arch_unlock() mono_mutex_unlock (&mini_arch_mutex) static mono_mutex_t mini_arch_mutex; int mono_exc_esp_offset = 0; static int tls_mode = TLS_MODE_DETECT; static int lmf_pthread_key = -1; static int monothread_key = -1; /* Whenever the host is little-endian */ static int little_endian; /* Index of ms word/register */ static int ls_word_idx; /* Index of ls word/register */ static int ms_word_idx; /* Same for offsets */ static int ls_word_offset; static int ms_word_offset; /* * The code generated for sequence points reads from this location, which is * made read-only when single stepping is enabled. */ static gpointer ss_trigger_page; /* Enabled breakpoints read from this trigger page */ static gpointer bp_trigger_page; #undef DEBUG #define DEBUG(a) if (cfg->verbose_level > 1) a #undef DEBUG #define DEBUG(a) a #undef DEBUG #define DEBUG(a) #define EMIT_SYSTEM_EXCEPTION_NAME(exc_name) \ do { \ code = mips_emit_exc_by_name (code, exc_name); \ cfg->bb_exit->max_offset += 16; \ } while (0) #define emit_linuxthreads_tls(code,dreg,key) do {\ int off1, off2; \ off1 = offsets_from_pthread_key ((key), &off2); \ g_assert_not_reached (); \ ppc_lwz ((code), (dreg), off1, ppc_r2); \ ppc_lwz ((code), (dreg), off2, (dreg)); \ } while (0); #define emit_tls_access(code,dreg,key) do { \ switch (tls_mode) { \ case TLS_MODE_LTHREADS: emit_linuxthreads_tls(code,dreg,key); break; \ default: g_assert_not_reached (); \ } \ } while (0) #define MONO_EMIT_NEW_LOAD_R8(cfg,dr,addr) do { \ MonoInst *inst; \ MONO_INST_NEW ((cfg), (inst), OP_R8CONST); \ inst->type = STACK_R8; \ inst->dreg = (dr); \ inst->inst_p0 = (void*)(addr); \ mono_bblock_add_inst (cfg->cbb, inst); \ } while (0) #define ins_is_compare(ins) ((ins) && (((ins)->opcode == OP_COMPARE) \ || ((ins)->opcode == OP_ICOMPARE) \ || ((ins)->opcode == OP_LCOMPARE))) #define ins_is_compare_imm(ins) ((ins) && (((ins)->opcode == OP_COMPARE_IMM) \ || ((ins)->opcode == OP_ICOMPARE_IMM) \ || ((ins)->opcode == OP_LCOMPARE_IMM))) #define INS_REWRITE(ins, op, _s1, _s2) do { \ int s1 = _s1; \ int s2 = _s2; \ ins->opcode = (op); \ ins->sreg1 = (s1); \ ins->sreg2 = (s2); \ } while (0); #define INS_REWRITE_IMM(ins, op, _s1, _imm) do { \ int s1 = _s1; \ ins->opcode = (op); \ ins->sreg1 = (s1); \ ins->inst_imm = (_imm); \ } while (0); typedef struct InstList InstList; struct InstList { InstList *prev; InstList *next; MonoInst *data; }; typedef enum { ArgInIReg, ArgOnStack, ArgInFReg, ArgStructByVal, ArgStructByAddr } ArgStorage; typedef struct { gint32 offset; guint16 vtsize; /* in param area */ guint8 reg; ArgStorage storage; guint8 size : 4; /* 1, 2, 4, 8, or regs used by ArgStructByVal */ } ArgInfo; typedef struct { int nargs; int gr; int fr; gboolean gr_passed; gboolean on_stack; gboolean vtype_retaddr; int stack_size; guint32 stack_usage; guint32 struct_ret; ArgInfo ret; ArgInfo sig_cookie; ArgInfo args [1]; } CallInfo; void patch_lui_addiu(guint32 *ip, guint32 val); guint8 *mono_arch_emit_epilog_sub (MonoCompile *cfg, guint8 *code); guint8 *mips_emit_cond_branch (MonoCompile *cfg, guint8 *code, int op, MonoInst *ins); void mips_adjust_stackframe(MonoCompile *cfg); void mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg); MonoInst *mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args); /* Not defined in asm/cachectl.h */ int cacheflush(char *addr, int nbytes, int cache); void mono_arch_flush_icache (guint8 *code, gint size) { /* Linux/MIPS specific */ cacheflush ((char*)code, size, BCACHE); } void mono_arch_flush_register_windows (void) { } gboolean mono_arch_is_inst_imm (gint64 imm) { return TRUE; } static guint8 * mips_emit_exc_by_name(guint8 *code, const char *name) { gpointer addr; MonoClass *exc_class; exc_class = mono_class_from_name (mono_defaults.corlib, "System", name); g_assert (exc_class); mips_load_const (code, mips_a0, exc_class->type_token); addr = mono_get_throw_corlib_exception (); mips_call (code, mips_t9, addr); return code; } guint8 * mips_emit_load_const(guint8 *code, int dreg, mgreg_t v) { if (mips_is_imm16 (v)) mips_addiu (code, dreg, mips_zero, ((guint32)v) & 0xffff); else { #if SIZEOF_REGISTER == 8 if (v != (long) v) { /* v is not a sign-extended 32-bit value */ mips_lui (code, dreg, mips_zero, (guint32)((v >> (32+16)) & 0xffff)); mips_ori (code, dreg, dreg, (guint32)((v >> (32)) & 0xffff)); mips_dsll (code, dreg, dreg, 16); mips_ori (code, dreg, dreg, (guint32)((v >> (16)) & 0xffff)); mips_dsll (code, dreg, dreg, 16); mips_ori (code, dreg, dreg, (guint32)(v & 0xffff)); return code; } #endif if (((guint32)v) & (1 << 15)) { mips_lui (code, dreg, mips_zero, (((guint32)v)>>16)+1); } else { mips_lui (code, dreg, mips_zero, (((guint32)v)>>16)); } if (((guint32)v) & 0xffff) mips_addiu (code, dreg, dreg, ((guint32)v) & 0xffff); } return code; } guint8 * mips_emit_cond_branch (MonoCompile *cfg, guint8 *code, int op, MonoInst *ins) { g_assert (ins); if (cfg->arch.long_branch) { int br_offset = 5; /* Invert test and emit branch around jump */ switch (op) { case OP_MIPS_BEQ: mips_bne (code, ins->sreg1, ins->sreg2, br_offset); mips_nop (code); break; case OP_MIPS_BNE: mips_beq (code, ins->sreg1, ins->sreg2, br_offset); mips_nop (code); break; case OP_MIPS_BGEZ: mips_bltz (code, ins->sreg1, br_offset); mips_nop (code); break; case OP_MIPS_BGTZ: mips_blez (code, ins->sreg1, br_offset); mips_nop (code); break; case OP_MIPS_BLEZ: mips_bgtz (code, ins->sreg1, br_offset); mips_nop (code); break; case OP_MIPS_BLTZ: mips_bgez (code, ins->sreg1, br_offset); mips_nop (code); break; default: g_assert_not_reached (); } mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); mips_lui (code, mips_at, mips_zero, 0); mips_addiu (code, mips_at, mips_at, 0); mips_jr (code, mips_at); mips_nop (code); } else { mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); switch (op) { case OP_MIPS_BEQ: mips_beq (code, ins->sreg1, ins->sreg2, 0); mips_nop (code); break; case OP_MIPS_BNE: mips_bne (code, ins->sreg1, ins->sreg2, 0); mips_nop (code); break; case OP_MIPS_BGEZ: mips_bgez (code, ins->sreg1, 0); mips_nop (code); break; case OP_MIPS_BGTZ: mips_bgtz (code, ins->sreg1, 0); mips_nop (code); break; case OP_MIPS_BLEZ: mips_blez (code, ins->sreg1, 0); mips_nop (code); break; case OP_MIPS_BLTZ: mips_bltz (code, ins->sreg1, 0); mips_nop (code); break; default: g_assert_not_reached (); } } return (code); } /* XXX - big-endian dependent? */ void patch_lui_addiu(guint32 *ip, guint32 val) { guint16 *__lui_addiu = (guint16*)(void *)(ip); #if 0 printf ("patch_lui_addiu ip=0x%08x (0x%08x, 0x%08x) to point to 0x%08x\n", ip, ((guint32 *)ip)[0], ((guint32 *)ip)[1], val); fflush (stdout); #endif if (((guint32)(val)) & (1 << 15)) __lui_addiu [MINI_LS_WORD_IDX] = ((((guint32)(val)) >> 16) & 0xffff) + 1; else __lui_addiu [MINI_LS_WORD_IDX] = (((guint32)(val)) >> 16) & 0xffff; __lui_addiu [MINI_LS_WORD_IDX + 2] = ((guint32)(val)) & 0xffff; mono_arch_flush_icache ((guint8 *)ip, 8); } guint32 trap_target; void mips_patch (guint32 *code, guint32 target) { guint32 ins = *code; guint32 op = ins >> 26; guint32 diff, offset; g_assert (trap_target != target); //printf ("patching 0x%08x (0x%08x) to point to 0x%08x\n", code, ins, target); switch (op) { case 0x00: /* jr ra */ if (ins == 0x3e00008) break; g_assert_not_reached (); break; case 0x02: /* j */ case 0x03: /* jal */ g_assert (!(target & 0x03)); g_assert ((target & 0xfc000000) == (((guint32)code) & 0xfc000000)); ins = (ins & 0xfc000000) | (((target) >> 2) & 0x03ffffff); *code = ins; mono_arch_flush_icache ((guint8 *)code, 4); break; case 0x01: /* BLTZ */ case 0x04: /* BEQ */ case 0x05: /* BNE */ case 0x06: /* BLEZ */ case 0x07: /* BGTZ */ case 0x11: /* bc1t */ diff = target - (guint32)(code + 1); g_assert (((diff & 0x0003ffff) == diff) || ((diff | 0xfffc0000) == diff)); g_assert (!(diff & 0x03)); offset = ((gint32)diff) >> 2; if (((int)offset) != ((int)(short)offset)) g_assert (((int)offset) == ((int)(short)offset)); ins = (ins & 0xffff0000) | (offset & 0x0000ffff); *code = ins; mono_arch_flush_icache ((guint8 *)code, 4); break; case 0x0f: /* LUI / ADDIU pair */ g_assert ((code[1] >> 26) == 0x9); patch_lui_addiu (code, target); mono_arch_flush_icache ((guint8 *)code, 8); break; default: printf ("unknown op 0x%02x (0x%08x) @ %p\n", op, ins, code); g_assert_not_reached (); } } #if 0 static int offsets_from_pthread_key (guint32 key, int *offset2) { int idx1 = key / 32; int idx2 = key % 32; *offset2 = idx2 * sizeof (gpointer); return 284 + idx1 * sizeof (gpointer); } #endif static void mono_arch_compute_omit_fp (MonoCompile *cfg); const char* mono_arch_regname (int reg) { #if _MIPS_SIM == _ABIO32 static const char * rnames[] = { "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3", "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra" }; #elif _MIPS_SIM == _ABIN32 static const char * rnames[] = { "zero", "at", "v0", "v1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "t0", "t1", "t2", "t3", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8", "t9", "k0", "k1", "gp", "sp", "fp", "ra" }; #endif if (reg >= 0 && reg < 32) return rnames [reg]; return "unknown"; } const char* mono_arch_fregname (int reg) { static const char * rnames[] = { "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31" }; if (reg >= 0 && reg < 32) return rnames [reg]; return "unknown"; } /* this function overwrites at */ static guint8* emit_memcpy (guint8 *code, int size, int dreg, int doffset, int sreg, int soffset) { /* XXX write a loop, not an unrolled loop */ while (size > 0) { mips_lw (code, mips_at, sreg, soffset); mips_sw (code, mips_at, dreg, doffset); size -= 4; soffset += 4; doffset += 4; } return code; } /* * mono_arch_get_argument_info: * @csig: a method signature * @param_count: the number of parameters to consider * @arg_info: an array to store the result infos * * Gathers information on parameters such as size, alignment and * padding. arg_info should be large enought to hold param_count + 1 entries. * * Returns the size of the activation frame. */ int mono_arch_get_argument_info (MonoGenericSharingContext *gsctx, MonoMethodSignature *csig, int param_count, MonoJitArgumentInfo *arg_info) { int k, frame_size = 0; guint32 size, align, pad; int offset = 0; if (MONO_TYPE_ISSTRUCT (csig->ret)) { frame_size += sizeof (gpointer); offset += 4; } arg_info [0].offset = offset; if (csig->hasthis) { frame_size += sizeof (gpointer); offset += 4; } arg_info [0].size = frame_size; for (k = 0; k < param_count; k++) { size = mini_type_stack_size_full (NULL, csig->params [k], &align, csig->pinvoke); /* ignore alignment for now */ align = 1; frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1); arg_info [k].pad = pad; frame_size += size; arg_info [k + 1].pad = 0; arg_info [k + 1].size = size; offset += pad; arg_info [k + 1].offset = offset; offset += size; } align = MONO_ARCH_FRAME_ALIGNMENT; frame_size += pad = (align - (frame_size & (align - 1))) & (align - 1); arg_info [k].pad = pad; return frame_size; } /* The delegate object plus 3 params */ #define MAX_ARCH_DELEGATE_PARAMS (4 - 1) static gpointer get_delegate_invoke_impl (gboolean has_target, gboolean param_count, guint32 *code_size) { guint8 *code, *start; if (has_target) { start = code = mono_global_codeman_reserve (16); /* Replace the this argument with the target */ mips_lw (code, mips_temp, mips_a0, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr)); mips_lw (code, mips_a0, mips_a0, MONO_STRUCT_OFFSET (MonoDelegate, target)); mips_jr (code, mips_temp); mips_nop (code); g_assert ((code - start) <= 16); mono_arch_flush_icache (start, 16); } else { int size, i; size = 16 + param_count * 4; start = code = mono_global_codeman_reserve (size); mips_lw (code, mips_temp, mips_a0, MONO_STRUCT_OFFSET (MonoDelegate, method_ptr)); /* slide down the arguments */ for (i = 0; i < param_count; ++i) { mips_move (code, mips_a0 + i, mips_a0 + i + 1); } mips_jr (code, mips_temp); mips_nop (code); g_assert ((code - start) <= size); mono_arch_flush_icache (start, size); } if (code_size) *code_size = code - start; return start; } /* * mono_arch_get_delegate_invoke_impls: * * Return a list of MonoAotTrampInfo structures for the delegate invoke impl * trampolines. */ GSList* mono_arch_get_delegate_invoke_impls (void) { GSList *res = NULL; guint8 *code; guint32 code_len; int i; char *tramp_name; code = get_delegate_invoke_impl (TRUE, 0, &code_len); res = g_slist_prepend (res, mono_tramp_info_create ("delegate_invoke_impl_has_target", code, code_len, NULL, NULL)); for (i = 0; i <= MAX_ARCH_DELEGATE_PARAMS; ++i) { code = get_delegate_invoke_impl (FALSE, i, &code_len); tramp_name = g_strdup_printf ("delegate_invoke_impl_target_%d", i); res = g_slist_prepend (res, mono_tramp_info_create (tramp_name, code, code_len, NULL, NULL)); g_free (tramp_name); } return res; } gpointer mono_arch_get_delegate_invoke_impl (MonoMethodSignature *sig, gboolean has_target) { guint8 *code, *start; /* FIXME: Support more cases */ if (MONO_TYPE_ISSTRUCT (sig->ret)) return NULL; if (has_target) { static guint8* cached = NULL; mono_mini_arch_lock (); if (cached) { mono_mini_arch_unlock (); return cached; } if (mono_aot_only) start = mono_aot_get_trampoline ("delegate_invoke_impl_has_target"); else start = get_delegate_invoke_impl (TRUE, 0, NULL); cached = start; mono_mini_arch_unlock (); return cached; } else { static guint8* cache [MAX_ARCH_DELEGATE_PARAMS + 1] = {NULL}; int i; if (sig->param_count > MAX_ARCH_DELEGATE_PARAMS) return NULL; for (i = 0; i < sig->param_count; ++i) if (!mono_is_regsize_var (sig->params [i])) return NULL; mono_mini_arch_lock (); code = cache [sig->param_count]; if (code) { mono_mini_arch_unlock (); return code; } if (mono_aot_only) { char *name = g_strdup_printf ("delegate_invoke_impl_target_%d", sig->param_count); start = mono_aot_get_trampoline (name); g_free (name); } else { start = get_delegate_invoke_impl (FALSE, sig->param_count, NULL); } cache [sig->param_count] = start; mono_mini_arch_unlock (); return start; } return NULL; } gpointer mono_arch_get_delegate_virtual_invoke_impl (MonoMethodSignature *sig, MonoMethod *method, int offset, gboolean load_imt_reg) { return NULL; } gpointer mono_arch_get_this_arg_from_call (mgreg_t *regs, guint8 *code) { g_assert(regs); return (gpointer)regs [mips_a0]; } /* * Initialize the cpu to execute managed code. */ void mono_arch_cpu_init (void) { #if TARGET_BYTE_ORDER == G_LITTLE_ENDIAN little_endian = 1; ls_word_idx = 0; ms_word_idx = 1; #else ls_word_idx = 1; ms_word_idx = 0; #endif ls_word_offset = ls_word_idx * 4; ms_word_offset = ms_word_idx * 4; } /* * Initialize architecture specific code. */ void mono_arch_init (void) { mono_mutex_init_recursive (&mini_arch_mutex); ss_trigger_page = mono_valloc (NULL, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_32BIT); bp_trigger_page = mono_valloc (NULL, mono_pagesize (), MONO_MMAP_READ|MONO_MMAP_32BIT); mono_mprotect (bp_trigger_page, mono_pagesize (), 0); } /* * Cleanup architecture specific code. */ void mono_arch_cleanup (void) { mono_mutex_destroy (&mini_arch_mutex); } /* * This function returns the optimizations supported on this cpu. */ guint32 mono_arch_cpu_optimizations (guint32 *exclude_mask) { guint32 opts = 0; /* no mips-specific optimizations yet */ *exclude_mask = 0; return opts; } /* * This function test for all SIMD functions supported. * * Returns a bitmask corresponding to all supported versions. * */ guint32 mono_arch_cpu_enumerate_simd_versions (void) { /* SIMD is currently unimplemented */ return 0; } GList * mono_arch_get_allocatable_int_vars (MonoCompile *cfg) { GList *vars = NULL; int i; for (i = 0; i < cfg->num_varinfo; i++) { MonoInst *ins = cfg->varinfo [i]; MonoMethodVar *vmv = MONO_VARINFO (cfg, i); /* unused vars */ if (vmv->range.first_use.abs_pos >= vmv->range.last_use.abs_pos) continue; if (ins->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT) || (ins->opcode != OP_LOCAL && ins->opcode != OP_ARG)) continue; /* we can only allocate 32 bit values */ if (mono_is_regsize_var (ins->inst_vtype)) { g_assert (MONO_VARINFO (cfg, i)->reg == -1); g_assert (i == vmv->idx); vars = mono_varlist_insert_sorted (cfg, vars, vmv, FALSE); } } return vars; } GList * mono_arch_get_global_int_regs (MonoCompile *cfg) { GList *regs = NULL; regs = g_list_prepend (regs, (gpointer)mips_s0); regs = g_list_prepend (regs, (gpointer)mips_s1); regs = g_list_prepend (regs, (gpointer)mips_s2); regs = g_list_prepend (regs, (gpointer)mips_s3); regs = g_list_prepend (regs, (gpointer)mips_s4); //regs = g_list_prepend (regs, (gpointer)mips_s5); regs = g_list_prepend (regs, (gpointer)mips_s6); regs = g_list_prepend (regs, (gpointer)mips_s7); return regs; } /* * mono_arch_regalloc_cost: * * Return the cost, in number of memory references, of the action of * allocating the variable VMV into a register during global register * allocation. */ guint32 mono_arch_regalloc_cost (MonoCompile *cfg, MonoMethodVar *vmv) { /* FIXME: */ return 2; } static void args_onto_stack (CallInfo *info) { g_assert (!info->on_stack); g_assert (info->stack_size <= MIPS_STACK_PARAM_OFFSET); info->on_stack = TRUE; info->stack_size = MIPS_STACK_PARAM_OFFSET; } #if _MIPS_SIM == _ABIO32 /* * O32 calling convention version */ static void add_int32_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; } else { ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 1; info->gr_passed = TRUE; } info->stack_size += 4; } static void add_int64_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr+1 > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { g_assert (info->stack_size % 4 == 0); info->stack_size += (info->stack_size % 8); ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; } else { // info->gr must be a0 or a2 info->gr += (info->gr - MIPS_FIRST_ARG_REG) % 2; g_assert(info->gr <= MIPS_LAST_ARG_REG); ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 2; info->gr_passed = TRUE; } info->stack_size += 8; } static void add_float32_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; } else { /* Only use FP regs for args if no int args passed yet */ if (!info->gr_passed && info->fr <= MIPS_LAST_FPARG_REG) { ainfo->storage = ArgInFReg; ainfo->reg = info->fr; /* Even though it's a single-precision float, it takes up two FP regs */ info->fr += 2; /* FP and GP slots do not overlap */ info->gr += 1; } else { /* Passing single-precision float arg in a GP register * such as: func (0, 1.0, 2, 3); * In this case, only one 'gr' register is consumed. */ ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 1; info->gr_passed = TRUE; } } info->stack_size += 4; } static void add_float64_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr+1 > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { g_assert(info->stack_size % 4 == 0); info->stack_size += (info->stack_size % 8); ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; } else { /* Only use FP regs for args if no int args passed yet */ if (!info->gr_passed && info->fr <= MIPS_LAST_FPARG_REG) { ainfo->storage = ArgInFReg; ainfo->reg = info->fr; info->fr += 2; /* FP and GP slots do not overlap */ info->gr += 2; } else { // info->gr must be a0 or a2 info->gr += (info->gr - MIPS_FIRST_ARG_REG) % 2; g_assert(info->gr <= MIPS_LAST_ARG_REG); ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 2; info->gr_passed = TRUE; } } info->stack_size += 8; } #elif _MIPS_SIM == _ABIN32 /* * N32 calling convention version */ static void add_int32_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; info->stack_size += SIZEOF_REGISTER; } else { ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 1; info->gr_passed = TRUE; } } static void add_int64_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack && info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); /* Now, place the argument */ if (info->on_stack) { g_assert (info->stack_size % 4 == 0); info->stack_size += (info->stack_size % 8); ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; info->stack_size += SIZEOF_REGISTER; } else { g_assert (info->gr <= MIPS_LAST_ARG_REG); ainfo->storage = ArgInIReg; ainfo->reg = info->gr; info->gr += 1; info->gr_passed = TRUE; } } static void add_float32_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack) { if (info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); else if (info->fr > MIPS_LAST_FPARG_REG) args_onto_stack (info); } /* Now, place the argument */ if (info->on_stack) { ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; info->stack_size += FREG_SIZE; } else { ainfo->storage = ArgInFReg; ainfo->reg = info->fr; info->fr += 1; /* FP and GP slots do not overlap */ info->gr += 1; } } static void add_float64_arg (CallInfo *info, ArgInfo *ainfo) { /* First, see if we need to drop onto the stack */ if (!info->on_stack) { if (info->gr > MIPS_LAST_ARG_REG) args_onto_stack (info); else if (info->fr > MIPS_LAST_FPARG_REG) args_onto_stack (info); } /* Now, place the argument */ if (info->on_stack) { g_assert(info->stack_size % 4 == 0); info->stack_size += (info->stack_size % 8); ainfo->storage = ArgOnStack; ainfo->reg = mips_sp; /* in the caller */ ainfo->offset = info->stack_size; info->stack_size += FREG_SIZE; } else { ainfo->storage = ArgInFReg; ainfo->reg = info->fr; info->fr += 1; /* FP and GP slots do not overlap */ info->gr += 1; } } #endif static CallInfo* get_call_info (MonoGenericSharingContext *gsctx, MonoMemPool *mp, MonoMethodSignature *sig) { guint i; int n = sig->hasthis + sig->param_count; int pstart; MonoType* simpletype; CallInfo *cinfo; gboolean is_pinvoke = sig->pinvoke; if (mp) cinfo = mono_mempool_alloc0 (mp, sizeof (CallInfo) + (sizeof (ArgInfo) * n)); else cinfo = g_malloc0 (sizeof (CallInfo) + (sizeof (ArgInfo) * n)); cinfo->fr = MIPS_FIRST_FPARG_REG; cinfo->gr = MIPS_FIRST_ARG_REG; cinfo->stack_size = 0; DEBUG(printf("calculate_sizes\n")); cinfo->vtype_retaddr = MONO_TYPE_ISSTRUCT (sig->ret) ? TRUE : FALSE; pstart = 0; n = 0; #if 0 /* handle returning a struct */ if (MONO_TYPE_ISSTRUCT (sig->ret)) { cinfo->struct_ret = cinfo->gr; add_int32_arg (cinfo, &cinfo->ret); } if (sig->hasthis) { add_int32_arg (cinfo, cinfo->args + n); n++; } #else /* * To simplify get_this_arg_reg () and LLVM integration, emit the vret arg after * the first argument, allowing 'this' to be always passed in the first arg reg. * Also do this if the first argument is a reference type, since virtual calls * are sometimes made using calli without sig->hasthis set, like in the delegate * invoke wrappers. */ if (cinfo->vtype_retaddr && !is_pinvoke && (sig->hasthis || (sig->param_count > 0 && MONO_TYPE_IS_REFERENCE (mini_type_get_underlying_type (gsctx, sig->params [0]))))) { if (sig->hasthis) { add_int32_arg (cinfo, cinfo->args + n); n ++; } else { add_int32_arg (cinfo, cinfo->args + sig->hasthis); pstart = 1; n ++; } add_int32_arg (cinfo, &cinfo->ret); cinfo->struct_ret = cinfo->ret.reg; } else { /* this */ if (sig->hasthis) { add_int32_arg (cinfo, cinfo->args + n); n ++; } if (cinfo->vtype_retaddr) { add_int32_arg (cinfo, &cinfo->ret); cinfo->struct_ret = cinfo->ret.reg; } } #endif DEBUG(printf("params: %d\n", sig->param_count)); for (i = pstart; i < sig->param_count; ++i) { if ((sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) { /* Prevent implicit arguments and sig_cookie from being passed in registers */ args_onto_stack (cinfo); /* Emit the signature cookie just before the implicit arguments */ add_int32_arg (cinfo, &cinfo->sig_cookie); } DEBUG(printf("param %d: ", i)); simpletype = mini_type_get_underlying_type (gsctx, sig->params [i]); switch (simpletype->type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_I1: case MONO_TYPE_U1: DEBUG(printf("1 byte\n")); cinfo->args [n].size = 1; add_int32_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_CHAR: case MONO_TYPE_I2: case MONO_TYPE_U2: DEBUG(printf("2 bytes\n")); cinfo->args [n].size = 2; add_int32_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_I4: case MONO_TYPE_U4: DEBUG(printf("4 bytes\n")); cinfo->args [n].size = 4; add_int32_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_STRING: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: cinfo->args [n].size = sizeof (gpointer); add_int32_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (simpletype)) { cinfo->args [n].size = sizeof (gpointer); add_int32_arg (cinfo, &cinfo->args[n]); n++; break; } /* Fall through */ case MONO_TYPE_TYPEDBYREF: case MONO_TYPE_VALUETYPE: { int j; int nwords = 0; int has_offset = FALSE; ArgInfo dummy_arg; gint size, alignment; MonoClass *klass; if (simpletype->type == MONO_TYPE_TYPEDBYREF) { size = sizeof (MonoTypedRef); alignment = sizeof (gpointer); } else { klass = mono_class_from_mono_type (sig->params [i]); if (is_pinvoke) size = mono_class_native_size (klass, NULL); else size = mono_class_value_size (klass, NULL); alignment = mono_class_min_align (klass); } #if MIPS_PASS_STRUCTS_BY_VALUE /* Need to do alignment if struct contains long or double */ if (alignment > 4) { /* Drop onto stack *before* looking at stack_size, if required. */ if (!cinfo->on_stack && cinfo->gr > MIPS_LAST_ARG_REG) args_onto_stack (cinfo); if (cinfo->stack_size & (alignment - 1)) { add_int32_arg (cinfo, &dummy_arg); } g_assert (!(cinfo->stack_size & (alignment - 1))); } #if 0 g_printf ("valuetype struct size=%d offset=%d align=%d\n", mono_class_native_size (sig->params [i]->data.klass, NULL), cinfo->stack_size, alignment); #endif nwords = (size + sizeof (gpointer) -1 ) / sizeof (gpointer); g_assert (cinfo->args [n].size == 0); g_assert (cinfo->args [n].vtsize == 0); for (j = 0; j < nwords; ++j) { if (j == 0) { add_int32_arg (cinfo, &cinfo->args [n]); if (cinfo->on_stack) has_offset = TRUE; } else { add_int32_arg (cinfo, &dummy_arg); if (!has_offset && cinfo->on_stack) { cinfo->args [n].offset = dummy_arg.offset; has_offset = TRUE; } } if (cinfo->on_stack) cinfo->args [n].vtsize += 1; else cinfo->args [n].size += 1; } //g_printf ("\tstack_size=%d vtsize=%d\n", cinfo->args [n].size, cinfo->args[n].vtsize); cinfo->args [n].storage = ArgStructByVal; #else add_int32_arg (cinfo, &cinfo->args[n]); cinfo->args [n].storage = ArgStructByAddr; #endif n++; break; } case MONO_TYPE_U8: case MONO_TYPE_I8: DEBUG(printf("8 bytes\n")); cinfo->args [n].size = 8; add_int64_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_R4: DEBUG(printf("R4\n")); cinfo->args [n].size = 4; add_float32_arg (cinfo, &cinfo->args[n]); n++; break; case MONO_TYPE_R8: DEBUG(printf("R8\n")); cinfo->args [n].size = 8; add_float64_arg (cinfo, &cinfo->args[n]); n++; break; default: g_error ("Can't trampoline 0x%x", sig->params [i]->type); } } /* Handle the case where there are no implicit arguments */ if ((sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) { /* Prevent implicit arguments and sig_cookie from being passed in registers */ args_onto_stack (cinfo); /* Emit the signature cookie just before the implicit arguments */ add_int32_arg (cinfo, &cinfo->sig_cookie); } { simpletype = mini_type_get_underlying_type (gsctx, sig->ret); switch (simpletype->type) { case MONO_TYPE_BOOLEAN: case MONO_TYPE_I1: case MONO_TYPE_U1: case MONO_TYPE_I2: case MONO_TYPE_U2: case MONO_TYPE_CHAR: case MONO_TYPE_I4: case MONO_TYPE_U4: case MONO_TYPE_I: case MONO_TYPE_U: case MONO_TYPE_PTR: case MONO_TYPE_FNPTR: case MONO_TYPE_CLASS: case MONO_TYPE_OBJECT: case MONO_TYPE_SZARRAY: case MONO_TYPE_ARRAY: case MONO_TYPE_STRING: cinfo->ret.reg = mips_v0; break; case MONO_TYPE_U8: case MONO_TYPE_I8: cinfo->ret.reg = mips_v0; break; case MONO_TYPE_R4: case MONO_TYPE_R8: cinfo->ret.reg = mips_f0; cinfo->ret.storage = ArgInFReg; break; case MONO_TYPE_GENERICINST: if (!mono_type_generic_inst_is_valuetype (simpletype)) { cinfo->ret.reg = mips_v0; break; } break; case MONO_TYPE_VALUETYPE: case MONO_TYPE_TYPEDBYREF: break; case MONO_TYPE_VOID: break; default: g_error ("Can't handle as return value 0x%x", sig->ret->type); } } /* align stack size to 16 */ cinfo->stack_size = (cinfo->stack_size + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); cinfo->stack_usage = cinfo->stack_size; return cinfo; } static gboolean debug_omit_fp (void) { #if 0 return mono_debug_count (); #else return TRUE; #endif } /** * mono_arch_compute_omit_fp: * * Determine whenever the frame pointer can be eliminated. */ static void mono_arch_compute_omit_fp (MonoCompile *cfg) { MonoMethodSignature *sig; MonoMethodHeader *header; int i, locals_size; CallInfo *cinfo; if (cfg->arch.omit_fp_computed) return; header = cfg->header; sig = mono_method_signature (cfg->method); if (!cfg->arch.cinfo) cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig); cinfo = cfg->arch.cinfo; /* * FIXME: Remove some of the restrictions. */ cfg->arch.omit_fp = TRUE; cfg->arch.omit_fp_computed = TRUE; if (cfg->disable_omit_fp) cfg->arch.omit_fp = FALSE; if (!debug_omit_fp ()) cfg->arch.omit_fp = FALSE; if (cfg->method->save_lmf) cfg->arch.omit_fp = FALSE; if (cfg->flags & MONO_CFG_HAS_ALLOCA) cfg->arch.omit_fp = FALSE; if (header->num_clauses) cfg->arch.omit_fp = FALSE; if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG)) cfg->arch.omit_fp = FALSE; if ((mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) || (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)) cfg->arch.omit_fp = FALSE; /* * On MIPS, fp points to the bottom of the frame, so it can be eliminated even if * there are stack arguments. */ /* if (cinfo->stack_usage) cfg->arch.omit_fp = FALSE; */ locals_size = 0; for (i = cfg->locals_start; i < cfg->num_varinfo; i++) { MonoInst *ins = cfg->varinfo [i]; int ialign; locals_size += mono_type_size (ins->inst_vtype, &ialign); } //printf ("D: %s %d\n", cfg->method->name, cfg->arch.omit_fp); } /* * Set var information according to the calling convention. mips version. * The locals var stuff should most likely be split in another method. */ void mono_arch_allocate_vars (MonoCompile *cfg) { MonoMethodSignature *sig; MonoMethodHeader *header; MonoInst *inst; int i, offset, size, align, curinst; int frame_reg = mips_sp; guint32 iregs_to_save = 0; #if SAVE_FP_REGS guint32 fregs_to_restore; #endif CallInfo *cinfo; sig = mono_method_signature (cfg->method); if (!cfg->arch.cinfo) cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig); cinfo = cfg->arch.cinfo; mono_arch_compute_omit_fp (cfg); /* spill down, we'll fix it in a separate pass */ // cfg->flags |= MONO_CFG_HAS_SPILLUP; /* allow room for the vararg method args: void* and long/double */ if (mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) cfg->param_area = MAX (cfg->param_area, sizeof (gpointer)*8); /* this is bug #60332: remove when #59509 is fixed, so no weird vararg * call convs needs to be handled this way. */ if (cfg->flags & MONO_CFG_HAS_VARARGS) cfg->param_area = MAX (cfg->param_area, sizeof (gpointer)*8); /* gtk-sharp and other broken code will dllimport vararg functions even with * non-varargs signatures. Since there is little hope people will get this right * we assume they won't. */ if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) cfg->param_area = MAX (cfg->param_area, sizeof (gpointer)*8); /* a0-a3 always present */ cfg->param_area = MAX (cfg->param_area, MIPS_STACK_PARAM_OFFSET); header = cfg->header; if (cfg->arch.omit_fp) frame_reg = mips_sp; else frame_reg = mips_fp; cfg->frame_reg = frame_reg; if (frame_reg != mips_sp) { cfg->used_int_regs |= 1 << frame_reg; } offset = 0; curinst = 0; if (!MONO_TYPE_ISSTRUCT (sig->ret)) { /* FIXME: handle long and FP values */ switch (mini_type_get_underlying_type (cfg->generic_sharing_context, sig->ret)->type) { case MONO_TYPE_VOID: break; case MONO_TYPE_R4: case MONO_TYPE_R8: cfg->ret->opcode = OP_REGVAR; cfg->ret->inst_c0 = cfg->ret->dreg = mips_f0; break; default: cfg->ret->opcode = OP_REGVAR; cfg->ret->inst_c0 = mips_v0; break; } } /* Space for outgoing parameters, including a0-a3 */ offset += cfg->param_area; /* allow room to save the return value (if it's a struct) */ if (mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method)) offset += 8; /* Now handle the local variables */ curinst = cfg->locals_start; for (i = curinst; i < cfg->num_varinfo; ++i) { inst = cfg->varinfo [i]; if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR) continue; /* inst->backend.is_pinvoke indicates native sized value types, this is used by the * pinvoke wrappers when they call functions returning structure */ if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), (unsigned int *) &align); else size = mono_type_size (inst->inst_vtype, &align); offset += align - 1; offset &= ~(align - 1); inst->inst_offset = offset; inst->opcode = OP_REGOFFSET; inst->inst_basereg = frame_reg; offset += size; // g_print ("allocating local %d to %d\n", i, inst->inst_offset); } /* Space for LMF (if needed) */ if (cfg->method->save_lmf) { /* align the offset to 16 bytes */ offset = (offset + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); cfg->arch.lmf_offset = offset; offset += sizeof (MonoLMF); } if (sig->call_convention == MONO_CALL_VARARG) { size = 4; align = 4; /* Allocate a local slot to hold the sig cookie address */ offset += align - 1; offset &= ~(align - 1); cfg->sig_cookie = offset; offset += size; } offset += SIZEOF_REGISTER - 1; offset &= ~(SIZEOF_REGISTER - 1); /* Space for saved registers */ cfg->arch.iregs_offset = offset; iregs_to_save = (cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS); if (iregs_to_save) { for (i = MONO_MAX_IREGS-1; i >= 0; --i) { if (iregs_to_save & (1 << i)) { offset += SIZEOF_REGISTER; } } } /* saved float registers */ #if SAVE_FP_REGS fregs_to_restore = (cfg->used_float_regs & MONO_ARCH_CALLEE_SAVED_FREGS); if (fregs_to_restore) { for (i = MONO_MAX_FREGS-1; i >= 0; --i) { if (fregs_to_restore & (1 << i)) { offset += sizeof(double); } } } #endif #if _MIPS_SIM == _ABIO32 /* Now add space for saving the ra */ offset += SIZEOF_VOID_P; /* change sign? */ offset = (offset + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); cfg->stack_offset = offset; cfg->arch.local_alloc_offset = cfg->stack_offset; #endif /* * Now allocate stack slots for the int arg regs (a0 - a3) * On MIPS o32, these are just above the incoming stack pointer * Even if the arg has been assigned to a regvar, it gets a stack slot */ /* Return struct-by-value results in a hidden first argument */ if (MONO_TYPE_ISSTRUCT (sig->ret)) { cfg->vret_addr->opcode = OP_REGOFFSET; cfg->vret_addr->inst_c0 = mips_a0; cfg->vret_addr->inst_offset = offset; cfg->vret_addr->inst_basereg = frame_reg; offset += SIZEOF_REGISTER; } for (i = 0; i < sig->param_count + sig->hasthis; ++i) { inst = cfg->args [i]; if (inst->opcode != OP_REGVAR) { MonoType *arg_type; if (sig->hasthis && (i == 0)) arg_type = &mono_defaults.object_class->byval_arg; else arg_type = sig->params [i - sig->hasthis]; inst->opcode = OP_REGOFFSET; size = mono_type_size (arg_type, &align); if (size < SIZEOF_REGISTER) { size = SIZEOF_REGISTER; align = SIZEOF_REGISTER; } inst->inst_basereg = frame_reg; offset = (offset + align - 1) & ~(align - 1); inst->inst_offset = offset; offset += size; if (cfg->verbose_level > 1) printf ("allocating param %d to fp[%d]\n", i, inst->inst_offset); } else { #if _MIPS_SIM == _ABIO32 /* o32: Even a0-a3 get stack slots */ size = SIZEOF_REGISTER; align = SIZEOF_REGISTER; inst->inst_basereg = frame_reg; offset = (offset + align - 1) & ~(align - 1); inst->inst_offset = offset; offset += size; if (cfg->verbose_level > 1) printf ("allocating param %d to fp[%d]\n", i, inst->inst_offset); #endif } } #if _MIPS_SIM == _ABIN32 /* Now add space for saving the ra */ offset += SIZEOF_VOID_P; /* change sign? */ offset = (offset + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); cfg->stack_offset = offset; cfg->arch.local_alloc_offset = cfg->stack_offset; #endif } void mono_arch_create_vars (MonoCompile *cfg) { MonoMethodSignature *sig; sig = mono_method_signature (cfg->method); if (MONO_TYPE_ISSTRUCT (sig->ret)) { cfg->vret_addr = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_ARG); if (G_UNLIKELY (cfg->verbose_level > 1)) { printf ("vret_addr = "); mono_print_ins (cfg->vret_addr); } } } /* Fixme: we need an alignment solution for enter_method and mono_arch_call_opcode, * currently alignment in mono_arch_call_opcode is computed without arch_get_argument_info */ /* * take the arguments and generate the arch-specific * instructions to properly call the function in call. * This includes pushing, moving arguments to the right register * etc. * Issue: who does the spilling if needed, and when? */ static void emit_sig_cookie (MonoCompile *cfg, MonoCallInst *call, CallInfo *cinfo) { MonoMethodSignature *tmp_sig; MonoInst *sig_arg; if (call->tail_call) NOT_IMPLEMENTED; /* FIXME: Add support for signature tokens to AOT */ cfg->disable_aot = TRUE; /* * mono_ArgIterator_Setup assumes the signature cookie is * passed first and all the arguments which were before it are * passed on the stack after the signature. So compensate by * passing a different signature. */ tmp_sig = mono_metadata_signature_dup (call->signature); tmp_sig->param_count -= call->signature->sentinelpos; tmp_sig->sentinelpos = 0; memcpy (tmp_sig->params, call->signature->params + call->signature->sentinelpos, tmp_sig->param_count * sizeof (MonoType*)); MONO_INST_NEW (cfg, sig_arg, OP_ICONST); sig_arg->dreg = mono_alloc_ireg (cfg); sig_arg->inst_p0 = tmp_sig; MONO_ADD_INS (cfg->cbb, sig_arg); MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, mips_sp, cinfo->sig_cookie.offset, sig_arg->dreg); } void mono_arch_emit_call (MonoCompile *cfg, MonoCallInst *call) { MonoInst *in, *ins; MonoMethodSignature *sig; int i, n; CallInfo *cinfo; int is_virtual = 0; sig = call->signature; n = sig->param_count + sig->hasthis; cinfo = get_call_info (NULL, cfg->mempool, sig); if (cinfo->struct_ret) call->used_iregs |= 1 << cinfo->struct_ret; for (i = 0; i < n; ++i) { ArgInfo *ainfo = cinfo->args + i; MonoType *t; if (i >= sig->hasthis) t = sig->params [i - sig->hasthis]; else t = &mono_defaults.int_class->byval_arg; t = mini_type_get_underlying_type (cfg->generic_sharing_context, t); if ((sig->call_convention == MONO_CALL_VARARG) && (i == sig->sentinelpos)) { /* Emit the signature cookie just before the implicit arguments */ emit_sig_cookie (cfg, call, cinfo); } if (is_virtual && i == 0) { /* the argument will be attached to the call instrucion */ in = call->args [i]; call->used_iregs |= 1 << ainfo->reg; continue; } in = call->args [i]; if (ainfo->storage == ArgInIReg) { #if SIZEOF_REGISTER == 4 if (!t->byref && ((t->type == MONO_TYPE_I8) || (t->type == MONO_TYPE_U8))) { MONO_INST_NEW (cfg, ins, OP_MOVE); ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = in->dreg + 1; MONO_ADD_INS (cfg->cbb, ins); mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, ainfo->reg + ls_word_idx, FALSE); MONO_INST_NEW (cfg, ins, OP_MOVE); ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = in->dreg + 2; MONO_ADD_INS (cfg->cbb, ins); mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, ainfo->reg + ms_word_idx, FALSE); } else #endif if (!t->byref && (t->type == MONO_TYPE_R4)) { int freg; #if PROMOTE_R4_TO_R8 /* ??? - convert to single first? */ MONO_INST_NEW (cfg, ins, OP_MIPS_CVTSD); ins->dreg = mono_alloc_freg (cfg); ins->sreg1 = in->dreg; MONO_ADD_INS (cfg->cbb, ins); freg = ins->dreg; #else freg = in->dreg; #endif /* trying to load float value into int registers */ MONO_INST_NEW (cfg, ins, OP_MIPS_MFC1S); ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = freg; MONO_ADD_INS (cfg->cbb, ins); mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, ainfo->reg, FALSE); } else if (!t->byref && (t->type == MONO_TYPE_R8)) { /* trying to load float value into int registers */ MONO_INST_NEW (cfg, ins, OP_MIPS_MFC1D); ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = in->dreg; MONO_ADD_INS (cfg->cbb, ins); mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, ainfo->reg, FALSE); } else { MONO_INST_NEW (cfg, ins, OP_MOVE); ins->dreg = mono_alloc_ireg (cfg); ins->sreg1 = in->dreg; MONO_ADD_INS (cfg->cbb, ins); mono_call_inst_add_outarg_reg (cfg, call, ins->dreg, ainfo->reg, FALSE); } } else if (ainfo->storage == ArgStructByAddr) { MONO_INST_NEW (cfg, ins, OP_OUTARG_VT); ins->opcode = OP_OUTARG_VT; ins->sreg1 = in->dreg; ins->klass = in->klass; ins->inst_p0 = call; ins->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo)); memcpy (ins->inst_p1, ainfo, sizeof (ArgInfo)); MONO_ADD_INS (cfg->cbb, ins); } else if (ainfo->storage == ArgStructByVal) { /* this is further handled in mono_arch_emit_outarg_vt () */ MONO_INST_NEW (cfg, ins, OP_OUTARG_VT); ins->opcode = OP_OUTARG_VT; ins->sreg1 = in->dreg; ins->klass = in->klass; ins->inst_p0 = call; ins->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo)); memcpy (ins->inst_p1, ainfo, sizeof (ArgInfo)); MONO_ADD_INS (cfg->cbb, ins); } else if (ainfo->storage == ArgOnStack) { if (!t->byref && ((t->type == MONO_TYPE_I8) || (t->type == MONO_TYPE_U8))) { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STOREI8_MEMBASE_REG, mips_sp, ainfo->offset, in->dreg); } else if (!t->byref && ((t->type == MONO_TYPE_R4) || (t->type == MONO_TYPE_R8))) { if (t->type == MONO_TYPE_R8) MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER8_MEMBASE_REG, mips_sp, ainfo->offset, in->dreg); else MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORER4_MEMBASE_REG, mips_sp, ainfo->offset, in->dreg); } else { MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, mips_sp, ainfo->offset, in->dreg); } } else if (ainfo->storage == ArgInFReg) { if (t->type == MONO_TYPE_VALUETYPE) { /* this is further handled in mono_arch_emit_outarg_vt () */ MONO_INST_NEW (cfg, ins, OP_OUTARG_VT); ins->opcode = OP_OUTARG_VT; ins->sreg1 = in->dreg; ins->klass = in->klass; ins->inst_p0 = call; ins->inst_p1 = mono_mempool_alloc (cfg->mempool, sizeof (ArgInfo)); memcpy (ins->inst_p1, ainfo, sizeof (ArgInfo)); MONO_ADD_INS (cfg->cbb, ins); cfg->flags |= MONO_CFG_HAS_FPOUT; } else { int dreg = mono_alloc_freg (cfg); if (ainfo->size == 4) { MONO_EMIT_NEW_UNALU (cfg, OP_MIPS_CVTSD, dreg, in->dreg); } else { MONO_INST_NEW (cfg, ins, OP_FMOVE); ins->dreg = dreg; ins->sreg1 = in->dreg; MONO_ADD_INS (cfg->cbb, ins); } mono_call_inst_add_outarg_reg (cfg, call, dreg, ainfo->reg, TRUE); cfg->flags |= MONO_CFG_HAS_FPOUT; } } else { g_assert_not_reached (); } } /* Handle the case where there are no implicit arguments */ if (!sig->pinvoke && (sig->call_convention == MONO_CALL_VARARG) && (n == sig->sentinelpos)) emit_sig_cookie (cfg, call, cinfo); if (cinfo->struct_ret) { MonoInst *vtarg; MONO_INST_NEW (cfg, vtarg, OP_MOVE); vtarg->sreg1 = call->vret_var->dreg; vtarg->dreg = mono_alloc_preg (cfg); MONO_ADD_INS (cfg->cbb, vtarg); mono_call_inst_add_outarg_reg (cfg, call, vtarg->dreg, cinfo->struct_ret, FALSE); } #if 0 /* * Reverse the call->out_args list. */ { MonoInst *prev = NULL, *list = call->out_args, *next; while (list) { next = list->next; list->next = prev; prev = list; list = next; } call->out_args = prev; } #endif call->stack_usage = cinfo->stack_usage; cfg->param_area = MAX (cfg->param_area, cinfo->stack_usage); #if _MIPS_SIM == _ABIO32 /* a0-a3 always present */ cfg->param_area = MAX (cfg->param_area, 4 * SIZEOF_REGISTER); #endif cfg->param_area = (cfg->param_area + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); cfg->flags |= MONO_CFG_HAS_CALLS; /* * should set more info in call, such as the stack space * used by the args that needs to be added back to esp */ } void mono_arch_emit_outarg_vt (MonoCompile *cfg, MonoInst *ins, MonoInst *src) { MonoCallInst *call = (MonoCallInst*)ins->inst_p0; ArgInfo *ainfo = ins->inst_p1; int ovf_size = ainfo->vtsize; int doffset = ainfo->offset; int i, soffset, dreg; if (ainfo->storage == ArgStructByVal) { #if 0 if (cfg->verbose_level > 0) { char* nm = mono_method_full_name (cfg->method, TRUE); g_print ("Method %s outarg_vt struct doffset=%d ainfo->size=%d ovf_size=%d\n", nm, doffset, ainfo->size, ovf_size); g_free (nm); } #endif soffset = 0; for (i = 0; i < ainfo->size; ++i) { dreg = mono_alloc_ireg (cfg); MONO_EMIT_NEW_LOAD_MEMBASE (cfg, dreg, src->dreg, soffset); mono_call_inst_add_outarg_reg (cfg, call, dreg, ainfo->reg + i, FALSE); soffset += SIZEOF_REGISTER; } if (ovf_size != 0) { mini_emit_memcpy (cfg, mips_sp, doffset, src->dreg, soffset, ovf_size * sizeof (gpointer), 0); } } else if (ainfo->storage == ArgInFReg) { int tmpr = mono_alloc_freg (cfg); if (ainfo->size == 4) MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADR4_MEMBASE, tmpr, src->dreg, 0); else MONO_EMIT_NEW_LOAD_MEMBASE_OP (cfg, OP_LOADR8_MEMBASE, tmpr, src->dreg, 0); dreg = mono_alloc_freg (cfg); MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, dreg, tmpr); mono_call_inst_add_outarg_reg (cfg, call, dreg, ainfo->reg, TRUE); } else { MonoInst *vtcopy = mono_compile_create_var (cfg, &src->klass->byval_arg, OP_LOCAL); MonoInst *load; guint32 size; /* FIXME: alignment? */ if (call->signature->pinvoke) { size = mono_type_native_stack_size (&src->klass->byval_arg, NULL); vtcopy->backend.is_pinvoke = 1; } else { size = mini_type_stack_size (cfg->generic_sharing_context, &src->klass->byval_arg, NULL); } if (size > 0) g_assert (ovf_size > 0); EMIT_NEW_VARLOADA (cfg, load, vtcopy, vtcopy->inst_vtype); mini_emit_memcpy (cfg, load->dreg, 0, src->dreg, 0, size, 0); if (ainfo->offset) MONO_EMIT_NEW_STORE_MEMBASE (cfg, OP_STORE_MEMBASE_REG, mips_at, ainfo->offset, load->dreg); else mono_call_inst_add_outarg_reg (cfg, call, load->dreg, ainfo->reg, FALSE); } } void mono_arch_emit_setret (MonoCompile *cfg, MonoMethod *method, MonoInst *val) { MonoType *ret = mini_type_get_underlying_type (cfg->generic_sharing_context, mono_method_signature (method)->ret); if (!ret->byref) { #if (SIZEOF_REGISTER == 4) if (ret->type == MONO_TYPE_I8 || ret->type == MONO_TYPE_U8) { MonoInst *ins; MONO_INST_NEW (cfg, ins, OP_SETLRET); ins->sreg1 = val->dreg + 1; ins->sreg2 = val->dreg + 2; MONO_ADD_INS (cfg->cbb, ins); return; } #endif if (ret->type == MONO_TYPE_R8) { MONO_EMIT_NEW_UNALU (cfg, OP_FMOVE, cfg->ret->dreg, val->dreg); return; } if (ret->type == MONO_TYPE_R4) { MONO_EMIT_NEW_UNALU (cfg, OP_MIPS_CVTSD, cfg->ret->dreg, val->dreg); return; } } MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, cfg->ret->dreg, val->dreg); } void mono_arch_peephole_pass_1 (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *n, *last_ins = NULL; if (cfg->verbose_level > 2) g_print ("Basic block %d peephole pass 1\n", bb->block_num); ins = bb->code; MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) { if (cfg->verbose_level > 2) mono_print_ins_index (0, ins); switch (ins->opcode) { #if 0 case OP_LOAD_MEMBASE: case OP_LOADI4_MEMBASE: /* * OP_IADD reg2, reg1, const1 * OP_LOAD_MEMBASE const2(reg2), reg3 * -> * OP_LOAD_MEMBASE (const1+const2)(reg1), reg3 */ if (last_ins && (last_ins->opcode == OP_IADD_IMM || last_ins->opcode == OP_ADD_IMM) && (last_ins->dreg == ins->inst_basereg) && (last_ins->sreg1 != last_ins->dreg)){ int const1 = last_ins->inst_imm; int const2 = ins->inst_offset; if (mips_is_imm16 (const1 + const2)) { ins->inst_basereg = last_ins->sreg1; ins->inst_offset = const1 + const2; } } break; #endif } last_ins = ins; ins = ins->next; } bb->last_ins = last_ins; } void mono_arch_peephole_pass_2 (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *n, *last_ins = NULL; ins = bb->code; MONO_BB_FOR_EACH_INS_SAFE (bb, n, ins) { MonoInst *last_ins = ins->prev; switch (ins->opcode) { case OP_MUL_IMM: /* remove unnecessary multiplication with 1 */ if (ins->inst_imm == 1) { if (ins->dreg != ins->sreg1) { ins->opcode = OP_MOVE; } else { MONO_DELETE_INS (bb, ins); continue; } } else { int power2 = mono_is_power_of_two (ins->inst_imm); if (power2 > 0) { ins->opcode = OP_SHL_IMM; ins->inst_imm = power2; } } break; case OP_LOAD_MEMBASE: case OP_LOADI4_MEMBASE: /* * OP_STORE_MEMBASE_REG reg, offset(basereg) * OP_LOAD_MEMBASE offset(basereg), reg */ if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_REG || last_ins->opcode == OP_STORE_MEMBASE_REG) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { if (ins->dreg == last_ins->sreg1) { MONO_DELETE_INS (bb, ins); continue; } else { //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++); ins->opcode = OP_MOVE; ins->sreg1 = last_ins->sreg1; } break; } /* * Note: reg1 must be different from the basereg in the second load * OP_LOAD_MEMBASE offset(basereg), reg1 * OP_LOAD_MEMBASE offset(basereg), reg2 * --> * OP_LOAD_MEMBASE offset(basereg), reg1 * OP_MOVE reg1, reg2 */ if (last_ins && (last_ins->opcode == OP_LOADI4_MEMBASE || last_ins->opcode == OP_LOAD_MEMBASE) && ins->inst_basereg != last_ins->dreg && ins->inst_basereg == last_ins->inst_basereg && ins->inst_offset == last_ins->inst_offset) { if (ins->dreg == last_ins->dreg) { MONO_DELETE_INS (bb, ins); continue; } else { ins->opcode = OP_MOVE; ins->sreg1 = last_ins->dreg; } //g_assert_not_reached (); break; } #if 0 /* * OP_STORE_MEMBASE_IMM imm, offset(basereg) * OP_LOAD_MEMBASE offset(basereg), reg * --> * OP_STORE_MEMBASE_IMM imm, offset(basereg) * OP_ICONST reg, imm */ if (last_ins && (last_ins->opcode == OP_STOREI4_MEMBASE_IMM || last_ins->opcode == OP_STORE_MEMBASE_IMM) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { //static int c = 0; printf ("MATCHX %s %d\n", cfg->method->name,c++); ins->opcode = OP_ICONST; ins->inst_c0 = last_ins->inst_imm; g_assert_not_reached (); // check this rule break; } #endif break; case OP_LOADU1_MEMBASE: case OP_LOADI1_MEMBASE: if (last_ins && (last_ins->opcode == OP_STOREI1_MEMBASE_REG) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { ins->opcode = (ins->opcode == OP_LOADI1_MEMBASE) ? OP_ICONV_TO_I1 : OP_ICONV_TO_U1; ins->sreg1 = last_ins->sreg1; } break; case OP_LOADU2_MEMBASE: case OP_LOADI2_MEMBASE: if (last_ins && (last_ins->opcode == OP_STOREI2_MEMBASE_REG) && ins->inst_basereg == last_ins->inst_destbasereg && ins->inst_offset == last_ins->inst_offset) { ins->opcode = (ins->opcode == OP_LOADI2_MEMBASE) ? OP_ICONV_TO_I2 : OP_ICONV_TO_U2; ins->sreg1 = last_ins->sreg1; } break; case OP_ICONV_TO_I4: case OP_ICONV_TO_U4: case OP_MOVE: ins->opcode = OP_MOVE; /* * OP_MOVE reg, reg */ if (ins->dreg == ins->sreg1) { MONO_DELETE_INS (bb, ins); continue; } /* * OP_MOVE sreg, dreg * OP_MOVE dreg, sreg */ if (last_ins && last_ins->opcode == OP_MOVE && ins->sreg1 == last_ins->dreg && ins->dreg == last_ins->sreg1) { MONO_DELETE_INS (bb, ins); continue; } break; } last_ins = ins; ins = ins->next; } bb->last_ins = last_ins; } void mono_arch_decompose_long_opts (MonoCompile *cfg, MonoInst *ins) { int tmp1 = -1; int tmp2 = -1; int tmp3 = -1; int tmp4 = -1; int tmp5 = -1; switch (ins->opcode) { #if 0 case OP_LCOMPARE: case OP_LCOMPARE_IMM: mono_print_ins (ins); g_assert_not_reached (); #endif case OP_LADD: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->dreg+1, ins->sreg1+1); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, ins->dreg+2, tmp1); NULLIFY_INS(ins); break; case OP_LADD_IMM: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IADD_IMM, ins->dreg+1, ins->sreg1+1, ins->inst_ls_word); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->dreg+1, ins->sreg1+1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_IADD_IMM, ins->dreg+2, ins->sreg1+2, ins->inst_ms_word); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, ins->dreg+2, tmp1); NULLIFY_INS(ins); break; case OP_LSUB: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->sreg1+1, ins->dreg+1); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->dreg+2, tmp1); NULLIFY_INS(ins); break; case OP_LSUB_IMM: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISUB_IMM, ins->dreg+1, ins->sreg1+1, ins->inst_ls_word); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->sreg1+1, ins->dreg+1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_ISUB_IMM, ins->dreg+2, ins->sreg1+2, ins->inst_ms_word); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->dreg+2, tmp1); NULLIFY_INS(ins); break; case OP_LMUL: case OP_LDIV: case OP_LDIV_UN: case OP_LREM: case OP_LREM_UN: case OP_LSHL: case OP_LSHR: case OP_LSHR_UN: mono_print_ins (ins); g_assert_not_reached (); case OP_LNEG: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, mips_zero, ins->sreg1+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, mips_zero, ins->dreg+1); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, mips_zero, ins->sreg1+2); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->dreg+2, tmp1); NULLIFY_INS(ins); break; #if 0 case OP_LNOT: #endif #if 0 case OP_LCONV_TO_I1: case OP_LCONV_TO_I2: case OP_LCONV_TO_I4: case OP_LCONV_TO_I8: case OP_LCONV_TO_R4: case OP_LCONV_TO_R8: case OP_LCONV_TO_U4: case OP_LCONV_TO_U8: case OP_LCONV_TO_U2: case OP_LCONV_TO_U1: case OP_LCONV_TO_I: case OP_LCONV_TO_OVF_I: case OP_LCONV_TO_OVF_U: #endif mono_print_ins (ins); g_assert_not_reached (); case OP_LADD_OVF: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); tmp3 = mono_alloc_ireg (cfg); tmp4 = mono_alloc_ireg (cfg); tmp5 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); /* tmp1 holds the carry from the low 32-bit to the high 32-bits */ MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp5, ins->dreg+1, ins->sreg1+1); /* add the high 32-bits, and add in the carry from the low 32-bits */ MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, tmp5, ins->dreg+2); /* Overflow happens if * neg + neg = pos or * pos + pos = neg * XOR of the high bits returns 0 if the signs match * XOR of that with the high bit of the result return 1 if overflow. */ /* tmp1 = 0 if the signs of the two inputs match, 1 otherwise */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp1, ins->sreg1+2, ins->sreg2+2); /* set tmp2 = 0 if bit31 of results matches is different than the operands */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp2, ins->dreg+2, ins->sreg2+2); MONO_EMIT_NEW_UNALU (cfg, OP_INOT, tmp2, tmp2); /* OR(tmp1, tmp2) = 0 if both conditions are true */ MONO_EMIT_NEW_BIALU (cfg, OP_IOR, tmp3, tmp2, tmp1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, tmp4, tmp3, 31); /* Now, if (tmp4 == 0) then overflow */ MONO_EMIT_NEW_COMPARE_EXC (cfg, EQ, tmp4, mips_zero, "OverflowException"); NULLIFY_INS(ins); break; case OP_LADD_OVF_UN: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->dreg+1, ins->sreg1+1); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg+2, tmp1, ins->dreg+2); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp2, ins->dreg+2, ins->sreg1+2); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp2, mips_zero, "OverflowException"); NULLIFY_INS(ins); break; case OP_LMUL_OVF: case OP_LMUL_OVF_UN: mono_print_ins (ins); g_assert_not_reached (); case OP_LSUB_OVF: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); tmp3 = mono_alloc_ireg (cfg); tmp4 = mono_alloc_ireg (cfg); tmp5 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp5, ins->sreg1+1, ins->dreg+1); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->dreg+2, tmp5); /* Overflow happens if * neg - pos = pos or * pos - neg = neg * XOR of bit31 of the lhs & rhs = 1 if the signs are different * * tmp1 = (lhs ^ rhs) * tmp2 = (lhs ^ result) * if ((tmp1 < 0) & (tmp2 < 0)) then overflow */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp1, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp2, ins->sreg1+2, ins->dreg+2); MONO_EMIT_NEW_BIALU (cfg, OP_IAND, tmp3, tmp2, tmp1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, tmp4, tmp3, 31); /* Now, if (tmp4 == 1) then overflow */ MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp4, mips_zero, "OverflowException"); NULLIFY_INS(ins); break; case OP_LSUB_OVF_UN: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+1, ins->sreg1+1, ins->sreg2+1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->sreg1+1, ins->dreg+1); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->sreg1+2, ins->sreg2+2); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg+2, ins->dreg+2, tmp1); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp2, ins->sreg1+2, ins->dreg+2); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp2, mips_zero, "OverflowException"); NULLIFY_INS(ins); break; #if 0 case OP_LCONV_TO_OVF_I1_UN: case OP_LCONV_TO_OVF_I2_UN: case OP_LCONV_TO_OVF_I4_UN: case OP_LCONV_TO_OVF_I8_UN: case OP_LCONV_TO_OVF_U1_UN: case OP_LCONV_TO_OVF_U2_UN: case OP_LCONV_TO_OVF_U4_UN: case OP_LCONV_TO_OVF_U8_UN: case OP_LCONV_TO_OVF_I_UN: case OP_LCONV_TO_OVF_U_UN: case OP_LCONV_TO_OVF_I1: case OP_LCONV_TO_OVF_U1: case OP_LCONV_TO_OVF_I2: case OP_LCONV_TO_OVF_U2: case OP_LCONV_TO_OVF_I4: case OP_LCONV_TO_OVF_U4: case OP_LCONV_TO_OVF_I8: case OP_LCONV_TO_OVF_U8: #endif case OP_LCEQ: case OP_LCGT: case OP_LCGT_UN: case OP_LCLT: case OP_LCLT_UN: #if 0 case OP_LCONV_TO_R_UN: case OP_LCONV_TO_U: #endif case OP_LMUL_IMM: case OP_LSHL_IMM: case OP_LSHR_IMM: case OP_LSHR_UN_IMM: case OP_LDIV_IMM: case OP_LDIV_UN_IMM: case OP_LREM_IMM: case OP_LREM_UN_IMM: case OP_LBEQ: case OP_LBGE: case OP_LBGT: case OP_LBLE: case OP_LBLT: case OP_LBNE_UN: case OP_LBGE_UN: case OP_LBGT_UN: case OP_LBLE_UN: case OP_LBLT_UN: mono_print_ins (ins); g_assert_not_reached (); #if 0 case OP_LCONV_TO_R8_2: case OP_LCONV_TO_R4_2: case OP_LCONV_TO_R_UN_2: #endif case OP_LCONV_TO_OVF_I4_2: tmp1 = mono_alloc_ireg (cfg); /* Overflows if reg2 != sign extension of reg1 */ MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, tmp1, ins->sreg1, 31); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, ins->sreg2, tmp1, "OverflowException"); MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->sreg1); NULLIFY_INS(ins); break; case OP_LMIN_UN: case OP_LMAX_UN: case OP_LMIN: case OP_LMAX: mono_print_ins (ins); g_assert_not_reached (); default: break; } } void mono_arch_decompose_opts (MonoCompile *cfg, MonoInst *ins) { int tmp1 = -1; int tmp2 = -1; int tmp3 = -1; int tmp4 = -1; int tmp5 = -1; switch (ins->opcode) { case OP_IADD_OVF: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); tmp3 = mono_alloc_ireg (cfg); tmp4 = mono_alloc_ireg (cfg); tmp5 = mono_alloc_ireg (cfg); /* add the operands */ MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg, ins->sreg1, ins->sreg2); /* Overflow happens if * neg + neg = pos or * pos + pos = neg * * (bit31s of operands match) AND (bit31 of operand != bit31 of result) * XOR of the high bit returns 0 if the signs match * XOR of that with the high bit of the result return 1 if overflow. */ /* tmp1 = 0 if the signs of the two inputs match, 1 otherwise */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp1, ins->sreg1, ins->sreg2); /* set tmp2 = 0 if bit31 of results matches is different than the operands */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp2, ins->dreg, ins->sreg2); MONO_EMIT_NEW_UNALU (cfg, OP_INOT, tmp3, tmp2); /* OR(tmp1, tmp2) = 0 if both conditions are true */ MONO_EMIT_NEW_BIALU (cfg, OP_IOR, tmp4, tmp3, tmp1); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_SHR_IMM, tmp5, tmp4, 31); /* Now, if (tmp5 == 0) then overflow */ MONO_EMIT_NEW_COMPARE_EXC (cfg, EQ, tmp5, mips_zero, "OverflowException"); /* Make decompse and method-to-ir.c happy, last insn writes dreg */ MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->dreg); NULLIFY_INS(ins); break; case OP_IADD_OVF_UN: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_IADD, ins->dreg, ins->sreg1, ins->sreg2); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->dreg, ins->sreg1); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp1, mips_zero, "OverflowException"); /* Make decompse and method-to-ir.c happy, last insn writes dreg */ MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->dreg); NULLIFY_INS(ins); break; case OP_ISUB_OVF: tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); tmp3 = mono_alloc_ireg (cfg); tmp4 = mono_alloc_ireg (cfg); tmp5 = mono_alloc_ireg (cfg); /* add the operands */ MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg, ins->sreg1, ins->sreg2); /* Overflow happens if * neg - pos = pos or * pos - neg = neg * XOR of bit31 of the lhs & rhs = 1 if the signs are different * * tmp1 = (lhs ^ rhs) * tmp2 = (lhs ^ result) * if ((tmp1 < 0) & (tmp2 < 0)) then overflow */ /* tmp3 = 1 if the signs of the two inputs differ */ MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp1, ins->sreg1, ins->sreg2); MONO_EMIT_NEW_BIALU (cfg, OP_IXOR, tmp2, ins->sreg1, ins->dreg); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MIPS_SLTI, tmp3, tmp1, 0); MONO_EMIT_NEW_BIALU_IMM (cfg, OP_MIPS_SLTI, tmp4, tmp2, 0); MONO_EMIT_NEW_BIALU (cfg, OP_IAND, tmp5, tmp4, tmp3); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp5, mips_zero, "OverflowException"); /* Make decompse and method-to-ir.c happy, last insn writes dreg */ MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->dreg); NULLIFY_INS(ins); break; case OP_ISUB_OVF_UN: tmp1 = mono_alloc_ireg (cfg); MONO_EMIT_NEW_BIALU (cfg, OP_ISUB, ins->dreg, ins->sreg1, ins->sreg2); MONO_EMIT_NEW_BIALU (cfg, OP_MIPS_SLTU, tmp1, ins->sreg1, ins->dreg); MONO_EMIT_NEW_COMPARE_EXC (cfg, NE_UN, tmp1, mips_zero, "OverflowException"); /* Make decompse and method-to-ir.c happy, last insn writes dreg */ MONO_EMIT_NEW_UNALU (cfg, OP_MOVE, ins->dreg, ins->dreg); NULLIFY_INS(ins); break; } } static int map_to_reg_reg_op (int op) { switch (op) { case OP_ADD_IMM: return OP_IADD; case OP_SUB_IMM: return OP_ISUB; case OP_AND_IMM: return OP_IAND; case OP_COMPARE_IMM: return OP_COMPARE; case OP_ICOMPARE_IMM: return OP_ICOMPARE; case OP_LCOMPARE_IMM: return OP_LCOMPARE; case OP_ADDCC_IMM: return OP_IADDCC; case OP_ADC_IMM: return OP_IADC; case OP_SUBCC_IMM: return OP_ISUBCC; case OP_SBB_IMM: return OP_ISBB; case OP_OR_IMM: return OP_IOR; case OP_XOR_IMM: return OP_IXOR; case OP_MUL_IMM: return OP_IMUL; case OP_LOAD_MEMBASE: return OP_LOAD_MEMINDEX; case OP_LOADI4_MEMBASE: return OP_LOADI4_MEMINDEX; case OP_LOADU4_MEMBASE: return OP_LOADU4_MEMINDEX; case OP_LOADU1_MEMBASE: return OP_LOADU1_MEMINDEX; case OP_LOADI2_MEMBASE: return OP_LOADI2_MEMINDEX; case OP_LOADU2_MEMBASE: return OP_LOADU2_MEMINDEX; case OP_LOADI1_MEMBASE: return OP_LOADI1_MEMINDEX; case OP_LOADR4_MEMBASE: return OP_LOADR4_MEMINDEX; case OP_LOADR8_MEMBASE: return OP_LOADR8_MEMINDEX; case OP_STOREI1_MEMBASE_REG: return OP_STOREI1_MEMINDEX; case OP_STOREI2_MEMBASE_REG: return OP_STOREI2_MEMINDEX; case OP_STOREI4_MEMBASE_REG: return OP_STOREI4_MEMINDEX; case OP_STORE_MEMBASE_REG: return OP_STORE_MEMINDEX; case OP_STORER4_MEMBASE_REG: return OP_STORER4_MEMINDEX; case OP_STORER8_MEMBASE_REG: return OP_STORER8_MEMINDEX; case OP_STORE_MEMBASE_IMM: return OP_STORE_MEMBASE_REG; case OP_STOREI1_MEMBASE_IMM: return OP_STOREI1_MEMBASE_REG; case OP_STOREI2_MEMBASE_IMM: return OP_STOREI2_MEMBASE_REG; case OP_STOREI4_MEMBASE_IMM: return OP_STOREI4_MEMBASE_REG; case OP_STOREI8_MEMBASE_IMM: return OP_STOREI8_MEMBASE_REG; } return mono_op_imm_to_op (op); } static int map_to_mips_op (int op) { switch (op) { case OP_FBEQ: return OP_MIPS_FBEQ; case OP_FBGE: return OP_MIPS_FBGE; case OP_FBGT: return OP_MIPS_FBGT; case OP_FBLE: return OP_MIPS_FBLE; case OP_FBLT: return OP_MIPS_FBLT; case OP_FBNE_UN: return OP_MIPS_FBNE; case OP_FBGE_UN: return OP_MIPS_FBGE_UN; case OP_FBGT_UN: return OP_MIPS_FBGT_UN; case OP_FBLE_UN: return OP_MIPS_FBLE_UN; case OP_FBLT_UN: return OP_MIPS_FBLT_UN; case OP_FCEQ: case OP_FCGT: case OP_FCGT_UN: case OP_FCLT: case OP_FCLT_UN: default: g_warning ("unknown opcode %s in %s()\n", mono_inst_name (op), __FUNCTION__); g_assert_not_reached (); } } #define NEW_INS(cfg,after,dest,op) do { \ MONO_INST_NEW((cfg), (dest), (op)); \ mono_bblock_insert_after_ins (bb, (after), (dest)); \ } while (0) #define INS(pos,op,_dreg,_sreg1,_sreg2) do { \ MonoInst *temp; \ MONO_INST_NEW(cfg, temp, (op)); \ mono_bblock_insert_after_ins (bb, (pos), temp); \ temp->dreg = (_dreg); \ temp->sreg1 = (_sreg1); \ temp->sreg2 = (_sreg2); \ pos = temp; \ } while (0) #define INS_IMM(pos,op,_dreg,_sreg1,_imm) do { \ MonoInst *temp; \ MONO_INST_NEW(cfg, temp, (op)); \ mono_bblock_insert_after_ins (bb, (pos), temp); \ temp->dreg = (_dreg); \ temp->sreg1 = (_sreg1); \ temp->inst_c0 = (_imm); \ pos = temp; \ } while (0) /* * Remove from the instruction list the instructions that can't be * represented with very simple instructions with no register * requirements. */ void mono_arch_lowering_pass (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins, *next, *temp, *last_ins = NULL; int imm; #if 1 if (cfg->verbose_level > 2) { int idx = 0; g_print ("BASIC BLOCK %d (before lowering)\n", bb->block_num); MONO_BB_FOR_EACH_INS (bb, ins) { mono_print_ins_index (idx++, ins); } } #endif MONO_BB_FOR_EACH_INS (bb, ins) { loop_start: switch (ins->opcode) { case OP_COMPARE: case OP_ICOMPARE: case OP_LCOMPARE: next = ins->next; /* Branch opts can eliminate the branch */ if (!next || (!(MONO_IS_COND_BRANCH_OP (next) || MONO_IS_COND_EXC (next) || MONO_IS_SETCC (next)))) { NULLIFY_INS(ins); break; } break; case OP_COMPARE_IMM: case OP_ICOMPARE_IMM: case OP_LCOMPARE_IMM: next = ins->next; /* Branch opts can eliminate the branch */ if (!next || (!(MONO_IS_COND_BRANCH_OP (next) || MONO_IS_COND_EXC (next) || MONO_IS_SETCC (next)))) { NULLIFY_INS(ins); break; } if (ins->inst_imm) { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; last_ins = temp; } else { ins->sreg2 = mips_zero; } if (ins->opcode == OP_COMPARE_IMM) ins->opcode = OP_COMPARE; else if (ins->opcode == OP_ICOMPARE_IMM) ins->opcode = OP_ICOMPARE; else if (ins->opcode == OP_LCOMPARE_IMM) ins->opcode = OP_LCOMPARE; goto loop_start; case OP_IDIV_UN_IMM: case OP_IDIV_IMM: case OP_IREM_IMM: case OP_IREM_UN_IMM: NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; if (ins->opcode == OP_IDIV_IMM) ins->opcode = OP_IDIV; else if (ins->opcode == OP_IREM_IMM) ins->opcode = OP_IREM; else if (ins->opcode == OP_IDIV_UN_IMM) ins->opcode = OP_IDIV_UN; else if (ins->opcode == OP_IREM_UN_IMM) ins->opcode = OP_IREM_UN; last_ins = temp; /* handle rem separately */ goto loop_start; #if 0 case OP_AND_IMM: case OP_OR_IMM: case OP_XOR_IMM: if ((ins->inst_imm & 0xffff0000) && (ins->inst_imm & 0xffff)) { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); } break; #endif case OP_AND_IMM: case OP_IAND_IMM: case OP_OR_IMM: case OP_IOR_IMM: case OP_XOR_IMM: case OP_IXOR_IMM: /* unsigned 16 bit immediate */ if (ins->inst_imm & 0xffff0000) { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); } break; case OP_IADD_IMM: case OP_ADD_IMM: case OP_ADDCC_IMM: /* signed 16 bit immediate */ if (!mips_is_imm16 (ins->inst_imm)) { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); } break; case OP_SUB_IMM: case OP_ISUB_IMM: if (!mips_is_imm16 (-ins->inst_imm)) { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); } break; case OP_MUL_IMM: case OP_IMUL_IMM: if (ins->inst_imm == 1) { ins->opcode = OP_MOVE; break; } if (ins->inst_imm == 0) { ins->opcode = OP_ICONST; ins->inst_c0 = 0; break; } imm = mono_is_power_of_two (ins->inst_imm); if (imm > 0) { ins->opcode = OP_SHL_IMM; ins->inst_imm = imm; break; } NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); break; case OP_LOCALLOC_IMM: NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg1 = temp->dreg; ins->opcode = OP_LOCALLOC; break; case OP_LOADR4_MEMBASE: case OP_STORER4_MEMBASE_REG: /* we can do two things: load the immed in a register * and use an indexed load, or see if the immed can be * represented as an ad_imm + a load with a smaller offset * that fits. We just do the first for now, optimize later. */ if (mips_is_imm16 (ins->inst_offset)) break; NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_offset; temp->dreg = mono_alloc_ireg (cfg); ins->sreg2 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); break; case OP_STORE_MEMBASE_IMM: case OP_STOREI1_MEMBASE_IMM: case OP_STOREI2_MEMBASE_IMM: case OP_STOREI4_MEMBASE_IMM: case OP_STOREI8_MEMBASE_IMM: if (!ins->inst_imm) { ins->sreg1 = mips_zero; ins->opcode = map_to_reg_reg_op (ins->opcode); } else { NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = ins->inst_imm; temp->dreg = mono_alloc_ireg (cfg); ins->sreg1 = temp->dreg; ins->opcode = map_to_reg_reg_op (ins->opcode); last_ins = temp; goto loop_start; /* make it handle the possibly big ins->inst_offset */ } break; case OP_FCOMPARE: next = ins->next; /* Branch opts can eliminate the branch */ if (!next || (!(MONO_IS_COND_BRANCH_OP (next) || MONO_IS_COND_EXC (next) || MONO_IS_SETCC (next)))) { NULLIFY_INS(ins); break; } g_assert(next); /* * remap compare/branch and compare/set * to MIPS specific opcodes. */ next->opcode = map_to_mips_op (next->opcode); next->sreg1 = ins->sreg1; next->sreg2 = ins->sreg2; NULLIFY_INS(ins); break; #if 0 case OP_R8CONST: case OP_R4CONST: NEW_INS (cfg, last_ins, temp, OP_ICONST); temp->inst_c0 = (guint32)ins->inst_p0; temp->dreg = mono_alloc_ireg (cfg); ins->inst_basereg = temp->dreg; ins->inst_offset = 0; ins->opcode = ins->opcode == OP_R4CONST? OP_LOADR4_MEMBASE: OP_LOADR8_MEMBASE; last_ins = temp; /* make it handle the possibly big ins->inst_offset * later optimize to use lis + load_membase */ goto loop_start; #endif case OP_IBEQ: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_BEQ, last_ins->sreg1, last_ins->sreg2); NULLIFY_INS(last_ins); break; case OP_IBNE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_BNE, last_ins->sreg1, last_ins->sreg2); NULLIFY_INS(last_ins); break; case OP_IBGE: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLT, last_ins->sreg1, last_ins->sreg2); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BEQ, last_ins->dreg, mips_zero); break; case OP_IBGE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLTU, last_ins->sreg1, last_ins->sreg2); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BEQ, last_ins->dreg, mips_zero); break; case OP_IBLT: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLT, last_ins->sreg1, last_ins->sreg2); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BNE, last_ins->dreg, mips_zero); break; case OP_IBLT_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLTU, last_ins->sreg1, last_ins->sreg2); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BNE, last_ins->dreg, mips_zero); break; case OP_IBLE: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLT, last_ins->sreg2, last_ins->sreg1); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BEQ, last_ins->dreg, mips_zero); break; case OP_IBLE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLTU, last_ins->sreg2, last_ins->sreg1); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BEQ, last_ins->dreg, mips_zero); break; case OP_IBGT: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLT, last_ins->sreg2, last_ins->sreg1); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BNE, last_ins->dreg, mips_zero); break; case OP_IBGT_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(last_ins, OP_MIPS_SLTU, last_ins->sreg2, last_ins->sreg1); last_ins->dreg = mono_alloc_ireg (cfg); INS_REWRITE(ins, OP_MIPS_BNE, last_ins->dreg, mips_zero); break; case OP_CEQ: case OP_ICEQ: g_assert (ins_is_compare(last_ins)); last_ins->opcode = OP_IXOR; last_ins->dreg = mono_alloc_ireg(cfg); INS_REWRITE_IMM(ins, OP_MIPS_SLTIU, last_ins->dreg, 1); break; case OP_CLT: case OP_ICLT: INS_REWRITE(ins, OP_MIPS_SLT, last_ins->sreg1, last_ins->sreg2); NULLIFY_INS(last_ins); break; case OP_CLT_UN: case OP_ICLT_UN: INS_REWRITE(ins, OP_MIPS_SLTU, last_ins->sreg1, last_ins->sreg2); NULLIFY_INS(last_ins); break; case OP_CGT: case OP_ICGT: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_SLT, last_ins->sreg2, last_ins->sreg1); MONO_DELETE_INS(bb, last_ins); break; case OP_CGT_UN: case OP_ICGT_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_SLTU, last_ins->sreg2, last_ins->sreg1); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_EQ: case OP_COND_EXC_IEQ: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_EQ, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_GE: case OP_COND_EXC_IGE: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_GE, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_GT: case OP_COND_EXC_IGT: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_GT, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_LE: case OP_COND_EXC_ILE: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_LE, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_LT: case OP_COND_EXC_ILT: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_LT, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_NE_UN: case OP_COND_EXC_INE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_NE_UN, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_GE_UN: case OP_COND_EXC_IGE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_GE_UN, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_GT_UN: case OP_COND_EXC_IGT_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_GT_UN, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_LE_UN: case OP_COND_EXC_ILE_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_LE_UN, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_LT_UN: case OP_COND_EXC_ILT_UN: g_assert (ins_is_compare(last_ins)); INS_REWRITE(ins, OP_MIPS_COND_EXC_LT_UN, last_ins->sreg1, last_ins->sreg2); MONO_DELETE_INS(bb, last_ins); break; case OP_COND_EXC_OV: case OP_COND_EXC_IOV: { int tmp1, tmp2, tmp3, tmp4, tmp5; MonoInst *pos = last_ins; /* Overflow happens if * neg + neg = pos or * pos + pos = neg * * (bit31s of operands match) AND (bit31 of operand * != bit31 of result) * XOR of the high bit returns 0 if the signs match * XOR of that with the high bit of the result return 1 * if overflow. */ g_assert (last_ins->opcode == OP_IADC); tmp1 = mono_alloc_ireg (cfg); tmp2 = mono_alloc_ireg (cfg); tmp3 = mono_alloc_ireg (cfg); tmp4 = mono_alloc_ireg (cfg); tmp5 = mono_alloc_ireg (cfg); /* tmp1 = 0 if the signs of the two inputs match, else 1 */ INS (pos, OP_IXOR, tmp1, last_ins->sreg1, last_ins->sreg2); /* set tmp2 = 0 if bit31 of results matches is different than the operands */ INS (pos, OP_IXOR, tmp2, last_ins->dreg, last_ins->sreg2); INS (pos, OP_INOT, tmp3, tmp2, -1); /* OR(tmp1, tmp2) = 0 if both conditions are true */ INS (pos, OP_IOR, tmp4, tmp3, tmp1); INS_IMM (pos, OP_SHR_IMM, tmp5, tmp4, 31); /* Now, if (tmp5 == 0) then overflow */ INS_REWRITE(ins, OP_MIPS_COND_EXC_EQ, tmp5, mips_zero); ins->dreg = -1; break; } case OP_COND_EXC_NO: case OP_COND_EXC_INO: g_assert_not_reached (); break; case OP_COND_EXC_C: case OP_COND_EXC_IC: g_assert_not_reached (); break; case OP_COND_EXC_NC: case OP_COND_EXC_INC: g_assert_not_reached (); break; } last_ins = ins; } bb->last_ins = last_ins; bb->max_vreg = cfg->next_vreg; #if 1 if (cfg->verbose_level > 2) { int idx = 0; g_print ("BASIC BLOCK %d (after lowering)\n", bb->block_num); MONO_BB_FOR_EACH_INS (bb, ins) { mono_print_ins_index (idx++, ins); } } #endif } static guchar* emit_float_to_int (MonoCompile *cfg, guchar *code, int dreg, int sreg, int size, gboolean is_signed) { /* sreg is a float, dreg is an integer reg. mips_at is used as scratch */ #if 1 mips_truncwd (code, mips_ftemp, sreg); #else mips_cvtwd (code, mips_ftemp, sreg); #endif mips_mfc1 (code, dreg, mips_ftemp); if (!is_signed) { if (size == 1) mips_andi (code, dreg, dreg, 0xff); else if (size == 2) { mips_sll (code, dreg, dreg, 16); mips_srl (code, dreg, dreg, 16); } } else { if (size == 1) { mips_sll (code, dreg, dreg, 24); mips_sra (code, dreg, dreg, 24); } else if (size == 2) { mips_sll (code, dreg, dreg, 16); mips_sra (code, dreg, dreg, 16); } } return code; } /* * emit_load_volatile_arguments: * * Load volatile arguments from the stack to the original input registers. * Required before a tail call. */ static guint8 * emit_load_volatile_arguments(MonoCompile *cfg, guint8 *code) { MonoMethod *method = cfg->method; MonoMethodSignature *sig; MonoInst *inst; CallInfo *cinfo; int i; sig = mono_method_signature (method); if (!cfg->arch.cinfo) cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig); cinfo = cfg->arch.cinfo; if (cinfo->struct_ret) { ArgInfo *ainfo = &cinfo->ret; inst = cfg->vret_addr; mips_lw (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); } for (i = 0; i < sig->param_count + sig->hasthis; ++i) { ArgInfo *ainfo = cinfo->args + i; inst = cfg->args [i]; if (inst->opcode == OP_REGVAR) { if (ainfo->storage == ArgInIReg) MIPS_MOVE (code, ainfo->reg, inst->dreg); else if (ainfo->storage == ArgInFReg) g_assert_not_reached(); else if (ainfo->storage == ArgOnStack) { /* do nothing */ } else g_assert_not_reached (); } else { if (ainfo->storage == ArgInIReg) { g_assert (mips_is_imm16 (inst->inst_offset)); switch (ainfo->size) { case 1: mips_lb (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); break; case 2: mips_lh (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); break; case 0: /* XXX */ case 4: mips_lw (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); break; case 8: mips_lw (code, ainfo->reg, inst->inst_basereg, inst->inst_offset + ls_word_offset); mips_lw (code, ainfo->reg + 1, inst->inst_basereg, inst->inst_offset + ms_word_offset); break; default: g_assert_not_reached (); break; } } else if (ainfo->storage == ArgOnStack) { /* do nothing */ } else if (ainfo->storage == ArgInFReg) { g_assert (mips_is_imm16 (inst->inst_offset)); if (ainfo->size == 8) { #if _MIPS_SIM == _ABIO32 mips_lwc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset + ls_word_offset); mips_lwc1 (code, ainfo->reg+1, inst->inst_basereg, inst->inst_offset + ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_ldc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); #endif } else if (ainfo->size == 4) mips_lwc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); else g_assert_not_reached (); } else if (ainfo->storage == ArgStructByVal) { int i; int doffset = inst->inst_offset; g_assert (mips_is_imm16 (inst->inst_offset)); g_assert (mips_is_imm16 (inst->inst_offset + ainfo->size * sizeof (gpointer))); for (i = 0; i < ainfo->size; ++i) { mips_lw (code, ainfo->reg + i, inst->inst_basereg, doffset); doffset += SIZEOF_REGISTER; } } else if (ainfo->storage == ArgStructByAddr) { g_assert (mips_is_imm16 (inst->inst_offset)); mips_lw (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); } else g_assert_not_reached (); } } return code; } static guint8* emit_reserve_param_area (MonoCompile *cfg, guint8 *code) { int size = cfg->param_area; size += MONO_ARCH_FRAME_ALIGNMENT - 1; size &= -MONO_ARCH_FRAME_ALIGNMENT; if (!size) return code; #if 0 ppc_lwz (code, ppc_r0, 0, ppc_sp); if (ppc_is_imm16 (-size)) { ppc_stwu (code, ppc_r0, -size, ppc_sp); } else { ppc_load (code, ppc_r12, -size); ppc_stwux (code, ppc_r0, ppc_sp, ppc_r12); } #endif return code; } static guint8* emit_unreserve_param_area (MonoCompile *cfg, guint8 *code) { int size = cfg->param_area; size += MONO_ARCH_FRAME_ALIGNMENT - 1; size &= -MONO_ARCH_FRAME_ALIGNMENT; if (!size) return code; #if 0 ppc_lwz (code, ppc_r0, 0, ppc_sp); if (ppc_is_imm16 (size)) { ppc_stwu (code, ppc_r0, size, ppc_sp); } else { ppc_load (code, ppc_r12, size); ppc_stwux (code, ppc_r0, ppc_sp, ppc_r12); } #endif return code; } void mono_arch_output_basic_block (MonoCompile *cfg, MonoBasicBlock *bb) { MonoInst *ins; MonoCallInst *call; guint offset; guint8 *code = cfg->native_code + cfg->code_len; MonoInst *last_ins = NULL; guint last_offset = 0; int max_len, cpos; int ins_cnt = 0; /* we don't align basic blocks of loops on mips */ if (cfg->verbose_level > 2) g_print ("Basic block %d starting at offset 0x%x\n", bb->block_num, bb->native_offset); cpos = bb->max_offset; #if 0 if (cfg->prof_options & MONO_PROFILE_COVERAGE) { MonoCoverageInfo *cov = mono_get_coverage_info (cfg->method); g_assert (!mono_compile_aot); cpos += 20; if (bb->cil_code) cov->data [bb->dfn].iloffset = bb->cil_code - cfg->cil_code; /* this is not thread save, but good enough */ /* fixme: howto handle overflows? */ mips_load_const (code, mips_at, &cov->data [bb->dfn].count); mips_lw (code, mips_temp, mips_at, 0); mips_addiu (code, mips_temp, mips_temp, 1); mips_sw (code, mips_temp, mips_at, 0); } #endif MONO_BB_FOR_EACH_INS (bb, ins) { offset = code - cfg->native_code; max_len = ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN]; if (offset > (cfg->code_size - max_len - 16)) { cfg->code_size *= 2; cfg->native_code = g_realloc (cfg->native_code, cfg->code_size); code = cfg->native_code + offset; } mono_debug_record_line_number (cfg, ins, offset); if (cfg->verbose_level > 2) { g_print (" @ 0x%x\t", offset); mono_print_ins_index (ins_cnt++, ins); } /* Check for virtual regs that snuck by */ g_assert ((ins->dreg >= -1) && (ins->dreg < 32)); switch (ins->opcode) { case OP_RELAXED_NOP: case OP_NOP: case OP_DUMMY_USE: case OP_DUMMY_STORE: case OP_NOT_REACHED: case OP_NOT_NULL: break; case OP_IL_SEQ_POINT: mono_add_seq_point (cfg, bb, ins, code - cfg->native_code); break; case OP_SEQ_POINT: { if (ins->flags & MONO_INST_SINGLE_STEP_LOC) { guint32 addr = (guint32)ss_trigger_page; mips_load_const (code, mips_t9, addr); mips_lw (code, mips_t9, mips_t9, 0); } mono_add_seq_point (cfg, bb, ins, code - cfg->native_code); /* * A placeholder for a possible breakpoint inserted by * mono_arch_set_breakpoint (). */ /* mips_load_const () + mips_lw */ mips_nop (code); mips_nop (code); mips_nop (code); break; } case OP_TLS_GET: g_assert_not_reached(); #if 0 emit_tls_access (code, ins->dreg, ins->inst_offset); #endif break; case OP_BIGMUL: mips_mult (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); mips_mfhi (code, ins->dreg+1); break; case OP_BIGMUL_UN: mips_multu (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); mips_mfhi (code, ins->dreg+1); break; case OP_MEMORY_BARRIER: mips_sync (code, 0); break; case OP_STOREI1_MEMBASE_IMM: mips_load_const (code, mips_temp, ins->inst_imm); if (mips_is_imm16 (ins->inst_offset)) { mips_sb (code, mips_temp, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_sb (code, mips_temp, mips_at, ins->inst_destbasereg); } break; case OP_STOREI2_MEMBASE_IMM: mips_load_const (code, mips_temp, ins->inst_imm); if (mips_is_imm16 (ins->inst_offset)) { mips_sh (code, mips_temp, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_sh (code, mips_temp, mips_at, ins->inst_destbasereg); } break; case OP_STOREI8_MEMBASE_IMM: mips_load_const (code, mips_temp, ins->inst_imm); if (mips_is_imm16 (ins->inst_offset)) { mips_sd (code, mips_temp, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_sd (code, mips_temp, mips_at, ins->inst_destbasereg); } break; case OP_STORE_MEMBASE_IMM: case OP_STOREI4_MEMBASE_IMM: mips_load_const (code, mips_temp, ins->inst_imm); if (mips_is_imm16 (ins->inst_offset)) { mips_sw (code, mips_temp, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_sw (code, mips_temp, mips_at, ins->inst_destbasereg); } break; case OP_STOREI1_MEMBASE_REG: if (mips_is_imm16 (ins->inst_offset)) { mips_sb (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_destbasereg); mips_sb (code, ins->sreg1, mips_at, 0); } break; case OP_STOREI2_MEMBASE_REG: if (mips_is_imm16 (ins->inst_offset)) { mips_sh (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_destbasereg); mips_sh (code, ins->sreg1, mips_at, 0); } break; case OP_STORE_MEMBASE_REG: case OP_STOREI4_MEMBASE_REG: if (mips_is_imm16 (ins->inst_offset)) { mips_sw (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_destbasereg); mips_sw (code, ins->sreg1, mips_at, 0); } break; case OP_STOREI8_MEMBASE_REG: if (mips_is_imm16 (ins->inst_offset)) { mips_sd (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_destbasereg); mips_sd (code, ins->sreg1, mips_at, 0); } break; case OP_LOADU4_MEM: g_assert_not_reached (); //x86_mov_reg_imm (code, ins->dreg, ins->inst_p0); //x86_mov_reg_membase (code, ins->dreg, ins->dreg, 0, 4); break; case OP_LOADI8_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { mips_ld (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_ld (code, ins->dreg, mips_at, 0); } break; case OP_LOAD_MEMBASE: case OP_LOADI4_MEMBASE: case OP_LOADU4_MEMBASE: g_assert (ins->dreg != -1); if (mips_is_imm16 (ins->inst_offset)) { mips_lw (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lw (code, ins->dreg, mips_at, 0); } break; case OP_LOADI1_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { mips_lb (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lb (code, ins->dreg, mips_at, 0); } break; case OP_LOADU1_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { mips_lbu (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lbu (code, ins->dreg, mips_at, 0); } break; case OP_LOADI2_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { mips_lh (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lh (code, ins->dreg, mips_at, 0); } break; case OP_LOADU2_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { mips_lhu (code, ins->dreg, ins->inst_basereg, ins->inst_offset); } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lhu (code, ins->dreg, mips_at, 0); } break; case OP_ICONV_TO_I1: mips_sll (code, mips_at, ins->sreg1, 24); mips_sra (code, ins->dreg, mips_at, 24); break; case OP_ICONV_TO_I2: mips_sll (code, mips_at, ins->sreg1, 16); mips_sra (code, ins->dreg, mips_at, 16); break; case OP_ICONV_TO_U1: mips_andi (code, ins->dreg, ins->sreg1, 0xff); break; case OP_ICONV_TO_U2: mips_sll (code, mips_at, ins->sreg1, 16); mips_srl (code, ins->dreg, mips_at, 16); break; case OP_MIPS_SLT: mips_slt (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_MIPS_SLTI: g_assert (mips_is_imm16 (ins->inst_imm)); mips_slti (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_MIPS_SLTU: mips_sltu (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_MIPS_SLTIU: g_assert (mips_is_imm16 (ins->inst_imm)); mips_sltiu (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_BREAK: /* * gdb does not like encountering the hw breakpoint ins in the debugged code. * So instead of emitting a trap, we emit a call a C function and place a * breakpoint there. */ mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_INTERNAL_METHOD, (gpointer)"mono_break"); mips_load (code, mips_t9, 0x1f1f1f1f); mips_jalr (code, mips_t9, mips_ra); mips_nop (code); break; case OP_IADD: mips_addu (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_LADD: mips_daddu (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_ADD_IMM: case OP_IADD_IMM: g_assert (mips_is_imm16 (ins->inst_imm)); mips_addiu (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_LADD_IMM: g_assert (mips_is_imm16 (ins->inst_imm)); mips_daddiu (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_ISUB: mips_subu (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_LSUB: mips_dsubu (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_ISUB_IMM: case OP_SUB_IMM: // we add the negated value g_assert (mips_is_imm16 (-ins->inst_imm)); mips_addiu (code, ins->dreg, ins->sreg1, -ins->inst_imm); break; case OP_LSUB_IMM: // we add the negated value g_assert (mips_is_imm16 (-ins->inst_imm)); mips_daddiu (code, ins->dreg, ins->sreg1, -ins->inst_imm); break; case OP_IAND: case OP_LAND: mips_and (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_AND_IMM: case OP_IAND_IMM: case OP_LAND_IMM: g_assert (!(ins->inst_imm & 0xffff0000)); mips_andi (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_IDIV: case OP_IREM: { guint32 *divisor_is_m1; guint32 *dividend_is_minvalue; guint32 *divisor_is_zero; mips_load_const (code, mips_at, -1); divisor_is_m1 = (guint32 *)(void *)code; mips_bne (code, ins->sreg2, mips_at, 0); mips_lui (code, mips_at, mips_zero, 0x8000); dividend_is_minvalue = (guint32 *)(void *)code; mips_bne (code, ins->sreg1, mips_at, 0); mips_nop (code); /* Divide Int32.MinValue by -1 -- throw exception */ EMIT_SYSTEM_EXCEPTION_NAME("OverflowException"); mips_patch (divisor_is_m1, (guint32)code); mips_patch (dividend_is_minvalue, (guint32)code); /* Put divide in branch delay slot (NOT YET) */ divisor_is_zero = (guint32 *)(void *)code; mips_bne (code, ins->sreg2, mips_zero, 0); mips_nop (code); /* Divide by zero -- throw exception */ EMIT_SYSTEM_EXCEPTION_NAME("DivideByZeroException"); mips_patch (divisor_is_zero, (guint32)code); mips_div (code, ins->sreg1, ins->sreg2); if (ins->opcode == OP_IDIV) mips_mflo (code, ins->dreg); else mips_mfhi (code, ins->dreg); break; } case OP_IDIV_UN: case OP_IREM_UN: { guint32 *divisor_is_zero = (guint32 *)(void *)code; /* Put divide in branch delay slot (NOT YET) */ mips_bne (code, ins->sreg2, mips_zero, 0); mips_nop (code); /* Divide by zero -- throw exception */ EMIT_SYSTEM_EXCEPTION_NAME("DivideByZeroException"); mips_patch (divisor_is_zero, (guint32)code); mips_divu (code, ins->sreg1, ins->sreg2); if (ins->opcode == OP_IDIV_UN) mips_mflo (code, ins->dreg); else mips_mfhi (code, ins->dreg); break; } case OP_DIV_IMM: g_assert_not_reached (); #if 0 ppc_load (code, ppc_r12, ins->inst_imm); ppc_divwod (code, ins->dreg, ins->sreg1, ppc_r12); ppc_mfspr (code, ppc_r0, ppc_xer); ppc_andisd (code, ppc_r0, ppc_r0, (1<<14)); /* FIXME: use OverflowException for 0x80000000/-1 */ EMIT_COND_SYSTEM_EXCEPTION_FLAGS (PPC_BR_FALSE, PPC_BR_EQ, "DivideByZeroException"); #endif g_assert_not_reached(); break; case OP_REM_IMM: g_assert_not_reached (); case OP_IOR: mips_or (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_OR_IMM: case OP_IOR_IMM: g_assert (!(ins->inst_imm & 0xffff0000)); mips_ori (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_IXOR: mips_xor (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_XOR_IMM: case OP_IXOR_IMM: /* unsigned 16-bit immediate */ g_assert (!(ins->inst_imm & 0xffff0000)); mips_xori (code, ins->dreg, ins->sreg1, ins->inst_imm); break; case OP_ISHL: mips_sllv (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_SHL_IMM: case OP_ISHL_IMM: mips_sll (code, ins->dreg, ins->sreg1, ins->inst_imm & 0x1f); break; case OP_ISHR: mips_srav (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_LSHR: mips_dsrav (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_SHR_IMM: case OP_ISHR_IMM: mips_sra (code, ins->dreg, ins->sreg1, ins->inst_imm & 0x1f); break; case OP_LSHR_IMM: mips_dsra (code, ins->dreg, ins->sreg1, ins->inst_imm & 0x3f); break; case OP_SHR_UN_IMM: case OP_ISHR_UN_IMM: mips_srl (code, ins->dreg, ins->sreg1, ins->inst_imm & 0x1f); break; case OP_LSHR_UN_IMM: mips_dsrl (code, ins->dreg, ins->sreg1, ins->inst_imm & 0x3f); break; case OP_ISHR_UN: mips_srlv (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_LSHR_UN: mips_dsrlv (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_INOT: case OP_LNOT: mips_nor (code, ins->dreg, mips_zero, ins->sreg1); break; case OP_INEG: mips_subu (code, ins->dreg, mips_zero, ins->sreg1); break; case OP_LNEG: mips_dsubu (code, ins->dreg, mips_zero, ins->sreg1); break; case OP_IMUL: #if USE_MUL mips_mul (code, ins->dreg, ins->sreg1, ins->sreg2); #else mips_mult (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); mips_nop (code); mips_nop (code); #endif break; #if SIZEOF_REGISTER == 8 case OP_LMUL: mips_dmult (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); break; #endif case OP_IMUL_OVF: { guint32 *patch; mips_mult (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); mips_mfhi (code, mips_at); mips_nop (code); mips_nop (code); mips_sra (code, mips_temp, ins->dreg, 31); patch = (guint32 *)(void *)code; mips_beq (code, mips_temp, mips_at, 0); mips_nop (code); EMIT_SYSTEM_EXCEPTION_NAME("OverflowException"); mips_patch (patch, (guint32)code); break; } case OP_IMUL_OVF_UN: { guint32 *patch; mips_mult (code, ins->sreg1, ins->sreg2); mips_mflo (code, ins->dreg); mips_mfhi (code, mips_at); mips_nop (code); mips_nop (code); patch = (guint32 *)(void *)code; mips_beq (code, mips_at, mips_zero, 0); mips_nop (code); EMIT_SYSTEM_EXCEPTION_NAME("OverflowException"); mips_patch (patch, (guint32)code); break; } case OP_ICONST: mips_load_const (code, ins->dreg, ins->inst_c0); break; #if SIZEOF_REGISTER == 8 case OP_I8CONST: mips_load_const (code, ins->dreg, ins->inst_c0); break; #endif case OP_AOTCONST: mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_i1, ins->inst_p0); mips_load (code, ins->dreg, 0); break; case OP_MIPS_MTC1S: mips_mtc1 (code, ins->dreg, ins->sreg1); break; case OP_MIPS_MTC1S_2: mips_mtc1 (code, ins->dreg, ins->sreg1); mips_mtc1 (code, ins->dreg+1, ins->sreg2); break; case OP_MIPS_MFC1S: mips_mfc1 (code, ins->dreg, ins->sreg1); break; case OP_MIPS_MTC1D: mips_dmtc1 (code, ins->dreg, ins->sreg1); break; case OP_MIPS_MFC1D: #if 0 mips_dmfc1 (code, ins->dreg, ins->sreg1); #else mips_mfc1 (code, ins->dreg, ins->sreg1 + ls_word_idx); mips_mfc1 (code, ins->dreg+1, ins->sreg1 + ms_word_idx); #endif break; case OP_ICONV_TO_I4: case OP_ICONV_TO_U4: case OP_MOVE: if (ins->dreg != ins->sreg1) MIPS_MOVE (code, ins->dreg, ins->sreg1); break; #if SIZEOF_REGISTER == 8 case OP_ZEXT_I4: mips_dsll (code, ins->dreg, ins->sreg1, 32); mips_dsrl (code, ins->dreg, ins->dreg, 32); break; case OP_SEXT_I4: mips_dsll (code, ins->dreg, ins->sreg1, 32); mips_dsra (code, ins->dreg, ins->dreg, 32); break; #endif case OP_SETLRET: { int lsreg = mips_v0 + ls_word_idx; int msreg = mips_v0 + ms_word_idx; /* Get sreg1 into lsreg, sreg2 into msreg */ if (ins->sreg1 == msreg) { if (ins->sreg1 != mips_at) MIPS_MOVE (code, mips_at, ins->sreg1); if (ins->sreg2 != msreg) MIPS_MOVE (code, msreg, ins->sreg2); MIPS_MOVE (code, lsreg, mips_at); } else { if (ins->sreg2 != msreg) MIPS_MOVE (code, msreg, ins->sreg2); if (ins->sreg1 != lsreg) MIPS_MOVE (code, lsreg, ins->sreg1); } break; } case OP_FMOVE: if (ins->dreg != ins->sreg1) { mips_fmovd (code, ins->dreg, ins->sreg1); } break; case OP_MOVE_F_TO_I4: mips_cvtsd (code, mips_ftemp, ins->sreg1); mips_mfc1 (code, ins->dreg, mips_ftemp); break; case OP_MOVE_I4_TO_F: mips_mtc1 (code, ins->dreg, ins->sreg1); mips_cvtds (code, ins->dreg, ins->dreg); break; case OP_MIPS_CVTSD: /* Convert from double to float and leave it there */ mips_cvtsd (code, ins->dreg, ins->sreg1); break; case OP_FCONV_TO_R4: #if 0 mips_cvtsd (code, ins->dreg, ins->sreg1); #else /* Just a move, no precision change */ if (ins->dreg != ins->sreg1) { mips_fmovd (code, ins->dreg, ins->sreg1); } #endif break; case OP_JMP: code = emit_load_volatile_arguments(cfg, code); /* * Pop our stack, then jump to specified method (tail-call) * Keep in sync with mono_arch_emit_epilog */ code = mono_arch_emit_epilog_sub (cfg, code); mono_add_patch_info (cfg, (guint8*) code - cfg->native_code, MONO_PATCH_INFO_METHOD_JUMP, ins->inst_p0); mips_load (code, mips_t9, 0); mips_jr (code, mips_t9); mips_nop (code); break; case OP_CHECK_THIS: /* ensure ins->sreg1 is not NULL */ mips_lw (code, mips_zero, ins->sreg1, 0); break; case OP_ARGLIST: { g_assert (mips_is_imm16 (cfg->sig_cookie)); mips_lw (code, mips_at, cfg->frame_reg, cfg->sig_cookie); mips_sw (code, mips_at, ins->sreg1, 0); break; } case OP_FCALL: case OP_LCALL: case OP_VCALL: case OP_VCALL2: case OP_VOIDCALL: case OP_CALL: case OP_FCALL_REG: case OP_LCALL_REG: case OP_VCALL_REG: case OP_VCALL2_REG: case OP_VOIDCALL_REG: case OP_CALL_REG: case OP_FCALL_MEMBASE: case OP_LCALL_MEMBASE: case OP_VCALL_MEMBASE: case OP_VCALL2_MEMBASE: case OP_VOIDCALL_MEMBASE: case OP_CALL_MEMBASE: call = (MonoCallInst*)ins; switch (ins->opcode) { case OP_FCALL: case OP_LCALL: case OP_VCALL: case OP_VCALL2: case OP_VOIDCALL: case OP_CALL: if (ins->flags & MONO_INST_HAS_METHOD) { mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_METHOD, call->method); mips_load (code, mips_t9, call->method); } else { mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_ABS, call->fptr); mips_load (code, mips_t9, call->fptr); } mips_jalr (code, mips_t9, mips_ra); mips_nop (code); break; case OP_FCALL_REG: case OP_LCALL_REG: case OP_VCALL_REG: case OP_VCALL2_REG: case OP_VOIDCALL_REG: case OP_CALL_REG: MIPS_MOVE (code, mips_t9, ins->sreg1); mips_jalr (code, mips_t9, mips_ra); mips_nop (code); break; case OP_FCALL_MEMBASE: case OP_LCALL_MEMBASE: case OP_VCALL_MEMBASE: case OP_VCALL2_MEMBASE: case OP_VOIDCALL_MEMBASE: case OP_CALL_MEMBASE: mips_lw (code, mips_t9, ins->sreg1, ins->inst_offset); mips_jalr (code, mips_t9, mips_ra); mips_nop (code); break; } #if PROMOTE_R4_TO_R8 /* returned an FP R4 (single), promote to R8 (double) in place */ switch (ins->opcode) { case OP_FCALL: case OP_FCALL_REG: case OP_FCALL_MEMBASE: if (call->signature->ret->type == MONO_TYPE_R4) mips_cvtds (code, mips_f0, mips_f0); break; default: break; } #endif break; case OP_LOCALLOC: { int area_offset = cfg->param_area; /* Round up ins->sreg1, mips_at ends up holding size */ mips_addiu (code, mips_at, ins->sreg1, 31); mips_addiu (code, mips_temp, mips_zero, ~31); mips_and (code, mips_at, mips_at, mips_temp); mips_subu (code, mips_sp, mips_sp, mips_at); g_assert (mips_is_imm16 (area_offset)); mips_addiu (code, ins->dreg, mips_sp, area_offset); if (ins->flags & MONO_INST_INIT) { guint32 *buf; buf = (guint32*)(void*)code; mips_beq (code, mips_at, mips_zero, 0); mips_nop (code); mips_move (code, mips_temp, ins->dreg); mips_sb (code, mips_zero, mips_temp, 0); mips_addiu (code, mips_at, mips_at, -1); mips_bne (code, mips_at, mips_zero, -3); mips_addiu (code, mips_temp, mips_temp, 1); mips_patch (buf, (guint32)code); } break; } case OP_THROW: { gpointer addr = mono_arch_get_throw_exception(NULL, FALSE); mips_move (code, mips_a0, ins->sreg1); mips_call (code, mips_t9, addr); mips_break (code, 0xfc); break; } case OP_RETHROW: { gpointer addr = mono_arch_get_rethrow_exception(NULL, FALSE); mips_move (code, mips_a0, ins->sreg1); mips_call (code, mips_t9, addr); mips_break (code, 0xfb); break; } case OP_START_HANDLER: { /* * The START_HANDLER instruction marks the beginning of * a handler block. It is called using a call * instruction, so mips_ra contains the return address. * Since the handler executes in the same stack frame * as the method itself, we can't use save/restore to * save the return address. Instead, we save it into * a dedicated variable. */ MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); g_assert (spvar->inst_basereg != mips_sp); code = emit_reserve_param_area (cfg, code); if (mips_is_imm16 (spvar->inst_offset)) { mips_sw (code, mips_ra, spvar->inst_basereg, spvar->inst_offset); } else { mips_load_const (code, mips_at, spvar->inst_offset); mips_addu (code, mips_at, mips_at, spvar->inst_basereg); mips_sw (code, mips_ra, mips_at, 0); } break; } case OP_ENDFILTER: { MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); g_assert (spvar->inst_basereg != mips_sp); code = emit_unreserve_param_area (cfg, code); if (ins->sreg1 != mips_v0) MIPS_MOVE (code, mips_v0, ins->sreg1); if (mips_is_imm16 (spvar->inst_offset)) { mips_lw (code, mips_ra, spvar->inst_basereg, spvar->inst_offset); } else { mips_load_const (code, mips_at, spvar->inst_offset); mips_addu (code, mips_at, mips_at, spvar->inst_basereg); mips_lw (code, mips_ra, mips_at, 0); } mips_jr (code, mips_ra); mips_nop (code); break; } case OP_ENDFINALLY: { MonoInst *spvar = mono_find_spvar_for_region (cfg, bb->region); g_assert (spvar->inst_basereg != mips_sp); code = emit_unreserve_param_area (cfg, code); mips_lw (code, mips_t9, spvar->inst_basereg, spvar->inst_offset); mips_jalr (code, mips_t9, mips_ra); mips_nop (code); break; } case OP_CALL_HANDLER: mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb); mips_lui (code, mips_t9, mips_zero, 0); mips_addiu (code, mips_t9, mips_t9, 0); mips_jalr (code, mips_t9, mips_ra); mips_nop (code); /*FIXME should it be before the NOP or not? Does MIPS has a delay slot like sparc?*/ mono_cfg_add_try_hole (cfg, ins->inst_eh_block, code, bb); break; case OP_LABEL: ins->inst_c0 = code - cfg->native_code; break; case OP_BR: mono_add_patch_info (cfg, offset, MONO_PATCH_INFO_BB, ins->inst_target_bb); if (cfg->arch.long_branch) { mips_lui (code, mips_at, mips_zero, 0); mips_addiu (code, mips_at, mips_at, 0); mips_jr (code, mips_at); mips_nop (code); } else { mips_beq (code, mips_zero, mips_zero, 0); mips_nop (code); } break; case OP_BR_REG: mips_jr (code, ins->sreg1); mips_nop (code); break; case OP_SWITCH: { int i; max_len += 4 * GPOINTER_TO_INT (ins->klass); if (offset > (cfg->code_size - max_len - 16)) { cfg->code_size += max_len; cfg->code_size *= 2; cfg->native_code = g_realloc (cfg->native_code, cfg->code_size); code = cfg->native_code + offset; } g_assert (ins->sreg1 != -1); mips_sll (code, mips_at, ins->sreg1, 2); if (1 || !(cfg->flags & MONO_CFG_HAS_CALLS)) MIPS_MOVE (code, mips_t8, mips_ra); mips_bgezal (code, mips_zero, 1); /* bal */ mips_nop (code); mips_addu (code, mips_t9, mips_ra, mips_at); /* Table is 16 or 20 bytes from target of bal above */ if (1 || !(cfg->flags & MONO_CFG_HAS_CALLS)) { MIPS_MOVE (code, mips_ra, mips_t8); mips_lw (code, mips_t9, mips_t9, 20); } else mips_lw (code, mips_t9, mips_t9, 16); mips_jalr (code, mips_t9, mips_t8); mips_nop (code); for (i = 0; i < GPOINTER_TO_INT (ins->klass); ++i) mips_emit32 (code, 0xfefefefe); break; } case OP_CEQ: case OP_ICEQ: mips_addiu (code, ins->dreg, mips_zero, 1); mips_beq (code, mips_at, mips_zero, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_CLT: case OP_CLT_UN: case OP_ICLT: case OP_ICLT_UN: mips_addiu (code, ins->dreg, mips_zero, 1); mips_bltz (code, mips_at, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_CGT: case OP_CGT_UN: case OP_ICGT: case OP_ICGT_UN: mips_addiu (code, ins->dreg, mips_zero, 1); mips_bgtz (code, mips_at, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_MIPS_COND_EXC_EQ: case OP_MIPS_COND_EXC_GE: case OP_MIPS_COND_EXC_GT: case OP_MIPS_COND_EXC_LE: case OP_MIPS_COND_EXC_LT: case OP_MIPS_COND_EXC_NE_UN: case OP_MIPS_COND_EXC_GE_UN: case OP_MIPS_COND_EXC_GT_UN: case OP_MIPS_COND_EXC_LE_UN: case OP_MIPS_COND_EXC_LT_UN: case OP_MIPS_COND_EXC_OV: case OP_MIPS_COND_EXC_NO: case OP_MIPS_COND_EXC_C: case OP_MIPS_COND_EXC_NC: case OP_MIPS_COND_EXC_IEQ: case OP_MIPS_COND_EXC_IGE: case OP_MIPS_COND_EXC_IGT: case OP_MIPS_COND_EXC_ILE: case OP_MIPS_COND_EXC_ILT: case OP_MIPS_COND_EXC_INE_UN: case OP_MIPS_COND_EXC_IGE_UN: case OP_MIPS_COND_EXC_IGT_UN: case OP_MIPS_COND_EXC_ILE_UN: case OP_MIPS_COND_EXC_ILT_UN: case OP_MIPS_COND_EXC_IOV: case OP_MIPS_COND_EXC_INO: case OP_MIPS_COND_EXC_IC: case OP_MIPS_COND_EXC_INC: { guint32 *skip; guint32 *throw; /* If the condition is true, raise the exception */ /* need to reverse test to skip around exception raising */ /* For the moment, branch around a branch to avoid reversing the tests. */ /* Remember, an unpatched branch to 0 branches to the delay slot */ switch (ins->opcode) { case OP_MIPS_COND_EXC_EQ: throw = (guint32 *)(void *)code; mips_beq (code, ins->sreg1, ins->sreg2, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_NE_UN: throw = (guint32 *)(void *)code; mips_bne (code, ins->sreg1, ins->sreg2, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_LE_UN: mips_sltu (code, mips_at, ins->sreg2, ins->sreg1); throw = (guint32 *)(void *)code; mips_beq (code, mips_at, mips_zero, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_GT: mips_slt (code, mips_at, ins->sreg2, ins->sreg1); throw = (guint32 *)(void *)code; mips_bne (code, mips_at, mips_zero, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_GT_UN: mips_sltu (code, mips_at, ins->sreg2, ins->sreg1); throw = (guint32 *)(void *)code; mips_bne (code, mips_at, mips_zero, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_LT: mips_slt (code, mips_at, ins->sreg1, ins->sreg2); throw = (guint32 *)(void *)code; mips_bne (code, mips_at, mips_zero, 0); mips_nop (code); break; case OP_MIPS_COND_EXC_LT_UN: mips_sltu (code, mips_at, ins->sreg1, ins->sreg2); throw = (guint32 *)(void *)code; mips_bne (code, mips_at, mips_zero, 0); mips_nop (code); break; default: /* Not yet implemented */ g_warning ("NYI conditional exception %s\n", mono_inst_name (ins->opcode)); g_assert_not_reached (); } skip = (guint32 *)(void *)code; mips_beq (code, mips_zero, mips_zero, 0); mips_nop (code); mips_patch (throw, (guint32)code); code = mips_emit_exc_by_name (code, ins->inst_p1); mips_patch (skip, (guint32)code); cfg->bb_exit->max_offset += 24; break; } case OP_MIPS_BEQ: case OP_MIPS_BNE: case OP_MIPS_BGEZ: case OP_MIPS_BGTZ: case OP_MIPS_BLEZ: case OP_MIPS_BLTZ: code = mips_emit_cond_branch (cfg, code, ins->opcode, ins); break; /* floating point opcodes */ case OP_R8CONST: #if 0 if (((guint32)ins->inst_p0) & (1 << 15)) mips_lui (code, mips_at, mips_zero, (((guint32)ins->inst_p0)>>16)+1); else mips_lui (code, mips_at, mips_zero, (((guint32)ins->inst_p0)>>16)); mips_ldc1 (code, ins->dreg, mips_at, ((guint32)ins->inst_p0) & 0xffff); #else mips_load_const (code, mips_at, ins->inst_p0); mips_lwc1 (code, ins->dreg, mips_at, ls_word_offset); mips_lwc1 (code, ins->dreg+1, mips_at, ms_word_offset); #endif break; case OP_R4CONST: if (((guint32)ins->inst_p0) & (1 << 15)) mips_lui (code, mips_at, mips_zero, (((guint32)ins->inst_p0)>>16)+1); else mips_lui (code, mips_at, mips_zero, (((guint32)ins->inst_p0)>>16)); mips_lwc1 (code, ins->dreg, mips_at, ((guint32)ins->inst_p0) & 0xffff); #if PROMOTE_R4_TO_R8 mips_cvtds (code, ins->dreg, ins->dreg); #endif break; case OP_STORER8_MEMBASE_REG: if (mips_is_imm16 (ins->inst_offset)) { #if _MIPS_SIM == _ABIO32 mips_swc1 (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset + ls_word_offset); mips_swc1 (code, ins->sreg1+1, ins->inst_destbasereg, ins->inst_offset + ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_sdc1 (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); #endif } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_destbasereg); mips_swc1 (code, ins->sreg1, mips_at, ls_word_offset); mips_swc1 (code, ins->sreg1+1, mips_at, ms_word_offset); } break; case OP_LOADR8_MEMBASE: if (mips_is_imm16 (ins->inst_offset)) { #if _MIPS_SIM == _ABIO32 mips_lwc1 (code, ins->dreg, ins->inst_basereg, ins->inst_offset + ls_word_offset); mips_lwc1 (code, ins->dreg+1, ins->inst_basereg, ins->inst_offset + ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_ldc1 (code, ins->dreg, ins->inst_basereg, ins->inst_offset); #endif } else { mips_load_const (code, mips_at, ins->inst_offset); mips_addu (code, mips_at, mips_at, ins->inst_basereg); mips_lwc1 (code, ins->dreg, mips_at, ls_word_offset); mips_lwc1 (code, ins->dreg+1, mips_at, ms_word_offset); } break; case OP_STORER4_MEMBASE_REG: g_assert (mips_is_imm16 (ins->inst_offset)); #if PROMOTE_R4_TO_R8 /* Need to convert ins->sreg1 to single-precision first */ mips_cvtsd (code, mips_ftemp, ins->sreg1); mips_swc1 (code, mips_ftemp, ins->inst_destbasereg, ins->inst_offset); #else mips_swc1 (code, ins->sreg1, ins->inst_destbasereg, ins->inst_offset); #endif break; case OP_MIPS_LWC1: g_assert (mips_is_imm16 (ins->inst_offset)); mips_lwc1 (code, ins->dreg, ins->inst_basereg, ins->inst_offset); break; case OP_LOADR4_MEMBASE: g_assert (mips_is_imm16 (ins->inst_offset)); mips_lwc1 (code, ins->dreg, ins->inst_basereg, ins->inst_offset); #if PROMOTE_R4_TO_R8 /* Convert to double precision in place */ mips_cvtds (code, ins->dreg, ins->dreg); #endif break; case OP_LOADR4_MEMINDEX: mips_addu (code, mips_at, ins->inst_basereg, ins->sreg2); mips_lwc1 (code, ins->dreg, mips_at, 0); break; case OP_LOADR8_MEMINDEX: mips_addu (code, mips_at, ins->inst_basereg, ins->sreg2); #if _MIPS_SIM == _ABIO32 mips_lwc1 (code, ins->dreg, mips_at, ls_word_offset); mips_lwc1 (code, ins->dreg+1, mips_at, ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_ldc1 (code, ins->dreg, mips_at, 0); #endif break; case OP_STORER4_MEMINDEX: mips_addu (code, mips_at, ins->inst_destbasereg, ins->sreg2); #if PROMOTE_R4_TO_R8 /* Need to convert ins->sreg1 to single-precision first */ mips_cvtsd (code, mips_ftemp, ins->sreg1); mips_swc1 (code, mips_ftemp, mips_at, 0); #else mips_swc1 (code, ins->sreg1, mips_at, 0); #endif break; case OP_STORER8_MEMINDEX: mips_addu (code, mips_at, ins->inst_destbasereg, ins->sreg2); #if _MIPS_SIM == _ABIO32 mips_swc1 (code, ins->sreg1, mips_at, ls_word_offset); mips_swc1 (code, ins->sreg1+1, mips_at, ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_sdc1 (code, ins->sreg1, mips_at, 0); #endif break; case OP_ICONV_TO_R_UN: { static const guint64 adjust_val = 0x41F0000000000000ULL; /* convert unsigned int to double */ mips_mtc1 (code, mips_ftemp, ins->sreg1); mips_bgez (code, ins->sreg1, 5); mips_cvtdw (code, ins->dreg, mips_ftemp); mips_load (code, mips_at, (guint32) &adjust_val); mips_ldc1 (code, mips_ftemp, mips_at, 0); mips_faddd (code, ins->dreg, ins->dreg, mips_ftemp); /* target is here */ break; } case OP_ICONV_TO_R4: mips_mtc1 (code, mips_ftemp, ins->sreg1); mips_cvtsw (code, ins->dreg, mips_ftemp); mips_cvtds (code, ins->dreg, ins->dreg); break; case OP_ICONV_TO_R8: mips_mtc1 (code, mips_ftemp, ins->sreg1); mips_cvtdw (code, ins->dreg, mips_ftemp); break; case OP_FCONV_TO_I1: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, TRUE); break; case OP_FCONV_TO_U1: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 1, FALSE); break; case OP_FCONV_TO_I2: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, TRUE); break; case OP_FCONV_TO_U2: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 2, FALSE); break; case OP_FCONV_TO_I4: case OP_FCONV_TO_I: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, TRUE); break; case OP_FCONV_TO_U4: case OP_FCONV_TO_U: code = emit_float_to_int (cfg, code, ins->dreg, ins->sreg1, 4, FALSE); break; case OP_SQRT: mips_fsqrtd (code, ins->dreg, ins->sreg1); break; case OP_FADD: mips_faddd (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_FSUB: mips_fsubd (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_FMUL: mips_fmuld (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_FDIV: mips_fdivd (code, ins->dreg, ins->sreg1, ins->sreg2); break; case OP_FNEG: mips_fnegd (code, ins->dreg, ins->sreg1); break; case OP_FCEQ: mips_fcmpd (code, MIPS_FPU_EQ, ins->sreg1, ins->sreg2); mips_addiu (code, ins->dreg, mips_zero, 1); mips_fbtrue (code, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_FCLT: mips_fcmpd (code, MIPS_FPU_LT, ins->sreg1, ins->sreg2); mips_addiu (code, ins->dreg, mips_zero, 1); mips_fbtrue (code, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_FCLT_UN: /* Less than, or Unordered */ mips_fcmpd (code, MIPS_FPU_ULT, ins->sreg1, ins->sreg2); mips_addiu (code, ins->dreg, mips_zero, 1); mips_fbtrue (code, 2); mips_nop (code); MIPS_MOVE (code, ins->dreg, mips_zero); break; case OP_FCGT: mips_fcmpd (code, MIPS_FPU_ULE, ins->sreg1, ins->sreg2); MIPS_MOVE (code, ins->dreg, mips_zero); mips_fbtrue (code, 2); mips_nop (code); mips_addiu (code, ins->dreg, mips_zero, 1); break; case OP_FCGT_UN: /* Greater than, or Unordered */ mips_fcmpd (code, MIPS_FPU_OLE, ins->sreg1, ins->sreg2); MIPS_MOVE (code, ins->dreg, mips_zero); mips_fbtrue (code, 2); mips_nop (code); mips_addiu (code, ins->dreg, mips_zero, 1); break; case OP_MIPS_FBEQ: case OP_MIPS_FBNE: case OP_MIPS_FBLT: case OP_MIPS_FBLT_UN: case OP_MIPS_FBGT: case OP_MIPS_FBGT_UN: case OP_MIPS_FBGE: case OP_MIPS_FBGE_UN: case OP_MIPS_FBLE: case OP_MIPS_FBLE_UN: { int cond = 0; gboolean is_true = TRUE, is_ordered = FALSE; guint32 *buf = NULL; switch (ins->opcode) { case OP_MIPS_FBEQ: cond = MIPS_FPU_EQ; is_true = TRUE; break; case OP_MIPS_FBNE: cond = MIPS_FPU_EQ; is_true = FALSE; break; case OP_MIPS_FBLT: cond = MIPS_FPU_LT; is_true = TRUE; is_ordered = TRUE; break; case OP_MIPS_FBLT_UN: cond = MIPS_FPU_ULT; is_true = TRUE; break; case OP_MIPS_FBGT: cond = MIPS_FPU_LE; is_true = FALSE; is_ordered = TRUE; break; case OP_MIPS_FBGT_UN: cond = MIPS_FPU_OLE; is_true = FALSE; break; case OP_MIPS_FBGE: cond = MIPS_FPU_LT; is_true = FALSE; is_ordered = TRUE; break; case OP_MIPS_FBGE_UN: cond = MIPS_FPU_OLT; is_true = FALSE; break; case OP_MIPS_FBLE: cond = MIPS_FPU_OLE; is_true = TRUE; is_ordered = TRUE; break; case OP_MIPS_FBLE_UN: cond = MIPS_FPU_ULE; is_true = TRUE; break; default: g_assert_not_reached (); } if (is_ordered) { /* Skip the check if unordered */ mips_fcmpd (code, MIPS_FPU_UN, ins->sreg1, ins->sreg2); mips_nop (code); buf = (guint32*)code; mips_fbtrue (code, 0); mips_nop (code); } mips_fcmpd (code, cond, ins->sreg1, ins->sreg2); mips_nop (code); mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_BB, ins->inst_true_bb); if (is_true) mips_fbtrue (code, 0); else mips_fbfalse (code, 0); mips_nop (code); if (is_ordered) mips_patch (buf, (guint32)code); break; } case OP_CKFINITE: { guint32 *branch_patch; mips_mfc1 (code, mips_at, ins->sreg1+1); mips_srl (code, mips_at, mips_at, 16+4); mips_andi (code, mips_at, mips_at, 2047); mips_addiu (code, mips_at, mips_at, -2047); branch_patch = (guint32 *)(void *)code; mips_bne (code, mips_at, mips_zero, 0); mips_nop (code); EMIT_SYSTEM_EXCEPTION_NAME("ArithmeticException"); mips_patch (branch_patch, (guint32)code); mips_fmovd (code, ins->dreg, ins->sreg1); break; } case OP_JUMP_TABLE: mono_add_patch_info (cfg, offset, (MonoJumpInfoType)ins->inst_c1, ins->inst_p0); mips_load (code, ins->dreg, 0x0f0f0f0f); break; default: g_warning ("unknown opcode %s in %s()\n", mono_inst_name (ins->opcode), __FUNCTION__); g_assert_not_reached (); } if ((cfg->opt & MONO_OPT_BRANCH) && ((code - cfg->native_code - offset) > max_len)) { g_warning ("wrong maximal instruction length of instruction %s (expected %d, got %d)", mono_inst_name (ins->opcode), max_len, code - cfg->native_code - offset); g_assert_not_reached (); } cpos += max_len; last_ins = ins; last_offset = offset; } cfg->code_len = code - cfg->native_code; } void mono_arch_register_lowlevel_calls (void) { } void mono_arch_patch_code (MonoCompile *cfg, MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *ji, gboolean run_cctors) { MonoJumpInfo *patch_info; for (patch_info = ji; patch_info; patch_info = patch_info->next) { unsigned char *ip = patch_info->ip.i + code; const unsigned char *target = NULL; switch (patch_info->type) { case MONO_PATCH_INFO_IP: patch_lui_addiu ((guint32 *)(void *)ip, (guint32)ip); continue; case MONO_PATCH_INFO_SWITCH: { gpointer *table = (gpointer *)patch_info->data.table->table; int i; patch_lui_addiu ((guint32 *)(void *)ip, (guint32)table); for (i = 0; i < patch_info->data.table->table_size; i++) { table [i] = (int)patch_info->data.table->table [i] + code; } continue; } case MONO_PATCH_INFO_METHODCONST: case MONO_PATCH_INFO_CLASS: case MONO_PATCH_INFO_IMAGE: case MONO_PATCH_INFO_FIELD: case MONO_PATCH_INFO_VTABLE: case MONO_PATCH_INFO_IID: case MONO_PATCH_INFO_SFLDA: case MONO_PATCH_INFO_LDSTR: case MONO_PATCH_INFO_TYPE_FROM_HANDLE: case MONO_PATCH_INFO_LDTOKEN: case MONO_PATCH_INFO_R4: case MONO_PATCH_INFO_R8: /* from OP_AOTCONST : lui + addiu */ target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors); patch_lui_addiu ((guint32 *)(void *)ip, (guint32)target); continue; #if 0 case MONO_PATCH_INFO_EXC_NAME: g_assert_not_reached (); *((gconstpointer *)(void *)(ip + 1)) = patch_info->data.name; continue; #endif case MONO_PATCH_INFO_NONE: /* everything is dealt with at epilog output time */ continue; default: target = mono_resolve_patch_target (method, domain, code, patch_info, run_cctors); mips_patch ((guint32 *)(void *)ip, (guint32)target); break; } } } /* * Allow tracing to work with this interface (with an optional argument) * * This code is expected to be inserted just after the 'real' prolog code, * and before the first basic block. We need to allocate a 2nd, temporary * stack frame so that we can preserve f12-f15 as well as a0-a3. */ void* mono_arch_instrument_prolog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) { guchar *code = p; int offset = cfg->arch.tracing_offset; mips_nop (code); mips_nop (code); mips_nop (code); MIPS_SW (code, mips_a0, mips_sp, offset + 0*SIZEOF_REGISTER); MIPS_SW (code, mips_a1, mips_sp, offset + 1*SIZEOF_REGISTER); MIPS_SW (code, mips_a2, mips_sp, offset + 2*SIZEOF_REGISTER); MIPS_SW (code, mips_a3, mips_sp, offset + 3*SIZEOF_REGISTER); #if _MIPS_SIM == _ABIN32 NOT_IMPLEMENTED; /* FIXME: Need a separate region for these */ MIPS_SW (code, mips_a4, mips_sp, offset + 4*SIZEOF_REGISTER); MIPS_SW (code, mips_a5, mips_sp, offset + 5*SIZEOF_REGISTER); MIPS_SW (code, mips_a6, mips_sp, offset + 6*SIZEOF_REGISTER); MIPS_SW (code, mips_a7, mips_sp, offset + 7*SIZEOF_REGISTER); */ #endif mips_load_const (code, mips_a0, cfg->method); mips_addiu (code, mips_a1, mips_sp, offset); mips_call (code, mips_t9, func); mips_nop (code); MIPS_LW (code, mips_a0, mips_sp, offset + 0*SIZEOF_REGISTER); MIPS_LW (code, mips_a1, mips_sp, offset + 1*SIZEOF_REGISTER); MIPS_LW (code, mips_a2, mips_sp, offset + 2*SIZEOF_REGISTER); MIPS_LW (code, mips_a3, mips_sp, offset + 3*SIZEOF_REGISTER); #if _MIPS_SIM == _ABIN32 NOT_IMPLEMENTED; /* MIPS_LW (code, mips_a4, mips_sp, offset + 4*SIZEOF_REGISTER); MIPS_LW (code, mips_a5, mips_sp, offset + 5*SIZEOF_REGISTER); MIPS_LW (code, mips_a6, mips_sp, offset + 6*SIZEOF_REGISTER); MIPS_LW (code, mips_a7, mips_sp, offset + 7*SIZEOF_REGISTER); */ #endif mips_nop (code); mips_nop (code); mips_nop (code); return code; } void mips_adjust_stackframe(MonoCompile *cfg) { MonoBasicBlock *bb; int delta, threshold, i; MonoMethodSignature *sig; int ra_offset; if (cfg->stack_offset == cfg->arch.local_alloc_offset) return; /* adjust cfg->stack_offset for account for down-spilling */ cfg->stack_offset += SIZEOF_REGISTER; /* re-align cfg->stack_offset if needed (due to var spilling) */ cfg->stack_offset = (cfg->stack_offset + MIPS_STACK_ALIGNMENT - 1) & ~(MIPS_STACK_ALIGNMENT - 1); delta = cfg->stack_offset - cfg->arch.local_alloc_offset; if (cfg->verbose_level > 2) { g_print ("mips_adjust_stackframe:\n"); g_print ("\tspillvars allocated 0x%x -> 0x%x\n", cfg->arch.local_alloc_offset, cfg->stack_offset); } threshold = cfg->arch.local_alloc_offset; ra_offset = cfg->stack_offset - sizeof(gpointer); if (cfg->verbose_level > 2) { g_print ("\tra_offset %d/0x%x delta %d/0x%x\n", ra_offset, ra_offset, delta, delta); } sig = mono_method_signature (cfg->method); if (sig && sig->ret && MONO_TYPE_ISSTRUCT (sig->ret)) { cfg->vret_addr->inst_offset += delta; } for (i = 0; i < sig->param_count + sig->hasthis; ++i) { MonoInst *inst = cfg->args [i]; inst->inst_offset += delta; } /* * loads and stores based off the frame reg that (used to) lie * above the spill var area need to be increased by 'delta' * to make room for the spill vars. */ /* Need to find loads and stores to adjust that * are above where the spillvars were inserted, but * which are not the spillvar references themselves. * * Idea - since all offsets from fp are positive, make * spillvar offsets negative to begin with so we can spot * them here. */ #if 1 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { int ins_cnt = 0; MonoInst *ins; if (cfg->verbose_level > 2) { g_print ("BASIC BLOCK %d:\n", bb->block_num); } MONO_BB_FOR_EACH_INS (bb, ins) { int adj_c0 = 0; int adj_imm = 0; if (cfg->verbose_level > 2) { mono_print_ins_index (ins_cnt, ins); } /* The == mips_sp tests catch FP spills */ if (MONO_IS_LOAD_MEMBASE(ins) && ((ins->inst_basereg == mips_fp) || (ins->inst_basereg == mips_sp))) { switch (ins->opcode) { case OP_LOADI8_MEMBASE: case OP_LOADR8_MEMBASE: adj_c0 = 8; break; default: adj_c0 = 4; break; } } else if (MONO_IS_STORE_MEMBASE(ins) && ((ins->dreg == mips_fp) || (ins->dreg == mips_sp))) { switch (ins->opcode) { case OP_STOREI8_MEMBASE_REG: case OP_STORER8_MEMBASE_REG: case OP_STOREI8_MEMBASE_IMM: adj_c0 = 8; break; default: adj_c0 = 4; break; } } if (((ins->opcode == OP_ADD_IMM) || (ins->opcode == OP_IADD_IMM)) && (ins->sreg1 == cfg->frame_reg)) adj_imm = 1; if (adj_c0) { if (ins->inst_c0 >= threshold) { ins->inst_c0 += delta; if (cfg->verbose_level > 2) { g_print ("adj"); mono_print_ins_index (ins_cnt, ins); } } else if (ins->inst_c0 < 0) { /* Adj_c0 holds the size of the datatype. */ ins->inst_c0 = - ins->inst_c0 - adj_c0; if (cfg->verbose_level > 2) { g_print ("spill"); mono_print_ins_index (ins_cnt, ins); } } g_assert (ins->inst_c0 != ra_offset); } if (adj_imm) { if (ins->inst_imm >= threshold) { ins->inst_imm += delta; if (cfg->verbose_level > 2) { g_print ("adj"); mono_print_ins_index (ins_cnt, ins); } } g_assert (ins->inst_c0 != ra_offset); } ++ins_cnt; } } #endif } /* * Stack frame layout: * * ------------------- sp + cfg->stack_usage + cfg->param_area * param area incoming * ------------------- sp + cfg->stack_usage + MIPS_STACK_PARAM_OFFSET * a0-a3 incoming * ------------------- sp + cfg->stack_usage * ra * ------------------- sp + cfg->stack_usage-4 * spilled regs * ------------------- sp + * MonoLMF structure optional * ------------------- sp + cfg->arch.lmf_offset * saved registers s0-s8 * ------------------- sp + cfg->arch.iregs_offset * locals * ------------------- sp + cfg->param_area * param area outgoing * ------------------- sp + MIPS_STACK_PARAM_OFFSET * a0-a3 outgoing * ------------------- sp * red zone */ guint8 * mono_arch_emit_prolog (MonoCompile *cfg) { MonoMethod *method = cfg->method; MonoMethodSignature *sig; MonoInst *inst; int alloc_size, pos, i, max_offset; int alloc2_size = 0; guint8 *code; CallInfo *cinfo; int tracing = 0; guint32 iregs_to_save = 0; #if SAVE_FP_REGS guint32 fregs_to_save = 0; #endif /* lmf_offset is the offset of the LMF from our stack pointer. */ guint32 lmf_offset = cfg->arch.lmf_offset; int cfa_offset = 0; MonoBasicBlock *bb; if (mono_jit_trace_calls != NULL && mono_trace_eval (method)) tracing = 1; if (tracing) cfg->flags |= MONO_CFG_HAS_CALLS; sig = mono_method_signature (method); cfg->code_size = 768 + sig->param_count * 20; code = cfg->native_code = g_malloc (cfg->code_size); /* * compute max_offset in order to use short forward jumps. */ max_offset = 0; for (bb = cfg->bb_entry; bb; bb = bb->next_bb) { MonoInst *ins = bb->code; bb->max_offset = max_offset; if (cfg->prof_options & MONO_PROFILE_COVERAGE) max_offset += 6; MONO_BB_FOR_EACH_INS (bb, ins) max_offset += ((guint8 *)ins_get_spec (ins->opcode))[MONO_INST_LEN]; } if (max_offset > 0xffff) cfg->arch.long_branch = TRUE; /* * Currently, fp points to the bottom of the frame on MIPS, unlike other platforms. * This means that we have to adjust the offsets inside instructions which reference * arguments received on the stack, since the initial offset doesn't take into * account spill slots. */ mips_adjust_stackframe (cfg); /* Offset between current sp and the CFA */ cfa_offset = 0; mono_emit_unwind_op_def_cfa (cfg, code, mips_sp, cfa_offset); /* stack_offset should not be changed here. */ alloc_size = cfg->stack_offset; cfg->stack_usage = alloc_size; iregs_to_save = (cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS); #if SAVE_FP_REGS #if 0 fregs_to_save = (cfg->used_float_regs & MONO_ARCH_CALLEE_SAVED_FREGS); #else fregs_to_save = MONO_ARCH_CALLEE_SAVED_FREGS; fregs_to_save |= (fregs_to_save << 1); #endif #endif /* If the stack size is too big, save 1024 bytes to start with * so the prologue can use imm16(reg) addressing, then allocate * the rest of the frame. */ if (alloc_size > ((1 << 15) - 1024)) { alloc2_size = alloc_size - 1024; alloc_size = 1024; } if (alloc_size) { g_assert (mips_is_imm16 (-alloc_size)); mips_addiu (code, mips_sp, mips_sp, -alloc_size); cfa_offset = alloc_size; mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset); } if ((cfg->flags & MONO_CFG_HAS_CALLS) || ALWAYS_SAVE_RA) { int offset = alloc_size + MIPS_RET_ADDR_OFFSET; if (mips_is_imm16(offset)) mips_sw (code, mips_ra, mips_sp, offset); else { g_assert_not_reached (); } /* sp = cfa - cfa_offset, so sp + offset = cfa - cfa_offset + offset */ mono_emit_unwind_op_offset (cfg, code, mips_ra, offset - cfa_offset); } /* XXX - optimize this later to not save all regs if LMF constructed */ pos = cfg->arch.iregs_offset - alloc2_size; if (iregs_to_save) { /* save used registers in own stack frame (at pos) */ for (i = MONO_MAX_IREGS-1; i >= 0; --i) { if (iregs_to_save & (1 << i)) { g_assert (pos < (int)(cfg->stack_usage - sizeof(gpointer))); g_assert (mips_is_imm16(pos)); MIPS_SW (code, i, mips_sp, pos); mono_emit_unwind_op_offset (cfg, code, i, pos - cfa_offset); pos += SIZEOF_REGISTER; } } } // FIXME: Don't save registers twice if there is an LMF // s8 has to be special cased since it is overwritten with the updated value // below if (method->save_lmf) { for (i = MONO_MAX_IREGS-1; i >= 0; --i) { int offset = lmf_offset + G_STRUCT_OFFSET(MonoLMF, iregs[i]); g_assert (mips_is_imm16(offset)); if (MIPS_LMF_IREGMASK & (1 << i)) MIPS_SW (code, i, mips_sp, offset); } } #if SAVE_FP_REGS /* Save float registers */ if (fregs_to_save) { for (i = MONO_MAX_FREGS-1; i >= 0; --i) { if (fregs_to_save & (1 << i)) { g_assert (pos < cfg->stack_usage - MIPS_STACK_ALIGNMENT); g_assert (mips_is_imm16(pos)); mips_swc1 (code, i, mips_sp, pos); pos += sizeof (gulong); } } } if (method->save_lmf) { for (i = MONO_MAX_FREGS-1; i >= 0; --i) { int offset = lmf_offset + G_STRUCT_OFFSET(MonoLMF, fregs[i]); g_assert (mips_is_imm16(offset)); mips_swc1 (code, i, mips_sp, offset); } } #endif if (cfg->frame_reg != mips_sp) { MIPS_MOVE (code, cfg->frame_reg, mips_sp); mono_emit_unwind_op_def_cfa (cfg, code, cfg->frame_reg, cfa_offset); if (method->save_lmf) { int offset = lmf_offset + G_STRUCT_OFFSET(MonoLMF, iregs[cfg->frame_reg]); g_assert (mips_is_imm16(offset)); MIPS_SW (code, cfg->frame_reg, mips_sp, offset); } } /* store runtime generic context */ if (cfg->rgctx_var) { MonoInst *ins = cfg->rgctx_var; g_assert (ins->opcode == OP_REGOFFSET); g_assert (mips_is_imm16 (ins->inst_offset)); mips_sw (code, MONO_ARCH_RGCTX_REG, ins->inst_basereg, ins->inst_offset); } /* load arguments allocated to register from the stack */ pos = 0; if (!cfg->arch.cinfo) cfg->arch.cinfo = get_call_info (cfg->generic_sharing_context, cfg->mempool, sig); cinfo = cfg->arch.cinfo; if (MONO_TYPE_ISSTRUCT (sig->ret)) { ArgInfo *ainfo = &cinfo->ret; inst = cfg->vret_addr; if (inst->opcode == OP_REGVAR) MIPS_MOVE (code, inst->dreg, ainfo->reg); else if (mips_is_imm16 (inst->inst_offset)) { mips_sw (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); } else { mips_load_const (code, mips_at, inst->inst_offset); mips_addu (code, mips_at, mips_at, inst->inst_basereg); mips_sw (code, ainfo->reg, mips_at, 0); } } if (sig->call_convention == MONO_CALL_VARARG) { ArgInfo *cookie = &cinfo->sig_cookie; int offset = alloc_size + cookie->offset; /* Save the sig cookie address */ g_assert (cookie->storage == ArgOnStack); g_assert (mips_is_imm16(offset)); mips_addi (code, mips_at, cfg->frame_reg, offset); mips_sw (code, mips_at, cfg->frame_reg, cfg->sig_cookie - alloc2_size); } /* Keep this in sync with emit_load_volatile_arguments */ for (i = 0; i < sig->param_count + sig->hasthis; ++i) { ArgInfo *ainfo = cinfo->args + i; inst = cfg->args [pos]; if (cfg->verbose_level > 2) g_print ("Saving argument %d (type: %d)\n", i, ainfo->storage); if (inst->opcode == OP_REGVAR) { /* Argument ends up in a register */ if (ainfo->storage == ArgInIReg) MIPS_MOVE (code, inst->dreg, ainfo->reg); else if (ainfo->storage == ArgInFReg) { g_assert_not_reached(); #if 0 ppc_fmr (code, inst->dreg, ainfo->reg); #endif } else if (ainfo->storage == ArgOnStack) { int offset = cfg->stack_usage + ainfo->offset; g_assert (mips_is_imm16(offset)); mips_lw (code, inst->dreg, mips_sp, offset); } else g_assert_not_reached (); if (cfg->verbose_level > 2) g_print ("Argument %d assigned to register %s\n", pos, mono_arch_regname (inst->dreg)); } else { /* Argument ends up on the stack */ if (ainfo->storage == ArgInIReg) { int basereg_offset; /* Incoming parameters should be above this frame */ if (cfg->verbose_level > 2) g_print ("stack slot at %d of %d+%d\n", inst->inst_offset, alloc_size, alloc2_size); /* g_assert (inst->inst_offset >= alloc_size); */ g_assert (inst->inst_basereg == cfg->frame_reg); basereg_offset = inst->inst_offset - alloc2_size; g_assert (mips_is_imm16 (basereg_offset)); switch (ainfo->size) { case 1: mips_sb (code, ainfo->reg, inst->inst_basereg, basereg_offset); break; case 2: mips_sh (code, ainfo->reg, inst->inst_basereg, basereg_offset); break; case 0: /* XXX */ case 4: mips_sw (code, ainfo->reg, inst->inst_basereg, basereg_offset); break; case 8: #if (SIZEOF_REGISTER == 4) mips_sw (code, ainfo->reg, inst->inst_basereg, basereg_offset + ls_word_offset); mips_sw (code, ainfo->reg + 1, inst->inst_basereg, basereg_offset + ms_word_offset); #elif (SIZEOF_REGISTER == 8) mips_sd (code, ainfo->reg, inst->inst_basereg, basereg_offset); #endif break; default: g_assert_not_reached (); break; } } else if (ainfo->storage == ArgOnStack) { /* * Argument comes in on the stack, and ends up on the stack * 1 and 2 byte args are passed as 32-bit quantities, but used as * 8 and 16 bit quantities. Shorten them in place. */ g_assert (mips_is_imm16 (inst->inst_offset)); switch (ainfo->size) { case 1: mips_lw (code, mips_at, inst->inst_basereg, inst->inst_offset); mips_sb (code, mips_at, inst->inst_basereg, inst->inst_offset); break; case 2: mips_lw (code, mips_at, inst->inst_basereg, inst->inst_offset); mips_sh (code, mips_at, inst->inst_basereg, inst->inst_offset); break; case 0: /* XXX */ case 4: case 8: break; default: g_assert_not_reached (); } } else if (ainfo->storage == ArgInFReg) { g_assert (mips_is_imm16 (inst->inst_offset)); g_assert (mips_is_imm16 (inst->inst_offset+4)); if (ainfo->size == 8) { #if _MIPS_SIM == _ABIO32 mips_swc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset + ls_word_offset); mips_swc1 (code, ainfo->reg+1, inst->inst_basereg, inst->inst_offset + ms_word_offset); #elif _MIPS_SIM == _ABIN32 mips_sdc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); #endif } else if (ainfo->size == 4) mips_swc1 (code, ainfo->reg, inst->inst_basereg, inst->inst_offset); else g_assert_not_reached (); } else if (ainfo->storage == ArgStructByVal) { int i; int doffset = inst->inst_offset; g_assert (mips_is_imm16 (inst->inst_offset)); g_assert (mips_is_imm16 (inst->inst_offset + ainfo->size * sizeof (gpointer))); /* Push the argument registers into their stack slots */ for (i = 0; i < ainfo->size; ++i) { g_assert (mips_is_imm16(doffset)); MIPS_SW (code, ainfo->reg + i, inst->inst_basereg, doffset); doffset += SIZEOF_REGISTER; } } else if (ainfo->storage == ArgStructByAddr) { g_assert (mips_is_imm16 (inst->inst_offset)); /* FIXME: handle overrun! with struct sizes not multiple of 4 */ code = emit_memcpy (code, ainfo->vtsize * sizeof (gpointer), inst->inst_basereg, inst->inst_offset, ainfo->reg, 0); } else g_assert_not_reached (); } pos++; } if (method->save_lmf) { mips_load_const (code, mips_at, MIPS_LMF_MAGIC1); mips_sw (code, mips_at, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, magic)); if (lmf_pthread_key != -1) { g_assert_not_reached(); #if 0 emit_tls_access (code, mips_temp, lmf_pthread_key); #endif if (G_STRUCT_OFFSET (MonoJitTlsData, lmf)) { int offset = G_STRUCT_OFFSET (MonoJitTlsData, lmf); g_assert (mips_is_imm16(offset)); mips_addiu (code, mips_a0, mips_temp, offset); } } else { /* This can/will clobber the a0-a3 registers */ mips_call (code, mips_t9, (gpointer)mono_get_lmf_addr); } /* mips_v0 is the result from mono_get_lmf_addr () (MonoLMF **) */ g_assert (mips_is_imm16(lmf_offset + G_STRUCT_OFFSET(MonoLMF, lmf_addr))); mips_sw (code, mips_v0, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, lmf_addr)); /* new_lmf->previous_lmf = *lmf_addr */ mips_lw (code, mips_at, mips_v0, 0); g_assert (mips_is_imm16(lmf_offset + G_STRUCT_OFFSET(MonoLMF, previous_lmf))); mips_sw (code, mips_at, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, previous_lmf)); /* *(lmf_addr) = sp + lmf_offset */ g_assert (mips_is_imm16(lmf_offset)); mips_addiu (code, mips_at, mips_sp, lmf_offset); mips_sw (code, mips_at, mips_v0, 0); /* save method info */ mips_load_const (code, mips_at, method); g_assert (mips_is_imm16(lmf_offset + G_STRUCT_OFFSET(MonoLMF, method))); mips_sw (code, mips_at, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, method)); /* save the current IP */ mono_add_patch_info (cfg, code - cfg->native_code, MONO_PATCH_INFO_IP, NULL); mips_load_const (code, mips_at, 0x01010101); mips_sw (code, mips_at, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, eip)); } if (alloc2_size) { if (mips_is_imm16 (-alloc2_size)) { mips_addu (code, mips_sp, mips_sp, -alloc2_size); } else { mips_load_const (code, mips_at, -alloc2_size); mips_addu (code, mips_sp, mips_sp, mips_at); } alloc_size += alloc2_size; cfa_offset += alloc2_size; if (cfg->frame_reg != mips_sp) MIPS_MOVE (code, cfg->frame_reg, mips_sp); else mono_emit_unwind_op_def_cfa_offset (cfg, code, cfa_offset); } if (tracing) { #if _MIPS_SIM == _ABIO32 cfg->arch.tracing_offset = cfg->stack_offset; #elif _MIPS_SIM == _ABIN32 /* no stack slots by default for argument regs, reserve a special block */ g_assert_not_reached (); #endif code = mono_arch_instrument_prolog (cfg, mono_trace_enter_method, code, TRUE); } cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); return code; } enum { SAVE_NONE, SAVE_STRUCT, SAVE_ONE, SAVE_TWO, SAVE_FP }; void* mono_arch_instrument_epilog_full (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments, gboolean preserve_argument_registers) { guchar *code = p; int save_mode = SAVE_NONE; int offset; MonoMethod *method = cfg->method; int rtype = mini_type_get_underlying_type (cfg->generic_sharing_context, mono_method_signature (method)->ret)->type; int save_offset = MIPS_STACK_PARAM_OFFSET; g_assert ((save_offset & (MIPS_STACK_ALIGNMENT-1)) == 0); offset = code - cfg->native_code; /* we need about 16 instructions */ if (offset > (cfg->code_size - 16 * 4)) { cfg->code_size *= 2; cfg->native_code = g_realloc (cfg->native_code, cfg->code_size); code = cfg->native_code + offset; } mips_nop (code); mips_nop (code); switch (rtype) { case MONO_TYPE_VOID: /* special case string .ctor icall */ if (strcmp (".ctor", method->name) && method->klass == mono_defaults.string_class) save_mode = SAVE_ONE; else save_mode = SAVE_NONE; break; case MONO_TYPE_R4: case MONO_TYPE_R8: save_mode = SAVE_FP; break; case MONO_TYPE_VALUETYPE: save_mode = SAVE_STRUCT; break; case MONO_TYPE_I8: case MONO_TYPE_U8: #if SIZEOF_REGISTER == 4 save_mode = SAVE_TWO; #elif SIZEOF_REGISTER == 8 save_mode = SAVE_ONE; #endif break; default: save_mode = SAVE_ONE; break; } mips_addiu (code, mips_sp, mips_sp, -32); g_assert (mips_is_imm16(save_offset)); switch (save_mode) { case SAVE_TWO: mips_sw (code, mips_v0, mips_sp, save_offset); g_assert (mips_is_imm16(save_offset + SIZEOF_REGISTER)); mips_sw (code, mips_v1, mips_sp, save_offset + SIZEOF_REGISTER); if (enable_arguments) { MIPS_MOVE (code, mips_a1, mips_v0); MIPS_MOVE (code, mips_a2, mips_v1); } break; case SAVE_ONE: MIPS_SW (code, mips_v0, mips_sp, save_offset); if (enable_arguments) { MIPS_MOVE (code, mips_a1, mips_v0); } break; case SAVE_FP: mips_sdc1 (code, mips_f0, mips_sp, save_offset); mips_ldc1 (code, mips_f12, mips_sp, save_offset); mips_lw (code, mips_a0, mips_sp, save_offset); g_assert (mips_is_imm16(save_offset + SIZEOF_REGISTER)); mips_lw (code, mips_a1, mips_sp, save_offset + SIZEOF_REGISTER); break; case SAVE_STRUCT: case SAVE_NONE: default: break; } mips_load_const (code, mips_a0, cfg->method); mips_call (code, mips_t9, func); switch (save_mode) { case SAVE_TWO: mips_lw (code, mips_v0, mips_sp, save_offset); g_assert (mips_is_imm16(save_offset + SIZEOF_REGISTER)); mips_lw (code, mips_v1, mips_sp, save_offset + SIZEOF_REGISTER); break; case SAVE_ONE: MIPS_LW (code, mips_v0, mips_sp, save_offset); break; case SAVE_FP: mips_ldc1 (code, mips_f0, mips_sp, save_offset); break; case SAVE_STRUCT: case SAVE_NONE: default: break; } mips_addiu (code, mips_sp, mips_sp, 32); mips_nop (code); mips_nop (code); return code; } guint8 * mono_arch_emit_epilog_sub (MonoCompile *cfg, guint8 *code) { MonoMethod *method = cfg->method; int pos = 0, i; int max_epilog_size = 16 + 20*4; int alloc2_size = 0; guint32 iregs_to_restore; #if SAVE_FP_REGS guint32 fregs_to_restore; #endif if (cfg->method->save_lmf) max_epilog_size += 128; if (mono_jit_trace_calls != NULL) max_epilog_size += 50; if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) max_epilog_size += 50; if (code) pos = code - cfg->native_code; while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) { cfg->code_size *= 2; cfg->native_code = g_realloc (cfg->native_code, cfg->code_size); cfg->stat_code_reallocs++; } /* * Keep in sync with OP_JMP */ if (code) code = cfg->native_code + pos; else code = cfg->native_code + cfg->code_len; if (mono_jit_trace_calls != NULL && mono_trace_eval (method)) { code = mono_arch_instrument_epilog (cfg, mono_trace_leave_method, code, TRUE); } if (cfg->frame_reg != mips_sp) { MIPS_MOVE (code, mips_sp, cfg->frame_reg); } /* If the stack frame is really large, deconstruct it in two steps */ if (cfg->stack_usage > ((1 << 15) - 1024)) { alloc2_size = cfg->stack_usage - 1024; /* partially deconstruct the stack */ mips_load_const (code, mips_at, alloc2_size); mips_addu (code, mips_sp, mips_sp, mips_at); } pos = cfg->arch.iregs_offset - alloc2_size; iregs_to_restore = (cfg->used_int_regs & MONO_ARCH_CALLEE_SAVED_REGS); if (iregs_to_restore) { for (i = MONO_MAX_IREGS-1; i >= 0; --i) { if (iregs_to_restore & (1 << i)) { g_assert (mips_is_imm16(pos)); MIPS_LW (code, i, mips_sp, pos); pos += SIZEOF_REGISTER; } } } #if SAVE_FP_REGS #if 0 fregs_to_restore = (cfg->used_float_regs & MONO_ARCH_CALLEE_SAVED_FREGS); #else fregs_to_restore = MONO_ARCH_CALLEE_SAVED_FREGS; fregs_to_restore |= (fregs_to_restore << 1); #endif if (fregs_to_restore) { for (i = MONO_MAX_FREGS-1; i >= 0; --i) { if (fregs_to_restore & (1 << i)) { g_assert (pos < cfg->stack_usage - MIPS_STACK_ALIGNMENT); g_assert (mips_is_imm16(pos)); mips_lwc1 (code, i, mips_sp, pos); pos += FREG_SIZE } } } #endif /* Unlink the LMF if necessary */ if (method->save_lmf) { int lmf_offset = cfg->arch.lmf_offset; /* t0 = current_lmf->previous_lmf */ g_assert (mips_is_imm16(lmf_offset + G_STRUCT_OFFSET(MonoLMF, previous_lmf))); mips_lw (code, mips_temp, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, previous_lmf)); /* t1 = lmf_addr */ g_assert (mips_is_imm16(lmf_offset + G_STRUCT_OFFSET(MonoLMF, lmf_addr))); mips_lw (code, mips_t1, mips_sp, lmf_offset + G_STRUCT_OFFSET(MonoLMF, lmf_addr)); /* (*lmf_addr) = previous_lmf */ mips_sw (code, mips_temp, mips_t1, 0); } #if 0 /* Restore the fp */ mips_lw (code, mips_fp, mips_sp, cfg->stack_usage + MIPS_FP_ADDR_OFFSET); #endif /* Restore ra */ if ((cfg->flags & MONO_CFG_HAS_CALLS) || ALWAYS_SAVE_RA) { g_assert (mips_is_imm16(cfg->stack_usage - alloc2_size + MIPS_RET_ADDR_OFFSET)); mips_lw (code, mips_ra, mips_sp, cfg->stack_usage - alloc2_size + MIPS_RET_ADDR_OFFSET); } /* Restore the stack pointer */ g_assert (mips_is_imm16(cfg->stack_usage - alloc2_size)); mips_addiu (code, mips_sp, mips_sp, cfg->stack_usage - alloc2_size); /* Caller will emit either return or tail-call sequence */ cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); return (code); } void mono_arch_emit_epilog (MonoCompile *cfg) { guint8 *code; code = mono_arch_emit_epilog_sub (cfg, NULL); mips_jr (code, mips_ra); mips_nop (code); cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); } /* remove once throw_exception_by_name is eliminated */ #if 0 static int exception_id_by_name (const char *name) { if (strcmp (name, "IndexOutOfRangeException") == 0) return MONO_EXC_INDEX_OUT_OF_RANGE; if (strcmp (name, "OverflowException") == 0) return MONO_EXC_OVERFLOW; if (strcmp (name, "ArithmeticException") == 0) return MONO_EXC_ARITHMETIC; if (strcmp (name, "DivideByZeroException") == 0) return MONO_EXC_DIVIDE_BY_ZERO; if (strcmp (name, "InvalidCastException") == 0) return MONO_EXC_INVALID_CAST; if (strcmp (name, "NullReferenceException") == 0) return MONO_EXC_NULL_REF; if (strcmp (name, "ArrayTypeMismatchException") == 0) return MONO_EXC_ARRAY_TYPE_MISMATCH; if (strcmp (name, "ArgumentException") == 0) return MONO_EXC_ARGUMENT; g_error ("Unknown intrinsic exception %s\n", name); return 0; } #endif void mono_arch_emit_exceptions (MonoCompile *cfg) { #if 0 MonoJumpInfo *patch_info; int i; guint8 *code; const guint8* exc_throw_pos [MONO_EXC_INTRINS_NUM] = {NULL}; guint8 exc_throw_found [MONO_EXC_INTRINS_NUM] = {0}; int max_epilog_size = 50; /* count the number of exception infos */ /* * make sure we have enough space for exceptions * 24 is the simulated call to throw_exception_by_name */ for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) { #if 0 if (patch_info->type == MONO_PATCH_INFO_EXC) { i = exception_id_by_name (patch_info->data.target); g_assert (i < MONO_EXC_INTRINS_NUM); if (!exc_throw_found [i]) { max_epilog_size += 12; exc_throw_found [i] = TRUE; } } #endif } while (cfg->code_len + max_epilog_size > (cfg->code_size - 16)) { cfg->code_size *= 2; cfg->native_code = g_realloc (cfg->native_code, cfg->code_size); cfg->stat_code_reallocs++; } code = cfg->native_code + cfg->code_len; /* add code to raise exceptions */ for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) { switch (patch_info->type) { case MONO_PATCH_INFO_EXC: { #if 0 //unsigned char *ip = patch_info->ip.i + cfg->native_code; i = exception_id_by_name (patch_info->data.target); g_assert (i >= 0 && i < MONO_EXC_INTRINS_NUM); if (!exc_throw_pos [i]) { guint32 addr; exc_throw_pos [i] = code; //g_print ("exc: writing stub at %p\n", code); mips_load_const (code, mips_a0, patch_info->data.target); addr = (guint32) mono_arch_get_throw_exception_by_name (); mips_load_const (code, mips_t9, addr); mips_jr (code, mips_t9); mips_nop (code); } //g_print ("exc: patch %p to %p\n", ip, exc_throw_pos[i]); /* Turn into a Relative patch, pointing at code stub */ patch_info->type = MONO_PATCH_INFO_METHOD_REL; patch_info->data.offset = exc_throw_pos[i] - cfg->native_code; #else g_assert_not_reached(); #endif break; } default: /* do nothing */ break; } } cfg->code_len = code - cfg->native_code; g_assert (cfg->code_len < cfg->code_size); #endif } /* * Thread local storage support */ static void setup_tls_access (void) { guint32 ptk; //guint32 *ins, *code; if (tls_mode == TLS_MODE_FAILED) return; if (g_getenv ("MONO_NO_TLS")) { tls_mode = TLS_MODE_FAILED; return; } if (tls_mode == TLS_MODE_DETECT) { /* XXX */ tls_mode = TLS_MODE_FAILED; return; #if 0 ins = (guint32*)pthread_getspecific; /* uncond branch to the real method */ if ((*ins >> 26) == 18) { gint32 val; val = (*ins & ~3) << 6; val >>= 6; if (*ins & 2) { /* absolute */ ins = (guint32*)val; } else { ins = (guint32*) ((char*)ins + val); } } code = &cmplwi_1023; ppc_cmpli (code, 0, 0, ppc_r3, 1023); code = &li_0x48; ppc_li (code, ppc_r4, 0x48); code = &blr_ins; ppc_blr (code); if (*ins == cmplwi_1023) { int found_lwz_284 = 0; for (ptk = 0; ptk < 20; ++ptk) { ++ins; if (!*ins || *ins == blr_ins) break; if ((guint16)*ins == 284 && (*ins >> 26) == 32) { found_lwz_284 = 1; break; } } if (!found_lwz_284) { tls_mode = TLS_MODE_FAILED; return; } tls_mode = TLS_MODE_LTHREADS; } else if (*ins == li_0x48) { ++ins; /* uncond branch to the real method */ if ((*ins >> 26) == 18) { gint32 val; val = (*ins & ~3) << 6; val >>= 6; if (*ins & 2) { /* absolute */ ins = (guint32*)val; } else { ins = (guint32*) ((char*)ins + val); } code = &val; ppc_li (code, ppc_r0, 0x7FF2); if (ins [1] == val) { /* Darwin on G4, implement */ tls_mode = TLS_MODE_FAILED; return; } else { code = &val; ppc_mfspr (code, ppc_r3, 104); if (ins [1] != val) { tls_mode = TLS_MODE_FAILED; return; } tls_mode = TLS_MODE_DARWIN_G5; } } else { tls_mode = TLS_MODE_FAILED; return; } } else { tls_mode = TLS_MODE_FAILED; return; } #endif } if (lmf_pthread_key == -1) { ptk = mono_jit_tls_id; if (ptk < 1024) { /*g_print ("MonoLMF at: %d\n", ptk);*/ /*if (!try_offset_access (mono_get_lmf_addr (), ptk)) { init_tls_failed = 1; return; }*/ lmf_pthread_key = ptk; } } if (monothread_key == -1) { ptk = mono_thread_get_tls_key (); if (ptk < 1024) { monothread_key = ptk; /*g_print ("thread inited: %d\n", ptk);*/ } else { /*g_print ("thread not inited yet %d\n", ptk);*/ } } } void mono_arch_finish_init (void) { setup_tls_access (); } void mono_arch_free_jit_tls_data (MonoJitTlsData *tls) { } void mono_arch_emit_this_vret_args (MonoCompile *cfg, MonoCallInst *inst, int this_reg, int this_type, int vt_reg) { int this_dreg = mips_a0; if (vt_reg != -1) this_dreg = mips_a1; /* add the this argument */ if (this_reg != -1) { MonoInst *this; MONO_INST_NEW (cfg, this, OP_MOVE); this->type = this_type; this->sreg1 = this_reg; this->dreg = mono_alloc_ireg (cfg); mono_bblock_add_inst (cfg->cbb, this); mono_call_inst_add_outarg_reg (cfg, inst, this->dreg, this_dreg, FALSE); } if (vt_reg != -1) { MonoInst *vtarg; MONO_INST_NEW (cfg, vtarg, OP_MOVE); vtarg->type = STACK_MP; vtarg->sreg1 = vt_reg; vtarg->dreg = mono_alloc_ireg (cfg); mono_bblock_add_inst (cfg->cbb, vtarg); mono_call_inst_add_outarg_reg (cfg, inst, vtarg->dreg, mips_a0, FALSE); } } MonoInst* mono_arch_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) { MonoInst *ins = NULL; return ins; } MonoInst* mono_arch_emit_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args) { return NULL; } gboolean mono_arch_print_tree (MonoInst *tree, int arity) { return 0; } mgreg_t mono_arch_context_get_int_reg (MonoContext *ctx, int reg) { return ctx->sc_regs [reg]; } #define ENABLE_WRONG_METHOD_CHECK 0 #define MIPS_LOAD_SEQUENCE_LENGTH 8 #define CMP_SIZE (MIPS_LOAD_SEQUENCE_LENGTH + 4) #define BR_SIZE 8 #define LOADSTORE_SIZE 4 #define JUMP_IMM_SIZE 16 #define JUMP_IMM32_SIZE (MIPS_LOAD_SEQUENCE_LENGTH + 8) #define LOAD_CONST_SIZE 8 #define JUMP_JR_SIZE 8 /* * LOCKING: called with the domain lock held */ gpointer mono_arch_build_imt_thunk (MonoVTable *vtable, MonoDomain *domain, MonoIMTCheckItem **imt_entries, int count, gpointer fail_tramp) { int i; int size = 0; guint8 *code, *start, *patch; for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; if (item->is_equals) { if (item->check_target_idx) { item->chunk_size += LOAD_CONST_SIZE + BR_SIZE + JUMP_JR_SIZE; if (item->has_target_code) item->chunk_size += LOAD_CONST_SIZE; else item->chunk_size += LOADSTORE_SIZE; } else { if (fail_tramp) { item->chunk_size += LOAD_CONST_SIZE + BR_SIZE + JUMP_IMM32_SIZE + LOADSTORE_SIZE + JUMP_IMM32_SIZE; if (!item->has_target_code) item->chunk_size += LOADSTORE_SIZE; } else { item->chunk_size += LOADSTORE_SIZE + JUMP_JR_SIZE; #if ENABLE_WRONG_METHOD_CHECK item->chunk_size += CMP_SIZE + BR_SIZE + 4; #endif } } } else { item->chunk_size += CMP_SIZE + BR_SIZE; imt_entries [item->check_target_idx]->compare_done = TRUE; } size += item->chunk_size; } /* the initial load of the vtable address */ size += MIPS_LOAD_SEQUENCE_LENGTH; if (fail_tramp) { code = mono_method_alloc_generic_virtual_thunk (domain, size); } else { code = mono_domain_code_reserve (domain, size); } start = code; /* t7 points to the vtable */ mips_load_const (code, mips_t7, (gsize)(& (vtable->vtable [0]))); for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; item->code_target = code; if (item->is_equals) { if (item->check_target_idx) { mips_load_const (code, mips_temp, (gsize)item->key); item->jmp_code = code; mips_bne (code, mips_temp, MONO_ARCH_IMT_REG, 0); mips_nop (code); if (item->has_target_code) { mips_load_const (code, mips_t9, item->value.target_code); } else { mips_lw (code, mips_t9, mips_t7, (sizeof (gpointer) * item->value.vtable_slot)); } mips_jr (code, mips_t9); mips_nop (code); } else { if (fail_tramp) { mips_load_const (code, mips_temp, (gsize)item->key); patch = code; mips_bne (code, mips_temp, MONO_ARCH_IMT_REG, 0); mips_nop (code); if (item->has_target_code) { mips_load_const (code, mips_t9, item->value.target_code); } else { g_assert (vtable); mips_load_const (code, mips_at, & (vtable->vtable [item->value.vtable_slot])); mips_lw (code, mips_t9, mips_at, 0); } mips_jr (code, mips_t9); mips_nop (code); mips_patch ((guint32 *)(void *)patch, (guint32)code); mips_load_const (code, mips_t9, fail_tramp); mips_jr (code, mips_t9); mips_nop (code); } else { /* enable the commented code to assert on wrong method */ #if ENABLE_WRONG_METHOD_CHECK ppc_load (code, ppc_r0, (guint32)item->key); ppc_compare_log (code, 0, MONO_ARCH_IMT_REG, ppc_r0); patch = code; ppc_bc (code, PPC_BR_FALSE, PPC_BR_EQ, 0); #endif mips_lw (code, mips_t9, mips_t7, (sizeof (gpointer) * item->value.vtable_slot)); mips_jr (code, mips_t9); mips_nop (code); #if ENABLE_WRONG_METHOD_CHECK ppc_patch (patch, code); ppc_break (code); #endif } } } else { mips_load_const (code, mips_temp, (gulong)item->key); mips_slt (code, mips_temp, MONO_ARCH_IMT_REG, mips_temp); item->jmp_code = code; mips_beq (code, mips_temp, mips_zero, 0); mips_nop (code); } } /* patch the branches to get to the target items */ for (i = 0; i < count; ++i) { MonoIMTCheckItem *item = imt_entries [i]; if (item->jmp_code && item->check_target_idx) { mips_patch ((guint32 *)item->jmp_code, (guint32)imt_entries [item->check_target_idx]->code_target); } } if (!fail_tramp) mono_stats.imt_thunks_size += code - start; g_assert (code - start <= size); mono_arch_flush_icache (start, size); return start; } MonoMethod* mono_arch_find_imt_method (mgreg_t *regs, guint8 *code) { return (MonoMethod*) regs [MONO_ARCH_IMT_REG]; } MonoVTable* mono_arch_find_static_call_vtable (mgreg_t *regs, guint8 *code) { return (MonoVTable*) regs [MONO_ARCH_RGCTX_REG]; } /* Soft Debug support */ #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED /* * mono_arch_set_breakpoint: * * See mini-amd64.c for docs. */ void mono_arch_set_breakpoint (MonoJitInfo *ji, guint8 *ip) { guint8 *code = ip; guint32 addr = (guint32)bp_trigger_page; mips_load_const (code, mips_t9, addr); mips_lw (code, mips_t9, mips_t9, 0); mono_arch_flush_icache (ip, code - ip); } /* * mono_arch_clear_breakpoint: * * See mini-amd64.c for docs. */ void mono_arch_clear_breakpoint (MonoJitInfo *ji, guint8 *ip) { guint8 *code = ip; mips_nop (code); mips_nop (code); mips_nop (code); mono_arch_flush_icache (ip, code - ip); } /* * mono_arch_start_single_stepping: * * See mini-amd64.c for docs. */ void mono_arch_start_single_stepping (void) { mono_mprotect (ss_trigger_page, mono_pagesize (), 0); } /* * mono_arch_stop_single_stepping: * * See mini-amd64.c for docs. */ void mono_arch_stop_single_stepping (void) { mono_mprotect (ss_trigger_page, mono_pagesize (), MONO_MMAP_READ); } /* * mono_arch_is_single_step_event: * * See mini-amd64.c for docs. */ gboolean mono_arch_is_single_step_event (void *info, void *sigctx) { siginfo_t* sinfo = (siginfo_t*) info; /* Sometimes the address is off by 4 */ if (sinfo->si_addr >= ss_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)ss_trigger_page + 128) return TRUE; else return FALSE; } /* * mono_arch_is_breakpoint_event: * * See mini-amd64.c for docs. */ gboolean mono_arch_is_breakpoint_event (void *info, void *sigctx) { siginfo_t* sinfo = (siginfo_t*) info; /* Sometimes the address is off by 4 */ if (sinfo->si_addr >= bp_trigger_page && (guint8*)sinfo->si_addr <= (guint8*)bp_trigger_page + 128) return TRUE; else return FALSE; } /* * mono_arch_skip_breakpoint: * * See mini-amd64.c for docs. */ void mono_arch_skip_breakpoint (MonoContext *ctx, MonoJitInfo *ji) { MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 4); } /* * mono_arch_skip_single_step: * * See mini-amd64.c for docs. */ void mono_arch_skip_single_step (MonoContext *ctx) { MONO_CONTEXT_SET_IP (ctx, (guint8*)MONO_CONTEXT_GET_IP (ctx) + 4); } /* * mono_arch_get_seq_point_info: * * See mini-amd64.c for docs. */ gpointer mono_arch_get_seq_point_info (MonoDomain *domain, guint8 *code) { NOT_IMPLEMENTED; return NULL; } void mono_arch_init_lmf_ext (MonoLMFExt *ext, gpointer prev_lmf) { ext->lmf.previous_lmf = prev_lmf; /* Mark that this is a MonoLMFExt */ ext->lmf.previous_lmf = (gpointer)(((gssize)ext->lmf.previous_lmf) | 2); ext->lmf.iregs [mips_sp] = (gssize)ext; } #endif /* MONO_ARCH_SOFT_DEBUG_SUPPORTED */ gboolean mono_arch_opcode_supported (int opcode) { return FALSE; }
434658.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_bzero.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jblack-b <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/22 17:44:20 by jblack-b #+# #+# */ /* Updated: 2018/12/11 18:06:18 by jblack-b ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include "libft.h" void ft_bzero(void *s, size_t n) { size_t i; i = 0; while (i < n) ((unsigned char*)s)[i++] = 0; }
92511.c
/* eventsql.c: event log to SQLite importer. * * $Id$ * * Copyright (c) 2012-2018 Ravenbrook Limited. See end of file for license. * * This is a command-line tool that imports events from a text-format * MPS telemetry file into a SQLite database file. * * The default MPS library will write a binary-format telemetry file * which can be converted into a text-format file using the eventcnv * program (q.v.). * * Each event type gets its own table in the database. These tables * are created from the definitions in eventdef.h if they don't * already exist. Each event becomes a single row in the appropriate * table, which has a column for each event parameter, a time column * for the event time field, and a log_serial column to identify the * source log file. Because the database schema depends on the event * definitions in eventdef.h, eventsql has to be compiled using the * same event header files as those used to compile the MPS and * eventcnv which generated and processed the telemetry output. * * The program also creates several other tables: three 'glue' tables * containing event metadata - event_kind (one row per kind), * event_type (one row per type), and event_param (one row per * parameter), all derived from eventdef.h - and the event_log table * which has one row per log file imported (the log_serial column in * the event tables is a primary key to this event_log table). * * No tables are created if they already exist, unless the -r * (rebuild) switch is given. * * Options: * * -v (verbose): Increase verbosity. eventsql logs to stderr. By * default, it doesn't log much; it can be made more and more * loquacious by adding more -v switches. * * -p (progress): Show progress with a series of dots written to * standard output (one dot per 100,000 events processed). Defaults * on if -v specified, off otherwise. * * -t (test): Run unit tests on parts of eventsql. There aren't many * of these. TODO: write more unit tests. * * -d (delete): Delete the SQL file before importing. * * -f (force): Import the events to SQL even if the SQL database * already includes a record of importing a matching log file. * * -r (rebuild): Drop the glue tables from SQL, which will force them * to be recreated. Important if you change event types or kinds in * eventdef.h. * * -i <logfile>: Import events from the named logfile. Defaults to * standard input. If the specified file (matched by size and * modtime) has previously been imported to the same database, it will * not be imported again unless -f is specified. * * -o <database>: Import events to the named database file. If not * specified, eventsql will use the MPS_TELEMETRY_DATABASE environment * variable, and default to "mpsevent.db". * * $Id$ */ #include "misc.h" #include "config.h" #include "eventdef.h" #include "eventcom.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> /* on Windows, we build SQLite locally from the amalgamated sources */ #ifdef MPS_BUILD_MV #include "sqlite3.h" #else #include <sqlite3.h> #endif #define DATABASE_NAME_ENVAR "MPS_TELEMETRY_DATABASE" #define DEFAULT_DATABASE_NAME "mpsevent.db" #ifdef MPS_BUILD_MV #define strtoll _strtoi64 #endif typedef sqlite3_int64 int64; /* At non-zero verbosity levels we output rows of dots. One dot per * SMALL_TICK events, BIG_TICK dots per row. */ #define SMALL_TICK 100000 #define BIG_TICK 50 /* Utility code for logging to stderr with multiple log levels, * and for reporting errors. */ static unsigned int verbosity = 0; #define LOG_ALWAYS 0 #define LOG_OFTEN 1 #define LOG_SOMETIMES 2 #define LOG_SELDOM 3 #define LOG_RARELY 4 ATTRIBUTE_FORMAT((printf, 2, 0)) static void vlog(unsigned int level, const char *format, va_list args) { if (level <= verbosity) { fflush(stderr); /* sync */ fprintf(stderr, "log %d: ", level); vfprintf(stderr, format, args); fprintf(stderr, "\n"); } } ATTRIBUTE_FORMAT((printf, 2, 3)) static void evlog(unsigned int level, const char *format, ...) { va_list args; va_start(args, format); vlog(level, format, args); va_end(args); } ATTRIBUTE_FORMAT((printf, 1, 2)) static void error(const char *format, ...) { va_list args; fprintf(stderr, "Fatal error: "); va_start(args, format); vlog(LOG_ALWAYS, format, args); va_end(args); exit(1); } static void sqlite_error(int res, sqlite3 *db, const char *format, ...) { va_list args; evlog(LOG_ALWAYS, "Fatal SQL error %d", res); va_start(args, format); vlog(LOG_ALWAYS, format, args); va_end(args); evlog(LOG_ALWAYS, "SQLite message: %s\n", sqlite3_errmsg(db)); exit(1); } /* global control variables set by command-line parameters. */ static const char *prog; /* program name */ static int rebuild = FALSE; static int deleteDatabase = FALSE; static int runTests = FALSE; static int force = FALSE; static int progress = FALSE; static const char *databaseName = NULL; static const char *logFileName = NULL; static void usage(void) { fprintf(stderr, "Usage: %s [-rfdvt] [-i <logfile>] [-o <database>]\n" " -h (help) : this message.\n" " -r (rebuild) : re-create glue tables.\n" " -f (force) : ignore previous import of same logfile.\n" " -d (delete) : delete and recreate database file.\n" " -v (verbose) : increase logging to stderr.\n" " -p (progress): show progress with dots to stdout.\n" " -t (test) : run self-tests.\n" " -i <logfile> : read logfile (defaults to stdin)\n" " -o <database>: write database (defaults to\n" " " DATABASE_NAME_ENVAR " or " DEFAULT_DATABASE_NAME ").\n", prog); } static void usageError(void) { usage(); error("Bad usage"); } /* parseArgs -- parse command line arguments */ static void parseArgs(int argc, char *argv[]) { int i = 1; if (argc >= 1) prog = argv[0]; else prog = "unknown"; while(i < argc) { /* consider argument i */ if (argv[i][0] == '-') { /* it's an option argument */ char *p = argv[i] + 1; while(*p) { switch (*p) { case 'v': /* verbosity */ ++ verbosity; break; case 'p': /* progress */ progress = TRUE; break; case 'r': /* rebuild */ rebuild = TRUE; break; case 'd': /* rebuild */ deleteDatabase = TRUE; break; case 'f': /* force */ force = TRUE; break; case 't': /* run tests */ runTests = TRUE; break; case 'i': /* input (log file) name */ if (p[1] == '\0') { /* last character in this arg; name is next arg */ logFileName = argv[i+1]; ++ i; } else { /* not last character in arg; name is rest of arg */ logFileName = p+1; } goto next_i; case 'o': /* output (database file) name */ if (p[1] == '\0') { /* last character in this arg; name is next arg */ databaseName = argv[i+1]; ++ i; } else { /* not last character in arg; name is rest of arg */ databaseName = p+1; } goto next_i; case 'h': usage(); exit(EXIT_SUCCESS); default: usageError(); } ++ p; } } else { /* not an option argument */ usageError(); } next_i: ++ i; } if (verbosity > LOG_ALWAYS) progress = TRUE; } /* openDatabase(p) opens the database file and returns a SQLite 3 * database connection object. */ static sqlite3 *openDatabase(void) { sqlite3 *db; int res; if (!databaseName) { databaseName = getenv(DATABASE_NAME_ENVAR); if(!databaseName) databaseName = DEFAULT_DATABASE_NAME; } if (deleteDatabase) { res = remove(databaseName); if (res) evlog(LOG_ALWAYS, "Could not remove database file %s", databaseName); else evlog(LOG_OFTEN, "Removed database file %s", databaseName); } res = sqlite3_open_v2(databaseName, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); /* use default sqlite_vfs object */ if (res != SQLITE_OK) sqlite_error(res, db, "Opening %s failed", databaseName); evlog(LOG_OFTEN, "Writing to %s.",databaseName); return db; } /* closeDatabase(db) closes the database opened by openDatabase(). */ static void closeDatabase(sqlite3 *db) { int res = sqlite3_close(db); if (res != SQLITE_OK) sqlite_error(res, db, "Closing database failed"); evlog(LOG_SOMETIMES, "Closed %s.", databaseName); } /* Utility functions for SQLite statements. */ static sqlite3_stmt *prepareStatement(sqlite3 *db, const char *sql) { int res; sqlite3_stmt *statement; evlog(LOG_SELDOM, "Preparing statement %s", sql); res = sqlite3_prepare_v2(db, sql, -1, /* prepare whole string as statement */ &statement, NULL); if (res != SQLITE_OK) sqlite_error(res, db, "statement preparation failed: %s", sql); return statement; } static void finalizeStatement(sqlite3 *db, sqlite3_stmt *statement) { int res; res = sqlite3_finalize(statement); if (res != SQLITE_OK) sqlite_error(res, db, "statement finalize failed"); } static void runStatement(sqlite3 *db, const char *sql, const char *description) { int res; evlog(LOG_SELDOM, "%s: %s", description, sql); res = sqlite3_exec(db, sql, NULL, /* No callback */ NULL, /* No callback closure */ NULL); /* error messages handled by sqlite_error */ if (res != SQLITE_OK) sqlite_error(res, db, "%s failed - statement %s", description, sql); } /* Test for the existence of a table using sqlite_master table. */ static int tableExists(sqlite3* db, const char *tableName) { int res; int exists = 0; sqlite3_stmt *statement = NULL; statement = prepareStatement(db, "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?"); res = sqlite3_bind_text(statement, 1, tableName, -1, SQLITE_STATIC); if (res != SQLITE_OK) sqlite_error(res, db, "table existence bind of name failed."); res = sqlite3_step(statement); switch(res) { case SQLITE_DONE: exists = 0; break; case SQLITE_ROW: exists = 1; break; default: sqlite_error(res, db, "select from sqlite_master failed."); } finalizeStatement(db, statement); return exists; } /* Unit test for tableExists() */ static struct { const char* name; int exists; } tableTests[] = { {"event_kind", TRUE}, {"spong", FALSE}, {"EVENT_SegSplit", TRUE} }; static void testTableExists(sqlite3 *db) { size_t i; int defects = 0; int tests = 0; for (i=0; i < NELEMS(tableTests); ++i) { const char *name = tableTests[i].name; int exists = tableExists(db, name); if (exists) evlog(LOG_OFTEN, "Table exists: %s", name); else evlog(LOG_OFTEN, "Table does not exist: %s", name); if (exists != tableTests[i].exists) { evlog(LOG_ALWAYS, "tableExists test failed on table %s", name); ++ defects; } ++ tests; } evlog(LOG_ALWAYS, "%d tests, %d defects found.", tests, defects); } /* Every time we put events from a log file into a database file, we * add the log file to the event_log table, and get a serial number * from SQL which is then attached to all event rows from that log. * We use this to record overall SQL activity, to deter mistaken * attempts to add the same log file twice, and to allow events from * several different log files to share the same SQL file. * * When reading events from stdin, we can't so easily avoid the * duplication (unless we, e.g., take a hash of the event set); we * have to assume that the user is smart enough not to do that. */ static int64 logSerial = 0; static void registerLogFile(sqlite3 *db, const char *filename) { sqlite3_stmt *statement; int res; const unsigned char *name; int64 completed; int64 file_size; int64 file_modtime; if (filename) { struct stat st; res = stat(filename, &st); if (res != 0) error("Couldn't stat() %s", filename); file_size = st.st_size; file_modtime = st.st_mtime; statement = prepareStatement(db, "SELECT name, serial, completed FROM event_log" " WHERE size = ? AND modtime = ?"); res = sqlite3_bind_int64(statement, 1, file_size); if (res != SQLITE_OK) sqlite_error(res, db, "event_log bind of size failed."); res = sqlite3_bind_int64(statement, 2, file_modtime); if (res != SQLITE_OK) sqlite_error(res, db, "event_log bind of modtime failed."); res = sqlite3_step(statement); switch(res) { case SQLITE_DONE: evlog(LOG_SOMETIMES, "No log file matching '%s' found in database.", filename); break; case SQLITE_ROW: name = sqlite3_column_text(statement, 0); logSerial = sqlite3_column_int64(statement, 1); completed = sqlite3_column_int64(statement, 2); evlog(force ? LOG_OFTEN : LOG_ALWAYS, "Log file matching '%s' already in event_log, named \"%s\" (serial %llu, completed %llu).", filename, name, logSerial, completed); if (force) { evlog(LOG_OFTEN, "Continuing anyway because -f specified."); } else { evlog(LOG_ALWAYS, "Exiting. Specify -f to force events into SQL anyway."); exit(0); } break; default: sqlite_error(res, db, "select from event_log failed."); } finalizeStatement(db, statement); } else { /* stdin */ filename = "<stdin>"; file_size = 0; file_modtime = 0; } statement = prepareStatement(db, "INSERT into event_log (name, size, modtime, completed)" " VALUES (?, ?, ?, 0)"); res = sqlite3_bind_text(statement, 1, filename, -1, SQLITE_STATIC); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of name failed."); res = sqlite3_bind_int64(statement, 2, file_size); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of size failed."); res = sqlite3_bind_int64(statement, 3, file_modtime); if (res != SQLITE_OK) sqlite_error(res, db, "event_log insert bind of modtime failed."); res = sqlite3_step(statement); if (res != SQLITE_DONE) sqlite_error(res, db, "insert into event_log failed."); logSerial = sqlite3_last_insert_rowid(db); evlog(LOG_SOMETIMES, "Log file %s added to event_log with serial %llu", filename, logSerial); finalizeStatement(db, statement); } static void logFileCompleted(sqlite3 *db, int64 completed) { sqlite3_stmt *statement; int res; statement = prepareStatement(db, "UPDATE event_log SET completed=? WHERE serial=?"); res = sqlite3_bind_int64(statement, 2, logSerial); if (res != SQLITE_OK) sqlite_error(res, db, "event_log update bind of serial failed."); res = sqlite3_bind_int64(statement, 1, completed); if (res != SQLITE_OK) sqlite_error(res, db, "event_log update bind of completed failed."); res = sqlite3_step(statement); if (res != SQLITE_DONE) sqlite_error(res, db, "insert into event_log failed."); evlog(LOG_SOMETIMES, "Marked in event_log: %llu events", completed); finalizeStatement(db, statement); } /* Macro magic to make a CREATE TABLE statement for each event type. */ #define EVENT_PARAM_SQL_TYPE_A "INTEGER" #define EVENT_PARAM_SQL_TYPE_P "INTEGER" #define EVENT_PARAM_SQL_TYPE_U "INTEGER" #define EVENT_PARAM_SQL_TYPE_W "INTEGER" #define EVENT_PARAM_SQL_TYPE_D "REAL " #define EVENT_PARAM_SQL_TYPE_S "TEXT " #define EVENT_PARAM_SQL_TYPE_B "INTEGER" #define EVENT_PARAM_SQL_COLUMN(X, index, sort, ident, doc) \ "\"" #ident "\" " EVENT_PARAM_SQL_TYPE_##sort ", " #define EVENT_TABLE_CREATE(X, name, code, used, kind) \ "CREATE TABLE IF NOT EXISTS EVENT_" #name " ( " \ EVENT_##name##_PARAMS(EVENT_PARAM_SQL_COLUMN, X) \ "time INTEGER, " \ "log_serial INTEGER)", /* An array of table-creation statement strings. */ static const char *createStatements[] = { "CREATE TABLE IF NOT EXISTS event_kind (name TEXT," " description TEXT," " enum INTEGER PRIMARY KEY)", "CREATE TABLE IF NOT EXISTS event_type (name TEXT," " code INTEGER PRIMARY KEY," " used INTEGER," " kind INTEGER," " FOREIGN KEY (kind) REFERENCES event_kind(enum));", "CREATE TABLE IF NOT EXISTS event_param (type INTEGER," " param_index INTEGER," " sort TEXT," " ident TEXT," " doc TEXT," " FOREIGN KEY (type) REFERENCES event_type(code));", "CREATE TABLE IF NOT EXISTS event_log (name TEXT," " size INTEGER," " modtime INTEGER," " completed INTEGER," " serial INTEGER PRIMARY KEY AUTOINCREMENT)", EVENT_LIST(EVENT_TABLE_CREATE, X) }; /* makeTables makes all the tables. */ static void makeTables(sqlite3 *db) { size_t i; evlog(LOG_SOMETIMES, "Creating tables."); for (i=0; i < NELEMS(createStatements); ++i) { runStatement(db, createStatements[i], "Table creation"); } } static const char *glueTables[] = { "event_kind", "event_type", "event_param", }; static void dropGlueTables(sqlite3 *db) { size_t i; int res; char sql[1024]; evlog(LOG_ALWAYS, "Dropping glue tables so they are rebuilt."); for (i=0; i < NELEMS(glueTables); ++i) { evlog(LOG_SOMETIMES, "Dropping table %s", glueTables[i]); sprintf(sql, "DROP TABLE %s", glueTables[i]); res = sqlite3_exec(db, sql, NULL, /* No callback */ NULL, /* No callback closure */ NULL); /* error messages handled by sqlite_error */ /* Don't check for errors. */ (void)res; } } /* Populate the metadata "glue" tables event_kind, event_type, and * event_param. */ #define EVENT_KIND_DO_INSERT(X, name, description) \ res = sqlite3_bind_text(statement, 1, #name, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_kind bind of name \"" #name "\" failed."); \ res = sqlite3_bind_text(statement, 2, description, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_kind bind of description \"" description "\" failed."); \ res = sqlite3_bind_int(statement, 3, i); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_kind bind of enum %d failed.", i); \ ++i; \ res = sqlite3_step(statement); \ if (res != SQLITE_DONE) \ sqlite_error(res, db, "event_kind insert of name \"" #name "\" failed."); \ if (sqlite3_changes(db) != 0) \ evlog(LOG_SOMETIMES, "Insert of event_kind row for \"" #name "\" affected %d rows.", sqlite3_changes(db)); \ res = sqlite3_reset(statement); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "Couldn't reset event_kind insert statement."); #define EVENT_TYPE_DO_INSERT(X, name, code, used, kind) \ res = sqlite3_bind_text(statement, 1, #name, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of name \"" #name "\" failed."); \ res = sqlite3_bind_int(statement, 2, code); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of code %d failed.", code); \ res = sqlite3_bind_int(statement, 3, used); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of used for name \"" #name "\" failed."); \ res = sqlite3_bind_int(statement, 4, EventKind##kind); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of kind for name \"" #name "\" failed."); \ res = sqlite3_step(statement); \ if (res != SQLITE_DONE) \ sqlite_error(res, db, "event_type insert of name \"" #name "\" failed."); \ if (sqlite3_changes(db) != 0) \ evlog(LOG_SOMETIMES, "Insert of event_type row for \"" #name "\" affected %d rows.", sqlite3_changes(db)); \ res = sqlite3_reset(statement); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "Couldn't reset event_type insert statement."); #define EVENT_PARAM_DO_INSERT(code, index, sort, ident, doc) \ res = sqlite3_bind_int(statement, 1, code); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_param bind of code %d failed.", code); \ res = sqlite3_bind_int(statement, 2, index); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_param bind of index %d failed.", index); \ res = sqlite3_bind_text(statement, 3, #sort, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of sort \"" #sort "\" failed."); \ res = sqlite3_bind_text(statement, 4, #ident, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of ident \"" #ident "\" failed."); \ res = sqlite3_bind_text(statement, 5, doc, -1, SQLITE_STATIC); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "event_type bind of doc \"" doc "\" failed."); \ res = sqlite3_step(statement); \ if (res != SQLITE_DONE) \ sqlite_error(res, db, "event_param insert of \"" #ident "\" for code %d failed.", code); \ if (sqlite3_changes(db) != 0) \ evlog(LOG_SOMETIMES, "Insert of event_param row for code %d, ident \"" #ident "\" affected %d rows.", code, sqlite3_changes(db)); \ res = sqlite3_reset(statement); \ if (res != SQLITE_OK) \ sqlite_error(res, db, "Couldn't reset event_param insert statement."); #define EVENT_TYPE_INSERT_PARAMS(X, name, code, used, kind) \ EVENT_##name##_PARAMS(EVENT_PARAM_DO_INSERT, code) static void fillGlueTables(sqlite3 *db) { int i; sqlite3_stmt *statement; int res; statement = prepareStatement(db, "INSERT OR IGNORE INTO event_kind (name, description, enum)" "VALUES (?, ?, ?)"); i = 0; EventKindENUM(EVENT_KIND_DO_INSERT, X); finalizeStatement(db, statement); statement = prepareStatement(db, "INSERT OR IGNORE INTO event_type (name, code, used, kind)" "VALUES (?, ?, ?, ?)"); EVENT_LIST(EVENT_TYPE_DO_INSERT, X); finalizeStatement(db, statement); statement = prepareStatement(db, "INSERT OR IGNORE INTO event_param (type, param_index, sort, ident, doc)" "VALUES (?, ?, ?, ?, ?)"); EVENT_LIST(EVENT_TYPE_INSERT_PARAMS, X); finalizeStatement(db, statement); } /* Populate the actual event tables. */ #define EVENT_TYPE_DECLARE_STATEMENT(X, name, code, used, kind) \ sqlite3_stmt *stmt_##name; #define EVENT_PARAM_PREPARE_IDENT(X, index, sort, ident, doc) "\"" #ident "\", " #define EVENT_PARAM_PREPARE_PLACE(X, index, sort, ident, doc) "?, " #define EVENT_TYPE_PREPARE_STATEMENT(X, name, code, used, kind) \ stmt_##name = \ prepareStatement(db, \ "INSERT INTO EVENT_" #name " (" \ EVENT_##name##_PARAMS(EVENT_PARAM_PREPARE_IDENT, X) \ "log_serial, time) VALUES (" \ EVENT_##name##_PARAMS(EVENT_PARAM_PREPARE_PLACE,X) \ "?, ?)"); #define EVENT_TYPE_FINALIZE_STATEMENT(X, name, code, used, kind) \ finalizeStatement(db, stmt_##name); #define EVENT_PARAM_BIND_A bind_int #define EVENT_PARAM_BIND_P bind_int #define EVENT_PARAM_BIND_U bind_int #define EVENT_PARAM_BIND_W bind_int #define EVENT_PARAM_BIND_D bind_real #define EVENT_PARAM_BIND_S bind_text #define EVENT_PARAM_BIND_B bind_int #define EVENT_PARAM_BIND(X, index, sort, ident, doc) \ p = EVENT_PARAM_BIND_##sort (db, statement, eventCount, index+1, p); \ last_index = index+1; #define EVENT_TYPE_WRITE_SQL(X, name, code, used, kind) \ case code: \ statement = stmt_##name; \ /* bind all the parameters of this particular event with macro magic. */ \ EVENT_##name##_PARAMS(EVENT_PARAM_BIND, X) \ break; static char *bind_int(sqlite3 *db, sqlite3_stmt *stmt, int64 count, int field, char *p) { char *q; long long val; int res; while(*p == ' ') ++p; val = strtoll(p, &q, 16); if (q == p) error("event %llu field %d not an integer: %s", count, field, p); res = sqlite3_bind_int64(stmt, field, val); if (res != SQLITE_OK) sqlite_error(res, db, "event %llu field %d bind failed", count, field); return q; } static char *bind_real(sqlite3 *db, sqlite3_stmt *stmt, int64 count, int field, char *p) { char *q; double val; int res; while(*p == ' ') ++p; val = strtod(p, &q); if (q == p) error("event %llu field %d not a floating-point value: %s", count, field, p); res = sqlite3_bind_double(stmt, field, val); if (res != SQLITE_OK) sqlite_error(res, db, "event %llu field %d bind failed", count, field); return q; } static char *bind_text(sqlite3 *db, sqlite3_stmt *stmt, int64 count, int field, char *p) { char *q; int res; while(*p == ' ') ++p; q = p; while((*q != '\n') && (*q != '\0')) { ++ q; } if ((q == p) || (q[-1] != '"')) error("event %llu string field %d has no closing quote mark.", count, field); res = sqlite3_bind_text(stmt, field, p, (int)(q-p-1), SQLITE_STATIC); if (res != SQLITE_OK) sqlite_error(res, db, "event %llu field %d bind failed", count, field); return q; } /* this is overkill, at present. */ #define MAX_LOG_LINE_LENGTH 1024 /* readLog -- read and parse log. Returns the number of events written. */ static int64 readLog(FILE *input, sqlite3 *db) { int64 eventCount = 0; /* declare statements for every event type */ EVENT_LIST(EVENT_TYPE_DECLARE_STATEMENT, X); /* prepare statements for every event type */ EVENT_LIST(EVENT_TYPE_PREPARE_STATEMENT, X); runStatement(db, "BEGIN", "Transaction start"); while (TRUE) { /* loop for each event */ char line[MAX_LOG_LINE_LENGTH]; char *p; char *q; int last_index=0; sqlite3_stmt *statement = NULL; int res; int64 clock_field; long code; p = fgets(line, MAX_LOG_LINE_LENGTH, input); if (!p) { if (feof(input)) break; else error("Couldn't read line after event %llu", eventCount); } eventCount++; clock_field = strtoll(p, &q, 16); if (q == p) error("event %llu clock field not a hex integer: %s", eventCount, p); if (*q != ' ') error("event %llu code field not preceded by ' ': %s", eventCount, q); while(*q == ' ') ++q; p = q; code = strtol(p, &q, 16); if (q == p) error("event %llu code field not an integer: %s", eventCount, p); p = q; /* Write event to SQLite. */ switch (code) { /* this macro sets statement and last_index */ EVENT_LIST(EVENT_TYPE_WRITE_SQL, X); default: error("Event %llu has Unknown event code %ld", eventCount, code); } /* bind the fields we store for every event */ \ res = sqlite3_bind_int64(statement, last_index+1, logSerial); if (res != SQLITE_OK) sqlite_error(res, db, "Event %llu bind of log_serial failed.", eventCount); res = sqlite3_bind_int64(statement, last_index+2, clock_field); if (res != SQLITE_OK) sqlite_error(res, db, "Event %llu bind of clock failed.", eventCount); res = sqlite3_step(statement); if (res != SQLITE_DONE) sqlite_error(res, db, "insert of event %llu failed.", eventCount); res = sqlite3_reset(statement); if (res != SQLITE_OK) sqlite_error(res, db, "Couldn't reset insert statement of event %llu", eventCount); if (progress) { if ((eventCount % SMALL_TICK) == 0) { printf("."); fflush(stdout); if (((eventCount / SMALL_TICK) % BIG_TICK) == 0) { printf("\n"); fflush(stdout); evlog(LOG_SOMETIMES, "%lu events.", (unsigned long)eventCount); } } } } if (progress) { printf("\n"); fflush(stdout); } runStatement(db, "COMMIT", "Transaction finish"); logFileCompleted(db, eventCount); /* finalize all the statements */ EVENT_LIST(EVENT_TYPE_FINALIZE_STATEMENT, X); return eventCount; } /* openLog -- open the log file doors, HAL */ static FILE *openLog(sqlite3 *db) { FILE *input; registerLogFile(db, logFileName); if (!logFileName) { input = stdin; logFileName = "<stdin>"; } else { input = fopen(logFileName, "r"); if (input == NULL) error("unable to open %s", logFileName); } evlog(LOG_OFTEN, "Reading %s.", logFileName ? logFileName : "standard input"); return input; } static int64 writeEventsToSQL(sqlite3 *db) { FILE *input; int64 count; input = openLog(db); count = readLog(input, db); (void)fclose(input); return count; } int main(int argc, char *argv[]) { sqlite3 *db; int64 count; parseArgs(argc, argv); db = openDatabase(); if (rebuild) { dropGlueTables(db); } makeTables(db); fillGlueTables(db); count = writeEventsToSQL(db); evlog(LOG_ALWAYS, "Imported %llu events from %s to %s, serial %llu.", count, logFileName, databaseName, logSerial); if (runTests) { /* TODO: more unit tests in here */ testTableExists(db); } closeDatabase(db); return 0; } /* COPYRIGHT AND LICENSE * * Copyright (c) 2012-2018 Ravenbrook Limited <http://www.ravenbrook.com/>. * All rights reserved. This is an open source license. Contact * Ravenbrook for commercial licensing options. * * 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. Redistributions in any form must be accompanied by information on how * to obtain complete source code for this software and any accompanying * software that uses this software. The source code must either be * included in the distribution or be available for no more than the cost * of distribution plus a nominal fee, and must be freely redistributable * under reasonable conditions. For an executable file, complete source * code means the source code for all modules it contains. It does not * include source code for modules or files that typically accompany the * major components of the operating system on which the executable file * runs. * * 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, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDERS AND 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. */
870119.c
/* * FIPS-46-3 compliant Triple-DES implementation * * Copyright (C) 2006-2014, Brainspark B.V. * * This file is part of PolarSSL (http://www.polarssl.org) * Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org> * * All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * DES, on which TDES is based, was originally designed by Horst Feistel * at IBM in 1974, and was adopted as a standard by NIST (formerly NBS). * * http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf */ #if !defined(POLARSSL_CONFIG_FILE) #include "polarssl/config.h" #else #include POLARSSL_CONFIG_FILE #endif #if defined(POLARSSL_DES_C) #include "polarssl/des.h" #if defined(POLARSSL_PLATFORM_C) #include "polarssl/platform.h" #else #define polarssl_printf printf #endif #if !defined(POLARSSL_DES_ALT) /* Implementation that should never be optimized out by the compiler */ static void polarssl_zeroize( void *v, size_t n ) { volatile unsigned char *p = v; while( n-- ) *p++ = 0; } /* * 32-bit integer manipulation macros (big endian) */ #ifndef GET_UINT32_BE #define GET_UINT32_BE(n,b,i) \ { \ (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ | ( (uint32_t) (b)[(i) + 1] << 16 ) \ | ( (uint32_t) (b)[(i) + 2] << 8 ) \ | ( (uint32_t) (b)[(i) + 3] ); \ } #endif #ifndef PUT_UINT32_BE #define PUT_UINT32_BE(n,b,i) \ { \ (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ (b)[(i) + 3] = (unsigned char) ( (n) ); \ } #endif /* * Expanded DES S-boxes */ static const uint32_t SB1[64] = { 0x01010400, 0x00000000, 0x00010000, 0x01010404, 0x01010004, 0x00010404, 0x00000004, 0x00010000, 0x00000400, 0x01010400, 0x01010404, 0x00000400, 0x01000404, 0x01010004, 0x01000000, 0x00000004, 0x00000404, 0x01000400, 0x01000400, 0x00010400, 0x00010400, 0x01010000, 0x01010000, 0x01000404, 0x00010004, 0x01000004, 0x01000004, 0x00010004, 0x00000000, 0x00000404, 0x00010404, 0x01000000, 0x00010000, 0x01010404, 0x00000004, 0x01010000, 0x01010400, 0x01000000, 0x01000000, 0x00000400, 0x01010004, 0x00010000, 0x00010400, 0x01000004, 0x00000400, 0x00000004, 0x01000404, 0x00010404, 0x01010404, 0x00010004, 0x01010000, 0x01000404, 0x01000004, 0x00000404, 0x00010404, 0x01010400, 0x00000404, 0x01000400, 0x01000400, 0x00000000, 0x00010004, 0x00010400, 0x00000000, 0x01010004 }; static const uint32_t SB2[64] = { 0x80108020, 0x80008000, 0x00008000, 0x00108020, 0x00100000, 0x00000020, 0x80100020, 0x80008020, 0x80000020, 0x80108020, 0x80108000, 0x80000000, 0x80008000, 0x00100000, 0x00000020, 0x80100020, 0x00108000, 0x00100020, 0x80008020, 0x00000000, 0x80000000, 0x00008000, 0x00108020, 0x80100000, 0x00100020, 0x80000020, 0x00000000, 0x00108000, 0x00008020, 0x80108000, 0x80100000, 0x00008020, 0x00000000, 0x00108020, 0x80100020, 0x00100000, 0x80008020, 0x80100000, 0x80108000, 0x00008000, 0x80100000, 0x80008000, 0x00000020, 0x80108020, 0x00108020, 0x00000020, 0x00008000, 0x80000000, 0x00008020, 0x80108000, 0x00100000, 0x80000020, 0x00100020, 0x80008020, 0x80000020, 0x00100020, 0x00108000, 0x00000000, 0x80008000, 0x00008020, 0x80000000, 0x80100020, 0x80108020, 0x00108000 }; static const uint32_t SB3[64] = { 0x00000208, 0x08020200, 0x00000000, 0x08020008, 0x08000200, 0x00000000, 0x00020208, 0x08000200, 0x00020008, 0x08000008, 0x08000008, 0x00020000, 0x08020208, 0x00020008, 0x08020000, 0x00000208, 0x08000000, 0x00000008, 0x08020200, 0x00000200, 0x00020200, 0x08020000, 0x08020008, 0x00020208, 0x08000208, 0x00020200, 0x00020000, 0x08000208, 0x00000008, 0x08020208, 0x00000200, 0x08000000, 0x08020200, 0x08000000, 0x00020008, 0x00000208, 0x00020000, 0x08020200, 0x08000200, 0x00000000, 0x00000200, 0x00020008, 0x08020208, 0x08000200, 0x08000008, 0x00000200, 0x00000000, 0x08020008, 0x08000208, 0x00020000, 0x08000000, 0x08020208, 0x00000008, 0x00020208, 0x00020200, 0x08000008, 0x08020000, 0x08000208, 0x00000208, 0x08020000, 0x00020208, 0x00000008, 0x08020008, 0x00020200 }; static const uint32_t SB4[64] = { 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802080, 0x00800081, 0x00800001, 0x00002001, 0x00000000, 0x00802000, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00800080, 0x00800001, 0x00000001, 0x00002000, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002001, 0x00002080, 0x00800081, 0x00000001, 0x00002080, 0x00800080, 0x00002000, 0x00802080, 0x00802081, 0x00000081, 0x00800080, 0x00800001, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00000000, 0x00802000, 0x00002080, 0x00800080, 0x00800081, 0x00000001, 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802081, 0x00000081, 0x00000001, 0x00002000, 0x00800001, 0x00002001, 0x00802080, 0x00800081, 0x00002001, 0x00002080, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002000, 0x00802080 }; static const uint32_t SB5[64] = { 0x00000100, 0x02080100, 0x02080000, 0x42000100, 0x00080000, 0x00000100, 0x40000000, 0x02080000, 0x40080100, 0x00080000, 0x02000100, 0x40080100, 0x42000100, 0x42080000, 0x00080100, 0x40000000, 0x02000000, 0x40080000, 0x40080000, 0x00000000, 0x40000100, 0x42080100, 0x42080100, 0x02000100, 0x42080000, 0x40000100, 0x00000000, 0x42000000, 0x02080100, 0x02000000, 0x42000000, 0x00080100, 0x00080000, 0x42000100, 0x00000100, 0x02000000, 0x40000000, 0x02080000, 0x42000100, 0x40080100, 0x02000100, 0x40000000, 0x42080000, 0x02080100, 0x40080100, 0x00000100, 0x02000000, 0x42080000, 0x42080100, 0x00080100, 0x42000000, 0x42080100, 0x02080000, 0x00000000, 0x40080000, 0x42000000, 0x00080100, 0x02000100, 0x40000100, 0x00080000, 0x00000000, 0x40080000, 0x02080100, 0x40000100 }; static const uint32_t SB6[64] = { 0x20000010, 0x20400000, 0x00004000, 0x20404010, 0x20400000, 0x00000010, 0x20404010, 0x00400000, 0x20004000, 0x00404010, 0x00400000, 0x20000010, 0x00400010, 0x20004000, 0x20000000, 0x00004010, 0x00000000, 0x00400010, 0x20004010, 0x00004000, 0x00404000, 0x20004010, 0x00000010, 0x20400010, 0x20400010, 0x00000000, 0x00404010, 0x20404000, 0x00004010, 0x00404000, 0x20404000, 0x20000000, 0x20004000, 0x00000010, 0x20400010, 0x00404000, 0x20404010, 0x00400000, 0x00004010, 0x20000010, 0x00400000, 0x20004000, 0x20000000, 0x00004010, 0x20000010, 0x20404010, 0x00404000, 0x20400000, 0x00404010, 0x20404000, 0x00000000, 0x20400010, 0x00000010, 0x00004000, 0x20400000, 0x00404010, 0x00004000, 0x00400010, 0x20004010, 0x00000000, 0x20404000, 0x20000000, 0x00400010, 0x20004010 }; static const uint32_t SB7[64] = { 0x00200000, 0x04200002, 0x04000802, 0x00000000, 0x00000800, 0x04000802, 0x00200802, 0x04200800, 0x04200802, 0x00200000, 0x00000000, 0x04000002, 0x00000002, 0x04000000, 0x04200002, 0x00000802, 0x04000800, 0x00200802, 0x00200002, 0x04000800, 0x04000002, 0x04200000, 0x04200800, 0x00200002, 0x04200000, 0x00000800, 0x00000802, 0x04200802, 0x00200800, 0x00000002, 0x04000000, 0x00200800, 0x04000000, 0x00200800, 0x00200000, 0x04000802, 0x04000802, 0x04200002, 0x04200002, 0x00000002, 0x00200002, 0x04000000, 0x04000800, 0x00200000, 0x04200800, 0x00000802, 0x00200802, 0x04200800, 0x00000802, 0x04000002, 0x04200802, 0x04200000, 0x00200800, 0x00000000, 0x00000002, 0x04200802, 0x00000000, 0x00200802, 0x04200000, 0x00000800, 0x04000002, 0x04000800, 0x00000800, 0x00200002 }; static const uint32_t SB8[64] = { 0x10001040, 0x00001000, 0x00040000, 0x10041040, 0x10000000, 0x10001040, 0x00000040, 0x10000000, 0x00040040, 0x10040000, 0x10041040, 0x00041000, 0x10041000, 0x00041040, 0x00001000, 0x00000040, 0x10040000, 0x10000040, 0x10001000, 0x00001040, 0x00041000, 0x00040040, 0x10040040, 0x10041000, 0x00001040, 0x00000000, 0x00000000, 0x10040040, 0x10000040, 0x10001000, 0x00041040, 0x00040000, 0x00041040, 0x00040000, 0x10041000, 0x00001000, 0x00000040, 0x10040040, 0x00001000, 0x00041040, 0x10001000, 0x00000040, 0x10000040, 0x10040000, 0x10040040, 0x10000000, 0x00040000, 0x10001040, 0x00000000, 0x10041040, 0x00040040, 0x10000040, 0x10040000, 0x10001000, 0x10001040, 0x00000000, 0x10041040, 0x00041000, 0x00041000, 0x00001040, 0x00001040, 0x00040040, 0x10000000, 0x10041000 }; /* * PC1: left and right halves bit-swap */ static const uint32_t LHs[16] = { 0x00000000, 0x00000001, 0x00000100, 0x00000101, 0x00010000, 0x00010001, 0x00010100, 0x00010101, 0x01000000, 0x01000001, 0x01000100, 0x01000101, 0x01010000, 0x01010001, 0x01010100, 0x01010101 }; static const uint32_t RHs[16] = { 0x00000000, 0x01000000, 0x00010000, 0x01010000, 0x00000100, 0x01000100, 0x00010100, 0x01010100, 0x00000001, 0x01000001, 0x00010001, 0x01010001, 0x00000101, 0x01000101, 0x00010101, 0x01010101, }; /* * Initial Permutation macro */ #define DES_IP(X,Y) \ { \ T = ((X >> 4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T << 4); \ T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16); \ T = ((Y >> 2) ^ X) & 0x33333333; X ^= T; Y ^= (T << 2); \ T = ((Y >> 8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T << 8); \ Y = ((Y << 1) | (Y >> 31)) & 0xFFFFFFFF; \ T = (X ^ Y) & 0xAAAAAAAA; Y ^= T; X ^= T; \ X = ((X << 1) | (X >> 31)) & 0xFFFFFFFF; \ } /* * Final Permutation macro */ #define DES_FP(X,Y) \ { \ X = ((X << 31) | (X >> 1)) & 0xFFFFFFFF; \ T = (X ^ Y) & 0xAAAAAAAA; X ^= T; Y ^= T; \ Y = ((Y << 31) | (Y >> 1)) & 0xFFFFFFFF; \ T = ((Y >> 8) ^ X) & 0x00FF00FF; X ^= T; Y ^= (T << 8); \ T = ((Y >> 2) ^ X) & 0x33333333; X ^= T; Y ^= (T << 2); \ T = ((X >> 16) ^ Y) & 0x0000FFFF; Y ^= T; X ^= (T << 16); \ T = ((X >> 4) ^ Y) & 0x0F0F0F0F; Y ^= T; X ^= (T << 4); \ } /* * DES round macro */ #define DES_ROUND(X,Y) \ { \ T = *SK++ ^ X; \ Y ^= SB8[ (T ) & 0x3F ] ^ \ SB6[ (T >> 8) & 0x3F ] ^ \ SB4[ (T >> 16) & 0x3F ] ^ \ SB2[ (T >> 24) & 0x3F ]; \ \ T = *SK++ ^ ((X << 28) | (X >> 4)); \ Y ^= SB7[ (T ) & 0x3F ] ^ \ SB5[ (T >> 8) & 0x3F ] ^ \ SB3[ (T >> 16) & 0x3F ] ^ \ SB1[ (T >> 24) & 0x3F ]; \ } #define SWAP(a,b) { uint32_t t = a; a = b; b = t; t = 0; } void des_init( des_context *ctx ) { memset( ctx, 0, sizeof( des_context ) ); } void des_free( des_context *ctx ) { if( ctx == NULL ) return; polarssl_zeroize( ctx, sizeof( des_context ) ); } void des3_init( des3_context *ctx ) { memset( ctx, 0, sizeof( des3_context ) ); } void des3_free( des3_context *ctx ) { if( ctx == NULL ) return; polarssl_zeroize( ctx, sizeof( des3_context ) ); } static const unsigned char odd_parity_table[128] = { 1, 2, 4, 7, 8, 11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44, 47, 49, 50, 52, 55, 56, 59, 61, 62, 64, 67, 69, 70, 73, 74, 76, 79, 81, 82, 84, 87, 88, 91, 93, 94, 97, 98, 100, 103, 104, 107, 109, 110, 112, 115, 117, 118, 121, 122, 124, 127, 128, 131, 133, 134, 137, 138, 140, 143, 145, 146, 148, 151, 152, 155, 157, 158, 161, 162, 164, 167, 168, 171, 173, 174, 176, 179, 181, 182, 185, 186, 188, 191, 193, 194, 196, 199, 200, 203, 205, 206, 208, 211, 213, 214, 217, 218, 220, 223, 224, 227, 229, 230, 233, 234, 236, 239, 241, 242, 244, 247, 248, 251, 253, 254 }; void des_key_set_parity( unsigned char key[DES_KEY_SIZE] ) { int i; for( i = 0; i < DES_KEY_SIZE; i++ ) key[i] = odd_parity_table[key[i] / 2]; } /* * Check the given key's parity, returns 1 on failure, 0 on SUCCESS */ int des_key_check_key_parity( const unsigned char key[DES_KEY_SIZE] ) { int i; for( i = 0; i < DES_KEY_SIZE; i++ ) if( key[i] != odd_parity_table[key[i] / 2] ) return( 1 ); return( 0 ); } /* * Table of weak and semi-weak keys * * Source: http://en.wikipedia.org/wiki/Weak_key * * Weak: * Alternating ones + zeros (0x0101010101010101) * Alternating 'F' + 'E' (0xFEFEFEFEFEFEFEFE) * '0xE0E0E0E0F1F1F1F1' * '0x1F1F1F1F0E0E0E0E' * * Semi-weak: * 0x011F011F010E010E and 0x1F011F010E010E01 * 0x01E001E001F101F1 and 0xE001E001F101F101 * 0x01FE01FE01FE01FE and 0xFE01FE01FE01FE01 * 0x1FE01FE00EF10EF1 and 0xE01FE01FF10EF10E * 0x1FFE1FFE0EFE0EFE and 0xFE1FFE1FFE0EFE0E * 0xE0FEE0FEF1FEF1FE and 0xFEE0FEE0FEF1FEF1 * */ #define WEAK_KEY_COUNT 16 static const unsigned char weak_key_table[WEAK_KEY_COUNT][DES_KEY_SIZE] = { { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }, { 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE }, { 0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E }, { 0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1 }, { 0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E }, { 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01 }, { 0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1 }, { 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01 }, { 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE }, { 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01 }, { 0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1 }, { 0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E }, { 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE }, { 0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E }, { 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE }, { 0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1 } }; int des_key_check_weak( const unsigned char key[DES_KEY_SIZE] ) { int i; for( i = 0; i < WEAK_KEY_COUNT; i++ ) if( memcmp( weak_key_table[i], key, DES_KEY_SIZE) == 0 ) return( 1 ); return( 0 ); } static void des_setkey( uint32_t SK[32], const unsigned char key[DES_KEY_SIZE] ) { int i; uint32_t X, Y, T; GET_UINT32_BE( X, key, 0 ); GET_UINT32_BE( Y, key, 4 ); /* * Permuted Choice 1 */ T = ((Y >> 4) ^ X) & 0x0F0F0F0F; X ^= T; Y ^= (T << 4); T = ((Y ) ^ X) & 0x10101010; X ^= T; Y ^= (T ); X = (LHs[ (X ) & 0xF] << 3) | (LHs[ (X >> 8) & 0xF ] << 2) | (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ] ) | (LHs[ (X >> 5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6) | (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4); Y = (RHs[ (Y >> 1) & 0xF] << 3) | (RHs[ (Y >> 9) & 0xF ] << 2) | (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ] ) | (RHs[ (Y >> 4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6) | (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4); X &= 0x0FFFFFFF; Y &= 0x0FFFFFFF; /* * calculate subkeys */ for( i = 0; i < 16; i++ ) { if( i < 2 || i == 8 || i == 15 ) { X = ((X << 1) | (X >> 27)) & 0x0FFFFFFF; Y = ((Y << 1) | (Y >> 27)) & 0x0FFFFFFF; } else { X = ((X << 2) | (X >> 26)) & 0x0FFFFFFF; Y = ((Y << 2) | (Y >> 26)) & 0x0FFFFFFF; } *SK++ = ((X << 4) & 0x24000000) | ((X << 28) & 0x10000000) | ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000) | ((X << 6) & 0x01000000) | ((X << 9) & 0x00200000) | ((X >> 1) & 0x00100000) | ((X << 10) & 0x00040000) | ((X << 2) & 0x00020000) | ((X >> 10) & 0x00010000) | ((Y >> 13) & 0x00002000) | ((Y >> 4) & 0x00001000) | ((Y << 6) & 0x00000800) | ((Y >> 1) & 0x00000400) | ((Y >> 14) & 0x00000200) | ((Y ) & 0x00000100) | ((Y >> 5) & 0x00000020) | ((Y >> 10) & 0x00000010) | ((Y >> 3) & 0x00000008) | ((Y >> 18) & 0x00000004) | ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001); *SK++ = ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000) | ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000) | ((X >> 2) & 0x02000000) | ((X << 1) & 0x01000000) | ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000) | ((X << 3) & 0x00080000) | ((X >> 6) & 0x00040000) | ((X << 15) & 0x00020000) | ((X >> 4) & 0x00010000) | ((Y >> 2) & 0x00002000) | ((Y << 8) & 0x00001000) | ((Y >> 14) & 0x00000808) | ((Y >> 9) & 0x00000400) | ((Y ) & 0x00000200) | ((Y << 7) & 0x00000100) | ((Y >> 7) & 0x00000020) | ((Y >> 3) & 0x00000011) | ((Y << 2) & 0x00000004) | ((Y >> 21) & 0x00000002); } } /* * DES key schedule (56-bit, encryption) */ int des_setkey_enc( des_context *ctx, const unsigned char key[DES_KEY_SIZE] ) { des_setkey( ctx->sk, key ); return( 0 ); } /* * DES key schedule (56-bit, decryption) */ int des_setkey_dec( des_context *ctx, const unsigned char key[DES_KEY_SIZE] ) { int i; des_setkey( ctx->sk, key ); for( i = 0; i < 16; i += 2 ) { SWAP( ctx->sk[i ], ctx->sk[30 - i] ); SWAP( ctx->sk[i + 1], ctx->sk[31 - i] ); } return( 0 ); } static void des3_set2key( uint32_t esk[96], uint32_t dsk[96], const unsigned char key[DES_KEY_SIZE*2] ) { int i; des_setkey( esk, key ); des_setkey( dsk + 32, key + 8 ); for( i = 0; i < 32; i += 2 ) { dsk[i ] = esk[30 - i]; dsk[i + 1] = esk[31 - i]; esk[i + 32] = dsk[62 - i]; esk[i + 33] = dsk[63 - i]; esk[i + 64] = esk[i ]; esk[i + 65] = esk[i + 1]; dsk[i + 64] = dsk[i ]; dsk[i + 65] = dsk[i + 1]; } } /* * Triple-DES key schedule (112-bit, encryption) */ int des3_set2key_enc( des3_context *ctx, const unsigned char key[DES_KEY_SIZE * 2] ) { uint32_t sk[96]; des3_set2key( ctx->sk, sk, key ); polarssl_zeroize( sk, sizeof( sk ) ); return( 0 ); } /* * Triple-DES key schedule (112-bit, decryption) */ int des3_set2key_dec( des3_context *ctx, const unsigned char key[DES_KEY_SIZE * 2] ) { uint32_t sk[96]; des3_set2key( sk, ctx->sk, key ); polarssl_zeroize( sk, sizeof( sk ) ); return( 0 ); } static void des3_set3key( uint32_t esk[96], uint32_t dsk[96], const unsigned char key[24] ) { int i; des_setkey( esk, key ); des_setkey( dsk + 32, key + 8 ); des_setkey( esk + 64, key + 16 ); for( i = 0; i < 32; i += 2 ) { dsk[i ] = esk[94 - i]; dsk[i + 1] = esk[95 - i]; esk[i + 32] = dsk[62 - i]; esk[i + 33] = dsk[63 - i]; dsk[i + 64] = esk[30 - i]; dsk[i + 65] = esk[31 - i]; } } /* * Triple-DES key schedule (168-bit, encryption) */ int des3_set3key_enc( des3_context *ctx, const unsigned char key[DES_KEY_SIZE * 3] ) { uint32_t sk[96]; des3_set3key( ctx->sk, sk, key ); polarssl_zeroize( sk, sizeof( sk ) ); return( 0 ); } /* * Triple-DES key schedule (168-bit, decryption) */ int des3_set3key_dec( des3_context *ctx, const unsigned char key[DES_KEY_SIZE * 3] ) { uint32_t sk[96]; des3_set3key( sk, ctx->sk, key ); polarssl_zeroize( sk, sizeof( sk ) ); return( 0 ); } /* * DES-ECB block encryption/decryption */ int des_crypt_ecb( des_context *ctx, const unsigned char input[8], unsigned char output[8] ) { int i; uint32_t X, Y, T, *SK; SK = ctx->sk; GET_UINT32_BE( X, input, 0 ); GET_UINT32_BE( Y, input, 4 ); DES_IP( X, Y ); for( i = 0; i < 8; i++ ) { DES_ROUND( Y, X ); DES_ROUND( X, Y ); } DES_FP( Y, X ); PUT_UINT32_BE( Y, output, 0 ); PUT_UINT32_BE( X, output, 4 ); return( 0 ); } #if defined(POLARSSL_CIPHER_MODE_CBC) /* * DES-CBC buffer encryption/decryption */ int des_crypt_cbc( des_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output ) { int i; unsigned char temp[8]; if( length % 8 ) return( POLARSSL_ERR_DES_INVALID_INPUT_LENGTH ); if( mode == DES_ENCRYPT ) { while( length > 0 ) { for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( input[i] ^ iv[i] ); des_crypt_ecb( ctx, output, output ); memcpy( iv, output, 8 ); input += 8; output += 8; length -= 8; } } else /* DES_DECRYPT */ { while( length > 0 ) { memcpy( temp, input, 8 ); des_crypt_ecb( ctx, input, output ); for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( output[i] ^ iv[i] ); memcpy( iv, temp, 8 ); input += 8; output += 8; length -= 8; } } return( 0 ); } #endif /* POLARSSL_CIPHER_MODE_CBC */ /* * 3DES-ECB block encryption/decryption */ int des3_crypt_ecb( des3_context *ctx, const unsigned char input[8], unsigned char output[8] ) { int i; uint32_t X, Y, T, *SK; SK = ctx->sk; GET_UINT32_BE( X, input, 0 ); GET_UINT32_BE( Y, input, 4 ); DES_IP( X, Y ); for( i = 0; i < 8; i++ ) { DES_ROUND( Y, X ); DES_ROUND( X, Y ); } for( i = 0; i < 8; i++ ) { DES_ROUND( X, Y ); DES_ROUND( Y, X ); } for( i = 0; i < 8; i++ ) { DES_ROUND( Y, X ); DES_ROUND( X, Y ); } DES_FP( Y, X ); PUT_UINT32_BE( Y, output, 0 ); PUT_UINT32_BE( X, output, 4 ); return( 0 ); } #if defined(POLARSSL_CIPHER_MODE_CBC) /* * 3DES-CBC buffer encryption/decryption */ int des3_crypt_cbc( des3_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output ) { int i; unsigned char temp[8]; if( length % 8 ) return( POLARSSL_ERR_DES_INVALID_INPUT_LENGTH ); if( mode == DES_ENCRYPT ) { while( length > 0 ) { for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( input[i] ^ iv[i] ); des3_crypt_ecb( ctx, output, output ); memcpy( iv, output, 8 ); input += 8; output += 8; length -= 8; } } else /* DES_DECRYPT */ { while( length > 0 ) { memcpy( temp, input, 8 ); des3_crypt_ecb( ctx, input, output ); for( i = 0; i < 8; i++ ) output[i] = (unsigned char)( output[i] ^ iv[i] ); memcpy( iv, temp, 8 ); input += 8; output += 8; length -= 8; } } return( 0 ); } #endif /* POLARSSL_CIPHER_MODE_CBC */ #endif /* !POLARSSL_DES_ALT */ #if defined(POLARSSL_SELF_TEST) #include <stdio.h> /* * DES and 3DES test vectors from: * * http://csrc.nist.gov/groups/STM/cavp/documents/des/tripledes-vectors.zip */ static const unsigned char des3_test_keys[24] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23 }; static const unsigned char des3_test_buf[8] = { 0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74 }; static const unsigned char des3_test_ecb_dec[3][8] = { { 0xCD, 0xD6, 0x4F, 0x2F, 0x94, 0x27, 0xC1, 0x5D }, { 0x69, 0x96, 0xC8, 0xFA, 0x47, 0xA2, 0xAB, 0xEB }, { 0x83, 0x25, 0x39, 0x76, 0x44, 0x09, 0x1A, 0x0A } }; static const unsigned char des3_test_ecb_enc[3][8] = { { 0x6A, 0x2A, 0x19, 0xF4, 0x1E, 0xCA, 0x85, 0x4B }, { 0x03, 0xE6, 0x9F, 0x5B, 0xFA, 0x58, 0xEB, 0x42 }, { 0xDD, 0x17, 0xE8, 0xB8, 0xB4, 0x37, 0xD2, 0x32 } }; #if defined(POLARSSL_CIPHER_MODE_CBC) static const unsigned char des3_test_iv[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, }; static const unsigned char des3_test_cbc_dec[3][8] = { { 0x12, 0x9F, 0x40, 0xB9, 0xD2, 0x00, 0x56, 0xB3 }, { 0x47, 0x0E, 0xFC, 0x9A, 0x6B, 0x8E, 0xE3, 0x93 }, { 0xC5, 0xCE, 0xCF, 0x63, 0xEC, 0xEC, 0x51, 0x4C } }; static const unsigned char des3_test_cbc_enc[3][8] = { { 0x54, 0xF1, 0x5A, 0xF6, 0xEB, 0xE3, 0xA4, 0xB4 }, { 0x35, 0x76, 0x11, 0x56, 0x5F, 0xA1, 0x8E, 0x4D }, { 0xCB, 0x19, 0x1F, 0x85, 0xD1, 0xED, 0x84, 0x39 } }; #endif /* POLARSSL_CIPHER_MODE_CBC */ /* * Checkup routine */ int des_self_test( int verbose ) { int i, j, u, v, ret = 0; des_context ctx; des3_context ctx3; unsigned char buf[8]; #if defined(POLARSSL_CIPHER_MODE_CBC) unsigned char prv[8]; unsigned char iv[8]; #endif des_init( &ctx ); des3_init( &ctx3 ); /* * ECB mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; v = i & 1; if( verbose != 0 ) polarssl_printf( " DES%c-ECB-%3d (%s): ", ( u == 0 ) ? ' ' : '3', 56 + u * 56, ( v == DES_DECRYPT ) ? "dec" : "enc" ); memcpy( buf, des3_test_buf, 8 ); switch( i ) { case 0: des_setkey_dec( &ctx, des3_test_keys ); break; case 1: des_setkey_enc( &ctx, des3_test_keys ); break; case 2: des3_set2key_dec( &ctx3, des3_test_keys ); break; case 3: des3_set2key_enc( &ctx3, des3_test_keys ); break; case 4: des3_set3key_dec( &ctx3, des3_test_keys ); break; case 5: des3_set3key_enc( &ctx3, des3_test_keys ); break; default: return( 1 ); } for( j = 0; j < 10000; j++ ) { if( u == 0 ) des_crypt_ecb( &ctx, buf, buf ); else des3_crypt_ecb( &ctx3, buf, buf ); } if( ( v == DES_DECRYPT && memcmp( buf, des3_test_ecb_dec[u], 8 ) != 0 ) || ( v != DES_DECRYPT && memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) ) { if( verbose != 0 ) polarssl_printf( "failed\n" ); ret = 1; goto exit; } if( verbose != 0 ) polarssl_printf( "passed\n" ); } if( verbose != 0 ) polarssl_printf( "\n" ); #if defined(POLARSSL_CIPHER_MODE_CBC) /* * CBC mode */ for( i = 0; i < 6; i++ ) { u = i >> 1; v = i & 1; if( verbose != 0 ) polarssl_printf( " DES%c-CBC-%3d (%s): ", ( u == 0 ) ? ' ' : '3', 56 + u * 56, ( v == DES_DECRYPT ) ? "dec" : "enc" ); memcpy( iv, des3_test_iv, 8 ); memcpy( prv, des3_test_iv, 8 ); memcpy( buf, des3_test_buf, 8 ); switch( i ) { case 0: des_setkey_dec( &ctx, des3_test_keys ); break; case 1: des_setkey_enc( &ctx, des3_test_keys ); break; case 2: des3_set2key_dec( &ctx3, des3_test_keys ); break; case 3: des3_set2key_enc( &ctx3, des3_test_keys ); break; case 4: des3_set3key_dec( &ctx3, des3_test_keys ); break; case 5: des3_set3key_enc( &ctx3, des3_test_keys ); break; default: return( 1 ); } if( v == DES_DECRYPT ) { for( j = 0; j < 10000; j++ ) { if( u == 0 ) des_crypt_cbc( &ctx, v, 8, iv, buf, buf ); else des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf ); } } else { for( j = 0; j < 10000; j++ ) { unsigned char tmp[8]; if( u == 0 ) des_crypt_cbc( &ctx, v, 8, iv, buf, buf ); else des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf ); memcpy( tmp, prv, 8 ); memcpy( prv, buf, 8 ); memcpy( buf, tmp, 8 ); } memcpy( buf, prv, 8 ); } if( ( v == DES_DECRYPT && memcmp( buf, des3_test_cbc_dec[u], 8 ) != 0 ) || ( v != DES_DECRYPT && memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) ) { if( verbose != 0 ) polarssl_printf( "failed\n" ); ret = 1; goto exit; } if( verbose != 0 ) polarssl_printf( "passed\n" ); } #endif /* POLARSSL_CIPHER_MODE_CBC */ if( verbose != 0 ) polarssl_printf( "\n" ); exit: des_free( &ctx ); des3_free( &ctx3 ); return( ret ); } #endif /* POLARSSL_SELF_TEST */ #endif /* POLARSSL_DES_C */
782075.c
/***************************************************************************** main.c Executes a predetermined program in its native environment (full login shell inside a console window). The goal is to allow simple Windows file type association to be handled by a Cygwin program as if it were invoked from the shell. *****************************************************************************/ /*---------------------------------------------------------------------------- Includes ----------------------------------------------------------------------------*/ #include <windows.h> #include <tchar.h> #include <shellapi.h> #include <strsafe.h> #include "config.h" #include "error.h" #include "path.h" /*---------------------------------------------------------------------------- Macros ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Types and Structures ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Memory Constants ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Module Variables ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- Module Prototypes ----------------------------------------------------------------------------*/ static void free_array( //frees an array of pointed-to things void** array, //pointer to array of pointers to free int count //number of items in the array ); static LPSTR* wc2mb_array( //convert array of strings WC -> MB LPCWSTR* strings, //wide-character array of string pointers int count //number of strings in array ); //multi-byte array of string pointers /*=========================================================================*/ int WINAPI WinMain( //Windows program entry point HINSTANCE hInstance, //handle to this application HINSTANCE hPrevInstance, //handle to previous application LPSTR lpCmdLine, //executed command int nCmdShow //window display options ) { //program exit status //local macros #define BUFFER_SIZE ( 512 ) //common size of string buffers //local variables int argc; //number of command line arguments LPTSTR* argv; //list of command line arguments LPWSTR* arguments; //list of argument string pointers static TCHAR command[ BUFFER_SIZE ]; //command to execute PROCESS_INFORMATION cp_pr_info; //CreateProcess process info BOOL cp_result; //result of CreateProcess STARTUPINFO cp_su_info; //CreateProcess startup info static TCHAR path[ BUFFER_SIZE ]; //file path argument error_t path_result;//error from path translation DWORD exit_code; //exit code of spawned process HRESULT str_result; //result of string operations //parse the command line arguments = CommandLineToArgvW( GetCommandLineW(), &argc ); if( arguments == NULL ) { return 1; } //see if a file was specified if( argc > 1 ) { //check for need to convert to ANSI characters #ifndef UNICODE argv = wc2mb_array( ( LPCWSTR* ) arguments, argc ); if( argv == NULL ) { LocalFree( arguments ); return 1; } #else argv = arguments; #endif //translate the file path path_result = cygpath( path, BUFFER_SIZE, argv[ 1 ], PATH_OPT_UNIX ); #ifndef UNICODE free_array( ( void** ) argv, argc ); #endif if( path_result < ERROR_NONE ) { LocalFree( arguments ); return 1; } //format command to execute a program with a file argument str_result = StringCchPrintf( command, BUFFER_SIZE, _T( "%s %s '%s \"%s\"'" ), config_console, config_shell, config_target, path ); } //no file specified else { //format command to execute a program without a file argument str_result = StringCchPrintf( command, BUFFER_SIZE, _T( "%s %s '%s'" ), config_console, config_shell, config_target ); } //parsed command-line arguments are no longer needed LocalFree( arguments ); //check string formatting results if( str_result != S_OK ) { return 1; } //initialize CreateProcess argument data memset( &cp_su_info, 0, sizeof( cp_su_info ) ); memset( &cp_pr_info, 0, sizeof( cp_pr_info ) ); //create the process for mintty cp_result = CreateProcess( NULL, command, NULL, NULL, FALSE, 0, NULL, NULL, &cp_su_info, &cp_pr_info ); //wait for console to finish if( cp_result == TRUE ) { WaitForSingleObject( cp_pr_info.hProcess, INFINITE ); cp_result = GetExitCodeProcess( cp_pr_info.hProcess, &exit_code ); CloseHandle( cp_pr_info.hProcess ); CloseHandle( cp_pr_info.hThread ); } //console was not started else { exit_code = 1; } //return exit code from spawned process return exit_code; } /*=========================================================================*/ static void free_array( //frees an array of pointed-to things void** array, //pointer to array of pointers to free int count //number of items in the array ) { //local variables int index; //array index //check pointer if( array == NULL ) { return; } //free each item in the array for( index = 0; index < count; ++index ) { if( array[ index ] != NULL ) { free( array[ index ] ); } } //free the array of pointers free( array ); } /*=========================================================================*/ static char** wc2mb_array( //convert array of strings WC -> MB LPCWSTR* strings, //wide-character array of string pointers int count //number of strings in array ) { //multi-byte array of string pointers //cleanly stops the string conversion loop #define stop_conversion() \ free_array( ( void** ) result, ( index + 1 ) ); \ result = NULL; \ break //local variables int conv_result;//result of string conversion int index; //array index int length; //lengths of strings char** result; //list of converted strings int size; //size of new buffer BOOL used_default; //flag if conversion defaulted //allocate an array of string pointers result = calloc( count, sizeof( char* ) ); //check allocation if( result == NULL ) { return NULL; } //convert each string to multi-byte representation for( index = 0; index < count; ++index ) { //get length of wide-character input string length = wcslen( strings[ index ] ); //converted string needs enough room for a terminator size = length + 1; //allocate storage for the same number of bytes result[ index ] = calloc( size, sizeof( char ) ); //check allocation if( result[ index ] == NULL ) { //free any allocated memory, and stop converting strings stop_conversion(); } //perform the conversion to a multi-byte string conv_result = WideCharToMultiByte( CP_ACP, //use context's codepage 0, //default conversion settings strings[ index ], //source string to convert length, //length of the string to convert result[ index ], //conversion destination memory size, //size of destination memory NULL, //use system default character &used_default //flag if conversion defaulted ); //check the conversion if( conv_result != length ) { //free any allocated memory, and stop converting strings stop_conversion(); } } //return list of converted strings (or NULL on failure) return result; }
54499.c
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2018 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Amitay Isaacs <[email protected]> | | Eric Warnke <[email protected]> | | Rasmus Lerdorf <[email protected]> | | Gerrit Thomson <[email protected]> | | Jani Taskinen <[email protected]> | | Stig Venaas <[email protected]> | | Doug Goldstein <[email protected]> | | PHP 4.0 updates: Zeev Suraski <[email protected]> | +----------------------------------------------------------------------+ */ /* $Id: 0ba62d9bc989a5fb9065dd1a0945b968b8b0f080 $ */ #define IS_EXT_MODULE #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include <stddef.h> #include "ext/standard/dl.h" #include "php_ldap.h" #ifdef PHP_WIN32 #include <string.h> #include "config.w32.h" #if HAVE_NSLDAP #include <winsock2.h> #endif #define strdup _strdup #undef WINDOWS #undef strcasecmp #undef strncasecmp #define WINSOCK 1 #define __STDC__ 1 #endif #include "ext/standard/php_string.h" #include "ext/standard/info.h" #ifdef HAVE_LDAP_SASL_H #include <sasl.h> #elif defined(HAVE_LDAP_SASL_SASL_H) #include <sasl/sasl.h> #endif #define PHP_LDAP_ESCAPE_FILTER 0x01 #define PHP_LDAP_ESCAPE_DN 0x02 #if defined(LDAP_CONTROL_PAGEDRESULTS) && !defined(HAVE_LDAP_CONTROL_FIND) LDAPControl *ldap_control_find( const char *oid, LDAPControl **ctrls, LDAPControl ***nextctrlp) { assert(nextctrlp == NULL); return ldap_find_control(oid, ctrls); } #endif #if !defined(LDAP_API_FEATURE_X_OPENLDAP) void ldap_memvfree(void **v) { ldap_value_free((char **)v); } #endif typedef struct { LDAP *link; #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC) zval rebindproc; #endif } ldap_linkdata; typedef struct { LDAPMessage *data; BerElement *ber; zval res; } ldap_resultentry; ZEND_DECLARE_MODULE_GLOBALS(ldap) static PHP_GINIT_FUNCTION(ldap); static int le_link, le_result, le_result_entry; #ifdef COMPILE_DL_LDAP ZEND_GET_MODULE(ldap) #endif static void _close_ldap_link(zend_resource *rsrc) /* {{{ */ { ldap_linkdata *ld = (ldap_linkdata *)rsrc->ptr; ldap_unbind_ext(ld->link, NULL, NULL); #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC) zval_ptr_dtor(&ld->rebindproc); #endif efree(ld); LDAPG(num_links)--; } /* }}} */ static void _free_ldap_result(zend_resource *rsrc) /* {{{ */ { LDAPMessage *result = (LDAPMessage *)rsrc->ptr; ldap_msgfree(result); } /* }}} */ static void _free_ldap_result_entry(zend_resource *rsrc) /* {{{ */ { ldap_resultentry *entry = (ldap_resultentry *)rsrc->ptr; if (entry->ber != NULL) { ber_free(entry->ber, 0); entry->ber = NULL; } zval_ptr_dtor(&entry->res); efree(entry); } /* }}} */ /* {{{ PHP_INI_BEGIN */ PHP_INI_BEGIN() STD_PHP_INI_ENTRY_EX("ldap.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_ldap_globals, ldap_globals, display_link_numbers) PHP_INI_END() /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(ldap) { ldap_globals->num_links = 0; } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(ldap) { REGISTER_INI_ENTRIES(); /* Constants to be used with deref-parameter in php_ldap_do_search() */ REGISTER_LONG_CONSTANT("LDAP_DEREF_NEVER", LDAP_DEREF_NEVER, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_DEREF_SEARCHING", LDAP_DEREF_SEARCHING, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_DEREF_FINDING", LDAP_DEREF_FINDING, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_DEREF_ALWAYS", LDAP_DEREF_ALWAYS, CONST_PERSISTENT | CONST_CS); /* Constants to be used with ldap_modify_batch() */ REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_ADD", LDAP_MODIFY_BATCH_ADD, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE", LDAP_MODIFY_BATCH_REMOVE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE_ALL", LDAP_MODIFY_BATCH_REMOVE_ALL, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REPLACE", LDAP_MODIFY_BATCH_REPLACE, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_ATTRIB", LDAP_MODIFY_BATCH_ATTRIB, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_MODTYPE", LDAP_MODIFY_BATCH_MODTYPE, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_VALUES", LDAP_MODIFY_BATCH_VALUES, CONST_PERSISTENT | CONST_CS); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP /* LDAP options */ REGISTER_LONG_CONSTANT("LDAP_OPT_DEREF", LDAP_OPT_DEREF, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_SIZELIMIT", LDAP_OPT_SIZELIMIT, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_TIMELIMIT", LDAP_OPT_TIMELIMIT, CONST_PERSISTENT | CONST_CS); #ifdef LDAP_OPT_NETWORK_TIMEOUT REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_OPT_NETWORK_TIMEOUT, CONST_PERSISTENT | CONST_CS); #elif defined (LDAP_X_OPT_CONNECT_TIMEOUT) REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_X_OPT_CONNECT_TIMEOUT, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_TIMEOUT REGISTER_LONG_CONSTANT("LDAP_OPT_TIMEOUT", LDAP_OPT_TIMEOUT, CONST_PERSISTENT | CONST_CS); #endif REGISTER_LONG_CONSTANT("LDAP_OPT_PROTOCOL_VERSION", LDAP_OPT_PROTOCOL_VERSION, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_NUMBER", LDAP_OPT_ERROR_NUMBER, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_REFERRALS", LDAP_OPT_REFERRALS, CONST_PERSISTENT | CONST_CS); #ifdef LDAP_OPT_RESTART REGISTER_LONG_CONSTANT("LDAP_OPT_RESTART", LDAP_OPT_RESTART, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_HOST_NAME REGISTER_LONG_CONSTANT("LDAP_OPT_HOST_NAME", LDAP_OPT_HOST_NAME, CONST_PERSISTENT | CONST_CS); #endif REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_STRING", LDAP_OPT_ERROR_STRING, CONST_PERSISTENT | CONST_CS); #ifdef LDAP_OPT_MATCHED_DN REGISTER_LONG_CONSTANT("LDAP_OPT_MATCHED_DN", LDAP_OPT_MATCHED_DN, CONST_PERSISTENT | CONST_CS); #endif REGISTER_LONG_CONSTANT("LDAP_OPT_SERVER_CONTROLS", LDAP_OPT_SERVER_CONTROLS, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_CLIENT_CONTROLS", LDAP_OPT_CLIENT_CONTROLS, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_DEBUG_LEVEL REGISTER_LONG_CONSTANT("LDAP_OPT_DEBUG_LEVEL", LDAP_OPT_DEBUG_LEVEL, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE REGISTER_LONG_CONSTANT("LDAP_OPT_DIAGNOSTIC_MESSAGE", LDAP_OPT_DIAGNOSTIC_MESSAGE, CONST_PERSISTENT | CONST_CS); #endif #ifdef HAVE_LDAP_SASL REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_MECH", LDAP_OPT_X_SASL_MECH, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_REALM", LDAP_OPT_X_SASL_REALM, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHCID", LDAP_OPT_X_SASL_AUTHCID, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHZID", LDAP_OPT_X_SASL_AUTHZID, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_SASL_NOCANON REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_NOCANON", LDAP_OPT_X_SASL_NOCANON, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_SASL_USERNAME REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_USERNAME", LDAP_OPT_X_SASL_USERNAME, CONST_PERSISTENT | CONST_CS); #endif #ifdef ORALDAP REGISTER_LONG_CONSTANT("GSLC_SSL_NO_AUTH", GSLC_SSL_NO_AUTH, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("GSLC_SSL_ONEWAY_AUTH", GSLC_SSL_ONEWAY_AUTH, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("GSLC_SSL_TWOWAY_AUTH", GSLC_SSL_TWOWAY_AUTH, CONST_PERSISTENT | CONST_CS); #endif #if (LDAP_API_VERSION > 2000) REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_REQUIRE_CERT", LDAP_OPT_X_TLS_REQUIRE_CERT, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_NEVER", LDAP_OPT_X_TLS_NEVER, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_HARD", LDAP_OPT_X_TLS_HARD, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_DEMAND", LDAP_OPT_X_TLS_DEMAND, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_ALLOW", LDAP_OPT_X_TLS_ALLOW, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_TRY", LDAP_OPT_X_TLS_TRY, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CACERTDIR", LDAP_OPT_X_TLS_CACERTDIR, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CACERTFILE", LDAP_OPT_X_TLS_CACERTFILE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CERTFILE", LDAP_OPT_X_TLS_CERTFILE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CIPHER_SUITE", LDAP_OPT_X_TLS_CIPHER_SUITE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_KEYFILE", LDAP_OPT_X_TLS_KEYFILE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_RANDOM_FILE", LDAP_OPT_X_TLS_RANDOM_FILE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_TLS_CRLCHECK REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRLCHECK", LDAP_OPT_X_TLS_CRLCHECK, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_NONE", LDAP_OPT_X_TLS_CRL_NONE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_PEER", LDAP_OPT_X_TLS_CRL_PEER, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_ALL", LDAP_OPT_X_TLS_CRL_ALL, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_TLS_DHFILE REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_DHFILE", LDAP_OPT_X_TLS_DHFILE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_TLS_CRLFILE REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRLFILE", LDAP_OPT_X_TLS_CRLFILE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_MIN", LDAP_OPT_X_TLS_PROTOCOL_MIN, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_SSL2", LDAP_OPT_X_TLS_PROTOCOL_SSL2, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_SSL3", LDAP_OPT_X_TLS_PROTOCOL_SSL3, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_0", LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_1", LDAP_OPT_X_TLS_PROTOCOL_TLS1_1, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_2", LDAP_OPT_X_TLS_PROTOCOL_TLS1_2, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_TLS_PACKAGE REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PACKAGE", LDAP_OPT_X_TLS_PACKAGE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_OPT_X_KEEPALIVE_IDLE REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_IDLE", LDAP_OPT_X_KEEPALIVE_IDLE, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_PROBES", LDAP_OPT_X_KEEPALIVE_PROBES, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_INTERVAL", LDAP_OPT_X_KEEPALIVE_INTERVAL, CONST_PERSISTENT | CONST_CS); #endif REGISTER_LONG_CONSTANT("LDAP_ESCAPE_FILTER", PHP_LDAP_ESCAPE_FILTER, CONST_PERSISTENT | CONST_CS); REGISTER_LONG_CONSTANT("LDAP_ESCAPE_DN", PHP_LDAP_ESCAPE_DN, CONST_PERSISTENT | CONST_CS); #ifdef HAVE_LDAP_EXTENDED_OPERATION_S REGISTER_STRING_CONSTANT("LDAP_EXOP_START_TLS", LDAP_EXOP_START_TLS, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_EXOP_MODIFY_PASSWD", LDAP_EXOP_MODIFY_PASSWD, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_EXOP_REFRESH", LDAP_EXOP_REFRESH, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_EXOP_WHO_AM_I", LDAP_EXOP_WHO_AM_I, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_EXOP_TURN", LDAP_EXOP_TURN, CONST_PERSISTENT | CONST_CS); #endif /* LDAP Controls */ /* standard track controls */ #ifdef LDAP_CONTROL_MANAGEDSAIT /* RFC 3296 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_MANAGEDSAIT", LDAP_CONTROL_MANAGEDSAIT, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_PROXY_AUTHZ /* RFC 4370 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_PROXY_AUTHZ", LDAP_CONTROL_PROXY_AUTHZ, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_SUBENTRIES /* RFC 3672 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_SUBENTRIES", LDAP_CONTROL_SUBENTRIES, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_VALUESRETURNFILTER /* RFC 3876 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_VALUESRETURNFILTER", LDAP_CONTROL_VALUESRETURNFILTER, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_ASSERT /* RFC 4528 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_ASSERT", LDAP_CONTROL_ASSERT, CONST_PERSISTENT | CONST_CS); /* RFC 4527 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_PRE_READ", LDAP_CONTROL_PRE_READ, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_POST_READ", LDAP_CONTROL_POST_READ, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_SORTREQUEST /* RFC 2891 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_SORTREQUEST", LDAP_CONTROL_SORTREQUEST, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_SORTRESPONSE", LDAP_CONTROL_SORTRESPONSE, CONST_PERSISTENT | CONST_CS); #endif /* non-standard track controls */ #ifdef LDAP_CONTROL_PAGEDRESULTS /* RFC 2696 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_PAGEDRESULTS", LDAP_CONTROL_PAGEDRESULTS, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_AUTHZID_REQUEST /* RFC 3829 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_AUTHZID_REQUEST", LDAP_CONTROL_AUTHZID_REQUEST, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_AUTHZID_RESPONSE", LDAP_CONTROL_AUTHZID_RESPONSE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_SYNC /* LDAP Content Synchronization Operation -- RFC 4533 */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC", LDAP_CONTROL_SYNC, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC_STATE", LDAP_CONTROL_SYNC_STATE, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC_DONE", LDAP_CONTROL_SYNC_DONE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_DONTUSECOPY /* LDAP Don't Use Copy Control (RFC 6171) */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_DONTUSECOPY", LDAP_CONTROL_DONTUSECOPY, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST /* Password policy Controls */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_PASSWORDPOLICYREQUEST", LDAP_CONTROL_PASSWORDPOLICYREQUEST, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_PASSWORDPOLICYRESPONSE", LDAP_CONTROL_PASSWORDPOLICYRESPONSE, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_X_INCREMENTAL_VALUES /* MS Active Directory controls */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_INCREMENTAL_VALUES", LDAP_CONTROL_X_INCREMENTAL_VALUES, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_DOMAIN_SCOPE", LDAP_CONTROL_X_DOMAIN_SCOPE, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_PERMISSIVE_MODIFY", LDAP_CONTROL_X_PERMISSIVE_MODIFY, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_SEARCH_OPTIONS", LDAP_CONTROL_X_SEARCH_OPTIONS, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_TREE_DELETE", LDAP_CONTROL_X_TREE_DELETE, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_EXTENDED_DN", LDAP_CONTROL_X_EXTENDED_DN, CONST_PERSISTENT | CONST_CS); #endif #ifdef LDAP_CONTROL_X_INCREMENTAL_VALUES /* LDAP VLV */ REGISTER_STRING_CONSTANT("LDAP_CONTROL_VLVREQUEST", LDAP_CONTROL_VLVREQUEST, CONST_PERSISTENT | CONST_CS); REGISTER_STRING_CONSTANT("LDAP_CONTROL_VLVRESPONSE", LDAP_CONTROL_VLVRESPONSE, CONST_PERSISTENT | CONST_CS); #endif le_link = zend_register_list_destructors_ex(_close_ldap_link, NULL, "ldap link", module_number); le_result = zend_register_list_destructors_ex(_free_ldap_result, NULL, "ldap result", module_number); le_result_entry = zend_register_list_destructors_ex(_free_ldap_result_entry, NULL, "ldap result entry", module_number); ldap_module_entry.type = type; return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(ldap) { UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(ldap) { char tmp[32]; #if HAVE_NSLDAP LDAPVersion ver; double SDKVersion; #endif php_info_print_table_start(); php_info_print_table_row(2, "LDAP Support", "enabled"); php_info_print_table_row(2, "RCS Version", "$Id: 0ba62d9bc989a5fb9065dd1a0945b968b8b0f080 $"); if (LDAPG(max_links) == -1) { snprintf(tmp, 31, ZEND_LONG_FMT "/unlimited", LDAPG(num_links)); } else { snprintf(tmp, 31, ZEND_LONG_FMT "/" ZEND_LONG_FMT, LDAPG(num_links), LDAPG(max_links)); } php_info_print_table_row(2, "Total Links", tmp); #ifdef LDAP_API_VERSION snprintf(tmp, 31, "%d", LDAP_API_VERSION); php_info_print_table_row(2, "API Version", tmp); #endif #ifdef LDAP_VENDOR_NAME php_info_print_table_row(2, "Vendor Name", LDAP_VENDOR_NAME); #endif #ifdef LDAP_VENDOR_VERSION snprintf(tmp, 31, "%d", LDAP_VENDOR_VERSION); php_info_print_table_row(2, "Vendor Version", tmp); #endif #if HAVE_NSLDAP SDKVersion = ldap_version(&ver); snprintf(tmp, 31, "%F", SDKVersion/100.0); php_info_print_table_row(2, "SDK Version", tmp); snprintf(tmp, 31, "%F", ver.protocol_version/100.0); php_info_print_table_row(2, "Highest LDAP Protocol Supported", tmp); snprintf(tmp, 31, "%F", ver.SSL_version/100.0); php_info_print_table_row(2, "SSL Level Supported", tmp); if (ver.security_level != LDAP_SECURITY_NONE) { snprintf(tmp, 31, "%d", ver.security_level); } else { strcpy(tmp, "SSL not enabled"); } php_info_print_table_row(2, "Level of Encryption", tmp); #endif #ifdef HAVE_LDAP_SASL php_info_print_table_row(2, "SASL Support", "Enabled"); #endif php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ proto resource ldap_connect([string host [, int port [, string wallet [, string wallet_passwd [, int authmode]]]]]) Connect to an LDAP server */ PHP_FUNCTION(ldap_connect) { char *host = NULL; size_t hostlen = 0; zend_long port = LDAP_PORT; #ifdef HAVE_ORALDAP char *wallet = NULL, *walletpasswd = NULL; size_t walletlen = 0, walletpasswdlen = 0; zend_long authmode = GSLC_SSL_NO_AUTH; int ssl=0; #endif ldap_linkdata *ld; LDAP *ldap = NULL; #ifdef HAVE_ORALDAP if (ZEND_NUM_ARGS() == 3 || ZEND_NUM_ARGS() == 4) { WRONG_PARAM_COUNT; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "|slssl", &host, &hostlen, &port, &wallet, &walletlen, &walletpasswd, &walletpasswdlen, &authmode) != SUCCESS) { RETURN_FALSE; } if (ZEND_NUM_ARGS() == 5) { ssl = 1; } #else if (zend_parse_parameters(ZEND_NUM_ARGS(), "|sl", &host, &hostlen, &port) != SUCCESS) { RETURN_FALSE; } #endif if (LDAPG(max_links) != -1 && LDAPG(num_links) >= LDAPG(max_links)) { php_error_docref(NULL, E_WARNING, "Too many open links (" ZEND_LONG_FMT ")", LDAPG(num_links)); RETURN_FALSE; } ld = ecalloc(1, sizeof(ldap_linkdata)); { int rc = LDAP_SUCCESS; char *url = host; if (url && !ldap_is_ldap_url(url)) { int urllen = hostlen + sizeof( "ldap://:65535" ); if (port <= 0 || port > 65535) { efree(ld); php_error_docref(NULL, E_WARNING, "invalid port number: " ZEND_LONG_FMT, port); RETURN_FALSE; } url = emalloc(urllen); snprintf( url, urllen, "ldap://%s:" ZEND_LONG_FMT, host, port ); } #ifdef LDAP_API_FEATURE_X_OPENLDAP /* ldap_init() is deprecated, use ldap_initialize() instead. */ rc = ldap_initialize(&ldap, url); #else /* ! LDAP_API_FEATURE_X_OPENLDAP */ /* ldap_init does not support URLs. * We must try the original host and port information. */ ldap = ldap_init(host, port); if (ldap == NULL) { efree(ld); php_error_docref(NULL, E_WARNING, "Could not create session handle"); RETURN_FALSE; } #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */ if (url != host) { efree(url); } if (rc != LDAP_SUCCESS) { efree(ld); php_error_docref(NULL, E_WARNING, "Could not create session handle: %s", ldap_err2string(rc)); RETURN_FALSE; } } if (ldap == NULL) { efree(ld); RETURN_FALSE; } else { #ifdef HAVE_ORALDAP if (ssl) { if (ldap_init_SSL(&ldap->ld_sb, wallet, walletpasswd, authmode)) { efree(ld); php_error_docref(NULL, E_WARNING, "SSL init failed"); RETURN_FALSE; } } #endif LDAPG(num_links)++; ld->link = ldap; RETURN_RES(zend_register_resource(ld, le_link)); } } /* }}} */ /* {{{ _get_lderrno */ static int _get_lderrno(LDAP *ldap) { #if !HAVE_NSLDAP #if LDAP_API_VERSION > 2000 || HAVE_ORALDAP int lderr; /* New versions of OpenLDAP do it this way */ ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr); return lderr; #else return ldap->ld_errno; #endif #else return ldap_get_lderrno(ldap, NULL, NULL); #endif } /* }}} */ /* {{{ _set_lderrno */ static void _set_lderrno(LDAP *ldap, int lderr) { #if !HAVE_NSLDAP #if LDAP_API_VERSION > 2000 || HAVE_ORALDAP /* New versions of OpenLDAP do it this way */ ldap_set_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr); #else ldap->ld_errno = lderr; #endif #else ldap_set_lderrno(ldap, lderr, NULL, NULL); #endif } /* }}} */ /* {{{ proto bool ldap_bind(resource link [, string dn [, string password]]) Bind to LDAP directory */ PHP_FUNCTION(ldap_bind) { zval *link; char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL; size_t ldap_bind_dnlen, ldap_bind_pwlen; ldap_linkdata *ld; int rc; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|ss", &link, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen) != SUCCESS) { RETURN_FALSE; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) { _set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS); php_error_docref(NULL, E_WARNING, "DN contains a null byte"); RETURN_FALSE; } if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) { _set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS); php_error_docref(NULL, E_WARNING, "Password contains a null byte"); RETURN_FALSE; } { #ifdef LDAP_API_FEATURE_X_OPENLDAP /* ldap_simple_bind_s() is deprecated, use ldap_sasl_bind_s() instead. */ struct berval cred; cred.bv_val = ldap_bind_pw; cred.bv_len = ldap_bind_pw ? ldap_bind_pwlen : 0; rc = ldap_sasl_bind_s(ld->link, ldap_bind_dn, LDAP_SASL_SIMPLE, &cred, NULL, NULL, /* no controls right now */ NULL); /* we don't care about the server's credentials */ #else /* ! LDAP_API_FEATURE_X_OPENLDAP */ rc = ldap_simple_bind_s(ld->link, ldap_bind_dn, ldap_bind_pw); #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */ } if ( rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc)); RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ #ifdef HAVE_LDAP_SASL typedef struct { char *mech; char *realm; char *authcid; char *passwd; char *authzid; } php_ldap_bictx; /* {{{ _php_sasl_setdefs */ static php_ldap_bictx *_php_sasl_setdefs(LDAP *ld, char *sasl_mech, char *sasl_realm, char *sasl_authc_id, char *passwd, char *sasl_authz_id) { php_ldap_bictx *ctx; ctx = ber_memalloc(sizeof(php_ldap_bictx)); ctx->mech = (sasl_mech) ? ber_strdup(sasl_mech) : NULL; ctx->realm = (sasl_realm) ? ber_strdup(sasl_realm) : NULL; ctx->authcid = (sasl_authc_id) ? ber_strdup(sasl_authc_id) : NULL; ctx->passwd = (passwd) ? ber_strdup(passwd) : NULL; ctx->authzid = (sasl_authz_id) ? ber_strdup(sasl_authz_id) : NULL; if (ctx->mech == NULL) { ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &ctx->mech); } if (ctx->realm == NULL) { ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &ctx->realm); } if (ctx->authcid == NULL) { ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &ctx->authcid); } if (ctx->authzid == NULL) { ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &ctx->authzid); } return ctx; } /* }}} */ /* {{{ _php_sasl_freedefs */ static void _php_sasl_freedefs(php_ldap_bictx *ctx) { if (ctx->mech) ber_memfree(ctx->mech); if (ctx->realm) ber_memfree(ctx->realm); if (ctx->authcid) ber_memfree(ctx->authcid); if (ctx->passwd) ber_memfree(ctx->passwd); if (ctx->authzid) ber_memfree(ctx->authzid); ber_memfree(ctx); } /* }}} */ /* {{{ _php_sasl_interact Internal interact function for SASL */ static int _php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in) { sasl_interact_t *interact = in; const char *p; php_ldap_bictx *ctx = defaults; for (;interact->id != SASL_CB_LIST_END;interact++) { p = NULL; switch(interact->id) { case SASL_CB_GETREALM: p = ctx->realm; break; case SASL_CB_AUTHNAME: p = ctx->authcid; break; case SASL_CB_USER: p = ctx->authzid; break; case SASL_CB_PASS: p = ctx->passwd; break; } if (p) { interact->result = p; interact->len = strlen(interact->result); } } return LDAP_SUCCESS; } /* }}} */ /* {{{ proto bool ldap_sasl_bind(resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authc_id [, string sasl_authz_id [, string props]]]]]]]) Bind to LDAP directory using SASL */ PHP_FUNCTION(ldap_sasl_bind) { zval *link; ldap_linkdata *ld; char *binddn = NULL; char *passwd = NULL; char *sasl_mech = NULL; char *sasl_realm = NULL; char *sasl_authz_id = NULL; char *sasl_authc_id = NULL; char *props = NULL; size_t rc, dn_len, passwd_len, mech_len, realm_len, authc_id_len, authz_id_len, props_len; php_ldap_bictx *ctx; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|sssssss", &link, &binddn, &dn_len, &passwd, &passwd_len, &sasl_mech, &mech_len, &sasl_realm, &realm_len, &sasl_authc_id, &authc_id_len, &sasl_authz_id, &authz_id_len, &props, &props_len) != SUCCESS) { RETURN_FALSE; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } ctx = _php_sasl_setdefs(ld->link, sasl_mech, sasl_realm, sasl_authc_id, passwd, sasl_authz_id); if (props) { ldap_set_option(ld->link, LDAP_OPT_X_SASL_SECPROPS, props); } rc = ldap_sasl_interactive_bind_s(ld->link, binddn, ctx->mech, NULL, NULL, LDAP_SASL_QUIET, _php_sasl_interact, ctx); if (rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc)); RETVAL_FALSE; } else { RETVAL_TRUE; } _php_sasl_freedefs(ctx); } /* }}} */ #endif /* HAVE_LDAP_SASL */ /* {{{ proto bool ldap_unbind(resource link) Unbind from LDAP directory */ PHP_FUNCTION(ldap_unbind) { zval *link; ldap_linkdata *ld; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) { RETURN_FALSE; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(link)); RETURN_TRUE; } /* }}} */ /* {{{ php_set_opts */ static void php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref) { /* sizelimit */ if (sizelimit > -1) { #if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_sizelimit); ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit); #else *old_sizelimit = ldap->ld_sizelimit; ldap->ld_sizelimit = sizelimit; #endif } /* timelimit */ if (timelimit > -1) { #if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP ldap_get_option(ldap, LDAP_OPT_TIMELIMIT, old_timelimit); ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &timelimit); #else *old_timelimit = ldap->ld_timelimit; ldap->ld_timelimit = timelimit; #endif } /* deref */ if (deref > -1) { #if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP ldap_get_option(ldap, LDAP_OPT_DEREF, old_deref); ldap_set_option(ldap, LDAP_OPT_DEREF, &deref); #else *old_deref = ldap->ld_deref; ldap->ld_deref = deref; #endif } } /* }}} */ /* {{{ php_ldap_do_search */ static void php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope) { zval *link, *base_dn, *filter, *attrs = NULL, *attr; zend_long attrsonly, sizelimit, timelimit, deref; char *ldap_base_dn = NULL, *ldap_filter = NULL, **ldap_attrs = NULL; ldap_linkdata *ld = NULL; LDAPMessage *ldap_res; int ldap_attrsonly = 0, ldap_sizelimit = -1, ldap_timelimit = -1, ldap_deref = -1; int old_ldap_sizelimit = -1, old_ldap_timelimit = -1, old_ldap_deref = -1; int num_attribs = 0, ret = 1, i, errno, argcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(argcount, "zzz|allll", &link, &base_dn, &filter, &attrs, &attrsonly, &sizelimit, &timelimit, &deref) == FAILURE) { return; } /* Reverse -> fall through */ switch (argcount) { case 8: ldap_deref = deref; case 7: ldap_timelimit = timelimit; case 6: ldap_sizelimit = sizelimit; case 5: ldap_attrsonly = attrsonly; case 4: num_attribs = zend_hash_num_elements(Z_ARRVAL_P(attrs)); ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0); for (i = 0; i<num_attribs; i++) { if ((attr = zend_hash_index_find(Z_ARRVAL_P(attrs), i)) == NULL) { php_error_docref(NULL, E_WARNING, "Array initialization wrong"); ret = 0; goto cleanup; } convert_to_string_ex(attr); ldap_attrs[i] = Z_STRVAL_P(attr); } ldap_attrs[num_attribs] = NULL; default: break; } /* parallel search? */ if (Z_TYPE_P(link) == IS_ARRAY) { int i, nlinks, nbases, nfilters, *rcs; ldap_linkdata **lds; zval *entry, resource; nlinks = zend_hash_num_elements(Z_ARRVAL_P(link)); if (nlinks == 0) { php_error_docref(NULL, E_WARNING, "No links in link array"); ret = 0; goto cleanup; } if (Z_TYPE_P(base_dn) == IS_ARRAY) { nbases = zend_hash_num_elements(Z_ARRVAL_P(base_dn)); if (nbases != nlinks) { php_error_docref(NULL, E_WARNING, "Base must either be a string, or an array with the same number of elements as the links array"); ret = 0; goto cleanup; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(base_dn)); } else { nbases = 0; /* this means string, not array */ /* If anything else than string is passed, ldap_base_dn = NULL */ if (Z_TYPE_P(base_dn) == IS_STRING) { ldap_base_dn = Z_STRVAL_P(base_dn); } else { ldap_base_dn = NULL; } } if (Z_TYPE_P(filter) == IS_ARRAY) { nfilters = zend_hash_num_elements(Z_ARRVAL_P(filter)); if (nfilters != nlinks) { php_error_docref(NULL, E_WARNING, "Filter must either be a string, or an array with the same number of elements as the links array"); ret = 0; goto cleanup; } zend_hash_internal_pointer_reset(Z_ARRVAL_P(filter)); } else { nfilters = 0; /* this means string, not array */ convert_to_string_ex(filter); ldap_filter = Z_STRVAL_P(filter); } lds = safe_emalloc(nlinks, sizeof(ldap_linkdata), 0); rcs = safe_emalloc(nlinks, sizeof(*rcs), 0); zend_hash_internal_pointer_reset(Z_ARRVAL_P(link)); for (i=0; i<nlinks; i++) { entry = zend_hash_get_current_data(Z_ARRVAL_P(link)); ld = (ldap_linkdata *) zend_fetch_resource_ex(entry, "ldap link", le_link); if (ld == NULL) { ret = 0; goto cleanup_parallel; } if (nbases != 0) { /* base_dn an array? */ entry = zend_hash_get_current_data(Z_ARRVAL_P(base_dn)); zend_hash_move_forward(Z_ARRVAL_P(base_dn)); /* If anything else than string is passed, ldap_base_dn = NULL */ if (Z_TYPE_P(entry) == IS_STRING) { ldap_base_dn = Z_STRVAL_P(entry); } else { ldap_base_dn = NULL; } } if (nfilters != 0) { /* filter an array? */ entry = zend_hash_get_current_data(Z_ARRVAL_P(filter)); zend_hash_move_forward(Z_ARRVAL_P(filter)); convert_to_string_ex(entry); ldap_filter = Z_STRVAL_P(entry); } php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref); /* Run the actual search */ ldap_search_ext(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly, NULL, NULL, NULL, ldap_sizelimit, &rcs[i]); lds[i] = ld; zend_hash_move_forward(Z_ARRVAL_P(link)); } array_init(return_value); /* Collect results from the searches */ for (i=0; i<nlinks; i++) { if (rcs[i] != -1) { rcs[i] = ldap_result(lds[i]->link, LDAP_RES_ANY, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res); } if (rcs[i] != -1) { ZVAL_RES(&resource, zend_register_resource(ldap_res, le_result)); add_next_index_zval(return_value, &resource); } else { add_next_index_bool(return_value, 0); } } cleanup_parallel: efree(lds); efree(rcs); } else { convert_to_string_ex(filter); ldap_filter = Z_STRVAL_P(filter); /* If anything else than string is passed, ldap_base_dn = NULL */ if (Z_TYPE_P(base_dn) == IS_STRING) { ldap_base_dn = Z_STRVAL_P(base_dn); } ld = (ldap_linkdata *) zend_fetch_resource_ex(link, "ldap link", le_link); if (ld == NULL) { ret = 0; goto cleanup; } php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref); /* Run the actual search */ errno = ldap_search_ext_s(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly, NULL, NULL, NULL, ldap_sizelimit, &ldap_res); if (errno != LDAP_SUCCESS && errno != LDAP_SIZELIMIT_EXCEEDED #ifdef LDAP_ADMINLIMIT_EXCEEDED && errno != LDAP_ADMINLIMIT_EXCEEDED #endif #ifdef LDAP_REFERRAL && errno != LDAP_REFERRAL #endif ) { php_error_docref(NULL, E_WARNING, "Search: %s", ldap_err2string(errno)); ret = 0; } else { if (errno == LDAP_SIZELIMIT_EXCEEDED) { php_error_docref(NULL, E_WARNING, "Partial search results returned: Sizelimit exceeded"); } #ifdef LDAP_ADMINLIMIT_EXCEEDED else if (errno == LDAP_ADMINLIMIT_EXCEEDED) { php_error_docref(NULL, E_WARNING, "Partial search results returned: Adminlimit exceeded"); } #endif RETVAL_RES(zend_register_resource(ldap_res, le_result)); } } cleanup: if (ld) { /* Restoring previous options */ php_set_opts(ld->link, old_ldap_sizelimit, old_ldap_timelimit, old_ldap_deref, &ldap_sizelimit, &ldap_timelimit, &ldap_deref); } if (ldap_attrs != NULL) { efree(ldap_attrs); } if (!ret) { RETVAL_BOOL(ret); } } /* }}} */ /* {{{ proto resource ldap_read(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]]) Read an entry */ PHP_FUNCTION(ldap_read) { php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_BASE); } /* }}} */ /* {{{ proto resource ldap_list(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]]) Single-level search */ PHP_FUNCTION(ldap_list) { php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_ONELEVEL); } /* }}} */ /* {{{ proto resource ldap_search(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]]) Search LDAP tree under base_dn */ PHP_FUNCTION(ldap_search) { php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_SUBTREE); } /* }}} */ /* {{{ proto bool ldap_free_result(resource result) Free result memory */ PHP_FUNCTION(ldap_free_result) { zval *result; LDAPMessage *ldap_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) != SUCCESS) { return; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(result)); /* Delete list entry */ RETVAL_TRUE; } /* }}} */ /* {{{ proto int ldap_count_entries(resource link, resource result) Count the number of entries in a search result */ PHP_FUNCTION(ldap_count_entries) { zval *link, *result; ldap_linkdata *ld; LDAPMessage *ldap_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } RETURN_LONG(ldap_count_entries(ld->link, ldap_result)); } /* }}} */ /* {{{ proto resource ldap_first_entry(resource link, resource result) Return first result id */ PHP_FUNCTION(ldap_first_entry) { zval *link, *result; ldap_linkdata *ld; ldap_resultentry *resultentry; LDAPMessage *ldap_result, *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } if ((entry = ldap_first_entry(ld->link, ldap_result)) == NULL) { RETVAL_FALSE; } else { resultentry = emalloc(sizeof(ldap_resultentry)); RETVAL_RES(zend_register_resource(resultentry, le_result_entry)); ZVAL_COPY(&resultentry->res, result); resultentry->data = entry; resultentry->ber = NULL; } } /* }}} */ /* {{{ proto resource ldap_next_entry(resource link, resource result_entry) Get next result entry */ PHP_FUNCTION(ldap_next_entry) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry, *resultentry_next; LDAPMessage *entry_next; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if ((entry_next = ldap_next_entry(ld->link, resultentry->data)) == NULL) { RETVAL_FALSE; } else { resultentry_next = emalloc(sizeof(ldap_resultentry)); RETVAL_RES(zend_register_resource(resultentry_next, le_result_entry)); ZVAL_COPY(&resultentry_next->res, &resultentry->res); resultentry_next->data = entry_next; resultentry_next->ber = NULL; } } /* }}} */ /* {{{ proto array ldap_get_entries(resource link, resource result) Get all result entries */ PHP_FUNCTION(ldap_get_entries) { zval *link, *result; LDAPMessage *ldap_result, *ldap_result_entry; zval tmp1, tmp2; ldap_linkdata *ld; LDAP *ldap; int num_entries, num_attrib, num_values, i; BerElement *ber; char *attribute; size_t attr_len; struct berval **ldap_value; char *dn; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } ldap = ld->link; num_entries = ldap_count_entries(ldap, ldap_result); array_init(return_value); add_assoc_long(return_value, "count", num_entries); if (num_entries == 0) { return; } ldap_result_entry = ldap_first_entry(ldap, ldap_result); if (ldap_result_entry == NULL) { zval_dtor(return_value); RETURN_FALSE; } num_entries = 0; while (ldap_result_entry != NULL) { array_init(&tmp1); num_attrib = 0; attribute = ldap_first_attribute(ldap, ldap_result_entry, &ber); while (attribute != NULL) { ldap_value = ldap_get_values_len(ldap, ldap_result_entry, attribute); num_values = ldap_count_values_len(ldap_value); array_init(&tmp2); add_assoc_long(&tmp2, "count", num_values); for (i = 0; i < num_values; i++) { add_index_stringl(&tmp2, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len); } ldap_value_free_len(ldap_value); attr_len = strlen(attribute); zend_hash_str_update(Z_ARRVAL(tmp1), php_strtolower(attribute, attr_len), attr_len, &tmp2); add_index_string(&tmp1, num_attrib, attribute); num_attrib++; #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(attribute); #endif attribute = ldap_next_attribute(ldap, ldap_result_entry, ber); } #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS if (ber != NULL) { ber_free(ber, 0); } #endif add_assoc_long(&tmp1, "count", num_attrib); dn = ldap_get_dn(ldap, ldap_result_entry); add_assoc_string(&tmp1, "dn", dn); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(dn); #else free(dn); #endif zend_hash_index_update(Z_ARRVAL_P(return_value), num_entries, &tmp1); num_entries++; ldap_result_entry = ldap_next_entry(ldap, ldap_result_entry); } add_assoc_long(return_value, "count", num_entries); } /* }}} */ /* {{{ proto string ldap_first_attribute(resource link, resource result_entry) Return first attribute */ PHP_FUNCTION(ldap_first_attribute) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry; char *attribute; zend_long dummy_ber; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if ((attribute = ldap_first_attribute(ld->link, resultentry->data, &resultentry->ber)) == NULL) { RETURN_FALSE; } else { RETVAL_STRING(attribute); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(attribute); #endif } } /* }}} */ /* {{{ proto string ldap_next_attribute(resource link, resource result_entry) Get the next attribute in result */ PHP_FUNCTION(ldap_next_attribute) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry; char *attribute; zend_long dummy_ber; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if (resultentry->ber == NULL) { php_error_docref(NULL, E_WARNING, "called before calling ldap_first_attribute() or no attributes found in result entry"); RETURN_FALSE; } if ((attribute = ldap_next_attribute(ld->link, resultentry->data, resultentry->ber)) == NULL) { #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS if (resultentry->ber != NULL) { ber_free(resultentry->ber, 0); resultentry->ber = NULL; } #endif RETURN_FALSE; } else { RETVAL_STRING(attribute); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(attribute); #endif } } /* }}} */ /* {{{ proto array ldap_get_attributes(resource link, resource result_entry) Get attributes from a search result entry */ PHP_FUNCTION(ldap_get_attributes) { zval *link, *result_entry; zval tmp; ldap_linkdata *ld; ldap_resultentry *resultentry; char *attribute; struct berval **ldap_value; int i, num_values, num_attrib; BerElement *ber; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } array_init(return_value); num_attrib = 0; attribute = ldap_first_attribute(ld->link, resultentry->data, &ber); while (attribute != NULL) { ldap_value = ldap_get_values_len(ld->link, resultentry->data, attribute); num_values = ldap_count_values_len(ldap_value); array_init(&tmp); add_assoc_long(&tmp, "count", num_values); for (i = 0; i < num_values; i++) { add_index_stringl(&tmp, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len); } ldap_value_free_len(ldap_value); zend_hash_str_update(Z_ARRVAL_P(return_value), attribute, strlen(attribute), &tmp); add_index_string(return_value, num_attrib, attribute); num_attrib++; #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(attribute); #endif attribute = ldap_next_attribute(ld->link, resultentry->data, ber); } #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS if (ber != NULL) { ber_free(ber, 0); } #endif add_assoc_long(return_value, "count", num_attrib); } /* }}} */ /* {{{ proto array ldap_get_values_len(resource link, resource result_entry, string attribute) Get all values with lengths from a result entry */ PHP_FUNCTION(ldap_get_values_len) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry; char *attr; struct berval **ldap_value_len; int i, num_values; size_t attr_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result_entry, &attr, &attr_len) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if ((ldap_value_len = ldap_get_values_len(ld->link, resultentry->data, attr)) == NULL) { php_error_docref(NULL, E_WARNING, "Cannot get the value(s) of attribute %s", ldap_err2string(_get_lderrno(ld->link))); RETURN_FALSE; } num_values = ldap_count_values_len(ldap_value_len); array_init(return_value); for (i=0; i<num_values; i++) { add_next_index_stringl(return_value, ldap_value_len[i]->bv_val, ldap_value_len[i]->bv_len); } add_assoc_long(return_value, "count", num_values); ldap_value_free_len(ldap_value_len); } /* }}} */ /* {{{ proto string ldap_get_dn(resource link, resource result_entry) Get the DN of a result entry */ PHP_FUNCTION(ldap_get_dn) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry; char *text; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } text = ldap_get_dn(ld->link, resultentry->data); if (text != NULL) { RETVAL_STRING(text); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(text); #else free(text); #endif } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto array ldap_explode_dn(string dn, int with_attrib) Splits DN into its component parts */ PHP_FUNCTION(ldap_explode_dn) { zend_long with_attrib; char *dn, **ldap_value; int i, count; size_t dn_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &dn, &dn_len, &with_attrib) != SUCCESS) { return; } if (!(ldap_value = ldap_explode_dn(dn, with_attrib))) { /* Invalid parameters were passed to ldap_explode_dn */ RETURN_FALSE; } i=0; while (ldap_value[i] != NULL) i++; count = i; array_init(return_value); add_assoc_long(return_value, "count", count); for (i = 0; i<count; i++) { add_index_string(return_value, i, ldap_value[i]); } ldap_memvfree((void **)ldap_value); } /* }}} */ /* {{{ proto string ldap_dn2ufn(string dn) Convert DN to User Friendly Naming format */ PHP_FUNCTION(ldap_dn2ufn) { char *dn, *ufn; size_t dn_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dn, &dn_len) != SUCCESS) { return; } ufn = ldap_dn2ufn(dn); if (ufn != NULL) { RETVAL_STRING(ufn); #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS ldap_memfree(ufn); #endif } else { RETURN_FALSE; } } /* }}} */ /* added to fix use of ldap_modify_add for doing an ldap_add, gerrit thomson. */ #define PHP_LD_FULL_ADD 0xff /* {{{ php_ldap_do_modify */ static void php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper) { zval *link, *entry, *value, *ivalue; ldap_linkdata *ld; char *dn; LDAPMod **ldap_mods; int i, j, num_attribs, num_values; size_t dn_len; int *num_berval; zend_string *attribute; zend_ulong index; int is_full_add=0; /* flag for full add operation so ldap_mod_add can be put back into oper, gerrit THomson */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa/", &link, &dn, &dn_len, &entry) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } num_attribs = zend_hash_num_elements(Z_ARRVAL_P(entry)); ldap_mods = safe_emalloc((num_attribs+1), sizeof(LDAPMod *), 0); num_berval = safe_emalloc(num_attribs, sizeof(int), 0); zend_hash_internal_pointer_reset(Z_ARRVAL_P(entry)); /* added by gerrit thomson to fix ldap_add using ldap_mod_add */ if (oper == PHP_LD_FULL_ADD) { oper = LDAP_MOD_ADD; is_full_add = 1; } /* end additional , gerrit thomson */ for (i = 0; i < num_attribs; i++) { ldap_mods[i] = emalloc(sizeof(LDAPMod)); ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES; ldap_mods[i]->mod_type = NULL; if (zend_hash_get_current_key(Z_ARRVAL_P(entry), &attribute, &index) == HASH_KEY_IS_STRING) { ldap_mods[i]->mod_type = estrndup(ZSTR_VAL(attribute), ZSTR_LEN(attribute)); } else { php_error_docref(NULL, E_WARNING, "Unknown attribute in the data"); /* Free allocated memory */ while (i >= 0) { if (ldap_mods[i]->mod_type) { efree(ldap_mods[i]->mod_type); } efree(ldap_mods[i]); i--; } efree(num_berval); efree(ldap_mods); RETURN_FALSE; } value = zend_hash_get_current_data(Z_ARRVAL_P(entry)); ZVAL_DEREF(value); if (Z_TYPE_P(value) != IS_ARRAY) { num_values = 1; } else { SEPARATE_ARRAY(value); num_values = zend_hash_num_elements(Z_ARRVAL_P(value)); } num_berval[i] = num_values; ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0); /* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */ if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) { convert_to_string_ex(value); ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval)); ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value); ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value); } else { for (j = 0; j < num_values; j++) { if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) { php_error_docref(NULL, E_WARNING, "Value array must have consecutive indices 0, 1, ..."); num_berval[i] = j; num_attribs = i + 1; RETVAL_FALSE; goto errexit; } convert_to_string_ex(ivalue); ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval)); ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue); ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue); } } ldap_mods[i]->mod_bvalues[num_values] = NULL; zend_hash_move_forward(Z_ARRVAL_P(entry)); } ldap_mods[num_attribs] = NULL; /* check flag to see if do_mod was called to perform full add , gerrit thomson */ if (is_full_add == 1) { if ((i = ldap_add_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Add: %s", ldap_err2string(i)); RETVAL_FALSE; } else RETVAL_TRUE; } else { if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Modify: %s", ldap_err2string(i)); RETVAL_FALSE; } else RETVAL_TRUE; } errexit: for (i = 0; i < num_attribs; i++) { efree(ldap_mods[i]->mod_type); for (j = 0; j < num_berval[i]; j++) { efree(ldap_mods[i]->mod_bvalues[j]); } efree(ldap_mods[i]->mod_bvalues); efree(ldap_mods[i]); } efree(num_berval); efree(ldap_mods); return; } /* }}} */ /* {{{ proto bool ldap_add(resource link, string dn, array entry) Add entries to LDAP directory */ PHP_FUNCTION(ldap_add) { /* use a newly define parameter into the do_modify so ldap_mod_add can be used the way it is supposed to be used , Gerrit THomson */ php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD); } /* }}} */ /* three functions for attribute base modifications, gerrit Thomson */ /* {{{ proto bool ldap_mod_replace(resource link, string dn, array entry) Replace attribute values with new ones */ PHP_FUNCTION(ldap_mod_replace) { php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE); } /* }}} */ /* {{{ proto bool ldap_mod_add(resource link, string dn, array entry) Add attribute values to current */ PHP_FUNCTION(ldap_mod_add) { php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD); } /* }}} */ /* {{{ proto bool ldap_mod_del(resource link, string dn, array entry) Delete attribute values */ PHP_FUNCTION(ldap_mod_del) { php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE); } /* }}} */ /* {{{ proto bool ldap_delete(resource link, string dn) Delete an entry from a directory */ PHP_FUNCTION(ldap_delete) { zval *link; ldap_linkdata *ld; char *dn; int rc; size_t dn_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &link, &dn, &dn_len) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((rc = ldap_delete_ext_s(ld->link, dn, NULL, NULL)) != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Delete: %s", ldap_err2string(rc)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ _ldap_str_equal_to_const */ static int _ldap_str_equal_to_const(const char *str, uint32_t str_len, const char *cstr) { uint32_t i; if (strlen(cstr) != str_len) return 0; for (i = 0; i < str_len; ++i) { if (str[i] != cstr[i]) { return 0; } } return 1; } /* }}} */ /* {{{ _ldap_strlen_max */ static int _ldap_strlen_max(const char *str, uint32_t max_len) { uint32_t i; for (i = 0; i < max_len; ++i) { if (str[i] == '\0') { return i; } } return max_len; } /* }}} */ /* {{{ _ldap_hash_fetch */ static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out) { *out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key)); } /* }}} */ /* {{{ proto bool ldap_modify_batch(resource link, string dn, array modifs) Perform multiple modifications as part of one operation */ PHP_FUNCTION(ldap_modify_batch) { ldap_linkdata *ld; zval *link, *mods, *mod, *modinfo, *modval; zval *attrib, *modtype, *vals; zval *fetched; char *dn; size_t dn_len; int i, j, k; int num_mods, num_modprops, num_modvals; LDAPMod **ldap_mods; uint32_t oper; /* $mods = array( array( "attrib" => "unicodePwd", "modtype" => LDAP_MODIFY_BATCH_REMOVE, "values" => array($oldpw) ), array( "attrib" => "unicodePwd", "modtype" => LDAP_MODIFY_BATCH_ADD, "values" => array($newpw) ), array( "attrib" => "userPrincipalName", "modtype" => LDAP_MODIFY_BATCH_REPLACE, "values" => array("[email protected]") ), array( "attrib" => "userCert", "modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL ) ); */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa/", &link, &dn, &dn_len, &mods) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } /* perform validation */ { zend_string *modkey; zend_long modtype; /* to store the wrongly-typed keys */ zend_ulong tmpUlong; /* make sure the DN contains no NUL bytes */ if ((size_t)_ldap_strlen_max(dn, dn_len) != dn_len) { php_error_docref(NULL, E_WARNING, "DN must not contain NUL bytes"); RETURN_FALSE; } /* make sure the top level is a normal array */ zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods)); if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) { php_error_docref(NULL, E_WARNING, "Modifications array must not be string-indexed"); RETURN_FALSE; } num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods)); for (i = 0; i < num_mods; i++) { /* is the numbering consecutive? */ if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) { php_error_docref(NULL, E_WARNING, "Modifications array must have consecutive indices 0, 1, ..."); RETURN_FALSE; } mod = fetched; /* is it an array? */ if (Z_TYPE_P(mod) != IS_ARRAY) { php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be an array itself"); RETURN_FALSE; } SEPARATE_ARRAY(mod); /* for the modification hashtable... */ zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod)); num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod)); for (j = 0; j < num_modprops; j++) { /* are the keys strings? */ if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong) != HASH_KEY_IS_STRING) { php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be string-indexed"); RETURN_FALSE; } /* is this a valid entry? */ if ( !_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB) && !_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE) && !_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES) ) { php_error_docref(NULL, E_WARNING, "The only allowed keys in entries of the modifications array are '" LDAP_MODIFY_BATCH_ATTRIB "', '" LDAP_MODIFY_BATCH_MODTYPE "' and '" LDAP_MODIFY_BATCH_VALUES "'"); RETURN_FALSE; } fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod)); modinfo = fetched; /* does the value type match the key? */ if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB)) { if (Z_TYPE_P(modinfo) != IS_STRING) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must be a string"); RETURN_FALSE; } if (Z_STRLEN_P(modinfo) != (size_t)_ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must not contain NUL bytes"); RETURN_FALSE; } } else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE)) { if (Z_TYPE_P(modinfo) != IS_LONG) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_MODTYPE "' value must be a long"); RETURN_FALSE; } /* is the value in range? */ modtype = Z_LVAL_P(modinfo); if ( modtype != LDAP_MODIFY_BATCH_ADD && modtype != LDAP_MODIFY_BATCH_REMOVE && modtype != LDAP_MODIFY_BATCH_REPLACE && modtype != LDAP_MODIFY_BATCH_REMOVE_ALL ) { php_error_docref(NULL, E_WARNING, "The '" LDAP_MODIFY_BATCH_MODTYPE "' value must match one of the LDAP_MODIFY_BATCH_* constants"); RETURN_FALSE; } /* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */ if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) { if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) { php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must not be provided"); RETURN_FALSE; } } else { if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) { php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is not LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must be provided"); RETURN_FALSE; } } } else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)) { if (Z_TYPE_P(modinfo) != IS_ARRAY) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' value must be an array"); RETURN_FALSE; } SEPARATE_ARRAY(modinfo); /* is the array not empty? */ zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo)); num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo)); if (num_modvals == 0) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have at least one element"); RETURN_FALSE; } /* are its keys integers? */ if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must not be string-indexed"); RETURN_FALSE; } /* are the keys consecutive? */ for (k = 0; k < num_modvals; k++) { if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) { php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have consecutive indices 0, 1, ..."); RETURN_FALSE; } modval = fetched; /* is the data element a string? */ if (Z_TYPE_P(modval) != IS_STRING) { php_error_docref(NULL, E_WARNING, "Each element of a '" LDAP_MODIFY_BATCH_VALUES "' array must be a string"); RETURN_FALSE; } } } zend_hash_move_forward(Z_ARRVAL_P(mod)); } } } /* validation was successful */ /* allocate array of modifications */ ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0); /* for each modification */ for (i = 0; i < num_mods; i++) { /* allocate the modification struct */ ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0); /* fetch the relevant data */ fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i); mod = fetched; _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib); _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype); _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals); /* map the modification type */ switch (Z_LVAL_P(modtype)) { case LDAP_MODIFY_BATCH_ADD: oper = LDAP_MOD_ADD; break; case LDAP_MODIFY_BATCH_REMOVE: case LDAP_MODIFY_BATCH_REMOVE_ALL: oper = LDAP_MOD_DELETE; break; case LDAP_MODIFY_BATCH_REPLACE: oper = LDAP_MOD_REPLACE; break; default: zend_throw_error(NULL, "Unknown and uncaught modification type."); RETVAL_FALSE; efree(ldap_mods[i]); num_mods = i; goto cleanup; } /* fill in the basic info */ ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES; ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib)); if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) { /* no values */ ldap_mods[i]->mod_bvalues = NULL; } else { /* allocate space for the values as part of this modification */ num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals)); ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0); /* for each value */ for (j = 0; j < num_modvals; j++) { /* fetch it */ fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j); modval = fetched; /* allocate the data struct */ ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0); /* fill it */ ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(modval); ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(Z_STRVAL_P(modval), Z_STRLEN_P(modval)); } /* NULL-terminate values */ ldap_mods[i]->mod_bvalues[num_modvals] = NULL; } } /* NULL-terminate modifications */ ldap_mods[num_mods] = NULL; /* perform (finally) */ if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Batch Modify: %s", ldap_err2string(i)); RETVAL_FALSE; } else RETVAL_TRUE; /* clean up */ cleanup: { for (i = 0; i < num_mods; i++) { /* attribute */ efree(ldap_mods[i]->mod_type); if (ldap_mods[i]->mod_bvalues != NULL) { /* each BER value */ for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) { /* free the data bytes */ efree(ldap_mods[i]->mod_bvalues[j]->bv_val); /* free the bvalue struct */ efree(ldap_mods[i]->mod_bvalues[j]); } /* the BER value array */ efree(ldap_mods[i]->mod_bvalues); } /* the modification */ efree(ldap_mods[i]); } /* the modifications array */ efree(ldap_mods); } } /* }}} */ /* {{{ proto int ldap_errno(resource link) Get the current ldap error number */ PHP_FUNCTION(ldap_errno) { zval *link; ldap_linkdata *ld; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } RETURN_LONG(_get_lderrno(ld->link)); } /* }}} */ /* {{{ proto string ldap_err2str(int errno) Convert error number to error string */ PHP_FUNCTION(ldap_err2str) { zend_long perrno; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perrno) != SUCCESS) { return; } RETURN_STRING(ldap_err2string(perrno)); } /* }}} */ /* {{{ proto string ldap_error(resource link) Get the current ldap error string */ PHP_FUNCTION(ldap_error) { zval *link; ldap_linkdata *ld; int ld_errno; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } ld_errno = _get_lderrno(ld->link); RETURN_STRING(ldap_err2string(ld_errno)); } /* }}} */ /* {{{ proto bool ldap_compare(resource link, string dn, string attr, string value) Determine if an entry has a specific value for one of its attributes */ PHP_FUNCTION(ldap_compare) { zval *link; char *dn, *attr, *value; size_t dn_len, attr_len, value_len; ldap_linkdata *ld; int errno; struct berval lvalue; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsss", &link, &dn, &dn_len, &attr, &attr_len, &value, &value_len) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } lvalue.bv_val = value; lvalue.bv_len = value_len; errno = ldap_compare_ext_s(ld->link, dn, attr, &lvalue, NULL, NULL); switch (errno) { case LDAP_COMPARE_TRUE: RETURN_TRUE; break; case LDAP_COMPARE_FALSE: RETURN_FALSE; break; } php_error_docref(NULL, E_WARNING, "Compare: %s", ldap_err2string(errno)); RETURN_LONG(-1); } /* }}} */ /* {{{ proto bool ldap_sort(resource link, resource result, string sortfilter) Sort LDAP result entries */ PHP_FUNCTION(ldap_sort) { zval *link, *result; ldap_linkdata *ld; char *sortfilter; size_t sflen; zend_resource *le; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result, &sortfilter, &sflen) != SUCCESS) { RETURN_FALSE; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } le = Z_RES_P(result); if (le->type != le_result) { php_error_docref(NULL, E_WARNING, "Supplied resource is not a valid ldap result resource"); RETURN_FALSE; } if (ldap_sort_entries(ld->link, (LDAPMessage **) &le->ptr, sflen ? sortfilter : NULL, strcmp) != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "%s", ldap_err2string(errno)); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP /* {{{ proto bool ldap_get_option(resource link, int option, mixed retval) Get the current value of various session-wide parameters */ PHP_FUNCTION(ldap_get_option) { zval *link, *retval; ldap_linkdata *ld; zend_long option; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz/", &link, &option, &retval) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } switch (option) { /* options with int value */ case LDAP_OPT_DEREF: case LDAP_OPT_SIZELIMIT: case LDAP_OPT_TIMELIMIT: case LDAP_OPT_PROTOCOL_VERSION: case LDAP_OPT_ERROR_NUMBER: case LDAP_OPT_REFERRALS: #ifdef LDAP_OPT_RESTART case LDAP_OPT_RESTART: #endif #ifdef LDAP_OPT_X_SASL_NOCANON case LDAP_OPT_X_SASL_NOCANON: #endif #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT case LDAP_OPT_X_TLS_REQUIRE_CERT: #endif #ifdef LDAP_OPT_X_TLS_CRLCHECK case LDAP_OPT_X_TLS_CRLCHECK: #endif #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN case LDAP_OPT_X_TLS_PROTOCOL_MIN: #endif #ifdef LDAP_OPT_X_KEEPALIVE_IDLE case LDAP_OPT_X_KEEPALIVE_IDLE: case LDAP_OPT_X_KEEPALIVE_PROBES: case LDAP_OPT_X_KEEPALIVE_INTERVAL: #endif { int val; if (ldap_get_option(ld->link, option, &val)) { RETURN_FALSE; } zval_ptr_dtor(retval); ZVAL_LONG(retval, val); } break; #ifdef LDAP_OPT_NETWORK_TIMEOUT case LDAP_OPT_NETWORK_TIMEOUT: { struct timeval *timeout = NULL; if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) { if (timeout) { ldap_memfree(timeout); } RETURN_FALSE; } if (!timeout) { RETURN_FALSE; } zval_ptr_dtor(retval); ZVAL_LONG(retval, timeout->tv_sec); ldap_memfree(timeout); } break; #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT) case LDAP_X_OPT_CONNECT_TIMEOUT: { int timeout; if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) { RETURN_FALSE; } zval_ptr_dtor(retval); ZVAL_LONG(retval, (timeout / 1000)); } break; #endif #ifdef LDAP_OPT_TIMEOUT case LDAP_OPT_TIMEOUT: { struct timeval *timeout = NULL; if (ldap_get_option(ld->link, LDAP_OPT_TIMEOUT, (void *) &timeout)) { if (timeout) { ldap_memfree(timeout); } RETURN_FALSE; } if (!timeout) { RETURN_FALSE; } zval_dtor(retval); ZVAL_LONG(retval, timeout->tv_sec); ldap_memfree(timeout); } break; #endif /* options with string value */ case LDAP_OPT_ERROR_STRING: #ifdef LDAP_OPT_HOST_NAME case LDAP_OPT_HOST_NAME: #endif #ifdef HAVE_LDAP_SASL case LDAP_OPT_X_SASL_MECH: case LDAP_OPT_X_SASL_REALM: case LDAP_OPT_X_SASL_AUTHCID: case LDAP_OPT_X_SASL_AUTHZID: #endif #ifdef LDAP_OPT_X_SASL_USERNAME case LDAP_OPT_X_SASL_USERNAME: #endif #if (LDAP_API_VERSION > 2000) case LDAP_OPT_X_TLS_CACERTDIR: case LDAP_OPT_X_TLS_CACERTFILE: case LDAP_OPT_X_TLS_CERTFILE: case LDAP_OPT_X_TLS_CIPHER_SUITE: case LDAP_OPT_X_TLS_KEYFILE: case LDAP_OPT_X_TLS_RANDOM_FILE: #endif #ifdef LDAP_OPT_X_TLS_PACKAGE case LDAP_OPT_X_TLS_PACKAGE: #endif #ifdef LDAP_OPT_X_TLS_CRLFILE case LDAP_OPT_X_TLS_CRLFILE: #endif #ifdef LDAP_OPT_X_TLS_DHFILE case LDAP_OPT_X_TLS_DHFILE: #endif #ifdef LDAP_OPT_MATCHED_DN case LDAP_OPT_MATCHED_DN: #endif { char *val = NULL; if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') { if (val) { ldap_memfree(val); } RETURN_FALSE; } zval_ptr_dtor(retval); ZVAL_STRING(retval, val); ldap_memfree(val); } break; case LDAP_OPT_SERVER_CONTROLS: case LDAP_OPT_CLIENT_CONTROLS: { zval tmp1; int num_entries; LDAPControl **ctrls = NULL, **ctrlp; if (ldap_get_option(ld->link, option, &ctrls) || ctrls == NULL) { if (ctrls) { ldap_memfree(ctrls); } RETURN_FALSE; } zval_ptr_dtor(retval); array_init(retval); num_entries = 0; ctrlp = ctrls; while (*ctrlp != NULL) { array_init(&tmp1); add_assoc_string(&tmp1, "oid", (*ctrlp)->ldctl_oid); add_assoc_bool(&tmp1, "iscritical", ((*ctrlp)->ldctl_iscritical != 0)); if ((*ctrlp)->ldctl_value.bv_len) { add_assoc_stringl(&tmp1, "value", (*ctrlp)->ldctl_value.bv_val, (*ctrlp)->ldctl_value.bv_len); } zend_hash_index_update(Z_ARRVAL_P(retval), num_entries, &tmp1); num_entries++; ctrlp++; } ldap_controls_free(ctrls); } break; /* options not implemented case LDAP_OPT_API_INFO: case LDAP_OPT_API_FEATURE_INFO: */ default: RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ldap_set_option(resource link, int option, mixed newval) Set the value of various session-wide parameters */ PHP_FUNCTION(ldap_set_option) { zval *link, *newval; ldap_linkdata *ld; LDAP *ldap; zend_long option; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zlz", &link, &option, &newval) != SUCCESS) { return; } if (Z_TYPE_P(link) == IS_NULL) { ldap = NULL; } else { if ((ld = (ldap_linkdata *)zend_fetch_resource_ex(link, "ldap link", le_link)) == NULL) { RETURN_FALSE; } ldap = ld->link; } switch (option) { /* options with int value */ case LDAP_OPT_DEREF: case LDAP_OPT_SIZELIMIT: case LDAP_OPT_TIMELIMIT: case LDAP_OPT_PROTOCOL_VERSION: case LDAP_OPT_ERROR_NUMBER: #ifdef LDAP_OPT_DEBUG_LEVEL case LDAP_OPT_DEBUG_LEVEL: #endif #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT case LDAP_OPT_X_TLS_REQUIRE_CERT: #endif #ifdef LDAP_OPT_X_TLS_CRLCHECK case LDAP_OPT_X_TLS_CRLCHECK: #endif #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN case LDAP_OPT_X_TLS_PROTOCOL_MIN: #endif #ifdef LDAP_OPT_X_KEEPALIVE_IDLE case LDAP_OPT_X_KEEPALIVE_IDLE: case LDAP_OPT_X_KEEPALIVE_PROBES: case LDAP_OPT_X_KEEPALIVE_INTERVAL: #endif { int val; convert_to_long_ex(newval); val = Z_LVAL_P(newval); if (ldap_set_option(ldap, option, &val)) { RETURN_FALSE; } } break; #ifdef LDAP_OPT_NETWORK_TIMEOUT case LDAP_OPT_NETWORK_TIMEOUT: { struct timeval timeout; convert_to_long_ex(newval); timeout.tv_sec = Z_LVAL_P(newval); timeout.tv_usec = 0; if (ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) { RETURN_FALSE; } } break; #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT) case LDAP_X_OPT_CONNECT_TIMEOUT: { int timeout; convert_to_long_ex(newval); timeout = 1000 * Z_LVAL_P(newval); /* Convert to milliseconds */ if (ldap_set_option(ldap, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) { RETURN_FALSE; } } break; #endif #ifdef LDAP_OPT_TIMEOUT case LDAP_OPT_TIMEOUT: { struct timeval timeout; convert_to_long_ex(newval); timeout.tv_sec = Z_LVAL_P(newval); timeout.tv_usec = 0; if (ldap_set_option(ldap, LDAP_OPT_TIMEOUT, (void *) &timeout)) { RETURN_FALSE; } } break; #endif /* options with string value */ case LDAP_OPT_ERROR_STRING: #ifdef LDAP_OPT_HOST_NAME case LDAP_OPT_HOST_NAME: #endif #ifdef HAVE_LDAP_SASL case LDAP_OPT_X_SASL_MECH: case LDAP_OPT_X_SASL_REALM: case LDAP_OPT_X_SASL_AUTHCID: case LDAP_OPT_X_SASL_AUTHZID: #endif #if (LDAP_API_VERSION > 2000) case LDAP_OPT_X_TLS_CACERTDIR: case LDAP_OPT_X_TLS_CACERTFILE: case LDAP_OPT_X_TLS_CERTFILE: case LDAP_OPT_X_TLS_CIPHER_SUITE: case LDAP_OPT_X_TLS_KEYFILE: case LDAP_OPT_X_TLS_RANDOM_FILE: #endif #ifdef LDAP_OPT_X_TLS_CRLFILE case LDAP_OPT_X_TLS_CRLFILE: #endif #ifdef LDAP_OPT_X_TLS_DHFILE case LDAP_OPT_X_TLS_DHFILE: #endif #ifdef LDAP_OPT_MATCHED_DN case LDAP_OPT_MATCHED_DN: #endif { char *val; convert_to_string_ex(newval); val = Z_STRVAL_P(newval); if (ldap_set_option(ldap, option, val)) { RETURN_FALSE; } } break; /* options with boolean value */ case LDAP_OPT_REFERRALS: #ifdef LDAP_OPT_RESTART case LDAP_OPT_RESTART: #endif #ifdef LDAP_OPT_X_SASL_NOCANON case LDAP_OPT_X_SASL_NOCANON: #endif { void *val; convert_to_boolean_ex(newval); val = Z_TYPE_P(newval) == IS_TRUE ? LDAP_OPT_ON : LDAP_OPT_OFF; if (ldap_set_option(ldap, option, val)) { RETURN_FALSE; } } break; /* options with control list value */ case LDAP_OPT_SERVER_CONTROLS: case LDAP_OPT_CLIENT_CONTROLS: { LDAPControl *ctrl, **ctrls, **ctrlp; zval *ctrlval, *val; int ncontrols; char error=0; if (Z_TYPE_P(newval) != IS_ARRAY) { php_error_docref(NULL, E_WARNING, "Expected array value for this option"); RETURN_FALSE; } ncontrols = zend_hash_num_elements(Z_ARRVAL_P(newval)); ctrls = safe_emalloc((1 + ncontrols), sizeof(*ctrls), 0); *ctrls = NULL; ctrlp = ctrls; ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(newval), ctrlval) { if (Z_TYPE_P(ctrlval) != IS_ARRAY) { php_error_docref(NULL, E_WARNING, "The array value must contain only arrays, where each array is a control"); error = 1; break; } if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "oid", sizeof("oid") - 1)) == NULL) { php_error_docref(NULL, E_WARNING, "Control must have an oid key"); error = 1; break; } ctrl = *ctrlp = emalloc(sizeof(**ctrlp)); convert_to_string_ex(val); ctrl->ldctl_oid = Z_STRVAL_P(val); if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "value", sizeof("value") - 1)) != NULL) { convert_to_string_ex(val); ctrl->ldctl_value.bv_val = Z_STRVAL_P(val); ctrl->ldctl_value.bv_len = Z_STRLEN_P(val); } else { ctrl->ldctl_value.bv_val = NULL; ctrl->ldctl_value.bv_len = 0; } if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "iscritical", sizeof("iscritical") - 1)) != NULL) { convert_to_boolean_ex(val); ctrl->ldctl_iscritical = Z_TYPE_P(val) == IS_TRUE; } else { ctrl->ldctl_iscritical = 0; } ++ctrlp; *ctrlp = NULL; } ZEND_HASH_FOREACH_END(); if (!error) { error = ldap_set_option(ldap, option, ctrls); } ctrlp = ctrls; while (*ctrlp) { efree(*ctrlp); ctrlp++; } efree(ctrls); if (error) { RETURN_FALSE; } } break; default: RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #ifdef HAVE_LDAP_PARSE_RESULT /* {{{ proto bool ldap_parse_result(resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals) Extract information from result */ PHP_FUNCTION(ldap_parse_result) { zval *link, *result, *errcode, *matcheddn, *errmsg, *referrals; ldap_linkdata *ld; LDAPMessage *ldap_result; char **lreferrals, **refp; char *lmatcheddn, *lerrmsg; int rc, lerrcode, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrz/|z/z/z/", &link, &result, &errcode, &matcheddn, &errmsg, &referrals) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } rc = ldap_parse_result(ld->link, ldap_result, &lerrcode, myargcount > 3 ? &lmatcheddn : NULL, myargcount > 4 ? &lerrmsg : NULL, myargcount > 5 ? &lreferrals : NULL, NULL /* &serverctrls */, 0); if (rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to parse result: %s", ldap_err2string(rc)); RETURN_FALSE; } zval_ptr_dtor(errcode); ZVAL_LONG(errcode, lerrcode); /* Reverse -> fall through */ switch (myargcount) { case 6: zval_ptr_dtor(referrals); array_init(referrals); if (lreferrals != NULL) { refp = lreferrals; while (*refp) { add_next_index_string(referrals, *refp); refp++; } ldap_memvfree((void**)lreferrals); } case 5: zval_ptr_dtor(errmsg); if (lerrmsg == NULL) { ZVAL_EMPTY_STRING(errmsg); } else { ZVAL_STRING(errmsg, lerrmsg); ldap_memfree(lerrmsg); } case 4: zval_ptr_dtor(matcheddn); if (lmatcheddn == NULL) { ZVAL_EMPTY_STRING(matcheddn); } else { ZVAL_STRING(matcheddn, lmatcheddn); ldap_memfree(lmatcheddn); } } RETURN_TRUE; } /* }}} */ #endif /* {{{ Extended operation response parsing, Pierangelo Masarati */ #ifdef HAVE_LDAP_PARSE_EXTENDED_RESULT /* {{{ proto bool ldap_parse_exop(resource link, resource result [, string retdata [, string retoid]]) Extract information from extended operation result */ PHP_FUNCTION(ldap_parse_exop) { zval *link, *result, *retdata, *retoid; ldap_linkdata *ld; LDAPMessage *ldap_result; char *lretoid; struct berval *lretdata; int rc, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|z/z/", &link, &result, &retdata, &retoid) != SUCCESS) { WRONG_PARAM_COUNT; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } rc = ldap_parse_extended_result(ld->link, ldap_result, myargcount > 3 ? &lretoid: NULL, myargcount > 2 ? &lretdata: NULL, 0); if (rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to parse extended operation result: %s", ldap_err2string(rc)); RETURN_FALSE; } /* Reverse -> fall through */ switch (myargcount) { case 4: zval_dtor(retoid); if (lretoid == NULL) { ZVAL_EMPTY_STRING(retoid); } else { ZVAL_STRING(retoid, lretoid); ldap_memfree(lretoid); } case 3: /* use arg #3 as the data returned by the server */ zval_dtor(retdata); if (lretdata == NULL) { ZVAL_EMPTY_STRING(retdata); } else { ZVAL_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len); ldap_memfree(lretdata->bv_val); ldap_memfree(lretdata); } } RETURN_TRUE; } /* }}} */ #endif /* }}} */ /* {{{ proto resource ldap_first_reference(resource link, resource result) Return first reference */ PHP_FUNCTION(ldap_first_reference) { zval *link, *result; ldap_linkdata *ld; ldap_resultentry *resultentry; LDAPMessage *ldap_result, *entry; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } if ((entry = ldap_first_reference(ld->link, ldap_result)) == NULL) { RETVAL_FALSE; } else { resultentry = emalloc(sizeof(ldap_resultentry)); RETVAL_RES(zend_register_resource(resultentry, le_result_entry)); ZVAL_COPY(&resultentry->res, result); resultentry->data = entry; resultentry->ber = NULL; } } /* }}} */ /* {{{ proto resource ldap_next_reference(resource link, resource reference_entry) Get next reference */ PHP_FUNCTION(ldap_next_reference) { zval *link, *result_entry; ldap_linkdata *ld; ldap_resultentry *resultentry, *resultentry_next; LDAPMessage *entry_next; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if ((entry_next = ldap_next_reference(ld->link, resultentry->data)) == NULL) { RETVAL_FALSE; } else { resultentry_next = emalloc(sizeof(ldap_resultentry)); RETVAL_RES(zend_register_resource(resultentry_next, le_result_entry)); ZVAL_COPY(&resultentry_next->res, &resultentry->res); resultentry_next->data = entry_next; resultentry_next->ber = NULL; } } /* }}} */ #ifdef HAVE_LDAP_PARSE_REFERENCE /* {{{ proto bool ldap_parse_reference(resource link, resource reference_entry, array referrals) Extract information from reference entry */ PHP_FUNCTION(ldap_parse_reference) { zval *link, *result_entry, *referrals; ldap_linkdata *ld; ldap_resultentry *resultentry; char **lreferrals, **refp; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrz/", &link, &result_entry, &referrals) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) { RETURN_FALSE; } if (ldap_parse_reference(ld->link, resultentry->data, &lreferrals, NULL /* &serverctrls */, 0) != LDAP_SUCCESS) { RETURN_FALSE; } zval_ptr_dtor(referrals); array_init(referrals); if (lreferrals != NULL) { refp = lreferrals; while (*refp) { add_next_index_string(referrals, *refp); refp++; } ldap_memvfree((void**)lreferrals); } RETURN_TRUE; } /* }}} */ #endif /* {{{ proto bool ldap_rename(resource link, string dn, string newrdn, string newparent, bool deleteoldrdn) Modify the name of an entry */ PHP_FUNCTION(ldap_rename) { zval *link; ldap_linkdata *ld; int rc; char *dn, *newrdn, *newparent; size_t dn_len, newrdn_len, newparent_len; zend_bool deleteoldrdn; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsssb", &link, &dn, &dn_len, &newrdn, &newrdn_len, &newparent, &newparent_len, &deleteoldrdn) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if (newparent_len == 0) { newparent = NULL; } #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP rc = ldap_rename_s(ld->link, dn, newrdn, newparent, deleteoldrdn, NULL, NULL); #else if (newparent_len != 0) { php_error_docref(NULL, E_WARNING, "You are using old LDAP API, newparent must be the empty string, can only modify RDN"); RETURN_FALSE; } /* could support old APIs but need check for ldap_modrdn2()/ldap_modrdn() */ rc = ldap_modrdn2_s(ld->link, dn, newrdn, deleteoldrdn); #endif if (rc == LDAP_SUCCESS) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ #ifdef HAVE_LDAP_START_TLS_S /* {{{ proto bool ldap_start_tls(resource link) Start TLS */ PHP_FUNCTION(ldap_start_tls) { zval *link; ldap_linkdata *ld; int rc, protocol = LDAP_VERSION3; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if (((rc = ldap_set_option(ld->link, LDAP_OPT_PROTOCOL_VERSION, &protocol)) != LDAP_SUCCESS) || ((rc = ldap_start_tls_s(ld->link, NULL, NULL)) != LDAP_SUCCESS) ) { php_error_docref(NULL, E_WARNING,"Unable to start TLS: %s", ldap_err2string(rc)); RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ #endif #endif /* (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP */ #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC) /* {{{ _ldap_rebind_proc() */ int _ldap_rebind_proc(LDAP *ldap, const char *url, ber_tag_t req, ber_int_t msgid, void *params) { ldap_linkdata *ld; int retval; zval cb_args[2]; zval cb_retval; zval *cb_link = (zval *) params; ld = (ldap_linkdata *) zend_fetch_resource_ex(cb_link, "ldap link", le_link); /* link exists and callback set? */ if (ld == NULL || Z_ISUNDEF(ld->rebindproc)) { php_error_docref(NULL, E_WARNING, "Link not found or no callback set"); return LDAP_OTHER; } /* callback */ ZVAL_COPY_VALUE(&cb_args[0], cb_link); ZVAL_STRING(&cb_args[1], url); if (call_user_function_ex(EG(function_table), NULL, &ld->rebindproc, &cb_retval, 2, cb_args, 0, NULL) == SUCCESS && !Z_ISUNDEF(cb_retval)) { convert_to_long_ex(&cb_retval); retval = Z_LVAL(cb_retval); zval_ptr_dtor(&cb_retval); } else { php_error_docref(NULL, E_WARNING, "rebind_proc PHP callback failed"); retval = LDAP_OTHER; } zval_ptr_dtor(&cb_args[1]); return retval; } /* }}} */ /* {{{ proto bool ldap_set_rebind_proc(resource link, string callback) Set a callback function to do re-binds on referral chasing. */ PHP_FUNCTION(ldap_set_rebind_proc) { zval *link, *callback; ldap_linkdata *ld; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz", &link, &callback) != SUCCESS) { RETURN_FALSE; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if (Z_TYPE_P(callback) == IS_STRING && Z_STRLEN_P(callback) == 0) { /* unregister rebind procedure */ if (!Z_ISUNDEF(ld->rebindproc)) { zval_ptr_dtor(&ld->rebindproc); ZVAL_UNDEF(&ld->rebindproc); ldap_set_rebind_proc(ld->link, NULL, NULL); } RETURN_TRUE; } /* callable? */ if (!zend_is_callable(callback, 0, NULL)) { zend_string *callback_name = zend_get_callable_name(callback); php_error_docref(NULL, E_WARNING, "Two arguments expected for '%s' to be a valid callback", ZSTR_VAL(callback_name)); zend_string_release(callback_name); RETURN_FALSE; } /* register rebind procedure */ if (Z_ISUNDEF(ld->rebindproc)) { ldap_set_rebind_proc(ld->link, _ldap_rebind_proc, (void *) link); } else { zval_ptr_dtor(&ld->rebindproc); } ZVAL_COPY(&ld->rebindproc, callback); RETURN_TRUE; } /* }}} */ #endif static zend_string* php_ldap_do_escape(const zend_bool *map, const char *value, size_t valuelen, zend_long flags) { char hex[] = "0123456789abcdef"; size_t i, p = 0; size_t len = 0; zend_string *ret; for (i = 0; i < valuelen; i++) { len += (map[(unsigned char) value[i]]) ? 3 : 1; } /* Per RFC 4514, a leading and trailing space must be escaped */ if ((flags & PHP_LDAP_ESCAPE_DN) && (value[0] == ' ')) { len += 2; } if ((flags & PHP_LDAP_ESCAPE_DN) && ((valuelen > 1) && (value[valuelen - 1] == ' '))) { len += 2; } ret = zend_string_alloc(len, 0); for (i = 0; i < valuelen; i++) { unsigned char v = (unsigned char) value[i]; if (map[v] || ((flags & PHP_LDAP_ESCAPE_DN) && ((i == 0) || (i + 1 == valuelen)) && (v == ' '))) { ZSTR_VAL(ret)[p++] = '\\'; ZSTR_VAL(ret)[p++] = hex[v >> 4]; ZSTR_VAL(ret)[p++] = hex[v & 0x0f]; } else { ZSTR_VAL(ret)[p++] = v; } } ZSTR_VAL(ret)[p] = '\0'; ZSTR_LEN(ret) = p; return ret; } static void php_ldap_escape_map_set_chars(zend_bool *map, const char *chars, const int charslen, char escape) { int i = 0; while (i < charslen) { map[(unsigned char) chars[i++]] = escape; } } PHP_FUNCTION(ldap_escape) { char *value, *ignores; size_t valuelen = 0, ignoreslen = 0; int i; zend_long flags = 0; zend_bool map[256] = {0}, havecharlist = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sl", &value, &valuelen, &ignores, &ignoreslen, &flags) != SUCCESS) { return; } if (!valuelen) { RETURN_EMPTY_STRING(); } if (flags & PHP_LDAP_ESCAPE_FILTER) { havecharlist = 1; php_ldap_escape_map_set_chars(map, "\\*()\0", sizeof("\\*()\0") - 1, 1); } if (flags & PHP_LDAP_ESCAPE_DN) { havecharlist = 1; php_ldap_escape_map_set_chars(map, "\\,=+<>;\"#\r", sizeof("\\,=+<>;\"#\r") - 1, 1); } if (!havecharlist) { for (i = 0; i < 256; i++) { map[i] = 1; } } if (ignoreslen) { php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0); } RETURN_NEW_STR(php_ldap_do_escape(map, value, valuelen, flags)); } #ifdef STR_TRANSLATION /* {{{ php_ldap_do_translate */ static void php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS, int way) { char *value; size_t value_len; int result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) != SUCCESS) { return; } if (value_len == 0) { RETURN_FALSE; } if (way == 1) { result = ldap_8859_to_t61(&value, &value_len, 0); } else { result = ldap_t61_to_8859(&value, &value_len, 0); } if (result == LDAP_SUCCESS) { RETVAL_STRINGL(value, value_len); free(value); } else { php_error_docref(NULL, E_WARNING, "Conversion from iso-8859-1 to t61 failed: %s", ldap_err2string(result)); RETVAL_FALSE; } } /* }}} */ /* {{{ proto string ldap_t61_to_8859(string value) Translate t61 characters to 8859 characters */ PHP_FUNCTION(ldap_t61_to_8859) { php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto string ldap_8859_to_t61(string value) Translate 8859 characters to t61 characters */ PHP_FUNCTION(ldap_8859_to_t61) { php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ #endif #ifdef LDAP_CONTROL_PAGEDRESULTS /* {{{ proto mixed ldap_control_paged_result(resource link, int pagesize [, bool iscritical [, string cookie]]) Inject paged results control*/ PHP_FUNCTION(ldap_control_paged_result) { zend_long pagesize; zend_bool iscritical; zval *link; char *cookie = NULL; size_t cookie_len = 0; struct berval lcookie = { 0, NULL }; ldap_linkdata *ld; LDAP *ldap; BerElement *ber = NULL; LDAPControl ctrl, *ctrlsp[2]; int rc, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|bs", &link, &pagesize, &iscritical, &cookie, &cookie_len) != SUCCESS) { return; } if (Z_TYPE_P(link) == IS_NULL) { ldap = NULL; } else { if ((ld = (ldap_linkdata *)zend_fetch_resource_ex(link, "ldap link", le_link)) == NULL) { RETURN_FALSE; } ldap = ld->link; } ber = ber_alloc_t(LBER_USE_DER); if (ber == NULL) { php_error_docref(NULL, E_WARNING, "Unable to alloc BER encoding resources for paged results control"); RETURN_FALSE; } ctrl.ldctl_iscritical = 0; switch (myargcount) { case 4: lcookie.bv_val = cookie; lcookie.bv_len = cookie_len; /* fallthru */ case 3: ctrl.ldctl_iscritical = (int)iscritical; /* fallthru */ } if (ber_printf(ber, "{iO}", (int)pagesize, &lcookie) == LBER_ERROR) { php_error_docref(NULL, E_WARNING, "Unable to BER printf paged results control"); RETVAL_FALSE; goto lcpr_error_out; } rc = ber_flatten2(ber, &ctrl.ldctl_value, 0); if (rc == LBER_ERROR) { php_error_docref(NULL, E_WARNING, "Unable to BER encode paged results control"); RETVAL_FALSE; goto lcpr_error_out; } ctrl.ldctl_oid = LDAP_CONTROL_PAGEDRESULTS; if (ldap) { /* directly set the option */ ctrlsp[0] = &ctrl; ctrlsp[1] = NULL; rc = ldap_set_option(ldap, LDAP_OPT_SERVER_CONTROLS, ctrlsp); if (rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to set paged results control: %s (%d)", ldap_err2string(rc), rc); RETVAL_FALSE; goto lcpr_error_out; } RETVAL_TRUE; } else { /* return a PHP control object */ array_init(return_value); add_assoc_string(return_value, "oid", ctrl.ldctl_oid); if (ctrl.ldctl_value.bv_len) { add_assoc_stringl(return_value, "value", ctrl.ldctl_value.bv_val, ctrl.ldctl_value.bv_len); } if (ctrl.ldctl_iscritical) { add_assoc_bool(return_value, "iscritical", ctrl.ldctl_iscritical); } } lcpr_error_out: if (ber != NULL) { ber_free(ber, 1); } return; } /* }}} */ /* {{{ proto bool ldap_control_paged_result_response(resource link, resource result [, string &cookie [, int &estimated]]) Extract paged results control response */ PHP_FUNCTION(ldap_control_paged_result_response) { zval *link, *result, *cookie, *estimated; struct berval lcookie; int lestimated; ldap_linkdata *ld; LDAPMessage *ldap_result; LDAPControl **lserverctrls, *lctrl; BerElement *ber; ber_tag_t tag; int rc, lerrcode, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|z/z/", &link, &result, &cookie, &estimated) != SUCCESS) { return; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) { RETURN_FALSE; } rc = ldap_parse_result(ld->link, ldap_result, &lerrcode, NULL, /* matcheddn */ NULL, /* errmsg */ NULL, /* referrals */ &lserverctrls, 0); if (rc != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Unable to parse result: %s (%d)", ldap_err2string(rc), rc); RETURN_FALSE; } if (lerrcode != LDAP_SUCCESS) { php_error_docref(NULL, E_WARNING, "Result is: %s (%d)", ldap_err2string(lerrcode), lerrcode); RETURN_FALSE; } if (lserverctrls == NULL) { php_error_docref(NULL, E_WARNING, "No server controls in result"); RETURN_FALSE; } lctrl = ldap_control_find(LDAP_CONTROL_PAGEDRESULTS, lserverctrls, NULL); if (lctrl == NULL) { ldap_controls_free(lserverctrls); php_error_docref(NULL, E_WARNING, "No paged results control response in result"); RETURN_FALSE; } ber = ber_init(&lctrl->ldctl_value); if (ber == NULL) { ldap_controls_free(lserverctrls); php_error_docref(NULL, E_WARNING, "Unable to alloc BER decoding resources for paged results control response"); RETURN_FALSE; } tag = ber_scanf(ber, "{io}", &lestimated, &lcookie); (void)ber_free(ber, 1); if (tag == LBER_ERROR) { ldap_controls_free(lserverctrls); php_error_docref(NULL, E_WARNING, "Unable to decode paged results control response"); RETURN_FALSE; } if (lestimated < 0) { ldap_controls_free(lserverctrls); php_error_docref(NULL, E_WARNING, "Invalid paged results control response value"); RETURN_FALSE; } ldap_controls_free(lserverctrls); if (myargcount == 4) { zval_dtor(estimated); ZVAL_LONG(estimated, lestimated); } zval_ptr_dtor(cookie); if (lcookie.bv_len == 0) { ZVAL_EMPTY_STRING(cookie); } else { ZVAL_STRINGL(cookie, lcookie.bv_val, lcookie.bv_len); } ldap_memfree(lcookie.bv_val); RETURN_TRUE; } /* }}} */ #endif /* {{{ Extended operations, Pierangelo Masarati */ #ifdef HAVE_LDAP_EXTENDED_OPERATION_S /* {{{ proto resource ldap_exop(resource link, string reqoid [, string reqdata [, array servercontrols [, string &retdata [, string &retoid]]]]) Extended operation */ PHP_FUNCTION(ldap_exop) { zval *servercontrols; zval *link, *reqoid, *reqdata, *retdata, *retoid; char *lreqoid, *lretoid = NULL; struct berval lreqdata, *lretdata = NULL; ldap_linkdata *ld; LDAPMessage *ldap_res; int rc, msgid, myargcount = ZEND_NUM_ARGS(); /* int reqoid_len, reqdata_len, retdata_len, retoid_len, retdat_len; */ if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz|zzz/z/", &link, &reqoid, &reqdata, &servercontrols, &retdata, &retoid) != SUCCESS) { WRONG_PARAM_COUNT; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } switch (myargcount) { case 6: case 5: case 4: case 3: convert_to_string_ex(reqdata); lreqdata.bv_val = Z_STRVAL_P(reqdata); lreqdata.bv_len = Z_STRLEN_P(reqdata); /* fallthru */ case 2: convert_to_string_ex(reqoid); lreqoid = Z_STRVAL_P(reqoid); } if (myargcount > 4) { /* synchronous call */ rc = ldap_extended_operation_s(ld->link, lreqoid, lreqdata.bv_len > 0 ? &lreqdata: NULL, NULL, NULL, myargcount > 5 ? &lretoid : NULL, &lretdata ); if (rc != LDAP_SUCCESS ) { php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", lreqoid, ldap_err2string(rc), rc); RETURN_FALSE; } /* Reverse -> fall through */ switch (myargcount) { case 6: zval_dtor(retoid); if (lretoid == NULL) { ZVAL_EMPTY_STRING(retoid); } else { ZVAL_STRING(retoid, lretoid); ldap_memfree(lretoid); } case 5: /* use arg #5 as the data returned by the server */ zval_dtor(retdata); if (lretdata == NULL) { ZVAL_EMPTY_STRING(retdata); } else { ZVAL_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len); ldap_memfree(lretdata->bv_val); ldap_memfree(lretdata); } } RETURN_TRUE; } /* asynchronous call */ rc = ldap_extended_operation(ld->link, lreqoid, lreqdata.bv_len > 0 ? &lreqdata: NULL, NULL, NULL, &msgid); if (rc != LDAP_SUCCESS ) { php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", lreqoid, ldap_err2string(rc), rc); RETURN_FALSE; } rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res); if (rc == -1) { php_error_docref(NULL, E_WARNING, "Extended operation %s failed", lreqoid); RETURN_FALSE; } /* return a PHP control object */ RETVAL_RES(zend_register_resource(ldap_res, le_result)); } /* }}} */ #endif #ifdef HAVE_LDAP_PASSWD_S /* {{{ proto bool|string ldap_exop_passwd(resource link [, string user [, string oldpw [, string newpw ]]]) Passwd modify extended operation */ PHP_FUNCTION(ldap_exop_passwd) { zval *link, *user, *newpw, *oldpw; struct berval luser, loldpw, lnewpw, lgenpasswd; ldap_linkdata *ld; int rc, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|zzz", &link, &user, &oldpw, &newpw) == FAILURE) { WRONG_PARAM_COUNT; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } luser.bv_len = 0; loldpw.bv_len = 0; lnewpw.bv_len = 0; switch (myargcount) { case 4: convert_to_string_ex(newpw); lnewpw.bv_val = Z_STRVAL_P(newpw); lnewpw.bv_len = Z_STRLEN_P(newpw); case 3: convert_to_string_ex(oldpw); loldpw.bv_val = Z_STRVAL_P(oldpw); loldpw.bv_len = Z_STRLEN_P(oldpw); case 2: convert_to_string_ex(user); luser.bv_val = Z_STRVAL_P(user); luser.bv_len = Z_STRLEN_P(user); } /* synchronous call */ rc = ldap_passwd_s(ld->link, &luser, loldpw.bv_len > 0 ? &loldpw : NULL, lnewpw.bv_len > 0 ? &lnewpw : NULL, &lgenpasswd, NULL, NULL); if (rc != LDAP_SUCCESS ) { php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc); RETURN_FALSE; } if (lnewpw.bv_len == 0) { if (lgenpasswd.bv_len == 0) { RETVAL_EMPTY_STRING(); } else { RETVAL_STRINGL(lgenpasswd.bv_val, lgenpasswd.bv_len); } } else { RETURN_TRUE; } ldap_memfree(lgenpasswd.bv_val); } /* }}} */ #endif #ifdef HAVE_LDAP_WHOAMI_S /* {{{ proto bool|string ldap_exop_whoami(resource link) Whoami extended operation */ PHP_FUNCTION(ldap_exop_whoami) { zval *link; struct berval *lauthzid; ldap_linkdata *ld; int rc, myargcount = ZEND_NUM_ARGS(); if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) == FAILURE) { WRONG_PARAM_COUNT; } if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) { RETURN_FALSE; } /* synchronous call */ rc = ldap_whoami_s(ld->link, &lauthzid, NULL, NULL); if (rc != LDAP_SUCCESS ) { php_error_docref(NULL, E_WARNING, "Whoami extended operation failed: %s (%d)", ldap_err2string(rc), rc); RETURN_FALSE; } if (lauthzid == NULL) { RETVAL_EMPTY_STRING(); } else { RETVAL_STRINGL(lauthzid->bv_val, lauthzid->bv_len); ldap_memfree(lauthzid->bv_val); ldap_memfree(lauthzid); } } /* }}} */ #endif /* }}} */ /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_connect, 0, 0, 0) ZEND_ARG_INFO(0, hostname) ZEND_ARG_INFO(0, port) #ifdef HAVE_ORALDAP ZEND_ARG_INFO(0, wallet) ZEND_ARG_INFO(0, wallet_passwd) ZEND_ARG_INFO(0, authmode) #endif ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_resource, 0, 0, 1) ZEND_ARG_INFO(0, link_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_bind, 0, 0, 1) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, bind_rdn) ZEND_ARG_INFO(0, bind_password) ZEND_END_ARG_INFO() #ifdef HAVE_LDAP_SASL ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sasl_bind, 0, 0, 1) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, binddn) ZEND_ARG_INFO(0, password) ZEND_ARG_INFO(0, sasl_mech) ZEND_ARG_INFO(0, sasl_realm) ZEND_ARG_INFO(0, sasl_authz_id) ZEND_ARG_INFO(0, props) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_read, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, base_dn) ZEND_ARG_INFO(0, filter) ZEND_ARG_INFO(0, attributes) ZEND_ARG_INFO(0, attrsonly) ZEND_ARG_INFO(0, sizelimit) ZEND_ARG_INFO(0, timelimit) ZEND_ARG_INFO(0, deref) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_list, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, base_dn) ZEND_ARG_INFO(0, filter) ZEND_ARG_INFO(0, attributes) ZEND_ARG_INFO(0, attrsonly) ZEND_ARG_INFO(0, sizelimit) ZEND_ARG_INFO(0, timelimit) ZEND_ARG_INFO(0, deref) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_search, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, base_dn) ZEND_ARG_INFO(0, filter) ZEND_ARG_INFO(0, attributes) ZEND_ARG_INFO(0, attrsonly) ZEND_ARG_INFO(0, sizelimit) ZEND_ARG_INFO(0, timelimit) ZEND_ARG_INFO(0, deref) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_count_entries, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_entry, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_entry, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_entries, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_attribute, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_attribute, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_attributes, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_ARG_INFO(0, attribute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values_len, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_ARG_INFO(0, attribute) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_dn, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, result_entry_identifier) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_explode_dn, 0, 0, 2) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, with_attrib) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_dn2ufn, 0, 0, 1) ZEND_ARG_INFO(0, dn) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_add, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_delete, 0, 0, 2) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify_batch, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_ARRAY_INFO(0, modifications_info, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_add, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_replace, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_del, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_err2str, 0, 0, 1) ZEND_ARG_INFO(0, errno) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_compare, 0, 0, 4) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, attribute) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sort, 0, 0, 3) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, sortfilter) ZEND_END_ARG_INFO() #ifdef LDAP_CONTROL_PAGEDRESULTS ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, pagesize) ZEND_ARG_INFO(0, iscritical) ZEND_ARG_INFO(0, cookie) ZEND_END_ARG_INFO(); ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result_response, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(1, cookie) ZEND_ARG_INFO(1, estimated) ZEND_END_ARG_INFO(); #endif #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_rename, 0, 0, 5) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, dn) ZEND_ARG_INFO(0, newrdn) ZEND_ARG_INFO(0, newparent) ZEND_ARG_INFO(0, deleteoldrdn) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_option, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(1, retval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_option, 0, 0, 3) ZEND_ARG_INFO(0, link_identifier) ZEND_ARG_INFO(0, option) ZEND_ARG_INFO(0, newval) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_reference, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_reference, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, entry) ZEND_END_ARG_INFO() #ifdef HAVE_LDAP_PARSE_REFERENCE ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_reference, 0, 0, 3) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, entry) ZEND_ARG_INFO(1, referrals) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LDAP_PARSE_RESULT ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_result, 0, 0, 3) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(1, errcode) ZEND_ARG_INFO(1, matcheddn) ZEND_ARG_INFO(1, errmsg) ZEND_ARG_INFO(1, referrals) ZEND_END_ARG_INFO() #endif #endif #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC) ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_rebind_proc, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, callback) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_escape, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_ARG_INFO(0, ignore) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #ifdef STR_TRANSLATION ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_t61_to_8859, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_8859_to_t61, 0, 0, 1) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LDAP_EXTENDED_OPERATION_S ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_exop, 0, 0, 2) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, reqoid) ZEND_ARG_INFO(0, reqdata) ZEND_ARG_INFO(0, servercontrols) ZEND_ARG_INFO(1, retdata) ZEND_ARG_INFO(1, retoid) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LDAP_PASSWD_S ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_exop_passwd, 0, 0, 4) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, user) ZEND_ARG_INFO(0, oldpw) ZEND_ARG_INFO(0, newpw) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LDAP_WHOAMI_S ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_exop_whoami, 0, 0, 1) ZEND_ARG_INFO(0, link) ZEND_END_ARG_INFO() #endif #ifdef HAVE_LDAP_PARSE_EXTENDED_RESULT ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_exop, 0, 0, 4) ZEND_ARG_INFO(0, link) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(1, retdata) ZEND_ARG_INFO(1, retoid) ZEND_END_ARG_INFO() #endif /* }}} */ /* This is just a small subset of the functionality provided by the LDAP library. All the operations are synchronous. Referrals are not handled automatically. */ /* {{{ ldap_functions[] */ const zend_function_entry ldap_functions[] = { PHP_FE(ldap_connect, arginfo_ldap_connect) PHP_FALIAS(ldap_close, ldap_unbind, arginfo_ldap_resource) PHP_FE(ldap_bind, arginfo_ldap_bind) #ifdef HAVE_LDAP_SASL PHP_FE(ldap_sasl_bind, arginfo_ldap_sasl_bind) #endif PHP_FE(ldap_unbind, arginfo_ldap_resource) PHP_FE(ldap_read, arginfo_ldap_read) PHP_FE(ldap_list, arginfo_ldap_list) PHP_FE(ldap_search, arginfo_ldap_search) PHP_FE(ldap_free_result, arginfo_ldap_resource) PHP_FE(ldap_count_entries, arginfo_ldap_count_entries) PHP_FE(ldap_first_entry, arginfo_ldap_first_entry) PHP_FE(ldap_next_entry, arginfo_ldap_next_entry) PHP_FE(ldap_get_entries, arginfo_ldap_get_entries) PHP_FE(ldap_first_attribute, arginfo_ldap_first_attribute) PHP_FE(ldap_next_attribute, arginfo_ldap_next_attribute) PHP_FE(ldap_get_attributes, arginfo_ldap_get_attributes) PHP_FALIAS(ldap_get_values, ldap_get_values_len, arginfo_ldap_get_values) PHP_FE(ldap_get_values_len, arginfo_ldap_get_values_len) PHP_FE(ldap_get_dn, arginfo_ldap_get_dn) PHP_FE(ldap_explode_dn, arginfo_ldap_explode_dn) PHP_FE(ldap_dn2ufn, arginfo_ldap_dn2ufn) PHP_FE(ldap_add, arginfo_ldap_add) PHP_FE(ldap_delete, arginfo_ldap_delete) PHP_FE(ldap_modify_batch, arginfo_ldap_modify_batch) PHP_FALIAS(ldap_modify, ldap_mod_replace, arginfo_ldap_modify) /* additional functions for attribute based modifications, Gerrit Thomson */ PHP_FE(ldap_mod_add, arginfo_ldap_mod_add) PHP_FE(ldap_mod_replace, arginfo_ldap_mod_replace) PHP_FE(ldap_mod_del, arginfo_ldap_mod_del) /* end gjt mod */ PHP_FE(ldap_errno, arginfo_ldap_resource) PHP_FE(ldap_err2str, arginfo_ldap_err2str) PHP_FE(ldap_error, arginfo_ldap_resource) PHP_FE(ldap_compare, arginfo_ldap_compare) PHP_DEP_FE(ldap_sort, arginfo_ldap_sort) #if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP PHP_FE(ldap_rename, arginfo_ldap_rename) PHP_FE(ldap_get_option, arginfo_ldap_get_option) PHP_FE(ldap_set_option, arginfo_ldap_set_option) PHP_FE(ldap_first_reference, arginfo_ldap_first_reference) PHP_FE(ldap_next_reference, arginfo_ldap_next_reference) #ifdef HAVE_LDAP_PARSE_REFERENCE PHP_FE(ldap_parse_reference, arginfo_ldap_parse_reference) #endif #ifdef HAVE_LDAP_PARSE_RESULT PHP_FE(ldap_parse_result, arginfo_ldap_parse_result) #endif #ifdef HAVE_LDAP_START_TLS_S PHP_FE(ldap_start_tls, arginfo_ldap_resource) #endif #ifdef HAVE_LDAP_EXTENDED_OPERATION_S PHP_FE(ldap_exop, arginfo_ldap_exop) #endif #ifdef HAVE_LDAP_PASSWD_S PHP_FE(ldap_exop_passwd, arginfo_ldap_exop_passwd) #endif #ifdef HAVE_LDAP_WHOAMI_S PHP_FE(ldap_exop_whoami, arginfo_ldap_exop_whoami) #endif #ifdef HAVE_LDAP_PARSE_EXTENDED_RESULT PHP_FE(ldap_parse_exop, arginfo_ldap_parse_exop) #endif #endif #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC) PHP_FE(ldap_set_rebind_proc, arginfo_ldap_set_rebind_proc) #endif PHP_FE(ldap_escape, arginfo_ldap_escape) #ifdef STR_TRANSLATION PHP_FE(ldap_t61_to_8859, arginfo_ldap_t61_to_8859) PHP_FE(ldap_8859_to_t61, arginfo_ldap_8859_to_t61) #endif #ifdef LDAP_CONTROL_PAGEDRESULTS PHP_FE(ldap_control_paged_result, arginfo_ldap_control_paged_result) PHP_FE(ldap_control_paged_result_response, arginfo_ldap_control_paged_result_response) #endif PHP_FE_END }; /* }}} */ zend_module_entry ldap_module_entry = { /* {{{ */ STANDARD_MODULE_HEADER, "ldap", ldap_functions, PHP_MINIT(ldap), PHP_MSHUTDOWN(ldap), NULL, NULL, PHP_MINFO(ldap), PHP_LDAP_VERSION, PHP_MODULE_GLOBALS(ldap), PHP_GINIT(ldap), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
325397.c
/** ****************************************************************************** * @file stm32f30x_i2c_cpal_usercallback.c * @author MCD Application Team * @version V1.2.1 * @date 31-October-2014 * @brief This file provides all the CPAL UserCallback functions. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f30x_i2c_cpal.h" /* Private typedef -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /*------------------------------------------------------------------------------ CPAL User Callbacks implementations ------------------------------------------------------------------------------*/ /*=========== Timeout UserCallback ===========*/ /** * @brief User callback that manages the Timeout error * @param pDevInitStruct * @retval None. */ uint32_t CPAL_TIMEOUT_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { return CPAL_PASS; } /*=========== Transfer UserCallback ===========*/ /** * @brief Manages the End of Tx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_TXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages the End of Rx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_RXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages Tx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_TX_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages Rx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_RX_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages the End of DMA Tx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMATXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages the Half of DMA Tx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMATXHT_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages Error of DMA Tx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMATXTE_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages the End of DMA Rx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMARXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages the Half of DMA Rx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMARXHT_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief Manages Error of DMA Rx transfer event * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DMARXTE_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /*=========== Error UserCallback ===========*/ /** * @brief User callback that manages the I2C device errors * @note Make sure that the define USE_SINGLE_ERROR_CALLBACK is uncommented in * the cpal_conf.h file, otherwise this callback will not be functional * @param pDevInitStruct * @param DeviceError * @retval None */ /*void CPAL_I2C_ERR_UserCallback(CPAL_DevTypeDef pDevInstance, uint32_t DeviceError) { }*/ /** * @brief User callback that manages BERR I2C device errors * @note Make sure that the define USE_MULTIPLE_ERROR_CALLBACK is uncommented in * the cpal_conf.h file, otherwise this callback will not be functional * @param pDevInstance * @retval None */ /*void CPAL_I2C_BERR_UserCallback(CPAL_DevTypeDef pDevInstance) { }*/ /** * @brief User callback that manages ARLO I2C device errors * @note Make sure that the define USE_MULTIPLE_ERROR_CALLBACK is uncommented in * the cpal_conf.h file, otherwise this callback will not be functional * @param pDevInstance * @retval None */ /*void CPAL_I2C_ARLO_UserCallback(CPAL_DevTypeDef pDevInstance) { }*/ /** * @brief User callback that manages OVR I2C device errors * @note Make sure that the define USE_MULTIPLE_ERROR_CALLBACK is uncommented in * the cpal_conf.h file, otherwise this callback will not be functional * @param pDevInstance * @retval None */ /*void CPAL_I2C_OVR_UserCallback(CPAL_DevTypeDef pDevInstance) { }*/ /** * @brief User callback that manages AF I2C device errors. * @note Make sure that the define USE_MULTIPLE_ERROR_CALLBACK is uncommented in * the cpal_conf.h file, otherwise this callback will not be functional * @param pDevInstance * @retval None */ /*void CPAL_I2C_AF_UserCallback(CPAL_DevTypeDef pDevInstance) { }*/ /*=========== Addressing Mode UserCallback ===========*/ /** * @brief User callback that manage General Call Addressing mode * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_GENCALL_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief User callback that manage Dual Address Addressing mode * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_DUALF_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /*=========== Listen Mode UserCallback ===========*/ /** * @brief User callback that manage slave read operation. * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_SLAVE_READ_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /** * @brief User callback that manage slave write operation. * @param pDevInitStruct * @retval None */ /*void CPAL_I2C_SLAVE_WRITE_UserCallback(CPAL_InitTypeDef* pDevInitStruct) { }*/ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
624842.c
/* This Thread sends commands to MMC card(which here in is emulated by thread 1). Created by Devesh Dedhia **********************************************************************************/ #include"mmc_init.c" #include<stdio.h> #include"error.h" #define END_SIM \ asm(".word 0x22222222"); unsigned int Transaction_speed; unsigned int Access_time; void intialize_global_parameters(); int main(){ intialize_global_parameters(); ErrorCode_t Error= NO_ERROR; printf("Frequency set to 400KHz\n"); Error=SEND_GO_TO_IDLE_STATE(); if(Error!=NO_ERROR){ printf("ERROR in response for GO_TO_IDLE_STATE command\n\n"); return (1); } //printf("SUCCESS for GO_TO_IDLE_STATE command\n\n"); Error=SEND_OP_CONDITIONS(); if(Error!=NO_ERROR){ printf("ERROR in response for SEND_OP_CONDITIONS command\n"); return (1); } //printf("SUCCESS for SEND_OP_CONDITIONS command\n\n"); printf("MMC INITIALISED\n\n"); Error=SEND_READ_CSD_CMD(8); if(Error!=NO_ERROR){ printf("ERROR in response for SEND_READ_CSD command\n"); return (1); } //printf("SUCCESS for SEND_READ_CSD command\n\n"); Error=Retrive_CSD_parameters(); if(Error!=NO_ERROR){ printf("CSD parameters not retrived\n"); return (1); } Transaction_speed=Cal_Trans_speed(); if(Transaction_speed<20000) // check if the Transfer speed required by the card is less than 20MHz {printf("MMC card with a transfer speeds less than 20Mhz are not supported"); } Frequency_MMC=HIGH; printf("Frequency set to 20MHz"); Access_time=Cal_Access_time(20); if(Access_time>150000){ printf("MMC card with access times greater than 150000 clock cycles are not supported"); } Error=SET_BLOCK_LEN_CMD(); if(Error!=NO_ERROR){ printf("ERROR in response for SET_BLOCK_LEN_CMD command\n"); return (1); } Error=SEND_READ_BLOCK_CMD(10); if(Error!=NO_ERROR){ printf("ERROR in response for SEND_READ_BLOCK_CMD command\n"); return (1); } printf("A block of 512 bytes read\n"); END_SIM; return(0); } void intialize_global_parameters(){ *Readflag=1; *Writeflag=0; Frequency_MMC=LOW; }
142683.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "DSRC" * found in "J2735_201603_ASN_CC.asn" * `asn1c -gen-PER -fcompound-names -fincludes-quoted -fskeletons-copy` */ #include "ApproachOrLane.h" static asn_oer_constraints_t asn_OER_type_ApproachOrLane_constr_1 CC_NOTUSED = { { 0, 0 }, -1}; asn_per_constraints_t asn_PER_type_ApproachOrLane_constr_1 CC_NOTUSED = { { APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; asn_TYPE_member_t asn_MBR_ApproachOrLane_1[] = { { ATF_NOFLAGS, 0, offsetof(struct ApproachOrLane, choice.approach), (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_ApproachID, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "approach" }, { ATF_NOFLAGS, 0, offsetof(struct ApproachOrLane, choice.lane), (ASN_TAG_CLASS_CONTEXT | (1 << 2)), -1, /* IMPLICIT tag at current level */ &asn_DEF_LaneID, 0, { 0, 0, 0 }, 0, 0, /* No default value */ "lane" }, }; static const asn_TYPE_tag2member_t asn_MAP_ApproachOrLane_tag2el_1[] = { { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* approach */ { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 } /* lane */ }; asn_CHOICE_specifics_t asn_SPC_ApproachOrLane_specs_1 = { sizeof(struct ApproachOrLane), offsetof(struct ApproachOrLane, _asn_ctx), offsetof(struct ApproachOrLane, present), sizeof(((struct ApproachOrLane *)0)->present), asn_MAP_ApproachOrLane_tag2el_1, 2, /* Count of tags in the map */ 0, 0, -1 /* Extensions start */ }; asn_TYPE_descriptor_t asn_DEF_ApproachOrLane = { "ApproachOrLane", "ApproachOrLane", &asn_OP_CHOICE, 0, /* No effective tags (pointer) */ 0, /* No effective tags (count) */ 0, /* No tags (pointer) */ 0, /* No tags (count) */ { &asn_OER_type_ApproachOrLane_constr_1, &asn_PER_type_ApproachOrLane_constr_1, CHOICE_constraint }, asn_MBR_ApproachOrLane_1, 2, /* Elements count */ &asn_SPC_ApproachOrLane_specs_1 /* Additional specs */ };
505027.c
// rumor.c #include <ansi.h> inherit ITEM; inherit F_AUTOLOAD; void setup() {} void create() { set_name(HIM "謠言生成器" NOR, ({"rumor generator", "rumor"})); if (clonep()) set_default_object(__FILE__); else { set("unit", "架"); set("long", "這是一架看起來怪怪的儀器,塗得五顏六色,專供各類長舌人士造謠使用。\n"); set("value", 1); set("no_sell", 1); } setup(); } int query_autoload() { return 1; }
72057.c
/* * FreeRTOS V202104.00 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * https://www.FreeRTOS.org * https://github.com/FreeRTOS * */ /* Standard includes. */ #include "stdio.h" #include "string.h" /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "stream_buffer.h" /* Demo app includes. */ #include "StreamBufferDemo.h" /* The number of bytes of storage in the stream buffers used in this test. */ #define sbSTREAM_BUFFER_LENGTH_BYTES ( ( size_t ) 30 ) /* Stream buffer length one. */ #define sbSTREAM_BUFFER_LENGTH_ONE ( ( size_t ) 1 ) /* Start and end ASCII characters used in data sent to the buffers. */ #define sbASCII_SPACE 32 #define sbASCII_TILDA 126 /* Defines the number of tasks to create in this test and demo. */ #define sbNUMBER_OF_ECHO_CLIENTS ( 2 ) #define sbNUMBER_OF_SENDER_TASKS ( 2 ) /* Priority of the test tasks. The send and receive go from low to high * priority tasks, and from high to low priority tasks. */ #define sbLOWER_PRIORITY ( tskIDLE_PRIORITY ) #define sbHIGHER_PRIORITY ( tskIDLE_PRIORITY + 1 ) /* Block times used when sending and receiving from the stream buffers. */ #define sbRX_TX_BLOCK_TIME pdMS_TO_TICKS( 125UL ) /* A block time of 0 means "don't block". */ #define sbDONT_BLOCK ( 0 ) /* The trigger level sets the number of bytes that must be present in the * stream buffer before a task that is blocked on the stream buffer is moved out of * the Blocked state so it can read the bytes. */ #define sbTRIGGER_LEVEL_1 ( 1 ) /* The size of the stack allocated to the tasks that run as part of this demo/ * test. The stack size is over generous in most cases. */ #ifndef configSTREAM_BUFFER_SENDER_TASK_STACK_SIZE #define sbSTACK_SIZE ( configMINIMAL_STACK_SIZE + ( configMINIMAL_STACK_SIZE >> 1 ) ) #else #define sbSTACK_SIZE configSTREAM_BUFFER_SENDER_TASK_STACK_SIZE #endif #ifndef configSTREAM_BUFFER_SMALLER_TASK_STACK_SIZE #define sbSMALLER_STACK_SIZE sbSTACK_SIZE #else #define sbSMALLER_STACK_SIZE configSTREAM_BUFFER_SMALLER_TASK_STACK_SIZE #endif /*-----------------------------------------------------------*/ /* * Performs various tests that do not require multiple tasks to interact. */ static void prvSingleTaskTests( StreamBufferHandle_t xStreamBuffer ); /* * Tests sending and receiving various lengths of data via a stream buffer. * The echo client sends the data to the echo server, which then sends the * data back to the echo client, which checks it receives exactly what it * sent. */ static void prvEchoClient( void * pvParameters ); static void prvEchoServer( void * pvParameters ); /* * Tasks that send and receive to a stream buffer at a low priority and without * blocking, so the send and receive functions interleave in time as the tasks * are switched in and out. */ static void prvNonBlockingReceiverTask( void * pvParameters ); static void prvNonBlockingSenderTask( void * pvParameters ); /* Performs an assert() like check in a way that won't get removed when * performing a code coverage analysis. */ static void prvCheckExpectedState( BaseType_t xState ); /* * A task that creates a stream buffer with a specific trigger level, then * receives a string from an interrupt (the RTOS tick hook) byte by byte to * check it is only unblocked when the specified trigger level is reached. */ static void prvInterruptTriggerLevelTest( void * pvParameters ); #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) /* This file tests both statically and dynamically allocated stream buffers. * Allocate the structures and buffers to be used by the statically allocated * objects, which get used in the echo tests. */ static void prvReceiverTask( void * pvParameters ); static void prvSenderTask( void * pvParameters ); static StaticStreamBuffer_t xStaticStreamBuffers[ sbNUMBER_OF_ECHO_CLIENTS ]; static uint32_t ulSenderLoopCounters[ sbNUMBER_OF_SENDER_TASKS ] = { 0 }; #endif /* configSUPPORT_STATIC_ALLOCATION */ /* The +1 is to make the test logic easier as the function that calculates the * free space will return one less than the actual free space - adding a 1 to the * actual length makes it appear to the tests as if the free space is returned as * it might logically be expected. Returning 1 less than the actual free space is * fine as it can never result in an overrun. */ static uint8_t ucBufferStorage[ sbNUMBER_OF_SENDER_TASKS ][ sbSTREAM_BUFFER_LENGTH_BYTES + 1 ]; /*-----------------------------------------------------------*/ /* The buffers used by the echo client and server tasks. */ typedef struct ECHO_STREAM_BUFFERS { /* Handles to the data structures that describe the stream buffers. */ StreamBufferHandle_t xEchoClientBuffer; StreamBufferHandle_t xEchoServerBuffer; } EchoStreamBuffers_t; static volatile uint32_t ulEchoLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; /* The non-blocking tasks monitor their operation, and if no errors have been * found, increment ulNonBlockingRxCounter. xAreStreamBufferTasksStillRunning() * then checks ulNonBlockingRxCounter and only returns pdPASS if * ulNonBlockingRxCounter is still incrementing. */ static volatile uint32_t ulNonBlockingRxCounter = 0; /* The task that receives characters from the tick interrupt in order to test * different trigger levels monitors its own behaviour. If it has not detected any * error then it increments ulInterruptTriggerCounter to indicate to the check task * that it is still operating correctly. */ static volatile uint32_t ulInterruptTriggerCounter = 0UL; /* The stream buffer used from the tick interrupt. This sends one byte at a time * to a test task to test the trigger level operation. The variable is set to NULL * in between test runs. */ static volatile StreamBufferHandle_t xInterruptStreamBuffer = NULL; /* The data sent from the tick interrupt to the task that tests the trigger * level functionality. */ static const char * pcDataSentFromInterrupt = "0123456789"; /* Data that is longer than the buffer that is sent to the buffers as a stream * of bytes. Parts of which are written to the stream buffer to test writing * different lengths at different offsets, to many bytes, part streams, streams * that wrap, etc.. Two messages are defined to ensure left over data is not * accidentally read out of the buffer. */ static const char * pc55ByteString = "One two three four five six seven eight nine ten eleven"; static const char * pc54ByteString = "01234567891abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ"; /* Used to log the status of the tests contained within this file for reporting * to a monitoring task ('check' task). */ static BaseType_t xErrorStatus = pdPASS; /*-----------------------------------------------------------*/ void vStartStreamBufferTasks( void ) { StreamBufferHandle_t xStreamBuffer; /* The echo servers sets up the stream buffers before creating the echo * client tasks. One set of tasks has the server as the higher priority, and * the other has the client as the higher priority. */ xTaskCreate( prvEchoServer, "1StrEchoServer", sbSMALLER_STACK_SIZE, NULL, sbHIGHER_PRIORITY, NULL ); xTaskCreate( prvEchoServer, "2StrEchoServer", sbSMALLER_STACK_SIZE, NULL, sbLOWER_PRIORITY, NULL ); /* The non blocking tasks run continuously and will interleave with each * other, so must be created at the lowest priority. The stream buffer they * use is created and passed in using the task's parameter. */ xStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); xTaskCreate( prvNonBlockingReceiverTask, "StrNonBlkRx", configMINIMAL_STACK_SIZE, ( void * ) xStreamBuffer, tskIDLE_PRIORITY, NULL ); xTaskCreate( prvNonBlockingSenderTask, "StrNonBlkTx", configMINIMAL_STACK_SIZE, ( void * ) xStreamBuffer, tskIDLE_PRIORITY, NULL ); /* The task that receives bytes from an interrupt to test that it unblocks * at a specific trigger level must run at a high priority to minimise the risk * of it receiving more characters before it can execute again after being * unblocked. */ xTaskCreate( prvInterruptTriggerLevelTest, "StrTrig", configMINIMAL_STACK_SIZE, NULL, configMAX_PRIORITIES - 1, NULL ); #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) { /* The sender tasks set up the stream buffers before creating the * receiver tasks. Priorities must be 0 and 1 as the priority is used to * index into the xStaticStreamBuffers and ucBufferStorage arrays. */ xTaskCreate( prvSenderTask, "Str1Sender", sbSMALLER_STACK_SIZE, NULL, sbHIGHER_PRIORITY, NULL ); xTaskCreate( prvSenderTask, "Str2Sender", sbSMALLER_STACK_SIZE, NULL, sbLOWER_PRIORITY, NULL ); } #endif /* configSUPPORT_STATIC_ALLOCATION */ } /*-----------------------------------------------------------*/ static void prvCheckExpectedState( BaseType_t xState ) { configASSERT( xState ); if( xState == pdFAIL ) { xErrorStatus = pdFAIL; } } /*-----------------------------------------------------------*/ static void prvSingleTaskTests( StreamBufferHandle_t xStreamBuffer ) { size_t xReturned, xItem, xExpected, xExpectedSpaces, xExpectedBytes; const size_t xMax6ByteMessages = sbSTREAM_BUFFER_LENGTH_BYTES / 6; const size_t xTrueSize = ( sizeof( ucBufferStorage ) / sbNUMBER_OF_SENDER_TASKS ); const size_t x6ByteLength = 6, x17ByteLength = 17, xFullBufferSize = sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2; uint8_t * pucFullBuffer, * pucData, * pucReadData; TickType_t xTimeBeforeCall, xTimeAfterCall; const TickType_t xBlockTime = pdMS_TO_TICKS( 15 ), xAllowableMargin = pdMS_TO_TICKS( 3 ), xMinimalBlockTime = 2; UBaseType_t uxOriginalPriority; /* Remove warning in case configASSERT() is not defined. */ ( void ) xAllowableMargin; /* To minimise stack and heap usage a full size buffer is allocated from the * heap, then buffers which hold smaller amounts of data are overlayed with the * larger buffer - just make sure not to use both at once! */ pucFullBuffer = pvPortMalloc( xFullBufferSize ); configASSERT( pucFullBuffer ); pucData = pucFullBuffer; pucReadData = pucData + x17ByteLength; /* Nothing has been added or removed yet, so expect the free space to be * exactly as created. Head and tail are both at 0. */ xExpectedSpaces = sbSTREAM_BUFFER_LENGTH_BYTES; xExpectedBytes = 0; xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Add a single item - number of bytes available should go up by one and spaces * available down by one. Head is in front of tail. */ xExpectedSpaces--; xExpectedBytes++; xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == sizeof( *pucData ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Now fill the buffer by adding another 29 bytes. Head is 30 tail is at 0. */ xExpectedSpaces -= 29; xExpectedBytes += 29; xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, ( sbSTREAM_BUFFER_LENGTH_BYTES - 1 ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == ( sbSTREAM_BUFFER_LENGTH_BYTES - 1 ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); /* Should not be able to add another byte now. */ xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == ( size_t ) 0 ); /* Remove a byte so the tail pointer moves off 0. Head pointer remains at the * end of the buffer. */ xExpectedSpaces += 1; xExpectedBytes -= 1; xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == sizeof( *pucData ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Should be able to add another byte to fill the buffer again now. */ xExpectedSpaces -= 1; xExpectedBytes += 1; xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == sizeof( *pucData ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); /* Now the head pointer is behind the tail pointer. Read another 29 bytes so * the tail pointer moves to the end of the buffer. */ xExpectedSpaces += 29; xExpectedBytes -= 29; xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, ( size_t ) 29, ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == ( size_t ) 29 ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Read out one more byte to wrap the tail back around to the start, to get back * to where we started. */ xExpectedSpaces += 1; xExpectedBytes -= 1; xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, sizeof( *pucData ), ( TickType_t ) 0 ); prvCheckExpectedState( xReturned == sizeof( *pucData ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedBytes ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Try filling the message buffer in one write, blocking indefinitely. Expect to * have written one byte less. */ xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, xTrueSize, portMAX_DELAY ); xExpectedSpaces = ( size_t ) 0; prvCheckExpectedState( xReturned == ( xTrueSize - ( size_t ) 1 ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == xExpectedSpaces ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); /* Empty the buffer again ready for the rest of the tests. Again block * indefinitely to ensure reading more than there can possible be won't lock this * task up, so expect to actually receive one byte less than requested. */ xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucData, xTrueSize, portMAX_DELAY ); prvCheckExpectedState( xReturned == ( xTrueSize - ( size_t ) 1 ) ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == sbSTREAM_BUFFER_LENGTH_BYTES ); xExpected = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == ( size_t ) 0 ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* The buffer is 30 bytes long. 6 5 byte messages should fit before the * buffer is completely full. */ xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) { prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Generate recognisable data to write to the buffer. This is just * ascii characters that shows which loop iteration the data was written * in. The 'FromISR' version is used to give it some exercise as a block * time is not used, so the call must be inside a critical section so it * runs with ports that don't support interrupt nesting (and therefore * don't have interrupt safe critical sections). */ memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); taskENTER_CRITICAL(); { xReturned = xStreamBufferSendFromISR( xStreamBuffer, ( void * ) pucData, x6ByteLength, NULL ); } taskEXIT_CRITICAL(); prvCheckExpectedState( xReturned == x6ByteLength ); /* The space in the buffer will have reduced by the amount of user data * written into the buffer. */ xExpected -= x6ByteLength; xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == xExpected ); xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); /* +1 as it is zero indexed. */ prvCheckExpectedState( xReturned == ( ( xItem + 1 ) * x6ByteLength ) ); } /* Now the buffer should be full, and attempting to add anything should fail. */ prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), sbDONT_BLOCK ); prvCheckExpectedState( xReturned == 0 ); /* Adding with a timeout should also fail after the appropriate time. The * priority is temporarily boosted in this part of the test to keep the * allowable margin to a minimum. */ uxOriginalPriority = uxTaskPriorityGet( NULL ); vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); xTimeBeforeCall = xTaskGetTickCount(); xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, sizeof( pucData[ 0 ] ), xBlockTime ); xTimeAfterCall = xTaskGetTickCount(); vTaskPrioritySet( NULL, uxOriginalPriority ); prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) >= xBlockTime ); prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) < ( xBlockTime + xAllowableMargin ) ); prvCheckExpectedState( xReturned == 0 ); /* The buffer is now full of data in the form "000000", "111111", etc. Make * sure the data is read out as expected. */ for( xItem = 0; xItem < xMax6ByteMessages; xItem++ ) { /* Generate the data that is expected to be read out for this loop * iteration. */ memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x6ByteLength ); /* Read the next 6 bytes out. The 'FromISR' version is used to give it * some exercise as a block time is not used, so a it must be called from * a critical section so this will work on ports that don't support * interrupt nesting (so don't have interrupt safe critical sections). */ taskENTER_CRITICAL(); { xReturned = xStreamBufferReceiveFromISR( xStreamBuffer, ( void * ) pucReadData, x6ByteLength, NULL ); } taskEXIT_CRITICAL(); prvCheckExpectedState( xReturned == x6ByteLength ); /* Does the data read out match that expected? */ prvCheckExpectedState( memcmp( ( void * ) pucData, ( void * ) pucReadData, x6ByteLength ) == 0 ); /* The space in the buffer will have increased by the amount of user * data removed from the buffer. */ xExpected += x6ByteLength; xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == xExpected ); xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == ( sbSTREAM_BUFFER_LENGTH_BYTES - xExpected ) ); } /* The buffer should be empty again. */ prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); xExpected = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xExpected == sbSTREAM_BUFFER_LENGTH_BYTES ); /* Reading with a timeout should also fail after the appropriate time. The * priority is temporarily boosted in this part of the test to keep the * allowable margin to a minimum. */ vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); xTimeBeforeCall = xTaskGetTickCount(); xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucReadData, x6ByteLength, xBlockTime ); xTimeAfterCall = xTaskGetTickCount(); vTaskPrioritySet( NULL, uxOriginalPriority ); prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) >= xBlockTime ); prvCheckExpectedState( ( ( TickType_t ) ( xTimeAfterCall - xTimeBeforeCall ) ) < ( xBlockTime + xAllowableMargin ) ); prvCheckExpectedState( xReturned == 0 ); /* In the next loop 17 bytes are written to then read out on each * iteration. As 30 is not divisible by 17 the data will wrap around. */ xExpected = sbSTREAM_BUFFER_LENGTH_BYTES - x17ByteLength; for( xItem = 0; xItem < 100; xItem++ ) { /* Generate recognisable data to write to the queue. This is just * ascii characters that shows which loop iteration the data was written * in. */ memset( ( void * ) pucData, ( ( int ) '0' ) + ( int ) xItem, x17ByteLength ); xReturned = xStreamBufferSend( xStreamBuffer, ( void * ) pucData, x17ByteLength, sbDONT_BLOCK ); prvCheckExpectedState( xReturned == x17ByteLength ); /* The space in the buffer will have reduced by the amount of user data * written into the buffer. */ xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == xExpected ); xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == x17ByteLength ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); /* Read the 17 bytes out again. */ xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucReadData, x17ByteLength, sbDONT_BLOCK ); prvCheckExpectedState( xReturned == x17ByteLength ); /* Does the data read out match that expected? */ prvCheckExpectedState( memcmp( ( void * ) pucData, ( void * ) pucReadData, x17ByteLength ) == 0 ); /* Full buffer space available again. */ xReturned = xStreamBufferSpacesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); xReturned = xStreamBufferBytesAvailable( xStreamBuffer ); prvCheckExpectedState( xReturned == 0 ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); } /* Fill the buffer with one message, check it is full, then read it back * again and check the correct data is received. */ xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES, sbDONT_BLOCK ); xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES, sbDONT_BLOCK ); prvCheckExpectedState( memcmp( pc55ByteString, pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); /* Fill the buffer one bytes at a time. */ for( xItem = 0; xItem < sbSTREAM_BUFFER_LENGTH_BYTES; xItem++ ) { /* Block time is only for test coverage, the task should never actually * block here. */ xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc54ByteString[ xItem ] ), sizeof( char ), sbRX_TX_BLOCK_TIME ); } /* The buffer should now be full. */ prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); /* Read the message out in one go, even though it was written in individual * bytes. Try reading much more data than is actually available to ensure only * the available bytes are returned (otherwise this read will write outside of * the memory allocated anyway!). */ xReturned = xStreamBufferReceive( xStreamBuffer, pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, sbRX_TX_BLOCK_TIME ); prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); prvCheckExpectedState( memcmp( ( const void * ) pc54ByteString, ( const void * ) pucFullBuffer, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); /* Now do the opposite, write in one go and read out in single bytes. */ xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES, sbRX_TX_BLOCK_TIME ); prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferBytesAvailable( xStreamBuffer ) == sbSTREAM_BUFFER_LENGTH_BYTES ); prvCheckExpectedState( xStreamBufferSpacesAvailable( xStreamBuffer ) == 0 ); /* Read from the buffer one byte at a time. */ for( xItem = 0; xItem < sbSTREAM_BUFFER_LENGTH_BYTES; xItem++ ) { /* Block time is only for test coverage, the task should never actually * block here. */ xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, sizeof( char ), sbRX_TX_BLOCK_TIME ); prvCheckExpectedState( pc55ByteString[ xItem ] == pucFullBuffer[ 0 ] ); } prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); /* Try writing more bytes than there is space. */ vTaskPrioritySet( NULL, configMAX_PRIORITIES - 1 ); xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, xMinimalBlockTime ); vTaskPrioritySet( NULL, uxOriginalPriority ); prvCheckExpectedState( xReturned == sbSTREAM_BUFFER_LENGTH_BYTES ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdTRUE ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdFALSE ); /* No space now though. */ xReturned = xStreamBufferSend( xStreamBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES * ( size_t ) 2, xMinimalBlockTime ); prvCheckExpectedState( xReturned == 0 ); /* Ensure data was written as expected even when there was an attempt to * write more than was available. This also tries to read more bytes than are * available. */ xReturned = xStreamBufferReceive( xStreamBuffer, ( void * ) pucFullBuffer, xFullBufferSize, xMinimalBlockTime ); prvCheckExpectedState( memcmp( ( const void * ) pucFullBuffer, ( const void * ) pc54ByteString, sbSTREAM_BUFFER_LENGTH_BYTES ) == 0 ); prvCheckExpectedState( xStreamBufferIsFull( xStreamBuffer ) == pdFALSE ); prvCheckExpectedState( xStreamBufferIsEmpty( xStreamBuffer ) == pdTRUE ); /* Clean up with data in the buffer to ensure the tests that follow don't * see the data (the data should be discarded). */ ( void ) xStreamBufferSend( xStreamBuffer, ( const void * ) pc55ByteString, sbSTREAM_BUFFER_LENGTH_BYTES / ( size_t ) 2, sbDONT_BLOCK ); vPortFree( pucFullBuffer ); xStreamBufferReset( xStreamBuffer ); } /*-----------------------------------------------------------*/ static void prvNonBlockingSenderTask( void * pvParameters ) { StreamBufferHandle_t xStreamBuffer; size_t xNextChar = 0, xBytesToSend, xBytesActuallySent; const size_t xStringLength = strlen( pc54ByteString ); /* In this case the stream buffer has already been created and is passed * into the task using the task's parameter. */ xStreamBuffer = ( StreamBufferHandle_t ) pvParameters; /* Keep sending the string to the stream buffer as many bytes as possible in * each go. Doesn't block so calls can interleave with the non-blocking * receives performed by prvNonBlockingReceiverTask(). */ for( ; ; ) { /* The whole string cannot be sent at once, so xNextChar is an index to * the position within the string that has been sent so far. How many * bytes are there left to send before the end of the string? */ xBytesToSend = xStringLength - xNextChar; /* Attempt to send right up to the end of the string. */ xBytesActuallySent = xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc54ByteString[ xNextChar ] ), xBytesToSend, sbDONT_BLOCK ); prvCheckExpectedState( xBytesActuallySent <= xBytesToSend ); /* Move the index up the string to the next character to be sent, * wrapping if the end of the string has been reached. */ xNextChar += xBytesActuallySent; prvCheckExpectedState( xNextChar <= xStringLength ); if( xNextChar == xStringLength ) { xNextChar = 0; } } } /*-----------------------------------------------------------*/ static void prvNonBlockingReceiverTask( void * pvParameters ) { StreamBufferHandle_t xStreamBuffer; size_t xNextChar = 0, xReceiveLength, xBytesToTest, xStartIndex; const size_t xStringLength = strlen( pc54ByteString ); char cRxString[ 12 ]; /* Holds received characters. */ BaseType_t xNonBlockingReceiveError = pdFALSE; /* In this case the stream buffer has already been created and is passed * into the task using the task's parameter. */ xStreamBuffer = ( StreamBufferHandle_t ) pvParameters; /* Expects to receive the pc54ByteString over and over again. Sends and * receives are not blocking so will interleave. */ for( ; ; ) { /* Attempt to receive as many bytes as possible, up to the limit of the * Rx buffer size. */ xReceiveLength = xStreamBufferReceive( xStreamBuffer, ( void * ) cRxString, sizeof( cRxString ), sbDONT_BLOCK ); if( xReceiveLength > 0 ) { /* xNextChar is the index into pc54ByteString that has been received * already. If xReceiveLength bytes are added to that, will it go off * the end of the string? If so, then first test up to the end of the * string, then go back to the start of pc54ByteString to test the * remains of the received data. */ xBytesToTest = xReceiveLength; if( ( xNextChar + xBytesToTest ) > xStringLength ) { /* Cap to test the received data to the end of the string. */ xBytesToTest = xStringLength - xNextChar; if( memcmp( ( const void * ) &( pc54ByteString[ xNextChar ] ), ( const void * ) cRxString, xBytesToTest ) != 0 ) { xNonBlockingReceiveError = pdTRUE; } /* Then move back to the start of the string to test the * remaining received bytes. */ xNextChar = 0; xStartIndex = xBytesToTest; xBytesToTest = xReceiveLength - xBytesToTest; } else { /* The string didn't wrap in the buffer, so start comparing from * the start of the received data. */ xStartIndex = 0; } /* Test the received bytes are as expected, then move the index * along the string to the next expected char to receive. */ if( memcmp( ( const void * ) &( pc54ByteString[ xNextChar ] ), ( const void * ) &( cRxString[ xStartIndex ] ), xBytesToTest ) != 0 ) { xNonBlockingReceiveError = pdTRUE; } if( xNonBlockingReceiveError == pdFALSE ) { /* No errors detected so increment the counter that lets the * check task know this test is still functioning correctly. */ ulNonBlockingRxCounter++; } xNextChar += xBytesToTest; if( xNextChar >= xStringLength ) { xNextChar = 0; } } } } /*-----------------------------------------------------------*/ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) static void prvSenderTask( void * pvParameters ) { StreamBufferHandle_t xStreamBuffer, xTempStreamBuffer; static uint8_t ucTempBuffer[ 10 ]; /* Just used to exercise stream buffer creating and deletion. */ const TickType_t xTicksToWait = sbRX_TX_BLOCK_TIME, xShortDelay = pdMS_TO_TICKS( 50 ); StaticStreamBuffer_t xStaticStreamBuffer; size_t xNextChar = 0, xBytesToSend, xBytesActuallySent; const size_t xStringLength = strlen( pc55ByteString ); /* The task's priority is used as an index into the loop counters used to * indicate this task is still running. */ UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); /* Make sure a change in priority does not inadvertently result in an * invalid array index. */ prvCheckExpectedState( uxIndex < sbNUMBER_OF_ECHO_CLIENTS ); /* Avoid compiler warnings about unused parameters. */ ( void ) pvParameters; xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ) / sbNUMBER_OF_SENDER_TASKS, /* The number of bytes in each buffer in the array. */ sbTRIGGER_LEVEL_1, /* The number of bytes to be in the buffer before a task blocked to wait for data is unblocked. */ &( ucBufferStorage[ uxIndex ][ 0 ] ), /* The address of the buffer to use within the array. */ &( xStaticStreamBuffers[ uxIndex ] ) ); /* The static stream buffer structure to use within the array. */ /* Now the stream buffer has been created the receiver task can be * created. If this sender task has the higher priority then the receiver * task is created at the lower priority - if this sender task has the * lower priority then the receiver task is created at the higher * priority. */ if( uxTaskPriorityGet( NULL ) == sbLOWER_PRIORITY ) { /* Here prvSingleTaskTests() performs various tests on a stream buffer * that was created statically. */ prvSingleTaskTests( xStreamBuffer ); xTaskCreate( prvReceiverTask, "StrReceiver", sbSMALLER_STACK_SIZE, ( void * ) xStreamBuffer, sbHIGHER_PRIORITY, NULL ); } else { xTaskCreate( prvReceiverTask, "StrReceiver", sbSMALLER_STACK_SIZE, ( void * ) xStreamBuffer, sbLOWER_PRIORITY, NULL ); } for( ; ; ) { /* The whole string cannot be sent at once, so xNextChar is an index * to the position within the string that has been sent so far. How * many bytes are there left to send before the end of the string? */ xBytesToSend = xStringLength - xNextChar; /* Attempt to send right up to the end of the string. */ xBytesActuallySent = xStreamBufferSend( xStreamBuffer, ( const void * ) &( pc55ByteString[ xNextChar ] ), xBytesToSend, xTicksToWait ); prvCheckExpectedState( xBytesActuallySent <= xBytesToSend ); /* Move the index up the string to the next character to be sent, * wrapping if the end of the string has been reached. */ xNextChar += xBytesActuallySent; prvCheckExpectedState( xNextChar <= xStringLength ); if( xNextChar == xStringLength ) { xNextChar = 0; } /* Increment a loop counter so a check task can tell this task is * still running as expected. */ ulSenderLoopCounters[ uxIndex ]++; if( uxTaskPriorityGet( NULL ) == sbHIGHER_PRIORITY ) { /* Allow other tasks to run. */ vTaskDelay( xShortDelay ); } /* This stream buffer is just created and deleted to ensure no * issues when attempting to delete a stream buffer that was * created using statically allocated memory. To save stack space * the buffer is set to point to the pc55ByteString, which is a const * string, but no data is written into the buffer so any valid address * will do. */ xTempStreamBuffer = xStreamBufferCreateStatic( sizeof( ucTempBuffer ), sbTRIGGER_LEVEL_1, ucTempBuffer, &xStaticStreamBuffer ); xStreamBufferReset( xTempStreamBuffer ); vStreamBufferDelete( xTempStreamBuffer ); } } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) static void prvReceiverTask( void * pvParameters ) { StreamBufferHandle_t const pxStreamBuffer = ( StreamBufferHandle_t ) pvParameters; char cRxString[ 12 ]; /* Large enough to hold a 32-bit number in ASCII. */ const TickType_t xTicksToWait = pdMS_TO_TICKS( 5UL ); const size_t xStringLength = strlen( pc55ByteString ); size_t xNextChar = 0, xReceivedLength, xBytesToReceive; for( ; ; ) { /* Attempt to receive the number of bytes to the end of the string, * or the number of byte that can be placed into the rx buffer, * whichever is smallest. */ xBytesToReceive = configMIN( ( xStringLength - xNextChar ), sizeof( cRxString ) ); do { xReceivedLength = xStreamBufferReceive( pxStreamBuffer, ( void * ) cRxString, xBytesToReceive, xTicksToWait ); } while( xReceivedLength == 0 ); /* Ensure the received string matches the expected string. */ prvCheckExpectedState( memcmp( ( void * ) cRxString, ( const void * ) &( pc55ByteString[ xNextChar ] ), xReceivedLength ) == 0 ); /* Move the index into the string up to the end of the bytes * received so far - wrapping if the end of the string has been * reached. */ xNextChar += xReceivedLength; if( xNextChar >= xStringLength ) { xNextChar = 0; } } } #endif /* configSUPPORT_STATIC_ALLOCATION */ /*-----------------------------------------------------------*/ static void prvEchoClient( void * pvParameters ) { size_t xSendLength = 0, ux; char * pcStringToSend, * pcStringReceived, cNextChar = sbASCII_SPACE; const TickType_t xTicksToWait = pdMS_TO_TICKS( 50 ); StreamBufferHandle_t xTempStreamBuffer; /* The task's priority is used as an index into the loop counters used to * indicate this task is still running. */ UBaseType_t uxIndex = uxTaskPriorityGet( NULL ); /* Pointers to the client and server stream buffers are passed into this task * using the task's parameter. */ EchoStreamBuffers_t * pxStreamBuffers = ( EchoStreamBuffers_t * ) pvParameters; /* Prevent compiler warnings. */ ( void ) pvParameters; /* Create the buffer into which strings to send to the server will be * created, and the buffer into which strings echoed back from the server will * be copied. */ pcStringToSend = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); pcStringReceived = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); configASSERT( pcStringToSend ); configASSERT( pcStringReceived ); for( ; ; ) { /* Generate the length of the next string to send. */ xSendLength++; /* The stream buffer is being used to hold variable length data, so * each data item requires sizeof( size_t ) bytes to hold the data's * length, hence the sizeof() in the if() condition below. */ if( xSendLength > ( sbSTREAM_BUFFER_LENGTH_BYTES - sizeof( size_t ) ) ) { /* Back to a string length of 1. */ xSendLength = sizeof( char ); } memset( pcStringToSend, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); for( ux = 0; ux < xSendLength; ux++ ) { pcStringToSend[ ux ] = cNextChar; cNextChar++; if( cNextChar > sbASCII_TILDA ) { cNextChar = sbASCII_SPACE; } } /* Send the generated string to the buffer. */ do { ux = xStreamBufferSend( pxStreamBuffers->xEchoClientBuffer, ( void * ) pcStringToSend, xSendLength, xTicksToWait ); } while( ux == 0 ); /* Wait for the string to be echoed back. */ memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); xStreamBufferReceive( pxStreamBuffers->xEchoServerBuffer, ( void * ) pcStringReceived, xSendLength, portMAX_DELAY ); prvCheckExpectedState( strcmp( pcStringToSend, pcStringReceived ) == 0 ); /* Maintain a count of the number of times this code executes so a * check task can determine if this task is still functioning as * expected or not. As there are two client tasks, and the priorities * used are 0 and 1, the task's priority is used as an index into the * loop count array. */ ulEchoLoopCounters[ uxIndex ]++; /* This stream buffer is just created and deleted to ensure no memory * leaks. */ xTempStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); vStreamBufferDelete( xTempStreamBuffer ); /* The following are tests for a stream buffer of size one. */ /* Create a buffer of size one. */ xTempStreamBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_ONE, sbTRIGGER_LEVEL_1 ); /* Ensure that the buffer was created successfully. */ configASSERT( xTempStreamBuffer ); /* Send one byte to the buffer. */ ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 1, sbDONT_BLOCK ); /* Ensure that the byte was sent successfully. */ configASSERT( ux == 1 ); /* Try sending another byte to the buffer. */ ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 1, sbDONT_BLOCK ); /* Make sure that send failed as the buffer is full. */ configASSERT( ux == 0 ); /* Receive one byte from the buffer. */ memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 1, sbDONT_BLOCK ); /* Ensure that the receive was successful. */ configASSERT( ux == 1 ); /* Ensure that the correct data was received. */ configASSERT( pcStringToSend[ 0 ] == pcStringReceived[ 0 ] ); /* Try receiving another byte from the buffer. */ ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 1, sbDONT_BLOCK ); /* Ensure that the receive failed as the buffer is empty. */ configASSERT( ux == 0 ); /* Try sending two bytes to the buffer. Since the size of the * buffer is one, we must not be able to send more than one. */ ux = xStreamBufferSend( xTempStreamBuffer, ( void * ) pcStringToSend, ( size_t ) 2, sbDONT_BLOCK ); /* Ensure that only one byte was sent. */ configASSERT( ux == 1 ); /* Try receiving two bytes from the buffer. Since the size of the * buffer is one, we must not be able to get more than one. */ memset( pcStringReceived, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); ux = xStreamBufferReceive( xTempStreamBuffer, ( void * ) pcStringReceived, ( size_t ) 2, sbDONT_BLOCK ); /* Ensure that only one byte was received. */ configASSERT( ux == 1 ); /* Ensure that the correct data was received. */ configASSERT( pcStringToSend[ 0 ] == pcStringReceived[ 0 ] ); /* Delete the buffer. */ vStreamBufferDelete( xTempStreamBuffer ); } } /*-----------------------------------------------------------*/ static void prvEchoServer( void * pvParameters ) { size_t xReceivedLength; char * pcReceivedString; EchoStreamBuffers_t xStreamBuffers; TickType_t xTimeOnEntering; const TickType_t xTicksToBlock = pdMS_TO_TICKS( 350UL ); /* Prevent compiler warnings about unused parameters. */ ( void ) pvParameters; /* Create the stream buffer used to send data from the client to the server, * and the stream buffer used to echo the data from the server back to the * client. */ xStreamBuffers.xEchoClientBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); xStreamBuffers.xEchoServerBuffer = xStreamBufferCreate( sbSTREAM_BUFFER_LENGTH_BYTES, sbTRIGGER_LEVEL_1 ); configASSERT( xStreamBuffers.xEchoClientBuffer ); configASSERT( xStreamBuffers.xEchoServerBuffer ); /* Create the buffer into which received strings will be copied. */ pcReceivedString = ( char * ) pvPortMalloc( sbSTREAM_BUFFER_LENGTH_BYTES ); configASSERT( pcReceivedString ); /* Don't expect to receive anything yet! */ xTimeOnEntering = xTaskGetTickCount(); xReceivedLength = xStreamBufferReceive( xStreamBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, sbSTREAM_BUFFER_LENGTH_BYTES, xTicksToBlock ); prvCheckExpectedState( ( ( TickType_t ) ( xTaskGetTickCount() - xTimeOnEntering ) ) >= xTicksToBlock ); prvCheckExpectedState( xReceivedLength == 0 ); /* Now the stream buffers have been created the echo client task can be * created. If this server task has the higher priority then the client task * is created at the lower priority - if this server task has the lower * priority then the client task is created at the higher priority. */ if( uxTaskPriorityGet( NULL ) == sbLOWER_PRIORITY ) { xTaskCreate( prvEchoClient, "EchoClient", sbSMALLER_STACK_SIZE, ( void * ) &xStreamBuffers, sbHIGHER_PRIORITY, NULL ); } else { /* Here prvSingleTaskTests() performs various tests on a stream buffer * that was created dynamically. */ prvSingleTaskTests( xStreamBuffers.xEchoClientBuffer ); xTaskCreate( prvEchoClient, "EchoClient", sbSMALLER_STACK_SIZE, ( void * ) &xStreamBuffers, sbLOWER_PRIORITY, NULL ); } for( ; ; ) { memset( pcReceivedString, 0x00, sbSTREAM_BUFFER_LENGTH_BYTES ); /* Has any data been sent by the client? */ xReceivedLength = xStreamBufferReceive( xStreamBuffers.xEchoClientBuffer, ( void * ) pcReceivedString, sbSTREAM_BUFFER_LENGTH_BYTES, portMAX_DELAY ); /* Should always receive data as max delay was used. */ prvCheckExpectedState( xReceivedLength > 0 ); /* Echo the received data back to the client. */ xStreamBufferSend( xStreamBuffers.xEchoServerBuffer, ( void * ) pcReceivedString, xReceivedLength, portMAX_DELAY ); } } /*-----------------------------------------------------------*/ void vPeriodicStreamBufferProcessing( void ) { static size_t xNextChar = 0; BaseType_t xHigherPriorityTaskWoken = pdFALSE; /* Called from the tick interrupt hook. If the global stream buffer * variable is not NULL then the prvInterruptTriggerTest() task expects a byte * to be sent to the stream buffer on each tick interrupt. */ if( xInterruptStreamBuffer != NULL ) { /* One character from the pcDataSentFromInterrupt string is sent on each * interrupt. The task blocked on the stream buffer should not be * unblocked until the defined trigger level is hit. */ xStreamBufferSendFromISR( xInterruptStreamBuffer, ( const void * ) &( pcDataSentFromInterrupt[ xNextChar ] ), sizeof( char ), &xHigherPriorityTaskWoken ); if( xNextChar < strlen( pcDataSentFromInterrupt ) ) { xNextChar++; } } else { /* Start at the beginning of the string being sent again. */ xNextChar = 0; } } /*-----------------------------------------------------------*/ static void prvInterruptTriggerLevelTest( void * pvParameters ) { StreamBufferHandle_t xStreamBuffer; size_t xTriggerLevel = 1, xBytesReceived; const size_t xStreamBufferSizeBytes = ( size_t ) 9, xMaxTriggerLevel = ( size_t ) 7, xMinTriggerLevel = ( size_t ) 2; const TickType_t xReadBlockTime = 5, xCycleBlockTime = pdMS_TO_TICKS( 100 ); uint8_t ucRxData[ 9 ]; BaseType_t xErrorDetected = pdFALSE; #ifndef configSTREAM_BUFFER_TRIGGER_LEVEL_TEST_MARGIN const size_t xAllowableMargin = ( size_t ) 0; #else const size_t xAllowableMargin = ( size_t ) configSTREAM_BUFFER_TRIGGER_LEVEL_TEST_MARGIN; #endif /* Remove compiler warning about unused parameter. */ ( void ) pvParameters; for( ; ; ) { for( xTriggerLevel = xMinTriggerLevel; xTriggerLevel < xMaxTriggerLevel; xTriggerLevel++ ) { /* This test is very time sensitive so delay at the beginning to ensure * the rest of the system is up and running before starting. Delay between * each loop to ensure the interrupt that sends to the stream buffer * detects it needs to start sending from the start of the strin again.. */ vTaskDelay( xCycleBlockTime ); /* Create the stream buffer that will be used from inside the tick * interrupt. */ memset( ucRxData, 0x00, sizeof( ucRxData ) ); xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); configASSERT( xStreamBuffer ); /* Now the stream buffer has been created it can be assigned to the * file scope variable, which will allow the tick interrupt to start * using it. */ taskENTER_CRITICAL(); { xInterruptStreamBuffer = xStreamBuffer; } taskEXIT_CRITICAL(); xBytesReceived = xStreamBufferReceive( xStreamBuffer, ( void * ) ucRxData, sizeof( ucRxData ), xReadBlockTime ); /* Set the file scope variable back to NULL so the interrupt doesn't * try to use it again. */ taskENTER_CRITICAL(); { xInterruptStreamBuffer = NULL; } taskEXIT_CRITICAL(); /* Now check the number of bytes received equals the trigger level, * except in the case that the read timed out before the trigger level * was reached. */ if( xTriggerLevel > xReadBlockTime ) { /* Trigger level was greater than the block time so expect to * time out having received xReadBlockTime bytes. */ if( xBytesReceived > xReadBlockTime ) { /* Received more bytes than expected. That could happen if * this task unblocked at the right time, but an interrupt * added another byte to the stream buffer before this task was * able to run. */ if( ( xBytesReceived - xReadBlockTime ) > xAllowableMargin ) { xErrorDetected = pdTRUE; } } else if( xReadBlockTime != xBytesReceived ) { /* It is possible the interrupt placed an item in the stream * buffer before this task called xStreamBufferReceive(), but * if that is the case then xBytesReceived will only every be * 0 as the interrupt will only have executed once. */ if( xBytesReceived != 1 ) { xErrorDetected = pdTRUE; } } } else if( xTriggerLevel < xReadBlockTime ) { /* Trigger level was less than the block time so we expect to * have received the trigger level number of bytes - could be more * though depending on other activity between the task being * unblocked and the task reading the number of bytes received. It * could also be less if the interrupt already put something in the * stream buffer before this task attempted to read it - in which * case the task would have returned the available bytes immediately * without ever blocking - in that case the bytes received will * only ever be 1 as the interrupt would not have executed more * than one in that time unless this task has too low a priority. */ if( xBytesReceived < xTriggerLevel ) { if( xBytesReceived != 1 ) { xErrorDetected = pdTRUE; } } else if( ( xBytesReceived - xTriggerLevel ) > xAllowableMargin ) { xErrorDetected = pdTRUE; } } else { /* The trigger level equalled the block time, so expect to * receive no greater than the block time. It could also be less * if the interrupt already put something in the stream buffer * before this task attempted to read it - in which case the task * would have returned the available bytes immediately without ever * blocking - in that case the bytes received would only ever be 1 * because the interrupt is not going to execute twice in that time * unless this task is running a too low a priority. */ if( xBytesReceived < xReadBlockTime ) { if( xBytesReceived != 1 ) { xErrorDetected = pdTRUE; } } else if( ( xBytesReceived - xReadBlockTime ) > xAllowableMargin ) { xErrorDetected = pdTRUE; } } if( xBytesReceived > sizeof( ucRxData ) ) { xErrorDetected = pdTRUE; } else if( memcmp( ( void * ) ucRxData, ( const void * ) pcDataSentFromInterrupt, xBytesReceived ) != 0 ) { /* Received data didn't match that expected. */ xErrorDetected = pdTRUE; } if( xErrorDetected == pdFALSE ) { /* Increment the cycle counter so the 'check' task knows this test * is still running without error. */ ulInterruptTriggerCounter++; } /* Tidy up ready for the next loop. */ vStreamBufferDelete( xStreamBuffer ); } } } /*-----------------------------------------------------------*/ BaseType_t xAreStreamBufferTasksStillRunning( void ) { static uint32_t ulLastEchoLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; static uint32_t ulLastNonBlockingRxCounter = 0; static uint32_t ulLastInterruptTriggerCounter = 0; BaseType_t x; for( x = 0; x < sbNUMBER_OF_ECHO_CLIENTS; x++ ) { if( ulLastEchoLoopCounters[ x ] == ulEchoLoopCounters[ x ] ) { xErrorStatus = pdFAIL; } else { ulLastEchoLoopCounters[ x ] = ulEchoLoopCounters[ x ]; } } if( ulNonBlockingRxCounter == ulLastNonBlockingRxCounter ) { xErrorStatus = pdFAIL; } else { ulLastNonBlockingRxCounter = ulNonBlockingRxCounter; } if( ulLastInterruptTriggerCounter == ulInterruptTriggerCounter ) { xErrorStatus = pdFAIL; } else { ulLastInterruptTriggerCounter = ulInterruptTriggerCounter; } #if ( configSUPPORT_STATIC_ALLOCATION == 1 ) { static uint32_t ulLastSenderLoopCounters[ sbNUMBER_OF_ECHO_CLIENTS ] = { 0 }; for( x = 0; x < sbNUMBER_OF_SENDER_TASKS; x++ ) { if( ulLastSenderLoopCounters[ x ] == ulSenderLoopCounters[ x ] ) { xErrorStatus = pdFAIL; } else { ulLastSenderLoopCounters[ x ] = ulSenderLoopCounters[ x ]; } } } #endif /* configSUPPORT_STATIC_ALLOCATION */ return xErrorStatus; } /*-----------------------------------------------------------*/
55711.c
//Kismet Weapon Spell #include <std.h> inherit "/d/magic/obj/weapons/godwpns_knights"; void create() { ::create(); set_name("%^BOLD%^%^CYAN%^W%^RESET%^%^BLUE%^e%^BOLD%^%^CYAN%^a%^WHITE%^ve-T"+ "%^CYAN%^o%^WHITE%^u%^CYAN%^c%^RESET%^%^BLUE%^h%^BOLD%^%^CYAN%^ed %^RESET%^%^BLUE%^B"+ "%^BOLD%^%^CYAN%^l%^WHITE%^a%^RESET%^%^BLUE%^d%^BOLD%^%^CYAN%^e%^RESET%^"); set_short("%^CYAN%^e%^YELLOW%^t%^RESET%^%^CYAN%^h%^BOLD%^e%^RESET%^%^CYAN%^r"+ "%^YELLOW%^e%^RESET%^%^CYAN%^a%^BOLD%^l %^WHITE%^s%^RESET%^i%^BOLD%^l%^RESET%^v"+ "%^BOLD%^e%^RESET%^r %^CYAN%^l%^YELLOW%^o%^RESET%^%^CYAN%^ngsw%^YELLOW%^or%^RESET%^%^CYAN%^d%^WHITE%^"); set_id(({"blade","sword","weave-touched blade","weapon"})); set_long("%^BOLD%^%^CYAN%^Fashioned out of pure %^WHITE%^s%^RESET%^i"+ "%^BOLD%^l%^RESET%^v%^BOLD%^e%^RESET%^r%^BOLD%^%^CYAN%^, this long sword "+ "shines with a blue-white glow. An %^WHITE%^e%^ORANGE%^t%^CYAN%^h%^WHITE%^e"+ "%^CYAN%^re%^ORANGE%^a%^WHITE%^l %^CYAN%^mesh of silver threads seems to wrap "+ "around the blade, as if infused with the silver metal. The hilt of the blade is "+ "crafted to look like a %^RESET%^%^BLUE%^s%^BOLD%^%^CYAN%^o%^RESET%^%^CYAN%^n"+ "%^BOLD%^g%^RESET%^%^BLUE%^b%^CYAN%^i%^BOLD%^r%^RESET%^%^BLUE%^d %^BOLD%^%^CYAN%^in "+ "flight, it's wings wrapped to form a knuckle-guard. A smooth pommel made of a coiled "+ "length of %^WHITE%^s%^RESET%^i%^BOLD%^l%^RESET%^v%^BOLD%^er %^CYAN%^supports the "+ "%^RESET%^d%^BOLD%^ia%^CYAN%^m%^WHITE%^on%^RESET%^d %^BOLD%^%^CYAN%^set into the base of the sword.%^RESET%^"); set_value(0); set_damage_type("slashing"); set_hit((:TO,"hit_func":)); } int hit_func(object targ){ targ = ETO->query_current_attacker(); if(!objectp(ETO)) return 1; if(!objectp(targ)) return 1; if(!random(10)) { tell_object(ETO,"%^BOLD%^The silver mesh around the blade blazes with a %^YELLOW%^b"+ "%^CYAN%^r%^WHITE%^i%^CYAN%^g%^ORANGE%^h%^CYAN%^t g%^WHITE%^l%^ORANGE%^o%^CYAN%^w%^RESET%^ as you "+ "slash into %^CYAN%^"+targ->QCN+".%^RESET%^"); tell_object(targ,"%^BOLD%^The silver mesh around %^ORANGE%^"+ETO->QCN+"'s %^WHITE%^blade blazes " "w%^RESET%^i%^BOLD%^th a %^YELLOW%^b%^CYAN%^r%^WHITE%^i%^CYAN%^g%^ORANGE%^h%^CYAN%^t g%^WHITE%^l%^ORANGE%^o%^CYAN%^w%^RESET%^ as %^ORANGE%^"+ETO->QS+" %^WHITE%^slashes into %^CYAN%^you%^WHITE%^!%^RESET%^"); tell_room(environment(ETO),"%^BOLD%^The silver mesh around %^ORANGE%^"+ETO->QCN+"'s %^WHITE%^blade "+ "blazes with a %^YELLOW%^b%^CYAN%^r%^WHITE%^i%^CYAN%^g%^ORANGE%^h%^CYAN%^t g%^WHITE%^l%^ORANGE%^o%^CYAN%^w%^RESET%^ as %^ORANGE%^"+ETO->QS+" %^WHITE%^slashes into %^CYAN%^"+targ->QCN+"%^WHITE%^!%^RESET%^",({ETO,targ})); return random(4)+8; } }
282828.c
/* * Virtualized GPU Memory Management * * Copyright (c) 2015-2020, NVIDIA CORPORATION. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include "vgpu_mm_gp10b.h" #include "gk20a/mm_gk20a.h" #include <nvgpu/bug.h> #include <nvgpu/dma.h> #include <nvgpu/vgpu/vgpu_ivc.h> #include <nvgpu/vgpu/vgpu.h> int vgpu_gp10b_init_mm_setup_hw(struct gk20a *g) { g->mm.disable_bigpage = true; return 0; } static inline int add_mem_desc(struct tegra_vgpu_mem_desc *mem_desc, u64 addr, u64 size, size_t *oob_size) { if (*oob_size < sizeof(*mem_desc)) return -ENOMEM; mem_desc->addr = addr; mem_desc->length = size; *oob_size -= sizeof(*mem_desc); return 0; } u64 vgpu_gp10b_locked_gmmu_map(struct vm_gk20a *vm, u64 map_offset, struct nvgpu_sgt *sgt, u64 buffer_offset, u64 size, u32 pgsz_idx, u8 kind_v, u32 ctag_offset, u32 flags, enum gk20a_mem_rw_flag rw_flag, bool clear_ctags, bool sparse, bool priv, struct vm_gk20a_mapping_batch *batch, enum nvgpu_aperture aperture) { int err = 0; struct gk20a *g = gk20a_from_vm(vm); struct tegra_vgpu_cmd_msg msg; struct tegra_vgpu_as_map_ex_params *p = &msg.params.as_map_ex; struct tegra_vgpu_mem_desc *mem_desc; u32 page_size = vm->gmmu_page_sizes[pgsz_idx]; u64 buffer_size = PAGE_ALIGN(size); u64 space_to_skip = buffer_offset; u32 mem_desc_count = 0, i; void *handle = NULL; size_t oob_size; u8 prot; struct nvgpu_sgl *sgl; nvgpu_log_fn(g, " "); /* FIXME: add support for sparse mappings */ if (WARN_ON(!sgt) || WARN_ON(nvgpu_iommuable(g))) return 0; if (space_to_skip & (page_size - 1)) return 0; memset(&msg, 0, sizeof(msg)); /* Allocate (or validate when map_offset != 0) the virtual address. */ if (!map_offset) { map_offset = __nvgpu_vm_alloc_va(vm, size, pgsz_idx); if (!map_offset) { nvgpu_err(g, "failed to allocate va space"); err = -ENOMEM; goto fail; } } handle = vgpu_ivc_oob_get_ptr(vgpu_ivc_get_server_vmid(), TEGRA_VGPU_QUEUE_CMD, (void **)&mem_desc, &oob_size); if (!handle) { err = -EINVAL; goto fail; } sgl = sgt->sgl; /* Align size to page size */ size = ALIGN(size, page_size); while (sgl) { u64 phys_addr; u64 chunk_length; /* * Cut out sgl ents for space_to_skip. */ if (space_to_skip && space_to_skip >= nvgpu_sgt_get_length(sgt, sgl)) { space_to_skip -= nvgpu_sgt_get_length(sgt, sgl); sgl = nvgpu_sgt_get_next(sgt, sgl); continue; } phys_addr = nvgpu_sgt_get_phys(g, sgt, sgl) + space_to_skip; chunk_length = min(size, nvgpu_sgt_get_length(sgt, sgl) - space_to_skip); if (add_mem_desc(&mem_desc[mem_desc_count++], phys_addr, chunk_length, &oob_size)) { err = -ENOMEM; goto fail; } space_to_skip = 0; size -= chunk_length; sgl = nvgpu_sgt_get_next(sgt, sgl); if (size == 0) break; } if (rw_flag == gk20a_mem_flag_read_only) prot = TEGRA_VGPU_MAP_PROT_READ_ONLY; else if (rw_flag == gk20a_mem_flag_write_only) prot = TEGRA_VGPU_MAP_PROT_WRITE_ONLY; else prot = TEGRA_VGPU_MAP_PROT_NONE; if (pgsz_idx == GMMU_PAGE_SIZE_KERNEL) { if (page_size == vm->gmmu_page_sizes[GMMU_PAGE_SIZE_SMALL]) { pgsz_idx = GMMU_PAGE_SIZE_SMALL; } else if (page_size == vm->gmmu_page_sizes[GMMU_PAGE_SIZE_BIG]) { pgsz_idx = GMMU_PAGE_SIZE_BIG; } else { nvgpu_err(g, "invalid kernel page size %d", page_size); goto fail; } } msg.cmd = TEGRA_VGPU_CMD_AS_MAP_EX; msg.handle = vgpu_get_handle(g); p->handle = vm->handle; p->gpu_va = map_offset; p->size = buffer_size; p->mem_desc_count = mem_desc_count; p->pgsz_idx = pgsz_idx; p->iova = 0; p->kind = kind_v; if (flags & NVGPU_VM_MAP_CACHEABLE) p->flags = TEGRA_VGPU_MAP_CACHEABLE; if (flags & NVGPU_VM_MAP_IO_COHERENT) p->flags |= TEGRA_VGPU_MAP_IO_COHERENT; if (flags & NVGPU_VM_MAP_L3_ALLOC) p->flags |= TEGRA_VGPU_MAP_L3_ALLOC; if (flags & NVGPU_VM_MAP_PLATFORM_ATOMIC) { p->flags |= TEGRA_VGPU_MAP_PLATFORM_ATOMIC; } p->prot = prot; p->ctag_offset = ctag_offset; p->clear_ctags = clear_ctags; err = vgpu_comm_sendrecv(&msg, sizeof(msg), sizeof(msg)); if (err || msg.ret) goto fail; /* TLB invalidate handled on server side */ vgpu_ivc_oob_put_ptr(handle); return map_offset; fail: if (handle) vgpu_ivc_oob_put_ptr(handle); nvgpu_err(g, "Failed: err=%d, msg.ret=%d", err, msg.ret); nvgpu_err(g, " Map: %-5s GPU virt %#-12llx +%#-9llx " "phys offset: %#-4llx; pgsz: %3dkb perm=%-2s | " "kind=%#02x APT=%-6s", vm->name, map_offset, buffer_size, buffer_offset, vm->gmmu_page_sizes[pgsz_idx] >> 10, nvgpu_gmmu_perm_str(rw_flag), kind_v, "SYSMEM"); for (i = 0; i < mem_desc_count; i++) nvgpu_err(g, " > 0x%010llx + 0x%llx", mem_desc[i].addr, mem_desc[i].length); return 0; }
522761.c
/** ****************************************************************************** * @file system_stm32f4xx.c * @author MCD Application Team * @version V2.4.2 * @date 13-November-2015 * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. * * This file provides two functions and one global variable to be called from * user application: * - SystemInit(): This function is called at startup just after reset and * before branch to main program. This call is made inside * the "startup_stm32f4xx.s" file. * * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used * by the user application to setup the SysTick * timer or configure other parameters. * * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must * be called whenever the core clock is changed * during program execution. * * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /** @addtogroup CMSIS * @{ */ /** @addtogroup stm32f4xx_system * @{ */ /** @addtogroup STM32F4xx_System_Private_Includes * @{ */ #include "stm32f4xx.h" #include <stm32f4xx_hal.h> #if !defined (HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */ #endif /* HSE_VALUE */ #if !defined (HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_TypesDefinitions * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Defines * @{ */ /************************* Miscellaneous Configuration ************************/ /*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ || defined(STM32F469xx) || defined(STM32F479xx) /* #define DATA_IN_ExtSRAM */ #endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx */ #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* #define DATA_IN_ExtSDRAM */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ /* #define VECT_TAB_SRAM */ #define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. This value must be a multiple of 0x200. */ /******************************************************************************/ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Macros * @{ */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Variables * @{ */ /* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency Note: If you use this function to configure the system clock; then there is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /** * @} */ /** @addtogroup STM32F4xx_System_Private_FunctionPrototypes * @{ */ #if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) static void SystemInit_ExtMemCtl(void); #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /** * @} */ /** @addtogroup STM32F4xx_System_Private_Functions * @{ */ /** * @brief Setup the microcontroller system * Initialize the FPU setting, vector table location and External memory * configuration. * @param None * @retval None */ void SystemInit(void) { /* FPU settings ------------------------------------------------------------*/ #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ #endif /* Reset the RCC clock configuration to the default reset state ------------*/ /* Set HSION bit */ RCC->CR |= (uint32_t)0x00000001; /* Reset CFGR register */ RCC->CFGR = 0x00000000; /* Reset HSEON, CSSON and PLLON bits */ RCC->CR &= (uint32_t)0xFEF6FFFF; /* Reset PLLCFGR register */ RCC->PLLCFGR = 0x24003010; /* Reset HSEBYP bit */ RCC->CR &= (uint32_t)0xFFFBFFFF; /* Disable all interrupts */ RCC->CIR = 0x00000000; #if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) SystemInit_ExtMemCtl(); #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /* Configure the Vector Table location add offset address ------------------*/ #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ #else SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ #endif } /** * @brief Update SystemCoreClock variable according to Clock Register Values. * The SystemCoreClock variable contains the core clock (HCLK), it can * be used by the user application to setup the SysTick timer or configure * other parameters. * * @note Each time the core clock (HCLK) changes, this function must be called * to update SystemCoreClock variable value. Otherwise, any configuration * based on this variable will be incorrect. * * @note - The system frequency computed by this function is not the real * frequency in the chip. It is calculated based on the predefined * constant and the selected clock source: * * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) * * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) * * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) * or HSI_VALUE(*) multiplied/divided by the PLL factors. * * (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value * 16 MHz) but the real value may vary depending on the variations * in voltage and temperature. * * (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value * depends on the application requirements), user has to ensure that HSE_VALUE * is same as the real frequency of the crystal used. Otherwise, this function * may have wrong result. * * - The result of this function could be not correct when using fractional * value for HSE crystal. * * @param None * @retval None */ void SystemCoreClockUpdate(void) { uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; /* Get SYSCLK source -------------------------------------------------------*/ tmp = RCC->CFGR & RCC_CFGR_SWS; switch (tmp) { case 0x00: /* HSI used as system clock source */ SystemCoreClock = HSI_VALUE; break; case 0x04: /* HSE used as system clock source */ SystemCoreClock = HSE_VALUE; break; case 0x08: /* PLL used as system clock source */ /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N SYSCLK = PLL_VCO / PLL_P */ pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; if (pllsource != 0) { /* HSE used as PLL clock source */ pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); } else { /* HSI used as PLL clock source */ pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); } pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; SystemCoreClock = pllvco/pllp; break; default: SystemCoreClock = HSI_VALUE; break; } /* Compute HCLK frequency --------------------------------------------------*/ /* Get HCLK prescaler */ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; /* HCLK frequency */ SystemCoreClock >>= tmp; } #if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM) #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) ||\ defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Setup the external memory controller. * Called in startup_stm32f4xx.s before jump to main. * This function configures the external memories (SRAM/SDRAM) * This SRAM/SDRAM will be used as program data memory (including heap and stack). * @param None * @retval None */ void SystemInit_ExtMemCtl(void) { __IO uint32_t tmp = 0x00; register uint32_t tmpreg = 0, timeout = 0xFFFF; register uint32_t index; /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ RCC->AHB1ENR |= 0x000001F8; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x00CCC0CC; GPIOD->AFR[1] = 0xCCCCCCCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xAAAA0A8A; /* Configure PDx pins speed to 100 MHz */ GPIOD->OSPEEDR = 0xFFFF0FCF; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00CC0CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA828A; /* Configure PEx pins speed to 100 MHz */ GPIOE->OSPEEDR = 0xFFFFC3CF; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0xCCCCCCCC; GPIOF->AFR[1] = 0xCCCCCCCC; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA800AAA; /* Configure PFx pins speed to 50 MHz */ GPIOF->OSPEEDR = 0xAA800AAA; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0xCCCCCCCC; GPIOG->AFR[1] = 0xCCCCCCCC; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0xAAAAAAAA; /* Configure PGx pins speed to 50 MHz */ GPIOG->OSPEEDR = 0xAAAAAAAA; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; /* Connect PHx pins to FMC Alternate function */ GPIOH->AFR[0] = 0x00C0CC00; GPIOH->AFR[1] = 0xCCCCCCCC; /* Configure PHx pins in Alternate function mode */ GPIOH->MODER = 0xAAAA08A0; /* Configure PHx pins speed to 50 MHz */ GPIOH->OSPEEDR = 0xAAAA08A0; /* Configure PHx pins Output type to push-pull */ GPIOH->OTYPER = 0x00000000; /* No pull-up, pull-down for PHx pins */ GPIOH->PUPDR = 0x00000000; /* Connect PIx pins to FMC Alternate function */ GPIOI->AFR[0] = 0xCCCCCCCC; GPIOI->AFR[1] = 0x00000CC0; /* Configure PIx pins in Alternate function mode */ GPIOI->MODER = 0x0028AAAA; /* Configure PIx pins speed to 50 MHz */ GPIOI->OSPEEDR = 0x0028AAAA; /* Configure PIx pins Output type to push-pull */ GPIOI->OTYPER = 0x00000000; /* No pull-up, pull-down for PIx pins */ GPIOI->PUPDR = 0x00000000; /*-- FMC Configuration -------------------------------------------------------*/ /* Enable the FMC interface clock */ RCC->AHB3ENR |= 0x00000001; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); FMC_Bank5_6->SDCR[0] = 0x000019E4; FMC_Bank5_6->SDTR[0] = 0x01115351; /* SDRAM initialization sequence */ /* Clock enable command */ FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Delay */ for (index = 0; index<1000; index++); /* PALL command */ FMC_Bank5_6->SDCMR = 0x00000012; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Auto refresh command */ FMC_Bank5_6->SDCMR = 0x00000073; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* MRD register program */ FMC_Bank5_6->SDCMR = 0x00046014; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Set refresh count */ tmpreg = FMC_Bank5_6->SDRTR; FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); /* Disable write protection */ tmpreg = FMC_Bank5_6->SDCR[0]; FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /* Configure and enable Bank1_SRAM2 */ FMC_Bank1->BTCR[2] = 0x00001011; FMC_Bank1->BTCR[3] = 0x00000201; FMC_Bank1E->BWTR[2] = 0x0fffffff; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /* Configure and enable Bank1_SRAM2 */ FMC_Bank1->BTCR[2] = 0x00001091; FMC_Bank1->BTCR[3] = 0x00110212; FMC_Bank1E->BWTR[2] = 0x0fffffff; #endif /* STM32F469xx || STM32F479xx */ (void)(tmp); } #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ #elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) /** * @brief Setup the external memory controller. * Called in startup_stm32f4xx.s before jump to main. * This function configures the external memories (SRAM/SDRAM) * This SRAM/SDRAM will be used as program data memory (including heap and stack). * @param None * @retval None */ void SystemInit_ExtMemCtl(void) { __IO uint32_t tmp = 0x00; #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) #if defined (DATA_IN_ExtSDRAM) register uint32_t tmpreg = 0, timeout = 0xFFFF; register uint32_t index; #if defined(STM32F446xx) /* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface clock */ RCC->AHB1ENR |= 0x0000007D; #else /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ RCC->AHB1ENR |= 0x000001F8; #endif /* STM32F446xx */ /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); #if defined(STM32F446xx) /* Connect PAx pins to FMC Alternate function */ GPIOA->AFR[0] |= 0xC0000000; GPIOA->AFR[1] |= 0x00000000; /* Configure PDx pins in Alternate function mode */ GPIOA->MODER |= 0x00008000; /* Configure PDx pins speed to 50 MHz */ GPIOA->OSPEEDR |= 0x00008000; /* Configure PDx pins Output type to push-pull */ GPIOA->OTYPER |= 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOA->PUPDR |= 0x00000000; /* Connect PCx pins to FMC Alternate function */ GPIOC->AFR[0] |= 0x00CC0000; GPIOC->AFR[1] |= 0x00000000; /* Configure PDx pins in Alternate function mode */ GPIOC->MODER |= 0x00000A00; /* Configure PDx pins speed to 50 MHz */ GPIOC->OSPEEDR |= 0x00000A00; /* Configure PDx pins Output type to push-pull */ GPIOC->OTYPER |= 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOC->PUPDR |= 0x00000000; #endif /* STM32F446xx */ /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x000000CC; GPIOD->AFR[1] = 0xCC000CCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xA02A000A; /* Configure PDx pins speed to 50 MHz */ GPIOD->OSPEEDR = 0xA02A000A; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00000CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA800A; /* Configure PEx pins speed to 50 MHz */ GPIOE->OSPEEDR = 0xAAAA800A; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0xCCCCCCCC; GPIOF->AFR[1] = 0xCCCCCCCC; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA800AAA; /* Configure PFx pins speed to 50 MHz */ GPIOF->OSPEEDR = 0xAA800AAA; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0xCCCCCCCC; GPIOG->AFR[1] = 0xCCCCCCCC; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0xAAAAAAAA; /* Configure PGx pins speed to 50 MHz */ GPIOG->OSPEEDR = 0xAAAAAAAA; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ || defined(STM32F469xx) || defined(STM32F479xx) /* Connect PHx pins to FMC Alternate function */ GPIOH->AFR[0] = 0x00C0CC00; GPIOH->AFR[1] = 0xCCCCCCCC; /* Configure PHx pins in Alternate function mode */ GPIOH->MODER = 0xAAAA08A0; /* Configure PHx pins speed to 50 MHz */ GPIOH->OSPEEDR = 0xAAAA08A0; /* Configure PHx pins Output type to push-pull */ GPIOH->OTYPER = 0x00000000; /* No pull-up, pull-down for PHx pins */ GPIOH->PUPDR = 0x00000000; /* Connect PIx pins to FMC Alternate function */ GPIOI->AFR[0] = 0xCCCCCCCC; GPIOI->AFR[1] = 0x00000CC0; /* Configure PIx pins in Alternate function mode */ GPIOI->MODER = 0x0028AAAA; /* Configure PIx pins speed to 50 MHz */ GPIOI->OSPEEDR = 0x0028AAAA; /* Configure PIx pins Output type to push-pull */ GPIOI->OTYPER = 0x00000000; /* No pull-up, pull-down for PIx pins */ GPIOI->PUPDR = 0x00000000; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*-- FMC Configuration -------------------------------------------------------*/ /* Enable the FMC interface clock */ RCC->AHB3ENR |= 0x00000001; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable SDRAM bank1 */ #if defined(STM32F446xx) FMC_Bank5_6->SDCR[0] = 0x00001954; #else FMC_Bank5_6->SDCR[0] = 0x000019E4; #endif /* STM32F446xx */ FMC_Bank5_6->SDTR[0] = 0x01115351; /* SDRAM initialization sequence */ /* Clock enable command */ FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Delay */ for (index = 0; index<1000; index++); /* PALL command */ FMC_Bank5_6->SDCMR = 0x00000012; timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Auto refresh command */ #if defined(STM32F446xx) FMC_Bank5_6->SDCMR = 0x000000F3; #else FMC_Bank5_6->SDCMR = 0x00000073; #endif /* STM32F446xx */ timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* MRD register program */ #if defined(STM32F446xx) FMC_Bank5_6->SDCMR = 0x00044014; #else FMC_Bank5_6->SDCMR = 0x00046014; #endif /* STM32F446xx */ timeout = 0xFFFF; while((tmpreg != 0) && (timeout-- > 0)) { tmpreg = FMC_Bank5_6->SDSR & 0x00000020; } /* Set refresh count */ tmpreg = FMC_Bank5_6->SDRTR; #if defined(STM32F446xx) FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1)); #else FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); #endif /* STM32F446xx */ /* Disable write protection */ tmpreg = FMC_Bank5_6->SDCR[0]; FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); #endif /* DATA_IN_ExtSDRAM */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ || defined(STM32F469xx) || defined(STM32F479xx) #if defined(DATA_IN_ExtSRAM) /*-- GPIOs Configuration -----------------------------------------------------*/ /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ RCC->AHB1ENR |= 0x00000078; /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN); /* Connect PDx pins to FMC Alternate function */ GPIOD->AFR[0] = 0x00CCC0CC; GPIOD->AFR[1] = 0xCCCCCCCC; /* Configure PDx pins in Alternate function mode */ GPIOD->MODER = 0xAAAA0A8A; /* Configure PDx pins speed to 100 MHz */ GPIOD->OSPEEDR = 0xFFFF0FCF; /* Configure PDx pins Output type to push-pull */ GPIOD->OTYPER = 0x00000000; /* No pull-up, pull-down for PDx pins */ GPIOD->PUPDR = 0x00000000; /* Connect PEx pins to FMC Alternate function */ GPIOE->AFR[0] = 0xC00CC0CC; GPIOE->AFR[1] = 0xCCCCCCCC; /* Configure PEx pins in Alternate function mode */ GPIOE->MODER = 0xAAAA828A; /* Configure PEx pins speed to 100 MHz */ GPIOE->OSPEEDR = 0xFFFFC3CF; /* Configure PEx pins Output type to push-pull */ GPIOE->OTYPER = 0x00000000; /* No pull-up, pull-down for PEx pins */ GPIOE->PUPDR = 0x00000000; /* Connect PFx pins to FMC Alternate function */ GPIOF->AFR[0] = 0x00CCCCCC; GPIOF->AFR[1] = 0xCCCC0000; /* Configure PFx pins in Alternate function mode */ GPIOF->MODER = 0xAA000AAA; /* Configure PFx pins speed to 100 MHz */ GPIOF->OSPEEDR = 0xFF000FFF; /* Configure PFx pins Output type to push-pull */ GPIOF->OTYPER = 0x00000000; /* No pull-up, pull-down for PFx pins */ GPIOF->PUPDR = 0x00000000; /* Connect PGx pins to FMC Alternate function */ GPIOG->AFR[0] = 0x00CCCCCC; GPIOG->AFR[1] = 0x000000C0; /* Configure PGx pins in Alternate function mode */ GPIOG->MODER = 0x00085AAA; /* Configure PGx pins speed to 100 MHz */ GPIOG->OSPEEDR = 0x000CAFFF; /* Configure PGx pins Output type to push-pull */ GPIOG->OTYPER = 0x00000000; /* No pull-up, pull-down for PGx pins */ GPIOG->PUPDR = 0x00000000; /*-- FMC/FSMC Configuration --------------------------------------------------*/ /* Enable the FMC/FSMC interface clock */ RCC->AHB3ENR |= 0x00000001; #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable Bank1_SRAM2 */ FMC_Bank1->BTCR[2] = 0x00001011; FMC_Bank1->BTCR[3] = 0x00000201; FMC_Bank1E->BWTR[2] = 0x0fffffff; #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ #if defined(STM32F469xx) || defined(STM32F479xx) /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); /* Configure and enable Bank1_SRAM2 */ FMC_Bank1->BTCR[2] = 0x00001091; FMC_Bank1->BTCR[3] = 0x00110212; FMC_Bank1E->BWTR[2] = 0x0fffffff; #endif /* STM32F469xx || STM32F479xx */ #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) /* Delay after an RCC peripheral clock enabling */ tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN); /* Configure and enable Bank1_SRAM2 */ FSMC_Bank1->BTCR[2] = 0x00001011; FSMC_Bank1->BTCR[3] = 0x00000201; FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ #endif /* DATA_IN_ExtSRAM */ #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ (void)(tmp); } #endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */ /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
762533.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py // RUN: %clang_cc1 -target-feature +f64mm -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -target-feature +f64mm -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK // RUN: %clang_cc1 -target-feature +f64mm -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - %s | FileCheck %s // RUN: %clang_cc1 -target-feature +f64mm -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu -target-feature +sve -fallow-half-arguments-and-returns -S -O1 -Werror -Wall -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK // REQUIRES: aarch64-registered-target || arm-registered-target #include <arm_sve.h> #ifdef SVE_OVERLOADED_FORMS // A simple used,unused... macro, long enough to represent any SVE builtin. #define SVE_ACLE_FUNC(A1, A2_UNUSED, A3, A4_UNUSED) A1##A3 #else #define SVE_ACLE_FUNC(A1, A2, A3, A4) A1##A2##A3##A4 #endif // CHECK-LABEL: @test_svtrn2_s8( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.trn2q.nxv16i8(<vscale x 16 x i8> [[OP1:%.*]], <vscale x 16 x i8> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 16 x i8> [[TMP0]] // // CPP-CHECK-LABEL: @_Z14test_svtrn2_s8u10__SVInt8_tu10__SVInt8_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.trn2q.nxv16i8(<vscale x 16 x i8> [[OP1:%.*]], <vscale x 16 x i8> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i8> [[TMP0]] // svint8_t test_svtrn2_s8(svint8_t op1, svint8_t op2) { return SVE_ACLE_FUNC(svtrn2q, _s8, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_s16( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.trn2q.nxv8i16(<vscale x 8 x i16> [[OP1:%.*]], <vscale x 8 x i16> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 8 x i16> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_s16u11__SVInt16_tu11__SVInt16_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.trn2q.nxv8i16(<vscale x 8 x i16> [[OP1:%.*]], <vscale x 8 x i16> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 8 x i16> [[TMP0]] // svint16_t test_svtrn2_s16(svint16_t op1, svint16_t op2) { return SVE_ACLE_FUNC(svtrn2q, _s16, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_s32( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.trn2q.nxv4i32(<vscale x 4 x i32> [[OP1:%.*]], <vscale x 4 x i32> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 4 x i32> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_s32u11__SVInt32_tu11__SVInt32_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.trn2q.nxv4i32(<vscale x 4 x i32> [[OP1:%.*]], <vscale x 4 x i32> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 4 x i32> [[TMP0]] // svint32_t test_svtrn2_s32(svint32_t op1, svint32_t op2) { return SVE_ACLE_FUNC(svtrn2q, _s32, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_s64( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.trn2q.nxv2i64(<vscale x 2 x i64> [[OP1:%.*]], <vscale x 2 x i64> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 2 x i64> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_s64u11__SVInt64_tu11__SVInt64_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.trn2q.nxv2i64(<vscale x 2 x i64> [[OP1:%.*]], <vscale x 2 x i64> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 2 x i64> [[TMP0]] // svint64_t test_svtrn2_s64(svint64_t op1, svint64_t op2) { return SVE_ACLE_FUNC(svtrn2q, _s64, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_u8( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.trn2q.nxv16i8(<vscale x 16 x i8> [[OP1:%.*]], <vscale x 16 x i8> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 16 x i8> [[TMP0]] // // CPP-CHECK-LABEL: @_Z14test_svtrn2_u8u11__SVUint8_tu11__SVUint8_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 16 x i8> @llvm.aarch64.sve.trn2q.nxv16i8(<vscale x 16 x i8> [[OP1:%.*]], <vscale x 16 x i8> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 16 x i8> [[TMP0]] // svuint8_t test_svtrn2_u8(svuint8_t op1, svuint8_t op2) { return SVE_ACLE_FUNC(svtrn2q, _u8, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_u16( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.trn2q.nxv8i16(<vscale x 8 x i16> [[OP1:%.*]], <vscale x 8 x i16> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 8 x i16> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_u16u12__SVUint16_tu12__SVUint16_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x i16> @llvm.aarch64.sve.trn2q.nxv8i16(<vscale x 8 x i16> [[OP1:%.*]], <vscale x 8 x i16> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 8 x i16> [[TMP0]] // svuint16_t test_svtrn2_u16(svuint16_t op1, svuint16_t op2) { return SVE_ACLE_FUNC(svtrn2q, _u16, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_u32( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.trn2q.nxv4i32(<vscale x 4 x i32> [[OP1:%.*]], <vscale x 4 x i32> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 4 x i32> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_u32u12__SVUint32_tu12__SVUint32_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x i32> @llvm.aarch64.sve.trn2q.nxv4i32(<vscale x 4 x i32> [[OP1:%.*]], <vscale x 4 x i32> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 4 x i32> [[TMP0]] // svuint32_t test_svtrn2_u32(svuint32_t op1, svuint32_t op2) { return SVE_ACLE_FUNC(svtrn2q, _u32, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_u64( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.trn2q.nxv2i64(<vscale x 2 x i64> [[OP1:%.*]], <vscale x 2 x i64> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 2 x i64> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_u64u12__SVUint64_tu12__SVUint64_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x i64> @llvm.aarch64.sve.trn2q.nxv2i64(<vscale x 2 x i64> [[OP1:%.*]], <vscale x 2 x i64> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 2 x i64> [[TMP0]] // svuint64_t test_svtrn2_u64(svuint64_t op1, svuint64_t op2) { return SVE_ACLE_FUNC(svtrn2q, _u64, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_f16( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x half> @llvm.aarch64.sve.trn2q.nxv8f16(<vscale x 8 x half> [[OP1:%.*]], <vscale x 8 x half> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 8 x half> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_f16u13__SVFloat16_tu13__SVFloat16_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 8 x half> @llvm.aarch64.sve.trn2q.nxv8f16(<vscale x 8 x half> [[OP1:%.*]], <vscale x 8 x half> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 8 x half> [[TMP0]] // svfloat16_t test_svtrn2_f16(svfloat16_t op1, svfloat16_t op2) { return SVE_ACLE_FUNC(svtrn2q, _f16, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_f32( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.aarch64.sve.trn2q.nxv4f32(<vscale x 4 x float> [[OP1:%.*]], <vscale x 4 x float> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 4 x float> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_f32u13__SVFloat32_tu13__SVFloat32_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 4 x float> @llvm.aarch64.sve.trn2q.nxv4f32(<vscale x 4 x float> [[OP1:%.*]], <vscale x 4 x float> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 4 x float> [[TMP0]] // svfloat32_t test_svtrn2_f32(svfloat32_t op1, svfloat32_t op2) { return SVE_ACLE_FUNC(svtrn2q, _f32, , )(op1, op2); } // CHECK-LABEL: @test_svtrn2_f64( // CHECK-NEXT: entry: // CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.aarch64.sve.trn2q.nxv2f64(<vscale x 2 x double> [[OP1:%.*]], <vscale x 2 x double> [[OP2:%.*]]) // CHECK-NEXT: ret <vscale x 2 x double> [[TMP0]] // // CPP-CHECK-LABEL: @_Z15test_svtrn2_f64u13__SVFloat64_tu13__SVFloat64_t( // CPP-CHECK-NEXT: entry: // CPP-CHECK-NEXT: [[TMP0:%.*]] = call <vscale x 2 x double> @llvm.aarch64.sve.trn2q.nxv2f64(<vscale x 2 x double> [[OP1:%.*]], <vscale x 2 x double> [[OP2:%.*]]) // CPP-CHECK-NEXT: ret <vscale x 2 x double> [[TMP0]] // svfloat64_t test_svtrn2_f64(svfloat64_t op1, svfloat64_t op2) { return SVE_ACLE_FUNC(svtrn2q, _f64, , )(op1, op2); }
871291.c
/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */ /* * USB descriptor handling functions for libusb * Copyright © 2007 Daniel Drake <[email protected]> * Copyright © 2001 Johannes Erdfelt <[email protected]> * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <errno.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include "libusbi.h" #define DESC_HEADER_LENGTH 2 #define DEVICE_DESC_LENGTH 18 #define CONFIG_DESC_LENGTH 9 #define INTERFACE_DESC_LENGTH 9 #define ENDPOINT_DESC_LENGTH 7 #define ENDPOINT_AUDIO_DESC_LENGTH 9 /** @defgroup desc USB descriptors * This page details how to examine the various standard USB descriptors * for detected devices */ /* set host_endian if the w values are already in host endian format, * as opposed to bus endian. */ int usbi_parse_descriptor(const unsigned char *source, const char *descriptor, void *dest, int host_endian) { const unsigned char *sp = source; unsigned char *dp = dest; uint16_t w; const char *cp; uint32_t d; for (cp = descriptor; *cp; cp++) { switch (*cp) { case 'b': /* 8-bit byte */ *dp++ = *sp++; break; case 'w': /* 16-bit word, convert from little endian to CPU */ dp += ((uintptr_t) dp & 1); /* Align to word boundary */ if (host_endian) { memcpy(dp, sp, 2); } else { w = (sp[1] << 8) | sp[0]; *((uint16_t *) dp) = w; } sp += 2; dp += 2; break; case 'd': /* 32-bit word, convert from little endian to CPU */ dp += ((uintptr_t) dp & 1); /* Align to word boundary */ if (host_endian) { memcpy(dp, sp, 4); } else { d = (sp[3] << 24) | (sp[2] << 16) | (sp[1] << 8) | sp[0]; *((uint32_t *) dp) = d; } sp += 4; dp += 4; break; case 'u': /* 16 byte UUID */ memcpy(dp, sp, 16); sp += 16; dp += 16; break; } } return (int) (sp - source); } static void clear_endpoint(struct libusb_endpoint_descriptor *endpoint) { if (endpoint->extra) free((unsigned char *) endpoint->extra); } static int parse_endpoint(struct libusb_context *ctx, struct libusb_endpoint_descriptor *endpoint, unsigned char *buffer, int size, int host_endian) { struct usb_descriptor_header header; unsigned char *extra; unsigned char *begin; int parsed = 0; int len; if (size < DESC_HEADER_LENGTH) { usbi_err(ctx, "short endpoint descriptor read %d/%d", size, DESC_HEADER_LENGTH); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(buffer, "bb", &header, 0); if (header.bDescriptorType != LIBUSB_DT_ENDPOINT) { usbi_err(ctx, "unexpected descriptor %x (expected %x)", header.bDescriptorType, LIBUSB_DT_ENDPOINT); return parsed; } if (header.bLength > size) { usbi_warn(ctx, "short endpoint descriptor read %d/%d", size, header.bLength); return parsed; } if (header.bLength >= ENDPOINT_AUDIO_DESC_LENGTH) usbi_parse_descriptor(buffer, "bbbbwbbb", endpoint, host_endian); else if (header.bLength >= ENDPOINT_DESC_LENGTH) usbi_parse_descriptor(buffer, "bbbbwb", endpoint, host_endian); else { usbi_err(ctx, "invalid endpoint bLength (%d)", header.bLength); return LIBUSB_ERROR_IO; } buffer += header.bLength; size -= header.bLength; parsed += header.bLength; /* Skip over the rest of the Class Specific or Vendor Specific */ /* descriptors */ begin = buffer; while (size >= DESC_HEADER_LENGTH) { usbi_parse_descriptor(buffer, "bb", &header, 0); if (header.bLength < DESC_HEADER_LENGTH) { usbi_err(ctx, "invalid extra ep desc len (%d)", header.bLength); return LIBUSB_ERROR_IO; } else if (header.bLength > size) { usbi_warn(ctx, "short extra ep desc read %d/%d", size, header.bLength); return parsed; } /* If we find another "proper" descriptor then we're done */ if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) || (header.bDescriptorType == LIBUSB_DT_INTERFACE) || (header.bDescriptorType == LIBUSB_DT_CONFIG) || (header.bDescriptorType == LIBUSB_DT_DEVICE)) break; usbi_dbg("skipping descriptor %x", header.bDescriptorType); buffer += header.bLength; size -= header.bLength; parsed += header.bLength; } /* Copy any unknown descriptors into a storage area for drivers */ /* to later parse */ len = (int) (buffer - begin); if (!len) { endpoint->extra = NULL; endpoint->extra_length = 0; return parsed; } extra = malloc(len); endpoint->extra = extra; if (!extra) { endpoint->extra_length = 0; return LIBUSB_ERROR_NO_MEM; } memcpy(extra, begin, len); endpoint->extra_length = len; return parsed; } static void clear_interface(struct libusb_interface *usb_interface) { int i; int j; if (usb_interface->altsetting) { for (i = 0; i < usb_interface->num_altsetting; i++) { struct libusb_interface_descriptor *ifp = (struct libusb_interface_descriptor *) usb_interface->altsetting + i; if (ifp->extra) free((void *) ifp->extra); if (ifp->endpoint) { for (j = 0; j < ifp->bNumEndpoints; j++) clear_endpoint((struct libusb_endpoint_descriptor *) ifp->endpoint + j); free((void *) ifp->endpoint); } } free((void *) usb_interface->altsetting); usb_interface->altsetting = NULL; } } static int parse_interface(libusb_context *ctx, struct libusb_interface *usb_interface, unsigned char *buffer, int size, int host_endian) { int i; int len; int r; int parsed = 0; int interface_number = -1; size_t tmp; struct usb_descriptor_header header; struct libusb_interface_descriptor *ifp; unsigned char *begin; usb_interface->num_altsetting = 0; while (size >= INTERFACE_DESC_LENGTH) { struct libusb_interface_descriptor *altsetting = (struct libusb_interface_descriptor *) usb_interface->altsetting; altsetting = usbi_reallocf(altsetting, sizeof(struct libusb_interface_descriptor) * (usb_interface->num_altsetting + 1)); if (!altsetting) { r = LIBUSB_ERROR_NO_MEM; goto err; } usb_interface->altsetting = altsetting; ifp = altsetting + usb_interface->num_altsetting; usbi_parse_descriptor(buffer, "bbbbbbbbb", ifp, 0); if (ifp->bDescriptorType != LIBUSB_DT_INTERFACE) { usbi_err(ctx, "unexpected descriptor %x (expected %x)", ifp->bDescriptorType, LIBUSB_DT_INTERFACE); return parsed; } if (ifp->bLength < INTERFACE_DESC_LENGTH) { usbi_err(ctx, "invalid interface bLength (%d)", ifp->bLength); r = LIBUSB_ERROR_IO; goto err; } if (ifp->bLength > size) { usbi_warn(ctx, "short intf descriptor read %d/%d", size, ifp->bLength); return parsed; } if (ifp->bNumEndpoints > USB_MAXENDPOINTS) { usbi_err(ctx, "too many endpoints (%d)", ifp->bNumEndpoints); r = LIBUSB_ERROR_IO; goto err; } usb_interface->num_altsetting++; ifp->extra = NULL; ifp->extra_length = 0; ifp->endpoint = NULL; if (interface_number == -1) interface_number = ifp->bInterfaceNumber; /* Skip over the interface */ buffer += ifp->bLength; parsed += ifp->bLength; size -= ifp->bLength; begin = buffer; /* Skip over any interface, class or vendor descriptors */ while (size >= DESC_HEADER_LENGTH) { usbi_parse_descriptor(buffer, "bb", &header, 0); if (header.bLength < DESC_HEADER_LENGTH) { usbi_err(ctx, "invalid extra intf desc len (%d)", header.bLength); r = LIBUSB_ERROR_IO; goto err; } else if (header.bLength > size) { usbi_warn(ctx, "short extra intf desc read %d/%d", size, header.bLength); return parsed; } /* If we find another "proper" descriptor then we're done */ if ((header.bDescriptorType == LIBUSB_DT_INTERFACE) || (header.bDescriptorType == LIBUSB_DT_ENDPOINT) || (header.bDescriptorType == LIBUSB_DT_CONFIG) || (header.bDescriptorType == LIBUSB_DT_DEVICE)) break; buffer += header.bLength; parsed += header.bLength; size -= header.bLength; } /* Copy any unknown descriptors into a storage area for */ /* drivers to later parse */ len = (int) (buffer - begin); if (len) { ifp->extra = malloc(len); if (!ifp->extra) { r = LIBUSB_ERROR_NO_MEM; goto err; } memcpy((unsigned char *) ifp->extra, begin, len); ifp->extra_length = len; } if (ifp->bNumEndpoints > 0) { struct libusb_endpoint_descriptor *endpoint; tmp = ifp->bNumEndpoints * sizeof(struct libusb_endpoint_descriptor); endpoint = malloc(tmp); ifp->endpoint = endpoint; if (!endpoint) { r = LIBUSB_ERROR_NO_MEM; goto err; } memset(endpoint, 0, tmp); for (i = 0; i < ifp->bNumEndpoints; i++) { r = parse_endpoint(ctx, endpoint + i, buffer, size, host_endian); if (r < 0) goto err; if (r == 0) { ifp->bNumEndpoints = (uint8_t) i; break;; } buffer += r; parsed += r; size -= r; } } /* We check to see if it's an alternate to this one */ ifp = (struct libusb_interface_descriptor *) buffer; if (size < LIBUSB_DT_INTERFACE_SIZE || ifp->bDescriptorType != LIBUSB_DT_INTERFACE || ifp->bInterfaceNumber != interface_number) return parsed; } return parsed; err: clear_interface(usb_interface); return r; } static void clear_configuration(struct libusb_config_descriptor *config) { if (config->interface) { int i; for (i = 0; i < config->bNumInterfaces; i++) clear_interface((struct libusb_interface *) config->interface + i); free((void *) config->interface); } if (config->extra) free((void *) config->extra); } static int parse_configuration(struct libusb_context *ctx, struct libusb_config_descriptor *config, unsigned char *buffer, int size, int host_endian) { int i; int r; size_t tmp; struct usb_descriptor_header header; struct libusb_interface *usb_interface; if (size < LIBUSB_DT_CONFIG_SIZE) { usbi_err(ctx, "short config descriptor read %d/%d", size, LIBUSB_DT_CONFIG_SIZE); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(buffer, "bbwbbbbb", config, host_endian); if (config->bDescriptorType != LIBUSB_DT_CONFIG) { usbi_err(ctx, "unexpected descriptor %x (expected %x)", config->bDescriptorType, LIBUSB_DT_CONFIG); return LIBUSB_ERROR_IO; } if (config->bLength < LIBUSB_DT_CONFIG_SIZE) { usbi_err(ctx, "invalid config bLength (%d)", config->bLength); return LIBUSB_ERROR_IO; } if (config->bLength > size) { usbi_err(ctx, "short config descriptor read %d/%d", size, config->bLength); return LIBUSB_ERROR_IO; } if (config->bNumInterfaces > USB_MAXINTERFACES) { usbi_err(ctx, "too many interfaces (%d)", config->bNumInterfaces); return LIBUSB_ERROR_IO; } tmp = config->bNumInterfaces * sizeof(struct libusb_interface); usb_interface = malloc(tmp); config->interface = usb_interface; if (!config->interface) return LIBUSB_ERROR_NO_MEM; memset(usb_interface, 0, tmp); buffer += config->bLength; size -= config->bLength; config->extra = NULL; config->extra_length = 0; for (i = 0; i < config->bNumInterfaces; i++) { int len; unsigned char *begin; /* Skip over the rest of the Class Specific or Vendor */ /* Specific descriptors */ begin = buffer; while (size >= DESC_HEADER_LENGTH) { usbi_parse_descriptor(buffer, "bb", &header, 0); if (header.bLength < DESC_HEADER_LENGTH) { usbi_err(ctx, "invalid extra config desc len (%d)", header.bLength); r = LIBUSB_ERROR_IO; goto err; } else if (header.bLength > size) { usbi_warn(ctx, "short extra config desc read %d/%d", size, header.bLength); config->bNumInterfaces = (uint8_t) i; return size; } /* If we find another "proper" descriptor then we're done */ if ((header.bDescriptorType == LIBUSB_DT_ENDPOINT) || (header.bDescriptorType == LIBUSB_DT_INTERFACE) || (header.bDescriptorType == LIBUSB_DT_CONFIG) || (header.bDescriptorType == LIBUSB_DT_DEVICE)) break; usbi_dbg("skipping descriptor 0x%x\n", header.bDescriptorType); buffer += header.bLength; size -= header.bLength; } /* Copy any unknown descriptors into a storage area for */ /* drivers to later parse */ len = (int) (buffer - begin); if (len) { /* FIXME: We should realloc and append here */ if (!config->extra_length) { config->extra = malloc(len); if (!config->extra) { r = LIBUSB_ERROR_NO_MEM; goto err; } memcpy((unsigned char *) config->extra, begin, len); config->extra_length = len; } } r = parse_interface(ctx, usb_interface + i, buffer, size, host_endian); if (r < 0) goto err; if (r == 0) { config->bNumInterfaces = (uint8_t) i; break; } buffer += r; size -= r; } return size; err: clear_configuration(config); return r; } static int raw_desc_to_config(struct libusb_context *ctx, unsigned char *buf, int size, int host_endian, struct libusb_config_descriptor **config) { struct libusb_config_descriptor *_config = malloc(sizeof(*_config)); int r; if (!_config) return LIBUSB_ERROR_NO_MEM; r = parse_configuration(ctx, _config, buf, size, host_endian); if (r < 0) { usbi_err(ctx, "parse_configuration failed with error %d", r); free(_config); return r; } else if (r > 0) { usbi_warn(ctx, "still %d bytes of descriptor data left", r); } *config = _config; return LIBUSB_SUCCESS; } int usbi_device_cache_descriptor(libusb_device *dev) { int r, host_endian = 0; r = usbi_backend->get_device_descriptor(dev, (unsigned char *) &dev->device_descriptor, &host_endian); if (r < 0) return r; if (!host_endian) { dev->device_descriptor.bcdUSB = libusb_le16_to_cpu(dev->device_descriptor.bcdUSB); dev->device_descriptor.idVendor = libusb_le16_to_cpu(dev->device_descriptor.idVendor); dev->device_descriptor.idProduct = libusb_le16_to_cpu(dev->device_descriptor.idProduct); dev->device_descriptor.bcdDevice = libusb_le16_to_cpu(dev->device_descriptor.bcdDevice); } return LIBUSB_SUCCESS; } /** \ingroup desc * Get the USB device descriptor for a given device. * * This is a non-blocking function; the device descriptor is cached in memory. * * Note since libusb-1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102, this * function always succeeds. * * \param dev the device * \param desc output location for the descriptor data * \returns 0 on success or a LIBUSB_ERROR code on failure */ int API_EXPORTED libusb_get_device_descriptor(libusb_device *dev, struct libusb_device_descriptor *desc) { usbi_dbg(""); memcpy((unsigned char *) desc, (unsigned char *) &dev->device_descriptor, sizeof(dev->device_descriptor)); return 0; } /** \ingroup desc * Get the USB configuration descriptor for the currently active configuration. * This is a non-blocking function which does not involve any requests being * sent to the device. * * \param dev a device * \param config output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() * after use. * \returns 0 on success * \returns LIBUSB_ERROR_NOT_FOUND if the device is in unconfigured state * \returns another LIBUSB_ERROR code on error * \see libusb_get_config_descriptor */ int API_EXPORTED libusb_get_active_config_descriptor(libusb_device *dev, struct libusb_config_descriptor **config) { struct libusb_config_descriptor _config; unsigned char tmp[LIBUSB_DT_CONFIG_SIZE]; unsigned char *buf = NULL; int host_endian = 0; int r; r = usbi_backend->get_active_config_descriptor(dev, tmp, LIBUSB_DT_CONFIG_SIZE, &host_endian); if (r < 0) return r; if (r < LIBUSB_DT_CONFIG_SIZE) { usbi_err(dev->ctx, "short config descriptor read %d/%d", r, LIBUSB_DT_CONFIG_SIZE); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(tmp, "bbw", &_config, host_endian); buf = malloc(_config.wTotalLength); if (!buf) return LIBUSB_ERROR_NO_MEM; r = usbi_backend->get_active_config_descriptor(dev, buf, _config.wTotalLength, &host_endian); if (r >= 0) r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config); free(buf); return r; } /** \ingroup desc * Get a USB configuration descriptor based on its index. * This is a non-blocking function which does not involve any requests being * sent to the device. * * \param dev a device * \param config_index the index of the configuration you wish to retrieve * \param config output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() * after use. * \returns 0 on success * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist * \returns another LIBUSB_ERROR code on error * \see libusb_get_active_config_descriptor() * \see libusb_get_config_descriptor_by_value() */ int API_EXPORTED libusb_get_config_descriptor(libusb_device *dev, uint8_t config_index, struct libusb_config_descriptor **config) { struct libusb_config_descriptor _config; unsigned char tmp[LIBUSB_DT_CONFIG_SIZE]; unsigned char *buf = NULL; int host_endian = 0; int r; usbi_dbg("index %d", config_index); if (config_index >= dev->num_configurations) return LIBUSB_ERROR_NOT_FOUND; r = usbi_backend->get_config_descriptor(dev, config_index, tmp, LIBUSB_DT_CONFIG_SIZE, &host_endian); if (r < 0) return r; if (r < LIBUSB_DT_CONFIG_SIZE) { usbi_err(dev->ctx, "short config descriptor read %d/%d", r, LIBUSB_DT_CONFIG_SIZE); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(tmp, "bbw", &_config, host_endian); buf = malloc(_config.wTotalLength); if (!buf) return LIBUSB_ERROR_NO_MEM; r = usbi_backend->get_config_descriptor(dev, config_index, buf, _config.wTotalLength, &host_endian); if (r >= 0) r = raw_desc_to_config(dev->ctx, buf, r, host_endian, config); free(buf); return r; } /* iterate through all configurations, returning the index of the configuration * matching a specific bConfigurationValue in the idx output parameter, or -1 * if the config was not found. * returns 0 on success or a LIBUSB_ERROR code */ int usbi_get_config_index_by_value(struct libusb_device *dev, uint8_t bConfigurationValue, int *idx) { uint8_t i; usbi_dbg("value %d", bConfigurationValue); for (i = 0; i < dev->num_configurations; i++) { unsigned char tmp[6]; int host_endian; int r = usbi_backend->get_config_descriptor(dev, i, tmp, sizeof(tmp), &host_endian); if (r < 0) { *idx = -1; return r; } if (tmp[5] == bConfigurationValue) { *idx = i; return 0; } } *idx = -1; return 0; } /** \ingroup desc * Get a USB configuration descriptor with a specific bConfigurationValue. * This is a non-blocking function which does not involve any requests being * sent to the device. * * \param dev a device * \param bConfigurationValue the bConfigurationValue of the configuration you * wish to retrieve * \param config output location for the USB configuration descriptor. Only * valid if 0 was returned. Must be freed with libusb_free_config_descriptor() * after use. * \returns 0 on success * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist * \returns another LIBUSB_ERROR code on error * \see libusb_get_active_config_descriptor() * \see libusb_get_config_descriptor() */ int API_EXPORTED libusb_get_config_descriptor_by_value(libusb_device *dev, uint8_t bConfigurationValue, struct libusb_config_descriptor **config) { int r, idx, host_endian; unsigned char *buf = NULL; if (usbi_backend->get_config_descriptor_by_value) { r = usbi_backend->get_config_descriptor_by_value(dev, bConfigurationValue, &buf, &host_endian); if (r < 0) return r; return raw_desc_to_config(dev->ctx, buf, r, host_endian, config); } r = usbi_get_config_index_by_value(dev, bConfigurationValue, &idx); if (r < 0) return r; else if (idx == -1) return LIBUSB_ERROR_NOT_FOUND; else return libusb_get_config_descriptor(dev, (uint8_t) idx, config); } /** \ingroup desc * Free a configuration descriptor obtained from * libusb_get_active_config_descriptor() or libusb_get_config_descriptor(). * It is safe to call this function with a NULL config parameter, in which * case the function simply returns. * * \param config the configuration descriptor to free */ void API_EXPORTED libusb_free_config_descriptor( struct libusb_config_descriptor *config) { if (!config) return; clear_configuration(config); free(config); } /** \ingroup desc * Get an endpoints superspeed endpoint companion descriptor (if any) * * \param ctx the context to operate on, or NULL for the default context * \param endpoint endpoint descriptor from which to get the superspeed * endpoint companion descriptor * \param ep_comp output location for the superspeed endpoint companion * descriptor. Only valid if 0 was returned. Must be freed with * libusb_free_ss_endpoint_companion_descriptor() after use. * \returns 0 on success * \returns LIBUSB_ERROR_NOT_FOUND if the configuration does not exist * \returns another LIBUSB_ERROR code on error */ int API_EXPORTED libusb_get_ss_endpoint_companion_descriptor( struct libusb_context *ctx, const struct libusb_endpoint_descriptor *endpoint, struct libusb_ss_endpoint_companion_descriptor **ep_comp) { struct usb_descriptor_header header; int size = endpoint->extra_length; const unsigned char *buffer = endpoint->extra; *ep_comp = NULL; while (size >= DESC_HEADER_LENGTH) { usbi_parse_descriptor(buffer, "bb", &header, 0); if (header.bLength < 2 || header.bLength > size) { usbi_err(ctx, "invalid descriptor length %d", header.bLength); return LIBUSB_ERROR_IO; } if (header.bDescriptorType != LIBUSB_DT_SS_ENDPOINT_COMPANION) { buffer += header.bLength; size -= header.bLength; continue; } if (header.bLength < LIBUSB_DT_SS_ENDPOINT_COMPANION_SIZE) { usbi_err(ctx, "invalid ss-ep-comp-desc length %d", header.bLength); return LIBUSB_ERROR_IO; } *ep_comp = malloc(sizeof(**ep_comp)); if (*ep_comp == NULL) return LIBUSB_ERROR_NO_MEM; usbi_parse_descriptor(buffer, "bbbbw", *ep_comp, 0); return LIBUSB_SUCCESS; } return LIBUSB_ERROR_NOT_FOUND; } /** \ingroup desc * Free a superspeed endpoint companion descriptor obtained from * libusb_get_ss_endpoint_companion_descriptor(). * It is safe to call this function with a NULL ep_comp parameter, in which * case the function simply returns. * * \param ep_comp the superspeed endpoint companion descriptor to free */ void API_EXPORTED libusb_free_ss_endpoint_companion_descriptor( struct libusb_ss_endpoint_companion_descriptor *ep_comp) { free(ep_comp); } static int parse_bos(struct libusb_context *ctx, struct libusb_bos_descriptor **bos, unsigned char *buffer, int size, int host_endian) { struct libusb_bos_descriptor bos_header, *_bos; struct libusb_bos_dev_capability_descriptor dev_cap; int i; if (size < LIBUSB_DT_BOS_SIZE) { usbi_err(ctx, "short bos descriptor read %d/%d", size, LIBUSB_DT_BOS_SIZE); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(buffer, "bbwb", &bos_header, host_endian); if (bos_header.bDescriptorType != LIBUSB_DT_BOS) { usbi_err(ctx, "unexpected descriptor %x (expected %x)", bos_header.bDescriptorType, LIBUSB_DT_BOS); return LIBUSB_ERROR_IO; } if (bos_header.bLength < LIBUSB_DT_BOS_SIZE) { usbi_err(ctx, "invalid bos bLength (%d)", bos_header.bLength); return LIBUSB_ERROR_IO; } if (bos_header.bLength > size) { usbi_err(ctx, "short bos descriptor read %d/%d", size, bos_header.bLength); return LIBUSB_ERROR_IO; } _bos = calloc(1, sizeof(*_bos) + bos_header.bNumDeviceCaps * sizeof(void *)); if (!_bos) return LIBUSB_ERROR_NO_MEM; usbi_parse_descriptor(buffer, "bbwb", _bos, host_endian); buffer += bos_header.bLength; size -= bos_header.bLength; /* Get the device capability descriptors */ for (i = 0; i < bos_header.bNumDeviceCaps; i++) { if (size < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) { usbi_warn(ctx, "short dev-cap descriptor read %d/%d", size, LIBUSB_DT_DEVICE_CAPABILITY_SIZE); break; } usbi_parse_descriptor(buffer, "bbb", &dev_cap, host_endian); if (dev_cap.bDescriptorType != LIBUSB_DT_DEVICE_CAPABILITY) { usbi_warn(ctx, "unexpected descriptor %x (expected %x)", dev_cap.bDescriptorType, LIBUSB_DT_DEVICE_CAPABILITY); break; } if (dev_cap.bLength < LIBUSB_DT_DEVICE_CAPABILITY_SIZE) { usbi_err(ctx, "invalid dev-cap bLength (%d)", dev_cap.bLength); libusb_free_bos_descriptor(_bos); return LIBUSB_ERROR_IO; } if (dev_cap.bLength > size) { usbi_warn(ctx, "short dev-cap descriptor read %d/%d", size, dev_cap.bLength); break; } _bos->dev_capability[i] = malloc(dev_cap.bLength); if (!_bos->dev_capability[i]) { libusb_free_bos_descriptor(_bos); return LIBUSB_ERROR_NO_MEM; } memcpy(_bos->dev_capability[i], buffer, dev_cap.bLength); buffer += dev_cap.bLength; size -= dev_cap.bLength; } _bos->bNumDeviceCaps = (uint8_t) i; *bos = _bos; return LIBUSB_SUCCESS; } /** \ingroup desc * Get a Binary Object Store (BOS) descriptor * This is a BLOCKING function, which will send requests to the device. * * \param handle the handle of an open libusb device * \param bos output location for the BOS descriptor. Only valid if 0 was returned. * Must be freed with \ref libusb_free_bos_descriptor() after use. * \returns 0 on success * \returns LIBUSB_ERROR_NOT_FOUND if the device doesn't have a BOS descriptor * \returns another LIBUSB_ERROR code on error */ int API_EXPORTED libusb_get_bos_descriptor(libusb_device_handle *handle, struct libusb_bos_descriptor **bos) { struct libusb_bos_descriptor _bos; uint8_t bos_header[LIBUSB_DT_BOS_SIZE] = {0}; unsigned char *bos_data = NULL; const int host_endian = 0; int r; /* Read the BOS. This generates 2 requests on the bus, * one for the header, and one for the full BOS */ r = libusb_get_descriptor(handle, LIBUSB_DT_BOS, 0, bos_header, LIBUSB_DT_BOS_SIZE); if (r < 0) { if (r != LIBUSB_ERROR_PIPE) usbi_err(handle->dev->ctx, "failed to read BOS (%d)", r); return r; } if (r < LIBUSB_DT_BOS_SIZE) { usbi_err(handle->dev->ctx, "short BOS read %d/%d", r, LIBUSB_DT_BOS_SIZE); return LIBUSB_ERROR_IO; } usbi_parse_descriptor(bos_header, "bbwb", &_bos, host_endian); usbi_dbg("found BOS descriptor: size %d bytes, %d capabilities", _bos.wTotalLength, _bos.bNumDeviceCaps); bos_data = calloc(_bos.wTotalLength, 1); if (bos_data == NULL) return LIBUSB_ERROR_NO_MEM; r = libusb_get_descriptor(handle, LIBUSB_DT_BOS, 0, bos_data, _bos.wTotalLength); if (r >= 0) r = parse_bos(handle->dev->ctx, bos, bos_data, r, host_endian); else usbi_err(handle->dev->ctx, "failed to read BOS (%d)", r); free(bos_data); return r; } /** \ingroup desc * Free a BOS descriptor obtained from libusb_get_bos_descriptor(). * It is safe to call this function with a NULL bos parameter, in which * case the function simply returns. * * \param bos the BOS descriptor to free */ void API_EXPORTED libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos) { int i; if (!bos) return; for (i = 0; i < bos->bNumDeviceCaps; i++) free(bos->dev_capability[i]); free(bos); } /** \ingroup desc * Get an USB 2.0 Extension descriptor * * \param ctx the context to operate on, or NULL for the default context * \param dev_cap Device Capability descriptor with a bDevCapabilityType of * \ref libusb_capability_type::LIBUSB_BT_USB_2_0_EXTENSION * LIBUSB_BT_USB_2_0_EXTENSION * \param usb_2_0_extension output location for the USB 2.0 Extension * descriptor. Only valid if 0 was returned. Must be freed with * libusb_free_usb_2_0_extension_descriptor() after use. * \returns 0 on success * \returns a LIBUSB_ERROR code on error */ int API_EXPORTED libusb_get_usb_2_0_extension_descriptor( struct libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension) { struct libusb_usb_2_0_extension_descriptor *_usb_2_0_extension; const int host_endian = 0; if (dev_cap->bDevCapabilityType != LIBUSB_BT_USB_2_0_EXTENSION) { usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", dev_cap->bDevCapabilityType, LIBUSB_BT_USB_2_0_EXTENSION); return LIBUSB_ERROR_INVALID_PARAM; } if (dev_cap->bLength < LIBUSB_BT_USB_2_0_EXTENSION_SIZE) { usbi_err(ctx, "short dev-cap descriptor read %d/%d", dev_cap->bLength, LIBUSB_BT_USB_2_0_EXTENSION_SIZE); return LIBUSB_ERROR_IO; } _usb_2_0_extension = malloc(sizeof(*_usb_2_0_extension)); if (!_usb_2_0_extension) return LIBUSB_ERROR_NO_MEM; usbi_parse_descriptor((unsigned char *) dev_cap, "bbbd", _usb_2_0_extension, host_endian); *usb_2_0_extension = _usb_2_0_extension; return LIBUSB_SUCCESS; } /** \ingroup desc * Free a USB 2.0 Extension descriptor obtained from * libusb_get_usb_2_0_extension_descriptor(). * It is safe to call this function with a NULL usb_2_0_extension parameter, * in which case the function simply returns. * * \param usb_2_0_extension the USB 2.0 Extension descriptor to free */ void API_EXPORTED libusb_free_usb_2_0_extension_descriptor( struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension) { free(usb_2_0_extension); } /** \ingroup desc * Get a SuperSpeed USB Device Capability descriptor * * \param ctx the context to operate on, or NULL for the default context * \param dev_cap Device Capability descriptor with a bDevCapabilityType of * \ref libusb_capability_type::LIBUSB_BT_SS_USB_DEVICE_CAPABILITY * LIBUSB_BT_SS_USB_DEVICE_CAPABILITY * \param ss_usb_device_cap output location for the SuperSpeed USB Device * Capability descriptor. Only valid if 0 was returned. Must be freed with * libusb_free_ss_usb_device_capability_descriptor() after use. * \returns 0 on success * \returns a LIBUSB_ERROR code on error */ int API_EXPORTED libusb_get_ss_usb_device_capability_descriptor( struct libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap) { struct libusb_ss_usb_device_capability_descriptor *_ss_usb_device_cap; const int host_endian = 0; if (dev_cap->bDevCapabilityType != LIBUSB_BT_SS_USB_DEVICE_CAPABILITY) { usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", dev_cap->bDevCapabilityType, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY); return LIBUSB_ERROR_INVALID_PARAM; } if (dev_cap->bLength < LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) { usbi_err(ctx, "short dev-cap descriptor read %d/%d", dev_cap->bLength, LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE); return LIBUSB_ERROR_IO; } _ss_usb_device_cap = malloc(sizeof(*_ss_usb_device_cap)); if (!_ss_usb_device_cap) return LIBUSB_ERROR_NO_MEM; usbi_parse_descriptor((unsigned char *) dev_cap, "bbbbwbbw", _ss_usb_device_cap, host_endian); *ss_usb_device_cap = _ss_usb_device_cap; return LIBUSB_SUCCESS; } /** \ingroup desc * Free a SuperSpeed USB Device Capability descriptor obtained from * libusb_get_ss_usb_device_capability_descriptor(). * It is safe to call this function with a NULL ss_usb_device_cap * parameter, in which case the function simply returns. * * \param ss_usb_device_cap the USB 2.0 Extension descriptor to free */ void API_EXPORTED libusb_free_ss_usb_device_capability_descriptor( struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap) { free(ss_usb_device_cap); } /** \ingroup desc * Get a Container ID descriptor * * \param ctx the context to operate on, or NULL for the default context * \param dev_cap Device Capability descriptor with a bDevCapabilityType of * \ref libusb_capability_type::LIBUSB_BT_CONTAINER_ID * LIBUSB_BT_CONTAINER_ID * \param container_id output location for the Container ID descriptor. * Only valid if 0 was returned. Must be freed with * libusb_free_container_id_descriptor() after use. * \returns 0 on success * \returns a LIBUSB_ERROR code on error */ int API_EXPORTED libusb_get_container_id_descriptor(struct libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_container_id_descriptor **container_id) { struct libusb_container_id_descriptor *_container_id; const int host_endian = 0; if (dev_cap->bDevCapabilityType != LIBUSB_BT_CONTAINER_ID) { usbi_err(ctx, "unexpected bDevCapabilityType %x (expected %x)", dev_cap->bDevCapabilityType, LIBUSB_BT_CONTAINER_ID); return LIBUSB_ERROR_INVALID_PARAM; } if (dev_cap->bLength < LIBUSB_BT_CONTAINER_ID_SIZE) { usbi_err(ctx, "short dev-cap descriptor read %d/%d", dev_cap->bLength, LIBUSB_BT_CONTAINER_ID_SIZE); return LIBUSB_ERROR_IO; } _container_id = malloc(sizeof(*_container_id)); if (!_container_id) return LIBUSB_ERROR_NO_MEM; usbi_parse_descriptor((unsigned char *) dev_cap, "bbbbu", _container_id, host_endian); *container_id = _container_id; return LIBUSB_SUCCESS; } /** \ingroup desc * Free a Container ID descriptor obtained from * libusb_get_container_id_descriptor(). * It is safe to call this function with a NULL container_id parameter, * in which case the function simply returns. * * \param container_id the USB 2.0 Extension descriptor to free */ void API_EXPORTED libusb_free_container_id_descriptor( struct libusb_container_id_descriptor *container_id) { free(container_id); } /** \ingroup desc * Retrieve a string descriptor in C style ASCII. * * Wrapper around libusb_get_string_descriptor(). Uses the first language * supported by the device. * * \param dev a device handle * \param desc_index the index of the descriptor to retrieve * \param data output buffer for ASCII string descriptor * \param length size of data buffer * \returns number of bytes returned in data, or LIBUSB_ERROR code on failure */ int API_EXPORTED libusb_get_string_descriptor_ascii(libusb_device_handle *dev, uint8_t desc_index, unsigned char *data, int length) { unsigned char tbuf[255]; /* Some devices choke on size > 255 */ int r, si, di; uint16_t langid; /* Asking for the zero'th index is special - it returns a string * descriptor that contains all the language IDs supported by the * device. Typically there aren't many - often only one. Language * IDs are 16 bit numbers, and they start at the third byte in the * descriptor. There's also no point in trying to read descriptor 0 * with this function. See USB 2.0 specification section 9.6.7 for * more information. */ if (desc_index == 0) return LIBUSB_ERROR_INVALID_PARAM; r = libusb_get_string_descriptor(dev, 0, 0, tbuf, sizeof(tbuf)); if (r < 0) return r; if (r < 4) return LIBUSB_ERROR_IO; langid = tbuf[2] | (tbuf[3] << 8); r = libusb_get_string_descriptor(dev, desc_index, langid, tbuf, sizeof(tbuf)); if (r < 0) return r; if (tbuf[1] != LIBUSB_DT_STRING) return LIBUSB_ERROR_IO; if (tbuf[0] > r) return LIBUSB_ERROR_IO; for (di = 0, si = 2; si < tbuf[0]; si += 2) { if (di >= (length - 1)) break; if ((tbuf[si] & 0x80) || (tbuf[si + 1])) /* non-ASCII */ data[di++] = '?'; else data[di++] = tbuf[si]; } data[di] = 0; return di; }
93699.c
/* * Driver interaction with Linux nl80211/cfg80211 - Capabilities * Copyright (c) 2002-2015, Jouni Malinen <[email protected]> * Copyright (c) 2007, Johannes Berg <[email protected]> * Copyright (c) 2009-2010, Atheros Communications * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include <netlink/genl/genl.h> #include "utils/common.h" #include "common/ieee802_11_defs.h" #include "common/ieee802_11_common.h" #include "common/qca-vendor.h" #include "common/qca-vendor-attr.h" #include "driver_nl80211.h" static int protocol_feature_handler(struct nl_msg *msg, void *arg) { u32 *feat = arg; struct nlattr *tb_msg[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (tb_msg[NL80211_ATTR_PROTOCOL_FEATURES]) *feat = nla_get_u32(tb_msg[NL80211_ATTR_PROTOCOL_FEATURES]); return NL_SKIP; } static u32 get_nl80211_protocol_features(struct wpa_driver_nl80211_data *drv) { u32 feat = 0; struct nl_msg *msg; msg = nlmsg_alloc(); if (!msg) return 0; if (!nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_PROTOCOL_FEATURES)) { nlmsg_free(msg); return 0; } if (send_and_recv_msgs(drv, msg, protocol_feature_handler, &feat) == 0) return feat; return 0; } struct wiphy_info_data { struct wpa_driver_nl80211_data *drv; struct wpa_driver_capa *capa; unsigned int num_multichan_concurrent; unsigned int error:1; unsigned int device_ap_sme:1; unsigned int poll_command_supported:1; unsigned int data_tx_status:1; unsigned int auth_supported:1; unsigned int connect_supported:1; unsigned int p2p_go_supported:1; unsigned int p2p_client_supported:1; unsigned int p2p_go_ctwindow_supported:1; unsigned int p2p_concurrent:1; unsigned int channel_switch_supported:1; unsigned int set_qos_map_supported:1; unsigned int have_low_prio_scan:1; unsigned int wmm_ac_supported:1; unsigned int mac_addr_rand_scan_supported:1; unsigned int mac_addr_rand_sched_scan_supported:1; }; static unsigned int probe_resp_offload_support(int supp_protocols) { unsigned int prot = 0; if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS) prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS; if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2) prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2; if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P) prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P; if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U) prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING; return prot; } static void wiphy_info_supported_iftypes(struct wiphy_info_data *info, struct nlattr *tb) { struct nlattr *nl_mode; int i; if (tb == NULL) return; nla_for_each_nested(nl_mode, tb, i) { switch (nla_type(nl_mode)) { case NL80211_IFTYPE_AP: info->capa->flags |= WPA_DRIVER_FLAGS_AP; break; case NL80211_IFTYPE_MESH_POINT: info->capa->flags |= WPA_DRIVER_FLAGS_MESH; break; case NL80211_IFTYPE_ADHOC: info->capa->flags |= WPA_DRIVER_FLAGS_IBSS; break; case NL80211_IFTYPE_P2P_DEVICE: info->capa->flags |= WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE; break; case NL80211_IFTYPE_P2P_GO: info->p2p_go_supported = 1; break; case NL80211_IFTYPE_P2P_CLIENT: info->p2p_client_supported = 1; break; } } } static int wiphy_info_iface_comb_process(struct wiphy_info_data *info, struct nlattr *nl_combi) { struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB]; struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT]; struct nlattr *nl_limit, *nl_mode; int err, rem_limit, rem_mode; int combination_has_p2p = 0, combination_has_mgd = 0; static struct nla_policy iface_combination_policy[NUM_NL80211_IFACE_COMB] = { [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED }, [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 }, [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG }, [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 }, [NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS] = { .type = NLA_U32 }, }, iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = { [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED }, [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 }, }; err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB, nl_combi, iface_combination_policy); if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] || !tb_comb[NL80211_IFACE_COMB_MAXNUM] || !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]) return 0; /* broken combination */ if (tb_comb[NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS]) info->capa->flags |= WPA_DRIVER_FLAGS_RADAR; nla_for_each_nested(nl_limit, tb_comb[NL80211_IFACE_COMB_LIMITS], rem_limit) { err = nla_parse_nested(tb_limit, MAX_NL80211_IFACE_LIMIT, nl_limit, iface_limit_policy); if (err || !tb_limit[NL80211_IFACE_LIMIT_TYPES]) return 0; /* broken combination */ nla_for_each_nested(nl_mode, tb_limit[NL80211_IFACE_LIMIT_TYPES], rem_mode) { int ift = nla_type(nl_mode); if (ift == NL80211_IFTYPE_P2P_GO || ift == NL80211_IFTYPE_P2P_CLIENT) combination_has_p2p = 1; if (ift == NL80211_IFTYPE_STATION) combination_has_mgd = 1; } if (combination_has_p2p && combination_has_mgd) break; } if (combination_has_p2p && combination_has_mgd) { unsigned int num_channels = nla_get_u32(tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]); info->p2p_concurrent = 1; if (info->num_multichan_concurrent < num_channels) info->num_multichan_concurrent = num_channels; } return 0; } static void wiphy_info_iface_comb(struct wiphy_info_data *info, struct nlattr *tb) { struct nlattr *nl_combi; int rem_combi; if (tb == NULL) return; nla_for_each_nested(nl_combi, tb, rem_combi) { if (wiphy_info_iface_comb_process(info, nl_combi) > 0) break; } } static void wiphy_info_supp_cmds(struct wiphy_info_data *info, struct nlattr *tb) { struct nlattr *nl_cmd; int i; if (tb == NULL) return; nla_for_each_nested(nl_cmd, tb, i) { switch (nla_get_u32(nl_cmd)) { case NL80211_CMD_AUTHENTICATE: info->auth_supported = 1; break; case NL80211_CMD_CONNECT: info->connect_supported = 1; break; case NL80211_CMD_START_SCHED_SCAN: info->capa->sched_scan_supported = 1; break; case NL80211_CMD_PROBE_CLIENT: info->poll_command_supported = 1; break; case NL80211_CMD_CHANNEL_SWITCH: info->channel_switch_supported = 1; break; case NL80211_CMD_SET_QOS_MAP: info->set_qos_map_supported = 1; break; } } } static void wiphy_info_cipher_suites(struct wiphy_info_data *info, struct nlattr *tb) { int i, num; u32 *ciphers; if (tb == NULL) return; num = nla_len(tb) / sizeof(u32); ciphers = nla_data(tb); for (i = 0; i < num; i++) { u32 c = ciphers[i]; wpa_printf(MSG_DEBUG, "nl80211: Supported cipher %02x-%02x-%02x:%d", c >> 24, (c >> 16) & 0xff, (c >> 8) & 0xff, c & 0xff); switch (c) { case WLAN_CIPHER_SUITE_CCMP_256: info->capa->enc |= WPA_DRIVER_CAPA_ENC_CCMP_256; break; case WLAN_CIPHER_SUITE_GCMP_256: info->capa->enc |= WPA_DRIVER_CAPA_ENC_GCMP_256; break; case WLAN_CIPHER_SUITE_CCMP: info->capa->enc |= WPA_DRIVER_CAPA_ENC_CCMP; break; case WLAN_CIPHER_SUITE_GCMP: info->capa->enc |= WPA_DRIVER_CAPA_ENC_GCMP; break; case WLAN_CIPHER_SUITE_TKIP: info->capa->enc |= WPA_DRIVER_CAPA_ENC_TKIP; break; case WLAN_CIPHER_SUITE_WEP104: info->capa->enc |= WPA_DRIVER_CAPA_ENC_WEP104; break; case WLAN_CIPHER_SUITE_WEP40: info->capa->enc |= WPA_DRIVER_CAPA_ENC_WEP40; break; case WLAN_CIPHER_SUITE_AES_CMAC: info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP; break; case WLAN_CIPHER_SUITE_BIP_GMAC_128: info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_GMAC_128; break; case WLAN_CIPHER_SUITE_BIP_GMAC_256: info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_GMAC_256; break; case WLAN_CIPHER_SUITE_BIP_CMAC_256: info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_CMAC_256; break; case WLAN_CIPHER_SUITE_NO_GROUP_ADDR: info->capa->enc |= WPA_DRIVER_CAPA_ENC_GTK_NOT_USED; break; } } } static void wiphy_info_max_roc(struct wpa_driver_capa *capa, struct nlattr *tb) { if (tb) capa->max_remain_on_chan = nla_get_u32(tb); } static void wiphy_info_tdls(struct wpa_driver_capa *capa, struct nlattr *tdls, struct nlattr *ext_setup) { if (tdls == NULL) return; wpa_printf(MSG_DEBUG, "nl80211: TDLS supported"); capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT; if (ext_setup) { wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup"); capa->flags |= WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP; } } static int ext_feature_isset(const u8 *ext_features, int ext_features_len, enum nl80211_ext_feature_index ftidx) { u8 ft_byte; if ((int) ftidx / 8 >= ext_features_len) return 0; ft_byte = ext_features[ftidx / 8]; return (ft_byte & BIT(ftidx % 8)) != 0; } static void wiphy_info_ext_feature_flags(struct wiphy_info_data *info, struct nlattr *tb) { struct wpa_driver_capa *capa = info->capa; u8 *ext_features; int len; if (tb == NULL) return; ext_features = nla_data(tb); len = nla_len(tb); if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_VHT_IBSS)) capa->flags |= WPA_DRIVER_FLAGS_VHT_IBSS; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_RRM)) capa->rrm_flags |= WPA_DRIVER_FLAGS_SUPPORT_RRM; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_FILS_STA)) capa->flags |= WPA_DRIVER_FLAGS_SUPPORT_FILS; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_BEACON_RATE_LEGACY)) capa->flags |= WPA_DRIVER_FLAGS_BEACON_RATE_LEGACY; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_BEACON_RATE_HT)) capa->flags |= WPA_DRIVER_FLAGS_BEACON_RATE_HT; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_BEACON_RATE_VHT)) capa->flags |= WPA_DRIVER_FLAGS_BEACON_RATE_VHT; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_SET_SCAN_DWELL)) capa->rrm_flags |= WPA_DRIVER_FLAGS_SUPPORT_SET_SCAN_DWELL; if (ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_SCAN_START_TIME) && ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_BSS_PARENT_TSF) && ext_feature_isset(ext_features, len, NL80211_EXT_FEATURE_SET_SCAN_DWELL)) capa->rrm_flags |= WPA_DRIVER_FLAGS_SUPPORT_BEACON_REPORT; } static void wiphy_info_feature_flags(struct wiphy_info_data *info, struct nlattr *tb) { u32 flags; struct wpa_driver_capa *capa = info->capa; if (tb == NULL) return; flags = nla_get_u32(tb); if (flags & NL80211_FEATURE_SK_TX_STATUS) info->data_tx_status = 1; if (flags & NL80211_FEATURE_INACTIVITY_TIMER) capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER; if (flags & NL80211_FEATURE_SAE) capa->flags |= WPA_DRIVER_FLAGS_SAE; if (flags & NL80211_FEATURE_NEED_OBSS_SCAN) capa->flags |= WPA_DRIVER_FLAGS_OBSS_SCAN; if (flags & NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE) capa->flags |= WPA_DRIVER_FLAGS_HT_2040_COEX; if (flags & NL80211_FEATURE_TDLS_CHANNEL_SWITCH) { wpa_printf(MSG_DEBUG, "nl80211: TDLS channel switch"); capa->flags |= WPA_DRIVER_FLAGS_TDLS_CHANNEL_SWITCH; } if (flags & NL80211_FEATURE_P2P_GO_CTWIN) info->p2p_go_ctwindow_supported = 1; if (flags & NL80211_FEATURE_LOW_PRIORITY_SCAN) info->have_low_prio_scan = 1; if (flags & NL80211_FEATURE_SCAN_RANDOM_MAC_ADDR) info->mac_addr_rand_scan_supported = 1; if (flags & NL80211_FEATURE_SCHED_SCAN_RANDOM_MAC_ADDR) info->mac_addr_rand_sched_scan_supported = 1; if (flags & NL80211_FEATURE_STATIC_SMPS) capa->smps_modes |= WPA_DRIVER_SMPS_MODE_STATIC; if (flags & NL80211_FEATURE_DYNAMIC_SMPS) capa->smps_modes |= WPA_DRIVER_SMPS_MODE_DYNAMIC; if (flags & NL80211_FEATURE_SUPPORTS_WMM_ADMISSION) info->wmm_ac_supported = 1; if (flags & NL80211_FEATURE_DS_PARAM_SET_IE_IN_PROBES) capa->rrm_flags |= WPA_DRIVER_FLAGS_DS_PARAM_SET_IE_IN_PROBES; if (flags & NL80211_FEATURE_WFA_TPC_IE_IN_PROBES) capa->rrm_flags |= WPA_DRIVER_FLAGS_WFA_TPC_IE_IN_PROBES; if (flags & NL80211_FEATURE_QUIET) capa->rrm_flags |= WPA_DRIVER_FLAGS_QUIET; if (flags & NL80211_FEATURE_TX_POWER_INSERTION) capa->rrm_flags |= WPA_DRIVER_FLAGS_TX_POWER_INSERTION; if (flags & NL80211_FEATURE_HT_IBSS) capa->flags |= WPA_DRIVER_FLAGS_HT_IBSS; if (flags & NL80211_FEATURE_FULL_AP_CLIENT_STATE) capa->flags |= WPA_DRIVER_FLAGS_FULL_AP_CLIENT_STATE; } static void wiphy_info_probe_resp_offload(struct wpa_driver_capa *capa, struct nlattr *tb) { u32 protocols; if (tb == NULL) return; protocols = nla_get_u32(tb); wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response offload in AP " "mode"); capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD; capa->probe_resp_offloads = probe_resp_offload_support(protocols); } static void wiphy_info_wowlan_triggers(struct wpa_driver_capa *capa, struct nlattr *tb) { struct nlattr *triggers[MAX_NL80211_WOWLAN_TRIG + 1]; if (tb == NULL) return; if (nla_parse_nested(triggers, MAX_NL80211_WOWLAN_TRIG, tb, NULL)) return; if (triggers[NL80211_WOWLAN_TRIG_ANY]) capa->wowlan_triggers.any = 1; if (triggers[NL80211_WOWLAN_TRIG_DISCONNECT]) capa->wowlan_triggers.disconnect = 1; if (triggers[NL80211_WOWLAN_TRIG_MAGIC_PKT]) capa->wowlan_triggers.magic_pkt = 1; if (triggers[NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE]) capa->wowlan_triggers.gtk_rekey_failure = 1; if (triggers[NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST]) capa->wowlan_triggers.eap_identity_req = 1; if (triggers[NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE]) capa->wowlan_triggers.four_way_handshake = 1; if (triggers[NL80211_WOWLAN_TRIG_RFKILL_RELEASE]) capa->wowlan_triggers.rfkill_release = 1; } static void wiphy_info_extended_capab(struct wpa_driver_nl80211_data *drv, struct nlattr *tb) { int rem = 0, i; struct nlattr *tb1[NL80211_ATTR_MAX + 1], *attr; if (!tb || drv->num_iface_ext_capa == NL80211_IFTYPE_MAX) return; nla_for_each_nested(attr, tb, rem) { unsigned int len; struct drv_nl80211_ext_capa *capa; nla_parse(tb1, NL80211_ATTR_MAX, nla_data(attr), nla_len(attr), NULL); if (!tb1[NL80211_ATTR_IFTYPE] || !tb1[NL80211_ATTR_EXT_CAPA] || !tb1[NL80211_ATTR_EXT_CAPA_MASK]) continue; capa = &drv->iface_ext_capa[drv->num_iface_ext_capa]; capa->iftype = nla_get_u32(tb1[NL80211_ATTR_IFTYPE]); wpa_printf(MSG_DEBUG, "nl80211: Driver-advertised extended capabilities for interface type %s", nl80211_iftype_str(capa->iftype)); len = nla_len(tb1[NL80211_ATTR_EXT_CAPA]); capa->ext_capa = os_malloc(len); if (!capa->ext_capa) goto err; os_memcpy(capa->ext_capa, nla_data(tb1[NL80211_ATTR_EXT_CAPA]), len); capa->ext_capa_len = len; wpa_hexdump(MSG_DEBUG, "nl80211: Extended capabilities", capa->ext_capa, capa->ext_capa_len); len = nla_len(tb1[NL80211_ATTR_EXT_CAPA_MASK]); capa->ext_capa_mask = os_malloc(len); if (!capa->ext_capa_mask) goto err; os_memcpy(capa->ext_capa_mask, nla_data(tb1[NL80211_ATTR_EXT_CAPA_MASK]), len); wpa_hexdump(MSG_DEBUG, "nl80211: Extended capabilities mask", capa->ext_capa_mask, capa->ext_capa_len); drv->num_iface_ext_capa++; if (drv->num_iface_ext_capa == NL80211_IFTYPE_MAX) break; } return; err: /* Cleanup allocated memory on error */ for (i = 0; i < NL80211_IFTYPE_MAX; i++) { os_free(drv->iface_ext_capa[i].ext_capa); drv->iface_ext_capa[i].ext_capa = NULL; os_free(drv->iface_ext_capa[i].ext_capa_mask); drv->iface_ext_capa[i].ext_capa_mask = NULL; drv->iface_ext_capa[i].ext_capa_len = 0; } drv->num_iface_ext_capa = 0; } static int wiphy_info_handler(struct nl_msg *msg, void *arg) { struct nlattr *tb[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); struct wiphy_info_data *info = arg; struct wpa_driver_capa *capa = info->capa; struct wpa_driver_nl80211_data *drv = info->drv; nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (tb[NL80211_ATTR_WIPHY]) drv->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]); if (tb[NL80211_ATTR_WIPHY_NAME]) os_strlcpy(drv->phyname, nla_get_string(tb[NL80211_ATTR_WIPHY_NAME]), sizeof(drv->phyname)); if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]) capa->max_scan_ssids = nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]); if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]) capa->max_sched_scan_ssids = nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]); if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_PLANS] && tb[NL80211_ATTR_MAX_SCAN_PLAN_INTERVAL] && tb[NL80211_ATTR_MAX_SCAN_PLAN_ITERATIONS]) { capa->max_sched_scan_plans = nla_get_u32(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_PLANS]); capa->max_sched_scan_plan_interval = nla_get_u32(tb[NL80211_ATTR_MAX_SCAN_PLAN_INTERVAL]); capa->max_sched_scan_plan_iterations = nla_get_u32(tb[NL80211_ATTR_MAX_SCAN_PLAN_ITERATIONS]); } if (tb[NL80211_ATTR_MAX_MATCH_SETS]) capa->max_match_sets = nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]); if (tb[NL80211_ATTR_MAC_ACL_MAX]) capa->max_acl_mac_addrs = nla_get_u8(tb[NL80211_ATTR_MAC_ACL_MAX]); wiphy_info_supported_iftypes(info, tb[NL80211_ATTR_SUPPORTED_IFTYPES]); wiphy_info_iface_comb(info, tb[NL80211_ATTR_INTERFACE_COMBINATIONS]); wiphy_info_supp_cmds(info, tb[NL80211_ATTR_SUPPORTED_COMMANDS]); wiphy_info_cipher_suites(info, tb[NL80211_ATTR_CIPHER_SUITES]); if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) { wpa_printf(MSG_DEBUG, "nl80211: Using driver-based " "off-channel TX"); capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX; } if (tb[NL80211_ATTR_ROAM_SUPPORT]) { wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming"); capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION; } wiphy_info_max_roc(capa, tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]); if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD]) capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD; wiphy_info_tdls(capa, tb[NL80211_ATTR_TDLS_SUPPORT], tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]); if (tb[NL80211_ATTR_DEVICE_AP_SME]) info->device_ap_sme = 1; wiphy_info_feature_flags(info, tb[NL80211_ATTR_FEATURE_FLAGS]); wiphy_info_ext_feature_flags(info, tb[NL80211_ATTR_EXT_FEATURES]); wiphy_info_probe_resp_offload(capa, tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]); if (tb[NL80211_ATTR_EXT_CAPA] && tb[NL80211_ATTR_EXT_CAPA_MASK] && drv->extended_capa == NULL) { drv->extended_capa = os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA])); if (drv->extended_capa) { os_memcpy(drv->extended_capa, nla_data(tb[NL80211_ATTR_EXT_CAPA]), nla_len(tb[NL80211_ATTR_EXT_CAPA])); drv->extended_capa_len = nla_len(tb[NL80211_ATTR_EXT_CAPA]); wpa_hexdump(MSG_DEBUG, "nl80211: Driver-advertised extended capabilities (default)", drv->extended_capa, drv->extended_capa_len); } drv->extended_capa_mask = os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA_MASK])); if (drv->extended_capa_mask) { os_memcpy(drv->extended_capa_mask, nla_data(tb[NL80211_ATTR_EXT_CAPA_MASK]), nla_len(tb[NL80211_ATTR_EXT_CAPA_MASK])); wpa_hexdump(MSG_DEBUG, "nl80211: Driver-advertised extended capabilities mask (default)", drv->extended_capa_mask, drv->extended_capa_len); } else { os_free(drv->extended_capa); drv->extended_capa = NULL; drv->extended_capa_len = 0; } } wiphy_info_extended_capab(drv, tb[NL80211_ATTR_IFTYPE_EXT_CAPA]); if (tb[NL80211_ATTR_VENDOR_DATA]) { struct nlattr *nl; int rem; nla_for_each_nested(nl, tb[NL80211_ATTR_VENDOR_DATA], rem) { struct nl80211_vendor_cmd_info *vinfo; if (nla_len(nl) != sizeof(*vinfo)) { wpa_printf(MSG_DEBUG, "nl80211: Unexpected vendor data info"); continue; } vinfo = nla_data(nl); if (vinfo->vendor_id == OUI_QCA) { switch (vinfo->subcmd) { case QCA_NL80211_VENDOR_SUBCMD_TEST: drv->vendor_cmd_test_avail = 1; break; #ifdef CONFIG_DRIVER_NL80211_QCA case QCA_NL80211_VENDOR_SUBCMD_ROAMING: drv->roaming_vendor_cmd_avail = 1; break; case QCA_NL80211_VENDOR_SUBCMD_DFS_CAPABILITY: drv->dfs_vendor_cmd_avail = 1; break; case QCA_NL80211_VENDOR_SUBCMD_GET_FEATURES: drv->get_features_vendor_cmd_avail = 1; break; case QCA_NL80211_VENDOR_SUBCMD_GET_PREFERRED_FREQ_LIST: drv->get_pref_freq_list = 1; break; case QCA_NL80211_VENDOR_SUBCMD_SET_PROBABLE_OPER_CHANNEL: drv->set_prob_oper_freq = 1; break; case QCA_NL80211_VENDOR_SUBCMD_DO_ACS: drv->capa.flags |= WPA_DRIVER_FLAGS_ACS_OFFLOAD; break; case QCA_NL80211_VENDOR_SUBCMD_SETBAND: drv->setband_vendor_cmd_avail = 1; break; case QCA_NL80211_VENDOR_SUBCMD_TRIGGER_SCAN: drv->scan_vendor_cmd_avail = 1; break; case QCA_NL80211_VENDOR_SUBCMD_SET_WIFI_CONFIGURATION: drv->set_wifi_conf_vendor_cmd_avail = 1; break; #endif /* CONFIG_DRIVER_NL80211_QCA */ } } wpa_printf(MSG_DEBUG, "nl80211: Supported vendor command: vendor_id=0x%x subcmd=%u", vinfo->vendor_id, vinfo->subcmd); } } if (tb[NL80211_ATTR_VENDOR_EVENTS]) { struct nlattr *nl; int rem; nla_for_each_nested(nl, tb[NL80211_ATTR_VENDOR_EVENTS], rem) { struct nl80211_vendor_cmd_info *vinfo; if (nla_len(nl) != sizeof(*vinfo)) { wpa_printf(MSG_DEBUG, "nl80211: Unexpected vendor data info"); continue; } vinfo = nla_data(nl); wpa_printf(MSG_DEBUG, "nl80211: Supported vendor event: vendor_id=0x%x subcmd=%u", vinfo->vendor_id, vinfo->subcmd); } } if (tb[NL80211_ATTR_WIPHY_BANDS]) { struct nlattr *nl; int rem; nla_for_each_nested(nl, tb[NL80211_ATTR_WIPHY_BANDS], rem) { if (!(capa->bands_mask & (1<<nl->nla_type))) { wpa_printf(MSG_DEBUG, "Band %d supported.", nl->nla_type); capa->bands_mask |= (1<<nl->nla_type); } } } wiphy_info_wowlan_triggers(capa, tb[NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED]); if (tb[NL80211_ATTR_MAX_AP_ASSOC_STA]) capa->max_stations = nla_get_u32(tb[NL80211_ATTR_MAX_AP_ASSOC_STA]); if (tb[NL80211_ATTR_MAX_CSA_COUNTERS]) capa->max_csa_counters = nla_get_u8(tb[NL80211_ATTR_MAX_CSA_COUNTERS]); return NL_SKIP; } static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv, struct wiphy_info_data *info) { u32 feat; struct nl_msg *msg; int flags = 0; os_memset(info, 0, sizeof(*info)); info->capa = &drv->capa; info->drv = drv; feat = get_nl80211_protocol_features(drv); if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP) flags = NLM_F_DUMP; msg = nl80211_cmd_msg(drv->first_bss, flags, NL80211_CMD_GET_WIPHY); if (!msg || nla_put_flag(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP)) { nlmsg_free(msg); return -1; } if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info)) return -1; if (info->auth_supported) drv->capa.flags |= WPA_DRIVER_FLAGS_SME; else if (!info->connect_supported) { wpa_printf(MSG_INFO, "nl80211: Driver does not support " "authentication/association or connect commands"); info->error = 1; } if (info->p2p_go_supported && info->p2p_client_supported) drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE; if (info->p2p_concurrent) { wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group " "interface (driver advertised support)"); drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT; drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P; } if (info->num_multichan_concurrent > 1) { wpa_printf(MSG_DEBUG, "nl80211: Enable multi-channel " "concurrent (driver advertised support)"); drv->capa.num_multichan_concurrent = info->num_multichan_concurrent; } if (drv->capa.flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) wpa_printf(MSG_DEBUG, "nl80211: use P2P_DEVICE support"); /* default to 5000 since early versions of mac80211 don't set it */ if (!drv->capa.max_remain_on_chan) drv->capa.max_remain_on_chan = 5000; drv->capa.wmm_ac_supported = info->wmm_ac_supported; drv->capa.mac_addr_rand_sched_scan_supported = info->mac_addr_rand_sched_scan_supported; drv->capa.mac_addr_rand_scan_supported = info->mac_addr_rand_scan_supported; if (info->channel_switch_supported) { drv->capa.flags |= WPA_DRIVER_FLAGS_AP_CSA; if (!drv->capa.max_csa_counters) drv->capa.max_csa_counters = 1; } if (!drv->capa.max_sched_scan_plans) { drv->capa.max_sched_scan_plans = 1; drv->capa.max_sched_scan_plan_interval = UINT32_MAX; drv->capa.max_sched_scan_plan_iterations = 0; } return 0; } #ifdef CONFIG_DRIVER_NL80211_QCA static int dfs_info_handler(struct nl_msg *msg, void *arg) { struct nlattr *tb[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); int *dfs_capability_ptr = arg; nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (tb[NL80211_ATTR_VENDOR_DATA]) { struct nlattr *nl_vend = tb[NL80211_ATTR_VENDOR_DATA]; struct nlattr *tb_vendor[QCA_WLAN_VENDOR_ATTR_MAX + 1]; nla_parse(tb_vendor, QCA_WLAN_VENDOR_ATTR_MAX, nla_data(nl_vend), nla_len(nl_vend), NULL); if (tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]) { u32 val; val = nla_get_u32(tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]); wpa_printf(MSG_DEBUG, "nl80211: DFS offload capability: %u", val); *dfs_capability_ptr = val; } } return NL_SKIP; } static void qca_nl80211_check_dfs_capa(struct wpa_driver_nl80211_data *drv) { struct nl_msg *msg; int dfs_capability = 0; int ret; if (!drv->dfs_vendor_cmd_avail) return; if (!(msg = nl80211_drv_msg(drv, 0, NL80211_CMD_VENDOR)) || nla_put_u32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA) || nla_put_u32(msg, NL80211_ATTR_VENDOR_SUBCMD, QCA_NL80211_VENDOR_SUBCMD_DFS_CAPABILITY)) { nlmsg_free(msg); return; } ret = send_and_recv_msgs(drv, msg, dfs_info_handler, &dfs_capability); if (!ret && dfs_capability) drv->capa.flags |= WPA_DRIVER_FLAGS_DFS_OFFLOAD; } struct features_info { u8 *flags; size_t flags_len; struct wpa_driver_capa *capa; }; static int features_info_handler(struct nl_msg *msg, void *arg) { struct nlattr *tb[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); struct features_info *info = arg; struct nlattr *nl_vend, *attr; nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); nl_vend = tb[NL80211_ATTR_VENDOR_DATA]; if (nl_vend) { struct nlattr *tb_vendor[QCA_WLAN_VENDOR_ATTR_MAX + 1]; nla_parse(tb_vendor, QCA_WLAN_VENDOR_ATTR_MAX, nla_data(nl_vend), nla_len(nl_vend), NULL); attr = tb_vendor[QCA_WLAN_VENDOR_ATTR_FEATURE_FLAGS]; if (attr) { int len = nla_len(attr); info->flags = os_malloc(len); if (info->flags != NULL) { os_memcpy(info->flags, nla_data(attr), len); info->flags_len = len; } } attr = tb_vendor[QCA_WLAN_VENDOR_ATTR_CONCURRENCY_CAPA]; if (attr) info->capa->conc_capab = nla_get_u32(attr); attr = tb_vendor[ QCA_WLAN_VENDOR_ATTR_MAX_CONCURRENT_CHANNELS_2_4_BAND]; if (attr) info->capa->max_conc_chan_2_4 = nla_get_u32(attr); attr = tb_vendor[ QCA_WLAN_VENDOR_ATTR_MAX_CONCURRENT_CHANNELS_5_0_BAND]; if (attr) info->capa->max_conc_chan_5_0 = nla_get_u32(attr); } return NL_SKIP; } static int check_feature(enum qca_wlan_vendor_features feature, struct features_info *info) { size_t idx = feature / 8; return (idx < info->flags_len) && (info->flags[idx] & BIT(feature % 8)); } static void qca_nl80211_get_features(struct wpa_driver_nl80211_data *drv) { struct nl_msg *msg; struct features_info info; int ret; if (!drv->get_features_vendor_cmd_avail) return; if (!(msg = nl80211_drv_msg(drv, 0, NL80211_CMD_VENDOR)) || nla_put_u32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA) || nla_put_u32(msg, NL80211_ATTR_VENDOR_SUBCMD, QCA_NL80211_VENDOR_SUBCMD_GET_FEATURES)) { nlmsg_free(msg); return; } os_memset(&info, 0, sizeof(info)); info.capa = &drv->capa; ret = send_and_recv_msgs(drv, msg, features_info_handler, &info); if (ret || !info.flags) return; if (check_feature(QCA_WLAN_VENDOR_FEATURE_KEY_MGMT_OFFLOAD, &info)) drv->capa.flags |= WPA_DRIVER_FLAGS_KEY_MGMT_OFFLOAD; if (check_feature(QCA_WLAN_VENDOR_FEATURE_SUPPORT_HW_MODE_ANY, &info)) drv->capa.flags |= WPA_DRIVER_FLAGS_SUPPORT_HW_MODE_ANY; if (check_feature(QCA_WLAN_VENDOR_FEATURE_OFFCHANNEL_SIMULTANEOUS, &info)) drv->capa.flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_SIMULTANEOUS; if (check_feature(QCA_WLAN_VENDOR_FEATURE_P2P_LISTEN_OFFLOAD, &info)) drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_LISTEN_OFFLOAD; os_free(info.flags); } #endif /* CONFIG_DRIVER_NL80211_QCA */ int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv) { struct wiphy_info_data info; if (wpa_driver_nl80211_get_info(drv, &info)) return -1; if (info.error) return -1; drv->has_capability = 1; drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA | WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK | WPA_DRIVER_CAPA_KEY_MGMT_WPA2 | WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK | WPA_DRIVER_CAPA_KEY_MGMT_SUITE_B | WPA_DRIVER_CAPA_KEY_MGMT_SUITE_B_192; drv->capa.auth = WPA_DRIVER_AUTH_OPEN | WPA_DRIVER_AUTH_SHARED | WPA_DRIVER_AUTH_LEAP; drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES; drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE; drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS; /* * As all cfg80211 drivers must support cases where the AP interface is * removed without the knowledge of wpa_supplicant/hostapd, e.g., in * case that the user space daemon has crashed, they must be able to * cleanup all stations and key entries in the AP tear down flow. Thus, * this flag can/should always be set for cfg80211 drivers. */ drv->capa.flags |= WPA_DRIVER_FLAGS_AP_TEARDOWN_SUPPORT; if (!info.device_ap_sme) { drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS; /* * No AP SME is currently assumed to also indicate no AP MLME * in the driver/firmware. */ drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME; } drv->device_ap_sme = info.device_ap_sme; drv->poll_command_supported = info.poll_command_supported; drv->data_tx_status = info.data_tx_status; drv->p2p_go_ctwindow_supported = info.p2p_go_ctwindow_supported; if (info.set_qos_map_supported) drv->capa.flags |= WPA_DRIVER_FLAGS_QOS_MAPPING; drv->have_low_prio_scan = info.have_low_prio_scan; /* * If poll command and tx status are supported, mac80211 is new enough * to have everything we need to not need monitor interfaces. */ drv->use_monitor = !info.device_ap_sme && (!info.poll_command_supported || !info.data_tx_status); /* * If we aren't going to use monitor interfaces, but the * driver doesn't support data TX status, we won't get TX * status for EAPOL frames. */ if (!drv->use_monitor && !info.data_tx_status) drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS; #ifdef CONFIG_DRIVER_NL80211_QCA qca_nl80211_check_dfs_capa(drv); qca_nl80211_get_features(drv); /* * To enable offchannel simultaneous support in wpa_supplicant, the * underlying driver needs to support the same along with offchannel TX. * Offchannel TX support is needed since remain_on_channel and * action_tx use some common data structures and hence cannot be * scheduled simultaneously. */ if (!(drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX)) drv->capa.flags &= ~WPA_DRIVER_FLAGS_OFFCHANNEL_SIMULTANEOUS; #endif /* CONFIG_DRIVER_NL80211_QCA */ return 0; } struct phy_info_arg { u16 *num_modes; struct hostapd_hw_modes *modes; int last_mode, last_chan_idx; int failed; u32 conf_tx_ant, conf_rx_ant; }; static void phy_info_ht_capa(struct hostapd_hw_modes *mode, struct nlattr *capa, struct nlattr *ampdu_factor, struct nlattr *ampdu_density, struct nlattr *mcs_set) { if (capa) mode->ht_capab = nla_get_u16(capa); if (ampdu_factor) mode->a_mpdu_params |= nla_get_u8(ampdu_factor) & 0x03; if (ampdu_density) mode->a_mpdu_params |= nla_get_u8(ampdu_density) << 2; if (mcs_set && nla_len(mcs_set) >= 16) { u8 *mcs; mcs = nla_data(mcs_set); os_memcpy(mode->mcs_set, mcs, 16); } } static void phy_info_vht_capa(struct hostapd_hw_modes *mode, struct nlattr *capa, struct nlattr *mcs_set) { if (capa) mode->vht_capab = nla_get_u32(capa); if (mcs_set && nla_len(mcs_set) >= 8) { u8 *mcs; mcs = nla_data(mcs_set); os_memcpy(mode->vht_mcs_set, mcs, 8); } } static void phy_info_freq(struct hostapd_hw_modes *mode, struct hostapd_channel_data *chan, struct nlattr *tb_freq[]) { u8 channel; chan->freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]); chan->flag = 0; chan->dfs_cac_ms = 0; if (ieee80211_freq_to_chan(chan->freq, &channel) != NUM_HOSTAPD_MODES) chan->chan = channel; if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED]) chan->flag |= HOSTAPD_CHAN_DISABLED; if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IR]) chan->flag |= HOSTAPD_CHAN_NO_IR; if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR]) chan->flag |= HOSTAPD_CHAN_RADAR; if (tb_freq[NL80211_FREQUENCY_ATTR_INDOOR_ONLY]) chan->flag |= HOSTAPD_CHAN_INDOOR_ONLY; if (tb_freq[NL80211_FREQUENCY_ATTR_GO_CONCURRENT]) chan->flag |= HOSTAPD_CHAN_GO_CONCURRENT; if (tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]) { enum nl80211_dfs_state state = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]); switch (state) { case NL80211_DFS_USABLE: chan->flag |= HOSTAPD_CHAN_DFS_USABLE; break; case NL80211_DFS_AVAILABLE: chan->flag |= HOSTAPD_CHAN_DFS_AVAILABLE; break; case NL80211_DFS_UNAVAILABLE: chan->flag |= HOSTAPD_CHAN_DFS_UNAVAILABLE; break; } } if (tb_freq[NL80211_FREQUENCY_ATTR_DFS_CAC_TIME]) { chan->dfs_cac_ms = nla_get_u32( tb_freq[NL80211_FREQUENCY_ATTR_DFS_CAC_TIME]); } } static int phy_info_freqs(struct phy_info_arg *phy_info, struct hostapd_hw_modes *mode, struct nlattr *tb) { static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = { [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 }, [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG }, [NL80211_FREQUENCY_ATTR_NO_IR] = { .type = NLA_FLAG }, [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG }, [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 }, [NL80211_FREQUENCY_ATTR_DFS_STATE] = { .type = NLA_U32 }, }; int new_channels = 0; struct hostapd_channel_data *channel; struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1]; struct nlattr *nl_freq; int rem_freq, idx; if (tb == NULL) return NL_OK; nla_for_each_nested(nl_freq, tb, rem_freq) { nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq), nla_len(nl_freq), freq_policy); if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ]) continue; new_channels++; } channel = os_realloc_array(mode->channels, mode->num_channels + new_channels, sizeof(struct hostapd_channel_data)); if (!channel) return NL_STOP; mode->channels = channel; mode->num_channels += new_channels; idx = phy_info->last_chan_idx; nla_for_each_nested(nl_freq, tb, rem_freq) { nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq), nla_len(nl_freq), freq_policy); if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ]) continue; phy_info_freq(mode, &mode->channels[idx], tb_freq); idx++; } phy_info->last_chan_idx = idx; return NL_OK; } static int phy_info_rates(struct hostapd_hw_modes *mode, struct nlattr *tb) { static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = { [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 }, [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG }, }; struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1]; struct nlattr *nl_rate; int rem_rate, idx; if (tb == NULL) return NL_OK; nla_for_each_nested(nl_rate, tb, rem_rate) { nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate), nla_len(nl_rate), rate_policy); if (!tb_rate[NL80211_BITRATE_ATTR_RATE]) continue; mode->num_rates++; } mode->rates = os_calloc(mode->num_rates, sizeof(int)); if (!mode->rates) return NL_STOP; idx = 0; nla_for_each_nested(nl_rate, tb, rem_rate) { nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate), nla_len(nl_rate), rate_policy); if (!tb_rate[NL80211_BITRATE_ATTR_RATE]) continue; mode->rates[idx] = nla_get_u32( tb_rate[NL80211_BITRATE_ATTR_RATE]); idx++; } return NL_OK; } static int phy_info_band(struct phy_info_arg *phy_info, struct nlattr *nl_band, struct hostapd_hw_modes **mode_used) { struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1]; struct hostapd_hw_modes *mode; int ret; if (phy_info->last_mode != nl_band->nla_type) { mode = os_realloc_array(phy_info->modes, *phy_info->num_modes + 1, sizeof(*mode)); if (!mode) { phy_info->failed = 1; return NL_STOP; } phy_info->modes = mode; mode = &phy_info->modes[*(phy_info->num_modes)]; os_memset(mode, 0, sizeof(*mode)); mode->mode = NUM_HOSTAPD_MODES; mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN | HOSTAPD_MODE_FLAG_VHT_INFO_KNOWN; /* * Unsupported VHT MCS stream is defined as value 3, so the VHT * MCS RX/TX map must be initialized with 0xffff to mark all 8 * possible streams as unsupported. This will be overridden if * driver advertises VHT support. */ mode->vht_mcs_set[0] = 0xff; mode->vht_mcs_set[1] = 0xff; mode->vht_mcs_set[4] = 0xff; mode->vht_mcs_set[5] = 0xff; *(phy_info->num_modes) += 1; phy_info->last_mode = nl_band->nla_type; phy_info->last_chan_idx = 0; } else mode = &phy_info->modes[*(phy_info->num_modes) - 1]; *mode_used = mode; nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band), nla_len(nl_band), NULL); phy_info_ht_capa(mode, tb_band[NL80211_BAND_ATTR_HT_CAPA], tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR], tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY], tb_band[NL80211_BAND_ATTR_HT_MCS_SET]); phy_info_vht_capa(mode, tb_band[NL80211_BAND_ATTR_VHT_CAPA], tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]); ret = phy_info_freqs(phy_info, mode, tb_band[NL80211_BAND_ATTR_FREQS]); if (ret == NL_OK) ret = phy_info_rates(mode, tb_band[NL80211_BAND_ATTR_RATES]); if (ret != NL_OK) { phy_info->failed = 1; return ret; } return NL_OK; } static int phy_info_handler(struct nl_msg *msg, void *arg) { struct nlattr *tb_msg[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); struct phy_info_arg *phy_info = arg; struct nlattr *nl_band; int rem_band; u32 tx, rx; nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (tb_msg[NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX] && tb_msg[NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX]) { tx = nla_get_u32(tb_msg[NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX]); rx = nla_get_u32(tb_msg[NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX]); wpa_printf(MSG_DEBUG, "Available Antennas: TX %#x RX %#x", tx, rx); } if (tb_msg[NL80211_ATTR_WIPHY_ANTENNA_TX] && tb_msg[NL80211_ATTR_WIPHY_ANTENNA_RX]) { tx = nla_get_u32(tb_msg[NL80211_ATTR_WIPHY_ANTENNA_TX]); rx = nla_get_u32(tb_msg[NL80211_ATTR_WIPHY_ANTENNA_RX]); wpa_printf(MSG_DEBUG, "Configured Antennas: TX %#x RX %#x", tx, rx); phy_info->conf_tx_ant = tx; phy_info->conf_rx_ant = rx; } if (!tb_msg[NL80211_ATTR_WIPHY_BANDS]) return NL_SKIP; nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) { struct hostapd_hw_modes *mode = NULL; int res = phy_info_band(phy_info, nl_band, &mode); if (res != NL_OK) return res; if (mode) { mode->conf_tx_ant = phy_info->conf_tx_ant; mode->conf_rx_ant = phy_info->conf_rx_ant; } } return NL_SKIP; } static struct hostapd_hw_modes * wpa_driver_nl80211_postprocess_modes(struct hostapd_hw_modes *modes, u16 *num_modes) { u16 m; struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode; int i, mode11g_idx = -1; /* heuristic to set up modes */ for (m = 0; m < *num_modes; m++) { if (!modes[m].num_channels) continue; if (modes[m].channels[0].freq < 4000) { modes[m].mode = HOSTAPD_MODE_IEEE80211B; for (i = 0; i < modes[m].num_rates; i++) { if (modes[m].rates[i] > 200) { modes[m].mode = HOSTAPD_MODE_IEEE80211G; break; } } } else if (modes[m].channels[0].freq > 50000) modes[m].mode = HOSTAPD_MODE_IEEE80211AD; else modes[m].mode = HOSTAPD_MODE_IEEE80211A; } /* If only 802.11g mode is included, use it to construct matching * 802.11b mode data. */ for (m = 0; m < *num_modes; m++) { if (modes[m].mode == HOSTAPD_MODE_IEEE80211B) return modes; /* 802.11b already included */ if (modes[m].mode == HOSTAPD_MODE_IEEE80211G) mode11g_idx = m; } if (mode11g_idx < 0) return modes; /* 2.4 GHz band not supported at all */ nmodes = os_realloc_array(modes, *num_modes + 1, sizeof(*nmodes)); if (nmodes == NULL) return modes; /* Could not add 802.11b mode */ mode = &nmodes[*num_modes]; os_memset(mode, 0, sizeof(*mode)); (*num_modes)++; modes = nmodes; mode->mode = HOSTAPD_MODE_IEEE80211B; mode11g = &modes[mode11g_idx]; mode->num_channels = mode11g->num_channels; mode->channels = os_malloc(mode11g->num_channels * sizeof(struct hostapd_channel_data)); if (mode->channels == NULL) { (*num_modes)--; return modes; /* Could not add 802.11b mode */ } os_memcpy(mode->channels, mode11g->channels, mode11g->num_channels * sizeof(struct hostapd_channel_data)); mode->num_rates = 0; mode->rates = os_malloc(4 * sizeof(int)); if (mode->rates == NULL) { os_free(mode->channels); (*num_modes)--; return modes; /* Could not add 802.11b mode */ } for (i = 0; i < mode11g->num_rates; i++) { if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 && mode11g->rates[i] != 55 && mode11g->rates[i] != 110) continue; mode->rates[mode->num_rates] = mode11g->rates[i]; mode->num_rates++; if (mode->num_rates == 4) break; } if (mode->num_rates == 0) { os_free(mode->channels); os_free(mode->rates); (*num_modes)--; return modes; /* No 802.11b rates */ } wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g " "information"); return modes; } static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start, int end) { int c; for (c = 0; c < mode->num_channels; c++) { struct hostapd_channel_data *chan = &mode->channels[c]; if (chan->freq - 10 >= start && chan->freq + 10 <= end) chan->flag |= HOSTAPD_CHAN_HT40; } } static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start, int end) { int c; for (c = 0; c < mode->num_channels; c++) { struct hostapd_channel_data *chan = &mode->channels[c]; if (!(chan->flag & HOSTAPD_CHAN_HT40)) continue; if (chan->freq - 30 >= start && chan->freq - 10 <= end) chan->flag |= HOSTAPD_CHAN_HT40MINUS; if (chan->freq + 10 >= start && chan->freq + 30 <= end) chan->flag |= HOSTAPD_CHAN_HT40PLUS; } } static void nl80211_reg_rule_max_eirp(u32 start, u32 end, u32 max_eirp, struct phy_info_arg *results) { u16 m; for (m = 0; m < *results->num_modes; m++) { int c; struct hostapd_hw_modes *mode = &results->modes[m]; for (c = 0; c < mode->num_channels; c++) { struct hostapd_channel_data *chan = &mode->channels[c]; if ((u32) chan->freq - 10 >= start && (u32) chan->freq + 10 <= end) chan->max_tx_power = max_eirp; } } } static void nl80211_reg_rule_ht40(u32 start, u32 end, struct phy_info_arg *results) { u16 m; for (m = 0; m < *results->num_modes; m++) { if (!(results->modes[m].ht_capab & HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET)) continue; nl80211_set_ht40_mode(&results->modes[m], start, end); } } static void nl80211_reg_rule_sec(struct nlattr *tb[], struct phy_info_arg *results) { u32 start, end, max_bw; u16 m; if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL || tb[NL80211_ATTR_FREQ_RANGE_END] == NULL || tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL) return; start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000; end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000; max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000; if (max_bw < 20) return; for (m = 0; m < *results->num_modes; m++) { if (!(results->modes[m].ht_capab & HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET)) continue; nl80211_set_ht40_mode_sec(&results->modes[m], start, end); } } static void nl80211_set_vht_mode(struct hostapd_hw_modes *mode, int start, int end, int max_bw) { int c; for (c = 0; c < mode->num_channels; c++) { struct hostapd_channel_data *chan = &mode->channels[c]; if (chan->freq - 10 >= start && chan->freq + 70 <= end) chan->flag |= HOSTAPD_CHAN_VHT_10_70; if (chan->freq - 30 >= start && chan->freq + 50 <= end) chan->flag |= HOSTAPD_CHAN_VHT_30_50; if (chan->freq - 50 >= start && chan->freq + 30 <= end) chan->flag |= HOSTAPD_CHAN_VHT_50_30; if (chan->freq - 70 >= start && chan->freq + 10 <= end) chan->flag |= HOSTAPD_CHAN_VHT_70_10; if (max_bw >= 160) { if (chan->freq - 10 >= start && chan->freq + 150 <= end) chan->flag |= HOSTAPD_CHAN_VHT_10_150; if (chan->freq - 30 >= start && chan->freq + 130 <= end) chan->flag |= HOSTAPD_CHAN_VHT_30_130; if (chan->freq - 50 >= start && chan->freq + 110 <= end) chan->flag |= HOSTAPD_CHAN_VHT_50_110; if (chan->freq - 70 >= start && chan->freq + 90 <= end) chan->flag |= HOSTAPD_CHAN_VHT_70_90; if (chan->freq - 90 >= start && chan->freq + 70 <= end) chan->flag |= HOSTAPD_CHAN_VHT_90_70; if (chan->freq - 110 >= start && chan->freq + 50 <= end) chan->flag |= HOSTAPD_CHAN_VHT_110_50; if (chan->freq - 130 >= start && chan->freq + 30 <= end) chan->flag |= HOSTAPD_CHAN_VHT_130_30; if (chan->freq - 150 >= start && chan->freq + 10 <= end) chan->flag |= HOSTAPD_CHAN_VHT_150_10; } } } static void nl80211_reg_rule_vht(struct nlattr *tb[], struct phy_info_arg *results) { u32 start, end, max_bw; u16 m; if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL || tb[NL80211_ATTR_FREQ_RANGE_END] == NULL || tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL) return; start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000; end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000; max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000; if (max_bw < 80) return; for (m = 0; m < *results->num_modes; m++) { if (!(results->modes[m].ht_capab & HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET)) continue; /* TODO: use a real VHT support indication */ if (!results->modes[m].vht_capab) continue; nl80211_set_vht_mode(&results->modes[m], start, end, max_bw); } } static const char * dfs_domain_name(enum nl80211_dfs_regions region) { switch (region) { case NL80211_DFS_UNSET: return "DFS-UNSET"; case NL80211_DFS_FCC: return "DFS-FCC"; case NL80211_DFS_ETSI: return "DFS-ETSI"; case NL80211_DFS_JP: return "DFS-JP"; default: return "DFS-invalid"; } } static int nl80211_get_reg(struct nl_msg *msg, void *arg) { struct phy_info_arg *results = arg; struct nlattr *tb_msg[NL80211_ATTR_MAX + 1]; struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg)); struct nlattr *nl_rule; struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1]; int rem_rule; static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = { [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 }, [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 }, [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 }, [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 }, [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 }, [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 }, }; nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0), genlmsg_attrlen(gnlh, 0), NULL); if (!tb_msg[NL80211_ATTR_REG_ALPHA2] || !tb_msg[NL80211_ATTR_REG_RULES]) { wpa_printf(MSG_DEBUG, "nl80211: No regulatory information " "available"); return NL_SKIP; } if (tb_msg[NL80211_ATTR_DFS_REGION]) { enum nl80211_dfs_regions dfs_domain; dfs_domain = nla_get_u8(tb_msg[NL80211_ATTR_DFS_REGION]); wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s (%s)", (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]), dfs_domain_name(dfs_domain)); } else { wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s", (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2])); } nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule) { u32 start, end, max_eirp = 0, max_bw = 0, flags = 0; nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_rule), nla_len(nl_rule), reg_policy); if (tb_rule[NL80211_ATTR_FREQ_RANGE_START] == NULL || tb_rule[NL80211_ATTR_FREQ_RANGE_END] == NULL) continue; start = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_START]) / 1000; end = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_END]) / 1000; if (tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP]) max_eirp = nla_get_u32(tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP]) / 100; if (tb_rule[NL80211_ATTR_FREQ_RANGE_MAX_BW]) max_bw = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000; if (tb_rule[NL80211_ATTR_REG_RULE_FLAGS]) flags = nla_get_u32(tb_rule[NL80211_ATTR_REG_RULE_FLAGS]); wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz %u mBm%s%s%s%s%s%s%s%s", start, end, max_bw, max_eirp, flags & NL80211_RRF_NO_OFDM ? " (no OFDM)" : "", flags & NL80211_RRF_NO_CCK ? " (no CCK)" : "", flags & NL80211_RRF_NO_INDOOR ? " (no indoor)" : "", flags & NL80211_RRF_NO_OUTDOOR ? " (no outdoor)" : "", flags & NL80211_RRF_DFS ? " (DFS)" : "", flags & NL80211_RRF_PTP_ONLY ? " (PTP only)" : "", flags & NL80211_RRF_PTMP_ONLY ? " (PTMP only)" : "", flags & NL80211_RRF_NO_IR ? " (no IR)" : ""); if (max_bw >= 40) nl80211_reg_rule_ht40(start, end, results); if (tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP]) nl80211_reg_rule_max_eirp(start, end, max_eirp, results); } nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule) { nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_rule), nla_len(nl_rule), reg_policy); nl80211_reg_rule_sec(tb_rule, results); } nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule) { nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_rule), nla_len(nl_rule), reg_policy); nl80211_reg_rule_vht(tb_rule, results); } return NL_SKIP; } static int nl80211_set_regulatory_flags(struct wpa_driver_nl80211_data *drv, struct phy_info_arg *results) { struct nl_msg *msg; msg = nlmsg_alloc(); if (!msg) return -ENOMEM; nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG); return send_and_recv_msgs(drv, msg, nl80211_get_reg, results); } struct hostapd_hw_modes * nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags) { u32 feat; struct i802_bss *bss = priv; struct wpa_driver_nl80211_data *drv = bss->drv; int nl_flags = 0; struct nl_msg *msg; struct phy_info_arg result = { .num_modes = num_modes, .modes = NULL, .last_mode = -1, .failed = 0, .conf_tx_ant = 0, .conf_rx_ant = 0, }; *num_modes = 0; *flags = 0; feat = get_nl80211_protocol_features(drv); if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP) nl_flags = NLM_F_DUMP; if (!(msg = nl80211_cmd_msg(bss, nl_flags, NL80211_CMD_GET_WIPHY)) || nla_put_flag(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP)) { nlmsg_free(msg); return NULL; } if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) { nl80211_set_regulatory_flags(drv, &result); if (result.failed) { int i; for (i = 0; result.modes && i < *num_modes; i++) { os_free(result.modes[i].channels); os_free(result.modes[i].rates); } os_free(result.modes); *num_modes = 0; return NULL; } return wpa_driver_nl80211_postprocess_modes(result.modes, num_modes); } return NULL; }
745275.c
#include "blas.h" #include "gf.h" #include <stddef.h> void PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256v_predicated_add(uint8_t *accu_b, uint8_t predicate, const uint8_t *a, size_t _num_byte) { uint8_t pr_u8 = (uint8_t) ((uint8_t) 0 - predicate); for (size_t i = 0; i < _num_byte; i++) { accu_b[i] ^= (a[i] & pr_u8); } } void PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256v_add(uint8_t *accu_b, const uint8_t *a, size_t _num_byte) { for (size_t i = 0; i < _num_byte; i++) { accu_b[i] ^= a[i]; } } void PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256v_mul_scalar(uint8_t *a, uint8_t b, size_t _num_byte) { for (size_t i = 0; i < _num_byte; i++) { a[i] = PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256_mul(a[i], b); } } void PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256v_madd(uint8_t *accu_c, const uint8_t *a, uint8_t gf256_b, size_t _num_byte) { for (size_t i = 0; i < _num_byte; i++) { accu_c[i] ^= PQCLEAN_RAINBOWIIICCYCLIC_CLEAN_gf256_mul(a[i], gf256_b); } }
465998.c
/* * Copyright (C) 2004, 2005, 2007, 2008 Internet Systems Consortium, Inc. ("ISC") * Copyright (C) 1998-2003 Internet Software Consortium. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #if !defined(lint) && !defined(SABER) static const char rcsid[] = "$Id: ctl_clnt.c,v 1.11 2008/11/14 02:36:51 marka Exp $"; #endif /* not lint */ /* Extern. */ #include <port_before.h> #include <sys/param.h> #include <sys/file.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/nameser.h> #include <arpa/inet.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <kits/support/String.h> #include <time.h> #include <unistd.h> #ifdef HAVE_MEMORY_H #include <memory.h> #endif #include <isc/assertions.h> #include <isc/ctl.h> #include <isc/eventlib.h> #include <isc/list.h> #include <isc/memcluster.h> #include <ctl_p.h> #include <port_after.h> /* Constants. */ /* Macros. */ #define donefunc_p(ctx) ((ctx).donefunc != NULL) #define arpacode_p(line) (isdigit((unsigned char)(line[0])) && \ isdigit((unsigned char)(line[1])) && \ isdigit((unsigned char)(line[2]))) #define arpacont_p(line) (line[3] == '-') #define arpadone_p(line) (line[3] == ' ' || line[3] == '\t' || \ line[3] == '\r' || line[3] == '\0') /* Types. */ enum state { initializing = 0, connecting, connected, destroyed }; struct ctl_tran { LINK(struct ctl_tran) link; LINK(struct ctl_tran) wlink; struct ctl_cctx * ctx; struct ctl_buf outbuf; ctl_clntdone donefunc; void * uap; }; struct ctl_cctx { enum state state; evContext ev; int sock; ctl_logfunc logger; ctl_clntdone donefunc; void * uap; evConnID coID; evTimerID tiID; evFileID rdID; evStreamID wrID; struct ctl_buf inbuf; struct timespec timeout; LIST(struct ctl_tran) tran; LIST(struct ctl_tran) wtran; }; /* Forward. */ static struct ctl_tran *new_tran(struct ctl_cctx *, ctl_clntdone, void *, int); static void start_write(struct ctl_cctx *); static void destroy(struct ctl_cctx *, int); static void error(struct ctl_cctx *); static void new_state(struct ctl_cctx *, enum state); static void conn_done(evContext, void *, int, const void *, int, const void *, int); static void write_done(evContext, void *, int, int); static void start_read(struct ctl_cctx *); static void stop_read(struct ctl_cctx *); static void readable(evContext, void *, int, int); static void start_timer(struct ctl_cctx *); static void stop_timer(struct ctl_cctx *); static void touch_timer(struct ctl_cctx *); static void timer(evContext, void *, struct timespec, struct timespec); #ifndef HAVE_MEMCHR static void * memchr(const void *b, int c, size_t len) { const unsigned char *p = b; size_t i; for (i = 0; i < len; i++, p++) if (*p == (unsigned char)c) return ((void *)p); return (NULL); } #endif /* Private data. */ static const char * const state_names[] = { "initializing", "connecting", "connected", "destroyed" }; /* Public. */ /*% * void * ctl_client() * create, condition, and connect to a listener on the control port. */ struct ctl_cctx * ctl_client(evContext lev, const struct sockaddr *cap, size_t cap_len, const struct sockaddr *sap, size_t sap_len, ctl_clntdone donefunc, void *uap, u_int timeout, ctl_logfunc logger) { static const char me[] = "ctl_client"; static const int on = 1; struct ctl_cctx *ctx; struct sockaddr *captmp; if (logger == NULL) logger = ctl_logger; ctx = memget(sizeof *ctx); if (ctx == NULL) { (*logger)(ctl_error, "%s: getmem: %s", me, strerror(errno)); goto fatal; } ctx->state = initializing; ctx->ev = lev; ctx->logger = logger; ctx->timeout = evConsTime(timeout, 0); ctx->donefunc = donefunc; ctx->uap = uap; ctx->coID.opaque = NULL; ctx->tiID.opaque = NULL; ctx->rdID.opaque = NULL; ctx->wrID.opaque = NULL; buffer_init(ctx->inbuf); INIT_LIST(ctx->tran); INIT_LIST(ctx->wtran); ctx->sock = socket(sap->sa_family, SOCK_STREAM, PF_UNSPEC); if (ctx->sock > evHighestFD(ctx->ev)) { ctx->sock = -1; errno = ENOTSOCK; } if (ctx->sock < 0) { (*ctx->logger)(ctl_error, "%s: socket: %s", me, strerror(errno)); goto fatal; } if (cap != NULL) { if (setsockopt(ctx->sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof on) != 0) { (*ctx->logger)(ctl_warning, "%s: setsockopt(REUSEADDR): %s", me, strerror(errno)); } DE_CONST(cap, captmp); if (bind(ctx->sock, captmp, cap_len) < 0) { (*ctx->logger)(ctl_error, "%s: bind: %s", me, strerror(errno)); goto fatal; } } if (evConnect(lev, ctx->sock, (const struct sockaddr *)sap, sap_len, conn_done, ctx, &ctx->coID) < 0) { (*ctx->logger)(ctl_error, "%s: evConnect(fd %d): %s", me, ctx->sock, strerror(errno)); fatal: if (ctx != NULL) { if (ctx->sock >= 0) close(ctx->sock); memput(ctx, sizeof *ctx); } return (NULL); } new_state(ctx, connecting); return (ctx); } /*% * void * ctl_endclient(ctx) * close a client and release all of its resources. */ void ctl_endclient(struct ctl_cctx *ctx) { if (ctx->state != destroyed) destroy(ctx, 0); memput(ctx, sizeof *ctx); } /*% * int * ctl_command(ctx, cmd, len, donefunc, uap) * Queue a transaction, which will begin with sending cmd * and complete by calling donefunc with the answer. */ int ctl_command(struct ctl_cctx *ctx, const char *cmd, size_t len, ctl_clntdone donefunc, void *uap) { struct ctl_tran *tran; char *pc; unsigned int n; switch (ctx->state) { case destroyed: errno = ENOTCONN; return (-1); case connecting: case connected: break; default: abort(); } if (len >= (size_t)MAX_LINELEN) { errno = EMSGSIZE; return (-1); } tran = new_tran(ctx, donefunc, uap, 1); if (tran == NULL) return (-1); if (ctl_bufget(&tran->outbuf, ctx->logger) < 0) return (-1); memcpy(tran->outbuf.text, cmd, len); tran->outbuf.used = len; for (pc = tran->outbuf.text, n = 0; n < tran->outbuf.used; pc++, n++) if (!isascii((unsigned char)*pc) || !isprint((unsigned char)*pc)) *pc = '\040'; start_write(ctx); return (0); } /* Private. */ static struct ctl_tran * new_tran(struct ctl_cctx *ctx, ctl_clntdone donefunc, void *uap, int w) { struct ctl_tran *new = memget(sizeof *new); if (new == NULL) return (NULL); new->ctx = ctx; buffer_init(new->outbuf); new->donefunc = donefunc; new->uap = uap; INIT_LINK(new, link); INIT_LINK(new, wlink); APPEND(ctx->tran, new, link); if (w) APPEND(ctx->wtran, new, wlink); return (new); } static void start_write(struct ctl_cctx *ctx) { static const char me[] = "isc/ctl_clnt::start_write"; struct ctl_tran *tran; struct iovec iov[2], *iovp = iov; char * tmp; REQUIRE(ctx->state == connecting || ctx->state == connected); /* If there is a write in progress, don't try to write more yet. */ if (ctx->wrID.opaque != NULL) return; /* If there are no trans, make sure timer is off, and we're done. */ if (EMPTY(ctx->wtran)) { if (ctx->tiID.opaque != NULL) stop_timer(ctx); return; } /* Pull it off the head of the write queue. */ tran = HEAD(ctx->wtran); UNLINK(ctx->wtran, tran, wlink); /* Since there are some trans, make sure timer is successfully "on". */ if (ctx->tiID.opaque != NULL) touch_timer(ctx); else start_timer(ctx); if (ctx->state == destroyed) return; /* Marshall a newline-terminated message and clock it out. */ *iovp++ = evConsIovec(tran->outbuf.text, tran->outbuf.used); DE_CONST("\r\n", tmp); *iovp++ = evConsIovec(tmp, 2); if (evWrite(ctx->ev, ctx->sock, iov, iovp - iov, write_done, tran, &ctx->wrID) < 0) { (*ctx->logger)(ctl_error, "%s: evWrite: %s", me, strerror(errno)); error(ctx); return; } if (evTimeRW(ctx->ev, ctx->wrID, ctx->tiID) < 0) { (*ctx->logger)(ctl_error, "%s: evTimeRW: %s", me, strerror(errno)); error(ctx); return; } } static void destroy(struct ctl_cctx *ctx, int notify) { struct ctl_tran *this, *next; if (ctx->sock != -1) { (void) close(ctx->sock); ctx->sock = -1; } switch (ctx->state) { case connecting: REQUIRE(ctx->wrID.opaque == NULL); REQUIRE(EMPTY(ctx->tran)); /* * This test is nec'y since destroy() can be called from * start_read() while the state is still "connecting". */ if (ctx->coID.opaque != NULL) { (void)evCancelConn(ctx->ev, ctx->coID); ctx->coID.opaque = NULL; } break; case connected: REQUIRE(ctx->coID.opaque == NULL); if (ctx->wrID.opaque != NULL) { (void)evCancelRW(ctx->ev, ctx->wrID); ctx->wrID.opaque = NULL; } if (ctx->rdID.opaque != NULL) stop_read(ctx); break; case destroyed: break; default: abort(); } if (allocated_p(ctx->inbuf)) ctl_bufput(&ctx->inbuf); for (this = HEAD(ctx->tran); this != NULL; this = next) { next = NEXT(this, link); if (allocated_p(this->outbuf)) ctl_bufput(&this->outbuf); if (notify && this->donefunc != NULL) (*this->donefunc)(ctx, this->uap, NULL, 0); memput(this, sizeof *this); } if (ctx->tiID.opaque != NULL) stop_timer(ctx); new_state(ctx, destroyed); } static void error(struct ctl_cctx *ctx) { REQUIRE(ctx->state != destroyed); destroy(ctx, 1); } static void new_state(struct ctl_cctx *ctx, enum state new_state) { static const char me[] = "isc/ctl_clnt::new_state"; (*ctx->logger)(ctl_debug, "%s: %s -> %s", me, state_names[ctx->state], state_names[new_state]); ctx->state = new_state; } static void conn_done(evContext ev, void *uap, int fd, const void *la, int lalen, const void *ra, int ralen) { static const char me[] = "isc/ctl_clnt::conn_done"; struct ctl_cctx *ctx = uap; struct ctl_tran *tran; UNUSED(ev); UNUSED(la); UNUSED(lalen); UNUSED(ra); UNUSED(ralen); ctx->coID.opaque = NULL; if (fd < 0) { (*ctx->logger)(ctl_error, "%s: evConnect: %s", me, strerror(errno)); error(ctx); return; } new_state(ctx, connected); tran = new_tran(ctx, ctx->donefunc, ctx->uap, 0); if (tran == NULL) { (*ctx->logger)(ctl_error, "%s: new_tran failed: %s", me, strerror(errno)); error(ctx); return; } start_read(ctx); if (ctx->state == destroyed) { (*ctx->logger)(ctl_error, "%s: start_read failed: %s", me, strerror(errno)); error(ctx); return; } } static void write_done(evContext lev, void *uap, int fd, int bytes) { struct ctl_tran *tran = (struct ctl_tran *)uap; struct ctl_cctx *ctx = tran->ctx; UNUSED(lev); UNUSED(fd); ctx->wrID.opaque = NULL; if (ctx->tiID.opaque != NULL) touch_timer(ctx); ctl_bufput(&tran->outbuf); start_write(ctx); if (bytes < 0) destroy(ctx, 1); else start_read(ctx); } static void start_read(struct ctl_cctx *ctx) { static const char me[] = "isc/ctl_clnt::start_read"; REQUIRE(ctx->state == connecting || ctx->state == connected); REQUIRE(ctx->rdID.opaque == NULL); if (evSelectFD(ctx->ev, ctx->sock, EV_READ, readable, ctx, &ctx->rdID) < 0) { (*ctx->logger)(ctl_error, "%s: evSelect(fd %d): %s", me, ctx->sock, strerror(errno)); error(ctx); return; } } static void stop_read(struct ctl_cctx *ctx) { REQUIRE(ctx->coID.opaque == NULL); REQUIRE(ctx->rdID.opaque != NULL); (void)evDeselectFD(ctx->ev, ctx->rdID); ctx->rdID.opaque = NULL; } static void readable(evContext ev, void *uap, int fd, int evmask) { static const char me[] = "isc/ctl_clnt::readable"; struct ctl_cctx *ctx = uap; struct ctl_tran *tran; ssize_t n; char *eos; UNUSED(ev); REQUIRE(ctx != NULL); REQUIRE(fd >= 0); REQUIRE(evmask == EV_READ); REQUIRE(ctx->state == connected); REQUIRE(!EMPTY(ctx->tran)); tran = HEAD(ctx->tran); if (!allocated_p(ctx->inbuf) && ctl_bufget(&ctx->inbuf, ctx->logger) < 0) { (*ctx->logger)(ctl_error, "%s: can't get an input buffer", me); error(ctx); return; } n = read(ctx->sock, ctx->inbuf.text + ctx->inbuf.used, MAX_LINELEN - ctx->inbuf.used); if (n <= 0) { (*ctx->logger)(ctl_warning, "%s: read: %s", me, (n == 0) ? "Unexpected EOF" : strerror(errno)); error(ctx); return; } if (ctx->tiID.opaque != NULL) touch_timer(ctx); ctx->inbuf.used += n; (*ctx->logger)(ctl_debug, "%s: read %d, used %d", me, n, ctx->inbuf.used); again: eos = memchr(ctx->inbuf.text, '\n', ctx->inbuf.used); if (eos != NULL && eos != ctx->inbuf.text && eos[-1] == '\r') { int done = 0; eos[-1] = '\0'; if (!arpacode_p(ctx->inbuf.text)) { /* XXX Doesn't FTP do this sometimes? Is it legal? */ (*ctx->logger)(ctl_error, "%s: no arpa code (%s)", me, ctx->inbuf.text); error(ctx); return; } if (arpadone_p(ctx->inbuf.text)) done = 1; else if (arpacont_p(ctx->inbuf.text)) done = 0; else { /* XXX Doesn't FTP do this sometimes? Is it legal? */ (*ctx->logger)(ctl_error, "%s: no arpa flag (%s)", me, ctx->inbuf.text); error(ctx); return; } (*tran->donefunc)(ctx, tran->uap, ctx->inbuf.text, (done ? 0 : CTL_MORE)); ctx->inbuf.used -= ((eos - ctx->inbuf.text) + 1); if (ctx->inbuf.used == 0U) ctl_bufput(&ctx->inbuf); else memmove(ctx->inbuf.text, eos + 1, ctx->inbuf.used); if (done) { UNLINK(ctx->tran, tran, link); memput(tran, sizeof *tran); stop_read(ctx); start_write(ctx); return; } if (allocated_p(ctx->inbuf)) goto again; return; } if (ctx->inbuf.used == (size_t)MAX_LINELEN) { (*ctx->logger)(ctl_error, "%s: line too long (%-10s...)", me, ctx->inbuf.text); error(ctx); } } /* Timer related stuff. */ static void start_timer(struct ctl_cctx *ctx) { static const char me[] = "isc/ctl_clnt::start_timer"; REQUIRE(ctx->tiID.opaque == NULL); if (evSetIdleTimer(ctx->ev, timer, ctx, ctx->timeout, &ctx->tiID) < 0){ (*ctx->logger)(ctl_error, "%s: evSetIdleTimer: %s", me, strerror(errno)); error(ctx); return; } } static void stop_timer(struct ctl_cctx *ctx) { static const char me[] = "isc/ctl_clnt::stop_timer"; REQUIRE(ctx->tiID.opaque != NULL); if (evClearIdleTimer(ctx->ev, ctx->tiID) < 0) { (*ctx->logger)(ctl_error, "%s: evClearIdleTimer: %s", me, strerror(errno)); error(ctx); return; } ctx->tiID.opaque = NULL; } static void touch_timer(struct ctl_cctx *ctx) { REQUIRE(ctx->tiID.opaque != NULL); evTouchIdleTimer(ctx->ev, ctx->tiID); } static void timer(evContext ev, void *uap, struct timespec due, struct timespec itv) { static const char me[] = "isc/ctl_clnt::timer"; struct ctl_cctx *ctx = uap; UNUSED(ev); UNUSED(due); UNUSED(itv); ctx->tiID.opaque = NULL; (*ctx->logger)(ctl_error, "%s: timeout after %u seconds while %s", me, ctx->timeout.tv_sec, state_names[ctx->state]); error(ctx); } /*! \file */
303759.c
/* * Copyright (C) 2006 Michael Brown <[email protected]>. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ FILE_LICENCE ( GPL2_OR_LATER ); #include <string.h> #include <stdio.h> #include <errno.h> #include <ipxe/netdevice.h> #include <ipxe/dhcp.h> #include <ipxe/settings.h> #include <ipxe/image.h> #include <ipxe/sanboot.h> #include <ipxe/uri.h> #include <ipxe/open.h> #include <ipxe/init.h> #include <usr/ifmgmt.h> #include <usr/route.h> #include <usr/dhcpmgmt.h> #include <usr/imgmgmt.h> #include <usr/autoboot.h> /** @file * * Automatic booting * */ /* Disambiguate the various error causes */ #define ENOENT_BOOT __einfo_error ( EINFO_ENOENT_BOOT ) #define EINFO_ENOENT_BOOT \ __einfo_uniqify ( EINFO_ENOENT, 0x01, "Nothing to boot" ) /** * Perform PXE menu boot when PXE stack is not available */ __weak int pxe_menu_boot ( struct net_device *netdev __unused ) { return -ENOTSUP; } /** * Identify the boot network device * * @ret netdev Boot network device */ static struct net_device * find_boot_netdev ( void ) { return NULL; } /** * Parse next-server and filename into a URI * * @v next_server Next-server address * @v filename Filename * @ret uri URI, or NULL on failure */ static struct uri * parse_next_server_and_filename ( struct in_addr next_server, const char *filename ) { char buf[ 23 /* "tftp://xxx.xxx.xxx.xxx/" */ + strlen ( filename ) + 1 /* NUL */ ]; struct uri *uri; /* Parse filename */ uri = parse_uri ( filename ); if ( ! uri ) return NULL; /* Construct a tftp:// URI for the filename, if applicable. * We can't just rely on the current working URI, because the * relative URI resolution will remove the distinction between * filenames with and without initial slashes, which is * significant for TFTP. */ if ( next_server.s_addr && filename[0] && ! uri_is_absolute ( uri ) ) { uri_put ( uri ); snprintf ( buf, sizeof ( buf ), "tftp://%s/%s", inet_ntoa ( next_server ), filename ); uri = parse_uri ( buf ); if ( ! uri ) return NULL; } return uri; } /** The "keep-san" setting */ struct setting keep_san_setting __setting ( SETTING_SANBOOT_EXTRA ) = { .name = "keep-san", .description = "Preserve SAN connection", .tag = DHCP_EB_KEEP_SAN, .type = &setting_type_int8, }; /** The "skip-san-boot" setting */ struct setting skip_san_boot_setting __setting ( SETTING_SANBOOT_EXTRA ) = { .name = "skip-san-boot", .description = "Do not boot from SAN device", .tag = DHCP_EB_SKIP_SAN_BOOT, .type = &setting_type_int8, }; /** * Boot from filename and root-path URIs * * @v filename Filename * @v root_path Root path * @ret rc Return status code */ int uriboot ( struct uri *filename, struct uri *root_path ) { int drive; int rc; /* Treat empty URIs as absent */ if ( filename && ( ! uri_has_path ( filename ) ) ) filename = NULL; if ( root_path && ( ! uri_is_absolute ( root_path ) ) ) root_path = NULL; /* If we have both a filename and a root path, ignore an * unsupported URI scheme in the root path, since it may * represent an NFS root. */ if ( filename && root_path && ( xfer_uri_opener ( root_path->scheme ) == NULL ) ) { printf ( "Ignoring unsupported root path\n" ); root_path = NULL; } /* Check that we have something to boot */ if ( ! ( filename || root_path ) ) { rc = -ENOENT_BOOT; printf ( "Nothing to boot: %s\n", strerror ( rc ) ); goto err_no_boot; } /* Hook SAN device, if applicable */ if ( root_path ) { drive = san_hook ( root_path, 0 ); if ( drive < 0 ) { rc = drive; printf ( "Could not open SAN device: %s\n", strerror ( rc ) ); goto err_san_hook; } printf ( "Registered as SAN device %#02x\n", drive ); } else { drive = -ENODEV; } /* Describe SAN device, if applicable */ if ( ( drive >= 0 ) && ( ( rc = san_describe ( drive ) ) != 0 ) ) { printf ( "Could not describe SAN device %#02x: %s\n", drive, strerror ( rc ) ); goto err_san_describe; } /* Allow a root-path-only boot with skip-san enabled to succeed */ rc = 0; /* Attempt filename boot if applicable */ if ( filename ) { if ( ( rc = imgdownload ( filename, NULL, NULL, register_and_boot_image ) ) != 0 ) { printf ( "\nCould not chain image: %s\n", strerror ( rc ) ); /* Fall through to (possibly) attempt a SAN boot * as a fallback. If no SAN boot is attempted, * our status will become the return status. */ } else { /* Always print an extra newline, because we * don't know where the NBP may have left the * cursor. */ printf ( "\n" ); } } /* Attempt SAN boot if applicable */ if ( root_path ) { if ( fetch_intz_setting ( NULL, &skip_san_boot_setting) == 0 ) { printf ( "Booting from SAN device %#02x\n", drive ); rc = san_boot ( drive ); printf ( "Boot from SAN device %#02x failed: %s\n", drive, strerror ( rc ) ); } else { printf ( "Skipping boot from SAN device %#02x\n", drive ); /* Avoid overwriting a possible failure status * from a filename boot. */ } } err_san_describe: /* Unhook SAN device, if applicable */ if ( drive >= 0 ) { if ( fetch_intz_setting ( NULL, &keep_san_setting ) == 0 ) { printf ( "Unregistering SAN device %#02x\n", drive ); san_unhook ( drive ); } else { printf ( "Preserving connection to SAN device %#02x\n", drive ); } } err_san_hook: err_no_boot: return rc; } /** * Close all open net devices * * Called before a fresh boot attempt in order to free up memory. We * don't just close the device immediately after the boot fails, * because there may still be TCP connections in the process of * closing. */ static void close_all_netdevs ( void ) { struct net_device *netdev; for_each_netdev ( netdev ) { ifclose ( netdev ); } } /** * Fetch next-server and filename settings into a URI * * @v settings Settings block * @ret uri URI, or NULL on failure */ struct uri * fetch_next_server_and_filename ( struct settings *settings ) { struct in_addr next_server; char buf[256]; char *filename; struct uri *uri; /* Fetch next-server setting */ fetch_ipv4_setting ( settings, &next_server_setting, &next_server ); if ( next_server.s_addr ) printf ( "Next server: %s\n", inet_ntoa ( next_server ) ); /* Fetch filename setting */ fetch_string_setting ( settings, &filename_setting, buf, sizeof ( buf ) ); if ( buf[0] ) printf ( "Filename: %s\n", buf ); /* Expand filename setting */ filename = expand_settings ( buf ); if ( ! filename ) return NULL; /* Parse next server and filename */ uri = parse_next_server_and_filename ( next_server, filename ); free ( filename ); return uri; } /** * Fetch root-path setting into a URI * * @v settings Settings block * @ret uri URI, or NULL on failure */ static struct uri * fetch_root_path ( struct settings *settings ) { char buf[256]; char *root_path; struct uri *uri; /* Fetch root-path setting */ fetch_string_setting ( settings, &root_path_setting, buf, sizeof ( buf ) ); if ( buf[0] ) printf ( "Root path: %s\n", buf ); /* Expand filename setting */ root_path = expand_settings ( buf ); if ( ! root_path ) return NULL; /* Parse root path */ uri = parse_uri ( root_path ); free ( root_path ); return uri; } /** * Check whether or not we have a usable PXE menu * * @ret have_menu A usable PXE menu is present */ static int have_pxe_menu ( void ) { struct setting vendor_class_id_setting = { .tag = DHCP_VENDOR_CLASS_ID }; struct setting pxe_discovery_control_setting = { .tag = DHCP_PXE_DISCOVERY_CONTROL }; struct setting pxe_boot_menu_setting = { .tag = DHCP_PXE_BOOT_MENU }; char buf[256]; unsigned int pxe_discovery_control; fetch_string_setting ( NULL, &vendor_class_id_setting, buf, sizeof ( buf ) ); pxe_discovery_control = fetch_uintz_setting ( NULL, &pxe_discovery_control_setting ); return ( ( strcmp ( buf, "PXEClient" ) == 0 ) && setting_exists ( NULL, &pxe_boot_menu_setting ) && ( ! ( ( pxe_discovery_control & PXEBS_SKIP ) && setting_exists ( NULL, &filename_setting ) ) ) ); } /** * Boot from a network device * * @v netdev Network device * @ret rc Return status code */ int netboot ( struct net_device *netdev ) { struct uri *filename; struct uri *root_path; int rc; /* Close all other network devices */ close_all_netdevs(); /* Open device and display device status */ if ( ( rc = ifopen ( netdev ) ) != 0 ) goto err_ifopen; ifstat ( netdev ); /* Configure device via DHCP */ if ( ( rc = dhcp ( netdev ) ) != 0 ) goto err_dhcp; route(); /* Try PXE menu boot, if applicable */ if ( have_pxe_menu() ) { printf ( "Booting from PXE menu\n" ); rc = pxe_menu_boot ( netdev ); goto err_pxe_menu_boot; } /* Fetch next server, filename and root path */ filename = fetch_next_server_and_filename ( NULL ); if ( ! filename ) goto err_filename; root_path = fetch_root_path ( NULL ); if ( ! root_path ) goto err_root_path; /* Boot using next server, filename and root path */ if ( ( rc = uriboot ( filename, root_path ) ) != 0 ) goto err_uriboot; err_uriboot: uri_put ( root_path ); err_root_path: uri_put ( filename ); err_filename: err_pxe_menu_boot: err_dhcp: err_ifopen: return rc; } /** * Boot the system */ int autoboot ( void ) { struct net_device *boot_netdev; struct net_device *netdev; int rc = -ENODEV; /* If we have an identifable boot device, try that first */ if ( ( boot_netdev = find_boot_netdev() ) ) rc = netboot ( boot_netdev ); /* If that fails, try booting from any of the other devices */ for_each_netdev ( netdev ) { if ( netdev == boot_netdev ) continue; rc = netboot ( netdev ); } printf ( "No more network devices\n" ); return rc; }
185483.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE124_Buffer_Underwrite__char_alloca_cpy_09.c Label Definition File: CWE124_Buffer_Underwrite.stack.label.xml Template File: sources-sink-09.tmpl.c */ /* * @description * CWE: 124 Buffer Underwrite * BadSource: Set data pointer to before the allocated memory buffer * GoodSource: Set data pointer to the allocated memory buffer * Sink: cpy * BadSink : Copy string to data using strcpy * Flow Variant: 09 Control flow: if(global_const_t) and if(global_const_f) * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE124_Buffer_Underwrite__char_alloca_cpy_09_bad() { char * data; char * data_buf = (char *)ALLOCA(100*sizeof(char)); memset(data_buf, 'A', 100-1); data_buf[100-1] = '\0'; if(global_const_t) { /* FLAW: Set data pointer to before the allocated memory buffer */ data = data_buf - 8; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FIX: Set data pointer to the allocated memory buffer */ data = data_buf; } { char src[100]; memset(src, 'C', 100-1); /* fill with 'C's */ src[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ strcpy(data, src); printLine(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the global_const_t to global_const_f */ static void goodG2B1() { char * data; char * data_buf = (char *)ALLOCA(100*sizeof(char)); memset(data_buf, 'A', 100-1); data_buf[100-1] = '\0'; if(global_const_f) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FLAW: Set data pointer to before the allocated memory buffer */ data = data_buf - 8; } else { /* FIX: Set data pointer to the allocated memory buffer */ data = data_buf; } { char src[100]; memset(src, 'C', 100-1); /* fill with 'C's */ src[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ strcpy(data, src); printLine(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { char * data; char * data_buf = (char *)ALLOCA(100*sizeof(char)); memset(data_buf, 'A', 100-1); data_buf[100-1] = '\0'; if(global_const_t) { /* FIX: Set data pointer to the allocated memory buffer */ data = data_buf; } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ /* FLAW: Set data pointer to before the allocated memory buffer */ data = data_buf - 8; } { char src[100]; memset(src, 'C', 100-1); /* fill with 'C's */ src[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ strcpy(data, src); printLine(data); } } void CWE124_Buffer_Underwrite__char_alloca_cpy_09_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE124_Buffer_Underwrite__char_alloca_cpy_09_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE124_Buffer_Underwrite__char_alloca_cpy_09_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
19585.c
/* This tool prints out the token stream for standard input. It's primarily * intended to help write tests. */ #include <stdio.h> #include "../pdjson.h" const char json_typename[][16] = { [JSON_ERROR] = "ERROR", [JSON_DONE] = "DONE", [JSON_OBJECT] = "OBJECT", [JSON_OBJECT_END] = "OBJECT_END", [JSON_ARRAY] = "ARRAY", [JSON_ARRAY_END] = "ARRAY_END", [JSON_STRING] = "STRING", [JSON_NUMBER] = "NUMBER", [JSON_TRUE] = "TRUE", [JSON_FALSE] = "FALSE", [JSON_NULL] = "NULL", }; int main(void) { json_stream s[1]; json_open_stream(s, stdin); json_set_streaming(s, 1); puts("struct expect seq[] = {"); for (;;) { enum json_type type = json_next(s); const char *value = 0; switch (type) { case JSON_DONE: json_reset(s); break; case JSON_NULL: value = "null"; break; case JSON_TRUE: value = "true"; break; case JSON_FALSE: value = "false"; break; case JSON_NUMBER: value = json_get_string(s, 0); break; case JSON_STRING: value = json_get_string(s, 0); break; case JSON_ARRAY: case JSON_OBJECT: case JSON_OBJECT_END: case JSON_ARRAY_END: case JSON_ERROR: break; } if (value) printf(" {JSON_%s, \"%s\"},\n", json_typename[type], value); else printf(" {JSON_%s},\n", json_typename[type]); if (type == JSON_ERROR) break; } puts("};"); json_close(s); }
280430.c
/** ****************************************************************************** * @file stm32wlxx_hal_hsem.c * @author MCD Application Team * @brief HSEM HAL module driver. * This file provides firmware functions to manage the following * functionalities of the semaphore peripheral: * + Semaphore Take function (2-Step Procedure) , non blocking * + Semaphore FastTake function (1-Step Procedure) , non blocking * + Semaphore Status check * + Semaphore Clear Key Set and Get * + Release and release all functions * + Semaphore notification enabling and disabling and callnack functions * + IRQ handler management * * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (#)Take a semaphore In 2-Step mode Using function HAL_HSEM_Take. This function takes as parameters : (++) the semaphore ID from 0 to 15 (++) the process ID from 0 to 255 (#) Fast Take semaphore In 1-Step mode Using function HAL_HSEM_FastTake. This function takes as parameter : (++) the semaphore ID from 0 to 15. Note that the process ID value is implicitly assumed as zero (#) Check if a semaphore is Taken using function HAL_HSEM_IsSemTaken. This function takes as parameter : (++) the semaphore ID from 0 to 15 (++) It returns 1 if the given semaphore is taken otherwise (Free) zero (#)Release a semaphore using function with HAL_HSEM_Release. This function takes as parameters : (++) the semaphore ID from 0 to 15 (++) the process ID from 0 to 255: (++) Note: If ProcessID and MasterID match, semaphore is freed, and an interrupt may be generated when enabled (notification activated). If ProcessID or MasterID does not match, semaphore remains taken (locked) (#)Release all semaphores at once taken by a given Master using function HAL_HSEM_Release_All This function takes as parameters : (++) the Release Key (value from 0 to 0xFFFF) can be Set or Get respectively by HAL_HSEM_SetClearKey() or HAL_HSEM_GetClearKey functions (++) the Master ID: (++) Note: If the Key and MasterID match, all semaphores taken by the given CPU that corresponds to MasterID will be freed, and an interrupt may be generated when enabled (notification activated). If the Key or the MasterID doesn't match, semaphores remains taken (locked) (#)Semaphores Release all key functions: (++) HAL_HSEM_SetClearKey() to set semaphore release all Key (++) HAL_HSEM_GetClearKey() to get release all Key (#)Semaphores notification functions : (++) HAL_HSEM_ActivateNotification to activate a notification callback on a given semaphores Mask (bitfield). When one or more semaphores defined by the mask are released the callback HAL_HSEM_FreeCallback will be asserted giving as parameters a mask of the released semaphores (bitfield). (++) HAL_HSEM_DeactivateNotification to deactivate the notification of a given semaphores Mask (bitfield). (++) See the description of the macro __HAL_HSEM_SEMID_TO_MASK to check how to calculate a semaphore mask Used by the notification functions *** HSEM HAL driver macros list *** ============================================= [..] Below the list of most used macros in HSEM HAL driver. (+) __HAL_HSEM_SEMID_TO_MASK: Helper macro to convert a Semaphore ID to a Mask. [..] Example of use : [..] mask = __HAL_HSEM_SEMID_TO_MASK(8) | __HAL_HSEM_SEMID_TO_MASK(21) | __HAL_HSEM_SEMID_TO_MASK(25). [..] All next macros take as parameter a semaphore Mask (bitfiled) that can be constructed using __HAL_HSEM_SEMID_TO_MASK as the above example. (+) __HAL_HSEM_ENABLE_IT: Enable the specified semaphores Mask interrupts. (+) __HAL_HSEM_DISABLE_IT: Disable the specified semaphores Mask interrupts. (+) __HAL_HSEM_GET_IT: Checks whether the specified semaphore interrupt has occurred or not. (+) __HAL_HSEM_GET_FLAG: Get the semaphores status release flags. (+) __HAL_HSEM_CLEAR_FLAG: Clear the semaphores status release flags. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32wlxx_hal.h" /** @addtogroup STM32WLxx_HAL_Driver * @{ */ /** @defgroup HSEM HSEM * @brief HSEM HAL module driver * @{ */ #ifdef HAL_HSEM_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #if defined(DUAL_CORE) #ifndef HSEM_R_MASTERID #define HSEM_R_MASTERID HSEM_R_COREID #endif #ifndef HSEM_RLR_MASTERID #define HSEM_RLR_MASTERID HSEM_RLR_COREID #endif #ifndef HSEM_CR_MASTERID #define HSEM_CR_MASTERID HSEM_CR_COREID #endif #endif /* DUAL_CORE */ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @defgroup HSEM_Exported_Functions HSEM Exported Functions * @{ */ /** @defgroup HSEM_Exported_Functions_Group1 Take and Release functions * @brief HSEM Take and Release functions * @verbatim ============================================================================== ##### HSEM Take and Release functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Take a semaphore with 2 Step method (+) Fast Take a semaphore with 1 Step method (+) Check semaphore state Taken or not (+) Release a semaphore (+) Release all semaphore at once @endverbatim * @{ */ /** * @brief Take a semaphore in 2 Step mode. * @param SemID: semaphore ID from 0 to 15 * @param ProcessID: Process ID from 0 to 255 * @retval HAL status */ HAL_StatusTypeDef HAL_HSEM_Take(uint32_t SemID, uint32_t ProcessID) { /* Check the parameters */ assert_param(IS_HSEM_SEMID(SemID)); assert_param(IS_HSEM_PROCESSID(ProcessID)); /* First step write R register with MasterID, processID and take bit=1*/ HSEM->R[SemID] = (ProcessID | HSEM_CR_COREID_CURRENT | HSEM_R_LOCK); /* second step : read the R register . Take achieved if MasterID and processID match and take bit set to 1 */ if (HSEM->R[SemID] == (ProcessID | HSEM_CR_COREID_CURRENT | HSEM_R_LOCK)) { /*take success when MasterID and ProcessID match and take bit set*/ return HAL_OK; } /* Semaphore take fails*/ return HAL_ERROR; } /** * @brief Fast Take a semaphore with 1 Step mode. * @param SemID: semaphore ID from 0 to 15 * @retval HAL status */ HAL_StatusTypeDef HAL_HSEM_FastTake(uint32_t SemID) { /* Check the parameters */ assert_param(IS_HSEM_SEMID(SemID)); /* Read the RLR register to take the semaphore */ if (HSEM->RLR[SemID] == (HSEM_CR_COREID_CURRENT | HSEM_RLR_LOCK)) { /*take success when MasterID match and take bit set*/ return HAL_OK; } /* Semaphore take fails */ return HAL_ERROR; } /** * @brief Check semaphore state Taken or not. * @param SemID: semaphore ID * @retval HAL HSEM state */ uint32_t HAL_HSEM_IsSemTaken(uint32_t SemID) { return (((HSEM->R[SemID] & HSEM_R_LOCK) != 0U) ? 1UL : 0UL); } /** * @brief Release a semaphore. * @param SemID: semaphore ID from 0 to 15 * @param ProcessID: Process ID from 0 to 255 * @retval None */ void HAL_HSEM_Release(uint32_t SemID, uint32_t ProcessID) { /* Check the parameters */ assert_param(IS_HSEM_SEMID(SemID)); assert_param(IS_HSEM_PROCESSID(ProcessID)); /* Clear the semaphore by writing to the R register : the MasterID , the processID and take bit = 0 */ HSEM->R[SemID] = (ProcessID | HSEM_CR_COREID_CURRENT); } /** * @brief Release All semaphore used by a given Master . * @param Key: Semaphore Key , value from 0 to 0xFFFF * @param CoreID: CoreID of the CPU that is using semaphores to be released * @retval None */ void HAL_HSEM_ReleaseAll(uint32_t Key, uint32_t CoreID) { assert_param(IS_HSEM_KEY(Key)); assert_param(IS_HSEM_COREID(CoreID)); HSEM->CR = ((Key << HSEM_CR_KEY_Pos) | (CoreID << HSEM_CR_COREID_Pos)); } /** * @} */ /** @defgroup HSEM_Exported_Functions_Group2 HSEM Set and Get Key functions * @brief HSEM Set and Get Key functions. * @verbatim ============================================================================== ##### HSEM Set and Get Key functions ##### ============================================================================== [..] This section provides functions allowing to: (+) Set semaphore Key (+) Get semaphore Key @endverbatim * @{ */ /** * @brief Set semaphore Key . * @param Key: Semaphore Key , value from 0 to 0xFFFF * @retval None */ void HAL_HSEM_SetClearKey(uint32_t Key) { assert_param(IS_HSEM_KEY(Key)); MODIFY_REG(HSEM->KEYR, HSEM_KEYR_KEY, (Key << HSEM_KEYR_KEY_Pos)); } /** * @brief Get semaphore Key . * @retval Semaphore Key , value from 0 to 0xFFFF */ uint32_t HAL_HSEM_GetClearKey(void) { return (HSEM->KEYR >> HSEM_KEYR_KEY_Pos); } /** * @} */ /** @defgroup HSEM_Exported_Functions_Group3 HSEM IRQ handler management * @brief HSEM Notification functions. * @verbatim ============================================================================== ##### HSEM IRQ handler management and Notification functions ##### ============================================================================== [..] This section provides HSEM IRQ handler and Notification function. @endverbatim * @{ */ /** * @brief Activate Semaphore release Notification for a given Semaphores Mask . * @param SemMask: Mask of Released semaphores * @retval Semaphore Key */ void HAL_HSEM_ActivateNotification(uint32_t SemMask) { HSEM_COMMON->IER |= SemMask; } /** * @brief Deactivate Semaphore release Notification for a given Semaphores Mask . * @param SemMask: Mask of Released semaphores * @retval Semaphore Key */ void HAL_HSEM_DeactivateNotification(uint32_t SemMask) { HSEM_COMMON->IER &= ~SemMask; } /** * @brief This function handles HSEM interrupt request * @retval None */ void HAL_HSEM_IRQHandler(void) { uint32_t statusreg; /* Get the list of masked freed semaphores*/ statusreg = HSEM_COMMON->MISR; /*Disable Interrupts*/ HSEM_COMMON->IER &= ~((uint32_t)statusreg); /*Clear Flags*/ HSEM_COMMON->ICR = ((uint32_t)statusreg); /* Call FreeCallback */ HAL_HSEM_FreeCallback(statusreg); } /** * @brief Semaphore Released Callback. * @param SemMask: Mask of Released semaphores * @retval None */ __weak void HAL_HSEM_FreeCallback(uint32_t SemMask) { /* Prevent unused argument(s) compilation warning */ UNUSED(SemMask); /* NOTE : This function should not be modified, when the callback is needed, the HAL_HSEM_FreeCallback can be implemented in the user file */ } /** * @} */ /** * @} */ #endif /* HAL_HSEM_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
892847.c
#include <stdlib.h> void assert(int); int main(int argc, char* argv[]) { int x, y, *p, *q; int havoc; p = &x; x = 0; y = 1; assert(*p == 0); // pass if (havoc) { q = &x; } else { q = &y; } assert(*q == 0); // fail return 0; }
913736.c
#include <stdio.h> int main(void) { int t; scanf("%d", &t); while(t--) { int N, output; long long int K, D, A, Asum=0; //taking long long due to constraints scanf("%d %Ld %Ld", &N, &K, &D); while(N--) { scanf("%Ld", &A); Asum += A; //getting total number of problems } output = Asum/K; //checking how many can be made if(output<=D) printf("%d\n", output); else printf("%d\n", D); //If number of days required are less then print the days count } return 0; }
389445.c
/* $NetBSD: lvmcache.c,v 1.1.1.3 2009/12/02 00:26:21 haad Exp $ */ /* * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved. * * This file is part of LVM2. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License v.2.1. * * You should have received a copy of the GNU Lesser 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 "lib.h" #include "lvmcache.h" #include "toolcontext.h" #include "dev-cache.h" #include "locking.h" #include "metadata.h" #include "filter.h" #include "filter-persistent.h" #include "memlock.h" #include "str_list.h" #include "format-text.h" #include "format_pool.h" #include "format1.h" static struct dm_hash_table *_pvid_hash = NULL; static struct dm_hash_table *_vgid_hash = NULL; static struct dm_hash_table *_vgname_hash = NULL; static struct dm_hash_table *_lock_hash = NULL; static struct dm_list _vginfos; static int _scanning_in_progress = 0; static int _has_scanned = 0; static int _vgs_locked = 0; static int _vg_global_lock_held = 0; /* Global lock held when cache wiped? */ int lvmcache_init(void) { dm_list_init(&_vginfos); if (!(_vgname_hash = dm_hash_create(128))) return 0; if (!(_vgid_hash = dm_hash_create(128))) return 0; if (!(_pvid_hash = dm_hash_create(128))) return 0; if (!(_lock_hash = dm_hash_create(128))) return 0; /* * Reinitialising the cache clears the internal record of * which locks are held. The global lock can be held during * this operation so its state must be restored afterwards. */ if (_vg_global_lock_held) { lvmcache_lock_vgname(VG_GLOBAL, 0); _vg_global_lock_held = 0; } return 1; } /* Volume Group metadata cache functions */ static void _free_cached_vgmetadata(struct lvmcache_vginfo *vginfo) { if (!vginfo || !vginfo->vgmetadata) return; dm_free(vginfo->vgmetadata); vginfo->vgmetadata = NULL; log_debug("Metadata cache: VG %s wiped.", vginfo->vgname); } /* * Cache VG metadata against the vginfo with matching vgid. */ static void _store_metadata(struct volume_group *vg, unsigned precommitted) { char uuid[64] __attribute((aligned(8))); struct lvmcache_vginfo *vginfo; int size; if (!(vginfo = vginfo_from_vgid((const char *)&vg->id))) { stack; return; } if (vginfo->vgmetadata) _free_cached_vgmetadata(vginfo); if (!(size = export_vg_to_buffer(vg, &vginfo->vgmetadata))) { stack; return; } vginfo->precommitted = precommitted; if (!id_write_format((const struct id *)vginfo->vgid, uuid, sizeof(uuid))) { stack; return; } log_debug("Metadata cache: VG %s (%s) stored (%d bytes%s).", vginfo->vgname, uuid, size, precommitted ? ", precommitted" : ""); } static void _update_cache_info_lock_state(struct lvmcache_info *info, int locked, int *cached_vgmetadata_valid) { int was_locked = (info->status & CACHE_LOCKED) ? 1 : 0; /* * Cache becomes invalid whenever lock state changes unless * exclusive VG_GLOBAL is held (i.e. while scanning). */ if (!vgname_is_locked(VG_GLOBAL) && (was_locked != locked)) { info->status |= CACHE_INVALID; *cached_vgmetadata_valid = 0; } if (locked) info->status |= CACHE_LOCKED; else info->status &= ~CACHE_LOCKED; } static void _update_cache_vginfo_lock_state(struct lvmcache_vginfo *vginfo, int locked) { struct lvmcache_info *info; int cached_vgmetadata_valid = 1; dm_list_iterate_items(info, &vginfo->infos) _update_cache_info_lock_state(info, locked, &cached_vgmetadata_valid); if (!cached_vgmetadata_valid) _free_cached_vgmetadata(vginfo); } static void _update_cache_lock_state(const char *vgname, int locked) { struct lvmcache_vginfo *vginfo; if (!(vginfo = vginfo_from_vgname(vgname, NULL))) return; _update_cache_vginfo_lock_state(vginfo, locked); } static void _drop_metadata(const char *vgname) { struct lvmcache_vginfo *vginfo; struct lvmcache_info *info; if (!(vginfo = vginfo_from_vgname(vgname, NULL))) return; /* * Invalidate cached PV labels. * If cached precommitted metadata exists that means we * already invalidated the PV labels (before caching it) * and we must not do it again. */ if (!vginfo->precommitted) dm_list_iterate_items(info, &vginfo->infos) info->status |= CACHE_INVALID; _free_cached_vgmetadata(vginfo); } void lvmcache_drop_metadata(const char *vgname) { /* For VG_ORPHANS, we need to invalidate all labels on orphan PVs. */ if (!strcmp(vgname, VG_ORPHANS)) { _drop_metadata(FMT_TEXT_ORPHAN_VG_NAME); _drop_metadata(FMT_LVM1_ORPHAN_VG_NAME); _drop_metadata(FMT_POOL_ORPHAN_VG_NAME); /* Indicate that PVs could now be missing from the cache */ init_full_scan_done(0); } else if (!vgname_is_locked(VG_GLOBAL)) _drop_metadata(vgname); } /* * Ensure vgname2 comes after vgname1 alphabetically. * Special VG names beginning with '#' don't count. */ static int _vgname_order_correct(const char *vgname1, const char *vgname2) { if ((*vgname1 == '#') || (*vgname2 == '#')) return 1; if (strcmp(vgname1, vgname2) < 0) return 1; return 0; } /* * Ensure VG locks are acquired in alphabetical order. */ int lvmcache_verify_lock_order(const char *vgname) { struct dm_hash_node *n; const char *vgname2; if (!_lock_hash) return_0; dm_hash_iterate(n, _lock_hash) { if (!dm_hash_get_data(_lock_hash, n)) return_0; vgname2 = dm_hash_get_key(_lock_hash, n); if (!_vgname_order_correct(vgname2, vgname)) { log_errno(EDEADLK, "Internal error: VG lock %s must " "be requested before %s, not after.", vgname, vgname2); return_0; } } return 1; } void lvmcache_lock_vgname(const char *vgname, int read_only __attribute((unused))) { if (!_lock_hash && !lvmcache_init()) { log_error("Internal cache initialisation failed"); return; } if (dm_hash_lookup(_lock_hash, vgname)) log_error("Internal error: Nested locking attempted on VG %s.", vgname); if (!dm_hash_insert(_lock_hash, vgname, (void *) 1)) log_error("Cache locking failure for %s", vgname); _update_cache_lock_state(vgname, 1); if (strcmp(vgname, VG_GLOBAL)) _vgs_locked++; } int vgname_is_locked(const char *vgname) { if (!_lock_hash) return 0; return dm_hash_lookup(_lock_hash, vgname) ? 1 : 0; } void lvmcache_unlock_vgname(const char *vgname) { if (!dm_hash_lookup(_lock_hash, vgname)) log_error("Internal error: Attempt to unlock unlocked VG %s.", vgname); _update_cache_lock_state(vgname, 0); dm_hash_remove(_lock_hash, vgname); /* FIXME Do this per-VG */ if (strcmp(vgname, VG_GLOBAL) && !--_vgs_locked) dev_close_all(); } int vgs_locked(void) { return _vgs_locked; } static void _vginfo_attach_info(struct lvmcache_vginfo *vginfo, struct lvmcache_info *info) { if (!vginfo) return; info->vginfo = vginfo; dm_list_add(&vginfo->infos, &info->list); } static void _vginfo_detach_info(struct lvmcache_info *info) { if (!dm_list_empty(&info->list)) { dm_list_del(&info->list); dm_list_init(&info->list); } info->vginfo = NULL; } /* If vgid supplied, require a match. */ struct lvmcache_vginfo *vginfo_from_vgname(const char *vgname, const char *vgid) { struct lvmcache_vginfo *vginfo; if (!vgname) return vginfo_from_vgid(vgid); if (!_vgname_hash) return NULL; if (!(vginfo = dm_hash_lookup(_vgname_hash, vgname))) return NULL; if (vgid) do if (!strncmp(vgid, vginfo->vgid, ID_LEN)) return vginfo; while ((vginfo = vginfo->next)); return vginfo; } const struct format_type *fmt_from_vgname(const char *vgname, const char *vgid) { struct lvmcache_vginfo *vginfo; struct lvmcache_info *info; struct label *label; struct dm_list *devh, *tmp; struct dm_list devs; struct device_list *devl; char vgid_found[ID_LEN + 1] __attribute((aligned(8))); if (!(vginfo = vginfo_from_vgname(vgname, vgid))) return NULL; /* This function is normally called before reading metadata so * we check cached labels here. Unfortunately vginfo is volatile. */ dm_list_init(&devs); dm_list_iterate_items(info, &vginfo->infos) { if (!(devl = dm_malloc(sizeof(*devl)))) { log_error("device_list element allocation failed"); return NULL; } devl->dev = info->dev; dm_list_add(&devs, &devl->list); } memcpy(vgid_found, vginfo->vgid, sizeof(vgid_found)); dm_list_iterate_safe(devh, tmp, &devs) { devl = dm_list_item(devh, struct device_list); label_read(devl->dev, &label, UINT64_C(0)); dm_list_del(&devl->list); dm_free(devl); } /* If vginfo changed, caller needs to rescan */ if (!(vginfo = vginfo_from_vgname(vgname, vgid_found)) || strncmp(vginfo->vgid, vgid_found, ID_LEN)) return NULL; return vginfo->fmt; } struct lvmcache_vginfo *vginfo_from_vgid(const char *vgid) { struct lvmcache_vginfo *vginfo; char id[ID_LEN + 1] __attribute((aligned(8))); if (!_vgid_hash || !vgid) return NULL; /* vgid not necessarily NULL-terminated */ strncpy(&id[0], vgid, ID_LEN); id[ID_LEN] = '\0'; if (!(vginfo = dm_hash_lookup(_vgid_hash, id))) return NULL; return vginfo; } const char *vgname_from_vgid(struct dm_pool *mem, const char *vgid) { struct lvmcache_vginfo *vginfo; const char *vgname = NULL; if ((vginfo = vginfo_from_vgid(vgid))) vgname = vginfo->vgname; if (mem && vgname) return dm_pool_strdup(mem, vgname); return vgname; } static int _info_is_valid(struct lvmcache_info *info) { if (info->status & CACHE_INVALID) return 0; /* * The caller must hold the VG lock to manipulate metadata. * In a cluster, remote nodes sometimes read metadata in the * knowledge that the controlling node is holding the lock. * So if the VG appears to be unlocked here, it should be safe * to use the cached value. */ if (info->vginfo && !vgname_is_locked(info->vginfo->vgname)) return 1; if (!(info->status & CACHE_LOCKED)) return 0; return 1; } static int _vginfo_is_valid(struct lvmcache_vginfo *vginfo) { struct lvmcache_info *info; /* Invalid if any info is invalid */ dm_list_iterate_items(info, &vginfo->infos) if (!_info_is_valid(info)) return 0; return 1; } /* vginfo is invalid if it does not contain at least one valid info */ static int _vginfo_is_invalid(struct lvmcache_vginfo *vginfo) { struct lvmcache_info *info; dm_list_iterate_items(info, &vginfo->infos) if (_info_is_valid(info)) return 0; return 1; } /* * If valid_only is set, data will only be returned if the cached data is * known still to be valid. */ struct lvmcache_info *info_from_pvid(const char *pvid, int valid_only) { struct lvmcache_info *info; char id[ID_LEN + 1] __attribute((aligned(8))); if (!_pvid_hash || !pvid) return NULL; strncpy(&id[0], pvid, ID_LEN); id[ID_LEN] = '\0'; if (!(info = dm_hash_lookup(_pvid_hash, id))) return NULL; if (valid_only && !_info_is_valid(info)) return NULL; return info; } static void _rescan_entry(struct lvmcache_info *info) { struct label *label; if (info->status & CACHE_INVALID) label_read(info->dev, &label, UINT64_C(0)); } static int _scan_invalid(void) { dm_hash_iter(_pvid_hash, (dm_hash_iterate_fn) _rescan_entry); return 1; } int lvmcache_label_scan(struct cmd_context *cmd, int full_scan) { struct label *label; struct dev_iter *iter; struct device *dev; struct format_type *fmt; int r = 0; /* Avoid recursion when a PVID can't be found! */ if (_scanning_in_progress) return 0; _scanning_in_progress = 1; if (!_vgname_hash && !lvmcache_init()) { log_error("Internal cache initialisation failed"); goto out; } if (_has_scanned && !full_scan) { r = _scan_invalid(); goto out; } if (full_scan == 2 && !refresh_filters(cmd)) { log_error("refresh filters failed"); goto out; } if (!(iter = dev_iter_create(cmd->filter, (full_scan == 2) ? 1 : 0))) { log_error("dev_iter creation failed"); goto out; } while ((dev = dev_iter_get(iter))) label_read(dev, &label, UINT64_C(0)); dev_iter_destroy(iter); _has_scanned = 1; /* Perform any format-specific scanning e.g. text files */ dm_list_iterate_items(fmt, &cmd->formats) { if (fmt->ops->scan && !fmt->ops->scan(fmt)) goto out; } /* * If we are a long-lived process, write out the updated persistent * device cache for the benefit of short-lived processes. */ if (full_scan == 2 && cmd->is_long_lived && cmd->dump_filter) persistent_filter_dump(cmd->filter); r = 1; out: _scanning_in_progress = 0; return r; } struct volume_group *lvmcache_get_vg(const char *vgid, unsigned precommitted) { struct lvmcache_vginfo *vginfo; struct volume_group *vg; struct format_instance *fid; if (!vgid || !(vginfo = vginfo_from_vgid(vgid)) || !vginfo->vgmetadata) return NULL; if (!_vginfo_is_valid(vginfo)) return NULL; /* * Don't return cached data if either: * (i) precommitted metadata is requested but we don't have it cached * - caller should read it off disk; * (ii) live metadata is requested but we have precommitted metadata cached * and no devices are suspended so caller may read it off disk. * * If live metadata is requested but we have precommitted metadata cached * and devices are suspended, we assume this precommitted metadata has * already been preloaded and committed so it's OK to return it as live. * Note that we do not clear the PRECOMMITTED flag. */ if ((precommitted && !vginfo->precommitted) || (!precommitted && vginfo->precommitted && !memlock())) return NULL; if (!(fid = vginfo->fmt->ops->create_instance(vginfo->fmt, vginfo->vgname, vgid, NULL))) return_NULL; if (!(vg = import_vg_from_buffer(vginfo->vgmetadata, fid)) || !vg_validate(vg)) { _free_cached_vgmetadata(vginfo); vg_release(vg); return_NULL; } log_debug("Using cached %smetadata for VG %s.", vginfo->precommitted ? "pre-committed" : "", vginfo->vgname); return vg; } struct dm_list *lvmcache_get_vgids(struct cmd_context *cmd, int full_scan) { struct dm_list *vgids; struct lvmcache_vginfo *vginfo; lvmcache_label_scan(cmd, full_scan); if (!(vgids = str_list_create(cmd->mem))) { log_error("vgids list allocation failed"); return NULL; } dm_list_iterate_items(vginfo, &_vginfos) { if (!str_list_add(cmd->mem, vgids, dm_pool_strdup(cmd->mem, vginfo->vgid))) { log_error("strlist allocation failed"); return NULL; } } return vgids; } struct dm_list *lvmcache_get_vgnames(struct cmd_context *cmd, int full_scan) { struct dm_list *vgnames; struct lvmcache_vginfo *vginfo; lvmcache_label_scan(cmd, full_scan); if (!(vgnames = str_list_create(cmd->mem))) { log_errno(ENOMEM, "vgnames list allocation failed"); return NULL; } dm_list_iterate_items(vginfo, &_vginfos) { if (!str_list_add(cmd->mem, vgnames, dm_pool_strdup(cmd->mem, vginfo->vgname))) { log_errno(ENOMEM, "strlist allocation failed"); return NULL; } } return vgnames; } struct dm_list *lvmcache_get_pvids(struct cmd_context *cmd, const char *vgname, const char *vgid) { struct dm_list *pvids; struct lvmcache_vginfo *vginfo; struct lvmcache_info *info; if (!(pvids = str_list_create(cmd->mem))) { log_error("pvids list allocation failed"); return NULL; } if (!(vginfo = vginfo_from_vgname(vgname, vgid))) return pvids; dm_list_iterate_items(info, &vginfo->infos) { if (!str_list_add(cmd->mem, pvids, dm_pool_strdup(cmd->mem, info->dev->pvid))) { log_error("strlist allocation failed"); return NULL; } } return pvids; } struct device *device_from_pvid(struct cmd_context *cmd, struct id *pvid) { struct label *label; struct lvmcache_info *info; /* Already cached ? */ if ((info = info_from_pvid((char *) pvid, 0))) { if (label_read(info->dev, &label, UINT64_C(0))) { info = (struct lvmcache_info *) label->info; if (id_equal(pvid, (struct id *) &info->dev->pvid)) return info->dev; } } lvmcache_label_scan(cmd, 0); /* Try again */ if ((info = info_from_pvid((char *) pvid, 0))) { if (label_read(info->dev, &label, UINT64_C(0))) { info = (struct lvmcache_info *) label->info; if (id_equal(pvid, (struct id *) &info->dev->pvid)) return info->dev; } } if (memlock()) return NULL; lvmcache_label_scan(cmd, 2); /* Try again */ if ((info = info_from_pvid((char *) pvid, 0))) { if (label_read(info->dev, &label, UINT64_C(0))) { info = (struct lvmcache_info *) label->info; if (id_equal(pvid, (struct id *) &info->dev->pvid)) return info->dev; } } return NULL; } static int _free_vginfo(struct lvmcache_vginfo *vginfo) { struct lvmcache_vginfo *primary_vginfo, *vginfo2; int r = 1; _free_cached_vgmetadata(vginfo); vginfo2 = primary_vginfo = vginfo_from_vgname(vginfo->vgname, NULL); if (vginfo == primary_vginfo) { dm_hash_remove(_vgname_hash, vginfo->vgname); if (vginfo->next && !dm_hash_insert(_vgname_hash, vginfo->vgname, vginfo->next)) { log_error("_vgname_hash re-insertion for %s failed", vginfo->vgname); r = 0; } } else do if (vginfo2->next == vginfo) { vginfo2->next = vginfo->next; break; } while ((vginfo2 = primary_vginfo->next)); if (vginfo->vgname) dm_free(vginfo->vgname); if (vginfo->creation_host) dm_free(vginfo->creation_host); if (*vginfo->vgid && _vgid_hash && vginfo_from_vgid(vginfo->vgid) == vginfo) dm_hash_remove(_vgid_hash, vginfo->vgid); dm_list_del(&vginfo->list); dm_free(vginfo); return r; } /* * vginfo must be info->vginfo unless info is NULL */ static int _drop_vginfo(struct lvmcache_info *info, struct lvmcache_vginfo *vginfo) { if (info) _vginfo_detach_info(info); /* vginfo still referenced? */ if (!vginfo || is_orphan_vg(vginfo->vgname) || !dm_list_empty(&vginfo->infos)) return 1; if (!_free_vginfo(vginfo)) return_0; return 1; } /* Unused void lvmcache_del(struct lvmcache_info *info) { if (info->dev->pvid[0] && _pvid_hash) dm_hash_remove(_pvid_hash, info->dev->pvid); _drop_vginfo(info, info->vginfo); info->label->labeller->ops->destroy_label(info->label->labeller, info->label); dm_free(info); return; } */ static int _lvmcache_update_pvid(struct lvmcache_info *info, const char *pvid) { /* * Nothing to do if already stored with same pvid. */ if (((dm_hash_lookup(_pvid_hash, pvid)) == info) && !strcmp(info->dev->pvid, pvid)) return 1; if (*info->dev->pvid) dm_hash_remove(_pvid_hash, info->dev->pvid); strncpy(info->dev->pvid, pvid, sizeof(info->dev->pvid)); if (!dm_hash_insert(_pvid_hash, pvid, info)) { log_error("_lvmcache_update: pvid insertion failed: %s", pvid); return 0; } return 1; } /* * vginfo must be info->vginfo unless info is NULL (orphans) */ static int _lvmcache_update_vgid(struct lvmcache_info *info, struct lvmcache_vginfo *vginfo, const char *vgid) { if (!vgid || !vginfo || !strncmp(vginfo->vgid, vgid, ID_LEN)) return 1; if (vginfo && *vginfo->vgid) dm_hash_remove(_vgid_hash, vginfo->vgid); if (!vgid) { log_debug("lvmcache: %s: clearing VGID", info ? dev_name(info->dev) : vginfo->vgname); return 1; } strncpy(vginfo->vgid, vgid, ID_LEN); vginfo->vgid[ID_LEN] = '\0'; if (!dm_hash_insert(_vgid_hash, vginfo->vgid, vginfo)) { log_error("_lvmcache_update: vgid hash insertion failed: %s", vginfo->vgid); return 0; } if (!is_orphan_vg(vginfo->vgname)) log_debug("lvmcache: %s: setting %s VGID to %s", dev_name(info->dev), vginfo->vgname, vginfo->vgid); return 1; } static int _insert_vginfo(struct lvmcache_vginfo *new_vginfo, const char *vgid, uint32_t vgstatus, const char *creation_host, struct lvmcache_vginfo *primary_vginfo) { struct lvmcache_vginfo *last_vginfo = primary_vginfo; char uuid_primary[64] __attribute((aligned(8))); char uuid_new[64] __attribute((aligned(8))); int use_new = 0; /* Pre-existing VG takes precedence. Unexported VG takes precedence. */ if (primary_vginfo) { if (!id_write_format((const struct id *)vgid, uuid_new, sizeof(uuid_new))) return_0; if (!id_write_format((const struct id *)&primary_vginfo->vgid, uuid_primary, sizeof(uuid_primary))) return_0; /* * If Primary not exported, new exported => keep * Else Primary exported, new not exported => change * Else Primary has hostname for this machine => keep * Else Primary has no hostname, new has one => change * Else New has hostname for this machine => change * Else Keep primary. */ if (!(primary_vginfo->status & EXPORTED_VG) && (vgstatus & EXPORTED_VG)) log_error("WARNING: Duplicate VG name %s: " "Existing %s takes precedence over " "exported %s", new_vginfo->vgname, uuid_primary, uuid_new); else if ((primary_vginfo->status & EXPORTED_VG) && !(vgstatus & EXPORTED_VG)) { log_error("WARNING: Duplicate VG name %s: " "%s takes precedence over exported %s", new_vginfo->vgname, uuid_new, uuid_primary); use_new = 1; } else if (primary_vginfo->creation_host && !strcmp(primary_vginfo->creation_host, primary_vginfo->fmt->cmd->hostname)) log_error("WARNING: Duplicate VG name %s: " "Existing %s (created here) takes precedence " "over %s", new_vginfo->vgname, uuid_primary, uuid_new); else if (!primary_vginfo->creation_host && creation_host) { log_error("WARNING: Duplicate VG name %s: " "%s (with creation_host) takes precedence over %s", new_vginfo->vgname, uuid_new, uuid_primary); use_new = 1; } else if (creation_host && !strcmp(creation_host, primary_vginfo->fmt->cmd->hostname)) { log_error("WARNING: Duplicate VG name %s: " "%s (created here) takes precedence over %s", new_vginfo->vgname, uuid_new, uuid_primary); use_new = 1; } if (!use_new) { while (last_vginfo->next) last_vginfo = last_vginfo->next; last_vginfo->next = new_vginfo; return 1; } dm_hash_remove(_vgname_hash, primary_vginfo->vgname); } if (!dm_hash_insert(_vgname_hash, new_vginfo->vgname, new_vginfo)) { log_error("cache_update: vg hash insertion failed: %s", new_vginfo->vgname); return 0; } if (primary_vginfo) new_vginfo->next = primary_vginfo; return 1; } static int _lvmcache_update_vgname(struct lvmcache_info *info, const char *vgname, const char *vgid, uint32_t vgstatus, const char *creation_host, const struct format_type *fmt) { struct lvmcache_vginfo *vginfo, *primary_vginfo, *orphan_vginfo; struct lvmcache_info *info2, *info3; char mdabuf[32]; // struct lvmcache_vginfo *old_vginfo, *next; if (!vgname || (info && info->vginfo && !strcmp(info->vginfo->vgname, vgname))) return 1; /* Remove existing vginfo entry */ if (info) _drop_vginfo(info, info->vginfo); /* Get existing vginfo or create new one */ if (!(vginfo = vginfo_from_vgname(vgname, vgid))) { /*** FIXME - vginfo ends up duplicated instead of renamed. // Renaming? This lookup fails. if ((vginfo = vginfo_from_vgid(vgid))) { next = vginfo->next; old_vginfo = vginfo_from_vgname(vginfo->vgname, NULL); if (old_vginfo == vginfo) { dm_hash_remove(_vgname_hash, old_vginfo->vgname); if (old_vginfo->next) { if (!dm_hash_insert(_vgname_hash, old_vginfo->vgname, old_vginfo->next)) { log_error("vg hash re-insertion failed: %s", old_vginfo->vgname); return 0; } } } else do { if (old_vginfo->next == vginfo) { old_vginfo->next = vginfo->next; break; } } while ((old_vginfo = old_vginfo->next)); vginfo->next = NULL; dm_free(vginfo->vgname); if (!(vginfo->vgname = dm_strdup(vgname))) { log_error("cache vgname alloc failed for %s", vgname); return 0; } // Rename so can assume new name does not already exist if (!dm_hash_insert(_vgname_hash, vginfo->vgname, vginfo->next)) { log_error("vg hash re-insertion failed: %s", vginfo->vgname); return 0; } } else { ***/ if (!(vginfo = dm_malloc(sizeof(*vginfo)))) { log_error("lvmcache_update_vgname: list alloc failed"); return 0; } memset(vginfo, 0, sizeof(*vginfo)); if (!(vginfo->vgname = dm_strdup(vgname))) { dm_free(vginfo); log_error("cache vgname alloc failed for %s", vgname); return 0; } dm_list_init(&vginfo->infos); /* * If we're scanning and there's an invalidated entry, remove it. * Otherwise we risk bogus warnings of duplicate VGs. */ while ((primary_vginfo = vginfo_from_vgname(vgname, NULL)) && _scanning_in_progress && _vginfo_is_invalid(primary_vginfo)) dm_list_iterate_items_safe(info2, info3, &primary_vginfo->infos) { orphan_vginfo = vginfo_from_vgname(primary_vginfo->fmt->orphan_vg_name, NULL); _drop_vginfo(info2, primary_vginfo); _vginfo_attach_info(orphan_vginfo, info2); if (info2->mdas.n) sprintf(mdabuf, " with %u mdas", dm_list_size(&info2->mdas)); else mdabuf[0] = '\0'; log_debug("lvmcache: %s: now in VG %s%s%s%s%s", dev_name(info2->dev), vgname, orphan_vginfo->vgid[0] ? " (" : "", orphan_vginfo->vgid[0] ? orphan_vginfo->vgid : "", orphan_vginfo->vgid[0] ? ")" : "", mdabuf); } if (!_insert_vginfo(vginfo, vgid, vgstatus, creation_host, primary_vginfo)) { dm_free(vginfo->vgname); dm_free(vginfo); return 0; } /* Ensure orphans appear last on list_iterate */ if (is_orphan_vg(vgname)) dm_list_add(&_vginfos, &vginfo->list); else dm_list_add_h(&_vginfos, &vginfo->list); /*** } ***/ } if (info) _vginfo_attach_info(vginfo, info); else if (!_lvmcache_update_vgid(NULL, vginfo, vgid)) /* Orphans */ return_0; _update_cache_vginfo_lock_state(vginfo, vgname_is_locked(vgname)); /* FIXME Check consistency of list! */ vginfo->fmt = fmt; if (info) { if (info->mdas.n) sprintf(mdabuf, " with %u mdas", dm_list_size(&info->mdas)); else mdabuf[0] = '\0'; log_debug("lvmcache: %s: now in VG %s%s%s%s%s", dev_name(info->dev), vgname, vginfo->vgid[0] ? " (" : "", vginfo->vgid[0] ? vginfo->vgid : "", vginfo->vgid[0] ? ")" : "", mdabuf); } else log_debug("lvmcache: initialised VG %s", vgname); return 1; } static int _lvmcache_update_vgstatus(struct lvmcache_info *info, uint32_t vgstatus, const char *creation_host) { if (!info || !info->vginfo) return 1; if ((info->vginfo->status & EXPORTED_VG) != (vgstatus & EXPORTED_VG)) log_debug("lvmcache: %s: VG %s %s exported", dev_name(info->dev), info->vginfo->vgname, vgstatus & EXPORTED_VG ? "now" : "no longer"); info->vginfo->status = vgstatus; if (!creation_host) return 1; if (info->vginfo->creation_host && !strcmp(creation_host, info->vginfo->creation_host)) return 1; if (info->vginfo->creation_host) dm_free(info->vginfo->creation_host); if (!(info->vginfo->creation_host = dm_strdup(creation_host))) { log_error("cache creation host alloc failed for %s", creation_host); return 0; } log_debug("lvmcache: %s: VG %s: Set creation host to %s.", dev_name(info->dev), info->vginfo->vgname, creation_host); return 1; } int lvmcache_add_orphan_vginfo(const char *vgname, struct format_type *fmt) { if (!_lock_hash && !lvmcache_init()) { log_error("Internal cache initialisation failed"); return 0; } return _lvmcache_update_vgname(NULL, vgname, vgname, 0, "", fmt); } int lvmcache_update_vgname_and_id(struct lvmcache_info *info, const char *vgname, const char *vgid, uint32_t vgstatus, const char *creation_host) { if (!vgname && !info->vginfo) { log_error("Internal error: NULL vgname handed to cache"); /* FIXME Remove this */ vgname = info->fmt->orphan_vg_name; vgid = vgname; } /* If PV without mdas is already in a real VG, don't make it orphan */ if (is_orphan_vg(vgname) && info->vginfo && !dm_list_size(&info->mdas) && !is_orphan_vg(info->vginfo->vgname) && memlock()) return 1; /* If moving PV from orphan to real VG, always mark it valid */ if (!is_orphan_vg(vgname)) info->status &= ~CACHE_INVALID; if (!_lvmcache_update_vgname(info, vgname, vgid, vgstatus, creation_host, info->fmt) || !_lvmcache_update_vgid(info, info->vginfo, vgid) || !_lvmcache_update_vgstatus(info, vgstatus, creation_host)) return_0; return 1; } int lvmcache_update_vg(struct volume_group *vg, unsigned precommitted) { struct pv_list *pvl; struct lvmcache_info *info; char pvid_s[ID_LEN + 1] __attribute((aligned(8))); pvid_s[sizeof(pvid_s) - 1] = '\0'; dm_list_iterate_items(pvl, &vg->pvs) { strncpy(pvid_s, (char *) &pvl->pv->id, sizeof(pvid_s) - 1); /* FIXME Could pvl->pv->dev->pvid ever be different? */ if ((info = info_from_pvid(pvid_s, 0)) && !lvmcache_update_vgname_and_id(info, vg->name, (char *) &vg->id, vg->status, NULL)) return_0; } /* store text representation of vg to cache */ if (vg->cmd->current_settings.cache_vgmetadata) _store_metadata(vg, precommitted); return 1; } struct lvmcache_info *lvmcache_add(struct labeller *labeller, const char *pvid, struct device *dev, const char *vgname, const char *vgid, uint32_t vgstatus) { struct label *label; struct lvmcache_info *existing, *info; char pvid_s[ID_LEN + 1] __attribute((aligned(8))); if (!_vgname_hash && !lvmcache_init()) { log_error("Internal cache initialisation failed"); return NULL; } strncpy(pvid_s, pvid, sizeof(pvid_s)); pvid_s[sizeof(pvid_s) - 1] = '\0'; if (!(existing = info_from_pvid(pvid_s, 0)) && !(existing = info_from_pvid(dev->pvid, 0))) { if (!(label = label_create(labeller))) return_NULL; if (!(info = dm_malloc(sizeof(*info)))) { log_error("lvmcache_info allocation failed"); label_destroy(label); return NULL; } memset(info, 0, sizeof(*info)); label->info = info; info->label = label; dm_list_init(&info->list); info->dev = dev; } else { if (existing->dev != dev) { /* Is the existing entry a duplicate pvid e.g. md ? */ if (dev_subsystem_part_major(existing->dev) && !dev_subsystem_part_major(dev)) { log_very_verbose("Ignoring duplicate PV %s on " "%s - using %s %s", pvid, dev_name(dev), dev_subsystem_name(existing->dev), dev_name(existing->dev)); return NULL; } else if (dm_is_dm_major(MAJOR(existing->dev->dev)) && !dm_is_dm_major(MAJOR(dev->dev))) { log_very_verbose("Ignoring duplicate PV %s on " "%s - using dm %s", pvid, dev_name(dev), dev_name(existing->dev)); return NULL; } else if (!dev_subsystem_part_major(existing->dev) && dev_subsystem_part_major(dev)) log_very_verbose("Duplicate PV %s on %s - " "using %s %s", pvid, dev_name(existing->dev), dev_subsystem_name(existing->dev), dev_name(dev)); else if (!dm_is_dm_major(MAJOR(existing->dev->dev)) && dm_is_dm_major(MAJOR(dev->dev))) log_very_verbose("Duplicate PV %s on %s - " "using dm %s", pvid, dev_name(existing->dev), dev_name(dev)); /* FIXME If both dm, check dependencies */ //else if (dm_is_dm_major(MAJOR(existing->dev->dev)) && //dm_is_dm_major(MAJOR(dev->dev))) // else if (!strcmp(pvid_s, existing->dev->pvid)) log_error("Found duplicate PV %s: using %s not " "%s", pvid, dev_name(dev), dev_name(existing->dev)); } if (strcmp(pvid_s, existing->dev->pvid)) log_debug("Updating pvid cache to %s (%s) from %s (%s)", pvid_s, dev_name(dev), existing->dev->pvid, dev_name(existing->dev)); /* Switch over to new preferred device */ existing->dev = dev; info = existing; /* Has labeller changed? */ if (info->label->labeller != labeller) { label_destroy(info->label); if (!(info->label = label_create(labeller))) /* FIXME leaves info without label! */ return_NULL; info->label->info = info; } label = info->label; } info->fmt = (const struct format_type *) labeller->private; info->status |= CACHE_INVALID; if (!_lvmcache_update_pvid(info, pvid_s)) { if (!existing) { dm_free(info); label_destroy(label); } return NULL; } if (!lvmcache_update_vgname_and_id(info, vgname, vgid, vgstatus, NULL)) { if (!existing) { dm_hash_remove(_pvid_hash, pvid_s); strcpy(info->dev->pvid, ""); dm_free(info); label_destroy(label); } return NULL; } return info; } static void _lvmcache_destroy_entry(struct lvmcache_info *info) { _vginfo_detach_info(info); strcpy(info->dev->pvid, ""); label_destroy(info->label); dm_free(info); } static void _lvmcache_destroy_vgnamelist(struct lvmcache_vginfo *vginfo) { struct lvmcache_vginfo *next; do { next = vginfo->next; if (!_free_vginfo(vginfo)) stack; } while ((vginfo = next)); } static void _lvmcache_destroy_lockname(struct dm_hash_node *n) { char *vgname; if (!dm_hash_get_data(_lock_hash, n)) return; vgname = dm_hash_get_key(_lock_hash, n); if (!strcmp(vgname, VG_GLOBAL)) _vg_global_lock_held = 1; else log_error("Internal error: Volume Group %s was not unlocked", dm_hash_get_key(_lock_hash, n)); } void lvmcache_destroy(struct cmd_context *cmd, int retain_orphans) { struct dm_hash_node *n; log_verbose("Wiping internal VG cache"); _has_scanned = 0; if (_vgid_hash) { dm_hash_destroy(_vgid_hash); _vgid_hash = NULL; } if (_pvid_hash) { dm_hash_iter(_pvid_hash, (dm_hash_iterate_fn) _lvmcache_destroy_entry); dm_hash_destroy(_pvid_hash); _pvid_hash = NULL; } if (_vgname_hash) { dm_hash_iter(_vgname_hash, (dm_hash_iterate_fn) _lvmcache_destroy_vgnamelist); dm_hash_destroy(_vgname_hash); _vgname_hash = NULL; } if (_lock_hash) { dm_hash_iterate(n, _lock_hash) _lvmcache_destroy_lockname(n); dm_hash_destroy(_lock_hash); _lock_hash = NULL; } if (!dm_list_empty(&_vginfos)) log_error("Internal error: _vginfos list should be empty"); dm_list_init(&_vginfos); if (retain_orphans) init_lvmcache_orphans(cmd); }
600094.c
/**************************************************************************/ /*! @file test_ehci_pipe_xfer.c @author hathach (tinyusb.org) @section LICENSE Software License Agreement (BSD License) Copyright (c) 2013, hathach (tinyusb.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holders 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 ''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 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This file is part of the tinyusb stack. */ /**************************************************************************/ #include <stdlib.h> #include "unity.h" #include "tusb_option.h" #include "tusb_errors.h" #include "binary.h" #include "type_helper.h" #include "hal.h" #include "mock_osal.h" #include "hcd.h" #include "mock_usbh_hcd.h" #include "ehci.h" #include "ehci_controller_fake.h" #include "host_helper.h" usbh_device_t _usbh_devices[CFG_TUSB_HOST_DEVICE_MAX+1]; static uint8_t const control_max_packet_size = 64; static uint8_t const hub_addr = 2; static uint8_t const hub_port = 2; static uint8_t dev_addr; static uint8_t hostid; static uint8_t xfer_data [100]; static ehci_qhd_t *async_head; static ehci_qhd_t *p_control_qhd; static ehci_qtd_t *p_setup; static ehci_qtd_t *p_data; static ehci_qtd_t *p_status; //--------------------------------------------------------------------+ // Setup/Teardown + helper declare //--------------------------------------------------------------------+ void setUp(void) { ehci_controller_init(); tu_memclr(_usbh_devices, sizeof(usbh_device_t)*(CFG_TUSB_HOST_DEVICE_MAX+1)); tu_memclr(xfer_data, sizeof(xfer_data)); TEST_ASSERT_STATUS( hcd_init() ); dev_addr = 1; hostid = RANDOM(CONTROLLER_HOST_NUMBER) + TEST_CONTROLLER_HOST_START_INDEX; helper_usbh_device_emulate(0 , hub_addr, hub_port, hostid, TUSB_SPEED_HIGH); helper_usbh_device_emulate(dev_addr , hub_addr, hub_port, hostid, TUSB_SPEED_HIGH); async_head = get_async_head( hostid ); //------------- pipe open -------------// TEST_ASSERT_STATUS( hcd_pipe_control_open(dev_addr, control_max_packet_size) ); p_control_qhd = &ehci_data.device[dev_addr-1].control.qhd; p_setup = &ehci_data.device[dev_addr-1].control.qtd[0]; p_data = &ehci_data.device[dev_addr-1].control.qtd[1]; p_status = &ehci_data.device[dev_addr-1].control.qtd[2]; } void tearDown(void) { } //--------------------------------------------------------------------+ // CONTROL TRANSFER //--------------------------------------------------------------------+ tusb_control_request_t request_get_dev_desc = { .bmRequestType_bit = { .direction = TUSB_DIR_DEV_TO_HOST, .type = TUSB_REQ_TYPE_STANDARD, .recipient = TUSB_REQ_RECIPIENT_DEVICE }, .bRequest = TUSB_REQ_GET_DESCRIPTOR, .wValue = (TUSB_DESC_TYPE_DEVICE << 8), .wLength = 18 }; tusb_control_request_t request_set_dev_addr = { .bmRequestType_bit = { .direction = TUSB_DIR_HOST_TO_DEV, .type = TUSB_REQ_TYPE_STANDARD, .recipient = TUSB_REQ_RECIPIENT_DEVICE }, .bRequest = TUSB_REQ_SET_ADDRESS, .wValue = 3 }; void verify_qtd(ehci_qtd_t *p_qtd, uint8_t p_data[], uint16_t length) { TEST_ASSERT_TRUE(p_qtd->alternate.terminate); // not used, always invalid TEST_ASSERT_FALSE(p_qtd->pingstate_err); TEST_ASSERT_FALSE(p_qtd->non_hs_split_state); TEST_ASSERT_FALSE(p_qtd->non_hs_period_missed_uframe); TEST_ASSERT_FALSE(p_qtd->xact_err); TEST_ASSERT_FALSE(p_qtd->babble_err); TEST_ASSERT_FALSE(p_qtd->buffer_err); TEST_ASSERT_FALSE(p_qtd->halted); TEST_ASSERT_TRUE(p_qtd->active); TEST_ASSERT_EQUAL(3, p_qtd->cerr); TEST_ASSERT_EQUAL(0, p_qtd->current_page); TEST_ASSERT_EQUAL(length, p_qtd->total_bytes); TEST_ASSERT_EQUAL_HEX(p_data, p_qtd->buffer[0]); } //--------------------------------------------------------------------+ // Address 0 //--------------------------------------------------------------------+ void test_control_addr0_xfer_get_check_qhd_qtd_mapping(void) { dev_addr = 0; ehci_qhd_t * const p_qhd = async_head; TEST_ASSERT_STATUS( hcd_pipe_control_open(dev_addr, control_max_packet_size) ); //------------- Code Under TEST -------------// TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_get_dev_desc, xfer_data) ); p_setup = &ehci_data.addr0_qtd[0]; p_data = &ehci_data.addr0_qtd[1]; p_status = &ehci_data.addr0_qtd[2]; TEST_ASSERT_EQUAL(0 , p_qhd->total_xferred_bytes); TEST_ASSERT_EQUAL_HEX( p_setup, p_qhd->qtd_overlay.next.address ); TEST_ASSERT_EQUAL_HEX( p_setup , p_qhd->p_qtd_list_head); TEST_ASSERT_EQUAL_HEX( p_data , p_setup->next.address); TEST_ASSERT_EQUAL_HEX( p_status , p_data->next.address ); TEST_ASSERT_TRUE( p_status->next.terminate ); verify_qtd(p_setup, (uint8_t*) &request_get_dev_desc, 8); } //--------------------------------------------------------------------+ // Normal Control //--------------------------------------------------------------------+ void test_control_xfer_get(void) { //------------- Code Under TEST -------------// TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_get_dev_desc, xfer_data) ); TEST_ASSERT_EQUAL_HEX( p_setup, p_control_qhd->qtd_overlay.next.address ); TEST_ASSERT_EQUAL_HEX( p_setup , p_control_qhd->p_qtd_list_head); TEST_ASSERT_EQUAL_HEX( p_data , p_setup->next.address); TEST_ASSERT_EQUAL_HEX( p_status , p_data->next.address ); TEST_ASSERT_TRUE( p_status->next.terminate ); //------------- SETUP -------------// verify_qtd(p_setup, (uint8_t*) &request_get_dev_desc, 8); TEST_ASSERT_FALSE(p_setup->int_on_complete); TEST_ASSERT_FALSE(p_setup->data_toggle); TEST_ASSERT_EQUAL(EHCI_PID_SETUP, p_setup->pid); //------------- DATA -------------// verify_qtd(p_data, xfer_data, request_get_dev_desc.wLength); TEST_ASSERT_FALSE(p_data->int_on_complete); TEST_ASSERT_TRUE(p_data->data_toggle); TEST_ASSERT_EQUAL(EHCI_PID_IN, p_data->pid); //------------- STATUS -------------// verify_qtd(p_status, NULL, 0); TEST_ASSERT_TRUE(p_status->int_on_complete); TEST_ASSERT_TRUE(p_status->data_toggle); TEST_ASSERT_EQUAL(EHCI_PID_OUT, p_status->pid); TEST_ASSERT_TRUE(p_status->next.terminate); TEST_ASSERT_EQUAL_HEX(p_setup, p_control_qhd->p_qtd_list_head); TEST_ASSERT_EQUAL_HEX(p_status, p_control_qhd->p_qtd_list_tail); } void test_control_xfer_set(void) { //------------- Code Under TEST -------------// TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_set_dev_addr, xfer_data) ); TEST_ASSERT_EQUAL_HEX( p_setup, p_control_qhd->qtd_overlay.next.address ); TEST_ASSERT_EQUAL_HEX( p_setup , p_control_qhd->p_qtd_list_head); TEST_ASSERT_EQUAL_HEX( p_status , p_setup->next.address ); TEST_ASSERT_TRUE( p_status->next.terminate ); //------------- STATUS -------------// verify_qtd(p_status, NULL, 0); TEST_ASSERT_TRUE(p_status->int_on_complete); TEST_ASSERT_TRUE(p_status->data_toggle); TEST_ASSERT_EQUAL(EHCI_PID_IN, p_status->pid); TEST_ASSERT_TRUE(p_status->next.terminate); TEST_ASSERT_EQUAL_HEX(p_setup, p_control_qhd->p_qtd_list_head); TEST_ASSERT_EQUAL_HEX(p_status, p_control_qhd->p_qtd_list_tail); } void test_control_xfer_complete_isr(void) { TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_get_dev_desc, xfer_data) ); hcd_event_xfer_complete_Expect(((pipe_handle_t){.dev_addr = dev_addr}), 0, XFER_RESULT_SUCCESS, 18); //------------- Code Under TEST -------------// ehci_controller_run(hostid); TEST_ASSERT_EQUAL(0, p_control_qhd->total_xferred_bytes); TEST_ASSERT_NULL(p_control_qhd->p_qtd_list_head); TEST_ASSERT_NULL(p_control_qhd->p_qtd_list_tail); TEST_ASSERT_FALSE(p_setup->used); TEST_ASSERT_FALSE(p_data->used); TEST_ASSERT_FALSE(p_status->used); } void test_control_xfer_error_isr(void) { TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_get_dev_desc, xfer_data) ); hcd_event_xfer_complete_Expect(((pipe_handle_t){.dev_addr = dev_addr}), 0, XFER_RESULT_FAILED, 0); //------------- Code Under TEST -------------// ehci_controller_run_error(hostid); TEST_ASSERT_EQUAL(0, p_control_qhd->total_xferred_bytes); TEST_ASSERT_NULL( p_control_qhd->p_qtd_list_head ); TEST_ASSERT_NULL( p_control_qhd->p_qtd_list_tail ); TEST_ASSERT_TRUE( p_control_qhd->qtd_overlay.next.terminate); TEST_ASSERT_TRUE( p_control_qhd->qtd_overlay.alternate.terminate); TEST_ASSERT_FALSE( p_control_qhd->qtd_overlay.halted); } void test_control_xfer_error_stall(void) { TEST_ASSERT( hcd_pipe_control_xfer(dev_addr, &request_get_dev_desc, xfer_data) ); hcd_event_xfer_complete_Expect(((pipe_handle_t){.dev_addr = dev_addr}), 0, XFER_RESULT_STALLED, 0); //------------- Code Under TEST -------------// ehci_controller_run_stall(hostid); TEST_ASSERT_EQUAL(0, p_control_qhd->total_xferred_bytes); TEST_ASSERT_NULL( p_control_qhd->p_qtd_list_head ); TEST_ASSERT_NULL( p_control_qhd->p_qtd_list_tail ); TEST_ASSERT_TRUE( p_control_qhd->qtd_overlay.next.terminate); TEST_ASSERT_TRUE( p_control_qhd->qtd_overlay.alternate.terminate); TEST_ASSERT_FALSE( p_control_qhd->qtd_overlay.halted); TEST_ASSERT_FALSE( p_setup->used ); TEST_ASSERT_FALSE( p_data->used ); TEST_ASSERT_FALSE( p_status->used ); }
934070.c
/*- * Copyright (c) 1989, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)slcompress.c 8.2 (Berkeley) 4/16/94 * $Id: slcompress.c,v 1.7.2.2 1998/06/23 21:33:22 peter Exp $ */ /* * Routines to compress and uncompess tcp packets (for transmission * over low speed serial lines. * * Van Jacobson ([email protected]), Dec 31, 1989: * - Initial distribution. * */ #include <sys/param.h> #include <sys/mbuf.h> #include <sys/systm.h> #include <netinet/in.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #include <netinet/tcp.h> #include <net/slcompress.h> #ifndef SL_NO_STATS #define INCR(counter) ++comp->counter; #else #define INCR(counter) #endif #define BCMP(p1, p2, n) bcmp((char *)(p1), (char *)(p2), (int)(n)) #define BCOPY(p1, p2, n) bcopy((char *)(p1), (char *)(p2), (int)(n)) #ifndef KERNEL #define ovbcopy bcopy #endif void sl_compress_init(comp, max_state) struct slcompress *comp; int max_state; { register u_int i; register struct cstate *tstate = comp->tstate; if (max_state == -1) { max_state = MAX_STATES - 1; bzero((char *)comp, sizeof(*comp)); } else { /* Don't reset statistics */ bzero((char *)comp->tstate, sizeof(comp->tstate)); bzero((char *)comp->rstate, sizeof(comp->rstate)); } for (i = max_state; i > 0; --i) { tstate[i].cs_id = i; tstate[i].cs_next = &tstate[i - 1]; } tstate[0].cs_next = &tstate[max_state]; tstate[0].cs_id = 0; comp->last_cs = &tstate[0]; comp->last_recv = 255; comp->last_xmit = 255; comp->flags = SLF_TOSS; } /* ENCODE encodes a number that is known to be non-zero. ENCODEZ * checks for zero (since zero has to be encoded in the long, 3 byte * form). */ #define ENCODE(n) { \ if ((u_int16_t)(n) >= 256) { \ *cp++ = 0; \ cp[1] = (n); \ cp[0] = (n) >> 8; \ cp += 2; \ } else { \ *cp++ = (n); \ } \ } #define ENCODEZ(n) { \ if ((u_int16_t)(n) >= 256 || (u_int16_t)(n) == 0) { \ *cp++ = 0; \ cp[1] = (n); \ cp[0] = (n) >> 8; \ cp += 2; \ } else { \ *cp++ = (n); \ } \ } #define DECODEL(f) { \ if (*cp == 0) {\ (f) = htonl(ntohl(f) + ((cp[1] << 8) | cp[2])); \ cp += 3; \ } else { \ (f) = htonl(ntohl(f) + (u_int32_t)*cp++); \ } \ } #define DECODES(f) { \ if (*cp == 0) {\ (f) = htons(ntohs(f) + ((cp[1] << 8) | cp[2])); \ cp += 3; \ } else { \ (f) = htons(ntohs(f) + (u_int32_t)*cp++); \ } \ } #define DECODEU(f) { \ if (*cp == 0) {\ (f) = htons((cp[1] << 8) | cp[2]); \ cp += 3; \ } else { \ (f) = htons((u_int32_t)*cp++); \ } \ } u_int sl_compress_tcp(m, ip, comp, compress_cid) struct mbuf *m; register struct ip *ip; struct slcompress *comp; int compress_cid; { register struct cstate *cs = comp->last_cs->cs_next; register u_int hlen = ip->ip_hl; register struct tcphdr *oth; register struct tcphdr *th; register u_int deltaS, deltaA; register u_int changes = 0; u_char new_seq[16]; register u_char *cp = new_seq; /* * Bail if this is an IP fragment or if the TCP packet isn't * `compressible' (i.e., ACK isn't set or some other control bit is * set). (We assume that the caller has already made sure the * packet is IP proto TCP). */ if ((ip->ip_off & htons(0x3fff)) || m->m_len < 40) return (TYPE_IP); th = (struct tcphdr *)&((int32_t *)ip)[hlen]; if ((th->th_flags & (TH_SYN|TH_FIN|TH_RST|TH_ACK)) != TH_ACK) return (TYPE_IP); /* * Packet is compressible -- we're going to send either a * COMPRESSED_TCP or UNCOMPRESSED_TCP packet. Either way we need * to locate (or create) the connection state. Special case the * most recently used connection since it's most likely to be used * again & we don't have to do any reordering if it's used. */ INCR(sls_packets) if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr || ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr || *(int32_t *)th != ((int32_t *)&cs->cs_ip)[cs->cs_ip.ip_hl]) { /* * Wasn't the first -- search for it. * * States are kept in a circularly linked list with * last_cs pointing to the end of the list. The * list is kept in lru order by moving a state to the * head of the list whenever it is referenced. Since * the list is short and, empirically, the connection * we want is almost always near the front, we locate * states via linear search. If we don't find a state * for the datagram, the oldest state is (re-)used. */ register struct cstate *lcs; register struct cstate *lastcs = comp->last_cs; do { lcs = cs; cs = cs->cs_next; INCR(sls_searches) if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr && ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr && *(int32_t *)th == ((int32_t *)&cs->cs_ip)[cs->cs_ip.ip_hl]) goto found; } while (cs != lastcs); /* * Didn't find it -- re-use oldest cstate. Send an * uncompressed packet that tells the other side what * connection number we're using for this conversation. * Note that since the state list is circular, the oldest * state points to the newest and we only need to set * last_cs to update the lru linkage. */ INCR(sls_misses) comp->last_cs = lcs; hlen += th->th_off; hlen <<= 2; if (hlen > m->m_len) return TYPE_IP; goto uncompressed; found: /* * Found it -- move to the front on the connection list. */ if (cs == lastcs) comp->last_cs = lcs; else { lcs->cs_next = cs->cs_next; cs->cs_next = lastcs->cs_next; lastcs->cs_next = cs; } } /* * Make sure that only what we expect to change changed. The first * line of the `if' checks the IP protocol version, header length & * type of service. The 2nd line checks the "Don't fragment" bit. * The 3rd line checks the time-to-live and protocol (the protocol * check is unnecessary but costless). The 4th line checks the TCP * header length. The 5th line checks IP options, if any. The 6th * line checks TCP options, if any. If any of these things are * different between the previous & current datagram, we send the * current datagram `uncompressed'. */ oth = (struct tcphdr *)&((int32_t *)&cs->cs_ip)[hlen]; deltaS = hlen; hlen += th->th_off; hlen <<= 2; if (hlen > m->m_len) return TYPE_IP; if (((u_int16_t *)ip)[0] != ((u_int16_t *)&cs->cs_ip)[0] || ((u_int16_t *)ip)[3] != ((u_int16_t *)&cs->cs_ip)[3] || ((u_int16_t *)ip)[4] != ((u_int16_t *)&cs->cs_ip)[4] || th->th_off != oth->th_off || (deltaS > 5 && BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) || (th->th_off > 5 && BCMP(th + 1, oth + 1, (th->th_off - 5) << 2))) goto uncompressed; /* * Figure out which of the changing fields changed. The * receiver expects changes in the order: urgent, window, * ack, seq (the order minimizes the number of temporaries * needed in this section of code). */ if (th->th_flags & TH_URG) { deltaS = ntohs(th->th_urp); ENCODEZ(deltaS); changes |= NEW_U; } else if (th->th_urp != oth->th_urp) /* argh! URG not set but urp changed -- a sensible * implementation should never do this but RFC793 * doesn't prohibit the change so we have to deal * with it. */ goto uncompressed; deltaS = (u_int16_t)(ntohs(th->th_win) - ntohs(oth->th_win)); if (deltaS) { ENCODE(deltaS); changes |= NEW_W; } deltaA = ntohl(th->th_ack) - ntohl(oth->th_ack); if (deltaA) { if (deltaA > 0xffff) goto uncompressed; ENCODE(deltaA); changes |= NEW_A; } deltaS = ntohl(th->th_seq) - ntohl(oth->th_seq); if (deltaS) { if (deltaS > 0xffff) goto uncompressed; ENCODE(deltaS); changes |= NEW_S; } switch(changes) { case 0: /* * Nothing changed. If this packet contains data and the * last one didn't, this is probably a data packet following * an ack (normal on an interactive connection) and we send * it compressed. Otherwise it's probably a retransmit, * retransmitted ack or window probe. Send it uncompressed * in case the other side missed the compressed version. */ if (ip->ip_len != cs->cs_ip.ip_len && ntohs(cs->cs_ip.ip_len) == hlen) break; /* (fall through) */ case SPECIAL_I: case SPECIAL_D: /* * actual changes match one of our special case encodings -- * send packet uncompressed. */ goto uncompressed; case NEW_S|NEW_A: if (deltaS == deltaA && deltaS == ntohs(cs->cs_ip.ip_len) - hlen) { /* special case for echoed terminal traffic */ changes = SPECIAL_I; cp = new_seq; } break; case NEW_S: if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) { /* special case for data xfer */ changes = SPECIAL_D; cp = new_seq; } break; } deltaS = ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id); if (deltaS != 1) { ENCODEZ(deltaS); changes |= NEW_I; } if (th->th_flags & TH_PUSH) changes |= TCP_PUSH_BIT; /* * Grab the cksum before we overwrite it below. Then update our * state with this packet's header. */ deltaA = ntohs(th->th_sum); BCOPY(ip, &cs->cs_ip, hlen); /* * We want to use the original packet as our compressed packet. * (cp - new_seq) is the number of bytes we need for compressed * sequence numbers. In addition we need one byte for the change * mask, one for the connection id and two for the tcp checksum. * So, (cp - new_seq) + 4 bytes of header are needed. hlen is how * many bytes of the original packet to toss so subtract the two to * get the new packet size. */ deltaS = cp - new_seq; cp = (u_char *)ip; if (compress_cid == 0 || comp->last_xmit != cs->cs_id) { comp->last_xmit = cs->cs_id; hlen -= deltaS + 4; cp += hlen; *cp++ = changes | NEW_C; *cp++ = cs->cs_id; } else { hlen -= deltaS + 3; cp += hlen; *cp++ = changes; } m->m_len -= hlen; m->m_data += hlen; *cp++ = deltaA >> 8; *cp++ = deltaA; BCOPY(new_seq, cp, deltaS); INCR(sls_compressed) return (TYPE_COMPRESSED_TCP); /* * Update connection state cs & send uncompressed packet ('uncompressed' * means a regular ip/tcp packet but with the 'conversation id' we hope * to use on future compressed packets in the protocol field). */ uncompressed: BCOPY(ip, &cs->cs_ip, hlen); ip->ip_p = cs->cs_id; comp->last_xmit = cs->cs_id; return (TYPE_UNCOMPRESSED_TCP); } int sl_uncompress_tcp(bufp, len, type, comp) u_char **bufp; int len; u_int type; struct slcompress *comp; { u_char *hdr, *cp; int hlen, vjlen; cp = bufp? *bufp: NULL; vjlen = sl_uncompress_tcp_core(cp, len, len, type, comp, &hdr, &hlen); if (vjlen < 0) return (0); /* error */ if (vjlen == 0) return (len); /* was uncompressed already */ cp += vjlen; len -= vjlen; /* * At this point, cp points to the first byte of data in the * packet. If we're not aligned on a 4-byte boundary, copy the * data down so the ip & tcp headers will be aligned. Then back up * cp by the tcp/ip header length to make room for the reconstructed * header (we assume the packet we were handed has enough space to * prepend 128 bytes of header). */ if ((long)cp & 3) { if (len > 0) (void) ovbcopy(cp, (caddr_t)((long)cp &~ 3), len); cp = (u_char *)((long)cp &~ 3); } cp -= hlen; len += hlen; BCOPY(hdr, cp, hlen); *bufp = cp; return (len); } /* * Uncompress a packet of total length total_len. The first buflen * bytes are at buf; this must include the entire (compressed or * uncompressed) TCP/IP header. This procedure returns the length * of the VJ header, with a pointer to the uncompressed IP header * in *hdrp and its length in *hlenp. */ int sl_uncompress_tcp_core(buf, buflen, total_len, type, comp, hdrp, hlenp) u_char *buf; int buflen, total_len; u_int type; struct slcompress *comp; u_char **hdrp; u_int *hlenp; { register u_char *cp; register u_int hlen, changes; register struct tcphdr *th; register struct cstate *cs; register struct ip *ip; register u_int16_t *bp; register u_int vjlen; switch (type) { case TYPE_UNCOMPRESSED_TCP: ip = (struct ip *) buf; if (ip->ip_p >= MAX_STATES) goto bad; cs = &comp->rstate[comp->last_recv = ip->ip_p]; comp->flags &=~ SLF_TOSS; ip->ip_p = IPPROTO_TCP; /* * Calculate the size of the TCP/IP header and make sure that * we don't overflow the space we have available for it. */ hlen = ip->ip_hl << 2; if (hlen + sizeof(struct tcphdr) > buflen) goto bad; hlen += ((struct tcphdr *)&((char *)ip)[hlen])->th_off << 2; if (hlen > MAX_HDR || hlen > buflen) goto bad; BCOPY(ip, &cs->cs_ip, hlen); cs->cs_hlen = hlen; INCR(sls_uncompressedin) *hdrp = (u_char *) &cs->cs_ip; *hlenp = hlen; return (0); default: goto bad; case TYPE_COMPRESSED_TCP: break; } /* We've got a compressed packet. */ INCR(sls_compressedin) cp = buf; changes = *cp++; if (changes & NEW_C) { /* Make sure the state index is in range, then grab the state. * If we have a good state index, clear the 'discard' flag. */ if (*cp >= MAX_STATES) goto bad; comp->flags &=~ SLF_TOSS; comp->last_recv = *cp++; } else { /* this packet has an implicit state index. If we've * had a line error since the last time we got an * explicit state index, we have to toss the packet. */ if (comp->flags & SLF_TOSS) { INCR(sls_tossed) return (-1); } } cs = &comp->rstate[comp->last_recv]; hlen = cs->cs_ip.ip_hl << 2; th = (struct tcphdr *)&((u_char *)&cs->cs_ip)[hlen]; th->th_sum = htons((*cp << 8) | cp[1]); cp += 2; if (changes & TCP_PUSH_BIT) th->th_flags |= TH_PUSH; else th->th_flags &=~ TH_PUSH; switch (changes & SPECIALS_MASK) { case SPECIAL_I: { register u_int i = ntohs(cs->cs_ip.ip_len) - cs->cs_hlen; th->th_ack = htonl(ntohl(th->th_ack) + i); th->th_seq = htonl(ntohl(th->th_seq) + i); } break; case SPECIAL_D: th->th_seq = htonl(ntohl(th->th_seq) + ntohs(cs->cs_ip.ip_len) - cs->cs_hlen); break; default: if (changes & NEW_U) { th->th_flags |= TH_URG; DECODEU(th->th_urp) } else th->th_flags &=~ TH_URG; if (changes & NEW_W) DECODES(th->th_win) if (changes & NEW_A) DECODEL(th->th_ack) if (changes & NEW_S) DECODEL(th->th_seq) break; } if (changes & NEW_I) { DECODES(cs->cs_ip.ip_id) } else cs->cs_ip.ip_id = htons(ntohs(cs->cs_ip.ip_id) + 1); /* * At this point, cp points to the first byte of data in the * packet. Fill in the IP total length and update the IP * header checksum. */ vjlen = cp - buf; buflen -= vjlen; if (buflen < 0) /* we must have dropped some characters (crc should detect * this but the old slip framing won't) */ goto bad; total_len += cs->cs_hlen - vjlen; cs->cs_ip.ip_len = htons(total_len); /* recompute the ip header checksum */ bp = (u_int16_t *) &cs->cs_ip; cs->cs_ip.ip_sum = 0; for (changes = 0; hlen > 0; hlen -= 2) changes += *bp++; changes = (changes & 0xffff) + (changes >> 16); changes = (changes & 0xffff) + (changes >> 16); cs->cs_ip.ip_sum = ~ changes; *hdrp = (u_char *) &cs->cs_ip; *hlenp = cs->cs_hlen; return vjlen; bad: comp->flags |= SLF_TOSS; INCR(sls_errorin) return (-1); }
141913.c
/* * Copyright (c) 2014 VMware, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "precomp.h" #include "NetProto.h" #include "Util.h" #include "Jhash.h" #include "Flow.h" #include "PacketParser.h" #include "Datapath.h" #include "Geneve.h" #ifdef OVS_DBG_MOD #undef OVS_DBG_MOD #endif #define OVS_DBG_MOD OVS_DBG_FLOW #include "Debug.h" #pragma warning( push ) #pragma warning( disable:4127 ) extern POVS_SWITCH_CONTEXT gOvsSwitchContext; extern UINT64 ovsTimeIncrementPerTick; static NTSTATUS ReportFlowInfo(OvsFlow *flow, UINT32 getFlags, OvsFlowInfo *info); static NTSTATUS HandleFlowPut(OvsFlowPut *put, OVS_DATAPATH *datapath, struct OvsFlowStats *stats); static NTSTATUS OvsPrepareFlow(OvsFlow **flow, const OvsFlowPut *put, UINT64 hash); static VOID RemoveFlow(OVS_DATAPATH *datapath, OvsFlow **flow); static VOID DeleteAllFlows(OVS_DATAPATH *datapath); static NTSTATUS AddFlow(OVS_DATAPATH *datapath, OvsFlow *flow); static VOID FreeFlow(OvsFlow *flow); static VOID __inline *GetStartAddrNBL(const NET_BUFFER_LIST *_pNB); static NTSTATUS _MapNlToFlowPut(POVS_MESSAGE msgIn, PNL_ATTR keyAttr, PNL_ATTR actionAttr, PNL_ATTR flowAttrClear, OvsFlowPut *mappedFlow); static VOID _MapKeyAttrToFlowPut(PNL_ATTR *keyAttrs, PNL_ATTR *tunnelAttrs, OvsFlowKey *destKey); static VOID _MapNlToFlowPutFlags(PGENL_MSG_HDR genlMsgHdr, PNL_ATTR flowAttrClear, OvsFlowPut *mappedFlow); static NTSTATUS _FlowNlGetCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen); static NTSTATUS _FlowNlDumpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen); static NTSTATUS _MapFlowInfoToNl(PNL_BUFFER nlBuf, OvsFlowInfo *flowInfo); static NTSTATUS _MapFlowStatsToNlStats(PNL_BUFFER nlBuf, OvsFlowStats *flowStats); static NTSTATUS _MapFlowActionToNlAction(PNL_BUFFER nlBuf, uint32_t actionsLen, PNL_ATTR actions); static NTSTATUS _MapFlowIpv4KeyToNlKey(PNL_BUFFER nlBuf, IpKey *ipv4FlowPutKey); static NTSTATUS _MapFlowIpv6KeyToNlKey(PNL_BUFFER nlBuf, Ipv6Key *ipv6FlowPutKey, Icmp6Key *ipv6FlowPutIcmpKey); static NTSTATUS _MapFlowArpKeyToNlKey(PNL_BUFFER nlBuf, ArpKey *arpFlowPutKey); static NTSTATUS _MapFlowMplsKeyToNlKey(PNL_BUFFER nlBuf, MplsKey *mplsFlowPutKey); static NTSTATUS OvsDoDumpFlows(OvsFlowDumpInput *dumpInput, OvsFlowDumpOutput *dumpOutput, UINT32 *replyLen); static NTSTATUS OvsProbeSupportedFeature(POVS_MESSAGE msgIn, PNL_ATTR keyAttr); static UINT16 OvsGetFlowL2Offset(const OvsIPv4TunnelKey *tunKey); #define OVS_FLOW_TABLE_SIZE 2048 #define OVS_FLOW_TABLE_MASK (OVS_FLOW_TABLE_SIZE -1) #define HASH_BUCKET(hash) ((hash) & OVS_FLOW_TABLE_MASK) /* Flow family related netlink policies */ /* For Parsing attributes in FLOW_* commands */ const NL_POLICY nlFlowPolicy[] = { [OVS_FLOW_ATTR_KEY] = {.type = NL_A_NESTED, .optional = FALSE}, [OVS_FLOW_ATTR_MASK] = {.type = NL_A_NESTED, .optional = TRUE}, [OVS_FLOW_ATTR_ACTIONS] = {.type = NL_A_NESTED, .optional = TRUE}, [OVS_FLOW_ATTR_STATS] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_flow_stats), .maxLen = sizeof(struct ovs_flow_stats), .optional = TRUE}, [OVS_FLOW_ATTR_TCP_FLAGS] = {NL_A_U8, .optional = TRUE}, [OVS_FLOW_ATTR_USED] = {NL_A_U64, .optional = TRUE}, [OVS_FLOW_ATTR_PROBE] = {.type = NL_A_FLAG, .optional = TRUE} }; /* For Parsing nested OVS_FLOW_ATTR_KEY attributes. */ const NL_POLICY nlFlowKeyPolicy[] = { [OVS_KEY_ATTR_ENCAP] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_KEY_ATTR_PRIORITY] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_IN_PORT] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_ETHERNET] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_ethernet), .maxLen = sizeof(struct ovs_key_ethernet), .optional = TRUE}, [OVS_KEY_ATTR_VLAN] = {.type = NL_A_UNSPEC, .minLen = 2, .maxLen = 2, .optional = TRUE}, [OVS_KEY_ATTR_ETHERTYPE] = {.type = NL_A_UNSPEC, .minLen = 2, .maxLen = 2, .optional = TRUE}, [OVS_KEY_ATTR_IPV4] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_ipv4), .maxLen = sizeof(struct ovs_key_ipv4), .optional = TRUE}, [OVS_KEY_ATTR_IPV6] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_ipv6), .maxLen = sizeof(struct ovs_key_ipv6), .optional = TRUE}, [OVS_KEY_ATTR_TCP] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_tcp), .maxLen = sizeof(struct ovs_key_tcp), .optional = TRUE}, [OVS_KEY_ATTR_UDP] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_udp), .maxLen = sizeof(struct ovs_key_udp), .optional = TRUE}, [OVS_KEY_ATTR_ICMP] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_icmp), .maxLen = sizeof(struct ovs_key_icmp), .optional = TRUE}, [OVS_KEY_ATTR_ICMPV6] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_icmpv6), .maxLen = sizeof(struct ovs_key_icmpv6), .optional = TRUE}, [OVS_KEY_ATTR_ARP] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_arp), .maxLen = sizeof(struct ovs_key_arp), .optional = TRUE}, [OVS_KEY_ATTR_ND] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_nd), .maxLen = sizeof(struct ovs_key_nd), .optional = TRUE}, [OVS_KEY_ATTR_SKB_MARK] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_TUNNEL] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_KEY_ATTR_SCTP] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_sctp), .maxLen = sizeof(struct ovs_key_sctp), .optional = TRUE}, [OVS_KEY_ATTR_TCP_FLAGS] = {.type = NL_A_UNSPEC, .minLen = 2, .maxLen = 2, .optional = TRUE}, [OVS_KEY_ATTR_DP_HASH] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_RECIRC_ID] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_MPLS] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_KEY_ATTR_CT_STATE] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_CT_ZONE] = {.type = NL_A_UNSPEC, .minLen = 2, .maxLen = 2, .optional = TRUE}, [OVS_KEY_ATTR_CT_MARK] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_KEY_ATTR_CT_LABELS] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_ct_labels), .maxLen = sizeof(struct ovs_key_ct_labels), .optional = TRUE}, [OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_key_ct_tuple_ipv4), .maxLen = sizeof(struct ovs_key_ct_tuple_ipv4), .optional = TRUE} }; const UINT32 nlFlowKeyPolicyLen = ARRAY_SIZE(nlFlowKeyPolicy); /* For Parsing nested OVS_KEY_ATTR_TUNNEL attributes */ const NL_POLICY nlFlowTunnelKeyPolicy[] = { [OVS_TUNNEL_KEY_ATTR_ID] = {.type = NL_A_UNSPEC, .minLen = 8, .maxLen = 8, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_IPV4_SRC] = {.type = NL_A_UNSPEC, .minLen = 4, .maxLen = 4, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_IPV4_DST] = {.type = NL_A_UNSPEC, .minLen = 4 , .maxLen = 4, .optional = FALSE}, [OVS_TUNNEL_KEY_ATTR_TOS] = {.type = NL_A_UNSPEC, .minLen = 1, .maxLen = 1, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_TTL] = {.type = NL_A_UNSPEC, .minLen = 1, .maxLen = 1, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT] = {.type = NL_A_UNSPEC, .minLen = 0, .maxLen = 0, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_CSUM] = {.type = NL_A_UNSPEC, .minLen = 0, .maxLen = 0, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_OAM] = {.type = NL_A_UNSPEC, .minLen = 0, .maxLen = 0, .optional = TRUE}, [OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS] = {.type = NL_A_VAR_LEN, .optional = TRUE} }; const UINT32 nlFlowTunnelKeyPolicyLen = ARRAY_SIZE(nlFlowTunnelKeyPolicy); /* For Parsing nested OVS_FLOW_ATTR_ACTIONS attributes */ const NL_POLICY nlFlowActionPolicy[] = { [OVS_ACTION_ATTR_OUTPUT] = {.type = NL_A_UNSPEC, .minLen = sizeof(UINT32), .maxLen = sizeof(UINT32), .optional = TRUE}, [OVS_ACTION_ATTR_USERSPACE] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_ACTION_ATTR_PUSH_VLAN] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_action_push_vlan), .maxLen = sizeof(struct ovs_action_push_vlan), .optional = TRUE}, [OVS_ACTION_ATTR_POP_VLAN] = {.type = NL_A_UNSPEC, .optional = TRUE}, [OVS_ACTION_ATTR_PUSH_MPLS] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_action_push_mpls), .maxLen = sizeof(struct ovs_action_push_mpls), .optional = TRUE}, [OVS_ACTION_ATTR_POP_MPLS] = {.type = NL_A_UNSPEC, .minLen = sizeof(UINT16), .maxLen = sizeof(UINT16), .optional = TRUE}, [OVS_ACTION_ATTR_RECIRC] = {.type = NL_A_UNSPEC, .minLen = sizeof(UINT32), .maxLen = sizeof(UINT32), .optional = TRUE}, [OVS_ACTION_ATTR_HASH] = {.type = NL_A_UNSPEC, .minLen = sizeof(struct ovs_action_hash), .maxLen = sizeof(struct ovs_action_hash), .optional = TRUE}, [OVS_ACTION_ATTR_SET] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_ACTION_ATTR_SAMPLE] = {.type = NL_A_VAR_LEN, .optional = TRUE}, [OVS_ACTION_ATTR_CT] = {.type = NL_A_VAR_LEN, .optional = TRUE} }; /* *---------------------------------------------------------------------------- * Netlink interface for flow commands. *---------------------------------------------------------------------------- */ /* *---------------------------------------------------------------------------- * OvsFlowNewCmdHandler -- * Handler for OVS_FLOW_CMD_NEW/SET/DEL command. * It also handles FLUSH case (DEL w/o any key in input) *---------------------------------------------------------------------------- */ NTSTATUS OvsFlowNlCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen) { NTSTATUS rc = STATUS_SUCCESS; BOOLEAN ok = FALSE; POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer; POVS_MESSAGE msgOut = (POVS_MESSAGE)usrParamsCtx->outputBuffer; PNL_MSG_HDR nlMsgHdr = &(msgIn->nlMsg); PGENL_MSG_HDR genlMsgHdr = &(msgIn->genlMsg); POVS_HDR ovsHdr = &(msgIn->ovsHdr); PNL_ATTR flowAttrs[__OVS_FLOW_ATTR_MAX]; UINT32 attrOffset = NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN; OvsFlowPut mappedFlow; OvsFlowStats stats; struct ovs_flow_stats replyStats; NL_ERROR nlError = NL_ERROR_SUCCESS; NL_BUFFER nlBuf; RtlZeroMemory(&mappedFlow, sizeof(OvsFlowPut)); RtlZeroMemory(&stats, sizeof(stats)); RtlZeroMemory(&replyStats, sizeof(replyStats)); if (!(usrParamsCtx->outputBuffer)) { /* No output buffer */ rc = STATUS_INVALID_BUFFER_SIZE; goto done; } /* FLOW_DEL command w/o any key input is a flush case. If we don't have any attr, we treat this as a flush command*/ if ((genlMsgHdr->cmd == OVS_FLOW_CMD_DEL) && (!NlMsgAttrsLen(nlMsgHdr))) { rc = OvsFlushFlowIoctl(ovsHdr->dp_ifindex); if (rc == STATUS_SUCCESS) { /* XXX: refactor this code. */ /* So far so good. Prepare the reply for userspace */ NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength); /* Prepare nl Msg headers */ ok = NlFillOvsMsg(&nlBuf, nlMsgHdr->nlmsgType, 0, nlMsgHdr->nlmsgSeq, nlMsgHdr->nlmsgPid, genlMsgHdr->cmd, OVS_FLOW_VERSION, ovsHdr->dp_ifindex); if (ok) { *replyLen = msgOut->nlMsg.nlmsgLen; } else { rc = STATUS_INVALID_BUFFER_SIZE; } } goto done; } /* Get all the top level Flow attributes */ if ((NlAttrParse(nlMsgHdr, attrOffset, NlMsgAttrsLen(nlMsgHdr), nlFlowPolicy, ARRAY_SIZE(nlFlowPolicy), flowAttrs, ARRAY_SIZE(flowAttrs))) != TRUE) { OVS_LOG_ERROR("Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } if (flowAttrs[OVS_FLOW_ATTR_PROBE]) { rc = OvsProbeSupportedFeature(msgIn, flowAttrs[OVS_FLOW_ATTR_KEY]); if (rc != STATUS_SUCCESS) { nlError = NlMapStatusToNlErr(rc); goto done; } } if ((rc = _MapNlToFlowPut(msgIn, flowAttrs[OVS_FLOW_ATTR_KEY], flowAttrs[OVS_FLOW_ATTR_ACTIONS], flowAttrs[OVS_FLOW_ATTR_CLEAR], &mappedFlow)) != STATUS_SUCCESS) { OVS_LOG_ERROR("Conversion to OvsFlowPut failed"); goto done; } rc = OvsPutFlowIoctl(&mappedFlow, sizeof (struct OvsFlowPut), &stats); if (rc != STATUS_SUCCESS) { OVS_LOG_ERROR("OvsPutFlowIoctl failed."); /* * Report back to the userspace the flow could not be modified, * created or deleted */ nlError = NL_ERROR_NOENT; if (rc == STATUS_DUPLICATE_NAME) { nlError = NL_ERROR_EXIST; } goto done; } replyStats.n_packets = stats.packetCount; replyStats.n_bytes = stats.byteCount; /* So far so good. Prepare the reply for userspace */ NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength); /* Prepare nl Msg headers */ ok = NlFillOvsMsg(&nlBuf, nlMsgHdr->nlmsgType, 0, nlMsgHdr->nlmsgSeq, nlMsgHdr->nlmsgPid, genlMsgHdr->cmd, OVS_FLOW_VERSION, ovsHdr->dp_ifindex); if (!ok) { rc = STATUS_INVALID_BUFFER_SIZE; goto done; } else { rc = STATUS_SUCCESS; } /* Append OVS_FLOW_ATTR_KEY attribute. This is need i.e. for flow delete*/ if (!NlMsgPutNested(&nlBuf, OVS_FLOW_ATTR_KEY, NlAttrData(flowAttrs[OVS_FLOW_ATTR_KEY]), NlAttrGetSize(flowAttrs[OVS_FLOW_ATTR_KEY]))) { OVS_LOG_ERROR("Adding OVS_FLOW_ATTR_KEY attribute failed."); rc = STATUS_INVALID_BUFFER_SIZE; goto done; } /* Append OVS_FLOW_ATTR_STATS attribute */ if (!NlMsgPutTailUnspec(&nlBuf, OVS_FLOW_ATTR_STATS, (PCHAR)(&replyStats), sizeof(replyStats))) { OVS_LOG_ERROR("Adding OVS_FLOW_ATTR_STATS attribute failed."); rc = STATUS_INVALID_BUFFER_SIZE; goto done; } msgOut->nlMsg.nlmsgLen = NLMSG_ALIGN(NlBufSize(&nlBuf)); *replyLen = msgOut->nlMsg.nlmsgLen; done: if (nlError != NL_ERROR_SUCCESS) { POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR) usrParamsCtx->outputBuffer; ASSERT(msgError); NlBuildErrorMsg(msgIn, msgError, nlError, replyLen); ASSERT(*replyLen != 0); rc = STATUS_SUCCESS; } return rc; } /* *---------------------------------------------------------------------------- * OvsFlowNlGetCmdHandler -- * Handler for OVS_FLOW_CMD_GET/DUMP commands. *---------------------------------------------------------------------------- */ NTSTATUS OvsFlowNlGetCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen) { NTSTATUS status = STATUS_SUCCESS; if (usrParamsCtx->devOp == OVS_TRANSACTION_DEV_OP) { status = _FlowNlGetCmdHandler(usrParamsCtx, replyLen); } else { status = _FlowNlDumpCmdHandler(usrParamsCtx, replyLen); } return status; } /* *---------------------------------------------------------------------------- * _FlowNlGetCmdHandler -- * Handler for OVS_FLOW_CMD_GET command. *---------------------------------------------------------------------------- */ NTSTATUS _FlowNlGetCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen) { NTSTATUS rc = STATUS_SUCCESS; POVS_MESSAGE msgIn = (POVS_MESSAGE)usrParamsCtx->inputBuffer; PNL_MSG_HDR nlMsgHdr = &(msgIn->nlMsg); POVS_HDR ovsHdr = &(msgIn->ovsHdr); PNL_MSG_HDR nlMsgOutHdr = NULL; UINT32 attrOffset = NLMSG_HDRLEN + GENL_HDRLEN + OVS_HDRLEN; PNL_ATTR nlAttrs[__OVS_FLOW_ATTR_MAX]; OvsFlowGetInput getInput; OvsFlowGetOutput getOutput; NL_BUFFER nlBuf; PNL_ATTR keyAttrs[__OVS_KEY_ATTR_MAX]; PNL_ATTR tunnelAttrs[__OVS_TUNNEL_KEY_ATTR_MAX]; PNL_ATTR encapAttrs[__OVS_KEY_ATTR_MAX]; NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength); RtlZeroMemory(&getInput, sizeof(OvsFlowGetInput)); RtlZeroMemory(&getOutput, sizeof(OvsFlowGetOutput)); UINT32 keyAttrOffset = 0; UINT32 tunnelKeyAttrOffset = 0; UINT32 encapOffset = 0; BOOLEAN ok; NL_ERROR nlError = NL_ERROR_SUCCESS; if (usrParamsCtx->inputLength > usrParamsCtx->outputLength) { /* Should not be the case. * We'll be copying the flow keys back from * input buffer to output buffer. */ rc = STATUS_INVALID_PARAMETER; OVS_LOG_ERROR("inputLength: %d GREATER THEN outputLength: %d", usrParamsCtx->inputLength, usrParamsCtx->outputLength); goto done; } /* Get all the top level Flow attributes */ if ((NlAttrParse(nlMsgHdr, attrOffset, NlMsgAttrsLen(nlMsgHdr), nlFlowPolicy, ARRAY_SIZE(nlFlowPolicy), nlAttrs, ARRAY_SIZE(nlAttrs))) != TRUE) { OVS_LOG_ERROR("Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } keyAttrOffset = (UINT32)((PCHAR) nlAttrs[OVS_FLOW_ATTR_KEY] - (PCHAR)nlMsgHdr); /* Get flow keys attributes */ if ((NlAttrParseNested(nlMsgHdr, keyAttrOffset, NlAttrLen(nlAttrs[OVS_FLOW_ATTR_KEY]), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), keyAttrs, ARRAY_SIZE(keyAttrs))) != TRUE) { OVS_LOG_ERROR("Key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } if (keyAttrs[OVS_KEY_ATTR_ENCAP]) { encapOffset = (UINT32)((PCHAR) (keyAttrs[OVS_KEY_ATTR_ENCAP]) - (PCHAR)nlMsgHdr); if ((NlAttrParseNested(nlMsgHdr, encapOffset, NlAttrLen(keyAttrs[OVS_KEY_ATTR_ENCAP]), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), encapAttrs, ARRAY_SIZE(encapAttrs))) != TRUE) { OVS_LOG_ERROR("Encap Key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } } if (keyAttrs[OVS_KEY_ATTR_TUNNEL]) { tunnelKeyAttrOffset = (UINT32)((PCHAR) (keyAttrs[OVS_KEY_ATTR_TUNNEL]) - (PCHAR)nlMsgHdr); /* Get tunnel keys attributes */ if ((NlAttrParseNested(nlMsgHdr, tunnelKeyAttrOffset, NlAttrLen(keyAttrs[OVS_KEY_ATTR_TUNNEL]), nlFlowTunnelKeyPolicy, ARRAY_SIZE(nlFlowTunnelKeyPolicy), tunnelAttrs, ARRAY_SIZE(tunnelAttrs))) != TRUE) { OVS_LOG_ERROR("Tunnel key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } } _MapKeyAttrToFlowPut(keyAttrs, tunnelAttrs, &(getInput.key)); ASSERT(keyAttrs[OVS_KEY_ATTR_IN_PORT]); if (encapOffset) { _MapKeyAttrToFlowPut(encapAttrs, tunnelAttrs, &(getInput.key)); } getInput.dpNo = ovsHdr->dp_ifindex; getInput.getFlags = FLOW_GET_STATS | FLOW_GET_ACTIONS; /* 4th argument is a no op. * We are keeping this argument to be compatible * with our dpif-windows based interface. */ rc = OvsGetFlowIoctl(&getInput, &getOutput); if (rc != STATUS_SUCCESS) { OVS_LOG_ERROR("OvsGetFlowIoctl failed."); /* * Report back to the userspace the flow could not be found */ nlError = NL_ERROR_NOENT; goto done; } /* Lets prepare the reply. */ nlMsgOutHdr = (PNL_MSG_HDR)(NlBufAt(&nlBuf, 0, 0)); /* Input already has all the attributes for the flow key. * Lets copy the values back. */ ok = NlMsgPutTail(&nlBuf, (PCHAR)(usrParamsCtx->inputBuffer), usrParamsCtx->inputLength); if (!ok) { OVS_LOG_ERROR("Could not copy the data to the buffer tail"); goto done; } rc = _MapFlowStatsToNlStats(&nlBuf, &((getOutput.info).stats)); if (rc != STATUS_SUCCESS) { OVS_LOG_ERROR("_OvsFlowMapFlowKeyToNlStats failed."); goto done; } rc = _MapFlowActionToNlAction(&nlBuf, ((getOutput.info).actionsLen), getOutput.info.actions); if (rc != STATUS_SUCCESS) { OVS_LOG_ERROR("_MapFlowActionToNlAction failed."); goto done; } NlMsgSetSize(nlMsgOutHdr, NlBufSize(&nlBuf)); NlMsgAlignSize(nlMsgOutHdr); *replyLen += NlMsgSize(nlMsgOutHdr); done: if (nlError != NL_ERROR_SUCCESS) { POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR) usrParamsCtx->outputBuffer; ASSERT(msgError); NlBuildErrorMsg(msgIn, msgError, nlError, replyLen); ASSERT(*replyLen != 0); rc = STATUS_SUCCESS; } return rc; } /* *---------------------------------------------------------------------------- * _FlowNlDumpCmdHandler -- * Handler for OVS_FLOW_CMD_DUMP command. *---------------------------------------------------------------------------- */ NTSTATUS _FlowNlDumpCmdHandler(POVS_USER_PARAMS_CONTEXT usrParamsCtx, UINT32 *replyLen) { NTSTATUS rc = STATUS_SUCCESS; UINT32 temp = 0; /* To keep compiler happy for calling OvsDoDumpFlows */ NL_ERROR nlError = NL_ERROR_SUCCESS; POVS_OPEN_INSTANCE instance = (POVS_OPEN_INSTANCE) (usrParamsCtx->ovsInstance); POVS_MESSAGE msgIn = instance->dumpState.ovsMsg; if (usrParamsCtx->devOp == OVS_WRITE_DEV_OP) { /* Dump Start */ OvsSetupDumpStart(usrParamsCtx); goto done; } PNL_MSG_HDR nlMsgHdr = &(msgIn->nlMsg); PGENL_MSG_HDR genlMsgHdr = &(msgIn->genlMsg); POVS_HDR ovsHdr = &(msgIn->ovsHdr); PNL_MSG_HDR nlMsgOutHdr = NULL; UINT32 hdrOffset = 0; /* Get Next */ OvsFlowDumpOutput dumpOutput; OvsFlowDumpInput dumpInput; NL_BUFFER nlBuf; NlBufInit(&nlBuf, usrParamsCtx->outputBuffer, usrParamsCtx->outputLength); ASSERT(usrParamsCtx->devOp == OVS_READ_DEV_OP); ASSERT(usrParamsCtx->outputLength); RtlZeroMemory(&dumpInput, sizeof(OvsFlowDumpInput)); RtlZeroMemory(&dumpOutput, sizeof(OvsFlowDumpOutput)); dumpInput.dpNo = ovsHdr->dp_ifindex; dumpInput.getFlags = FLOW_GET_KEY | FLOW_GET_STATS | FLOW_GET_ACTIONS; /* Lets provide as many flows to userspace as possible. */ do { dumpInput.position[0] = instance->dumpState.index[0]; dumpInput.position[1] = instance->dumpState.index[1]; rc = OvsDoDumpFlows(&dumpInput, &dumpOutput, &temp); if (rc != STATUS_SUCCESS) { OVS_LOG_ERROR("OvsDoDumpFlows failed with rc: %d", rc); /* * Report back to the userspace the flows could not be found */ nlError = NL_ERROR_NOENT; break; } /* Done with Dump, send NLMSG_DONE */ if (!(dumpOutput.n)) { BOOLEAN ok; OVS_LOG_INFO("Dump Done"); nlMsgOutHdr = (PNL_MSG_HDR)(NlBufAt(&nlBuf, NlBufSize(&nlBuf), 0)); ok = NlFillNlHdr(&nlBuf, NLMSG_DONE, NLM_F_MULTI, nlMsgHdr->nlmsgSeq, nlMsgHdr->nlmsgPid); if (!ok) { rc = STATUS_INVALID_BUFFER_SIZE; OVS_LOG_ERROR("Unable to prepare DUMP_DONE reply."); break; } else { rc = STATUS_SUCCESS; } NlMsgAlignSize(nlMsgOutHdr); *replyLen += NlMsgSize(nlMsgOutHdr); FreeUserDumpState(instance); break; } else { BOOLEAN ok; hdrOffset = NlBufSize(&nlBuf); nlMsgOutHdr = (PNL_MSG_HDR)(NlBufAt(&nlBuf, hdrOffset, 0)); /* Netlink header */ ok = NlFillOvsMsg(&nlBuf, nlMsgHdr->nlmsgType, NLM_F_MULTI, nlMsgHdr->nlmsgSeq, nlMsgHdr->nlmsgPid, genlMsgHdr->cmd, genlMsgHdr->version, ovsHdr->dp_ifindex); if (!ok) { /* Reset rc to success so that we can * send already added messages to user space. */ rc = STATUS_SUCCESS; break; } /* Time to add attributes */ rc = _MapFlowInfoToNl(&nlBuf, &(dumpOutput.flow)); if (rc != STATUS_SUCCESS) { /* Adding the attribute failed, we are out of space in the buffer, remove the appended OVS header */ NlMsgSetSize(nlMsgOutHdr, NlMsgSize(nlMsgOutHdr) - sizeof(struct _OVS_MESSAGE)); /* Reset rc to success so that we can * send already added messages to user space. */ rc = STATUS_SUCCESS; break; } NlMsgSetSize(nlMsgOutHdr, NlBufSize(&nlBuf) - hdrOffset); NlMsgAlignSize(nlMsgOutHdr); *replyLen += NlMsgSize(nlMsgOutHdr); instance->dumpState.index[0] = dumpOutput.position[0]; instance->dumpState.index[1] = dumpOutput.position[1]; } } while(TRUE); done: if (nlError != NL_ERROR_SUCCESS) { POVS_MESSAGE_ERROR msgError = (POVS_MESSAGE_ERROR) usrParamsCtx->outputBuffer; ASSERT(msgError); NlBuildErrorMsg(msgIn, msgError, nlError, replyLen); ASSERT(*replyLen != 0); rc = STATUS_SUCCESS; } return rc; } /* *---------------------------------------------------------------------------- * _MapFlowInfoToNl -- * Maps OvsFlowInfo to Netlink attributes. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowInfoToNl(PNL_BUFFER nlBuf, OvsFlowInfo *flowInfo) { NTSTATUS rc; rc = MapFlowKeyToNlKey(nlBuf, &(flowInfo->key), OVS_FLOW_ATTR_KEY, OVS_KEY_ATTR_TUNNEL); if (rc != STATUS_SUCCESS) { goto done; } rc = _MapFlowStatsToNlStats(nlBuf, &(flowInfo->stats)); if (rc != STATUS_SUCCESS) { goto done; } rc = _MapFlowActionToNlAction(nlBuf, flowInfo->actionsLen, flowInfo->actions); if (rc != STATUS_SUCCESS) { goto done; } done: return rc; } UINT64 OvsFlowUsedTime(UINT64 flowUsed) { UINT64 currentMs, iddleMs; LARGE_INTEGER tickCount; KeQueryTickCount(&tickCount); iddleMs = tickCount.QuadPart - flowUsed; iddleMs *= ovsTimeIncrementPerTick; currentMs = KeQueryPerformanceCounter(&tickCount).QuadPart * 1000 / tickCount.QuadPart; return currentMs - iddleMs; } /* *---------------------------------------------------------------------------- * _MapFlowStatsToNlStats -- * Maps OvsFlowStats to OVS_FLOW_ATTR_STATS attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowStatsToNlStats(PNL_BUFFER nlBuf, OvsFlowStats *flowStats) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_flow_stats replyStats; replyStats.n_packets = flowStats->packetCount; replyStats.n_bytes = flowStats->byteCount; if (flowStats->used && !NlMsgPutTailU64(nlBuf, OVS_FLOW_ATTR_USED, OvsFlowUsedTime(flowStats->used)) ) { rc = STATUS_INVALID_BUFFER_SIZE; goto done; } if (!NlMsgPutTailUnspec(nlBuf, OVS_FLOW_ATTR_STATS, (PCHAR)(&replyStats), sizeof(struct ovs_flow_stats))) { rc = STATUS_INVALID_BUFFER_SIZE; goto done; } if (!NlMsgPutTailU8(nlBuf, OVS_FLOW_ATTR_TCP_FLAGS, flowStats->tcpFlags)) { rc = STATUS_INVALID_BUFFER_SIZE; goto done; } done: return rc; } /* *---------------------------------------------------------------------------- * _MapFlowActionToNlAction -- * Maps flow actions to OVS_FLOW_ATTR_ACTION attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowActionToNlAction(PNL_BUFFER nlBuf, uint32_t actionsLen, PNL_ATTR actions) { NTSTATUS rc = STATUS_SUCCESS; UINT32 offset = 0; offset = NlMsgStartNested(nlBuf, OVS_FLOW_ATTR_ACTIONS); if (!offset) { /* Starting the nested attribute failed. */ rc = STATUS_INVALID_BUFFER_SIZE; goto error_nested_start; } if (!NlBufCopyAtTail(nlBuf, (PCHAR)actions, actionsLen)) { /* Adding a nested attribute failed. */ rc = STATUS_INVALID_BUFFER_SIZE; goto done; } done: NlMsgEndNested(nlBuf, offset); error_nested_start: return rc; } /* *---------------------------------------------------------------------------- * MapFlowKeyToNlKey -- * Maps OvsFlowKey to OVS_FLOW_ATTR_KEY attribute. *---------------------------------------------------------------------------- */ NTSTATUS MapFlowKeyToNlKey(PNL_BUFFER nlBuf, OvsFlowKey *flowKey, UINT16 keyType, UINT16 tunKeyType) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_key_ethernet ethKey; UINT32 offset = 0, encap_offset = 0; offset = NlMsgStartNested(nlBuf, keyType); if (!offset) { /* Starting the nested attribute failed. */ rc = STATUS_UNSUCCESSFUL; goto error_nested_start; } if (!NlMsgPutTailU32(nlBuf, OVS_KEY_ATTR_RECIRC_ID, flowKey->recircId)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU32(nlBuf, OVS_KEY_ATTR_CT_STATE, flowKey->ct.state)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU16(nlBuf, OVS_KEY_ATTR_CT_ZONE, flowKey->ct.zone)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU32(nlBuf, OVS_KEY_ATTR_CT_MARK, flowKey->ct.mark)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_CT_LABELS, (PCHAR)(&flowKey->ct.labels), sizeof(struct ovs_key_ct_labels))) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4, (PCHAR)(&flowKey->ct.tuple_ipv4), sizeof(struct ovs_key_ct_tuple_ipv4))) { rc = STATUS_UNSUCCESSFUL; goto done; } if (flowKey->dpHash) { if (!NlMsgPutTailU32(nlBuf, OVS_KEY_ATTR_DP_HASH, flowKey->dpHash)) { rc = STATUS_UNSUCCESSFUL; goto done; } } /* Ethernet header */ RtlCopyMemory(&(ethKey.eth_src), flowKey->l2.dlSrc, ETH_ADDR_LEN); RtlCopyMemory(&(ethKey.eth_dst), flowKey->l2.dlDst, ETH_ADDR_LEN); if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_ETHERNET, (PCHAR)(&ethKey), sizeof(struct ovs_key_ethernet))) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU32(nlBuf, OVS_KEY_ATTR_IN_PORT, flowKey->l2.inPort)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU16(nlBuf, OVS_KEY_ATTR_ETHERTYPE, flowKey->l2.vlanKey.vlanTci == 0 ? flowKey->l2.dlType : flowKey->l2.vlanKey.vlanTpid)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (flowKey->l2.vlanKey.vlanTci || flowKey->l2.dlType == ETH_TYPE_802_1PQ) { if (!NlMsgPutTailU16(nlBuf, OVS_KEY_ATTR_VLAN, flowKey->l2.vlanKey.vlanTci)) { rc = STATUS_UNSUCCESSFUL; goto done; } /* Add encap attributes. */ encap_offset = NlMsgStartNested(nlBuf, OVS_KEY_ATTR_ENCAP); if (!encap_offset) { /* Starting the nested attribute failed. */ rc = STATUS_UNSUCCESSFUL; goto done; } /* Add packet Ethernet Type*/ if (!NlMsgPutTailU16(nlBuf, OVS_KEY_ATTR_ETHERTYPE, flowKey->l2.dlType)) { rc = STATUS_UNSUCCESSFUL; goto encap; } } /* ==== L3 + L4 ==== */ switch (ntohs(flowKey->l2.dlType)) { case ETH_TYPE_IPV4: { IpKey *ipv4FlowPutKey = &(flowKey->ipKey); rc = _MapFlowIpv4KeyToNlKey(nlBuf, ipv4FlowPutKey); break; } case ETH_TYPE_IPV6: { Ipv6Key *ipv6FlowPutKey = &(flowKey->ipv6Key); Icmp6Key *icmpv6FlowPutKey = &(flowKey->icmp6Key); rc = _MapFlowIpv6KeyToNlKey(nlBuf, ipv6FlowPutKey, icmpv6FlowPutKey); break; } case ETH_TYPE_ARP: case ETH_TYPE_RARP: { ArpKey *arpFlowPutKey = &(flowKey->arpKey); rc = _MapFlowArpKeyToNlKey(nlBuf, arpFlowPutKey); break; } case ETH_TYPE_MPLS: case ETH_TYPE_MPLS_MCAST: { MplsKey *mplsFlowPutKey = &(flowKey->mplsKey); rc = _MapFlowMplsKeyToNlKey(nlBuf, mplsFlowPutKey); break; } default: break; } if (rc != STATUS_SUCCESS) { goto done; } if (flowKey->tunKey.dst) { rc = MapFlowTunKeyToNlKey(nlBuf, &(flowKey->tunKey), tunKeyType); if (rc != STATUS_SUCCESS) { goto done; } } encap: if (encap_offset) { NlMsgEndNested(nlBuf, encap_offset); } done: NlMsgEndNested(nlBuf, offset); error_nested_start: return rc; } /* *---------------------------------------------------------------------------- * MapFlowTunKeyToNlKey -- * Maps OvsIPv4TunnelKey to OVS_TUNNEL_KEY_ATTR_ID attribute. *---------------------------------------------------------------------------- */ NTSTATUS MapFlowTunKeyToNlKey(PNL_BUFFER nlBuf, OvsIPv4TunnelKey *tunKey, UINT16 tunKeyType) { NTSTATUS rc = STATUS_SUCCESS; UINT32 offset = 0; offset = NlMsgStartNested(nlBuf, tunKeyType); if (!offset) { /* Starting the nested attribute failed. */ rc = STATUS_UNSUCCESSFUL; goto error_nested_start; } if (!NlMsgPutTailU64(nlBuf, OVS_TUNNEL_KEY_ATTR_ID, tunKey->tunnelId)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU32(nlBuf, OVS_TUNNEL_KEY_ATTR_IPV4_DST, tunKey->dst)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU32(nlBuf, OVS_TUNNEL_KEY_ATTR_IPV4_SRC, tunKey->src)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU8(nlBuf, OVS_TUNNEL_KEY_ATTR_TOS, tunKey->tos)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU8(nlBuf, OVS_TUNNEL_KEY_ATTR_TTL, tunKey->ttl)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (tunKey->tunOptLen > 0 && !NlMsgPutTailUnspec(nlBuf, OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS, (PCHAR)TunnelKeyGetOptions(tunKey), tunKey->tunOptLen)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU16(nlBuf, OVS_TUNNEL_KEY_ATTR_TP_SRC, tunKey->flow_hash)) { rc = STATUS_UNSUCCESSFUL; goto done; } if (!NlMsgPutTailU16(nlBuf, OVS_TUNNEL_KEY_ATTR_TP_DST, tunKey->dst_port)) { rc = STATUS_UNSUCCESSFUL; goto done; } done: NlMsgEndNested(nlBuf, offset); error_nested_start: return rc; } /* *---------------------------------------------------------------------------- * _MapFlowTunKeyToNlKey -- * Maps OvsIPv4FlowPutKey to OVS_KEY_ATTR_IPV4 attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowIpv4KeyToNlKey(PNL_BUFFER nlBuf, IpKey *ipv4FlowPutKey) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_key_ipv4 ipv4Key; ipv4Key.ipv4_src = ipv4FlowPutKey->nwSrc; ipv4Key.ipv4_dst = ipv4FlowPutKey->nwDst; ipv4Key.ipv4_proto = ipv4FlowPutKey->nwProto; ipv4Key.ipv4_tos = ipv4FlowPutKey->nwTos; ipv4Key.ipv4_ttl = ipv4FlowPutKey->nwTtl; ipv4Key.ipv4_frag = ipv4FlowPutKey->nwFrag; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_IPV4, (PCHAR)(&ipv4Key), sizeof(struct ovs_key_ipv4))) { rc = STATUS_UNSUCCESSFUL; goto done; } switch (ipv4Key.ipv4_proto) { case IPPROTO_TCP: { struct ovs_key_tcp tcpKey; tcpKey.tcp_src = ipv4FlowPutKey->l4.tpSrc; tcpKey.tcp_dst = ipv4FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_TCP, (PCHAR)(&tcpKey), sizeof(tcpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_UDP: { struct ovs_key_udp udpKey; udpKey.udp_src = ipv4FlowPutKey->l4.tpSrc; udpKey.udp_dst = ipv4FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_UDP, (PCHAR)(&udpKey), sizeof(udpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_SCTP: { struct ovs_key_sctp sctpKey; sctpKey.sctp_src = ipv4FlowPutKey->l4.tpSrc; sctpKey.sctp_dst = ipv4FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_SCTP, (PCHAR)(&sctpKey), sizeof(sctpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_ICMP: { struct ovs_key_icmp icmpKey; icmpKey.icmp_type = (__u8)ntohs(ipv4FlowPutKey->l4.tpSrc); icmpKey.icmp_code = (__u8)ntohs(ipv4FlowPutKey->l4.tpDst); if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_ICMP, (PCHAR)(&icmpKey), sizeof(icmpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } default: break; } done: return rc; } /* *---------------------------------------------------------------------------- * _MapFlowIpv6KeyToNlKey -- * Maps _MapFlowIpv6KeyToNlKey to OVS_KEY_ATTR_IPV6 attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowIpv6KeyToNlKey(PNL_BUFFER nlBuf, Ipv6Key *ipv6FlowPutKey, Icmp6Key *icmpv6FlowPutKey) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_key_ipv6 ipv6Key; RtlCopyMemory(&(ipv6Key.ipv6_src), &ipv6FlowPutKey->ipv6Src, sizeof ipv6Key.ipv6_src); RtlCopyMemory(&(ipv6Key.ipv6_dst), &ipv6FlowPutKey->ipv6Dst, sizeof ipv6Key.ipv6_dst); ipv6Key.ipv6_label = ipv6FlowPutKey->ipv6Label; ipv6Key.ipv6_proto = ipv6FlowPutKey->nwProto; ipv6Key.ipv6_tclass = ipv6FlowPutKey->nwTos; ipv6Key.ipv6_hlimit = ipv6FlowPutKey->nwTtl; ipv6Key.ipv6_frag = ipv6FlowPutKey->nwFrag; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_IPV6, (PCHAR)(&ipv6Key), sizeof(ipv6Key))) { rc = STATUS_UNSUCCESSFUL; goto done; } switch (ipv6Key.ipv6_proto) { case IPPROTO_TCP: { struct ovs_key_tcp tcpKey; tcpKey.tcp_src = ipv6FlowPutKey->l4.tpSrc; tcpKey.tcp_dst = ipv6FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_TCP, (PCHAR)(&tcpKey), sizeof(tcpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_UDP: { struct ovs_key_udp udpKey; udpKey.udp_src = ipv6FlowPutKey->l4.tpSrc; udpKey.udp_dst = ipv6FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_UDP, (PCHAR)(&udpKey), sizeof(udpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_SCTP: { struct ovs_key_sctp sctpKey; sctpKey.sctp_src = ipv6FlowPutKey->l4.tpSrc; sctpKey.sctp_dst = ipv6FlowPutKey->l4.tpDst; if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_SCTP, (PCHAR)(&sctpKey), sizeof(sctpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } case IPPROTO_ICMPV6: { struct ovs_key_icmpv6 icmpV6Key; struct ovs_key_nd ndKey; icmpV6Key.icmpv6_type = (__u8)ntohs(icmpv6FlowPutKey->l4.tpSrc); icmpV6Key.icmpv6_code = (__u8)ntohs(icmpv6FlowPutKey->l4.tpDst); if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_ICMPV6, (PCHAR)(&icmpV6Key), sizeof(icmpV6Key))) { rc = STATUS_UNSUCCESSFUL; goto done; } RtlCopyMemory(&(ndKey.nd_target), &icmpv6FlowPutKey->ndTarget, sizeof(icmpv6FlowPutKey->ndTarget)); RtlCopyMemory(&(ndKey.nd_sll), &icmpv6FlowPutKey->arpSha, ETH_ADDR_LEN); RtlCopyMemory(&(ndKey.nd_tll), &icmpv6FlowPutKey->arpTha, ETH_ADDR_LEN); if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_ND, (PCHAR)(&ndKey), sizeof(ndKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } break; } default: break; } done: return rc; } /* *---------------------------------------------------------------------------- * _MapFlowArpKeyToNlKey -- * Maps _MapFlowArpKeyToNlKey to OVS_KEY_ATTR_ARP attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowArpKeyToNlKey(PNL_BUFFER nlBuf, ArpKey *arpFlowPutKey) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_key_arp arpKey; arpKey.arp_sip = arpFlowPutKey->nwSrc; arpKey.arp_tip = arpFlowPutKey->nwDst; RtlCopyMemory(&(arpKey.arp_sha), arpFlowPutKey->arpSha, ETH_ADDR_LEN); RtlCopyMemory(&(arpKey.arp_tha), arpFlowPutKey->arpTha, ETH_ADDR_LEN); /* * Flow_Extract() stores 'nwProto' in host order for ARP since 'nwProto' is * 1 byte field and the ARP opcode is 2 bytes, and all of the kernel code * understand this while looking at an ARP key. * While we pass up the ARP key to userspace, convert from host order to * network order. Likewise, when processing an ARP key from userspace, * convert from network order to host order. * * It is important to note that the flow table stores the ARP opcode field * in host order. */ arpKey.arp_op = htons(arpFlowPutKey->nwProto); if (!NlMsgPutTailUnspec(nlBuf, OVS_KEY_ATTR_ARP, (PCHAR)(&arpKey), sizeof(arpKey))) { rc = STATUS_UNSUCCESSFUL; goto done; } done: return rc; } /* *---------------------------------------------------------------------------- * _MapFlowMplsKeyToNlKey -- * Maps _MapFlowMplsKeyToNlKey to OVS_KEY_ATTR_MPLS attribute. *---------------------------------------------------------------------------- */ static NTSTATUS _MapFlowMplsKeyToNlKey(PNL_BUFFER nlBuf, MplsKey *mplsFlowPutKey) { NTSTATUS rc = STATUS_SUCCESS; struct ovs_key_mpls *mplsKey; mplsKey = (struct ovs_key_mpls *) NlMsgPutTailUnspecUninit(nlBuf, OVS_KEY_ATTR_MPLS, sizeof(*mplsKey)); if (!mplsKey) { rc = STATUS_UNSUCCESSFUL; goto done; } mplsKey->mpls_lse = mplsFlowPutKey->lse; done: return rc; } /* *---------------------------------------------------------------------------- * _MapNlToFlowPut -- * Maps input netlink message to OvsFlowPut. *---------------------------------------------------------------------------- */ static NTSTATUS _MapNlToFlowPut(POVS_MESSAGE msgIn, PNL_ATTR keyAttr, PNL_ATTR actionAttr, PNL_ATTR flowAttrClear, OvsFlowPut *mappedFlow) { NTSTATUS rc = STATUS_SUCCESS; PNL_MSG_HDR nlMsgHdr = &(msgIn->nlMsg); PGENL_MSG_HDR genlMsgHdr = &(msgIn->genlMsg); POVS_HDR ovsHdr = &(msgIn->ovsHdr); UINT32 keyAttrOffset = (UINT32)((PCHAR)keyAttr - (PCHAR)nlMsgHdr); UINT32 tunnelKeyAttrOffset; UINT32 encapOffset = 0; PNL_ATTR keyAttrs[__OVS_KEY_ATTR_MAX] = {NULL}; PNL_ATTR tunnelAttrs[__OVS_TUNNEL_KEY_ATTR_MAX] = {NULL}; PNL_ATTR encapAttrs[__OVS_KEY_ATTR_MAX] = { NULL }; /* Get flow keys attributes */ if ((NlAttrParseNested(nlMsgHdr, keyAttrOffset, NlAttrLen(keyAttr), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), keyAttrs, ARRAY_SIZE(keyAttrs))) != TRUE) { OVS_LOG_ERROR("Key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } if (keyAttrs[OVS_KEY_ATTR_ENCAP]) { encapOffset = (UINT32)((PCHAR)(keyAttrs[OVS_KEY_ATTR_ENCAP]) - (PCHAR)nlMsgHdr); if ((NlAttrParseNested(nlMsgHdr, encapOffset, NlAttrLen(keyAttrs[OVS_KEY_ATTR_ENCAP]), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), encapAttrs, ARRAY_SIZE(encapAttrs))) != TRUE) { OVS_LOG_ERROR("Encap Key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } } if (keyAttrs[OVS_KEY_ATTR_TUNNEL]) { tunnelKeyAttrOffset = (UINT32)((PCHAR) (keyAttrs[OVS_KEY_ATTR_TUNNEL]) - (PCHAR)nlMsgHdr); /* Get tunnel keys attributes */ if ((NlAttrParseNested(nlMsgHdr, tunnelKeyAttrOffset, NlAttrLen(keyAttrs[OVS_KEY_ATTR_TUNNEL]), nlFlowTunnelKeyPolicy, ARRAY_SIZE(nlFlowTunnelKeyPolicy), tunnelAttrs, ARRAY_SIZE(tunnelAttrs))) != TRUE) { OVS_LOG_ERROR("Tunnel key Attr Parsing failed for msg: %p", nlMsgHdr); rc = STATUS_INVALID_PARAMETER; goto done; } } _MapKeyAttrToFlowPut(keyAttrs, tunnelAttrs, &(mappedFlow->key)); ASSERT(keyAttrs[OVS_KEY_ATTR_IN_PORT]); if (encapOffset) { _MapKeyAttrToFlowPut(encapAttrs, tunnelAttrs, &(mappedFlow->key)); } /* Map the action */ if (actionAttr) { mappedFlow->actionsLen = NlAttrGetSize(actionAttr); mappedFlow->actions = NlAttrGet(actionAttr); } mappedFlow->dpNo = ovsHdr->dp_ifindex; _MapNlToFlowPutFlags(genlMsgHdr, flowAttrClear, mappedFlow); done: return rc; } /* *---------------------------------------------------------------------------- * _MapNlToFlowPutFlags -- * Maps netlink message to OvsFlowPut->flags. *---------------------------------------------------------------------------- */ static VOID _MapNlToFlowPutFlags(PGENL_MSG_HDR genlMsgHdr, PNL_ATTR flowAttrClear, OvsFlowPut *mappedFlow) { uint32_t flags = 0; switch (genlMsgHdr->cmd) { case OVS_FLOW_CMD_NEW: flags |= OVSWIN_FLOW_PUT_CREATE; break; case OVS_FLOW_CMD_DEL: flags |= OVSWIN_FLOW_PUT_DELETE; break; case OVS_FLOW_CMD_SET: flags |= OVSWIN_FLOW_PUT_MODIFY; break; default: ASSERT(0); } if (flowAttrClear) { flags |= OVSWIN_FLOW_PUT_CLEAR; } mappedFlow->flags = flags; } /* *---------------------------------------------------------------------------- * _MapKeyAttrToFlowPut -- * Converts FLOW_KEY attribute to OvsFlowPut->key. *---------------------------------------------------------------------------- */ static VOID _MapKeyAttrToFlowPut(PNL_ATTR *keyAttrs, PNL_ATTR *tunnelAttrs, OvsFlowKey *destKey) { MapTunAttrToFlowPut(keyAttrs, tunnelAttrs, destKey); if (keyAttrs[OVS_KEY_ATTR_RECIRC_ID]) { destKey->recircId = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_RECIRC_ID]); } if (keyAttrs[OVS_KEY_ATTR_DP_HASH]) { destKey->dpHash = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_DP_HASH]); } if (keyAttrs[OVS_KEY_ATTR_CT_STATE]) { destKey->ct.state = (NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_STATE])); } if (keyAttrs[OVS_KEY_ATTR_CT_ZONE]) { destKey->ct.zone = (NlAttrGetU16(keyAttrs[OVS_KEY_ATTR_CT_ZONE])); } if (keyAttrs[OVS_KEY_ATTR_CT_MARK]) { destKey->ct.mark = (NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_MARK])); } if (keyAttrs[OVS_KEY_ATTR_CT_LABELS]) { const struct ovs_key_ct_labels *ct_labels; ct_labels = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_LABELS]); NdisMoveMemory(&destKey->ct.labels, ct_labels, sizeof(struct ovs_key_ct_labels)); } if (keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]) { const struct ovs_key_ct_tuple_ipv4 *tuple_ipv4; tuple_ipv4 = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]); NdisMoveMemory(&destKey->ct.tuple_ipv4, tuple_ipv4, sizeof(struct ovs_key_ct_tuple_ipv4)); } /* ===== L2 headers ===== */ if (keyAttrs[OVS_KEY_ATTR_IN_PORT]) { destKey->l2.inPort = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_IN_PORT]); } if (keyAttrs[OVS_KEY_ATTR_ETHERNET]) { const struct ovs_key_ethernet *eth_key; eth_key = NlAttrGet(keyAttrs[OVS_KEY_ATTR_ETHERNET]); RtlCopyMemory(destKey->l2.dlSrc, eth_key->eth_src, ETH_ADDR_LEN); RtlCopyMemory(destKey->l2.dlDst, eth_key->eth_dst, ETH_ADDR_LEN); } /* TODO: Ideally ETHERTYPE should not be optional. * But during vswitchd bootup we are seeing FLOW_ADD * requests with no ETHERTYPE attributes. * Need to verify this. */ if (keyAttrs[OVS_KEY_ATTR_ETHERTYPE]) { destKey->l2.dlType = (NlAttrGetU16(keyAttrs [OVS_KEY_ATTR_ETHERTYPE])); } if (keyAttrs[OVS_KEY_ATTR_VLAN]) { destKey->l2.vlanKey.vlanTci = NlAttrGetU16(keyAttrs[OVS_KEY_ATTR_VLAN]); if (destKey->l2.vlanKey.vlanTci != 0) { /* set TPID to dlType. */ destKey->l2.vlanKey.vlanTpid = destKey->l2.dlType; } } /* ==== L3 + L4. ==== */ destKey->l2.keyLen = OVS_WIN_TUNNEL_KEY_SIZE + OVS_L2_KEY_SIZE - destKey->l2.offset; switch (ntohs(destKey->l2.dlType)) { case ETH_TYPE_IPV4: { if (keyAttrs[OVS_KEY_ATTR_IPV4]) { const struct ovs_key_ipv4 *ipv4Key; ipv4Key = NlAttrGet(keyAttrs[OVS_KEY_ATTR_IPV4]); IpKey *ipv4FlowPutKey = &(destKey->ipKey); ipv4FlowPutKey->nwSrc = ipv4Key->ipv4_src; ipv4FlowPutKey->nwDst = ipv4Key->ipv4_dst; ipv4FlowPutKey->nwProto = ipv4Key->ipv4_proto; ipv4FlowPutKey->nwTos = ipv4Key->ipv4_tos; ipv4FlowPutKey->nwTtl = ipv4Key->ipv4_ttl; ipv4FlowPutKey->nwFrag = ipv4Key->ipv4_frag; if (keyAttrs[OVS_KEY_ATTR_TCP]) { const struct ovs_key_tcp *tcpKey; tcpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_TCP]); ipv4FlowPutKey->l4.tpSrc = tcpKey->tcp_src; ipv4FlowPutKey->l4.tpDst = tcpKey->tcp_dst; } if (keyAttrs[OVS_KEY_ATTR_UDP]) { const struct ovs_key_udp *udpKey; udpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_UDP]); ipv4FlowPutKey->l4.tpSrc = udpKey->udp_src; ipv4FlowPutKey->l4.tpDst = udpKey->udp_dst; } if (keyAttrs[OVS_KEY_ATTR_SCTP]) { const struct ovs_key_sctp *sctpKey; sctpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_SCTP]); ipv4FlowPutKey->l4.tpSrc = sctpKey->sctp_src; ipv4FlowPutKey->l4.tpDst = sctpKey->sctp_dst; } if (keyAttrs[OVS_KEY_ATTR_ICMP]) { const struct ovs_key_icmp *icmpKey; icmpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_ICMP]); ipv4FlowPutKey->l4.tpSrc = htons(icmpKey->icmp_type); ipv4FlowPutKey->l4.tpDst = htons(icmpKey->icmp_code); } destKey->l2.keyLen += OVS_IP_KEY_SIZE; } break; } case ETH_TYPE_IPV6: { if (keyAttrs[OVS_KEY_ATTR_IPV6]) { const struct ovs_key_ipv6 *ipv6Key; ipv6Key = NlAttrGet(keyAttrs[OVS_KEY_ATTR_IPV6]); Ipv6Key *ipv6FlowPutKey = &(destKey->ipv6Key); RtlCopyMemory(&ipv6FlowPutKey->ipv6Src, ipv6Key->ipv6_src, sizeof ipv6Key->ipv6_src); RtlCopyMemory(&ipv6FlowPutKey->ipv6Dst, ipv6Key->ipv6_dst, sizeof ipv6Key->ipv6_dst); ipv6FlowPutKey->ipv6Label = ipv6Key->ipv6_label; ipv6FlowPutKey->nwProto = ipv6Key->ipv6_proto; ipv6FlowPutKey->nwTos = ipv6Key->ipv6_tclass; ipv6FlowPutKey->nwTtl = ipv6Key->ipv6_hlimit; ipv6FlowPutKey->nwFrag = ipv6Key->ipv6_frag; if (keyAttrs[OVS_KEY_ATTR_TCP]) { const struct ovs_key_tcp *tcpKey; tcpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_TCP]); ipv6FlowPutKey->l4.tpSrc = tcpKey->tcp_src; ipv6FlowPutKey->l4.tpDst = tcpKey->tcp_dst; } if (keyAttrs[OVS_KEY_ATTR_UDP]) { const struct ovs_key_udp *udpKey; udpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_UDP]); ipv6FlowPutKey->l4.tpSrc = udpKey->udp_src; ipv6FlowPutKey->l4.tpDst = udpKey->udp_dst; } if (keyAttrs[OVS_KEY_ATTR_SCTP]) { const struct ovs_key_sctp *sctpKey; sctpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_SCTP]); ipv6FlowPutKey->l4.tpSrc = sctpKey->sctp_src; ipv6FlowPutKey->l4.tpDst = sctpKey->sctp_dst; } if (keyAttrs[OVS_KEY_ATTR_ICMPV6]) { const struct ovs_key_icmpv6 *icmpv6Key; Icmp6Key *icmp6FlowPutKey= &(destKey->icmp6Key); icmpv6Key = NlAttrGet(keyAttrs[OVS_KEY_ATTR_ICMPV6]); icmp6FlowPutKey->l4.tpSrc = htons(icmpv6Key->icmpv6_type); icmp6FlowPutKey->l4.tpDst = htons(icmpv6Key->icmpv6_code); if (keyAttrs[OVS_KEY_ATTR_ND]) { const struct ovs_key_nd *ndKey; ndKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_ND]); RtlCopyMemory(&icmp6FlowPutKey->ndTarget, ndKey->nd_target, sizeof (icmp6FlowPutKey->ndTarget)); RtlCopyMemory(icmp6FlowPutKey->arpSha, ndKey->nd_sll, ETH_ADDR_LEN); RtlCopyMemory(icmp6FlowPutKey->arpTha, ndKey->nd_tll, ETH_ADDR_LEN); } destKey->l2.keyLen += OVS_ICMPV6_KEY_SIZE; } else { destKey->l2.keyLen += OVS_IPV6_KEY_SIZE; } ipv6FlowPutKey->pad = 0; } break; } case ETH_TYPE_ARP: case ETH_TYPE_RARP: { if (keyAttrs[OVS_KEY_ATTR_ARP]) { ArpKey *arpFlowPutKey = &destKey->arpKey; const struct ovs_key_arp *arpKey; arpKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_ARP]); arpFlowPutKey->nwSrc = arpKey->arp_sip; arpFlowPutKey->nwDst = arpKey->arp_tip; RtlCopyMemory(arpFlowPutKey->arpSha, arpKey->arp_sha, ETH_ADDR_LEN); RtlCopyMemory(arpFlowPutKey->arpTha, arpKey->arp_tha, ETH_ADDR_LEN); /* Kernel datapath assumes 'arpFlowPutKey->nwProto' to be in host * order. */ arpFlowPutKey->nwProto = (UINT8)ntohs((arpKey->arp_op)); arpFlowPutKey->pad[0] = 0; arpFlowPutKey->pad[1] = 0; arpFlowPutKey->pad[2] = 0; destKey->l2.keyLen += OVS_ARP_KEY_SIZE; } break; } case ETH_TYPE_MPLS: case ETH_TYPE_MPLS_MCAST: { if (keyAttrs[OVS_KEY_ATTR_MPLS]) { MplsKey *mplsFlowPutKey = &destKey->mplsKey; const struct ovs_key_mpls *mplsKey; mplsKey = NlAttrGet(keyAttrs[OVS_KEY_ATTR_MPLS]); mplsFlowPutKey->lse = mplsKey->mpls_lse; mplsFlowPutKey->pad[0] = 0; mplsFlowPutKey->pad[1] = 0; mplsFlowPutKey->pad[2] = 0; mplsFlowPutKey->pad[3] = 0; destKey->l2.keyLen += OVS_MPLS_KEY_SIZE; } break; } } } /* *---------------------------------------------------------------------------- * OvsTunnelAttrToGeneveOptions -- * Converts OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS attribute to tunKey->tunOpts. *---------------------------------------------------------------------------- */ static __inline NTSTATUS OvsTunnelAttrToGeneveOptions(PNL_ATTR attr, OvsIPv4TunnelKey *tunKey) { UINT32 optLen = NlAttrGetSize(attr); GeneveOptionHdr *option; BOOLEAN isCritical = FALSE; if (optLen > TUN_OPT_MAX_LEN) { OVS_LOG_ERROR("Geneve option length err (len %d, max %Iu).", optLen, TUN_OPT_MAX_LEN); return STATUS_INFO_LENGTH_MISMATCH; } else if (optLen % 4 != 0) { OVS_LOG_ERROR("Geneve opt len %d is not a multiple of 4.", optLen); return STATUS_INFO_LENGTH_MISMATCH; } tunKey->tunOptLen = (UINT8)optLen; option = (GeneveOptionHdr *)NlAttrData(attr); while (optLen > 0) { UINT32 len; if (optLen < sizeof(*option)) { return STATUS_INFO_LENGTH_MISMATCH; } len = sizeof(*option) + option->length * 4; if (len > optLen) { return STATUS_INFO_LENGTH_MISMATCH; } if (option->type & GENEVE_CRIT_OPT_TYPE) { isCritical = TRUE; } option = (GeneveOptionHdr *)((UINT8 *)option + len); optLen -= len; } memcpy(TunnelKeyGetOptions(tunKey), NlAttrData(attr), tunKey->tunOptLen); if (isCritical) { tunKey->flags |= OVS_TNL_F_CRT_OPT; } return STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * OvsTunnelAttrToIPv4TunnelKey -- * Converts OVS_KEY_ATTR_TUNNEL attribute to tunKey. *---------------------------------------------------------------------------- */ NTSTATUS OvsTunnelAttrToIPv4TunnelKey(PNL_ATTR attr, OvsIPv4TunnelKey *tunKey) { PNL_ATTR a; INT rem; INT hasOpt = 0; NTSTATUS status; memset(tunKey, 0, OVS_WIN_TUNNEL_KEY_SIZE); ASSERT(NlAttrType(attr) == OVS_KEY_ATTR_TUNNEL); NL_ATTR_FOR_EACH_UNSAFE(a, rem, NlAttrData(attr), NlAttrGetSize(attr)) { switch (NlAttrType(a)) { case OVS_TUNNEL_KEY_ATTR_ID: tunKey->tunnelId = NlAttrGetBe64(a); tunKey->flags |= OVS_TNL_F_KEY; break; case OVS_TUNNEL_KEY_ATTR_IPV4_SRC: tunKey->src = NlAttrGetBe32(a); break; case OVS_TUNNEL_KEY_ATTR_IPV4_DST: tunKey->dst = NlAttrGetBe32(a); break; case OVS_TUNNEL_KEY_ATTR_TOS: tunKey->tos = NlAttrGetU8(a); break; case OVS_TUNNEL_KEY_ATTR_TTL: tunKey->ttl = NlAttrGetU8(a); break; case OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT: tunKey->flags |= OVS_TNL_F_DONT_FRAGMENT; break; case OVS_TUNNEL_KEY_ATTR_CSUM: tunKey->flags |= OVS_TNL_F_CSUM; break; case OVS_TUNNEL_KEY_ATTR_OAM: tunKey->flags |= OVS_TNL_F_OAM; break; case OVS_TUNNEL_KEY_ATTR_TP_DST: tunKey->dst_port = NlAttrGetBe16(a); break; case OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS: if (hasOpt) { /* Duplicate options attribute is not allowed. */ return NDIS_STATUS_FAILURE; } status = OvsTunnelAttrToGeneveOptions(a, tunKey); if (!SUCCEEDED(status)) { return status; } tunKey->flags |= OVS_TNL_F_GENEVE_OPT; hasOpt = 1; break; default: // XXX: Support OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS return STATUS_INVALID_PARAMETER; } } return STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * MapTunAttrToFlowPut -- * Converts FLOW_TUNNEL_KEY attribute to OvsFlowKey->tunKey. *---------------------------------------------------------------------------- */ VOID MapTunAttrToFlowPut(PNL_ATTR *keyAttrs, PNL_ATTR *tunAttrs, OvsFlowKey *destKey) { memset(&destKey->tunKey, 0, OVS_WIN_TUNNEL_KEY_SIZE); if (keyAttrs[OVS_KEY_ATTR_TUNNEL]) { /* XXX: This blocks performs same functionality as OvsTunnelAttrToIPv4TunnelKey. Consider refactoring the code.*/ if (tunAttrs[OVS_TUNNEL_KEY_ATTR_ID]) { destKey->tunKey.tunnelId = NlAttrGetU64(tunAttrs[OVS_TUNNEL_KEY_ATTR_ID]); destKey->tunKey.flags |= OVS_TNL_F_KEY; } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_IPV4_DST]) { destKey->tunKey.dst = NlAttrGetU32(tunAttrs[OVS_TUNNEL_KEY_ATTR_IPV4_DST]); } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_IPV4_SRC]) { destKey->tunKey.src = NlAttrGetU32(tunAttrs[OVS_TUNNEL_KEY_ATTR_IPV4_SRC]); } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT]) { destKey->tunKey.flags |= OVS_TNL_F_DONT_FRAGMENT; } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_CSUM]) { destKey->tunKey.flags |= OVS_TNL_F_CSUM; } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_TOS]) { destKey->tunKey.tos = NlAttrGetU8(tunAttrs[OVS_TUNNEL_KEY_ATTR_TOS]); } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_TTL]) { destKey->tunKey.ttl = NlAttrGetU8(tunAttrs[OVS_TUNNEL_KEY_ATTR_TTL]); } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_OAM]) { destKey->tunKey.flags |= OVS_TNL_F_OAM; } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_TP_DST]) { destKey->tunKey.dst_port = NlAttrGetU16(tunAttrs[OVS_TUNNEL_KEY_ATTR_TP_DST]); } if (tunAttrs[OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS]) { NTSTATUS status = OvsTunnelAttrToGeneveOptions( tunAttrs[OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS], &destKey->tunKey); if (SUCCEEDED(status)) { destKey->tunKey.flags |= OVS_TNL_F_GENEVE_OPT; } } destKey->l2.offset = OvsGetFlowL2Offset(&destKey->tunKey); } else { destKey->l2.offset = OvsGetFlowL2Offset(NULL); } } /* *---------------------------------------------------------------------------- * OvsDeleteFlowTable -- * Results: * NDIS_STATUS_SUCCESS always. *---------------------------------------------------------------------------- */ NDIS_STATUS OvsDeleteFlowTable(OVS_DATAPATH *datapath) { if (datapath == NULL || datapath->flowTable == NULL) { return NDIS_STATUS_SUCCESS; } DeleteAllFlows(datapath); OvsFreeMemoryWithTag(datapath->flowTable, OVS_FLOW_POOL_TAG); datapath->flowTable = NULL; if (datapath->lock == NULL) { return NDIS_STATUS_SUCCESS; } NdisFreeRWLock(datapath->lock); return NDIS_STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * OvsAllocateFlowTable -- * Results: * NDIS_STATUS_SUCCESS on success. * NDIS_STATUS_RESOURCES if memory couldn't be allocated *---------------------------------------------------------------------------- */ NDIS_STATUS OvsAllocateFlowTable(OVS_DATAPATH *datapath, POVS_SWITCH_CONTEXT switchContext) { PLIST_ENTRY bucket; int i; datapath->flowTable = OvsAllocateMemoryWithTag( OVS_FLOW_TABLE_SIZE * sizeof(LIST_ENTRY), OVS_FLOW_POOL_TAG); if (!datapath->flowTable) { return NDIS_STATUS_RESOURCES; } for (i = 0; i < OVS_FLOW_TABLE_SIZE; i++) { bucket = &(datapath->flowTable[i]); InitializeListHead(bucket); } datapath->lock = NdisAllocateRWLock(switchContext->NdisFilterHandle); if (!datapath->lock) { return NDIS_STATUS_RESOURCES; } return NDIS_STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * GetStartAddrNBL -- * Get the virtual address of the frame. * * Results: * Virtual address of the frame. *---------------------------------------------------------------------------- */ static __inline VOID * GetStartAddrNBL(const NET_BUFFER_LIST *_pNB) { PMDL curMdl; PUINT8 curBuffer; PEthHdr curHeader; ASSERT(_pNB); // Ethernet Header is a guaranteed safe access. curMdl = (NET_BUFFER_LIST_FIRST_NB(_pNB))->CurrentMdl; curBuffer = OvsGetMdlWithLowPriority(curMdl); if (!curBuffer) { return NULL; } curHeader = (PEthHdr) (curBuffer + (NET_BUFFER_LIST_FIRST_NB(_pNB))->CurrentMdlOffset); return (VOID *) curHeader; } VOID OvsFlowUsed(OvsFlow *flow, const NET_BUFFER_LIST *packet, const POVS_PACKET_HDR_INFO layers) { LARGE_INTEGER tickCount; KeQueryTickCount(&tickCount); flow->used = tickCount.QuadPart; flow->packetCount++; flow->byteCount += OvsPacketLenNBL(packet); flow->tcpFlags |= OvsGetTcpFlags(packet, &flow->key, layers); } VOID DeleteAllFlows(OVS_DATAPATH *datapath) { INT i; PLIST_ENTRY bucket; for (i = 0; i < OVS_FLOW_TABLE_SIZE; i++) { PLIST_ENTRY next; bucket = &(datapath->flowTable[i]); while (!IsListEmpty(bucket)) { OvsFlow *flow; next = bucket->Flink; flow = CONTAINING_RECORD(next, OvsFlow, ListEntry); RemoveFlow(datapath, &flow); } } } NDIS_STATUS OvsGetFlowMetadata(OvsFlowKey *key, PNL_ATTR *keyAttrs) { NDIS_STATUS status = NDIS_STATUS_SUCCESS; if (keyAttrs[OVS_KEY_ATTR_RECIRC_ID]) { key->recircId = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_RECIRC_ID]); } if (keyAttrs[OVS_KEY_ATTR_DP_HASH]) { key->dpHash = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_DP_HASH]); } if (keyAttrs[OVS_KEY_ATTR_CT_STATE]) { key->ct.state = (NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_STATE])); } if (keyAttrs[OVS_KEY_ATTR_CT_ZONE]) { key->ct.zone = (NlAttrGetU16(keyAttrs[OVS_KEY_ATTR_CT_ZONE])); } if (keyAttrs[OVS_KEY_ATTR_CT_MARK]) { key->ct.mark = (NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_MARK])); } if (keyAttrs[OVS_KEY_ATTR_CT_LABELS]) { const struct ovs_key_ct_labels *ct_labels; ct_labels = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_LABELS]); NdisMoveMemory(&key->ct.labels, ct_labels, sizeof(struct ovs_key_ct_labels)); } if (keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]) { const struct ovs_key_ct_tuple_ipv4 *tuple_ipv4; tuple_ipv4 = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]); NdisMoveMemory(&key->ct.tuple_ipv4, tuple_ipv4, sizeof(struct ovs_key_ct_tuple_ipv4)); } return status; } UINT16 OvsGetFlowL2Offset(const OvsIPv4TunnelKey *tunKey) { if (tunKey != NULL) { // Align with int64 boundary if (tunKey->tunOptLen == 0) { return (TUN_OPT_MAX_LEN + 1) / 8 * 8; } return TunnelKeyGetOptionsOffset(tunKey) / 8 * 8; } else { return OVS_WIN_TUNNEL_KEY_SIZE; } } /* *---------------------------------------------------------------------------- * Initializes 'layers' members from 'packet' * * Initializes 'layers' header pointers as follows: * * - layers->l2 to the start of the Ethernet header. * * - layers->l3 to just past the Ethernet header, or just past the * vlan_header if one is present, to the first byte of the payload of the * Ethernet frame. * * - layers->l4 to just past the IPv4 header, if one is present and has a * correct length, and otherwise NULL. * * - layers->l7 to just past the TCP, UDP, SCTP or ICMP header, if one is * present and has a correct length, and otherwise NULL. * * - layers->isIPv4/isIPv6/isTcp/isUdp/isSctp based on the packet type * * Returns NDIS_STATUS_SUCCESS normally. * Fails only if packet data cannot be accessed. * (e.g. if OvsParseIPv6() returns an error). *---------------------------------------------------------------------------- */ NDIS_STATUS OvsExtractLayers(const NET_BUFFER_LIST *packet, POVS_PACKET_HDR_INFO layers) { struct Eth_Header *eth; UINT8 offset = 0; PVOID vlanTagValue; ovs_be16 dlType; layers->value = 0; /* Link layer. */ eth = (Eth_Header *)GetStartAddrNBL((NET_BUFFER_LIST *)packet); /* * vlan_tci. */ vlanTagValue = NET_BUFFER_LIST_INFO(packet, Ieee8021QNetBufferListInfo); if (!vlanTagValue) { if (eth->dix.typeNBO == ETH_TYPE_802_1PQ_NBO) { offset = sizeof(Eth_802_1pq_Tag); } /* * XXX Please note after this point, src mac and dst mac should * not be accessed through eth */ eth = (Eth_Header *)((UINT8 *)eth + offset); } /* * dl_type. * * XXX assume that at least the first * 12 bytes of received packets are mapped. This code has the stronger * assumption that at least the first 22 bytes of 'packet' is mapped (if my * arithmetic is right). */ if (ETH_TYPENOT8023(eth->dix.typeNBO)) { dlType = eth->dix.typeNBO; layers->l3Offset = ETH_HEADER_LEN_DIX + offset; } else if (OvsPacketLenNBL(packet) >= ETH_HEADER_LEN_802_3 && eth->e802_3.llc.dsap == 0xaa && eth->e802_3.llc.ssap == 0xaa && eth->e802_3.llc.control == ETH_LLC_CONTROL_UFRAME && eth->e802_3.snap.snapOrg[0] == 0x00 && eth->e802_3.snap.snapOrg[1] == 0x00 && eth->e802_3.snap.snapOrg[2] == 0x00) { dlType = eth->e802_3.snap.snapType.typeNBO; layers->l3Offset = ETH_HEADER_LEN_802_3 + offset; } else { dlType = htons(OVSWIN_DL_TYPE_NONE); layers->l3Offset = ETH_HEADER_LEN_DIX + offset; } /* Network layer. */ if (dlType == htons(ETH_TYPE_IPV4)) { struct IPHdr ip_storage; const struct IPHdr *nh; layers->isIPv4 = 1; nh = OvsGetIp(packet, layers->l3Offset, &ip_storage); if (nh) { layers->l4Offset = layers->l3Offset + nh->ihl * 4; if (!(nh->frag_off & htons(IP_OFFSET))) { if (nh->protocol == SOCKET_IPPROTO_TCP) { OvsParseTcp(packet, NULL, layers); } else if (nh->protocol == SOCKET_IPPROTO_UDP) { OvsParseUdp(packet, NULL, layers); } else if (nh->protocol == SOCKET_IPPROTO_SCTP) { OvsParseSctp(packet, NULL, layers); } else if (nh->protocol == SOCKET_IPPROTO_ICMP) { ICMPHdr icmpStorage; const ICMPHdr *icmp; icmp = OvsGetIcmp(packet, layers->l4Offset, &icmpStorage); if (icmp) { layers->l7Offset = layers->l4Offset + sizeof *icmp; } } } } else { /* Invalid network header */ return NDIS_STATUS_INVALID_PACKET; } } else if (dlType == htons(ETH_TYPE_IPV6)) { NDIS_STATUS status; Ipv6Key ipv6Key; status = OvsParseIPv6(packet, &ipv6Key, layers); if (status != NDIS_STATUS_SUCCESS) { return status; } layers->isIPv6 = 1; if (ipv6Key.nwProto == SOCKET_IPPROTO_TCP) { OvsParseTcp(packet, &(ipv6Key.l4), layers); } else if (ipv6Key.nwProto == SOCKET_IPPROTO_UDP) { OvsParseUdp(packet, &(ipv6Key.l4), layers); } else if (ipv6Key.nwProto == SOCKET_IPPROTO_SCTP) { OvsParseSctp(packet, &ipv6Key.l4, layers); } else if (ipv6Key.nwProto == SOCKET_IPPROTO_ICMPV6) { Icmp6Key icmp6Key; OvsParseIcmpV6(packet, NULL, &icmp6Key, layers); } } else if (OvsEthertypeIsMpls(dlType)) { MPLSHdr mplsStorage; const MPLSHdr *mpls; /* * In the presence of an MPLS label stack the end of the L2 * header and the beginning of the L3 header differ. * * A network packet may contain multiple MPLS labels, but we * are only interested in the topmost label stack entry. * * Advance network header to the beginning of the L3 header. * layers->l3Offset corresponds to the end of the L2 header. */ for (UINT32 i = 0; i < FLOW_MAX_MPLS_LABELS; i++) { mpls = OvsGetMpls(packet, layers->l3Offset, &mplsStorage); if (!mpls) { break; } layers->l3Offset += MPLS_HLEN; layers->l4Offset += MPLS_HLEN; if (mpls->lse & htonl(MPLS_BOS_MASK)) { /* * Bottom of Stack bit is set, which means there are no * remaining MPLS labels in the packet. */ break; } } } return NDIS_STATUS_SUCCESS; } /* *---------------------------------------------------------------------------- * Initializes 'flow' members from 'packet', 'skb_priority', 'tun_id', and * 'ofp_in_port'. * * Initializes 'packet' header pointers as follows: * * - packet->l2 to the start of the Ethernet header. * * - packet->l3 to just past the Ethernet header, or just past the * vlan_header if one is present, to the first byte of the payload of the * Ethernet frame. * * - packet->l4 to just past the IPv4 header, if one is present and has a * correct length, and otherwise NULL. * * - packet->l7 to just past the TCP, UDP, SCTP or ICMP header, if one is * present and has a correct length, and otherwise NULL. * * Returns NDIS_STATUS_SUCCESS normally. * Fails only if packet data cannot be accessed. * (e.g. if Pkt_CopyBytesOut() returns an error). *---------------------------------------------------------------------------- */ NDIS_STATUS OvsExtractFlow(const NET_BUFFER_LIST *packet, UINT32 inPort, OvsFlowKey *flow, POVS_PACKET_HDR_INFO layers, OvsIPv4TunnelKey *tunKey) { struct Eth_Header *eth; UINT8 offset = 0; PVOID vlanTagValue; layers->value = 0; if (tunKey) { ASSERT(tunKey->dst != 0); UINT8 optOffset = TunnelKeyGetOptionsOffset(tunKey); RtlMoveMemory(((UINT8 *)&flow->tunKey) + optOffset, ((UINT8 *)tunKey) + optOffset, TunnelKeyGetRealSize(tunKey)); } else { flow->tunKey.dst = 0; } flow->l2.offset = OvsGetFlowL2Offset(tunKey); flow->l2.inPort = inPort; if (OvsPacketLenNBL(packet) < ETH_HEADER_LEN_DIX) { flow->l2.keyLen = OVS_WIN_TUNNEL_KEY_SIZE + 8 - flow->l2.offset; return NDIS_STATUS_SUCCESS; } /* Link layer. */ eth = (Eth_Header *)GetStartAddrNBL((NET_BUFFER_LIST *)packet); RtlCopyMemory(flow->l2.dlSrc, eth->src, ETH_ADDR_LENGTH); RtlCopyMemory(flow->l2.dlDst, eth->dst, ETH_ADDR_LENGTH); /* * vlan_tci. */ vlanTagValue = NET_BUFFER_LIST_INFO(packet, Ieee8021QNetBufferListInfo); if (vlanTagValue) { PNDIS_NET_BUFFER_LIST_8021Q_INFO vlanTag = (PNDIS_NET_BUFFER_LIST_8021Q_INFO)(PVOID *)&vlanTagValue; flow->l2.vlanKey.vlanTci = htons(vlanTag->TagHeader.VlanId | OVSWIN_VLAN_CFI | (vlanTag->TagHeader.UserPriority << 13)); flow->l2.vlanKey.vlanTpid = htons(ETH_TYPE_802_1PQ); } else { if (eth->dix.typeNBO == ETH_TYPE_802_1PQ_NBO) { Eth_802_1pq_Tag *tag= (Eth_802_1pq_Tag *)&eth->dix.typeNBO; flow->l2.vlanKey.vlanTci = htons(((UINT16)tag->priority << 13) | OVSWIN_VLAN_CFI | ((UINT16)tag->vidHi << 8) | tag->vidLo); flow->l2.vlanKey.vlanTpid = htons(ETH_TYPE_802_1PQ); offset = sizeof (Eth_802_1pq_Tag); } else { /* Initialize vlan key to 0 for non vlan packets. */ flow->l2.vlanKey.vlanTci = 0; flow->l2.vlanKey.vlanTpid = 0; } /* * XXX Please note after this point, src mac and dst mac should * not be accessed through eth */ eth = (Eth_Header *)((UINT8 *)eth + offset); } /* * dl_type. * * XXX assume that at least the first * 12 bytes of received packets are mapped. This code has the stronger * assumption that at least the first 22 bytes of 'packet' is mapped (if my * arithmetic is right). */ if (ETH_TYPENOT8023(eth->dix.typeNBO)) { flow->l2.dlType = eth->dix.typeNBO; layers->l3Offset = ETH_HEADER_LEN_DIX + offset; } else if (OvsPacketLenNBL(packet) >= ETH_HEADER_LEN_802_3 && eth->e802_3.llc.dsap == 0xaa && eth->e802_3.llc.ssap == 0xaa && eth->e802_3.llc.control == ETH_LLC_CONTROL_UFRAME && eth->e802_3.snap.snapOrg[0] == 0x00 && eth->e802_3.snap.snapOrg[1] == 0x00 && eth->e802_3.snap.snapOrg[2] == 0x00) { flow->l2.dlType = eth->e802_3.snap.snapType.typeNBO; layers->l3Offset = ETH_HEADER_LEN_802_3 + offset; } else { flow->l2.dlType = htons(OVSWIN_DL_TYPE_NONE); layers->l3Offset = ETH_HEADER_LEN_DIX + offset; } flow->l2.keyLen = OVS_WIN_TUNNEL_KEY_SIZE + OVS_L2_KEY_SIZE - flow->l2.offset; /* Network layer. */ if (flow->l2.dlType == htons(ETH_TYPE_IPV4)) { struct IPHdr ip_storage; const struct IPHdr *nh; IpKey *ipKey = &flow->ipKey; flow->l2.keyLen += OVS_IP_KEY_SIZE; layers->isIPv4 = 1; nh = OvsGetIp(packet, layers->l3Offset, &ip_storage); if (nh) { layers->l4Offset = layers->l3Offset + nh->ihl * 4; ipKey->nwSrc = nh->saddr; ipKey->nwDst = nh->daddr; ipKey->nwProto = nh->protocol; ipKey->nwTos = nh->tos; if (nh->frag_off & htons(IP_MF | IP_OFFSET)) { ipKey->nwFrag = OVS_FRAG_TYPE_FIRST; if (nh->frag_off & htons(IP_OFFSET)) { ipKey->nwFrag = OVS_FRAG_TYPE_LATER; } } else { ipKey->nwFrag = OVS_FRAG_TYPE_NONE; } ipKey->nwTtl = nh->ttl; ipKey->l4.tpSrc = 0; ipKey->l4.tpDst = 0; if (!(nh->frag_off & htons(IP_OFFSET))) { if (ipKey->nwProto == SOCKET_IPPROTO_TCP) { OvsParseTcp(packet, &ipKey->l4, layers); } else if (ipKey->nwProto == SOCKET_IPPROTO_UDP) { OvsParseUdp(packet, &ipKey->l4, layers); } else if (ipKey->nwProto == SOCKET_IPPROTO_SCTP) { OvsParseSctp(packet, &ipKey->l4, layers); } else if (ipKey->nwProto == SOCKET_IPPROTO_ICMP) { ICMPHdr icmpStorage; const ICMPHdr *icmp; icmp = OvsGetIcmp(packet, layers->l4Offset, &icmpStorage); if (icmp) { ipKey->l4.tpSrc = htons(icmp->type); ipKey->l4.tpDst = htons(icmp->code); layers->l7Offset = layers->l4Offset + sizeof *icmp; } } } } else { /* Invalid network header */ ((UINT64 *)ipKey)[0] = 0; ((UINT64 *)ipKey)[1] = 0; return NDIS_STATUS_INVALID_PACKET; } } else if (flow->l2.dlType == htons(ETH_TYPE_IPV6)) { NDIS_STATUS status; flow->l2.keyLen += OVS_IPV6_KEY_SIZE; status = OvsParseIPv6(packet, &flow->ipv6Key, layers); if (status != NDIS_STATUS_SUCCESS) { RtlZeroMemory(&flow->ipv6Key, sizeof (Ipv6Key)); return status; } layers->isIPv6 = 1; flow->ipv6Key.l4.tpSrc = 0; flow->ipv6Key.l4.tpDst = 0; flow->ipv6Key.pad = 0; if (flow->ipv6Key.nwProto == SOCKET_IPPROTO_TCP) { OvsParseTcp(packet, &(flow->ipv6Key.l4), layers); } else if (flow->ipv6Key.nwProto == SOCKET_IPPROTO_UDP) { OvsParseUdp(packet, &(flow->ipv6Key.l4), layers); } else if (flow->ipv6Key.nwProto == SOCKET_IPPROTO_SCTP) { OvsParseSctp(packet, &flow->ipv6Key.l4, layers); } else if (flow->ipv6Key.nwProto == SOCKET_IPPROTO_ICMPV6) { OvsParseIcmpV6(packet, &flow->ipv6Key, &flow->icmp6Key, layers); flow->l2.keyLen += (OVS_ICMPV6_KEY_SIZE - OVS_IPV6_KEY_SIZE); } } else if (flow->l2.dlType == htons(ETH_TYPE_ARP)) { EtherArp arpStorage; const EtherArp *arp; ArpKey *arpKey = &flow->arpKey; ((UINT64 *)arpKey)[0] = 0; ((UINT64 *)arpKey)[1] = 0; ((UINT64 *)arpKey)[2] = 0; flow->l2.keyLen += OVS_ARP_KEY_SIZE; arp = OvsGetArp(packet, layers->l3Offset, &arpStorage); if (arp && arp->ea_hdr.ar_hrd == htons(1) && arp->ea_hdr.ar_pro == htons(ETH_TYPE_IPV4) && arp->ea_hdr.ar_hln == ETH_ADDR_LENGTH && arp->ea_hdr.ar_pln == 4) { /* We only match on the lower 8 bits of the opcode. */ if (ntohs(arp->ea_hdr.ar_op) <= 0xff) { arpKey->nwProto = (UINT8)ntohs(arp->ea_hdr.ar_op); } if (arpKey->nwProto == ARPOP_REQUEST || arpKey->nwProto == ARPOP_REPLY) { RtlCopyMemory(&arpKey->nwSrc, arp->arp_spa, 4); RtlCopyMemory(&arpKey->nwDst, arp->arp_tpa, 4); RtlCopyMemory(arpKey->arpSha, arp->arp_sha, ETH_ADDR_LENGTH); RtlCopyMemory(arpKey->arpTha, arp->arp_tha, ETH_ADDR_LENGTH); } } } else if (OvsEthertypeIsMpls(flow->l2.dlType)) { MPLSHdr mplsStorage; const MPLSHdr *mpls; MplsKey *mplsKey = &flow->mplsKey; ((UINT64 *)mplsKey)[0] = 0; flow->l2.keyLen += OVS_MPLS_KEY_SIZE; /* * In the presence of an MPLS label stack the end of the L2 * header and the beginning of the L3 header differ. * * A network packet may contain multiple MPLS labels, but we * are only interested in the topmost label stack entry. * * Advance network header to the beginning of the L3 header. * layers->l3Offset corresponds to the end of the L2 header. */ for (UINT32 i = 0; i < FLOW_MAX_MPLS_LABELS; i++) { mpls = OvsGetMpls(packet, layers->l3Offset, &mplsStorage); if (!mpls) { break; } /* Keep only the topmost MPLS label stack entry. */ if (i == 0) { mplsKey->lse = mpls->lse; } layers->l3Offset += MPLS_HLEN; layers->l4Offset += MPLS_HLEN; if (mpls->lse & htonl(MPLS_BOS_MASK)) { /* * Bottom of Stack bit is set, which means there are no * remaining MPLS labels in the packet. */ break; } } } return NDIS_STATUS_SUCCESS; } __inline BOOLEAN FlowMemoryEqual(UINT64 *src, UINT64 *dst, UINT32 size) { UINT32 i; ASSERT((size & 0x7) == 0); ASSERT(((UINT64)src & 0x7) == 0); ASSERT(((UINT64)dst & 0x7) == 0); for (i = 0; i < (size >> 3); i++) { if (src[i] != dst[i]) { return FALSE; } } return TRUE; } __inline BOOLEAN FlowEqual(OvsFlow *srcFlow, const OvsFlowKey *dstKey, UINT8 *dstStart, UINT64 hash, UINT32 offset, UINT16 size) { return (srcFlow->hash == hash && srcFlow->key.l2.val == dstKey->l2.val && srcFlow->key.recircId == dstKey->recircId && srcFlow->key.dpHash == dstKey->dpHash && srcFlow->key.ct.state == dstKey->ct.state && srcFlow->key.ct.zone == dstKey->ct.zone && srcFlow->key.ct.mark == dstKey->ct.mark && !memcmp(&srcFlow->key.ct.labels, &dstKey->ct.labels, sizeof(struct ovs_key_ct_labels)) && !memcmp(&srcFlow->key.ct.tuple_ipv4, &dstKey->ct.tuple_ipv4, sizeof(struct ovs_key_ct_tuple_ipv4)) && FlowMemoryEqual((UINT64 *)((UINT8 *)&srcFlow->key + offset), (UINT64 *) dstStart, size)); } /* * ---------------------------------------------------------------------------- * AddFlow -- * Add a flow to flow table. * * Results: * NDIS_STATUS_SUCCESS if no same flow in the flow table. * ---------------------------------------------------------------------------- */ NTSTATUS AddFlow(OVS_DATAPATH *datapath, OvsFlow *flow) { PLIST_ENTRY head; if (OvsLookupFlow(datapath, &flow->key, &flow->hash, TRUE) != NULL) { return STATUS_INVALID_HANDLE; } head = &(datapath->flowTable[HASH_BUCKET(flow->hash)]); /* * We need fence here to make sure flow's nextPtr is updated before * head->nextPtr is updated. */ KeMemoryBarrier(); //KeAcquireSpinLock(&FilterDeviceExtension->NblQueueLock, &oldIrql); InsertTailList(head, &flow->ListEntry); //KeReleaseSpinLock(&FilterDeviceExtension->NblQueueLock, oldIrql); datapath->nFlows++; return STATUS_SUCCESS; } /* ---------------------------------------------------------------------------- * RemoveFlow -- * Remove a flow from flow table, and added to wait list * ---------------------------------------------------------------------------- */ VOID RemoveFlow(OVS_DATAPATH *datapath, OvsFlow **flow) { OvsFlow *f = *flow; *flow = NULL; ASSERT(datapath->nFlows); datapath->nFlows--; // Remove the flow from queue RemoveEntryList(&f->ListEntry); FreeFlow(f); } /* * ---------------------------------------------------------------------------- * OvsLookupFlow -- * * Find flow from flow table based on flow key. * Caller should either hold portset handle or should * have a flowRef in datapath or Acquired datapath. * * Results: * Flow pointer if lookup successful. * NULL if not exists. * ---------------------------------------------------------------------------- */ OvsFlow * OvsLookupFlow(OVS_DATAPATH *datapath, const OvsFlowKey *key, UINT64 *hash, BOOLEAN hashValid) { PLIST_ENTRY link, head; UINT16 offset = key->l2.offset; UINT16 size = key->l2.keyLen; UINT8 *start; ASSERT(key->tunKey.dst || offset == sizeof(OvsIPv4TunnelKey)); ASSERT(!key->tunKey.dst || offset == OvsGetFlowL2Offset(&key->tunKey)); start = (UINT8 *)key + offset; if (!hashValid) { *hash = OvsJhashBytes(start, size, 0); if (key->recircId) { *hash = OvsJhashWords((UINT32*)hash, 1, key->recircId); } if (key->dpHash) { *hash = OvsJhashWords((UINT32*)hash, 1, key->dpHash); } if (key->ct.state) { *hash = OvsJhashWords((UINT32*)hash, 1, key->ct.state); } if (key->ct.zone) { *hash = OvsJhashWords((UINT32*)hash, 1, key->ct.zone); } if (key->ct.mark) { *hash = OvsJhashWords((UINT32*)hash, 1, key->ct.mark); } if (key->ct.labels.ct_labels) { UINT32 lblHash = OvsJhashBytes(&key->ct.labels, sizeof(struct ovs_key_ct_labels), 0); *hash = OvsJhashWords((UINT32*)hash, 1, lblHash); } if (key->ct.tuple_ipv4.ipv4_src) { UINT32 tupleHash = OvsJhashBytes( &key->ct.tuple_ipv4, sizeof(struct ovs_key_ct_tuple_ipv4), 0); *hash = OvsJhashWords((UINT32*)hash, 1, tupleHash); } } head = &datapath->flowTable[HASH_BUCKET(*hash)]; link = head->Flink; while (link != head) { OvsFlow *flow = CONTAINING_RECORD(link, OvsFlow, ListEntry); if (FlowEqual(flow, key, start, *hash, offset, size)) { return flow; } link = link->Flink; } return NULL; } /* * ---------------------------------------------------------------------------- * OvsHashFlow -- * Calculate the hash for the given flow key. * ---------------------------------------------------------------------------- */ UINT64 OvsHashFlow(const OvsFlowKey *key) { UINT16 offset = key->l2.offset; UINT16 size = key->l2.keyLen; UINT8 *start; ASSERT(key->tunKey.dst || offset == sizeof(OvsIPv4TunnelKey)); ASSERT(!key->tunKey.dst || offset == OvsGetFlowL2Offset(&key->tunKey)); start = (UINT8 *)key + offset; return OvsJhashBytes(start, size, 0); } /* * ---------------------------------------------------------------------------- * FreeFlow -- * Free a flow and its actions. * ---------------------------------------------------------------------------- */ VOID FreeFlow(OvsFlow *flow) { ASSERT(flow); OvsFreeMemoryWithTag(flow, OVS_FLOW_POOL_TAG); } NTSTATUS OvsDoDumpFlows(OvsFlowDumpInput *dumpInput, OvsFlowDumpOutput *dumpOutput, UINT32 *replyLen) { UINT32 dpNo; OVS_DATAPATH *datapath = NULL; OvsFlow *flow; PLIST_ENTRY node, head; UINT32 column = 0; UINT32 rowIndex, columnIndex; LOCK_STATE_EX dpLockState; NTSTATUS status = STATUS_SUCCESS; BOOLEAN findNextNonEmpty = FALSE; dpNo = dumpInput->dpNo; if (gOvsSwitchContext->dpNo != dpNo) { status = STATUS_INVALID_PARAMETER; goto exit; } rowIndex = dumpInput->position[0]; if (rowIndex >= OVS_FLOW_TABLE_SIZE) { dumpOutput->n = 0; *replyLen = sizeof(*dumpOutput); goto exit; } columnIndex = dumpInput->position[1]; datapath = &gOvsSwitchContext->datapath; ASSERT(datapath); OvsAcquireDatapathRead(datapath, &dpLockState, FALSE); head = &datapath->flowTable[rowIndex]; node = head->Flink; while (column < columnIndex) { if (node == head) { break; } node = node->Flink; column++; } if (node == head) { findNextNonEmpty = TRUE; columnIndex = 0; } if (findNextNonEmpty) { while (head == node) { if (++rowIndex >= OVS_FLOW_TABLE_SIZE) { dumpOutput->n = 0; goto dp_unlock; } head = &datapath->flowTable[rowIndex]; node = head->Flink; } } ASSERT(node != head); ASSERT(rowIndex < OVS_FLOW_TABLE_SIZE); flow = CONTAINING_RECORD(node, OvsFlow, ListEntry); status = ReportFlowInfo(flow, dumpInput->getFlags, &dumpOutput->flow); if (status == STATUS_BUFFER_TOO_SMALL) { dumpOutput->n = sizeof(OvsFlowDumpOutput) + flow->actionsLen; *replyLen = sizeof(*dumpOutput); } else { dumpOutput->n = 1; //one flow reported. *replyLen = sizeof(*dumpOutput) + dumpOutput->flow.actionsLen; } dumpOutput->position[0] = rowIndex; dumpOutput->position[1] = ++columnIndex; dp_unlock: OvsReleaseDatapath(datapath, &dpLockState); exit: return status; } static NTSTATUS ReportFlowInfo(OvsFlow *flow, UINT32 getFlags, OvsFlowInfo *info) { NTSTATUS status = STATUS_SUCCESS; if (getFlags & FLOW_GET_KEY) { // always copy the tunnel key part RtlCopyMemory(&info->key, &flow->key, flow->key.l2.keyLen + flow->key.l2.offset); } if (getFlags & FLOW_GET_STATS) { OvsFlowStats *stats = &info->stats; stats->packetCount = flow->packetCount; stats->byteCount = flow->byteCount; stats->used = flow->used; stats->tcpFlags = flow->tcpFlags; } if (getFlags & FLOW_GET_ACTIONS) { if (flow->actionsLen == 0) { info->actionsLen = 0; } else { info->actions = flow->actions; info->actionsLen = flow->actionsLen; } } info->key.recircId = flow->key.recircId; info->key.dpHash = flow->key.dpHash; info->key.ct.state = flow->key.ct.state; info->key.ct.zone = flow->key.ct.zone; info->key.ct.mark = flow->key.ct.mark; NdisMoveMemory(&info->key.ct.labels, &flow->key.ct.labels, sizeof(struct ovs_key_ct_labels)); NdisMoveMemory(&info->key.ct.tuple_ipv4, &flow->key.ct.tuple_ipv4, sizeof(struct ovs_key_ct_tuple_ipv4)); return status; } NTSTATUS OvsPutFlowIoctl(PVOID inputBuffer, UINT32 inputLength, struct OvsFlowStats *stats) { NTSTATUS status = STATUS_SUCCESS; OVS_DATAPATH *datapath = NULL; ULONG actionsLen; OvsFlowPut *put; UINT32 dpNo; LOCK_STATE_EX dpLockState; if ((inputLength < sizeof(OvsFlowPut)) || (inputBuffer == NULL)) { return STATUS_INFO_LENGTH_MISMATCH; } put = (OvsFlowPut *)inputBuffer; if (put->actionsLen > 0) { actionsLen = put->actionsLen; } else { actionsLen = 0; } dpNo = put->dpNo; if (gOvsSwitchContext->dpNo != dpNo) { status = STATUS_INVALID_PARAMETER; goto exit; } datapath = &gOvsSwitchContext->datapath; ASSERT(datapath); OvsAcquireDatapathWrite(datapath, &dpLockState, FALSE); status = HandleFlowPut(put, datapath, stats); OvsReleaseDatapath(datapath, &dpLockState); exit: return status; } /* Handles flow add, modify as well as delete */ static NTSTATUS HandleFlowPut(OvsFlowPut *put, OVS_DATAPATH *datapath, struct OvsFlowStats *stats) { BOOLEAN mayCreate, mayModify, mayDelete; OvsFlow *KernelFlow; UINT64 hash; NTSTATUS status = STATUS_SUCCESS; mayCreate = (put->flags & OVSWIN_FLOW_PUT_CREATE) != 0; mayModify = (put->flags & OVSWIN_FLOW_PUT_MODIFY) != 0; mayDelete = (put->flags & OVSWIN_FLOW_PUT_DELETE) != 0; if ((mayCreate || mayModify) == mayDelete) { return STATUS_INVALID_PARAMETER; } KernelFlow = OvsLookupFlow(datapath, &put->key, &hash, FALSE); if (!KernelFlow) { if (!mayCreate) { return STATUS_INVALID_PARAMETER; } status = OvsPrepareFlow(&KernelFlow, put, hash); if (status != STATUS_SUCCESS) { return STATUS_UNSUCCESSFUL; } status = AddFlow(datapath, KernelFlow); if (status != STATUS_SUCCESS) { FreeFlow(KernelFlow); return STATUS_UNSUCCESSFUL; } #if DBG /* Validate the flow addition */ { UINT64 newHash; OvsFlow *flow = OvsLookupFlow(datapath, &put->key, &newHash, FALSE); ASSERT(flow); ASSERT(newHash == hash); if (!flow || newHash != hash) { return STATUS_UNSUCCESSFUL; } } #endif } else { stats->packetCount = KernelFlow->packetCount; stats->byteCount = KernelFlow->byteCount; stats->tcpFlags = KernelFlow->tcpFlags; stats->used = KernelFlow->used; if (mayModify) { OvsFlow *newFlow; status = OvsPrepareFlow(&newFlow, put, hash); if (status != STATUS_SUCCESS) { return STATUS_UNSUCCESSFUL; } if ((put->flags & OVSWIN_FLOW_PUT_CLEAR) == 0) { newFlow->packetCount = KernelFlow->packetCount; newFlow->byteCount = KernelFlow->byteCount; newFlow->tcpFlags = KernelFlow->tcpFlags; newFlow->used = KernelFlow->used; } RemoveFlow(datapath, &KernelFlow); status = AddFlow(datapath, newFlow); ASSERT(status == STATUS_SUCCESS); #if DBG /* Validate the flow addition */ { UINT64 newHash; OvsFlow *testflow = OvsLookupFlow(datapath, &put->key, &newHash, FALSE); ASSERT(testflow); ASSERT(newHash == hash); if (!testflow || newHash != hash) { FreeFlow(newFlow); return STATUS_UNSUCCESSFUL; } } #endif } else { if (mayDelete) { if (KernelFlow) { RemoveFlow(datapath, &KernelFlow); } } else { /* Return duplicate if an identical flow already exists. */ return STATUS_DUPLICATE_NAME; } } } return STATUS_SUCCESS; } static NTSTATUS OvsPrepareFlow(OvsFlow **flow, const OvsFlowPut *put, UINT64 hash) { OvsFlow *localFlow = *flow; NTSTATUS status = STATUS_SUCCESS; do { *flow = localFlow = OvsAllocateMemoryWithTag(sizeof(OvsFlow) + put->actionsLen, OVS_FLOW_POOL_TAG); if (localFlow == NULL) { status = STATUS_NO_MEMORY; break; } localFlow->key = put->key; localFlow->actionsLen = put->actionsLen; if (put->actionsLen) { NdisMoveMemory((PUCHAR)localFlow->actions, put->actions, put->actionsLen); } localFlow->userActionsLen = 0; // 0 indicate no conversion is made localFlow->used = 0; localFlow->packetCount = 0; localFlow->byteCount = 0; localFlow->tcpFlags = 0; localFlow->hash = hash; } while(FALSE); return status; } NTSTATUS OvsGetFlowIoctl(PVOID inputBuffer, PVOID outputBuffer) { NTSTATUS status = STATUS_SUCCESS; OVS_DATAPATH *datapath = NULL; OvsFlow *flow; UINT32 getFlags, getActionsLen; OvsFlowGetInput *getInput; OvsFlowGetOutput *getOutput; UINT64 hash; UINT32 dpNo; LOCK_STATE_EX dpLockState; getInput = (OvsFlowGetInput *) inputBuffer; getFlags = getInput->getFlags; getActionsLen = getInput->actionsLen; if (outputBuffer == NULL) { return STATUS_INFO_LENGTH_MISMATCH; } dpNo = getInput->dpNo; if (gOvsSwitchContext->dpNo != dpNo) { status = STATUS_INVALID_PARAMETER; goto exit; } datapath = &gOvsSwitchContext->datapath; ASSERT(datapath); OvsAcquireDatapathRead(datapath, &dpLockState, FALSE); flow = OvsLookupFlow(datapath, &getInput->key, &hash, FALSE); if (!flow) { status = STATUS_INVALID_PARAMETER; goto dp_unlock; } getOutput = (OvsFlowGetOutput *)outputBuffer; ReportFlowInfo(flow, getFlags, &getOutput->info); dp_unlock: OvsReleaseDatapath(datapath, &dpLockState); exit: return status; } NTSTATUS OvsFlushFlowIoctl(UINT32 dpNo) { NTSTATUS status = STATUS_SUCCESS; OVS_DATAPATH *datapath = NULL; LOCK_STATE_EX dpLockState; if (gOvsSwitchContext->dpNo != dpNo) { status = STATUS_INVALID_PARAMETER; goto exit; } datapath = &gOvsSwitchContext->datapath; ASSERT(datapath); OvsAcquireDatapathWrite(datapath, &dpLockState, FALSE); DeleteAllFlows(datapath); OvsReleaseDatapath(datapath, &dpLockState); exit: return status; } UINT32 OvsFlowKeyAttrSize(void) { return NlAttrTotalSize(4) /* OVS_KEY_ATTR_PRIORITY */ + NlAttrTotalSize(0) /* OVS_KEY_ATTR_TUNNEL */ + OvsTunKeyAttrSize() + NlAttrTotalSize(4) /* OVS_KEY_ATTR_IN_PORT */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_SKB_MARK */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_DP_HASH */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_RECIRC_ID */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_CT_STATE */ + NlAttrTotalSize(2) /* OVS_KEY_ATTR_CT_ZONE */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_CT_MARK */ + NlAttrTotalSize(16) /* OVS_KEY_ATTR_CT_LABELS */ + NlAttrTotalSize(13) /* OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4 */ + NlAttrTotalSize(12) /* OVS_KEY_ATTR_ETHERNET */ + NlAttrTotalSize(2) /* OVS_KEY_ATTR_ETHERTYPE */ + NlAttrTotalSize(4) /* OVS_KEY_ATTR_VLAN */ + NlAttrTotalSize(0) /* OVS_KEY_ATTR_ENCAP */ + NlAttrTotalSize(2) /* OVS_KEY_ATTR_ETHERTYPE */ + NlAttrTotalSize(40) /* OVS_KEY_ATTR_IPV6 */ + NlAttrTotalSize(2) /* OVS_KEY_ATTR_ICMPV6 */ + NlAttrTotalSize(28); /* OVS_KEY_ATTR_ND */ } UINT32 OvsTunKeyAttrSize(void) { /* Whenever adding new OVS_TUNNEL_KEY_ FIELDS, we should consider * updating this function. */ return NlAttrTotalSize(8) /* OVS_TUNNEL_KEY_ATTR_ID */ + NlAttrTotalSize(4) /* OVS_TUNNEL_KEY_ATTR_IPV4_SRC */ + NlAttrTotalSize(4) /* OVS_TUNNEL_KEY_ATTR_IPV4_DST */ + NlAttrTotalSize(1) /* OVS_TUNNEL_KEY_ATTR_TOS */ + NlAttrTotalSize(1) /* OVS_TUNNEL_KEY_ATTR_TTL */ + NlAttrTotalSize(0) /* OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT */ + NlAttrTotalSize(0) /* OVS_TUNNEL_KEY_ATTR_CSUM */ + NlAttrTotalSize(0) /* OVS_TUNNEL_KEY_ATTR_OAM */ + NlAttrTotalSize(256) /* OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS */ + NlAttrTotalSize(2) /* OVS_TUNNEL_KEY_ATTR_TP_SRC */ + NlAttrTotalSize(2); /* OVS_TUNNEL_KEY_ATTR_TP_DST */ } /* *---------------------------------------------------------------------------- * OvsProbeSupportedFeature -- * Verifies if the probed feature is supported. * * Results: * STATUS_SUCCESS if the probed feature is supported. *---------------------------------------------------------------------------- */ static NTSTATUS OvsProbeSupportedFeature(POVS_MESSAGE msgIn, PNL_ATTR keyAttr) { NTSTATUS status = STATUS_SUCCESS; PNL_MSG_HDR nlMsgHdr = &(msgIn->nlMsg); UINT32 keyAttrOffset = (UINT32)((PCHAR)keyAttr - (PCHAR)nlMsgHdr); UINT32 encapOffset = 0; PNL_ATTR keyAttrs[__OVS_KEY_ATTR_MAX] = { NULL }; PNL_ATTR encapAttrs[__OVS_KEY_ATTR_MAX] = { NULL }; /* Get flow keys attributes */ if ((NlAttrParseNested(nlMsgHdr, keyAttrOffset, NlAttrLen(keyAttr), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), keyAttrs, ARRAY_SIZE(keyAttrs))) != TRUE) { OVS_LOG_ERROR("Key Attr Parsing failed for msg: %p", nlMsgHdr); status = STATUS_INVALID_PARAMETER; goto done; } if (keyAttrs[OVS_KEY_ATTR_ENCAP]) { encapOffset = (UINT32)((PCHAR)(keyAttrs[OVS_KEY_ATTR_ENCAP]) - (PCHAR)nlMsgHdr); /* Get tunnel keys attributes */ if ((NlAttrParseNested(nlMsgHdr, encapOffset, NlAttrLen(keyAttrs[OVS_KEY_ATTR_ENCAP]), nlFlowKeyPolicy, ARRAY_SIZE(nlFlowKeyPolicy), encapAttrs, ARRAY_SIZE(encapAttrs))) != TRUE) { OVS_LOG_ERROR("Encap Key Attr Parsing failed for msg: %p", nlMsgHdr); status = STATUS_INVALID_PARAMETER; goto done; } } if (keyAttrs[OVS_KEY_ATTR_MPLS] && keyAttrs[OVS_KEY_ATTR_ETHERTYPE]) { ovs_be16 ethType = NlAttrGetU16(keyAttrs[OVS_KEY_ATTR_ETHERTYPE]); if (OvsEthertypeIsMpls(ethType)) { if (!OvsCountMplsLabels(keyAttrs[OVS_KEY_ATTR_MPLS])) { OVS_LOG_ERROR("Maximum supported MPLS labels exceeded."); status = STATUS_INVALID_MESSAGE; } } else { OVS_LOG_ERROR("Wrong ethertype for MPLS attribute."); status = STATUS_INVALID_PARAMETER; } } else if (keyAttrs[OVS_KEY_ATTR_RECIRC_ID]) { UINT32 recircId = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_RECIRC_ID]); if (!recircId) { OVS_LOG_ERROR("Invalid recirculation ID."); status = STATUS_INVALID_PARAMETER; } } else if (keyAttrs[OVS_KEY_ATTR_CT_STATE]) { UINT32 state = NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_STATE]); if (!state) { status = STATUS_INVALID_PARAMETER; OVS_LOG_ERROR("Invalid state specified."); } } else if (keyAttrs[OVS_KEY_ATTR_CT_ZONE]) { UINT16 zone = (NlAttrGetU16(keyAttrs[OVS_KEY_ATTR_CT_ZONE])); if (!zone) { OVS_LOG_ERROR("Invalid zone specified."); status = STATUS_INVALID_PARAMETER; } } else if (keyAttrs[OVS_KEY_ATTR_CT_MARK]) { UINT32 mark = (NlAttrGetU32(keyAttrs[OVS_KEY_ATTR_CT_MARK])); if (!mark) { OVS_LOG_ERROR("Invalid ct mark specified."); status = STATUS_INVALID_PARAMETER; } } else if (keyAttrs[OVS_KEY_ATTR_CT_LABELS]) { const struct ovs_key_ct_labels *ct_labels; ct_labels = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_LABELS]); if (!ct_labels->ct_labels) { OVS_LOG_ERROR("Invalid ct label specified."); status = STATUS_INVALID_PARAMETER; } } else if (keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]) { const struct ovs_key_ct_tuple_ipv4 *ct_tuple_ipv4; ct_tuple_ipv4 = NlAttrGet(keyAttrs[OVS_KEY_ATTR_CT_ORIG_TUPLE_IPV4]); if (!ct_tuple_ipv4) { OVS_LOG_ERROR("Invalid ct_tuple_ipv4."); status = STATUS_INVALID_PARAMETER; } } else { OVS_LOG_ERROR("Feature not supported."); status = STATUS_INVALID_PARAMETER; } done: return status; } #pragma warning( pop )
467580.c
#ifdef HAVE_XORG_CONFIG_H #include <xorg-config.h> #endif #include <X11/X.h> #include "os.h" #include "xf86.h" #include "xf86Priv.h" /* * Utility functions required by libxf86_os. */ _X_EXPORT void FatalError(const char *f, ...) { va_list args; va_start(args, f); fprintf(stderr, "Fatal Error:\n"); vfprintf(stderr, f, args); va_end(args); exit(1); }
708369.c
/* * PicoDrive * (C) notaz, 2010 * * This work is licensed under the terms of MAME license. * See COPYING file in the top-level directory. */ #include "pico_int.h" #include <zlib.h> #include "../cpu/sh2/sh2.h" #include "sound/ym2612.h" #include "state.h" // sn76496 extern int *sn76496_regs; static arearw *areaRead; static arearw *areaWrite; static areaeof *areaEof; static areaseek *areaSeek; static areaclose *areaClose; carthw_state_chunk *carthw_chunks; void (*PicoStateProgressCB)(const char *str); void (*PicoLoadStateHook)(void); /* I/O functions */ static size_t gzRead2(void *p, size_t _size, size_t _n, void *file) { return gzread(file, p, _size * _n); } static size_t gzWrite2(void *p, size_t _size, size_t _n, void *file) { return gzwrite(file, p, _size * _n); } static void set_cbs(int gz) { if (gz) { areaRead = gzRead2; areaWrite = gzWrite2; areaEof = (areaeof *) gzeof; areaSeek = (areaseek *) gzseek; areaClose = (areaclose *) gzclose; } else { areaRead = (arearw *) fread; areaWrite = (arearw *) fwrite; areaEof = (areaeof *) feof; areaSeek = (areaseek *) fseek; areaClose = (areaclose *) fclose; } } static void *open_save_file(const char *fname, int is_save) { int len = strlen(fname); void *afile = NULL; if (len > 3 && strcmp(fname + len - 3, ".gz") == 0) { if ( (afile = gzopen(fname, is_save ? "wb" : "rb")) ) { set_cbs(1); if (is_save) gzsetparams(afile, 9, Z_DEFAULT_STRATEGY); } } else { if ( (afile = fopen(fname, is_save ? "wb" : "rb")) ) { set_cbs(0); } } return afile; } // --------------------------------------------------------------------------- typedef enum { CHUNK_M68K = 1, CHUNK_RAM, CHUNK_VRAM, CHUNK_ZRAM, CHUNK_CRAM, // 5 CHUNK_VSRAM, CHUNK_MISC, CHUNK_VIDEO, CHUNK_Z80, CHUNK_PSG, // 10 CHUNK_FM, // CD stuff CHUNK_S68K, CHUNK_PRG_RAM, CHUNK_WORD_RAM, CHUNK_PCM_RAM, // 15 CHUNK_BRAM, CHUNK_GA_REGS, CHUNK_PCM, CHUNK_CDC, // old CHUNK_CDD, // 20 old CHUNK_SCD, // old CHUNK_RC, // old CHUNK_MISC_CD, // CHUNK_IOPORTS, // versions < 1.70 did not save that.. CHUNK_SMS, // 25 // 32x CHUNK_MSH2, CHUNK_MSH2_DATA, CHUNK_MSH2_PERI, CHUNK_SSH2, CHUNK_SSH2_DATA, // 30 CHUNK_SSH2_PERI, CHUNK_32XSYS, CHUNK_M68K_BIOS, CHUNK_MSH2_BIOS, CHUNK_SSH2_BIOS, // 35 CHUNK_SDRAM, CHUNK_DRAM, CHUNK_32XPAL, CHUNK_32X_EVT, CHUNK_32X_FIRST = CHUNK_MSH2, CHUNK_32X_LAST = CHUNK_32X_EVT, // add new stuff here CHUNK_CD_EVT = 50, CHUNK_CD_GFX, CHUNK_CD_CDC, CHUNK_CD_CDD, // CHUNK_DEFAULT_COUNT, CHUNK_CARTHW_ = CHUNK_CARTHW, // 64 (defined in PicoInt) } chunk_name_e; static const char * const chunk_names[CHUNK_DEFAULT_COUNT] = { "INVALID!", "M68K state", "RAM", "VRAM", "ZRAM", "CRAM", // 5 "VSRAM", "emu state", "VIDEO", "Z80 state", "PSG", // 10 "FM", // CD stuff "S68K state", "PRG_RAM", "WORD_RAM", "PCM_RAM", // 15 "BRAM", "GATE ARRAY regs", "PCM state", "CDC", "CDD", // 20 "SCD", "GFX chip", "MCD state", // "IO", "SMS state", // 25 // 32x "MSH2", "MSH2 data", "MSH2 peri", "SSH2", "SSH2 data", // 30 "SSH2 peri", "32X system regs", "M68K BIOS", "MSH2 BIOS", "SSH2 BIOS", // 35 "SDRAM", "DRAM", "PAL", "events", }; static int write_chunk(chunk_name_e name, int len, void *data, void *file) { size_t bwritten = 0; bwritten += areaWrite(&name, 1, 1, file); bwritten += areaWrite(&len, 1, 4, file); bwritten += areaWrite(data, 1, len, file); return (bwritten == len + 4 + 1); } #define CHUNK_LIMIT_W 18772 // sizeof(cdc) #define CHECKED_WRITE(name,len,data) { \ if (PicoStateProgressCB && name < CHUNK_DEFAULT_COUNT && chunk_names[name]) { \ strncpy(sbuff + 9, chunk_names[name], sizeof(sbuff) - 9); \ PicoStateProgressCB(sbuff); \ } \ if (data == buf2 && len > CHUNK_LIMIT_W) \ goto out; \ if (!write_chunk(name, len, data, file)) \ goto out; \ } #define CHECKED_WRITE_BUFF(name,buff) { \ if (PicoStateProgressCB && name < CHUNK_DEFAULT_COUNT && chunk_names[name]) { \ strncpy(sbuff + 9, chunk_names[name], sizeof(sbuff) - 9); \ PicoStateProgressCB(sbuff); \ } \ if (!write_chunk(name, sizeof(buff), &buff, file)) \ goto out; \ } static int state_save(void *file) { char sbuff[32] = "Saving.. "; unsigned char buff[0x60], buff_z80[Z80_STATE_SIZE]; void *ym2612_regs = YM2612GetRegs(); void *buf2 = NULL; int ver = 0x0191; // not really used.. int retval = -1; int len; areaWrite("PicoSEXT", 1, 8, file); areaWrite(&ver, 1, 4, file); if (!(PicoIn.AHW & PAHW_SMS)) { // the patches can cause incompatible saves with no-idle SekFinishIdleDet(); memset(buff, 0, sizeof(buff)); SekPackCpu(buff, 0); CHECKED_WRITE_BUFF(CHUNK_M68K, buff); CHECKED_WRITE_BUFF(CHUNK_RAM, PicoMem.ram); CHECKED_WRITE_BUFF(CHUNK_VSRAM, PicoMem.vsram); CHECKED_WRITE_BUFF(CHUNK_IOPORTS, PicoMem.ioports); ym2612_pack_state(); CHECKED_WRITE(CHUNK_FM, 0x200+4, ym2612_regs); if (!(PicoIn.opt & POPT_DIS_IDLE_DET)) SekInitIdleDet(); } else { CHECKED_WRITE_BUFF(CHUNK_SMS, Pico.ms); } CHECKED_WRITE_BUFF(CHUNK_VRAM, PicoMem.vram); CHECKED_WRITE_BUFF(CHUNK_ZRAM, PicoMem.zram); CHECKED_WRITE_BUFF(CHUNK_CRAM, PicoMem.cram); CHECKED_WRITE_BUFF(CHUNK_MISC, Pico.m); CHECKED_WRITE_BUFF(CHUNK_VIDEO, Pico.video); z80_pack(buff_z80); CHECKED_WRITE_BUFF(CHUNK_Z80, buff_z80); CHECKED_WRITE(CHUNK_PSG, 28*4, sn76496_regs); if (PicoIn.AHW & PAHW_MCD) { buf2 = malloc(CHUNK_LIMIT_W); if (buf2 == NULL) return -1; memset(buff, 0, sizeof(buff)); SekPackCpu(buff, 1); if (Pico_mcd->s68k_regs[3] & 4) // 1M mode? wram_1M_to_2M(Pico_mcd->word_ram2M); memcpy(&Pico_mcd->m.hint_vector, Pico_mcd->bios + 0x72, sizeof(Pico_mcd->m.hint_vector)); CHECKED_WRITE_BUFF(CHUNK_S68K, buff); CHECKED_WRITE_BUFF(CHUNK_PRG_RAM, Pico_mcd->prg_ram); CHECKED_WRITE_BUFF(CHUNK_WORD_RAM, Pico_mcd->word_ram2M); // in 2M format CHECKED_WRITE_BUFF(CHUNK_PCM_RAM, Pico_mcd->pcm_ram); CHECKED_WRITE_BUFF(CHUNK_BRAM, Pico_mcd->bram); CHECKED_WRITE_BUFF(CHUNK_GA_REGS, Pico_mcd->s68k_regs); // GA regs, not CPU regs CHECKED_WRITE_BUFF(CHUNK_PCM, Pico_mcd->pcm); CHECKED_WRITE_BUFF(CHUNK_MISC_CD, Pico_mcd->m); memset(buff, 0, 0x40); memcpy(buff, pcd_event_times, sizeof(pcd_event_times)); CHECKED_WRITE(CHUNK_CD_EVT, 0x40, buff); len = gfx_context_save(buf2); CHECKED_WRITE(CHUNK_CD_GFX, len, buf2); len = cdc_context_save(buf2); CHECKED_WRITE(CHUNK_CD_CDC, len, buf2); len = cdd_context_save(buf2); CHECKED_WRITE(CHUNK_CD_CDD, len, buf2); if (Pico_mcd->s68k_regs[3] & 4) // convert back wram_2M_to_1M(Pico_mcd->word_ram2M); } #ifndef NO_32X if (PicoIn.AHW & PAHW_32X) { unsigned char cpubuff[SH2_STATE_SIZE]; memset(cpubuff, 0, sizeof(cpubuff)); sh2_pack(&sh2s[0], cpubuff); CHECKED_WRITE_BUFF(CHUNK_MSH2, cpubuff); CHECKED_WRITE_BUFF(CHUNK_MSH2_DATA, sh2s[0].data_array); CHECKED_WRITE_BUFF(CHUNK_MSH2_PERI, sh2s[0].peri_regs); sh2_pack(&sh2s[1], cpubuff); CHECKED_WRITE_BUFF(CHUNK_SSH2, cpubuff); CHECKED_WRITE_BUFF(CHUNK_SSH2_DATA, sh2s[1].data_array); CHECKED_WRITE_BUFF(CHUNK_SSH2_PERI, sh2s[1].peri_regs); CHECKED_WRITE_BUFF(CHUNK_32XSYS, Pico32x); CHECKED_WRITE_BUFF(CHUNK_M68K_BIOS, Pico32xMem->m68k_rom); CHECKED_WRITE_BUFF(CHUNK_MSH2_BIOS, Pico32xMem->sh2_rom_m); CHECKED_WRITE_BUFF(CHUNK_SSH2_BIOS, Pico32xMem->sh2_rom_s); CHECKED_WRITE_BUFF(CHUNK_SDRAM, Pico32xMem->sdram); CHECKED_WRITE_BUFF(CHUNK_DRAM, Pico32xMem->dram); CHECKED_WRITE_BUFF(CHUNK_32XPAL, Pico32xMem->pal); memset(buff, 0, 0x40); memcpy(buff, p32x_event_times, sizeof(p32x_event_times)); CHECKED_WRITE(CHUNK_32X_EVT, 0x40, buff); } #endif if (carthw_chunks != NULL) { carthw_state_chunk *chwc; if (PicoStateProgressCB) PicoStateProgressCB("Saving.. cart hw state"); for (chwc = carthw_chunks; chwc->ptr != NULL; chwc++) CHECKED_WRITE(chwc->chunk, chwc->size, chwc->ptr); } retval = 0; out: if (buf2 != NULL) free(buf2); return retval; } static int g_read_offs = 0; #define R_ERROR_RETURN(error) \ { \ elprintf(EL_STATUS, "load_state @ %x: " error, g_read_offs); \ goto out; \ } // when is eof really set? #define CHECKED_READ(len,data) { \ if (areaRead(data, 1, len, file) != len) { \ if (len == 1 && areaEof(file)) goto readend; \ R_ERROR_RETURN("areaRead: premature EOF\n"); \ } \ g_read_offs += len; \ } #define CHECKED_READ2(len2,data) { \ if (len2 != len) { \ elprintf(EL_STATUS, "unexpected len %i, wanted %i (%s)", len, len2, #len2); \ if (len > len2) R_ERROR_RETURN("failed."); \ /* else read anyway and hope for the best.. */ \ } \ CHECKED_READ(len, data); \ } #define CHECKED_READ_BUFF(buff) CHECKED_READ2(sizeof(buff), &buff); #define CHUNK_LIMIT_R 0x10960 // sizeof(old_cdc) #define CHECKED_READ_LIM(data) { \ if (len > CHUNK_LIMIT_R) \ R_ERROR_RETURN("chunk size over limit."); \ CHECKED_READ(len, data); \ } static int state_load(void *file) { unsigned char buff_m68k[0x60], buff_s68k[0x60]; unsigned char buff_z80[Z80_STATE_SIZE]; unsigned char buff_sh2[SH2_STATE_SIZE]; unsigned char *buf = NULL; unsigned char chunk; void *ym2612_regs; int len_check; int retval = -1; char header[8]; int ver, len; memset(buff_m68k, 0, sizeof(buff_m68k)); memset(buff_s68k, 0, sizeof(buff_s68k)); memset(buff_z80, 0, sizeof(buff_z80)); buf = malloc(CHUNK_LIMIT_R); if (buf == NULL) return -1; g_read_offs = 0; CHECKED_READ(8, header); if (strncmp(header, "PicoSMCD", 8) && strncmp(header, "PicoSEXT", 8)) R_ERROR_RETURN("bad header"); CHECKED_READ(4, &ver); memset(pcd_event_times, 0, sizeof(pcd_event_times)); memset(p32x_event_times, 0, sizeof(p32x_event_times)); while (!areaEof(file)) { len_check = 0; CHECKED_READ(1, &chunk); CHECKED_READ(4, &len); if (len < 0 || len > 1024*512) R_ERROR_RETURN("bad length"); if (CHUNK_S68K <= chunk && chunk <= CHUNK_MISC_CD && !(PicoIn.AHW & PAHW_MCD)) R_ERROR_RETURN("cd chunk in non CD state?"); if (CHUNK_32X_FIRST <= chunk && chunk <= CHUNK_32X_LAST && !(PicoIn.AHW & PAHW_32X)) Pico32xStartup(); switch (chunk) { case CHUNK_M68K: CHECKED_READ_BUFF(buff_m68k); break; case CHUNK_Z80: CHECKED_READ_BUFF(buff_z80); break; case CHUNK_RAM: CHECKED_READ_BUFF(PicoMem.ram); break; case CHUNK_VRAM: CHECKED_READ_BUFF(PicoMem.vram); break; case CHUNK_ZRAM: CHECKED_READ_BUFF(PicoMem.zram); break; case CHUNK_CRAM: CHECKED_READ_BUFF(PicoMem.cram); break; case CHUNK_VSRAM: CHECKED_READ_BUFF(PicoMem.vsram); break; case CHUNK_MISC: CHECKED_READ_BUFF(Pico.m); break; case CHUNK_VIDEO: CHECKED_READ_BUFF(Pico.video); break; case CHUNK_IOPORTS: CHECKED_READ_BUFF(PicoMem.ioports); break; case CHUNK_PSG: CHECKED_READ2(28*4, sn76496_regs); break; case CHUNK_FM: ym2612_regs = YM2612GetRegs(); CHECKED_READ2(0x200+4, ym2612_regs); ym2612_unpack_state(); break; case CHUNK_SMS: CHECKED_READ_BUFF(Pico.ms); break; // cd stuff case CHUNK_S68K: CHECKED_READ_BUFF(buff_s68k); break; case CHUNK_PRG_RAM: CHECKED_READ_BUFF(Pico_mcd->prg_ram); break; case CHUNK_WORD_RAM: CHECKED_READ_BUFF(Pico_mcd->word_ram2M); break; case CHUNK_PCM_RAM: CHECKED_READ_BUFF(Pico_mcd->pcm_ram); break; case CHUNK_BRAM: CHECKED_READ_BUFF(Pico_mcd->bram); break; case CHUNK_GA_REGS: CHECKED_READ_BUFF(Pico_mcd->s68k_regs); break; case CHUNK_PCM: CHECKED_READ_BUFF(Pico_mcd->pcm); break; case CHUNK_MISC_CD: CHECKED_READ_BUFF(Pico_mcd->m); break; case CHUNK_CD_EVT: CHECKED_READ2(0x40, buf); memcpy(pcd_event_times, buf, sizeof(pcd_event_times)); break; case CHUNK_CD_GFX: CHECKED_READ_LIM(buf); len_check = gfx_context_load(buf); break; case CHUNK_CD_CDC: CHECKED_READ_LIM(buf); len_check = cdc_context_load(buf); break; case CHUNK_CD_CDD: CHECKED_READ_LIM(buf); len_check = cdd_context_load(buf); break; // old, to be removed: case CHUNK_CDC: CHECKED_READ_LIM(buf); cdc_context_load_old(buf); break; case CHUNK_SCD: CHECKED_READ_LIM(buf); cdd_context_load_old(buf); break; // 32x stuff #ifndef NO_32X case CHUNK_MSH2: CHECKED_READ_BUFF(buff_sh2); sh2_unpack(&sh2s[0], buff_sh2); break; case CHUNK_SSH2: CHECKED_READ_BUFF(buff_sh2); sh2_unpack(&sh2s[1], buff_sh2); break; case CHUNK_MSH2_DATA: CHECKED_READ_BUFF(sh2s[0].data_array); break; case CHUNK_MSH2_PERI: CHECKED_READ_BUFF(sh2s[0].peri_regs); break; case CHUNK_SSH2_DATA: CHECKED_READ_BUFF(sh2s[1].data_array); break; case CHUNK_SSH2_PERI: CHECKED_READ_BUFF(sh2s[1].peri_regs); break; case CHUNK_32XSYS: CHECKED_READ_BUFF(Pico32x); break; case CHUNK_M68K_BIOS: CHECKED_READ_BUFF(Pico32xMem->m68k_rom); break; case CHUNK_MSH2_BIOS: CHECKED_READ_BUFF(Pico32xMem->sh2_rom_m); break; case CHUNK_SSH2_BIOS: CHECKED_READ_BUFF(Pico32xMem->sh2_rom_s); break; case CHUNK_SDRAM: CHECKED_READ_BUFF(Pico32xMem->sdram); break; case CHUNK_DRAM: CHECKED_READ_BUFF(Pico32xMem->dram); break; case CHUNK_32XPAL: CHECKED_READ_BUFF(Pico32xMem->pal); break; case CHUNK_32X_EVT: CHECKED_READ2(0x40, buf); memcpy(p32x_event_times, buf, sizeof(p32x_event_times)); break; #endif default: if (carthw_chunks != NULL) { carthw_state_chunk *chwc; for (chwc = carthw_chunks; chwc->ptr != NULL; chwc++) { if (chwc->chunk == chunk) { CHECKED_READ2(chwc->size, chwc->ptr); goto breakswitch; } } } elprintf(EL_STATUS, "load_state: skipping unknown chunk %i of size %i", chunk, len); areaSeek(file, len, SEEK_CUR); break; } breakswitch: if (len_check != 0 && len_check != len) elprintf(EL_STATUS, "load_state: chunk %d has bad len %d/%d", len, len_check); } readend: if (PicoIn.AHW & PAHW_SMS) PicoStateLoadedMS(); if (PicoIn.AHW & PAHW_32X) Pico32xStateLoaded(1); if (PicoLoadStateHook != NULL) PicoLoadStateHook(); // must unpack 68k and z80 after banks are set up if (!(PicoIn.AHW & PAHW_SMS)) SekUnpackCpu(buff_m68k, 0); if (PicoIn.AHW & PAHW_MCD) SekUnpackCpu(buff_s68k, 1); z80_unpack(buff_z80); // due to dep from 68k cycles.. Pico.t.m68c_aim = Pico.t.m68c_cnt; if (PicoIn.AHW & PAHW_32X) Pico32xStateLoaded(0); if (PicoIn.AHW & PAHW_MCD) { SekCycleAimS68k = SekCycleCntS68k; pcd_state_loaded(); } Pico.m.dirtyPal = 1; Pico.video.status &= ~(SR_VB | SR_F); Pico.video.status |= ((Pico.video.reg[1] >> 3) ^ SR_VB) & SR_VB; Pico.video.status |= (Pico.video.pending_ints << 2) & SR_F; retval = 0; out: free(buf); return retval; } static int state_load_gfx(void *file) { int ver, len, found = 0, to_find = 4; char buff[8]; if (PicoIn.AHW & PAHW_32X) to_find += 2; g_read_offs = 0; CHECKED_READ(8, buff); if (strncmp((char *)buff, "PicoSMCD", 8) && strncmp((char *)buff, "PicoSEXT", 8)) R_ERROR_RETURN("bad header"); CHECKED_READ(4, &ver); while (!areaEof(file) && found < to_find) { CHECKED_READ(1, buff); CHECKED_READ(4, &len); if (len < 0 || len > 1024*512) R_ERROR_RETURN("bad length"); if (buff[0] > CHUNK_FM && buff[0] <= CHUNK_MISC_CD && !(PicoIn.AHW & PAHW_MCD)) R_ERROR_RETURN("cd chunk in non CD state?"); switch (buff[0]) { case CHUNK_VRAM: CHECKED_READ_BUFF(PicoMem.vram); found++; break; case CHUNK_CRAM: CHECKED_READ_BUFF(PicoMem.cram); found++; break; case CHUNK_VSRAM: CHECKED_READ_BUFF(PicoMem.vsram); found++; break; case CHUNK_VIDEO: CHECKED_READ_BUFF(Pico.video); found++; break; #ifndef NO_32X case CHUNK_DRAM: if (Pico32xMem != NULL) CHECKED_READ_BUFF(Pico32xMem->dram); break; case CHUNK_32XPAL: if (Pico32xMem != NULL) CHECKED_READ_BUFF(Pico32xMem->pal); Pico32x.dirty_pal = 1; break; case CHUNK_32XSYS: CHECKED_READ_BUFF(Pico32x); break; #endif default: areaSeek(file, len, SEEK_CUR); break; } } out: readend: return 0; } static int pico_state_internal(void *afile, int is_save) { int ret; if (is_save) ret = state_save(afile); else ret = state_load(afile); return ret; } int PicoState(const char *fname, int is_save) { void *afile = NULL; int ret; afile = open_save_file(fname, is_save); if (afile == NULL) return -1; ret = pico_state_internal(afile, is_save); areaClose(afile); return ret; } int PicoStateFP(void *afile, int is_save, arearw *read, arearw *write, areaeof *eof, areaseek *seek) { areaRead = read; areaWrite = write; areaEof = eof; areaSeek = seek; areaClose = NULL; return pico_state_internal(afile, is_save); } int PicoStateLoadGfx(const char *fname) { void *afile; int ret; afile = open_save_file(fname, 0); if (afile == NULL) return -1; ret = state_load_gfx(afile); if (ret != 0) { // assume legacy areaSeek(afile, 0x10020, SEEK_SET); // skip header and RAM areaRead(PicoMem.vram, 1, sizeof(PicoMem.vram), afile); areaSeek(afile, 0x2000, SEEK_CUR); areaRead(PicoMem.cram, 1, sizeof(PicoMem.cram), afile); areaRead(PicoMem.vsram, 1, sizeof(PicoMem.vsram), afile); areaSeek(afile, 0x221a0, SEEK_SET); areaRead(&Pico.video, 1, sizeof(Pico.video), afile); } areaClose(afile); return 0; } // tmp state struct PicoTmp { unsigned short vram[0x8000]; unsigned short cram[0x40]; unsigned short vsram[0x40]; //struct PicoMisc m; struct PicoVideo video; struct { struct Pico32x p32x; unsigned short dram[2][0x20000/2]; unsigned short pal[0x100]; } t32x; }; // returns data ptr to free() or PicoTmpStateRestore() void *PicoTmpStateSave(void) { // gfx only for now struct PicoTmp *t = malloc(sizeof(*t)); if (t == NULL) return NULL; memcpy(t->vram, PicoMem.vram, sizeof(PicoMem.vram)); memcpy(t->cram, PicoMem.cram, sizeof(PicoMem.cram)); memcpy(t->vsram, PicoMem.vsram, sizeof(PicoMem.vsram)); memcpy(&t->video, &Pico.video, sizeof(Pico.video)); #ifndef NO_32X if (PicoIn.AHW & PAHW_32X) { memcpy(&t->t32x.p32x, &Pico32x, sizeof(Pico32x)); memcpy(t->t32x.dram, Pico32xMem->dram, sizeof(Pico32xMem->dram)); memcpy(t->t32x.pal, Pico32xMem->pal, sizeof(Pico32xMem->pal)); } #endif return t; } void PicoTmpStateRestore(void *data) { struct PicoTmp *t = data; if (t == NULL) return; memcpy(PicoMem.vram, t->vram, sizeof(PicoMem.vram)); memcpy(PicoMem.cram, t->cram, sizeof(PicoMem.cram)); memcpy(PicoMem.vsram, t->vsram, sizeof(PicoMem.vsram)); memcpy(&Pico.video, &t->video, sizeof(Pico.video)); Pico.m.dirtyPal = 1; #ifndef NO_32X if (PicoIn.AHW & PAHW_32X) { memcpy(&Pico32x, &t->t32x.p32x, sizeof(Pico32x)); memcpy(Pico32xMem->dram, t->t32x.dram, sizeof(Pico32xMem->dram)); memcpy(Pico32xMem->pal, t->t32x.pal, sizeof(Pico32xMem->pal)); Pico32x.dirty_pal = 1; } #endif } // vim:shiftwidth=2:ts=2:expandtab
56881.c
/* * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509v3.h> #include "ext_dat.h" static ENUMERATED_NAMES crl_reasons[] = { {CRL_REASON_UNSPECIFIED, "Unspecified", "unspecified"}, {CRL_REASON_KEY_COMPROMISE, "Key Compromise", "keyCompromise"}, {CRL_REASON_CA_COMPROMISE, "CA Compromise", "CACompromise"}, {CRL_REASON_AFFILIATION_CHANGED, "Affiliation Changed", "affiliationChanged"}, {CRL_REASON_SUPERSEDED, "Superseded", "superseded"}, {CRL_REASON_CESSATION_OF_OPERATION, "Cessation Of Operation", "cessationOfOperation"}, {CRL_REASON_CERTIFICATE_HOLD, "Certificate Hold", "certificateHold"}, {CRL_REASON_REMOVE_FROM_CRL, "Remove From CRL", "removeFromCRL"}, {CRL_REASON_PRIVILEGE_WITHDRAWN, "Privilege Withdrawn", "privilegeWithdrawn"}, {CRL_REASON_AA_COMPROMISE, "AA Compromise", "AACompromise"}, {-1, NULL, NULL} }; const X509V3_EXT_METHOD ossl_v3_crl_reason = { NID_crl_reason, 0, ASN1_ITEM_ref(ASN1_ENUMERATED), 0, 0, 0, 0, (X509V3_EXT_I2S)i2s_ASN1_ENUMERATED_TABLE, 0, 0, 0, 0, 0, crl_reasons }; char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *e) { ENUMERATED_NAMES *enam; long strval; strval = ASN1_ENUMERATED_get(e); for (enam = method->usr_data; enam->lname; enam++) { if (strval == enam->bitnum) return OPENSSL_strdup(enam->lname); } return i2s_ASN1_ENUMERATED(method, e); }
260176.c
// // Created by NBao on 2021/01/29. // // Input: // Matrix-Chain U_{1..n} = <U_1, U_2, ..., U_n> // Dimensions p_0, p_1, ..., p_n, U_i's dimension is p_{i-1} * p_i // Output: // Find a way to add parentheses to determine the calculation order // of matrix chain multiplication, so as to minimize the number of // matrix chain scalar multiplications // #include <stdio.h> #include <string.h> #define N 6 int p[N + 1] = {2, 3, 7, 9, 5, 2, 4}; int dp[N + 1][N + 1]; int rec[N + 1][N + 1]; void PrintMatrixChain(int i, int j) { if (i == j) { printf("U_%d", i); return; } printf("("); PrintMatrixChain(i, rec[i][j]); printf(")("); PrintMatrixChain(rec[i][j] + 1, j); printf(")"); } int main() { memset(dp,0x3f,sizeof(dp)); // Initial dp[][] to infinity for (int i = 1; i <= N; i++) { dp[i][i] = 0; } for (int l = 2; l <= N; l++) { // Traverse interval length from short to long for (int i = 1; i <= N - l + 1; i++) { // Left Boundary int j = i + l - 1; // Right Boundary for (int k = i; k <= j - 1; k++) { // Traverse each k from i to j int q = dp[i][k] + dp[k + 1][j] + p[i - 1]* p[k] * p[j]; if (q < dp[i][j]) { dp[i][j] = q; rec[i][j] = k; } } } } PrintMatrixChain(1, N); printf("\n"); return 0; }
90909.c
/* WINMAIN.C, placed in the public domain by Sam Lantinga 4/13/98 The WinMain function -- calls your program's main() function */ #ifdef _WIN32 #if !defined (WIN32) #define WIN32 #endif /* The WinMain function -- calls your program's main() function */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <windows.h> #include "paramline.h" #include "SDL/SDL.h" /* This is where execution begins */ int STDCALL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) { char *appname; char *ptr; int i; FILE *fp; char **argv; int argc; /* * Direct Draw has a nasty bug where a file that is opened before * Direct Draw is invoked, *stays* open until the system is rebooted. * So we need to get Direct Draw loaded before we open any files. */ { HANDLE h; h = LoadLibrary ("DDRAW.DLL"); if (h) FreeLibrary (LoadLibrary ("DDRAW.DLL")); } /* FIXME: * fprintf needs to be remapped to a windows function, otherwise when * executor dies the user has no idea why it just vanished. */ fp = freopen ("stdout.txt", "w", stdout); #if !defined (stdout) if (!fp) stdout = fopen ("stdout.txt", "w"); #else if (!fp) *stdout = *fopen ("stdout.txt", "w"); #endif setbuf (stdout, 0); fp = freopen ("stderr.txt", "w", stderr); #if !defined (stderr) if (!fp) stderr = fopen ("stderr.txt", "w"); #else if (!fp) *stderr = *fopen ("stderr.txt", "w"); #endif setbuf (stderr, 0); paramline_to_argcv (GetCommandLine (), &argc, &argv); /* Get the class name from argv[0] */ /* Basename... */ if ( (ptr=strrchr(argv[0], '\\')) == NULL ) appname = argv[0]; else appname = ptr+1; /* minus extension... */ if ( (ptr=strrchr(appname, '.')) == NULL ) i = strlen(appname); else i = (ptr-appname); /* equals appname! */ ptr=(char *)alloca(i+1); strncpy(ptr, appname, i); ptr[i] = '\0'; appname = ptr; /* Load SDL dynamic link library */ if ( SDL_Init(0) < 0 ) { fprintf(stderr, "WinMain() error: %s\n", SDL_GetError()); return(FALSE); } atexit(SDL_Quit); /* Create and register our class, then run main code */ if ( SDL_RegisterApp(appname, CS_BYTEALIGNCLIENT, hInst) < 0 ) { fprintf(stderr, "WinMain() error: %s\n", SDL_GetError()); return(FALSE); } SDL_main(argc, argv); exit(0); } #endif /* _WIN32 */
247630.c
#include "port.h" #include "port-testing.h" #include <string.h> int main(void) { P6Val *val; Test("Initialization"); P6State *state = p6_init(); Assert(state, "Failed to initialise"); Test("Numbers"); AssertEq(p6eval(state, "+'1'"), p6_make_int(1)); AssertEq(p6eval(state, "15.78"), p6_make_num(15.78)); AssertEq(p6eval(state, "12 + 14.4"), p6_make_num(26.4)); Test("Strings"); AssertEq(p6eval(state, "~18"), p6_make_str("18")); Test("Nil/Any"); AssertIsType(p6eval(state, "Nil"), P6Nil); AssertIsType(p6eval(state, "Any"), P6Any); Test("Error"); AssertIsType(p6eval(state, "~~~"), P6Error); Test("Bool"); AssertEq(p6eval(state, "?24"), p6_make_bool(true)); AssertEq(p6eval(state, "!24"), p6_make_bool(false)); Test("List"); val = p6eval(state, "[16, ^3, 'h']"); AssertIsType(val, P6List); Assert(p6_list_len(val) == 3, "length is %zu but should be 3", p6_list_len(val)); AssertIsType(p6_list_index(val, 0), P6Int); val = p6_list_index(val, 1); AssertIsType(val, P6List); Assert(p6_list_len(val) == 3, "length of second val should be 3 but is %zu", p6_list_len(val)); AssertIsType(p6_list_index(val, 1), P6Int); AssertEq(p6_list_index(val, 1), p6_make_int(1)); Test("Sub"); val = p6eval(state, "&addering"); AssertIsType(val, P6Sub); Assert(p6_get_arity(val) == 3, "arity is %zi but should be 3", p6_get_arity(val)); Assert(p6_get_return_type(val) == P6Int, "return type is %d but should be P6Int (%d)", p6_get_return_type(val), P6Int); Assert(p6_get_parameter_types(val)[1] == P6Int, "type of 2nd parameter is %d; should be P6Int (%d)", p6_get_parameter_types(val)[1], P6Int); End_Testing; }
369103.c
#include <stdio.h> struct testStruct { int a; int b; } *s; int t; struct testStruct *s1, *s2; int h(int c); int g(int b) { int *p = &c; return h(*b); } int f(int a) { int *c = 1; intLock(); *c = l(2); kernDispatchDisable(); *c = 4; intUnlock(); //goto next; *c = 3; kernDispatchEnable(); if (*c == 1) { intLock(); } else { kernDispatchDisable(); } if (*c == 1) { //c = 1; l1(2); } else { //c = 2; l(1); } /*if (c > 0) { //intLock(); if (c < 3) { goto next; }// else { //intUnlock(); //} return 1; //intUnlock(); } switch (a) { case 0: return 0; case 1: return g(a - 1); case 2: return g(a -2); case 3: return g(a -3); default: return g(a - 4); } next:*/ return 0; } int h(int c) { int d; //intLock(); d = c + 1; return d; } int l(int c) { int *p = &c; return *(p + 1); } int l1(int c) { int *p = &c; l1(*(p + 2)); } int l2(int c) { return l1(c + 1); } int main() { int a; int q = 1; int* temp; int* temp2; t = 1; intLock(); l1(3); t = 2; intUnlock(); temp = &a; q = h(q); switch (q) { case 0: intLock(); break; case 1: kernDispatchDisable(); break; } temp = &q; intLock(); a = 1; intLock(); t = 2; temp = sdlFirst(&t); intUnlock(); *temp = 3; if (q == 1) { intLock(); q = h(1); temp = sdlFirst(&(s->a)); return; } else { q = l2(1); } intUnlock(); temp2 = sdlFirst(temp); temp2 = sdlFirst(temp2); q = *temp2; h(q); t1 = a; t2 = link(t1); t = *t2; temp = &a; h(a); for (int i = 0; i < 10; i++) { intLock(); a = f(4); temp = &a; intUnlock(); } s->a = 1; if (s->a){ { a = 1; } a = 2; } int b = a + q; intUnlock(); queLock(q); a = 2; queUnlock(q); a = 3; printf("%i\n",a); }