filename
stringlengths
3
9
code
stringlengths
4
1.87M
690055.c
#include "stream.h" #include <string.h> void PQCLEAN_DILITHIUM4_CLEAN_shake128_stream_init( shake128ctx *state, const uint8_t seed[SEEDBYTES], uint16_t nonce) { uint8_t buf[SEEDBYTES + 2]; memcpy(buf, seed, SEEDBYTES); buf[SEEDBYTES] = (uint8_t)nonce; buf[SEEDBYTES + 1] = (uint8_t)(nonce >> 8); shake128_absorb(state, buf, SEEDBYTES + 2); } void PQCLEAN_DILITHIUM4_CLEAN_shake256_stream_init( shake256ctx *state, const uint8_t seed[CRHBYTES], uint16_t nonce) { uint8_t buf[CRHBYTES + 2]; memcpy(buf, seed, CRHBYTES); buf[CRHBYTES] = (uint8_t)nonce; buf[CRHBYTES + 1] = (uint8_t)(nonce >> 8); shake256_absorb(state, buf, CRHBYTES + 2); }
319484.c
#include "sbfMemory.h" void sbfMemory_asprintf (char** ret, const char* fmt, ...) { va_list ap; va_start (ap, fmt); if (vasprintf (ret, fmt, ap) == -1) SBF_FATAL ("out of memory"); va_end (ap); } void sbfMemory_vasprintf (char** ret, const char* fmt, va_list ap) { if (vasprintf (ret, fmt, ap) == -1) SBF_FATAL ("out of memory"); } void* sbfMemory_malloc (size_t size) { void* ptr; if (size == 0) SBF_FATAL ("zero size"); ptr = malloc (size); if (ptr == NULL) SBF_FATAL ("out of memory"); return ptr; } void* sbfMemory_calloc (size_t nmemb, size_t size) { void *ptr; if (size == 0 || nmemb == 0) SBF_FATAL ("zero size"); if (SIZE_MAX / nmemb < size) SBF_FATAL ("size too big"); ptr = calloc(nmemb, size); if (ptr == NULL) SBF_FATAL ("out of memory"); return ptr; } void* sbfMemory_realloc (void* ptr, size_t nmemb, size_t size) { size_t newsize; newsize = nmemb * size; if (newsize == 0) SBF_FATAL ("zero size"); if (SIZE_MAX / nmemb < size) SBF_FATAL ("size too big"); ptr = realloc (ptr, newsize); if (ptr == NULL) SBF_FATAL ("out of memory"); return ptr; } char* sbfMemory_strdup (const char* s) { char* ss; ss = strdup (s); if (ss == NULL) SBF_FATAL ("out of memory"); return ss; }
962139.c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE284_Access_Control_Issues__wchar_t_w32CreateFile_11.c Label Definition File: CWE284_Access_Control_Issues.label.xml Template File: point-flaw-11.tmpl.c */ /* * @description * CWE: 284 Access Control Issues * Sinks: w32CreateFile * GoodSink: Create a file using CreateFileW() without excessive privileges * BadSink : Create a file using CreateFileW() with excessive privileges * Flow Variant: 11 Control flow: if(global_returns_t()) and if(global_returns_f()) * * */ #include "std_testcase.h" #include <windows.h> #ifndef OMITBAD void CWE284_Access_Control_Issues__wchar_t_w32CreateFile_11_bad() { if(global_returns_t()) { #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FLAW: Call CreateFileW() with FILE_ALL_ACCESS as the 2nd parameter */ hFile = CreateFileW( filename, FILE_ALL_ACCESS, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FIX: Call CreateFileW() without FILE_ALL_ACCESS as the 2nd parameter to limit access */ hFile = CreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } } #endif /* OMITBAD */ #ifndef OMITGOOD /* good1() uses if(global_returns_f()) instead of if(global_returns_t()) */ static void good1() { if(global_returns_f()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FLAW: Call CreateFileW() with FILE_ALL_ACCESS as the 2nd parameter */ hFile = CreateFileW( filename, FILE_ALL_ACCESS, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } else { #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FIX: Call CreateFileW() without FILE_ALL_ACCESS as the 2nd parameter to limit access */ hFile = CreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } } /* good2() reverses the bodies in the if statement */ static void good2() { if(global_returns_t()) { #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FIX: Call CreateFileW() without FILE_ALL_ACCESS as the 2nd parameter to limit access */ hFile = CreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } else { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ #ifdef _WIN32 { HANDLE hFile; wchar_t * filename = L"C:\\temp\\file.txt"; /* FLAW: Call CreateFileW() with FILE_ALL_ACCESS as the 2nd parameter */ hFile = CreateFileW( filename, FILE_ALL_ACCESS, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printLine("File could not be created"); } else { printLine("File created successfully"); CloseHandle(hFile); } } #endif } } void CWE284_Access_Control_Issues__wchar_t_w32CreateFile_11_good() { good1(); good2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE284_Access_Control_Issues__wchar_t_w32CreateFile_11_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE284_Access_Control_Issues__wchar_t_w32CreateFile_11_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
89544.c
/* MOD2CONVERT.C - Routines converting between sparse and dense mod2 matrices.*/ /* Copyright (c) 1996, 2001 by Radford M. Neal * * Permission is granted for anyone to copy, use, modify, or distribute this * program and accompanying programs and documents for any purpose, provided * this copyright notice is retained and prominently displayed, along with * a note saying that the original programs are available from Radford Neal's * web page, and note is made of any changes made to the programs. The * programs and documents are distributed without any warranty, express or * implied. As the programs were written for research purposes only, they have * not been tested to the degree that would be advisable in any important * application. All use of these programs is entirely at the user's own risk. */ /* NOTE: See mod2convert.html for documentation on these procedures. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "mod2dense.h" #include "mod2sparse.h" #include "mod2convert.h" /* CONVERT A MOD2 MATRIX FROM SPARSE TO DENSE FORM. */ void mod2sparse_to_dense ( mod2sparse *m, /* Sparse matrix to convert */ mod2dense *r /* Place to store result */ ) { mod2entry *e; int i; if (mod2sparse_rows(m)>mod2dense_rows(r) || mod2sparse_cols(m)>mod2dense_cols(r)) { fprintf(stderr, "mod2sparse_to_dense: Dimension of result matrix is less than source\n"); exit(1); } mod2dense_clear(r); for (i = 0; i<mod2sparse_rows(m); i++) { e = mod2sparse_first_in_row(m,i); while (!mod2sparse_at_end(e)) { mod2dense_set(r,i,mod2sparse_col(e),1); e = mod2sparse_next_in_row(e); } } } /* CONVERT A MOD2 MATRIX FROM DENSE TO SPARSE FORM. */ void mod2dense_to_sparse ( mod2dense *m, /* Dense matrix to convert */ mod2sparse *r /* Place to store result */ ) { int i, j; if (mod2dense_rows(m)>mod2sparse_rows(r) || mod2dense_cols(m)>mod2sparse_cols(r)) { fprintf(stderr, "mod2dense_to_sparse: Dimension of result matrix is less than source\n"); exit(1); } mod2sparse_clear(r); for (i = 0; i<mod2dense_rows(m); i++) { for (j = 0; j<mod2dense_cols(m); j++) { if (mod2dense_get(m,i,j)) { mod2sparse_insert(r,i,j); } } } }
802886.c
#include "types.h" #include "stat.h" #include "user.h" void periodic(); static int i; int main(int argc, char *argv[]) { printf(1, "alarmtest starting\n"); alarm(100, periodic); for(i = 0; i < 25*50000000; i++){ printf(1, " "); // for(int h = 0; h < 2000; h++); //printf(1, "%x\n", i); // write(2, ".", 1); } exit(); } void periodic() { printf(1, "%d\n", i); }
799020.c
/* pfmlib_intel_x86_perf.c : perf_event Intel X86 functions * * Copyright (c) 2011 Google, Inc * Contributed by Stephane Eranian <[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 <sys/types.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> /* private headers */ #include "pfmlib_priv.h" #include "pfmlib_intel_x86_priv.h" #include "pfmlib_perf_event_priv.h" int pfm_intel_x86_get_perf_encoding(void *this, pfmlib_event_desc_t *e) { pfmlib_pmu_t *pmu = this; struct perf_event_attr *attr = e->os_data; int ret; if (!pmu->get_event_encoding[PFM_OS_NONE]) return PFM_ERR_NOTSUPP; /* * first, we need to do the generic encoding */ ret = pmu->get_event_encoding[PFM_OS_NONE](this, e); if (ret != PFM_SUCCESS) return ret; if (e->count > 2) { DPRINT("%s: unsupported count=%d\n", e->count); return PFM_ERR_NOTSUPP; } attr->type = PERF_TYPE_RAW; attr->config = e->codes[0]; /* * Nehalem/Westmere/Sandy Bridge OFFCORE_RESPONSE events * take two MSRs. lower level returns two codes: * - codes[0] goes to regular counter config * - codes[1] goes into extra MSR */ if (intel_x86_eflag(this, e->event, INTEL_X86_NHM_OFFCORE)) { if (e->count != 2) { DPRINT("perf_encoding: offcore=1 count=%d\n", e->count); return PFM_ERR_INVAL; } attr->config1 = e->codes[1]; } return PFM_SUCCESS; } int pfm_intel_nhm_unc_get_perf_encoding(void *this, pfmlib_event_desc_t *e) { pfmlib_pmu_t *pmu = this; struct perf_event_attr *attr = e->os_data; int ret; return PFM_ERR_NOTSUPP; if (!pmu->get_event_encoding[PFM_OS_NONE]) return PFM_ERR_NOTSUPP; ret = pmu->get_event_encoding[PFM_OS_NONE](this, e); if (ret != PFM_SUCCESS) return ret; //attr->type = PERF_TYPE_UNCORE; attr->config = e->codes[0]; /* * uncore measures at all priv levels * * user cannot set per-event priv levels because * attributes are simply not there * * dfl_plm is ignored in this case */ attr->exclude_hv = 0; attr->exclude_kernel = 0; attr->exclude_user = 0; return PFM_SUCCESS; } int pfm_intel_x86_requesting_pebs(pfmlib_event_desc_t *e) { pfm_event_attr_info_t *a; int i; for (i = 0; i < e->nattrs; i++) { a = attr(e, i); if (a->ctrl != PFM_ATTR_CTRL_PERF_EVENT) continue; if (a->idx == PERF_ATTR_PR && e->attrs[i].ival) return 1; } return 0; } static int intel_x86_event_has_pebs(void *this, pfmlib_event_desc_t *e) { pfm_event_attr_info_t *a; int i; /* first check at the event level */ if (intel_x86_eflag(e->pmu, e->event, INTEL_X86_PEBS)) return 1; /* check umasks */ for(i=0; i < e->npattrs; i++) { a = e->pattrs+i; if (a->ctrl != PFM_ATTR_CTRL_PMU || a->type != PFM_ATTR_UMASK) continue; if (intel_x86_uflag(e->pmu, e->event, a->idx, INTEL_X86_PEBS)) return 1; } return 0; } /* * remove attrs which are in conflicts (or duplicated) with os layer */ void pfm_intel_x86_perf_validate_pattrs(void *this, pfmlib_event_desc_t *e) { pfmlib_pmu_t *pmu = this; int i, compact; int has_pebs = intel_x86_event_has_pebs(this, e); for (i = 0; i < e->npattrs; i++) { compact = 0; /* umasks never conflict */ if (e->pattrs[i].type == PFM_ATTR_UMASK) continue; /* * with perf_events, u and k are handled at the OS level * via exclude_user, exclude_kernel. */ if (e->pattrs[i].ctrl == PFM_ATTR_CTRL_PMU) { if (e->pattrs[i].idx == INTEL_X86_ATTR_U || e->pattrs[i].idx == INTEL_X86_ATTR_K) compact = 1; } if (e->pattrs[i].ctrl == PFM_ATTR_CTRL_PERF_EVENT) { /* Precise mode, subject to PEBS */ if (e->pattrs[i].idx == PERF_ATTR_PR && !has_pebs) compact = 1; /* * No hypervisor on Intel */ if (e->pattrs[i].idx == PERF_ATTR_H) compact = 1; /* * uncore has no priv level support */ if (pmu->type == PFM_PMU_TYPE_UNCORE && (e->pattrs[i].idx == PERF_ATTR_U || e->pattrs[i].idx == PERF_ATTR_K)) compact = 1; } if (compact) { pfmlib_compact_pattrs(e, i); i--; } } }
736862.c
#include <stdio.h> #include <string.h> #include "driver/gpio.h" #include "driver/uart.h" #include "esp_log.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "subsys_uart.h" #include "at_handler.h" #include "subsys_uart.h" #include "wifi.h" #define ARRAY_SIZE 11 char *default_keys[ARRAY_SIZE] = { "NVS_RST", "WIFI_OFF", "WAP_SSID", "WAP_PASS", "WAP_CHAN", "WAP_AUTH", "WIFI_ON", "WIFI_MODE", "WIFI_RST", "WSTA_SSID", "WSTA_PASS", }; char *symbols[4] = { "+", "&", "?", "=", }; int get_symbol(char *command, size_t len, char *output) { for (size_t i = 0; i < len; i++) { for (size_t j = 0; j < 4; j++) { if (command[i] == symbols[j][0]) { memcpy(output, symbols[j], 2); return ESP_OK; } } } return ESP_FAIL; } esp_err_t parse_at_message(uint8_t *at_command, at_request_t *output) { size_t at_size = strlen((char *)at_command) + 1; char commands[at_size]; memcpy(commands, at_command, at_size); char plus[2]; memset(plus, "0", sizeof(plus)); get_symbol(commands, at_size, plus); char *key = strtok(commands, plus); char first_step[100]; char *key_value = NULL; char *value = NULL; int i = 0; char second_character[2]; while (key != NULL) { if (i == 1) { memcpy(first_step, key, sizeof(first_step)); } i++; key = strtok(NULL, plus); } get_symbol(first_step, at_size, second_character); char *key2 = strtok(first_step, second_character); i = 0; while (key2 != NULL) { if (i == 0) { key_value = (char *)malloc(strlen(key2) + 1); memset(key_value, 0, strlen(key2) + 1); memcpy(key_value, key2, strlen(key2) + 1); } if (i == 1) { value = (char *)malloc(strlen(key2) + 1); memcpy(value, key2, strlen(key2) + 1); } i++; key2 = strtok(NULL, "+"); } /* cppcheck-suppress nullPointerRedundantCheck * (reason: <is necessary verify that this data is not null>) */ memcpy(output->key, key_value, strlen(key_value) + 1); if (value != NULL) { memcpy(output->value, value, strlen(value) + 1); } memcpy(output->action, plus, 2); memcpy(output->read_or_write, second_character, 2); if (key_value == NULL && value == NULL) { return ESP_FAIL; } free(value); free(key_value); return ESP_OK; } int at_cmd_to_name(char *key) { for (size_t i = 0; i < ARRAY_SIZE; i++) { key[strlen(key)] = 0; if (strcmp(key, default_keys[i]) == 0) { return i; } } return -1; } void action_request(enum at_keys_n at_key, at_request_t *payload) { esp_err_t err = ESP_FAIL; switch (at_key) { case (NVS_RST): err = wifi_restore_default(); break; case (WIFI_OFF): err = wifi_turn_off(); break; case (WIFI_ON): err = wifi_on(); break; case (WIFI_RST): err = wifi_restart(); break; default: ESP_LOGE(__func__, "unhandler event %i \n", at_key); err = ESP_FAIL; break; } if (err != ESP_OK) { sendData(__func__, "\r\n400\r\n"); } else { sendData(__func__, "\r\n200\r\n"); } } void write_request(enum at_keys_n at_key, at_request_t *payload) { int wifi_mode = 0; uint8_t channel = 0; uint8_t max_connection = 0; uint8_t auth = 0; esp_err_t err = ESP_FAIL; if (strcmp(payload->read_or_write, symbols[2]) == 0) { ESP_LOGI(__func__, "read AT request"); err = ESP_OK; // read AT request is not defined yet. } else if (strcmp(payload->read_or_write, symbols[3]) == 0) { switch (at_key) { case (WAP_SSID): err = change_wifi_ap_ssid(payload->value); break; case (WAP_PASS): err = change_wifi_ap_pass(payload->value); break; case (WAP_CHAN): channel = atoi(payload->value); err = select_wifi_channel(channel); break; case (WAP_AUTH): auth = atoi(payload->value); err = change_ap_auth(auth); break; case (WIFI_MODE): wifi_mode = atoi(payload->value); err = change_wifi_mode(wifi_mode); break; case (WSTA_SSID): err = change_wifi_sta_ssid(payload->value); break; case (WSTA_PASS): err = change_wifi_sta_pass(payload->value); break; default: ESP_LOGE(__func__, "unhandler event %i \n", at_key); err = ESP_FAIL; break; } } if (err != ESP_OK) { sendData(__func__, "\r\n400\r\n"); } else { sendData(__func__, "\r\n200\r\n"); } } void at_handler(uint8_t *at_command) { ESP_LOGI(__func__, "enter in at handler"); at_request_t payload; payload.key = (char *)malloc(32); payload.value = (char *)malloc(32); parse_at_message(at_command, &payload); enum at_keys_n at_key = at_cmd_to_name(payload.key); ESP_LOGI(__func__, "the key is %d the string key is %s and %s and %s and %s", at_key, payload.key, payload.value, payload.action, payload.read_or_write); if (strcmp(payload.action, symbols[0]) == 0) { write_request(at_key, &payload); } else if (strcmp(payload.action, symbols[1]) == 0) { action_request(at_key, &payload); } else { sendData(__func__, "\r\n400\r\n"); } }
670513.c
/* Implementation of the PRODUCT intrinsic Copyright 2002 Free Software Foundation, Inc. Contributed by Paul Brook <[email protected]> This file is part of the GNU Fortran 95 runtime library (libgfortran). Libgfortran 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. In addition to the permissions in the GNU General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file into combinations with other programs, and to distribute those combinations without any restriction coming from the use of this file. (The General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into a combine executable.) Libgfortran 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 libgfortran; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include <stdlib.h> #include <assert.h> #include "libgfortran.h" #if defined (HAVE_GFC_COMPLEX_4) && defined (HAVE_GFC_COMPLEX_4) extern void product_c4 (gfc_array_c4 * const restrict, gfc_array_c4 * const restrict, const index_type * const restrict); export_proto(product_c4); void product_c4 (gfc_array_c4 * const restrict retarray, gfc_array_c4 * const restrict array, const index_type * const restrict pdim) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type dstride[GFC_MAX_DIMENSIONS]; const GFC_COMPLEX_4 * restrict base; GFC_COMPLEX_4 * restrict dest; index_type rank; index_type n; index_type len; index_type delta; index_type dim; /* Make dim zero based to avoid confusion. */ dim = (*pdim) - 1; rank = GFC_DESCRIPTOR_RANK (array) - 1; len = array->dim[dim].ubound + 1 - array->dim[dim].lbound; delta = array->dim[dim].stride; for (n = 0; n < dim; n++) { sstride[n] = array->dim[n].stride; extent[n] = array->dim[n].ubound + 1 - array->dim[n].lbound; if (extent[n] < 0) extent[n] = 0; } for (n = dim; n < rank; n++) { sstride[n] = array->dim[n + 1].stride; extent[n] = array->dim[n + 1].ubound + 1 - array->dim[n + 1].lbound; if (extent[n] < 0) extent[n] = 0; } if (retarray->data == NULL) { size_t alloc_size; for (n = 0; n < rank; n++) { retarray->dim[n].lbound = 0; retarray->dim[n].ubound = extent[n]-1; if (n == 0) retarray->dim[n].stride = 1; else retarray->dim[n].stride = retarray->dim[n-1].stride * extent[n-1]; } retarray->offset = 0; retarray->dtype = (array->dtype & ~GFC_DTYPE_RANK_MASK) | rank; alloc_size = sizeof (GFC_COMPLEX_4) * retarray->dim[rank-1].stride * extent[rank-1]; if (alloc_size == 0) { /* Make sure we have a zero-sized array. */ retarray->dim[0].lbound = 0; retarray->dim[0].ubound = -1; return; } else retarray->data = internal_malloc_size (alloc_size); } else { if (rank != GFC_DESCRIPTOR_RANK (retarray)) runtime_error ("rank of return array incorrect"); } for (n = 0; n < rank; n++) { count[n] = 0; dstride[n] = retarray->dim[n].stride; if (extent[n] <= 0) len = 0; } base = array->data; dest = retarray->data; while (base) { const GFC_COMPLEX_4 * restrict src; GFC_COMPLEX_4 result; src = base; { result = 1; if (len <= 0) *dest = 1; else { for (n = 0; n < len; n++, src += delta) { result *= *src; } *dest = result; } } /* Advance to the next element. */ count[0]++; base += sstride[0]; dest += dstride[0]; n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; dest -= dstride[n] * extent[n]; n++; if (n == rank) { /* Break out of the look. */ base = NULL; break; } else { count[n]++; base += sstride[n]; dest += dstride[n]; } } } } extern void mproduct_c4 (gfc_array_c4 * const restrict, gfc_array_c4 * const restrict, const index_type * const restrict, gfc_array_l4 * const restrict); export_proto(mproduct_c4); void mproduct_c4 (gfc_array_c4 * const restrict retarray, gfc_array_c4 * const restrict array, const index_type * const restrict pdim, gfc_array_l4 * const restrict mask) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type sstride[GFC_MAX_DIMENSIONS]; index_type dstride[GFC_MAX_DIMENSIONS]; index_type mstride[GFC_MAX_DIMENSIONS]; GFC_COMPLEX_4 * restrict dest; const GFC_COMPLEX_4 * restrict base; const GFC_LOGICAL_4 * restrict mbase; int rank; int dim; index_type n; index_type len; index_type delta; index_type mdelta; dim = (*pdim) - 1; rank = GFC_DESCRIPTOR_RANK (array) - 1; len = array->dim[dim].ubound + 1 - array->dim[dim].lbound; if (len <= 0) return; delta = array->dim[dim].stride; mdelta = mask->dim[dim].stride; for (n = 0; n < dim; n++) { sstride[n] = array->dim[n].stride; mstride[n] = mask->dim[n].stride; extent[n] = array->dim[n].ubound + 1 - array->dim[n].lbound; if (extent[n] < 0) extent[n] = 0; } for (n = dim; n < rank; n++) { sstride[n] = array->dim[n + 1].stride; mstride[n] = mask->dim[n + 1].stride; extent[n] = array->dim[n + 1].ubound + 1 - array->dim[n + 1].lbound; if (extent[n] < 0) extent[n] = 0; } if (retarray->data == NULL) { size_t alloc_size; for (n = 0; n < rank; n++) { retarray->dim[n].lbound = 0; retarray->dim[n].ubound = extent[n]-1; if (n == 0) retarray->dim[n].stride = 1; else retarray->dim[n].stride = retarray->dim[n-1].stride * extent[n-1]; } alloc_size = sizeof (GFC_COMPLEX_4) * retarray->dim[rank-1].stride * extent[rank-1]; retarray->offset = 0; retarray->dtype = (array->dtype & ~GFC_DTYPE_RANK_MASK) | rank; if (alloc_size == 0) { /* Make sure we have a zero-sized array. */ retarray->dim[0].lbound = 0; retarray->dim[0].ubound = -1; return; } else retarray->data = internal_malloc_size (alloc_size); } else { if (rank != GFC_DESCRIPTOR_RANK (retarray)) runtime_error ("rank of return array incorrect"); } for (n = 0; n < rank; n++) { count[n] = 0; dstride[n] = retarray->dim[n].stride; if (extent[n] <= 0) return; } dest = retarray->data; base = array->data; mbase = mask->data; if (GFC_DESCRIPTOR_SIZE (mask) != 4) { /* This allows the same loop to be used for all logical types. */ assert (GFC_DESCRIPTOR_SIZE (mask) == 8); for (n = 0; n < rank; n++) mstride[n] <<= 1; mdelta <<= 1; mbase = (GFOR_POINTER_L8_TO_L4 (mbase)); } while (base) { const GFC_COMPLEX_4 * restrict src; const GFC_LOGICAL_4 * restrict msrc; GFC_COMPLEX_4 result; src = base; msrc = mbase; { result = 1; if (len <= 0) *dest = 1; else { for (n = 0; n < len; n++, src += delta, msrc += mdelta) { if (*msrc) result *= *src; } *dest = result; } } /* Advance to the next element. */ count[0]++; base += sstride[0]; mbase += mstride[0]; dest += dstride[0]; n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ base -= sstride[n] * extent[n]; mbase -= mstride[n] * extent[n]; dest -= dstride[n] * extent[n]; n++; if (n == rank) { /* Break out of the look. */ base = NULL; break; } else { count[n]++; base += sstride[n]; mbase += mstride[n]; dest += dstride[n]; } } } } extern void sproduct_c4 (gfc_array_c4 * const restrict, gfc_array_c4 * const restrict, const index_type * const restrict, GFC_LOGICAL_4 *); export_proto(sproduct_c4); void sproduct_c4 (gfc_array_c4 * const restrict retarray, gfc_array_c4 * const restrict array, const index_type * const restrict pdim, GFC_LOGICAL_4 * mask) { index_type rank; index_type n; index_type dstride; GFC_COMPLEX_4 *dest; if (*mask) { product_c4 (retarray, array, pdim); return; } rank = GFC_DESCRIPTOR_RANK (array); if (rank <= 0) runtime_error ("Rank of array needs to be > 0"); if (retarray->data == NULL) { retarray->dim[0].lbound = 0; retarray->dim[0].ubound = rank-1; retarray->dim[0].stride = 1; retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1; retarray->offset = 0; retarray->data = internal_malloc_size (sizeof (GFC_COMPLEX_4) * rank); } else { if (GFC_DESCRIPTOR_RANK (retarray) != 1) runtime_error ("rank of return array does not equal 1"); if (retarray->dim[0].ubound + 1 - retarray->dim[0].lbound != rank) runtime_error ("dimension of return array incorrect"); } dstride = retarray->dim[0].stride; dest = retarray->data; for (n = 0; n < rank; n++) dest[n * dstride] = 1 ; } #endif
356980.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "S1AP-IEs" * found in "r14.4.0/36413-e40.asn" * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps -no-gen-example` */ #include "EUTRANRoundTripDelayEstimationInfo.h" int EUTRANRoundTripDelayEstimationInfo_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= 0 && value <= 2047)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ static asn_oer_constraints_t asn_OER_type_EUTRANRoundTripDelayEstimationInfo_constr_1 CC_NOTUSED = { { 2, 1 } /* (0..2047) */, -1}; static asn_per_constraints_t asn_PER_type_EUTRANRoundTripDelayEstimationInfo_constr_1 CC_NOTUSED = { { APC_CONSTRAINED, 11, 11, 0, 2047 } /* (0..2047) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static const ber_tlv_tag_t asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_EUTRANRoundTripDelayEstimationInfo = { "EUTRANRoundTripDelayEstimationInfo", "EUTRANRoundTripDelayEstimationInfo", &asn_OP_NativeInteger, asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1, sizeof(asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1) /sizeof(asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1[0]), /* 1 */ asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1, /* Same as above */ sizeof(asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1) /sizeof(asn_DEF_EUTRANRoundTripDelayEstimationInfo_tags_1[0]), /* 1 */ { &asn_OER_type_EUTRANRoundTripDelayEstimationInfo_constr_1, &asn_PER_type_EUTRANRoundTripDelayEstimationInfo_constr_1, EUTRANRoundTripDelayEstimationInfo_constraint }, 0, 0, /* No members */ 0 /* No specifics */ };
657255.c
/* * WPA Supplicant / dbus-based control interface * Copyright (c) 2006, Dan Williams <[email protected]> and Red Hat, Inc. * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include <dbus/dbus.h> #include "common.h" #include "eloop.h" #include "wps/wps.h" #include "../config.h" #include "../wpa_supplicant_i.h" #include "../bss.h" #include "dbus_old.h" #include "dbus_old_handlers.h" #include "dbus_common_i.h" /** * wpas_dbus_decompose_object_path - Decompose an interface object path into parts * @path: The dbus object path * @network: (out) the configured network this object path refers to, if any * @bssid: (out) the scanned bssid this object path refers to, if any * Returns: The object path of the network interface this path refers to * * For a given object path, decomposes the object path into object id, network, * and BSSID parts, if those parts exist. */ char * wpas_dbus_decompose_object_path(const char *path, char **network, char **bssid) { const unsigned int dev_path_prefix_len = strlen(WPAS_DBUS_PATH_INTERFACES "/"); char *obj_path_only; char *next_sep; /* Be a bit paranoid about path */ if (!path || strncmp(path, WPAS_DBUS_PATH_INTERFACES "/", dev_path_prefix_len)) return NULL; /* Ensure there's something at the end of the path */ if ((path + dev_path_prefix_len)[0] == '\0') return NULL; obj_path_only = os_strdup(path); if (obj_path_only == NULL) return NULL; next_sep = strchr(obj_path_only + dev_path_prefix_len, '/'); if (next_sep != NULL) { const char *net_part = strstr(next_sep, WPAS_DBUS_NETWORKS_PART "/"); const char *bssid_part = strstr(next_sep, WPAS_DBUS_BSSIDS_PART "/"); if (network && net_part) { /* Deal with a request for a configured network */ const char *net_name = net_part + strlen(WPAS_DBUS_NETWORKS_PART "/"); *network = NULL; if (strlen(net_name)) *network = os_strdup(net_name); } else if (bssid && bssid_part) { /* Deal with a request for a scanned BSSID */ const char *bssid_name = bssid_part + strlen(WPAS_DBUS_BSSIDS_PART "/"); if (strlen(bssid_name)) *bssid = os_strdup(bssid_name); else *bssid = NULL; } /* Cut off interface object path before "/" */ *next_sep = '\0'; } return obj_path_only; } /** * wpas_dbus_new_invalid_iface_error - Return a new invalid interface error message * @message: Pointer to incoming dbus message this error refers to * Returns: A dbus error message * * Convenience function to create and return an invalid interface error */ DBusMessage * wpas_dbus_new_invalid_iface_error(DBusMessage *message) { return dbus_message_new_error(message, WPAS_ERROR_INVALID_IFACE, "wpa_supplicant knows nothing about " "this interface."); } /** * wpas_dbus_new_invalid_network_error - Return a new invalid network error message * @message: Pointer to incoming dbus message this error refers to * Returns: a dbus error message * * Convenience function to create and return an invalid network error */ DBusMessage * wpas_dbus_new_invalid_network_error(DBusMessage *message) { return dbus_message_new_error(message, WPAS_ERROR_INVALID_NETWORK, "The requested network does not exist."); } /** * wpas_dbus_new_invalid_bssid_error - Return a new invalid bssid error message * @message: Pointer to incoming dbus message this error refers to * Returns: a dbus error message * * Convenience function to create and return an invalid bssid error */ static DBusMessage * wpas_dbus_new_invalid_bssid_error(DBusMessage *message) { return dbus_message_new_error(message, WPAS_ERROR_INVALID_BSSID, "The BSSID requested was invalid."); } /** * wpas_dispatch_network_method - dispatch messages for configured networks * @message: the incoming dbus message * @wpa_s: a network interface's data * @network_id: id of the configured network we're interested in * Returns: a reply dbus message, or a dbus error message * * This function dispatches all incoming dbus messages for configured networks. */ static DBusMessage * wpas_dispatch_network_method(DBusMessage *message, struct wpa_supplicant *wpa_s, int network_id) { DBusMessage *reply = NULL; const char *method = dbus_message_get_member(message); struct wpa_ssid *ssid; ssid = wpa_config_get_network(wpa_s->conf, network_id); if (ssid == NULL) return wpas_dbus_new_invalid_network_error(message); if (!strcmp(method, "set")) reply = wpas_dbus_iface_set_network(message, wpa_s, ssid); else if (!strcmp(method, "enable")) reply = wpas_dbus_iface_enable_network(message, wpa_s, ssid); else if (!strcmp(method, "disable")) reply = wpas_dbus_iface_disable_network(message, wpa_s, ssid); return reply; } /** * wpas_dispatch_bssid_method - dispatch messages for scanned networks * @message: the incoming dbus message * @wpa_s: a network interface's data * @bssid: bssid of the scanned network we're interested in * Returns: a reply dbus message, or a dbus error message * * This function dispatches all incoming dbus messages for scanned networks. */ static DBusMessage * wpas_dispatch_bssid_method(DBusMessage *message, struct wpa_supplicant *wpa_s, const char *bssid_txt) { u8 bssid[ETH_ALEN]; struct wpa_bss *bss; if (hexstr2bin(bssid_txt, bssid, ETH_ALEN) < 0) return wpas_dbus_new_invalid_bssid_error(message); bss = wpa_bss_get_bssid(wpa_s, bssid); if (bss == NULL) return wpas_dbus_new_invalid_bssid_error(message); /* Dispatch the method call against the scanned bssid */ if (os_strcmp(dbus_message_get_member(message), "properties") == 0) return wpas_dbus_bssid_properties(message, wpa_s, bss); return NULL; } /** * wpas_iface_message_handler - Dispatch messages for interfaces or networks * @connection: Connection to the system message bus * @message: An incoming dbus message * @user_data: A pointer to a dbus control interface data structure * Returns: Whether or not the message was handled * * This function dispatches all incoming dbus messages for network interfaces, * or objects owned by them, such as scanned BSSIDs and configured networks. */ static DBusHandlerResult wpas_iface_message_handler(DBusConnection *connection, DBusMessage *message, void *user_data) { struct wpa_supplicant *wpa_s = user_data; const char *method = dbus_message_get_member(message); const char *path = dbus_message_get_path(message); const char *msg_interface = dbus_message_get_interface(message); char *iface_obj_path = NULL; char *network = NULL; char *bssid = NULL; DBusMessage *reply = NULL; /* Caller must specify a message interface */ if (!msg_interface) goto out; iface_obj_path = wpas_dbus_decompose_object_path(path, &network, &bssid); if (iface_obj_path == NULL) { reply = wpas_dbus_new_invalid_iface_error(message); goto out; } /* Make sure the message's object path actually refers to the * wpa_supplicant structure it's supposed to (which is wpa_s) */ if (wpa_supplicant_get_iface_by_dbus_path(wpa_s->global, iface_obj_path) != wpa_s) { reply = wpas_dbus_new_invalid_iface_error(message); goto out; } if (network && !strcmp(msg_interface, WPAS_DBUS_IFACE_NETWORK)) { /* A method for one of this interface's configured networks */ int nid = strtoul(network, NULL, 10); if (errno != EINVAL) reply = wpas_dispatch_network_method(message, wpa_s, nid); else reply = wpas_dbus_new_invalid_network_error(message); } else if (bssid && !strcmp(msg_interface, WPAS_DBUS_IFACE_BSSID)) { /* A method for one of this interface's scanned BSSIDs */ reply = wpas_dispatch_bssid_method(message, wpa_s, bssid); } else if (!strcmp(msg_interface, WPAS_DBUS_IFACE_INTERFACE)) { /* A method for an interface only. */ if (!strcmp(method, "scan")) reply = wpas_dbus_iface_scan(message, wpa_s); else if (!strcmp(method, "scanResults")) reply = wpas_dbus_iface_scan_results(message, wpa_s); else if (!strcmp(method, "addNetwork")) reply = wpas_dbus_iface_add_network(message, wpa_s); else if (!strcmp(method, "removeNetwork")) reply = wpas_dbus_iface_remove_network(message, wpa_s); else if (!strcmp(method, "selectNetwork")) reply = wpas_dbus_iface_select_network(message, wpa_s); else if (!strcmp(method, "capabilities")) reply = wpas_dbus_iface_capabilities(message, wpa_s); else if (!strcmp(method, "disconnect")) reply = wpas_dbus_iface_disconnect(message, wpa_s); else if (!strcmp(method, "setAPScan")) reply = wpas_dbus_iface_set_ap_scan(message, wpa_s); else if (!strcmp(method, "setSmartcardModules")) reply = wpas_dbus_iface_set_smartcard_modules(message, wpa_s); else if (!strcmp(method, "state")) reply = wpas_dbus_iface_get_state(message, wpa_s); else if (!strcmp(method, "scanning")) reply = wpas_dbus_iface_get_scanning(message, wpa_s); #ifndef CONFIG_NO_CONFIG_BLOBS else if (!strcmp(method, "setBlobs")) reply = wpas_dbus_iface_set_blobs(message, wpa_s); else if (!strcmp(method, "removeBlobs")) reply = wpas_dbus_iface_remove_blobs(message, wpa_s); #endif /* CONFIG_NO_CONFIG_BLOBS */ #ifdef CONFIG_WPS else if (!os_strcmp(method, "wpsPbc")) reply = wpas_dbus_iface_wps_pbc(message, wpa_s); else if (!os_strcmp(method, "wpsPin")) reply = wpas_dbus_iface_wps_pin(message, wpa_s); else if (!os_strcmp(method, "wpsReg")) reply = wpas_dbus_iface_wps_reg(message, wpa_s); #endif /* CONFIG_WPS */ else if (!os_strcmp(method, "flush")) reply = wpas_dbus_iface_flush(message, wpa_s); } /* If the message was handled, send back the reply */ if (reply) { if (!dbus_message_get_no_reply(message)) dbus_connection_send(connection, reply, NULL); dbus_message_unref(reply); } out: os_free(iface_obj_path); os_free(network); os_free(bssid); return reply ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } /** * wpas_message_handler - dispatch incoming dbus messages * @connection: connection to the system message bus * @message: an incoming dbus message * @user_data: a pointer to a dbus control interface data structure * Returns: whether or not the message was handled * * This function dispatches all incoming dbus messages to the correct * handlers, depending on what the message's target object path is, * and what the method call is. */ static DBusHandlerResult wpas_message_handler(DBusConnection *connection, DBusMessage *message, void *user_data) { struct wpas_dbus_priv *ctrl_iface = user_data; const char *method; const char *path; const char *msg_interface; DBusMessage *reply = NULL; method = dbus_message_get_member(message); path = dbus_message_get_path(message); msg_interface = dbus_message_get_interface(message); if (!method || !path || !ctrl_iface || !msg_interface) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; /* Validate the method interface */ if (strcmp(msg_interface, WPAS_DBUS_INTERFACE) != 0) return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; if (!strcmp(path, WPAS_DBUS_PATH)) { /* dispatch methods against our global dbus interface here */ if (!strcmp(method, "addInterface")) { reply = wpas_dbus_global_add_interface( message, ctrl_iface->global); } else if (!strcmp(method, "removeInterface")) { reply = wpas_dbus_global_remove_interface( message, ctrl_iface->global); } else if (!strcmp(method, "getInterface")) { reply = wpas_dbus_global_get_interface( message, ctrl_iface->global); } else if (!strcmp(method, "setDebugParams")) { reply = wpas_dbus_global_set_debugparams( message, ctrl_iface->global); } } /* If the message was handled, send back the reply */ if (reply) { if (!dbus_message_get_no_reply(message)) dbus_connection_send(connection, reply, NULL); dbus_message_unref(reply); } return reply ? DBUS_HANDLER_RESULT_HANDLED : DBUS_HANDLER_RESULT_NOT_YET_HANDLED; } /** * wpa_supplicant_dbus_notify_scan_results - Send a scan results signal * @wpa_s: %wpa_supplicant network interface data * Returns: 0 on success, -1 on failure * * Notify listeners that this interface has updated scan results. */ void wpa_supplicant_dbus_notify_scan_results(struct wpa_supplicant *wpa_s) { struct wpas_dbus_priv *iface = wpa_s->global->dbus; DBusMessage *_signal; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; _signal = dbus_message_new_signal(wpa_s->dbus_path, WPAS_DBUS_IFACE_INTERFACE, "ScanResultsAvailable"); if (_signal == NULL) { wpa_printf(MSG_ERROR, "dbus: Not enough memory to send scan " "results signal"); return; } dbus_connection_send(iface->con, _signal, NULL); dbus_message_unref(_signal); } /** * wpa_supplicant_dbus_notify_state_change - Send a state change signal * @wpa_s: %wpa_supplicant network interface data * @new_state: new state wpa_supplicant is entering * @old_state: old state wpa_supplicant is leaving * Returns: 0 on success, -1 on failure * * Notify listeners that wpa_supplicant has changed state */ void wpa_supplicant_dbus_notify_state_change(struct wpa_supplicant *wpa_s, enum wpa_states new_state, enum wpa_states old_state) { struct wpas_dbus_priv *iface; DBusMessage *_signal = NULL; const char *new_state_str, *old_state_str; if (wpa_s->dbus_path == NULL) return; /* Skip signal since D-Bus setup is not yet ready */ /* Do nothing if the control interface is not turned on */ if (wpa_s->global == NULL) return; iface = wpa_s->global->dbus; if (iface == NULL) return; /* Only send signal if state really changed */ if (new_state == old_state) return; _signal = dbus_message_new_signal(wpa_s->dbus_path, WPAS_DBUS_IFACE_INTERFACE, "StateChange"); if (_signal == NULL) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_state_change: " "could not create dbus signal; likely out of " "memory"); return; } new_state_str = wpa_supplicant_state_txt(new_state); old_state_str = wpa_supplicant_state_txt(old_state); if (new_state_str == NULL || old_state_str == NULL) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_state_change: " "Could not convert state strings"); goto out; } if (!dbus_message_append_args(_signal, DBUS_TYPE_STRING, &new_state_str, DBUS_TYPE_STRING, &old_state_str, DBUS_TYPE_INVALID)) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_state_change: " "Not enough memory to construct state change " "signal"); goto out; } dbus_connection_send(iface->con, _signal, NULL); out: dbus_message_unref(_signal); } /** * wpa_supplicant_dbus_notify_scanning - send scanning status * @wpa_s: %wpa_supplicant network interface data * Returns: 0 on success, -1 on failure * * Notify listeners of interface scanning state changes */ void wpa_supplicant_dbus_notify_scanning(struct wpa_supplicant *wpa_s) { struct wpas_dbus_priv *iface = wpa_s->global->dbus; DBusMessage *_signal; dbus_bool_t scanning = wpa_s->scanning ? TRUE : FALSE; /* Do nothing if the control interface is not turned on */ if (iface == NULL) return; _signal = dbus_message_new_signal(wpa_s->dbus_path, WPAS_DBUS_IFACE_INTERFACE, "Scanning"); if (_signal == NULL) { wpa_printf(MSG_ERROR, "dbus: Not enough memory to send scan " "results signal"); return; } if (dbus_message_append_args(_signal, DBUS_TYPE_BOOLEAN, &scanning, DBUS_TYPE_INVALID)) { dbus_connection_send(iface->con, _signal, NULL); } else { wpa_printf(MSG_ERROR, "dbus: Not enough memory to construct " "signal"); } dbus_message_unref(_signal); } #ifdef CONFIG_WPS void wpa_supplicant_dbus_notify_wps_cred(struct wpa_supplicant *wpa_s, const struct wps_credential *cred) { struct wpas_dbus_priv *iface; DBusMessage *_signal = NULL; /* Do nothing if the control interface is not turned on */ if (wpa_s->global == NULL) return; iface = wpa_s->global->dbus; if (iface == NULL) return; _signal = dbus_message_new_signal(wpa_s->dbus_path, WPAS_DBUS_IFACE_INTERFACE, "WpsCred"); if (_signal == NULL) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_wps_cred: " "Could not create dbus signal; likely out of " "memory"); return; } if (!dbus_message_append_args(_signal, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &cred->cred_attr, cred->cred_attr_len, DBUS_TYPE_INVALID)) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_wps_cred: " "Not enough memory to construct signal"); goto out; } dbus_connection_send(iface->con, _signal, NULL); out: dbus_message_unref(_signal); } #else /* CONFIG_WPS */ void wpa_supplicant_dbus_notify_wps_cred(struct wpa_supplicant *wpa_s, const struct wps_credential *cred) { } #endif /* CONFIG_WPS */ void wpa_supplicant_dbus_notify_certification(struct wpa_supplicant *wpa_s, int depth, const char *subject, const char *cert_hash, const struct wpabuf *cert) { struct wpas_dbus_priv *iface; DBusMessage *_signal = NULL; const char *hash; const char *cert_hex; int cert_hex_len; /* Do nothing if the control interface is not turned on */ if (wpa_s->global == NULL) return; iface = wpa_s->global->dbus; if (iface == NULL) return; _signal = dbus_message_new_signal(wpa_s->dbus_path, WPAS_DBUS_IFACE_INTERFACE, "Certification"); if (_signal == NULL) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_certification: " "Could not create dbus signal; likely out of " "memory"); return; } hash = cert_hash ? cert_hash : ""; cert_hex = cert ? wpabuf_head(cert) : ""; cert_hex_len = cert ? wpabuf_len(cert) : 0; if (!dbus_message_append_args(_signal, DBUS_TYPE_INT32,&depth, DBUS_TYPE_STRING, &subject, DBUS_TYPE_STRING, &hash, DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &cert_hex, cert_hex_len, DBUS_TYPE_INVALID)) { wpa_printf(MSG_ERROR, "dbus: wpa_supplicant_dbus_notify_certification: " "Not enough memory to construct signal"); goto out; } dbus_connection_send(iface->con, _signal, NULL); out: dbus_message_unref(_signal); } /** * wpa_supplicant_dbus_ctrl_iface_init - Initialize dbus control interface * @global: Pointer to global data from wpa_supplicant_init() * Returns: 0 on success, -1 on failure * * Initialize the dbus control interface and start receiving commands from * external programs over the bus. */ int wpa_supplicant_dbus_ctrl_iface_init(struct wpas_dbus_priv *iface) { DBusError error; int ret = -1; DBusObjectPathVTable wpas_vtable = { NULL, &wpas_message_handler, NULL, NULL, NULL, NULL }; /* Register the message handler for the global dbus interface */ if (!dbus_connection_register_object_path(iface->con, WPAS_DBUS_PATH, &wpas_vtable, iface)) { wpa_printf(MSG_ERROR, "dbus: Could not set up message " "handler"); return -1; } /* Register our service with the message bus */ dbus_error_init(&error); switch (dbus_bus_request_name(iface->con, WPAS_DBUS_SERVICE, 0, &error)) { case DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: ret = 0; break; case DBUS_REQUEST_NAME_REPLY_EXISTS: case DBUS_REQUEST_NAME_REPLY_IN_QUEUE: case DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER: wpa_printf(MSG_ERROR, "dbus: Could not request service name: " "already registered"); break; default: wpa_printf(MSG_ERROR, "dbus: Could not request service name: " "%s %s", error.name, error.message); break; } dbus_error_free(&error); if (ret != 0) return -1; wpa_printf(MSG_DEBUG, "Providing DBus service '" WPAS_DBUS_SERVICE "'."); return 0; } /** * wpas_dbus_register_new_iface - Register a new interface with dbus * @wpa_s: %wpa_supplicant interface description structure to register * Returns: 0 on success, -1 on error * * Registers a new interface with dbus and assigns it a dbus object path. */ int wpas_dbus_register_iface(struct wpa_supplicant *wpa_s) { struct wpas_dbus_priv *ctrl_iface = wpa_s->global->dbus; DBusConnection * con; u32 next; DBusObjectPathVTable vtable = { NULL, &wpas_iface_message_handler, NULL, NULL, NULL, NULL }; /* Do nothing if the control interface is not turned on */ if (ctrl_iface == NULL) return 0; con = ctrl_iface->con; next = ctrl_iface->next_objid++; /* Create and set the interface's object path */ wpa_s->dbus_path = os_zalloc(WPAS_DBUS_OBJECT_PATH_MAX); if (wpa_s->dbus_path == NULL) return -1; os_snprintf(wpa_s->dbus_path, WPAS_DBUS_OBJECT_PATH_MAX, WPAS_DBUS_PATH_INTERFACES "/%u", next); /* Register the message handler for the interface functions */ if (!dbus_connection_register_fallback(con, wpa_s->dbus_path, &vtable, wpa_s)) { wpa_printf(MSG_ERROR, "dbus: Could not set up message " "handler for interface %s", wpa_s->ifname); return -1; } return 0; } /** * wpas_dbus_unregister_iface - Unregister an interface from dbus * @wpa_s: wpa_supplicant interface structure * Returns: 0 on success, -1 on failure * * Unregisters the interface with dbus */ int wpas_dbus_unregister_iface(struct wpa_supplicant *wpa_s) { struct wpas_dbus_priv *ctrl_iface; DBusConnection *con; /* Do nothing if the control interface is not turned on */ if (wpa_s == NULL || wpa_s->global == NULL) return 0; ctrl_iface = wpa_s->global->dbus; if (ctrl_iface == NULL) return 0; con = ctrl_iface->con; if (!dbus_connection_unregister_object_path(con, wpa_s->dbus_path)) return -1; os_free(wpa_s->dbus_path); wpa_s->dbus_path = NULL; return 0; } /** * wpa_supplicant_get_iface_by_dbus_path - Get a new network interface * @global: Pointer to global data from wpa_supplicant_init() * @path: Pointer to a dbus object path representing an interface * Returns: Pointer to the interface or %NULL if not found */ struct wpa_supplicant * wpa_supplicant_get_iface_by_dbus_path( struct wpa_global *global, const char *path) { struct wpa_supplicant *wpa_s; for (wpa_s = global->ifaces; wpa_s; wpa_s = wpa_s->next) { if (strcmp(wpa_s->dbus_path, path) == 0) return wpa_s; } return NULL; }
417007.c
// Auto-generated file. Do not edit! // Template: src/qs8-gemm/MRx4c2-sse.c.in // Generator: tools/xngen // // Copyright 2020 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <assert.h> #include <emmintrin.h> #include <xnnpack/gemm.h> #include <xnnpack/math.h> void xnn_qs8_gemm_xw_minmax_gemmlowp_ukernel_1x4c2__sse2( size_t mr, size_t nc, size_t kc, const int8_t* restrict a, size_t a_stride, const void* restrict w, int8_t* restrict c, size_t cm_stride, size_t cn_stride, const union xnn_qs8_conv_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_DISABLE_TSAN XNN_DISABLE_MSAN { assert(mr != 0); assert(mr <= 1); assert(nc != 0); assert(kc != 0); assert(kc % sizeof(int8_t) == 0); assert(a != NULL); assert(w != NULL); assert(c != NULL); kc = round_up_po2(kc, 2); const int8_t* a0 = a; int8_t* c0 = c; do { __m128i vacc0x0123 = _mm_loadu_si128((const __m128i*) w); w = (const void*) ((uintptr_t) w + 4 * sizeof(int32_t)); size_t k = kc; while (k >= 8 * sizeof(int8_t)) { const __m128i va0 = _mm_loadl_epi64((const __m128i*) a0); const __m128i vxa0 = _mm_unpacklo_epi8(va0, _mm_cmpgt_epi8(_mm_setzero_si128(), va0)); a0 += 8; const __m128i vxb0 = _mm_load_si128((const __m128i*) w); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0)); const __m128i vxb1 = _mm_load_si128((const __m128i*) ((uintptr_t) w + 8 * sizeof(int16_t))); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1)); const __m128i vxb2 = _mm_load_si128((const __m128i*) ((uintptr_t) w + 16 * sizeof(int16_t))); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2)); const __m128i vxb3 = _mm_load_si128((const __m128i*) ((uintptr_t) w + 24 * sizeof(int16_t))); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(3, 3, 3, 3)), vxb3)); w = (const void*) ((uintptr_t) w + 32 * sizeof(int16_t)); k -= 8 * sizeof(int8_t); } if (k != 0) { const __m128i va0 = _mm_loadl_epi64((const __m128i*) a0); const __m128i vxa0 = _mm_unpacklo_epi8(va0, _mm_cmpgt_epi8(_mm_setzero_si128(), va0)); a0 = (const int8_t*) ((uintptr_t) a0 + k); const __m128i vxb0 = _mm_load_si128((const __m128i*) w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int16_t)); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(0, 0, 0, 0)), vxb0)); if (k > 2 * sizeof(int8_t)) { const __m128i vxb1 = _mm_load_si128((const __m128i*) w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int16_t)); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(1, 1, 1, 1)), vxb1)); if (k > 4 * sizeof(int8_t)) { const __m128i vxb2 = _mm_load_si128((const __m128i*) w); w = (const void*) ((uintptr_t) w + 8 * sizeof(int16_t)); vacc0x0123 = _mm_add_epi32(vacc0x0123, _mm_madd_epi16(_mm_shuffle_epi32(vxa0, _MM_SHUFFLE(2, 2, 2, 2)), vxb2)); } } } const __m128i vmultiplier = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.multiplier); const __m128i vrounding = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.rounding); const __m128i vnmask0x0123 = _mm_cmpgt_epi32(_mm_setzero_si128(), vacc0x0123); const __m128i vabsacc0x0123 = _mm_sub_epi32(_mm_xor_si128(vacc0x0123, vnmask0x0123), vnmask0x0123); const __m128i vabsacc0x1133 = _mm_shuffle_epi32(vabsacc0x0123, _MM_SHUFFLE(3, 3, 1, 1)); const __m128i vabsprod0x02 = _mm_mul_epu32(vabsacc0x0123, vmultiplier); const __m128i vnmask0x02 = _mm_shuffle_epi32(vnmask0x0123, _MM_SHUFFLE(2, 2, 0, 0)); const __m128i vprod0x02 = _mm_sub_epi64(_mm_xor_si128(vabsprod0x02, vnmask0x02), vnmask0x02); const __m128i vq31prod0x02 = _mm_srli_epi64(_mm_add_epi64(vprod0x02, vrounding), 31); const __m128i vabsprod0x13 = _mm_mul_epu32(vabsacc0x1133, vmultiplier); const __m128i vnmask0x13 = _mm_shuffle_epi32(vnmask0x0123, _MM_SHUFFLE(3, 3, 1, 1)); const __m128i vprod0x13 = _mm_sub_epi64(_mm_xor_si128(vabsprod0x13, vnmask0x13), vnmask0x13); const __m128i vq31prod0x13 = _mm_srli_epi64(_mm_add_epi64(vprod0x13, vrounding), 31); const __m128i vq31prod0x0213 = _mm_castps_si128(_mm_shuffle_ps( _mm_castsi128_ps(vq31prod0x02), _mm_castsi128_ps(vq31prod0x13), _MM_SHUFFLE(2, 0, 2, 0))); const __m128i vq31prod0x0123 = _mm_shuffle_epi32(vq31prod0x0213, _MM_SHUFFLE(3, 1, 2, 0)); const __m128i vremainder_mask = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.remainder_mask); const __m128i vrem0x0123 = _mm_add_epi32(_mm_and_si128(vq31prod0x0123, vremainder_mask), _mm_cmpgt_epi32(_mm_setzero_si128(), vq31prod0x0123)); const __m128i vremainder_threshold = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.remainder_threshold); const __m128i vshift = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.shift); vacc0x0123 = _mm_sub_epi32(_mm_sra_epi32(vq31prod0x0123, vshift), _mm_cmpgt_epi32(vrem0x0123, vremainder_threshold)); const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.output_zero_point); __m128i vacc00x0123 = _mm_adds_epi16(_mm_packs_epi32(vacc0x0123, vacc0x0123), voutput_zero_point); const __m128i voutput_min = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.output_min); const __m128i voutput_max = _mm_load_si128((const __m128i*) params->gemmlowp_sse2.output_max); vacc00x0123 = _mm_min_epi16(_mm_max_epi16(vacc00x0123, voutput_min), voutput_max); __m128i vout = _mm_packs_epi16(vacc00x0123, vacc00x0123); if (nc >= 4) { *((uint32_t*) c0) = (uint32_t) _mm_cvtsi128_si32(vout); c0 = (int8_t*) ((uintptr_t) c0 + cn_stride); a0 = (const int8_t*) ((uintptr_t) a0 - kc); nc -= 4; } else { if (nc & 2) { *((uint16_t*) c0) = (uint16_t) _mm_extract_epi16(vout, 0); c0 += 2; vout = _mm_srli_epi32(vout, 16); } if (nc & 1) { *((int8_t*) c0) = (int8_t) _mm_cvtsi128_si32(vout); } nc = 0; } } while (nc != 0); }
390808.c
/* Helper function for repacking arrays. Copyright 2003, 2006, 2007, 2009 Free Software Foundation, Inc. Contributed by Paul Brook <[email protected]> This file is part of the GNU Fortran 95 runtime library (libgfortran). Libgfortran is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. Libgfortran 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. Under Section 7 of GPL version 3, you are granted additional permissions described in the GCC Runtime Library Exception, version 3.1, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License and a copy of the GCC Runtime Library Exception along with this program; see the files COPYING3 and COPYING.RUNTIME respectively. If not, see <http://www.gnu.org/licenses/>. */ #include "libgfortran.h" #include <stdlib.h> #include <assert.h> #include <string.h> #if defined (HAVE_GFC_REAL_8) void internal_unpack_r8 (gfc_array_r8 * d, const GFC_REAL_8 * src) { index_type count[GFC_MAX_DIMENSIONS]; index_type extent[GFC_MAX_DIMENSIONS]; index_type stride[GFC_MAX_DIMENSIONS]; index_type stride0; index_type dim; index_type dsize; GFC_REAL_8 * restrict dest; int n; dest = d->data; if (src == dest || !src) return; dim = GFC_DESCRIPTOR_RANK (d); dsize = 1; for (n = 0; n < dim; n++) { count[n] = 0; stride[n] = d->dim[n].stride; extent[n] = d->dim[n].ubound + 1 - d->dim[n].lbound; if (extent[n] <= 0) return; if (dsize == stride[n]) dsize *= extent[n]; else dsize = 0; } if (dsize != 0) { memcpy (dest, src, dsize * sizeof (GFC_REAL_8)); return; } stride0 = stride[0]; while (dest) { /* Copy the data. */ *dest = *(src++); /* Advance to the next element. */ dest += stride0; count[0]++; /* Advance to the next source element. */ n = 0; while (count[n] == extent[n]) { /* When we get to the end of a dimension, reset it and increment the next dimension. */ count[n] = 0; /* We could precalculate these products, but this is a less frequently used path so probably not worth it. */ dest -= stride[n] * extent[n]; n++; if (n == dim) { dest = NULL; break; } else { count[n]++; dest += stride[n]; } } } } #endif
430741.c
/* * at91 pinctrl driver based on at91 pinmux core * * Copyright (C) 2011-2012 Jean-Christophe PLAGNIOL-VILLARD <[email protected]> * * Under GPLv2 only */ #include <linux/clk.h> #include <linux/err.h> #include <linux/init.h> #include <linux/module.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/of_address.h> #include <linux/of_irq.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/io.h> #include <linux/gpio.h> #include <linux/pinctrl/machine.h> #include <linux/pinctrl/pinconf.h> #include <linux/pinctrl/pinctrl.h> #include <linux/pinctrl/pinmux.h> /* Since we request GPIOs from ourself */ #include <linux/pinctrl/consumer.h> #include "pinctrl-at91.h" #include "core.h" #define MAX_GPIO_BANKS 5 #define MAX_NB_GPIO_PER_BANK 32 struct at91_pinctrl_mux_ops; struct at91_gpio_chip { struct gpio_chip chip; struct pinctrl_gpio_range range; struct at91_gpio_chip *next; /* Bank sharing same clock */ int pioc_hwirq; /* PIO bank interrupt identifier on AIC */ int pioc_virq; /* PIO bank Linux virtual interrupt */ int pioc_idx; /* PIO bank index */ void __iomem *regbase; /* PIO bank virtual address */ struct clk *clock; /* associated clock */ struct at91_pinctrl_mux_ops *ops; /* ops */ }; #define to_at91_gpio_chip(c) container_of(c, struct at91_gpio_chip, chip) static struct at91_gpio_chip *gpio_chips[MAX_GPIO_BANKS]; static int gpio_banks; #define PULL_UP (1 << 0) #define MULTI_DRIVE (1 << 1) #define DEGLITCH (1 << 2) #define PULL_DOWN (1 << 3) #define DIS_SCHMIT (1 << 4) #define DRIVE_STRENGTH_SHIFT 5 #define DRIVE_STRENGTH_MASK 0x3 #define DRIVE_STRENGTH (DRIVE_STRENGTH_MASK << DRIVE_STRENGTH_SHIFT) #define DEBOUNCE (1 << 16) #define DEBOUNCE_VAL_SHIFT 17 #define DEBOUNCE_VAL (0x3fff << DEBOUNCE_VAL_SHIFT) /** * These defines will translated the dt binding settings to our internal * settings. They are not necessarily the same value as the register setting. * The actual drive strength current of low, medium and high must be looked up * from the corresponding device datasheet. This value is different for pins * that are even in the same banks. It is also dependent on VCC. * DRIVE_STRENGTH_DEFAULT is just a placeholder to avoid changing the drive * strength when there is no dt config for it. */ #define DRIVE_STRENGTH_DEFAULT (0 << DRIVE_STRENGTH_SHIFT) #define DRIVE_STRENGTH_LOW (1 << DRIVE_STRENGTH_SHIFT) #define DRIVE_STRENGTH_MED (2 << DRIVE_STRENGTH_SHIFT) #define DRIVE_STRENGTH_HI (3 << DRIVE_STRENGTH_SHIFT) /** * struct at91_pmx_func - describes AT91 pinmux functions * @name: the name of this specific function * @groups: corresponding pin groups * @ngroups: the number of groups */ struct at91_pmx_func { const char *name; const char **groups; unsigned ngroups; }; enum at91_mux { AT91_MUX_GPIO = 0, AT91_MUX_PERIPH_A = 1, AT91_MUX_PERIPH_B = 2, AT91_MUX_PERIPH_C = 3, AT91_MUX_PERIPH_D = 4, }; /** * struct at91_pmx_pin - describes an At91 pin mux * @bank: the bank of the pin * @pin: the pin number in the @bank * @mux: the mux mode : gpio or periph_x of the pin i.e. alternate function. * @conf: the configuration of the pin: PULL_UP, MULTIDRIVE etc... */ struct at91_pmx_pin { uint32_t bank; uint32_t pin; enum at91_mux mux; unsigned long conf; }; /** * struct at91_pin_group - describes an At91 pin group * @name: the name of this specific pin group * @pins_conf: the mux mode for each pin in this group. The size of this * array is the same as pins. * @pins: an array of discrete physical pins used in this group, taken * from the driver-local pin enumeration space * @npins: the number of pins in this group array, i.e. the number of * elements in .pins so we can iterate over that array */ struct at91_pin_group { const char *name; struct at91_pmx_pin *pins_conf; unsigned int *pins; unsigned npins; }; /** * struct at91_pinctrl_mux_ops - describes an AT91 mux ops group * on new IP with support for periph C and D the way to mux in * periph A and B has changed * So provide the right call back * if not present means the IP does not support it * @get_periph: return the periph mode configured * @mux_A_periph: mux as periph A * @mux_B_periph: mux as periph B * @mux_C_periph: mux as periph C * @mux_D_periph: mux as periph D * @get_deglitch: get deglitch status * @set_deglitch: enable/disable deglitch * @get_debounce: get debounce status * @set_debounce: enable/disable debounce * @get_pulldown: get pulldown status * @set_pulldown: enable/disable pulldown * @get_schmitt_trig: get schmitt trigger status * @disable_schmitt_trig: disable schmitt trigger * @irq_type: return irq type */ struct at91_pinctrl_mux_ops { enum at91_mux (*get_periph)(void __iomem *pio, unsigned mask); void (*mux_A_periph)(void __iomem *pio, unsigned mask); void (*mux_B_periph)(void __iomem *pio, unsigned mask); void (*mux_C_periph)(void __iomem *pio, unsigned mask); void (*mux_D_periph)(void __iomem *pio, unsigned mask); bool (*get_deglitch)(void __iomem *pio, unsigned pin); void (*set_deglitch)(void __iomem *pio, unsigned mask, bool is_on); bool (*get_debounce)(void __iomem *pio, unsigned pin, u32 *div); void (*set_debounce)(void __iomem *pio, unsigned mask, bool is_on, u32 div); bool (*get_pulldown)(void __iomem *pio, unsigned pin); void (*set_pulldown)(void __iomem *pio, unsigned mask, bool is_on); bool (*get_schmitt_trig)(void __iomem *pio, unsigned pin); void (*disable_schmitt_trig)(void __iomem *pio, unsigned mask); unsigned (*get_drivestrength)(void __iomem *pio, unsigned pin); void (*set_drivestrength)(void __iomem *pio, unsigned pin, u32 strength); /* irq */ int (*irq_type)(struct irq_data *d, unsigned type); }; static int gpio_irq_type(struct irq_data *d, unsigned type); static int alt_gpio_irq_type(struct irq_data *d, unsigned type); struct at91_pinctrl { struct device *dev; struct pinctrl_dev *pctl; int nbanks; uint32_t *mux_mask; int nmux; struct at91_pmx_func *functions; int nfunctions; struct at91_pin_group *groups; int ngroups; struct at91_pinctrl_mux_ops *ops; }; static const inline struct at91_pin_group *at91_pinctrl_find_group_by_name( const struct at91_pinctrl *info, const char *name) { const struct at91_pin_group *grp = NULL; int i; for (i = 0; i < info->ngroups; i++) { if (strcmp(info->groups[i].name, name)) continue; grp = &info->groups[i]; dev_dbg(info->dev, "%s: %d 0:%d\n", name, grp->npins, grp->pins[0]); break; } return grp; } static int at91_get_groups_count(struct pinctrl_dev *pctldev) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); return info->ngroups; } static const char *at91_get_group_name(struct pinctrl_dev *pctldev, unsigned selector) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); return info->groups[selector].name; } static int at91_get_group_pins(struct pinctrl_dev *pctldev, unsigned selector, const unsigned **pins, unsigned *npins) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); if (selector >= info->ngroups) return -EINVAL; *pins = info->groups[selector].pins; *npins = info->groups[selector].npins; return 0; } static void at91_pin_dbg_show(struct pinctrl_dev *pctldev, struct seq_file *s, unsigned offset) { seq_printf(s, "%s", dev_name(pctldev->dev)); } static int at91_dt_node_to_map(struct pinctrl_dev *pctldev, struct device_node *np, struct pinctrl_map **map, unsigned *num_maps) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); const struct at91_pin_group *grp; struct pinctrl_map *new_map; struct device_node *parent; int map_num = 1; int i; /* * first find the group of this node and check if we need to create * config maps for pins */ grp = at91_pinctrl_find_group_by_name(info, np->name); if (!grp) { dev_err(info->dev, "unable to find group for node %s\n", np->name); return -EINVAL; } map_num += grp->npins; new_map = devm_kzalloc(pctldev->dev, sizeof(*new_map) * map_num, GFP_KERNEL); if (!new_map) return -ENOMEM; *map = new_map; *num_maps = map_num; /* create mux map */ parent = of_get_parent(np); if (!parent) { devm_kfree(pctldev->dev, new_map); return -EINVAL; } new_map[0].type = PIN_MAP_TYPE_MUX_GROUP; new_map[0].data.mux.function = parent->name; new_map[0].data.mux.group = np->name; of_node_put(parent); /* create config map */ new_map++; for (i = 0; i < grp->npins; i++) { new_map[i].type = PIN_MAP_TYPE_CONFIGS_PIN; new_map[i].data.configs.group_or_pin = pin_get_name(pctldev, grp->pins[i]); new_map[i].data.configs.configs = &grp->pins_conf[i].conf; new_map[i].data.configs.num_configs = 1; } dev_dbg(pctldev->dev, "maps: function %s group %s num %d\n", (*map)->data.mux.function, (*map)->data.mux.group, map_num); return 0; } static void at91_dt_free_map(struct pinctrl_dev *pctldev, struct pinctrl_map *map, unsigned num_maps) { } static const struct pinctrl_ops at91_pctrl_ops = { .get_groups_count = at91_get_groups_count, .get_group_name = at91_get_group_name, .get_group_pins = at91_get_group_pins, .pin_dbg_show = at91_pin_dbg_show, .dt_node_to_map = at91_dt_node_to_map, .dt_free_map = at91_dt_free_map, }; static void __iomem *pin_to_controller(struct at91_pinctrl *info, unsigned int bank) { return gpio_chips[bank]->regbase; } static inline int pin_to_bank(unsigned pin) { return pin /= MAX_NB_GPIO_PER_BANK; } static unsigned pin_to_mask(unsigned int pin) { return 1 << pin; } static unsigned two_bit_pin_value_shift_amount(unsigned int pin) { /* return the shift value for a pin for "two bit" per pin registers, * i.e. drive strength */ return 2*((pin >= MAX_NB_GPIO_PER_BANK/2) ? pin - MAX_NB_GPIO_PER_BANK/2 : pin); } static unsigned sama5d3_get_drive_register(unsigned int pin) { /* drive strength is split between two registers * with two bits per pin */ return (pin >= MAX_NB_GPIO_PER_BANK/2) ? SAMA5D3_PIO_DRIVER2 : SAMA5D3_PIO_DRIVER1; } static unsigned at91sam9x5_get_drive_register(unsigned int pin) { /* drive strength is split between two registers * with two bits per pin */ return (pin >= MAX_NB_GPIO_PER_BANK/2) ? AT91SAM9X5_PIO_DRIVER2 : AT91SAM9X5_PIO_DRIVER1; } static void at91_mux_disable_interrupt(void __iomem *pio, unsigned mask) { writel_relaxed(mask, pio + PIO_IDR); } static unsigned at91_mux_get_pullup(void __iomem *pio, unsigned pin) { return !((readl_relaxed(pio + PIO_PUSR) >> pin) & 0x1); } static void at91_mux_set_pullup(void __iomem *pio, unsigned mask, bool on) { if (on) writel_relaxed(mask, pio + PIO_PPDDR); writel_relaxed(mask, pio + (on ? PIO_PUER : PIO_PUDR)); } static unsigned at91_mux_get_multidrive(void __iomem *pio, unsigned pin) { return (readl_relaxed(pio + PIO_MDSR) >> pin) & 0x1; } static void at91_mux_set_multidrive(void __iomem *pio, unsigned mask, bool on) { writel_relaxed(mask, pio + (on ? PIO_MDER : PIO_MDDR)); } static void at91_mux_set_A_periph(void __iomem *pio, unsigned mask) { writel_relaxed(mask, pio + PIO_ASR); } static void at91_mux_set_B_periph(void __iomem *pio, unsigned mask) { writel_relaxed(mask, pio + PIO_BSR); } static void at91_mux_pio3_set_A_periph(void __iomem *pio, unsigned mask) { writel_relaxed(readl_relaxed(pio + PIO_ABCDSR1) & ~mask, pio + PIO_ABCDSR1); writel_relaxed(readl_relaxed(pio + PIO_ABCDSR2) & ~mask, pio + PIO_ABCDSR2); } static void at91_mux_pio3_set_B_periph(void __iomem *pio, unsigned mask) { writel_relaxed(readl_relaxed(pio + PIO_ABCDSR1) | mask, pio + PIO_ABCDSR1); writel_relaxed(readl_relaxed(pio + PIO_ABCDSR2) & ~mask, pio + PIO_ABCDSR2); } static void at91_mux_pio3_set_C_periph(void __iomem *pio, unsigned mask) { writel_relaxed(readl_relaxed(pio + PIO_ABCDSR1) & ~mask, pio + PIO_ABCDSR1); writel_relaxed(readl_relaxed(pio + PIO_ABCDSR2) | mask, pio + PIO_ABCDSR2); } static void at91_mux_pio3_set_D_periph(void __iomem *pio, unsigned mask) { writel_relaxed(readl_relaxed(pio + PIO_ABCDSR1) | mask, pio + PIO_ABCDSR1); writel_relaxed(readl_relaxed(pio + PIO_ABCDSR2) | mask, pio + PIO_ABCDSR2); } static enum at91_mux at91_mux_pio3_get_periph(void __iomem *pio, unsigned mask) { unsigned select; if (readl_relaxed(pio + PIO_PSR) & mask) return AT91_MUX_GPIO; select = !!(readl_relaxed(pio + PIO_ABCDSR1) & mask); select |= (!!(readl_relaxed(pio + PIO_ABCDSR2) & mask) << 1); return select + 1; } static enum at91_mux at91_mux_get_periph(void __iomem *pio, unsigned mask) { unsigned select; if (readl_relaxed(pio + PIO_PSR) & mask) return AT91_MUX_GPIO; select = readl_relaxed(pio + PIO_ABSR) & mask; return select + 1; } static bool at91_mux_get_deglitch(void __iomem *pio, unsigned pin) { return (__raw_readl(pio + PIO_IFSR) >> pin) & 0x1; } static void at91_mux_set_deglitch(void __iomem *pio, unsigned mask, bool is_on) { __raw_writel(mask, pio + (is_on ? PIO_IFER : PIO_IFDR)); } static bool at91_mux_pio3_get_deglitch(void __iomem *pio, unsigned pin) { if ((__raw_readl(pio + PIO_IFSR) >> pin) & 0x1) return !((__raw_readl(pio + PIO_IFSCSR) >> pin) & 0x1); return false; } static void at91_mux_pio3_set_deglitch(void __iomem *pio, unsigned mask, bool is_on) { if (is_on) __raw_writel(mask, pio + PIO_IFSCDR); at91_mux_set_deglitch(pio, mask, is_on); } static bool at91_mux_pio3_get_debounce(void __iomem *pio, unsigned pin, u32 *div) { *div = __raw_readl(pio + PIO_SCDR); return ((__raw_readl(pio + PIO_IFSR) >> pin) & 0x1) && ((__raw_readl(pio + PIO_IFSCSR) >> pin) & 0x1); } static void at91_mux_pio3_set_debounce(void __iomem *pio, unsigned mask, bool is_on, u32 div) { if (is_on) { __raw_writel(mask, pio + PIO_IFSCER); __raw_writel(div & PIO_SCDR_DIV, pio + PIO_SCDR); __raw_writel(mask, pio + PIO_IFER); } else __raw_writel(mask, pio + PIO_IFSCDR); } static bool at91_mux_pio3_get_pulldown(void __iomem *pio, unsigned pin) { return !((__raw_readl(pio + PIO_PPDSR) >> pin) & 0x1); } static void at91_mux_pio3_set_pulldown(void __iomem *pio, unsigned mask, bool is_on) { if (is_on) __raw_writel(mask, pio + PIO_PUDR); __raw_writel(mask, pio + (is_on ? PIO_PPDER : PIO_PPDDR)); } static void at91_mux_pio3_disable_schmitt_trig(void __iomem *pio, unsigned mask) { __raw_writel(__raw_readl(pio + PIO_SCHMITT) | mask, pio + PIO_SCHMITT); } static bool at91_mux_pio3_get_schmitt_trig(void __iomem *pio, unsigned pin) { return (__raw_readl(pio + PIO_SCHMITT) >> pin) & 0x1; } static inline u32 read_drive_strength(void __iomem *reg, unsigned pin) { unsigned tmp = __raw_readl(reg); tmp = tmp >> two_bit_pin_value_shift_amount(pin); return tmp & DRIVE_STRENGTH_MASK; } static unsigned at91_mux_sama5d3_get_drivestrength(void __iomem *pio, unsigned pin) { unsigned tmp = read_drive_strength(pio + sama5d3_get_drive_register(pin), pin); /* SAMA5 strength is 1:1 with our defines, * except 0 is equivalent to low per datasheet */ if (!tmp) tmp = DRIVE_STRENGTH_LOW; return tmp; } static unsigned at91_mux_sam9x5_get_drivestrength(void __iomem *pio, unsigned pin) { unsigned tmp = read_drive_strength(pio + at91sam9x5_get_drive_register(pin), pin); /* strength is inverse in SAM9x5s hardware with the pinctrl defines * hardware: 0 = hi, 1 = med, 2 = low, 3 = rsvd */ tmp = DRIVE_STRENGTH_HI - tmp; return tmp; } static void set_drive_strength(void __iomem *reg, unsigned pin, u32 strength) { unsigned tmp = __raw_readl(reg); unsigned shift = two_bit_pin_value_shift_amount(pin); tmp &= ~(DRIVE_STRENGTH_MASK << shift); tmp |= strength << shift; __raw_writel(tmp, reg); } static void at91_mux_sama5d3_set_drivestrength(void __iomem *pio, unsigned pin, u32 setting) { /* do nothing if setting is zero */ if (!setting) return; /* strength is 1 to 1 with setting for SAMA5 */ set_drive_strength(pio + sama5d3_get_drive_register(pin), pin, setting); } static void at91_mux_sam9x5_set_drivestrength(void __iomem *pio, unsigned pin, u32 setting) { /* do nothing if setting is zero */ if (!setting) return; /* strength is inverse on SAM9x5s with our defines * 0 = hi, 1 = med, 2 = low, 3 = rsvd */ setting = DRIVE_STRENGTH_HI - setting; set_drive_strength(pio + at91sam9x5_get_drive_register(pin), pin, setting); } static struct at91_pinctrl_mux_ops at91rm9200_ops = { .get_periph = at91_mux_get_periph, .mux_A_periph = at91_mux_set_A_periph, .mux_B_periph = at91_mux_set_B_periph, .get_deglitch = at91_mux_get_deglitch, .set_deglitch = at91_mux_set_deglitch, .irq_type = gpio_irq_type, }; static struct at91_pinctrl_mux_ops at91sam9x5_ops = { .get_periph = at91_mux_pio3_get_periph, .mux_A_periph = at91_mux_pio3_set_A_periph, .mux_B_periph = at91_mux_pio3_set_B_periph, .mux_C_periph = at91_mux_pio3_set_C_periph, .mux_D_periph = at91_mux_pio3_set_D_periph, .get_deglitch = at91_mux_pio3_get_deglitch, .set_deglitch = at91_mux_pio3_set_deglitch, .get_debounce = at91_mux_pio3_get_debounce, .set_debounce = at91_mux_pio3_set_debounce, .get_pulldown = at91_mux_pio3_get_pulldown, .set_pulldown = at91_mux_pio3_set_pulldown, .get_schmitt_trig = at91_mux_pio3_get_schmitt_trig, .disable_schmitt_trig = at91_mux_pio3_disable_schmitt_trig, .get_drivestrength = at91_mux_sam9x5_get_drivestrength, .set_drivestrength = at91_mux_sam9x5_set_drivestrength, .irq_type = alt_gpio_irq_type, }; static struct at91_pinctrl_mux_ops sama5d3_ops = { .get_periph = at91_mux_pio3_get_periph, .mux_A_periph = at91_mux_pio3_set_A_periph, .mux_B_periph = at91_mux_pio3_set_B_periph, .mux_C_periph = at91_mux_pio3_set_C_periph, .mux_D_periph = at91_mux_pio3_set_D_periph, .get_deglitch = at91_mux_pio3_get_deglitch, .set_deglitch = at91_mux_pio3_set_deglitch, .get_debounce = at91_mux_pio3_get_debounce, .set_debounce = at91_mux_pio3_set_debounce, .get_pulldown = at91_mux_pio3_get_pulldown, .set_pulldown = at91_mux_pio3_set_pulldown, .get_schmitt_trig = at91_mux_pio3_get_schmitt_trig, .disable_schmitt_trig = at91_mux_pio3_disable_schmitt_trig, .get_drivestrength = at91_mux_sama5d3_get_drivestrength, .set_drivestrength = at91_mux_sama5d3_set_drivestrength, .irq_type = alt_gpio_irq_type, }; static void at91_pin_dbg(const struct device *dev, const struct at91_pmx_pin *pin) { if (pin->mux) { dev_dbg(dev, "pio%c%d configured as periph%c with conf = 0x%lx\n", pin->bank + 'A', pin->pin, pin->mux - 1 + 'A', pin->conf); } else { dev_dbg(dev, "pio%c%d configured as gpio with conf = 0x%lx\n", pin->bank + 'A', pin->pin, pin->conf); } } static int pin_check_config(struct at91_pinctrl *info, const char *name, int index, const struct at91_pmx_pin *pin) { int mux; /* check if it's a valid config */ if (pin->bank >= info->nbanks) { dev_err(info->dev, "%s: pin conf %d bank_id %d >= nbanks %d\n", name, index, pin->bank, info->nbanks); return -EINVAL; } if (pin->pin >= MAX_NB_GPIO_PER_BANK) { dev_err(info->dev, "%s: pin conf %d pin_bank_id %d >= %d\n", name, index, pin->pin, MAX_NB_GPIO_PER_BANK); return -EINVAL; } if (!pin->mux) return 0; mux = pin->mux - 1; if (mux >= info->nmux) { dev_err(info->dev, "%s: pin conf %d mux_id %d >= nmux %d\n", name, index, mux, info->nmux); return -EINVAL; } if (!(info->mux_mask[pin->bank * info->nmux + mux] & 1 << pin->pin)) { dev_err(info->dev, "%s: pin conf %d mux_id %d not supported for pio%c%d\n", name, index, mux, pin->bank + 'A', pin->pin); return -EINVAL; } return 0; } static void at91_mux_gpio_disable(void __iomem *pio, unsigned mask) { writel_relaxed(mask, pio + PIO_PDR); } static void at91_mux_gpio_enable(void __iomem *pio, unsigned mask, bool input) { writel_relaxed(mask, pio + PIO_PER); writel_relaxed(mask, pio + (input ? PIO_ODR : PIO_OER)); } static int at91_pmx_set(struct pinctrl_dev *pctldev, unsigned selector, unsigned group) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); const struct at91_pmx_pin *pins_conf = info->groups[group].pins_conf; const struct at91_pmx_pin *pin; uint32_t npins = info->groups[group].npins; int i, ret; unsigned mask; void __iomem *pio; dev_dbg(info->dev, "enable function %s group %s\n", info->functions[selector].name, info->groups[group].name); /* first check that all the pins of the group are valid with a valid * parameter */ for (i = 0; i < npins; i++) { pin = &pins_conf[i]; ret = pin_check_config(info, info->groups[group].name, i, pin); if (ret) return ret; } for (i = 0; i < npins; i++) { pin = &pins_conf[i]; at91_pin_dbg(info->dev, pin); pio = pin_to_controller(info, pin->bank); mask = pin_to_mask(pin->pin); at91_mux_disable_interrupt(pio, mask); switch (pin->mux) { case AT91_MUX_GPIO: at91_mux_gpio_enable(pio, mask, 1); break; case AT91_MUX_PERIPH_A: info->ops->mux_A_periph(pio, mask); break; case AT91_MUX_PERIPH_B: info->ops->mux_B_periph(pio, mask); break; case AT91_MUX_PERIPH_C: if (!info->ops->mux_C_periph) return -EINVAL; info->ops->mux_C_periph(pio, mask); break; case AT91_MUX_PERIPH_D: if (!info->ops->mux_D_periph) return -EINVAL; info->ops->mux_D_periph(pio, mask); break; } if (pin->mux) at91_mux_gpio_disable(pio, mask); } return 0; } static int at91_pmx_get_funcs_count(struct pinctrl_dev *pctldev) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); return info->nfunctions; } static const char *at91_pmx_get_func_name(struct pinctrl_dev *pctldev, unsigned selector) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); return info->functions[selector].name; } static int at91_pmx_get_groups(struct pinctrl_dev *pctldev, unsigned selector, const char * const **groups, unsigned * const num_groups) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); *groups = info->functions[selector].groups; *num_groups = info->functions[selector].ngroups; return 0; } static int at91_gpio_request_enable(struct pinctrl_dev *pctldev, struct pinctrl_gpio_range *range, unsigned offset) { struct at91_pinctrl *npct = pinctrl_dev_get_drvdata(pctldev); struct at91_gpio_chip *at91_chip; struct gpio_chip *chip; unsigned mask; if (!range) { dev_err(npct->dev, "invalid range\n"); return -EINVAL; } if (!range->gc) { dev_err(npct->dev, "missing GPIO chip in range\n"); return -EINVAL; } chip = range->gc; at91_chip = container_of(chip, struct at91_gpio_chip, chip); dev_dbg(npct->dev, "enable pin %u as GPIO\n", offset); mask = 1 << (offset - chip->base); dev_dbg(npct->dev, "enable pin %u as PIO%c%d 0x%x\n", offset, 'A' + range->id, offset - chip->base, mask); writel_relaxed(mask, at91_chip->regbase + PIO_PER); return 0; } static void at91_gpio_disable_free(struct pinctrl_dev *pctldev, struct pinctrl_gpio_range *range, unsigned offset) { struct at91_pinctrl *npct = pinctrl_dev_get_drvdata(pctldev); dev_dbg(npct->dev, "disable pin %u as GPIO\n", offset); /* Set the pin to some default state, GPIO is usually default */ } static const struct pinmux_ops at91_pmx_ops = { .get_functions_count = at91_pmx_get_funcs_count, .get_function_name = at91_pmx_get_func_name, .get_function_groups = at91_pmx_get_groups, .set_mux = at91_pmx_set, .gpio_request_enable = at91_gpio_request_enable, .gpio_disable_free = at91_gpio_disable_free, }; static int at91_pinconf_get(struct pinctrl_dev *pctldev, unsigned pin_id, unsigned long *config) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); void __iomem *pio; unsigned pin; int div; *config = 0; dev_dbg(info->dev, "%s:%d, pin_id=%d", __func__, __LINE__, pin_id); pio = pin_to_controller(info, pin_to_bank(pin_id)); pin = pin_id % MAX_NB_GPIO_PER_BANK; if (at91_mux_get_multidrive(pio, pin)) *config |= MULTI_DRIVE; if (at91_mux_get_pullup(pio, pin)) *config |= PULL_UP; if (info->ops->get_deglitch && info->ops->get_deglitch(pio, pin)) *config |= DEGLITCH; if (info->ops->get_debounce && info->ops->get_debounce(pio, pin, &div)) *config |= DEBOUNCE | (div << DEBOUNCE_VAL_SHIFT); if (info->ops->get_pulldown && info->ops->get_pulldown(pio, pin)) *config |= PULL_DOWN; if (info->ops->get_schmitt_trig && info->ops->get_schmitt_trig(pio, pin)) *config |= DIS_SCHMIT; if (info->ops->get_drivestrength) *config |= (info->ops->get_drivestrength(pio, pin) << DRIVE_STRENGTH_SHIFT); return 0; } static int at91_pinconf_set(struct pinctrl_dev *pctldev, unsigned pin_id, unsigned long *configs, unsigned num_configs) { struct at91_pinctrl *info = pinctrl_dev_get_drvdata(pctldev); unsigned mask; void __iomem *pio; int i; unsigned long config; unsigned pin; for (i = 0; i < num_configs; i++) { config = configs[i]; dev_dbg(info->dev, "%s:%d, pin_id=%d, config=0x%lx", __func__, __LINE__, pin_id, config); pio = pin_to_controller(info, pin_to_bank(pin_id)); pin = pin_id % MAX_NB_GPIO_PER_BANK; mask = pin_to_mask(pin); if (config & PULL_UP && config & PULL_DOWN) return -EINVAL; at91_mux_set_pullup(pio, mask, config & PULL_UP); at91_mux_set_multidrive(pio, mask, config & MULTI_DRIVE); if (info->ops->set_deglitch) info->ops->set_deglitch(pio, mask, config & DEGLITCH); if (info->ops->set_debounce) info->ops->set_debounce(pio, mask, config & DEBOUNCE, (config & DEBOUNCE_VAL) >> DEBOUNCE_VAL_SHIFT); if (info->ops->set_pulldown) info->ops->set_pulldown(pio, mask, config & PULL_DOWN); if (info->ops->disable_schmitt_trig && config & DIS_SCHMIT) info->ops->disable_schmitt_trig(pio, mask); if (info->ops->set_drivestrength) info->ops->set_drivestrength(pio, pin, (config & DRIVE_STRENGTH) >> DRIVE_STRENGTH_SHIFT); } /* for each config */ return 0; } #define DBG_SHOW_FLAG(flag) do { \ if (config & flag) { \ if (num_conf) \ seq_puts(s, "|"); \ seq_puts(s, #flag); \ num_conf++; \ } \ } while (0) #define DBG_SHOW_FLAG_MASKED(mask,flag) do { \ if ((config & mask) == flag) { \ if (num_conf) \ seq_puts(s, "|"); \ seq_puts(s, #flag); \ num_conf++; \ } \ } while (0) static void at91_pinconf_dbg_show(struct pinctrl_dev *pctldev, struct seq_file *s, unsigned pin_id) { unsigned long config; int val, num_conf = 0; at91_pinconf_get(pctldev, pin_id, &config); DBG_SHOW_FLAG(MULTI_DRIVE); DBG_SHOW_FLAG(PULL_UP); DBG_SHOW_FLAG(PULL_DOWN); DBG_SHOW_FLAG(DIS_SCHMIT); DBG_SHOW_FLAG(DEGLITCH); DBG_SHOW_FLAG_MASKED(DRIVE_STRENGTH, DRIVE_STRENGTH_LOW); DBG_SHOW_FLAG_MASKED(DRIVE_STRENGTH, DRIVE_STRENGTH_MED); DBG_SHOW_FLAG_MASKED(DRIVE_STRENGTH, DRIVE_STRENGTH_HI); DBG_SHOW_FLAG(DEBOUNCE); if (config & DEBOUNCE) { val = config >> DEBOUNCE_VAL_SHIFT; seq_printf(s, "(%d)", val); } return; } static void at91_pinconf_group_dbg_show(struct pinctrl_dev *pctldev, struct seq_file *s, unsigned group) { } static const struct pinconf_ops at91_pinconf_ops = { .pin_config_get = at91_pinconf_get, .pin_config_set = at91_pinconf_set, .pin_config_dbg_show = at91_pinconf_dbg_show, .pin_config_group_dbg_show = at91_pinconf_group_dbg_show, }; static struct pinctrl_desc at91_pinctrl_desc = { .pctlops = &at91_pctrl_ops, .pmxops = &at91_pmx_ops, .confops = &at91_pinconf_ops, .owner = THIS_MODULE, }; static const char *gpio_compat = "atmel,at91rm9200-gpio"; static void at91_pinctrl_child_count(struct at91_pinctrl *info, struct device_node *np) { struct device_node *child; for_each_child_of_node(np, child) { if (of_device_is_compatible(child, gpio_compat)) { info->nbanks++; } else { info->nfunctions++; info->ngroups += of_get_child_count(child); } } } static int at91_pinctrl_mux_mask(struct at91_pinctrl *info, struct device_node *np) { int ret = 0; int size; const __be32 *list; list = of_get_property(np, "atmel,mux-mask", &size); if (!list) { dev_err(info->dev, "can not read the mux-mask of %d\n", size); return -EINVAL; } size /= sizeof(*list); if (!size || size % info->nbanks) { dev_err(info->dev, "wrong mux mask array should be by %d\n", info->nbanks); return -EINVAL; } info->nmux = size / info->nbanks; info->mux_mask = devm_kzalloc(info->dev, sizeof(u32) * size, GFP_KERNEL); if (!info->mux_mask) { dev_err(info->dev, "could not alloc mux_mask\n"); return -ENOMEM; } ret = of_property_read_u32_array(np, "atmel,mux-mask", info->mux_mask, size); if (ret) dev_err(info->dev, "can not read the mux-mask of %d\n", size); return ret; } static int at91_pinctrl_parse_groups(struct device_node *np, struct at91_pin_group *grp, struct at91_pinctrl *info, u32 index) { struct at91_pmx_pin *pin; int size; const __be32 *list; int i, j; dev_dbg(info->dev, "group(%d): %s\n", index, np->name); /* Initialise group */ grp->name = np->name; /* * the binding format is atmel,pins = <bank pin mux CONFIG ...>, * do sanity check and calculate pins number */ list = of_get_property(np, "atmel,pins", &size); /* we do not check return since it's safe node passed down */ size /= sizeof(*list); if (!size || size % 4) { dev_err(info->dev, "wrong pins number or pins and configs should be by 4\n"); return -EINVAL; } grp->npins = size / 4; pin = grp->pins_conf = devm_kzalloc(info->dev, grp->npins * sizeof(struct at91_pmx_pin), GFP_KERNEL); grp->pins = devm_kzalloc(info->dev, grp->npins * sizeof(unsigned int), GFP_KERNEL); if (!grp->pins_conf || !grp->pins) return -ENOMEM; for (i = 0, j = 0; i < size; i += 4, j++) { pin->bank = be32_to_cpu(*list++); pin->pin = be32_to_cpu(*list++); grp->pins[j] = pin->bank * MAX_NB_GPIO_PER_BANK + pin->pin; pin->mux = be32_to_cpu(*list++); pin->conf = be32_to_cpu(*list++); at91_pin_dbg(info->dev, pin); pin++; } return 0; } static int at91_pinctrl_parse_functions(struct device_node *np, struct at91_pinctrl *info, u32 index) { struct device_node *child; struct at91_pmx_func *func; struct at91_pin_group *grp; int ret; static u32 grp_index; u32 i = 0; dev_dbg(info->dev, "parse function(%d): %s\n", index, np->name); func = &info->functions[index]; /* Initialise function */ func->name = np->name; func->ngroups = of_get_child_count(np); if (func->ngroups == 0) { dev_err(info->dev, "no groups defined\n"); return -EINVAL; } func->groups = devm_kzalloc(info->dev, func->ngroups * sizeof(char *), GFP_KERNEL); if (!func->groups) return -ENOMEM; for_each_child_of_node(np, child) { func->groups[i] = child->name; grp = &info->groups[grp_index++]; ret = at91_pinctrl_parse_groups(child, grp, info, i++); if (ret) return ret; } return 0; } static struct of_device_id at91_pinctrl_of_match[] = { { .compatible = "atmel,sama5d3-pinctrl", .data = &sama5d3_ops }, { .compatible = "atmel,at91sam9x5-pinctrl", .data = &at91sam9x5_ops }, { .compatible = "atmel,at91rm9200-pinctrl", .data = &at91rm9200_ops }, { /* sentinel */ } }; static int at91_pinctrl_probe_dt(struct platform_device *pdev, struct at91_pinctrl *info) { int ret = 0; int i, j; uint32_t *tmp; struct device_node *np = pdev->dev.of_node; struct device_node *child; if (!np) return -ENODEV; info->dev = &pdev->dev; info->ops = (struct at91_pinctrl_mux_ops *) of_match_device(at91_pinctrl_of_match, &pdev->dev)->data; at91_pinctrl_child_count(info, np); if (info->nbanks < 1) { dev_err(&pdev->dev, "you need to specify at least one gpio-controller\n"); return -EINVAL; } ret = at91_pinctrl_mux_mask(info, np); if (ret) return ret; dev_dbg(&pdev->dev, "nmux = %d\n", info->nmux); dev_dbg(&pdev->dev, "mux-mask\n"); tmp = info->mux_mask; for (i = 0; i < info->nbanks; i++) { for (j = 0; j < info->nmux; j++, tmp++) { dev_dbg(&pdev->dev, "%d:%d\t0x%x\n", i, j, tmp[0]); } } dev_dbg(&pdev->dev, "nfunctions = %d\n", info->nfunctions); dev_dbg(&pdev->dev, "ngroups = %d\n", info->ngroups); info->functions = devm_kzalloc(&pdev->dev, info->nfunctions * sizeof(struct at91_pmx_func), GFP_KERNEL); if (!info->functions) return -ENOMEM; info->groups = devm_kzalloc(&pdev->dev, info->ngroups * sizeof(struct at91_pin_group), GFP_KERNEL); if (!info->groups) return -ENOMEM; dev_dbg(&pdev->dev, "nbanks = %d\n", info->nbanks); dev_dbg(&pdev->dev, "nfunctions = %d\n", info->nfunctions); dev_dbg(&pdev->dev, "ngroups = %d\n", info->ngroups); i = 0; for_each_child_of_node(np, child) { if (of_device_is_compatible(child, gpio_compat)) continue; ret = at91_pinctrl_parse_functions(child, info, i++); if (ret) { dev_err(&pdev->dev, "failed to parse function\n"); return ret; } } return 0; } static int at91_pinctrl_probe(struct platform_device *pdev) { struct at91_pinctrl *info; struct pinctrl_pin_desc *pdesc; int ret, i, j, k; info = devm_kzalloc(&pdev->dev, sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; ret = at91_pinctrl_probe_dt(pdev, info); if (ret) return ret; /* * We need all the GPIO drivers to probe FIRST, or we will not be able * to obtain references to the struct gpio_chip * for them, and we * need this to proceed. */ for (i = 0; i < info->nbanks; i++) { if (!gpio_chips[i]) { dev_warn(&pdev->dev, "GPIO chip %d not registered yet\n", i); devm_kfree(&pdev->dev, info); return -EPROBE_DEFER; } } at91_pinctrl_desc.name = dev_name(&pdev->dev); at91_pinctrl_desc.npins = info->nbanks * MAX_NB_GPIO_PER_BANK; at91_pinctrl_desc.pins = pdesc = devm_kzalloc(&pdev->dev, sizeof(*pdesc) * at91_pinctrl_desc.npins, GFP_KERNEL); if (!at91_pinctrl_desc.pins) return -ENOMEM; for (i = 0 , k = 0; i < info->nbanks; i++) { for (j = 0; j < MAX_NB_GPIO_PER_BANK; j++, k++) { pdesc->number = k; pdesc->name = kasprintf(GFP_KERNEL, "pio%c%d", i + 'A', j); pdesc++; } } platform_set_drvdata(pdev, info); info->pctl = pinctrl_register(&at91_pinctrl_desc, &pdev->dev, info); if (!info->pctl) { dev_err(&pdev->dev, "could not register AT91 pinctrl driver\n"); ret = -EINVAL; goto err; } /* We will handle a range of GPIO pins */ for (i = 0; i < info->nbanks; i++) pinctrl_add_gpio_range(info->pctl, &gpio_chips[i]->range); dev_info(&pdev->dev, "initialized AT91 pinctrl driver\n"); return 0; err: return ret; } static int at91_pinctrl_remove(struct platform_device *pdev) { struct at91_pinctrl *info = platform_get_drvdata(pdev); pinctrl_unregister(info->pctl); return 0; } static int at91_gpio_request(struct gpio_chip *chip, unsigned offset) { /* * Map back to global GPIO space and request muxing, the direction * parameter does not matter for this controller. */ int gpio = chip->base + offset; int bank = chip->base / chip->ngpio; dev_dbg(chip->dev, "%s:%d pio%c%d(%d)\n", __func__, __LINE__, 'A' + bank, offset, gpio); return pinctrl_request_gpio(gpio); } static void at91_gpio_free(struct gpio_chip *chip, unsigned offset) { int gpio = chip->base + offset; pinctrl_free_gpio(gpio); } static int at91_gpio_get_direction(struct gpio_chip *chip, unsigned offset) { struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << offset; u32 osr; osr = readl_relaxed(pio + PIO_OSR); return !(osr & mask); } static int at91_gpio_direction_input(struct gpio_chip *chip, unsigned offset) { struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << offset; writel_relaxed(mask, pio + PIO_ODR); return 0; } static int at91_gpio_get(struct gpio_chip *chip, unsigned offset) { struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << offset; u32 pdsr; pdsr = readl_relaxed(pio + PIO_PDSR); return (pdsr & mask) != 0; } static void at91_gpio_set(struct gpio_chip *chip, unsigned offset, int val) { struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << offset; writel_relaxed(mask, pio + (val ? PIO_SODR : PIO_CODR)); } static int at91_gpio_direction_output(struct gpio_chip *chip, unsigned offset, int val) { struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << offset; writel_relaxed(mask, pio + (val ? PIO_SODR : PIO_CODR)); writel_relaxed(mask, pio + PIO_OER); return 0; } #ifdef CONFIG_DEBUG_FS static void at91_gpio_dbg_show(struct seq_file *s, struct gpio_chip *chip) { enum at91_mux mode; int i; struct at91_gpio_chip *at91_gpio = to_at91_gpio_chip(chip); void __iomem *pio = at91_gpio->regbase; for (i = 0; i < chip->ngpio; i++) { unsigned mask = pin_to_mask(i); const char *gpio_label; gpio_label = gpiochip_is_requested(chip, i); if (!gpio_label) continue; mode = at91_gpio->ops->get_periph(pio, mask); seq_printf(s, "[%s] GPIO%s%d: ", gpio_label, chip->label, i); if (mode == AT91_MUX_GPIO) { seq_printf(s, "[gpio] "); seq_printf(s, "%s ", readl_relaxed(pio + PIO_OSR) & mask ? "output" : "input"); seq_printf(s, "%s\n", readl_relaxed(pio + PIO_PDSR) & mask ? "set" : "clear"); } else { seq_printf(s, "[periph %c]\n", mode + 'A' - 1); } } } #else #define at91_gpio_dbg_show NULL #endif /* Several AIC controller irqs are dispatched through this GPIO handler. * To use any AT91_PIN_* as an externally triggered IRQ, first call * at91_set_gpio_input() then maybe enable its glitch filter. * Then just request_irq() with the pin ID; it works like any ARM IRQ * handler. * First implementation always triggers on rising and falling edges * whereas the newer PIO3 can be additionally configured to trigger on * level, edge with any polarity. * * Alternatively, certain pins may be used directly as IRQ0..IRQ6 after * configuring them with at91_set_a_periph() or at91_set_b_periph(). * IRQ0..IRQ6 should be configurable, e.g. level vs edge triggering. */ static void gpio_irq_mask(struct irq_data *d) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << d->hwirq; if (pio) writel_relaxed(mask, pio + PIO_IDR); } static void gpio_irq_unmask(struct irq_data *d) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << d->hwirq; if (pio) writel_relaxed(mask, pio + PIO_IER); } static int gpio_irq_type(struct irq_data *d, unsigned type) { switch (type) { case IRQ_TYPE_NONE: case IRQ_TYPE_EDGE_BOTH: return 0; default: return -EINVAL; } } /* Alternate irq type for PIO3 support */ static int alt_gpio_irq_type(struct irq_data *d, unsigned type) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); void __iomem *pio = at91_gpio->regbase; unsigned mask = 1 << d->hwirq; switch (type) { case IRQ_TYPE_EDGE_RISING: __irq_set_handler_locked(d->irq, handle_simple_irq); writel_relaxed(mask, pio + PIO_ESR); writel_relaxed(mask, pio + PIO_REHLSR); break; case IRQ_TYPE_EDGE_FALLING: __irq_set_handler_locked(d->irq, handle_simple_irq); writel_relaxed(mask, pio + PIO_ESR); writel_relaxed(mask, pio + PIO_FELLSR); break; case IRQ_TYPE_LEVEL_LOW: __irq_set_handler_locked(d->irq, handle_level_irq); writel_relaxed(mask, pio + PIO_LSR); writel_relaxed(mask, pio + PIO_FELLSR); break; case IRQ_TYPE_LEVEL_HIGH: __irq_set_handler_locked(d->irq, handle_level_irq); writel_relaxed(mask, pio + PIO_LSR); writel_relaxed(mask, pio + PIO_REHLSR); break; case IRQ_TYPE_EDGE_BOTH: /* * disable additional interrupt modes: * fall back to default behavior */ __irq_set_handler_locked(d->irq, handle_simple_irq); writel_relaxed(mask, pio + PIO_AIMDR); return 0; case IRQ_TYPE_NONE: default: pr_warn("AT91: No type for irq %d\n", gpio_to_irq(d->irq)); return -EINVAL; } /* enable additional interrupt modes */ writel_relaxed(mask, pio + PIO_AIMER); return 0; } static void gpio_irq_ack(struct irq_data *d) { /* the interrupt is already cleared before by reading ISR */ } static unsigned int gpio_irq_startup(struct irq_data *d) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); unsigned pin = d->hwirq; int ret; ret = gpiochip_lock_as_irq(&at91_gpio->chip, pin); if (ret) { dev_err(at91_gpio->chip.dev, "unable to lock pind %lu IRQ\n", d->hwirq); return ret; } gpio_irq_unmask(d); return 0; } static void gpio_irq_shutdown(struct irq_data *d) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); unsigned pin = d->hwirq; gpio_irq_mask(d); gpiochip_unlock_as_irq(&at91_gpio->chip, pin); } #ifdef CONFIG_PM static u32 wakeups[MAX_GPIO_BANKS]; static u32 backups[MAX_GPIO_BANKS]; static int gpio_irq_set_wake(struct irq_data *d, unsigned state) { struct at91_gpio_chip *at91_gpio = irq_data_get_irq_chip_data(d); unsigned bank = at91_gpio->pioc_idx; unsigned mask = 1 << d->hwirq; if (unlikely(bank >= MAX_GPIO_BANKS)) return -EINVAL; if (state) wakeups[bank] |= mask; else wakeups[bank] &= ~mask; irq_set_irq_wake(at91_gpio->pioc_virq, state); return 0; } void at91_pinctrl_gpio_suspend(void) { int i; for (i = 0; i < gpio_banks; i++) { void __iomem *pio; if (!gpio_chips[i]) continue; pio = gpio_chips[i]->regbase; backups[i] = __raw_readl(pio + PIO_IMR); __raw_writel(backups[i], pio + PIO_IDR); __raw_writel(wakeups[i], pio + PIO_IER); if (!wakeups[i]) clk_disable_unprepare(gpio_chips[i]->clock); else printk(KERN_DEBUG "GPIO-%c may wake for %08x\n", 'A'+i, wakeups[i]); } } void at91_pinctrl_gpio_resume(void) { int i; for (i = 0; i < gpio_banks; i++) { void __iomem *pio; if (!gpio_chips[i]) continue; pio = gpio_chips[i]->regbase; if (!wakeups[i]) clk_prepare_enable(gpio_chips[i]->clock); __raw_writel(wakeups[i], pio + PIO_IDR); __raw_writel(backups[i], pio + PIO_IER); } } #else #define gpio_irq_set_wake NULL #endif /* CONFIG_PM */ static struct irq_chip gpio_irqchip = { .name = "GPIO", .irq_ack = gpio_irq_ack, .irq_startup = gpio_irq_startup, .irq_shutdown = gpio_irq_shutdown, .irq_disable = gpio_irq_mask, .irq_mask = gpio_irq_mask, .irq_unmask = gpio_irq_unmask, /* .irq_set_type is set dynamically */ .irq_set_wake = gpio_irq_set_wake, }; static void gpio_irq_handler(unsigned irq, struct irq_desc *desc) { struct irq_chip *chip = irq_get_chip(irq); struct gpio_chip *gpio_chip = irq_desc_get_handler_data(desc); struct at91_gpio_chip *at91_gpio = container_of(gpio_chip, struct at91_gpio_chip, chip); void __iomem *pio = at91_gpio->regbase; unsigned long isr; int n; chained_irq_enter(chip, desc); for (;;) { /* Reading ISR acks pending (edge triggered) GPIO interrupts. * When there are none pending, we're finished unless we need * to process multiple banks (like ID_PIOCDE on sam9263). */ isr = readl_relaxed(pio + PIO_ISR) & readl_relaxed(pio + PIO_IMR); if (!isr) { if (!at91_gpio->next) break; at91_gpio = at91_gpio->next; pio = at91_gpio->regbase; gpio_chip = &at91_gpio->chip; continue; } for_each_set_bit(n, &isr, BITS_PER_LONG) { generic_handle_irq(irq_find_mapping( gpio_chip->irqdomain, n)); } } chained_irq_exit(chip, desc); /* now it may re-trigger */ } static int at91_gpio_of_irq_setup(struct platform_device *pdev, struct at91_gpio_chip *at91_gpio) { struct at91_gpio_chip *prev = NULL; struct irq_data *d = irq_get_irq_data(at91_gpio->pioc_virq); int ret; at91_gpio->pioc_hwirq = irqd_to_hwirq(d); /* Setup proper .irq_set_type function */ gpio_irqchip.irq_set_type = at91_gpio->ops->irq_type; /* Disable irqs of this PIO controller */ writel_relaxed(~0, at91_gpio->regbase + PIO_IDR); /* * Let the generic code handle this edge IRQ, the the chained * handler will perform the actual work of handling the parent * interrupt. */ ret = gpiochip_irqchip_add(&at91_gpio->chip, &gpio_irqchip, 0, handle_edge_irq, IRQ_TYPE_EDGE_BOTH); if (ret) { dev_err(&pdev->dev, "at91_gpio.%d: Couldn't add irqchip to gpiochip.\n", at91_gpio->pioc_idx); return ret; } /* Setup chained handler */ if (at91_gpio->pioc_idx) prev = gpio_chips[at91_gpio->pioc_idx - 1]; /* The top level handler handles one bank of GPIOs, except * on some SoC it can handle up to three... * We only set up the handler for the first of the list. */ if (prev && prev->next == at91_gpio) return 0; /* Then register the chain on the parent IRQ */ gpiochip_set_chained_irqchip(&at91_gpio->chip, &gpio_irqchip, at91_gpio->pioc_virq, gpio_irq_handler); return 0; } /* This structure is replicated for each GPIO block allocated at probe time */ static struct gpio_chip at91_gpio_template = { .request = at91_gpio_request, .free = at91_gpio_free, .get_direction = at91_gpio_get_direction, .direction_input = at91_gpio_direction_input, .get = at91_gpio_get, .direction_output = at91_gpio_direction_output, .set = at91_gpio_set, .dbg_show = at91_gpio_dbg_show, .can_sleep = false, .ngpio = MAX_NB_GPIO_PER_BANK, }; static void at91_gpio_probe_fixup(void) { unsigned i; struct at91_gpio_chip *at91_gpio, *last = NULL; for (i = 0; i < gpio_banks; i++) { at91_gpio = gpio_chips[i]; /* * GPIO controller are grouped on some SoC: * PIOC, PIOD and PIOE can share the same IRQ line */ if (last && last->pioc_virq == at91_gpio->pioc_virq) last->next = at91_gpio; last = at91_gpio; } } static struct of_device_id at91_gpio_of_match[] = { { .compatible = "atmel,at91sam9x5-gpio", .data = &at91sam9x5_ops, }, { .compatible = "atmel,at91rm9200-gpio", .data = &at91rm9200_ops }, { /* sentinel */ } }; static int at91_gpio_probe(struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct resource *res; struct at91_gpio_chip *at91_chip = NULL; struct gpio_chip *chip; struct pinctrl_gpio_range *range; int ret = 0; int irq, i; int alias_idx = of_alias_get_id(np, "gpio"); uint32_t ngpio; char **names; BUG_ON(alias_idx >= ARRAY_SIZE(gpio_chips)); if (gpio_chips[alias_idx]) { ret = -EBUSY; goto err; } irq = platform_get_irq(pdev, 0); if (irq < 0) { ret = irq; goto err; } at91_chip = devm_kzalloc(&pdev->dev, sizeof(*at91_chip), GFP_KERNEL); if (!at91_chip) { ret = -ENOMEM; goto err; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); at91_chip->regbase = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(at91_chip->regbase)) { ret = PTR_ERR(at91_chip->regbase); goto err; } at91_chip->ops = (struct at91_pinctrl_mux_ops *) of_match_device(at91_gpio_of_match, &pdev->dev)->data; at91_chip->pioc_virq = irq; at91_chip->pioc_idx = alias_idx; at91_chip->clock = devm_clk_get(&pdev->dev, NULL); if (IS_ERR(at91_chip->clock)) { dev_err(&pdev->dev, "failed to get clock, ignoring.\n"); ret = PTR_ERR(at91_chip->clock); goto err; } ret = clk_prepare(at91_chip->clock); if (ret) goto clk_prepare_err; /* enable PIO controller's clock */ ret = clk_enable(at91_chip->clock); if (ret) { dev_err(&pdev->dev, "failed to enable clock, ignoring.\n"); goto clk_enable_err; } at91_chip->chip = at91_gpio_template; chip = &at91_chip->chip; chip->of_node = np; chip->label = dev_name(&pdev->dev); chip->dev = &pdev->dev; chip->owner = THIS_MODULE; chip->base = alias_idx * MAX_NB_GPIO_PER_BANK; if (!of_property_read_u32(np, "#gpio-lines", &ngpio)) { if (ngpio >= MAX_NB_GPIO_PER_BANK) pr_err("at91_gpio.%d, gpio-nb >= %d failback to %d\n", alias_idx, MAX_NB_GPIO_PER_BANK, MAX_NB_GPIO_PER_BANK); else chip->ngpio = ngpio; } names = devm_kzalloc(&pdev->dev, sizeof(char *) * chip->ngpio, GFP_KERNEL); if (!names) { ret = -ENOMEM; goto clk_enable_err; } for (i = 0; i < chip->ngpio; i++) names[i] = kasprintf(GFP_KERNEL, "pio%c%d", alias_idx + 'A', i); chip->names = (const char *const *)names; range = &at91_chip->range; range->name = chip->label; range->id = alias_idx; range->pin_base = range->base = range->id * MAX_NB_GPIO_PER_BANK; range->npins = chip->ngpio; range->gc = chip; ret = gpiochip_add(chip); if (ret) goto gpiochip_add_err; gpio_chips[alias_idx] = at91_chip; gpio_banks = max(gpio_banks, alias_idx + 1); at91_gpio_probe_fixup(); ret = at91_gpio_of_irq_setup(pdev, at91_chip); if (ret) goto irq_setup_err; dev_info(&pdev->dev, "at address %p\n", at91_chip->regbase); return 0; irq_setup_err: gpiochip_remove(chip); gpiochip_add_err: clk_disable(at91_chip->clock); clk_enable_err: clk_unprepare(at91_chip->clock); clk_prepare_err: err: dev_err(&pdev->dev, "Failure %i for GPIO %i\n", ret, alias_idx); return ret; } static struct platform_driver at91_gpio_driver = { .driver = { .name = "gpio-at91", .of_match_table = at91_gpio_of_match, }, .probe = at91_gpio_probe, }; static struct platform_driver at91_pinctrl_driver = { .driver = { .name = "pinctrl-at91", .of_match_table = at91_pinctrl_of_match, }, .probe = at91_pinctrl_probe, .remove = at91_pinctrl_remove, }; static int __init at91_pinctrl_init(void) { int ret; ret = platform_driver_register(&at91_gpio_driver); if (ret) return ret; return platform_driver_register(&at91_pinctrl_driver); } arch_initcall(at91_pinctrl_init); static void __exit at91_pinctrl_exit(void) { platform_driver_unregister(&at91_pinctrl_driver); } module_exit(at91_pinctrl_exit); MODULE_AUTHOR("Jean-Christophe PLAGNIOL-VILLARD <[email protected]>"); MODULE_DESCRIPTION("Atmel AT91 pinctrl driver"); MODULE_LICENSE("GPL v2");
211779.c
/* * Copyright (c) 2015 Paul B Mahol * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tesseract/capi.h> #include "libavutil/opt.h" #include "avfilter.h" #include "formats.h" #include "internal.h" #include "video.h" typedef struct OCRContext { const AVClass *class; char *datapath; char *language; char *whitelist; char *blacklist; TessBaseAPI *tess; } OCRContext; #define OFFSET(x) offsetof(OCRContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM static const AVOption ocr_options[] = { { "datapath", "set datapath", OFFSET(datapath), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS }, { "language", "set language", OFFSET(language), AV_OPT_TYPE_STRING, {.str="eng"}, 0, 0, FLAGS }, { "whitelist", "set character whitelist", OFFSET(whitelist), AV_OPT_TYPE_STRING, {.str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.:;,-+_!?\"'[]{}()<>|/\\=*&%$#@!~"}, 0, 0, FLAGS }, { "blacklist", "set character blacklist", OFFSET(blacklist), AV_OPT_TYPE_STRING, {.str=""}, 0, 0, FLAGS }, { NULL } }; static av_cold int init(AVFilterContext *ctx) { OCRContext *s = ctx->priv; s->tess = TessBaseAPICreate(); if (TessBaseAPIInit3(s->tess, s->datapath, s->language) == -1) { av_log(ctx, AV_LOG_ERROR, "failed to init tesseract\n"); return AVERROR(EINVAL); } if (!TessBaseAPISetVariable(s->tess, "tessedit_char_whitelist", s->whitelist)) { av_log(ctx, AV_LOG_ERROR, "failed to set whitelist\n"); return AVERROR(EINVAL); } if (!TessBaseAPISetVariable(s->tess, "tessedit_char_blacklist", s->blacklist)) { av_log(ctx, AV_LOG_ERROR, "failed to set blacklist\n"); return AVERROR(EINVAL); } av_log(ctx, AV_LOG_DEBUG, "Tesseract version: %s\n", TessVersion()); return 0; } static int query_formats(AVFilterContext *ctx) { static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE }; AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts); if (!fmts_list) return AVERROR(ENOMEM); return ff_set_common_formats(ctx, fmts_list); } static int filter_frame(AVFilterLink *inlink, AVFrame *in) { AVDictionary **metadata = &in->metadata; AVFilterContext *ctx = inlink->dst; AVFilterLink *outlink = ctx->outputs[0]; OCRContext *s = ctx->priv; char *result; int *confs; result = TessBaseAPIRect(s->tess, in->data[0], 1, in->linesize[0], 0, 0, in->width, in->height); confs = TessBaseAPIAllWordConfidences(s->tess); av_dict_set(metadata, "lavfi.ocr.text", result, 0); for (int i = 0; confs[i] != -1; i++) { char number[256]; snprintf(number, sizeof(number), "%d ", confs[i]); av_dict_set(metadata, "lavfi.ocr.confidence", number, AV_DICT_APPEND); } TessDeleteText(result); TessDeleteIntArray(confs); return ff_filter_frame(outlink, in); } static av_cold void uninit(AVFilterContext *ctx) { OCRContext *s = ctx->priv; TessBaseAPIEnd(s->tess); TessBaseAPIDelete(s->tess); } AVFILTER_DEFINE_CLASS(ocr); static const AVFilterPad ocr_inputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, .filter_frame = filter_frame, }, { NULL } }; static const AVFilterPad ocr_outputs[] = { { .name = "default", .type = AVMEDIA_TYPE_VIDEO, }, { NULL } }; AVFilter ff_vf_ocr = { .name = "ocr", .description = NULL_IF_CONFIG_SMALL("Optical Character Recognition."), .priv_size = sizeof(OCRContext), .priv_class = &ocr_class, .query_formats = query_formats, .init = init, .uninit = uninit, .inputs = ocr_inputs, .outputs = ocr_outputs, };
69002.c
/* This file is included (from xmltok.c, 1-3 times depending on XML_MIN_SIZE)! __ __ _ ___\ \/ /_ __ __ _| |_ / _ \\ /| '_ \ / _` | __| | __// \| |_) | (_| | |_ \___/_/\_\ .__/ \__,_|\__| |_| XML parser Copyright (c) 1997-2000 Thai Open Source Software Center Ltd Copyright (c) 2000 Clark Cooper <[email protected]> Copyright (c) 2002 Fred L. Drake, Jr. <[email protected]> Copyright (c) 2002-2016 Karl Waclawek <[email protected]> Copyright (c) 2016-2021 Sebastian Pipping <[email protected]> Copyright (c) 2017 Rhodri James <[email protected]> Copyright (c) 2018 Benjamin Peterson <[email protected]> Copyright (c) 2018 Anton Maklakov <[email protected]> Copyright (c) 2019 David Loffredo <[email protected]> Copyright (c) 2020 Boris Kolpackov <[email protected]> Licensed under the MIT license: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef XML_TOK_IMPL_C # ifndef IS_INVALID_CHAR // i.e. for UTF-16 and XML_MIN_SIZE not defined # define IS_INVALID_CHAR(enc, ptr, n) (0) # endif # define INVALID_LEAD_CASE(n, ptr, nextTokPtr) \ case BT_LEAD##n: \ if (end - ptr < n) \ return XML_TOK_PARTIAL_CHAR; \ if (IS_INVALID_CHAR(enc, ptr, n)) { \ *(nextTokPtr) = (ptr); \ return XML_TOK_INVALID; \ } \ ptr += n; \ break; # define INVALID_CASES(ptr, nextTokPtr) \ INVALID_LEAD_CASE(2, ptr, nextTokPtr) \ INVALID_LEAD_CASE(3, ptr, nextTokPtr) \ INVALID_LEAD_CASE(4, ptr, nextTokPtr) \ case BT_NONXML: \ case BT_MALFORM: \ case BT_TRAIL: \ *(nextTokPtr) = (ptr); \ return XML_TOK_INVALID; # define CHECK_NAME_CASE(n, enc, ptr, end, nextTokPtr) \ case BT_LEAD##n: \ if (end - ptr < n) \ return XML_TOK_PARTIAL_CHAR; \ if (! IS_NAME_CHAR(enc, ptr, n)) { \ *nextTokPtr = ptr; \ return XML_TOK_INVALID; \ } \ ptr += n; \ break; # define CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) \ case BT_NONASCII: \ if (! IS_NAME_CHAR_MINBPC(enc, ptr)) { \ *nextTokPtr = ptr; \ return XML_TOK_INVALID; \ } \ /* fall through */ \ case BT_NMSTRT: \ case BT_HEX: \ case BT_DIGIT: \ case BT_NAME: \ case BT_MINUS: \ ptr += MINBPC(enc); \ break; \ CHECK_NAME_CASE(2, enc, ptr, end, nextTokPtr) \ CHECK_NAME_CASE(3, enc, ptr, end, nextTokPtr) \ CHECK_NAME_CASE(4, enc, ptr, end, nextTokPtr) # define CHECK_NMSTRT_CASE(n, enc, ptr, end, nextTokPtr) \ case BT_LEAD##n: \ if (end - ptr < n) \ return XML_TOK_PARTIAL_CHAR; \ if (! IS_NMSTRT_CHAR(enc, ptr, n)) { \ *nextTokPtr = ptr; \ return XML_TOK_INVALID; \ } \ ptr += n; \ break; # define CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) \ case BT_NONASCII: \ if (! IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { \ *nextTokPtr = ptr; \ return XML_TOK_INVALID; \ } \ /* fall through */ \ case BT_NMSTRT: \ case BT_HEX: \ ptr += MINBPC(enc); \ break; \ CHECK_NMSTRT_CASE(2, enc, ptr, end, nextTokPtr) \ CHECK_NMSTRT_CASE(3, enc, ptr, end, nextTokPtr) \ CHECK_NMSTRT_CASE(4, enc, ptr, end, nextTokPtr) # ifndef PREFIX # define PREFIX(ident) ident # endif # define HAS_CHARS(enc, ptr, end, count) (end - ptr >= count * MINBPC(enc)) # define HAS_CHAR(enc, ptr, end) HAS_CHARS(enc, ptr, end, 1) # define REQUIRE_CHARS(enc, ptr, end, count) \ { \ if (! HAS_CHARS(enc, ptr, end, count)) { \ return XML_TOK_PARTIAL; \ } \ } # define REQUIRE_CHAR(enc, ptr, end) REQUIRE_CHARS(enc, ptr, end, 1) /* ptr points to character following "<!-" */ static int PTRCALL PREFIX(scanComment)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { if (HAS_CHAR(enc, ptr, end)) { if (! CHAR_MATCHES(enc, ptr, ASCII_MINUS)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } ptr += MINBPC(enc); while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { INVALID_CASES(ptr, nextTokPtr) case BT_MINUS: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_MINUS)) { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_COMMENT; } break; default: ptr += MINBPC(enc); break; } } } return XML_TOK_PARTIAL; } /* ptr points to character following "<!" */ static int PTRCALL PREFIX(scanDecl)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { case BT_MINUS: return PREFIX(scanComment)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_LSQB: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_COND_SECT_OPEN; case BT_NMSTRT: case BT_HEX: ptr += MINBPC(enc); break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { case BT_PERCNT: REQUIRE_CHARS(enc, ptr, end, 2); /* don't allow <!ENTITY% foo "whatever"> */ switch (BYTE_TYPE(enc, ptr + MINBPC(enc))) { case BT_S: case BT_CR: case BT_LF: case BT_PERCNT: *nextTokPtr = ptr; return XML_TOK_INVALID; } /* fall through */ case BT_S: case BT_CR: case BT_LF: *nextTokPtr = ptr; return XML_TOK_DECL_OPEN; case BT_NMSTRT: case BT_HEX: ptr += MINBPC(enc); break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } static int PTRCALL PREFIX(checkPiTarget)(const ENCODING *enc, const char *ptr, const char *end, int *tokPtr) { int upper = 0; UNUSED_P(enc); *tokPtr = XML_TOK_PI; if (end - ptr != MINBPC(enc) * 3) return 1; switch (BYTE_TO_ASCII(enc, ptr)) { case ASCII_x: break; case ASCII_X: upper = 1; break; default: return 1; } ptr += MINBPC(enc); switch (BYTE_TO_ASCII(enc, ptr)) { case ASCII_m: break; case ASCII_M: upper = 1; break; default: return 1; } ptr += MINBPC(enc); switch (BYTE_TO_ASCII(enc, ptr)) { case ASCII_l: break; case ASCII_L: upper = 1; break; default: return 1; } if (upper) return 0; *tokPtr = XML_TOK_XML_DECL; return 1; } /* ptr points to character following "<?" */ static int PTRCALL PREFIX(scanPi)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { int tok; const char *target = ptr; REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_S: case BT_CR: case BT_LF: if (! PREFIX(checkPiTarget)(enc, target, ptr, &tok)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } ptr += MINBPC(enc); while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { INVALID_CASES(ptr, nextTokPtr) case BT_QUEST: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_GT)) { *nextTokPtr = ptr + MINBPC(enc); return tok; } break; default: ptr += MINBPC(enc); break; } } return XML_TOK_PARTIAL; case BT_QUEST: if (! PREFIX(checkPiTarget)(enc, target, ptr, &tok)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_GT)) { *nextTokPtr = ptr + MINBPC(enc); return tok; } /* fall through */ default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } static int PTRCALL PREFIX(scanCdataSection)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { static const char CDATA_LSQB[] = {ASCII_C, ASCII_D, ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB}; int i; UNUSED_P(enc); /* CDATA[ */ REQUIRE_CHARS(enc, ptr, end, 6); for (i = 0; i < 6; i++, ptr += MINBPC(enc)) { if (! CHAR_MATCHES(enc, ptr, CDATA_LSQB[i])) { *nextTokPtr = ptr; return XML_TOK_INVALID; } } *nextTokPtr = ptr; return XML_TOK_CDATA_SECT_OPEN; } static int PTRCALL PREFIX(cdataSectionTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { if (ptr >= end) return XML_TOK_NONE; if (MINBPC(enc) > 1) { size_t n = end - ptr; if (n & (MINBPC(enc) - 1)) { n &= ~(MINBPC(enc) - 1); if (n == 0) return XML_TOK_PARTIAL; end = ptr + n; } } switch (BYTE_TYPE(enc, ptr)) { case BT_RSQB: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (! CHAR_MATCHES(enc, ptr, ASCII_RSQB)) break; ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) { ptr -= MINBPC(enc); break; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CDATA_SECT_CLOSE; case BT_CR: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (BYTE_TYPE(enc, ptr) == BT_LF) ptr += MINBPC(enc); *nextTokPtr = ptr; return XML_TOK_DATA_NEWLINE; case BT_LF: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_DATA_NEWLINE; INVALID_CASES(ptr, nextTokPtr) default: ptr += MINBPC(enc); break; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ *nextTokPtr = ptr; \ return XML_TOK_DATA_CHARS; \ } \ ptr += n; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_NONXML: case BT_MALFORM: case BT_TRAIL: case BT_CR: case BT_LF: case BT_RSQB: *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; default: ptr += MINBPC(enc); break; } } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; } /* ptr points to character following "</" */ static int PTRCALL PREFIX(scanEndTag)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_S: case BT_CR: case BT_LF: for (ptr += MINBPC(enc); HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) { switch (BYTE_TYPE(enc, ptr)) { case BT_S: case BT_CR: case BT_LF: break; case BT_GT: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_END_TAG; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; # ifdef XML_NS case BT_COLON: /* no need to check qname syntax here, since end-tag must match exactly */ ptr += MINBPC(enc); break; # endif case BT_GT: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_END_TAG; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } /* ptr points to character following "&#X" */ static int PTRCALL PREFIX(scanHexCharRef)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { if (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { case BT_DIGIT: case BT_HEX: break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } for (ptr += MINBPC(enc); HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) { switch (BYTE_TYPE(enc, ptr)) { case BT_DIGIT: case BT_HEX: break; case BT_SEMI: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CHAR_REF; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } } return XML_TOK_PARTIAL; } /* ptr points to character following "&#" */ static int PTRCALL PREFIX(scanCharRef)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { if (HAS_CHAR(enc, ptr, end)) { if (CHAR_MATCHES(enc, ptr, ASCII_x)) return PREFIX(scanHexCharRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); switch (BYTE_TYPE(enc, ptr)) { case BT_DIGIT: break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } for (ptr += MINBPC(enc); HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) { switch (BYTE_TYPE(enc, ptr)) { case BT_DIGIT: break; case BT_SEMI: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CHAR_REF; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } } return XML_TOK_PARTIAL; } /* ptr points to character following "&" */ static int PTRCALL PREFIX(scanRef)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) case BT_NUM: return PREFIX(scanCharRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_SEMI: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_ENTITY_REF; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } /* ptr points to character following first character of attribute name */ static int PTRCALL PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { # ifdef XML_NS int hadColon = 0; # endif while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) # ifdef XML_NS case BT_COLON: if (hadColon) { *nextTokPtr = ptr; return XML_TOK_INVALID; } hadColon = 1; ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) default: *nextTokPtr = ptr; return XML_TOK_INVALID; } break; # endif case BT_S: case BT_CR: case BT_LF: for (;;) { int t; ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); t = BYTE_TYPE(enc, ptr); if (t == BT_EQUALS) break; switch (t) { case BT_S: case BT_LF: case BT_CR: break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } /* fall through */ case BT_EQUALS: { int open; # ifdef XML_NS hadColon = 0; # endif for (;;) { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); open = BYTE_TYPE(enc, ptr); if (open == BT_QUOT || open == BT_APOS) break; switch (open) { case BT_S: case BT_LF: case BT_CR: break; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } ptr += MINBPC(enc); /* in attribute value */ for (;;) { int t; REQUIRE_CHAR(enc, ptr, end); t = BYTE_TYPE(enc, ptr); if (t == open) break; switch (t) { INVALID_CASES(ptr, nextTokPtr) case BT_AMP: { int tok = PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, &ptr); if (tok <= 0) { if (tok == XML_TOK_INVALID) *nextTokPtr = ptr; return tok; } break; } case BT_LT: *nextTokPtr = ptr; return XML_TOK_INVALID; default: ptr += MINBPC(enc); break; } } ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { case BT_S: case BT_CR: case BT_LF: break; case BT_SOL: goto sol; case BT_GT: goto gt; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } /* ptr points to closing quote */ for (;;) { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) case BT_S: case BT_CR: case BT_LF: continue; case BT_GT: gt: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_START_TAG_WITH_ATTS; case BT_SOL: sol: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_EMPTY_ELEMENT_WITH_ATTS; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } break; } break; } default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } /* ptr points to character following "<" */ static int PTRCALL PREFIX(scanLt)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { # ifdef XML_NS int hadColon; # endif REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) case BT_EXCL: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { case BT_MINUS: return PREFIX(scanComment)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_LSQB: return PREFIX(scanCdataSection)(enc, ptr + MINBPC(enc), end, nextTokPtr); } *nextTokPtr = ptr; return XML_TOK_INVALID; case BT_QUEST: return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_SOL: return PREFIX(scanEndTag)(enc, ptr + MINBPC(enc), end, nextTokPtr); default: *nextTokPtr = ptr; return XML_TOK_INVALID; } # ifdef XML_NS hadColon = 0; # endif /* we have a start-tag */ while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) # ifdef XML_NS case BT_COLON: if (hadColon) { *nextTokPtr = ptr; return XML_TOK_INVALID; } hadColon = 1; ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) default: *nextTokPtr = ptr; return XML_TOK_INVALID; } break; # endif case BT_S: case BT_CR: case BT_LF: { ptr += MINBPC(enc); while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) case BT_GT: goto gt; case BT_SOL: goto sol; case BT_S: case BT_CR: case BT_LF: ptr += MINBPC(enc); continue; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } return PREFIX(scanAtts)(enc, ptr, end, nextTokPtr); } return XML_TOK_PARTIAL; } case BT_GT: gt: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_START_TAG_NO_ATTS; case BT_SOL: sol: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_EMPTY_ELEMENT_NO_ATTS; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } static int PTRCALL PREFIX(contentTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { if (ptr >= end) return XML_TOK_NONE; if (MINBPC(enc) > 1) { size_t n = end - ptr; if (n & (MINBPC(enc) - 1)) { n &= ~(MINBPC(enc) - 1); if (n == 0) return XML_TOK_PARTIAL; end = ptr + n; } } switch (BYTE_TYPE(enc, ptr)) { case BT_LT: return PREFIX(scanLt)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_AMP: return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_CR: ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return XML_TOK_TRAILING_CR; if (BYTE_TYPE(enc, ptr) == BT_LF) ptr += MINBPC(enc); *nextTokPtr = ptr; return XML_TOK_DATA_NEWLINE; case BT_LF: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_DATA_NEWLINE; case BT_RSQB: ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return XML_TOK_TRAILING_RSQB; if (! CHAR_MATCHES(enc, ptr, ASCII_RSQB)) break; ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return XML_TOK_TRAILING_RSQB; if (! CHAR_MATCHES(enc, ptr, ASCII_GT)) { ptr -= MINBPC(enc); break; } *nextTokPtr = ptr; return XML_TOK_INVALID; INVALID_CASES(ptr, nextTokPtr) default: ptr += MINBPC(enc); break; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ if (end - ptr < n || IS_INVALID_CHAR(enc, ptr, n)) { \ *nextTokPtr = ptr; \ return XML_TOK_DATA_CHARS; \ } \ ptr += n; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_RSQB: if (HAS_CHARS(enc, ptr, end, 2)) { if (! CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_RSQB)) { ptr += MINBPC(enc); break; } if (HAS_CHARS(enc, ptr, end, 3)) { if (! CHAR_MATCHES(enc, ptr + 2 * MINBPC(enc), ASCII_GT)) { ptr += MINBPC(enc); break; } *nextTokPtr = ptr + 2 * MINBPC(enc); return XML_TOK_INVALID; } } /* fall through */ case BT_AMP: case BT_LT: case BT_NONXML: case BT_MALFORM: case BT_TRAIL: case BT_CR: case BT_LF: *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; default: ptr += MINBPC(enc); break; } } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; } /* ptr points to character following "%" */ static int PTRCALL PREFIX(scanPercent)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) case BT_S: case BT_LF: case BT_CR: case BT_PERCNT: *nextTokPtr = ptr; return XML_TOK_PERCENT; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_SEMI: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_PARAM_ENTITY_REF; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return XML_TOK_PARTIAL; } static int PTRCALL PREFIX(scanPoundName)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { CHECK_NMSTRT_CASES(enc, ptr, end, nextTokPtr) default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_CR: case BT_LF: case BT_S: case BT_RPAR: case BT_GT: case BT_PERCNT: case BT_VERBAR: *nextTokPtr = ptr; return XML_TOK_POUND_NAME; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return -XML_TOK_POUND_NAME; } static int PTRCALL PREFIX(scanLit)(int open, const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { while (HAS_CHAR(enc, ptr, end)) { int t = BYTE_TYPE(enc, ptr); switch (t) { INVALID_CASES(ptr, nextTokPtr) case BT_QUOT: case BT_APOS: ptr += MINBPC(enc); if (t != open) break; if (! HAS_CHAR(enc, ptr, end)) return -XML_TOK_LITERAL; *nextTokPtr = ptr; switch (BYTE_TYPE(enc, ptr)) { case BT_S: case BT_CR: case BT_LF: case BT_GT: case BT_PERCNT: case BT_LSQB: return XML_TOK_LITERAL; default: return XML_TOK_INVALID; } default: ptr += MINBPC(enc); break; } } return XML_TOK_PARTIAL; } static int PTRCALL PREFIX(prologTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { int tok; if (ptr >= end) return XML_TOK_NONE; if (MINBPC(enc) > 1) { size_t n = end - ptr; if (n & (MINBPC(enc) - 1)) { n &= ~(MINBPC(enc) - 1); if (n == 0) return XML_TOK_PARTIAL; end = ptr + n; } } switch (BYTE_TYPE(enc, ptr)) { case BT_QUOT: return PREFIX(scanLit)(BT_QUOT, enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_APOS: return PREFIX(scanLit)(BT_APOS, enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_LT: { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); switch (BYTE_TYPE(enc, ptr)) { case BT_EXCL: return PREFIX(scanDecl)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_QUEST: return PREFIX(scanPi)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_NMSTRT: case BT_HEX: case BT_NONASCII: case BT_LEAD2: case BT_LEAD3: case BT_LEAD4: *nextTokPtr = ptr - MINBPC(enc); return XML_TOK_INSTANCE_START; } *nextTokPtr = ptr; return XML_TOK_INVALID; } case BT_CR: if (ptr + MINBPC(enc) == end) { *nextTokPtr = end; /* indicate that this might be part of a CR/LF pair */ return -XML_TOK_PROLOG_S; } /* fall through */ case BT_S: case BT_LF: for (;;) { ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) break; switch (BYTE_TYPE(enc, ptr)) { case BT_S: case BT_LF: break; case BT_CR: /* don't split CR/LF pair */ if (ptr + MINBPC(enc) != end) break; /* fall through */ default: *nextTokPtr = ptr; return XML_TOK_PROLOG_S; } } *nextTokPtr = ptr; return XML_TOK_PROLOG_S; case BT_PERCNT: return PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr); case BT_COMMA: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_COMMA; case BT_LSQB: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_OPEN_BRACKET; case BT_RSQB: ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return -XML_TOK_CLOSE_BRACKET; if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { REQUIRE_CHARS(enc, ptr, end, 2); if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_GT)) { *nextTokPtr = ptr + 2 * MINBPC(enc); return XML_TOK_COND_SECT_CLOSE; } } *nextTokPtr = ptr; return XML_TOK_CLOSE_BRACKET; case BT_LPAR: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_OPEN_PAREN; case BT_RPAR: ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return -XML_TOK_CLOSE_PAREN; switch (BYTE_TYPE(enc, ptr)) { case BT_AST: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CLOSE_PAREN_ASTERISK; case BT_QUEST: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CLOSE_PAREN_QUESTION; case BT_PLUS: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_CLOSE_PAREN_PLUS; case BT_CR: case BT_LF: case BT_S: case BT_GT: case BT_COMMA: case BT_VERBAR: case BT_RPAR: *nextTokPtr = ptr; return XML_TOK_CLOSE_PAREN; } *nextTokPtr = ptr; return XML_TOK_INVALID; case BT_VERBAR: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_OR; case BT_GT: *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_DECL_CLOSE; case BT_NUM: return PREFIX(scanPoundName)(enc, ptr + MINBPC(enc), end, nextTokPtr); # define LEAD_CASE(n) \ case BT_LEAD##n: \ if (end - ptr < n) \ return XML_TOK_PARTIAL_CHAR; \ if (IS_NMSTRT_CHAR(enc, ptr, n)) { \ ptr += n; \ tok = XML_TOK_NAME; \ break; \ } \ if (IS_NAME_CHAR(enc, ptr, n)) { \ ptr += n; \ tok = XML_TOK_NMTOKEN; \ break; \ } \ *nextTokPtr = ptr; \ return XML_TOK_INVALID; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_NMSTRT: case BT_HEX: tok = XML_TOK_NAME; ptr += MINBPC(enc); break; case BT_DIGIT: case BT_NAME: case BT_MINUS: # ifdef XML_NS case BT_COLON: # endif tok = XML_TOK_NMTOKEN; ptr += MINBPC(enc); break; case BT_NONASCII: if (IS_NMSTRT_CHAR_MINBPC(enc, ptr)) { ptr += MINBPC(enc); tok = XML_TOK_NAME; break; } if (IS_NAME_CHAR_MINBPC(enc, ptr)) { ptr += MINBPC(enc); tok = XML_TOK_NMTOKEN; break; } /* fall through */ default: *nextTokPtr = ptr; return XML_TOK_INVALID; } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) case BT_GT: case BT_RPAR: case BT_COMMA: case BT_VERBAR: case BT_LSQB: case BT_PERCNT: case BT_S: case BT_CR: case BT_LF: *nextTokPtr = ptr; return tok; # ifdef XML_NS case BT_COLON: ptr += MINBPC(enc); switch (tok) { case XML_TOK_NAME: REQUIRE_CHAR(enc, ptr, end); tok = XML_TOK_PREFIXED_NAME; switch (BYTE_TYPE(enc, ptr)) { CHECK_NAME_CASES(enc, ptr, end, nextTokPtr) default: tok = XML_TOK_NMTOKEN; break; } break; case XML_TOK_PREFIXED_NAME: tok = XML_TOK_NMTOKEN; break; } break; # endif case BT_PLUS: if (tok == XML_TOK_NMTOKEN) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_NAME_PLUS; case BT_AST: if (tok == XML_TOK_NMTOKEN) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_NAME_ASTERISK; case BT_QUEST: if (tok == XML_TOK_NMTOKEN) { *nextTokPtr = ptr; return XML_TOK_INVALID; } *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_NAME_QUESTION; default: *nextTokPtr = ptr; return XML_TOK_INVALID; } } return -tok; } static int PTRCALL PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { const char *start; if (ptr >= end) return XML_TOK_NONE; else if (! HAS_CHAR(enc, ptr, end)) { /* This line cannot be executed. The incoming data has already * been tokenized once, so incomplete characters like this have * already been eliminated from the input. Retaining the paranoia * check is still valuable, however. */ return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */ } start = ptr; while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ ptr += n; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_AMP: if (ptr == start) return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_LT: /* this is for inside entity references */ *nextTokPtr = ptr; return XML_TOK_INVALID; case BT_LF: if (ptr == start) { *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_DATA_NEWLINE; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_CR: if (ptr == start) { ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return XML_TOK_TRAILING_CR; if (BYTE_TYPE(enc, ptr) == BT_LF) ptr += MINBPC(enc); *nextTokPtr = ptr; return XML_TOK_DATA_NEWLINE; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_S: if (ptr == start) { *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_ATTRIBUTE_VALUE_S; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; default: ptr += MINBPC(enc); break; } } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; } static int PTRCALL PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { const char *start; if (ptr >= end) return XML_TOK_NONE; else if (! HAS_CHAR(enc, ptr, end)) { /* This line cannot be executed. The incoming data has already * been tokenized once, so incomplete characters like this have * already been eliminated from the input. Retaining the paranoia * check is still valuable, however. */ return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */ } start = ptr; while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ ptr += n; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_AMP: if (ptr == start) return PREFIX(scanRef)(enc, ptr + MINBPC(enc), end, nextTokPtr); *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_PERCNT: if (ptr == start) { int tok = PREFIX(scanPercent)(enc, ptr + MINBPC(enc), end, nextTokPtr); return (tok == XML_TOK_PERCENT) ? XML_TOK_INVALID : tok; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_LF: if (ptr == start) { *nextTokPtr = ptr + MINBPC(enc); return XML_TOK_DATA_NEWLINE; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; case BT_CR: if (ptr == start) { ptr += MINBPC(enc); if (! HAS_CHAR(enc, ptr, end)) return XML_TOK_TRAILING_CR; if (BYTE_TYPE(enc, ptr) == BT_LF) ptr += MINBPC(enc); *nextTokPtr = ptr; return XML_TOK_DATA_NEWLINE; } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; default: ptr += MINBPC(enc); break; } } *nextTokPtr = ptr; return XML_TOK_DATA_CHARS; } # ifdef XML_DTD static int PTRCALL PREFIX(ignoreSectionTok)(const ENCODING *enc, const char *ptr, const char *end, const char **nextTokPtr) { int level = 0; if (MINBPC(enc) > 1) { size_t n = end - ptr; if (n & (MINBPC(enc) - 1)) { n &= ~(MINBPC(enc) - 1); end = ptr + n; } } while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { INVALID_CASES(ptr, nextTokPtr) case BT_LT: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_EXCL)) { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_LSQB)) { ++level; ptr += MINBPC(enc); } } break; case BT_RSQB: ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_RSQB)) { ptr += MINBPC(enc); REQUIRE_CHAR(enc, ptr, end); if (CHAR_MATCHES(enc, ptr, ASCII_GT)) { ptr += MINBPC(enc); if (level == 0) { *nextTokPtr = ptr; return XML_TOK_IGNORE_SECT; } --level; } } break; default: ptr += MINBPC(enc); break; } } return XML_TOK_PARTIAL; } # endif /* XML_DTD */ static int PTRCALL PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end, const char **badPtr) { ptr += MINBPC(enc); end -= MINBPC(enc); for (; HAS_CHAR(enc, ptr, end); ptr += MINBPC(enc)) { switch (BYTE_TYPE(enc, ptr)) { case BT_DIGIT: case BT_HEX: case BT_MINUS: case BT_APOS: case BT_LPAR: case BT_RPAR: case BT_PLUS: case BT_COMMA: case BT_SOL: case BT_EQUALS: case BT_QUEST: case BT_CR: case BT_LF: case BT_SEMI: case BT_EXCL: case BT_AST: case BT_PERCNT: case BT_NUM: # ifdef XML_NS case BT_COLON: # endif break; case BT_S: if (CHAR_MATCHES(enc, ptr, ASCII_TAB)) { *badPtr = ptr; return 0; } break; case BT_NAME: case BT_NMSTRT: if (! (BYTE_TO_ASCII(enc, ptr) & ~0x7f)) break; /* fall through */ default: switch (BYTE_TO_ASCII(enc, ptr)) { case 0x24: /* $ */ case 0x40: /* @ */ break; default: *badPtr = ptr; return 0; } break; } } return 1; } /* This must only be called for a well-formed start-tag or empty element tag. Returns the number of attributes. Pointers to the first attsMax attributes are stored in atts. */ static int PTRCALL PREFIX(getAtts)(const ENCODING *enc, const char *ptr, int attsMax, ATTRIBUTE *atts) { enum { other, inName, inValue } state = inName; int nAtts = 0; int open = 0; /* defined when state == inValue; initialization just to shut up compilers */ for (ptr += MINBPC(enc);; ptr += MINBPC(enc)) { switch (BYTE_TYPE(enc, ptr)) { # define START_NAME \ if (state == other) { \ if (nAtts < attsMax) { \ atts[nAtts].name = ptr; \ atts[nAtts].normalized = 1; \ } \ state = inName; \ } # define LEAD_CASE(n) \ case BT_LEAD##n: \ START_NAME ptr += (n - MINBPC(enc)); \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_NONASCII: case BT_NMSTRT: case BT_HEX: START_NAME break; # undef START_NAME case BT_QUOT: if (state != inValue) { if (nAtts < attsMax) atts[nAtts].valuePtr = ptr + MINBPC(enc); state = inValue; open = BT_QUOT; } else if (open == BT_QUOT) { state = other; if (nAtts < attsMax) atts[nAtts].valueEnd = ptr; nAtts++; } break; case BT_APOS: if (state != inValue) { if (nAtts < attsMax) atts[nAtts].valuePtr = ptr + MINBPC(enc); state = inValue; open = BT_APOS; } else if (open == BT_APOS) { state = other; if (nAtts < attsMax) atts[nAtts].valueEnd = ptr; nAtts++; } break; case BT_AMP: if (nAtts < attsMax) atts[nAtts].normalized = 0; break; case BT_S: if (state == inName) state = other; else if (state == inValue && nAtts < attsMax && atts[nAtts].normalized && (ptr == atts[nAtts].valuePtr || BYTE_TO_ASCII(enc, ptr) != ASCII_SPACE || BYTE_TO_ASCII(enc, ptr + MINBPC(enc)) == ASCII_SPACE || BYTE_TYPE(enc, ptr + MINBPC(enc)) == open)) atts[nAtts].normalized = 0; break; case BT_CR: case BT_LF: /* This case ensures that the first attribute name is counted Apart from that we could just change state on the quote. */ if (state == inName) state = other; else if (state == inValue && nAtts < attsMax) atts[nAtts].normalized = 0; break; case BT_GT: case BT_SOL: if (state != inValue) return nAtts; break; default: break; } } /* not reached */ } static int PTRFASTCALL PREFIX(charRefNumber)(const ENCODING *enc, const char *ptr) { int result = 0; /* skip &# */ UNUSED_P(enc); ptr += 2 * MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_x)) { for (ptr += MINBPC(enc); ! CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) { int c = BYTE_TO_ASCII(enc, ptr); switch (c) { case ASCII_0: case ASCII_1: case ASCII_2: case ASCII_3: case ASCII_4: case ASCII_5: case ASCII_6: case ASCII_7: case ASCII_8: case ASCII_9: result <<= 4; result |= (c - ASCII_0); break; case ASCII_A: case ASCII_B: case ASCII_C: case ASCII_D: case ASCII_E: case ASCII_F: result <<= 4; result += 10 + (c - ASCII_A); break; case ASCII_a: case ASCII_b: case ASCII_c: case ASCII_d: case ASCII_e: case ASCII_f: result <<= 4; result += 10 + (c - ASCII_a); break; } if (result >= 0x110000) return -1; } } else { for (; ! CHAR_MATCHES(enc, ptr, ASCII_SEMI); ptr += MINBPC(enc)) { int c = BYTE_TO_ASCII(enc, ptr); result *= 10; result += (c - ASCII_0); if (result >= 0x110000) return -1; } } return checkCharRefNumber(result); } static int PTRCALL PREFIX(predefinedEntityName)(const ENCODING *enc, const char *ptr, const char *end) { UNUSED_P(enc); switch ((end - ptr) / MINBPC(enc)) { case 2: if (CHAR_MATCHES(enc, ptr + MINBPC(enc), ASCII_t)) { switch (BYTE_TO_ASCII(enc, ptr)) { case ASCII_l: return ASCII_LT; case ASCII_g: return ASCII_GT; } } break; case 3: if (CHAR_MATCHES(enc, ptr, ASCII_a)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_m)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_p)) return ASCII_AMP; } } break; case 4: switch (BYTE_TO_ASCII(enc, ptr)) { case ASCII_q: ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_u)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_o)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_t)) return ASCII_QUOT; } } break; case ASCII_a: ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_p)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_o)) { ptr += MINBPC(enc); if (CHAR_MATCHES(enc, ptr, ASCII_s)) return ASCII_APOS; } } break; } } return 0; } static int PTRCALL PREFIX(nameMatchesAscii)(const ENCODING *enc, const char *ptr1, const char *end1, const char *ptr2) { UNUSED_P(enc); for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) { if (end1 - ptr1 < MINBPC(enc)) { /* This line cannot be executed. The incoming data has already * been tokenized once, so incomplete characters like this have * already been eliminated from the input. Retaining the * paranoia check is still valuable, however. */ return 0; /* LCOV_EXCL_LINE */ } if (! CHAR_MATCHES(enc, ptr1, *ptr2)) return 0; } return ptr1 == end1; } static int PTRFASTCALL PREFIX(nameLength)(const ENCODING *enc, const char *ptr) { const char *start = ptr; for (;;) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ ptr += n; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_NONASCII: case BT_NMSTRT: # ifdef XML_NS case BT_COLON: # endif case BT_HEX: case BT_DIGIT: case BT_NAME: case BT_MINUS: ptr += MINBPC(enc); break; default: return (int)(ptr - start); } } } static const char *PTRFASTCALL PREFIX(skipS)(const ENCODING *enc, const char *ptr) { for (;;) { switch (BYTE_TYPE(enc, ptr)) { case BT_LF: case BT_CR: case BT_S: ptr += MINBPC(enc); break; default: return ptr; } } } static void PTRCALL PREFIX(updatePosition)(const ENCODING *enc, const char *ptr, const char *end, POSITION *pos) { while (HAS_CHAR(enc, ptr, end)) { switch (BYTE_TYPE(enc, ptr)) { # define LEAD_CASE(n) \ case BT_LEAD##n: \ ptr += n; \ pos->columnNumber++; \ break; LEAD_CASE(2) LEAD_CASE(3) LEAD_CASE(4) # undef LEAD_CASE case BT_LF: pos->columnNumber = 0; pos->lineNumber++; ptr += MINBPC(enc); break; case BT_CR: pos->lineNumber++; ptr += MINBPC(enc); if (HAS_CHAR(enc, ptr, end) && BYTE_TYPE(enc, ptr) == BT_LF) ptr += MINBPC(enc); pos->columnNumber = 0; break; default: ptr += MINBPC(enc); pos->columnNumber++; break; } } } # undef DO_LEAD_CASE # undef MULTIBYTE_CASES # undef INVALID_CASES # undef CHECK_NAME_CASE # undef CHECK_NAME_CASES # undef CHECK_NMSTRT_CASE # undef CHECK_NMSTRT_CASES #endif /* XML_TOK_IMPL_C */
539734.c
#include <idt.h> #include <string.h> extern void idt_flush(idtr_t*); idt_t idt[256]; idtr_t idtr[1]; static void set_gate_idt(int n, unsigned int offset, unsigned short sel, unsigned char flags, unsigned char dpl, unsigned char p) { idt[n].offset_15_0 = offset &0xFFFF; idt[n].sel = sel; idt[n].unused = 0; idt[n].flags = flags; idt[n].dpl = dpl; idt[n].p = p; idt[n].offset_31_16 = offset >> 16 &0xFFFF; } void idt_install(void) { memset(idt,0,sizeof(idt_t)*256); // 0 - 0x1F exceptions_install(); // 0x20 - irq_install(); idtr->limit = (sizeof(idt_t)*256)-1; idtr->base = (unsigned int)idt; idt_flush(idtr); } void trap(int n, unsigned int offset,unsigned short sel, unsigned char dpl ) { set_gate_idt(n,offset,sel,0x8F,dpl,1); } void interrupter(int n, unsigned int offset, unsigned short sel, unsigned char dpl ) { set_gate_idt(n,offset,sel,0x8E,dpl,1); }
779566.c
// // Created by Michael Gafert on 19.11.17. // #include <avr/io.h> #include "pump.h" #ifndef CONCAT_HELPER #define CONCAT_HELPER(a, b) a ## b #endif #ifndef CONCAT #define CONCAT(a, b) CONCAT_HELPER(a,b) #endif #define PUMP_DDRx CONCAT(DDR, PUMP_PORT) #define PUMP_PORTx CONCAT(PORT, PUMP_PORT) void init_pump(){ PUMP_DDRx |= _BV(PUMP_PIN); } void pump_on(){ PUMP_PORTx |= _BV(PUMP_PIN); } void pump_off(){ PUMP_PORTx &= ~_BV(PUMP_PIN); }
180612.c
/* * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved. * Copyright (C) 2004-2009 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "tools.h" struct vgrename_params { const char *vg_name_old; const char *vg_name_new; unsigned int old_name_is_uuid : 1; unsigned int lock_vg_old_first : 1; unsigned int unlock_new_name: 1; }; static int _lock_new_vg_for_rename(struct cmd_context *cmd, const char *vg_name_new) { if (!lock_vol(cmd, vg_name_new, LCK_VG_WRITE, NULL)) { log_error("Can't get lock for %s", vg_name_new); return 0; } return 1; } static int _vgrename_single(struct cmd_context *cmd, const char *vg_name, struct volume_group *vg, struct processing_handle *handle) { struct vgrename_params *vp = (struct vgrename_params *) handle->custom_handle; char old_path[PATH_MAX]; char new_path[PATH_MAX]; struct id id; const char *name; char *dev_dir; /* * vg_name_old may be a UUID which process_each_vg * replaced with the real VG name. In that case, * vp->vg_name_old will be the UUID and vg_name will be * the actual VG name. Check again if the old and new * names match, using the real names. */ if (vp->old_name_is_uuid && !strcmp(vp->vg_name_new, vg_name)) { log_error("New VG name must differ from the old VG name."); return ECMD_FAILED; } /* * Check if a VG already exists with the new VG name. * * (FIXME: We could look for the new name in the list of all * VGs that process_each_vg created, but we don't have access * to that list here, so we have to look in lvmcache. * This requires populating lvmcache when using lvmetad.) */ lvmcache_seed_infos_from_lvmetad(cmd); if (lvmcache_vginfo_from_vgname(vp->vg_name_new, NULL)) { log_error("New VG name \"%s\" already exists", vp->vg_name_new); return ECMD_FAILED; } if (id_read_format_try(&id, vp->vg_name_new) && (name = lvmcache_vgname_from_vgid(cmd->mem, (const char *)&id))) { log_error("New VG name \"%s\" matches the UUID of existing VG %s", vp->vg_name_new, name); return ECMD_FAILED; } /* * Lock the old VG name first: * . The old VG name has already been locked by process_each_vg. * . Now lock the new VG name here, second. * * Lock the new VG name first: * . The new VG name has already been pre-locked below, * before process_each_vg was called. * . process_each_vg then locked the old VG name second. * . Nothing to do here. * * Special case when the old VG name is a uuid: * . The old VG's real name wasn't known before process_each_vg, * so the correct lock ordering wasn't known beforehand, * so no pre-locking was done. * . The old VG's real name has been locked by process_each_vg. * . Now lock the new VG name here, second. * . Suppress lock ordering checks because the lock order may * have wanted the new name first, which wasn't possible in * this uuid-for-name case. */ if (vp->lock_vg_old_first || vp->old_name_is_uuid) { if (vp->old_name_is_uuid) lvmcache_lock_ordering(0); if (!_lock_new_vg_for_rename(cmd, vp->vg_name_new)) return ECMD_FAILED; lvmcache_lock_ordering(1); } dev_dir = cmd->dev_dir; if (!archive(vg)) goto error; /* Remove references based on old name */ if (!drop_cached_metadata(vg)) stack; if (!lockd_rename_vg_before(cmd, vg)) { stack; goto error; } /* Change the volume group name */ vg_rename(cmd, vg, vp->vg_name_new); /* store it on disks */ log_verbose("Writing out updated volume group"); if (!vg_write(vg) || !vg_commit(vg)) { goto error; } if ((dm_snprintf(old_path, sizeof(old_path), "%s%s", dev_dir, vg_name) < 0) || (dm_snprintf(new_path, sizeof(new_path), "%s%s", dev_dir, vp->vg_name_new) < 0)) { log_error("Renaming path is too long %s/%s %s/%s", dev_dir, vg_name, dev_dir, vp->vg_name_new); goto error; } if (activation() && dir_exists(old_path)) { log_verbose("Renaming \"%s\" to \"%s\"", old_path, new_path); if (test_mode()) log_verbose("Test mode: Skipping rename."); else if (lvs_in_vg_activated(vg)) { if (!vg_refresh_visible(cmd, vg)) { log_error("Renaming \"%s\" to \"%s\" failed", old_path, new_path); goto error; } } } lockd_rename_vg_final(cmd, vg, 1); if (!backup(vg)) stack; if (!backup_remove(cmd, vg_name)) stack; unlock_vg(cmd, vg, vp->vg_name_new); vp->unlock_new_name = 0; log_print_unless_silent("Volume group \"%s\" successfully renamed to \"%s\"", vp->vg_name_old, vp->vg_name_new); return 1; error: unlock_vg(cmd, vg, vp->vg_name_new); vp->unlock_new_name = 0; lockd_rename_vg_final(cmd, vg, 0); return 0; } int vgrename(struct cmd_context *cmd, int argc, char **argv) { struct vgrename_params vp = { 0 }; struct processing_handle *handle; const char *vg_name_new; const char *vg_name_old; struct id id; int ret; if (argc != 2) { log_error("Old and new volume group names need specifying"); return EINVALID_CMD_LINE; } vg_name_old = skip_dev_dir(cmd, argv[0], NULL); vg_name_new = skip_dev_dir(cmd, argv[1], NULL); if (!validate_vg_rename_params(cmd, vg_name_old, vg_name_new)) return_0; if (!(vp.vg_name_old = dm_pool_strdup(cmd->mem, vg_name_old))) return_ECMD_FAILED; if (!(vp.vg_name_new = dm_pool_strdup(cmd->mem, vg_name_new))) return_ECMD_FAILED; /* Needed change the global VG namespace. */ if (!lockd_gl(cmd, "ex", LDGL_UPDATE_NAMES)) return_ECMD_FAILED; /* * Special case where vg_name_old may be a UUID: * If vg_name_old is a UUID, then process_each may * translate it to an actual VG name that we don't * yet know. The lock ordering, and pre-locking, * needs to be done based on VG names. When * vg_name_old is a UUID, do not do any pre-locking * based on it, since it's likely to be wrong, and * defer all the locking to the _single function. * * When it's not a UUID, we know the two VG names, * and we can pre-lock the new VG name if the lock * ordering wants it locked before the old VG name * which will be locked by process_each. If lock * ordering wants the old name locked first, then * the _single function will lock the new VG name. */ if (!(vp.old_name_is_uuid = id_read_format_try(&id, vg_name_old))) { if (strcmp(vg_name_new, vg_name_old) < 0) { vp.lock_vg_old_first = 0; vp.unlock_new_name = 1; if (!_lock_new_vg_for_rename(cmd, vg_name_new)) return ECMD_FAILED; } else { /* The old VG is locked by process_each_vg. */ vp.lock_vg_old_first = 1; } } if (!(handle = init_processing_handle(cmd, NULL))) { log_error("Failed to initialize processing handle."); return ECMD_FAILED; } handle->custom_handle = &vp; ret = process_each_vg(cmd, 0, NULL, vg_name_old, NULL, READ_FOR_UPDATE | READ_ALLOW_EXPORTED, 0, handle, _vgrename_single); /* Needed if process_each_vg returns error before calling _single. */ if (vp.unlock_new_name) unlock_vg(cmd, NULL, vg_name_new); destroy_processing_handle(cmd, handle); return ret; }
108916.c
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * 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 <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/mphal.h" #include "pin.h" #include "sdcard.h" const mp_obj_type_t pin_cpu_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_cpu, .locals_dict = (mp_obj_dict_t *)&pin_cpu_pins_locals_dict, }; const mp_obj_type_t pin_board_pins_obj_type = { { &mp_type_type }, .name = MP_QSTR_board, .locals_dict = (mp_obj_dict_t *)&pin_board_pins_locals_dict, }; const pin_obj_t *pin_find_named_pin(const mp_obj_dict_t *named_pins, mp_obj_t name) { const mp_map_t *named_map = &named_pins->map; mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t *)named_map, name, MP_MAP_LOOKUP); if (named_elem != NULL && named_elem->value != MP_OBJ_NULL) { return MP_OBJ_TO_PTR(named_elem->value); } return NULL; } const pin_af_obj_t *pin_find_af(const pin_obj_t *pin, uint8_t fn, uint8_t unit) { const pin_af_obj_t *af = pin->af; for (mp_uint_t i = 0; i < pin->num_af; i++, af++) { if (af->fn == fn && af->unit == unit) { return af; } } return NULL; } const pin_af_obj_t *pin_find_af_by_index(const pin_obj_t *pin, mp_uint_t af_idx) { const pin_af_obj_t *af = pin->af; for (mp_uint_t i = 0; i < pin->num_af; i++, af++) { if (af->idx == af_idx) { return af; } } return NULL; } /* unused const pin_af_obj_t *pin_find_af_by_name(const pin_obj_t *pin, const char *name) { const pin_af_obj_t *af = pin->af; for (mp_uint_t i = 0; i < pin->num_af; i++, af++) { if (strcmp(name, qstr_str(af->name)) == 0) { return af; } } return NULL; } */
649091.c
/* * Copyright (c) 2014 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <limits.h> #include <math.h> #include "vpx_dsp/vpx_dsp_common.h" #include "vpx_ports/system_state.h" #include "vp9/encoder/vp9_aq_cyclicrefresh.h" #include "vp9/common/vp9_seg_common.h" #include "vp9/encoder/vp9_ratectrl.h" #include "vp9/encoder/vp9_segmentation.h" static const uint8_t VP9_VAR_OFFS[64] = { 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128 }; CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) { size_t last_coded_q_map_size; CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr)); if (cr == NULL) return NULL; cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map)); if (cr->map == NULL) { vp9_cyclic_refresh_free(cr); return NULL; } last_coded_q_map_size = mi_rows * mi_cols * sizeof(*cr->last_coded_q_map); cr->last_coded_q_map = vpx_malloc(last_coded_q_map_size); if (cr->last_coded_q_map == NULL) { vp9_cyclic_refresh_free(cr); return NULL; } assert(MAXQ <= 255); memset(cr->last_coded_q_map, MAXQ, last_coded_q_map_size); cr->counter_encode_maxq_scene_change = 0; return cr; } void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) { if (cr != NULL) { vpx_free(cr->map); vpx_free(cr->last_coded_q_map); vpx_free(cr); } } // Check if this coding block, of size bsize, should be considered for refresh // (lower-qp coding). Decision can be based on various factors, such as // size of the coding block (i.e., below min_block size rejected), coding // mode, and rate/distortion. static int candidate_refresh_aq(const CYCLIC_REFRESH *cr, const MODE_INFO *mi, int64_t rate, int64_t dist, int bsize) { MV mv = mi->mv[0].as_mv; // Reject the block for lower-qp coding if projected distortion // is above the threshold, and any of the following is true: // 1) mode uses large mv // 2) mode is an intra-mode // Otherwise accept for refresh. if (dist > cr->thresh_dist_sb && (mv.row > cr->motion_thresh || mv.row < -cr->motion_thresh || mv.col > cr->motion_thresh || mv.col < -cr->motion_thresh || !is_inter_block(mi))) return CR_SEGMENT_ID_BASE; else if (bsize >= BLOCK_16X16 && rate < cr->thresh_rate_sb && is_inter_block(mi) && mi->mv[0].as_int == 0 && cr->rate_boost_fac > 10) // More aggressive delta-q for bigger blocks with zero motion. return CR_SEGMENT_ID_BOOST2; else return CR_SEGMENT_ID_BOOST1; } // Compute delta-q for the segment. static int compute_deltaq(const VP9_COMP *cpi, int q, double rate_factor) { const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; const RATE_CONTROL *const rc = &cpi->rc; int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type, q, rate_factor, cpi->common.bit_depth); if ((-deltaq) > cr->max_qdelta_perc * q / 100) { deltaq = -cr->max_qdelta_perc * q / 100; } return deltaq; } // For the just encoded frame, estimate the bits, incorporating the delta-q // from non-base segment. For now ignore effect of multiple segments // (with different delta-q). Note this function is called in the postencode // (called from rc_update_rate_correction_factors()). int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi, double correction_factor) { const VP9_COMMON *const cm = &cpi->common; const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; int estimated_bits; int mbs = cm->MBs; int num8x8bl = mbs << 2; // Weight for non-base segments: use actual number of blocks refreshed in // previous/just encoded frame. Note number of blocks here is in 8x8 units. double weight_segment1 = (double)cr->actual_num_seg1_blocks / num8x8bl; double weight_segment2 = (double)cr->actual_num_seg2_blocks / num8x8bl; // Take segment weighted average for estimated bits. estimated_bits = (int)((1.0 - weight_segment1 - weight_segment2) * vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs, correction_factor, cm->bit_depth) + weight_segment1 * vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex + cr->qindex_delta[1], mbs, correction_factor, cm->bit_depth) + weight_segment2 * vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex + cr->qindex_delta[2], mbs, correction_factor, cm->bit_depth)); return estimated_bits; } // Prior to encoding the frame, estimate the bits per mb, for a given q = i and // a corresponding delta-q (for segment 1). This function is called in the // rc_regulate_q() to set the base qp index. // Note: the segment map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or // to 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock, prior to encoding. int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i, double correction_factor) { const VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; int bits_per_mb; int deltaq = 0; if (cpi->oxcf.speed < 8) deltaq = compute_deltaq(cpi, i, cr->rate_ratio_qdelta); else deltaq = -(cr->max_qdelta_perc * i) / 200; // Take segment weighted average for bits per mb. bits_per_mb = (int)((1.0 - cr->weight_segment) * vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) + cr->weight_segment * vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor, cm->bit_depth)); return bits_per_mb; } // Prior to coding a given prediction block, of size bsize at (mi_row, mi_col), // check if we should reset the segment_id, and update the cyclic_refresh map // and segmentation map. void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi, MODE_INFO *const mi, int mi_row, int mi_col, BLOCK_SIZE bsize, int64_t rate, int64_t dist, int skip, struct macroblock_plane *const p) { const VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; const int bw = num_8x8_blocks_wide_lookup[bsize]; const int bh = num_8x8_blocks_high_lookup[bsize]; const int xmis = VPXMIN(cm->mi_cols - mi_col, bw); const int ymis = VPXMIN(cm->mi_rows - mi_row, bh); const int block_index = mi_row * cm->mi_cols + mi_col; int refresh_this_block = candidate_refresh_aq(cr, mi, rate, dist, bsize); // Default is to not update the refresh map. int new_map_value = cr->map[block_index]; int x = 0; int y = 0; int is_skin = 0; if (refresh_this_block == 0 && bsize <= BLOCK_16X16 && cpi->use_skin_detection) { is_skin = vp9_compute_skin_block(p[0].src.buf, p[1].src.buf, p[2].src.buf, p[0].src.stride, p[1].src.stride, bsize, 0, 0); if (is_skin) refresh_this_block = 1; } if (cpi->oxcf.rc_mode == VPX_VBR && mi->ref_frame[0] == GOLDEN_FRAME) refresh_this_block = 0; // If this block is labeled for refresh, check if we should reset the // segment_id. if (cpi->sf.use_nonrd_pick_mode && cyclic_refresh_segment_id_boosted(mi->segment_id)) { mi->segment_id = refresh_this_block; // Reset segment_id if it will be skipped. if (skip) mi->segment_id = CR_SEGMENT_ID_BASE; } // Update the cyclic refresh map, to be used for setting segmentation map // for the next frame. If the block will be refreshed this frame, mark it // as clean. The magnitude of the -ve influences how long before we consider // it for refresh again. if (cyclic_refresh_segment_id_boosted(mi->segment_id)) { new_map_value = -cr->time_for_refresh; } else if (refresh_this_block) { // Else if it is accepted as candidate for refresh, and has not already // been refreshed (marked as 1) then mark it as a candidate for cleanup // for future time (marked as 0), otherwise don't update it. if (cr->map[block_index] == 1) new_map_value = 0; } else { // Leave it marked as block that is not candidate for refresh. new_map_value = 1; } // Update entries in the cyclic refresh map with new_map_value, and // copy mbmi->segment_id into global segmentation map. for (y = 0; y < ymis; y++) for (x = 0; x < xmis; x++) { int map_offset = block_index + y * cm->mi_cols + x; cr->map[map_offset] = new_map_value; cpi->segmentation_map[map_offset] = mi->segment_id; } } void vp9_cyclic_refresh_update_sb_postencode(VP9_COMP *const cpi, const MODE_INFO *const mi, int mi_row, int mi_col, BLOCK_SIZE bsize) { const VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; const int bw = num_8x8_blocks_wide_lookup[bsize]; const int bh = num_8x8_blocks_high_lookup[bsize]; const int xmis = VPXMIN(cm->mi_cols - mi_col, bw); const int ymis = VPXMIN(cm->mi_rows - mi_row, bh); const int block_index = mi_row * cm->mi_cols + mi_col; int x, y; for (y = 0; y < ymis; y++) for (x = 0; x < xmis; x++) { int map_offset = block_index + y * cm->mi_cols + x; // Inter skip blocks were clearly not coded at the current qindex, so // don't update the map for them. For cases where motion is non-zero or // the reference frame isn't the previous frame, the previous value in // the map for this spatial location is not entirely correct. if ((!is_inter_block(mi) || !mi->skip) && mi->segment_id <= CR_SEGMENT_ID_BOOST2) { cr->last_coded_q_map[map_offset] = clamp(cm->base_qindex + cr->qindex_delta[mi->segment_id], 0, MAXQ); } else if (is_inter_block(mi) && mi->skip && mi->segment_id <= CR_SEGMENT_ID_BOOST2) { cr->last_coded_q_map[map_offset] = VPXMIN( clamp(cm->base_qindex + cr->qindex_delta[mi->segment_id], 0, MAXQ), cr->last_coded_q_map[map_offset]); } } } // From the just encoded frame: update the actual number of blocks that were // applied the segment delta q, and the amount of low motion in the frame. // Also check conditions for forcing golden update, or preventing golden // update if the period is up. void vp9_cyclic_refresh_postencode(VP9_COMP *const cpi) { VP9_COMMON *const cm = &cpi->common; MODE_INFO **mi = cm->mi_grid_visible; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; RATE_CONTROL *const rc = &cpi->rc; unsigned char *const seg_map = cpi->segmentation_map; double fraction_low = 0.0; int force_gf_refresh = 0; int low_content_frame = 0; int mi_row, mi_col; cr->actual_num_seg1_blocks = 0; cr->actual_num_seg2_blocks = 0; for (mi_row = 0; mi_row < cm->mi_rows; mi_row++) { for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) { MV mv = mi[0]->mv[0].as_mv; int map_index = mi_row * cm->mi_cols + mi_col; if (cyclic_refresh_segment_id(seg_map[map_index]) == CR_SEGMENT_ID_BOOST1) cr->actual_num_seg1_blocks++; else if (cyclic_refresh_segment_id(seg_map[map_index]) == CR_SEGMENT_ID_BOOST2) cr->actual_num_seg2_blocks++; // Accumulate low_content_frame. if (is_inter_block(mi[0]) && abs(mv.row) < 16 && abs(mv.col) < 16) low_content_frame++; mi++; } mi += 8; } // Check for golden frame update: only for non-SVC and non-golden boost. if (!cpi->use_svc && cpi->ext_refresh_frame_flags_pending == 0 && !cpi->oxcf.gf_cbr_boost_pct) { // Force this frame as a golden update frame if this frame changes the // resolution (resize_pending != 0). if (cpi->resize_pending != 0) { vp9_cyclic_refresh_set_golden_update(cpi); rc->frames_till_gf_update_due = rc->baseline_gf_interval; if (rc->frames_till_gf_update_due > rc->frames_to_key) rc->frames_till_gf_update_due = rc->frames_to_key; cpi->refresh_golden_frame = 1; force_gf_refresh = 1; } // Update average of low content/motion in the frame. fraction_low = (double)low_content_frame / (cm->mi_rows * cm->mi_cols); cr->low_content_avg = (fraction_low + 3 * cr->low_content_avg) / 4; if (!force_gf_refresh && cpi->refresh_golden_frame == 1 && rc->frames_since_key > rc->frames_since_golden + 1) { // Don't update golden reference if the amount of low_content for the // current encoded frame is small, or if the recursive average of the // low_content over the update interval window falls below threshold. if (fraction_low < 0.65 || cr->low_content_avg < 0.6) { cpi->refresh_golden_frame = 0; } // Reset for next internal. cr->low_content_avg = fraction_low; } } } // Set golden frame update interval, for non-svc 1 pass CBR mode. void vp9_cyclic_refresh_set_golden_update(VP9_COMP *const cpi) { RATE_CONTROL *const rc = &cpi->rc; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; // Set minimum gf_interval for GF update to a multiple of the refresh period, // with some max limit. Depending on past encoding stats, GF flag may be // reset and update may not occur until next baseline_gf_interval. if (cr->percent_refresh > 0) rc->baseline_gf_interval = VPXMIN(4 * (100 / cr->percent_refresh), 40); else rc->baseline_gf_interval = 40; if (cpi->oxcf.rc_mode == VPX_VBR) rc->baseline_gf_interval = 20; if (rc->avg_frame_low_motion < 50 && rc->frames_since_key > 40) rc->baseline_gf_interval = 10; } static int is_superblock_flat_static(VP9_COMP *const cpi, int sb_row_index, int sb_col_index) { unsigned int source_variance; const uint8_t *src_y = cpi->Source->y_buffer; const int ystride = cpi->Source->y_stride; unsigned int sse; const BLOCK_SIZE bsize = BLOCK_64X64; src_y += (sb_row_index << 6) * ystride + (sb_col_index << 6); source_variance = cpi->fn_ptr[bsize].vf(src_y, ystride, VP9_VAR_OFFS, 0, &sse); if (source_variance == 0) { uint64_t block_sad; const uint8_t *last_src_y = cpi->Last_Source->y_buffer; const int last_ystride = cpi->Last_Source->y_stride; last_src_y += (sb_row_index << 6) * ystride + (sb_col_index << 6); block_sad = cpi->fn_ptr[bsize].sdf(src_y, ystride, last_src_y, last_ystride); if (block_sad == 0) return 1; } return 0; } // Update the segmentation map, and related quantities: cyclic refresh map, // refresh sb_index, and target number of blocks to be refreshed. // The map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or to // 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock. // Blocks labeled as BOOST1 may later get set to BOOST2 (during the // encoding of the superblock). static void cyclic_refresh_update_map(VP9_COMP *const cpi) { VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; unsigned char *const seg_map = cpi->segmentation_map; int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame; int xmis, ymis, x, y; int consec_zero_mv_thresh = 0; int qindex_thresh = 0; int count_sel = 0; int count_tot = 0; memset(seg_map, CR_SEGMENT_ID_BASE, cm->mi_rows * cm->mi_cols); sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE; sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE; sbs_in_frame = sb_cols * sb_rows; // Number of target blocks to get the q delta (segment 1). block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100; // Set the segmentation map: cycle through the superblocks, starting at // cr->mb_index, and stopping when either block_count blocks have been found // to be refreshed, or we have passed through whole frame. assert(cr->sb_index < sbs_in_frame); i = cr->sb_index; cr->target_num_seg_blocks = 0; if (cpi->oxcf.content != VP9E_CONTENT_SCREEN) { consec_zero_mv_thresh = 100; } qindex_thresh = cpi->oxcf.content == VP9E_CONTENT_SCREEN ? vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST2, cm->base_qindex) : vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST1, cm->base_qindex); // More aggressive settings for noisy content. if (cpi->noise_estimate.enabled && cpi->noise_estimate.level >= kMedium) { consec_zero_mv_thresh = 60; qindex_thresh = VPXMAX(vp9_get_qindex(&cm->seg, CR_SEGMENT_ID_BOOST1, cm->base_qindex), cm->base_qindex); } do { int sum_map = 0; int consec_zero_mv_thresh_block = consec_zero_mv_thresh; // Get the mi_row/mi_col corresponding to superblock index i. int sb_row_index = (i / sb_cols); int sb_col_index = i - sb_row_index * sb_cols; int mi_row = sb_row_index * MI_BLOCK_SIZE; int mi_col = sb_col_index * MI_BLOCK_SIZE; int flat_static_blocks = 0; int compute_content = 1; assert(mi_row >= 0 && mi_row < cm->mi_rows); assert(mi_col >= 0 && mi_col < cm->mi_cols); #if CONFIG_VP9_HIGHBITDEPTH if (cpi->common.use_highbitdepth) compute_content = 0; #endif if (cpi->Last_Source == NULL || cpi->Last_Source->y_width != cpi->Source->y_width || cpi->Last_Source->y_height != cpi->Source->y_height) compute_content = 0; bl_index = mi_row * cm->mi_cols + mi_col; // Loop through all 8x8 blocks in superblock and update map. xmis = VPXMIN(cm->mi_cols - mi_col, num_8x8_blocks_wide_lookup[BLOCK_64X64]); ymis = VPXMIN(cm->mi_rows - mi_row, num_8x8_blocks_high_lookup[BLOCK_64X64]); if (cpi->noise_estimate.enabled && cpi->noise_estimate.level >= kMedium && (xmis <= 2 || ymis <= 2)) consec_zero_mv_thresh_block = 4; for (y = 0; y < ymis; y++) { for (x = 0; x < xmis; x++) { const int bl_index2 = bl_index + y * cm->mi_cols + x; // If the block is as a candidate for clean up then mark it // for possible boost/refresh (segment 1). The segment id may get // reset to 0 later depending on the coding mode. if (cr->map[bl_index2] == 0) { count_tot++; if (cr->last_coded_q_map[bl_index2] > qindex_thresh || cpi->consec_zero_mv[bl_index2] < consec_zero_mv_thresh_block) { sum_map++; count_sel++; } } else if (cr->map[bl_index2] < 0) { cr->map[bl_index2]++; } } } // Enforce constant segment over superblock. // If segment is at least half of superblock, set to 1. if (sum_map >= xmis * ymis / 2) { // This superblock is a candidate for refresh: // compute spatial variance and exclude blocks that are spatially flat // and stationary. Note: this is currently only done for screne content // mode. if (compute_content && cr->skip_flat_static_blocks) flat_static_blocks = is_superblock_flat_static(cpi, sb_row_index, sb_col_index); if (!flat_static_blocks) { // Label this superblock as segment 1. for (y = 0; y < ymis; y++) for (x = 0; x < xmis; x++) { seg_map[bl_index + y * cm->mi_cols + x] = CR_SEGMENT_ID_BOOST1; } cr->target_num_seg_blocks += xmis * ymis; } } i++; if (i == sbs_in_frame) { i = 0; } } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index); cr->sb_index = i; cr->reduce_refresh = 0; if (cpi->oxcf.content != VP9E_CONTENT_SCREEN) if (count_sel<(3 * count_tot)>> 2) cr->reduce_refresh = 1; } // Set cyclic refresh parameters. void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) { const RATE_CONTROL *const rc = &cpi->rc; const VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; int num8x8bl = cm->MBs << 2; int target_refresh = 0; double weight_segment_target = 0; double weight_segment = 0; int thresh_low_motion = 20; int qp_thresh = VPXMIN((cpi->oxcf.content == VP9E_CONTENT_SCREEN) ? 35 : 20, rc->best_quality << 1); int qp_max_thresh = 117 * MAXQ >> 7; cr->apply_cyclic_refresh = 1; if (frame_is_intra_only(cm) || cpi->svc.temporal_layer_id > 0 || is_lossless_requested(&cpi->oxcf) || rc->avg_frame_qindex[INTER_FRAME] < qp_thresh || (cpi->use_svc && cpi->svc.layer_context[cpi->svc.temporal_layer_id].is_key_frame) || (!cpi->use_svc && rc->avg_frame_low_motion < thresh_low_motion && rc->frames_since_key > 40) || (!cpi->use_svc && rc->avg_frame_qindex[INTER_FRAME] > qp_max_thresh && rc->frames_since_key > 20)) { cr->apply_cyclic_refresh = 0; return; } cr->percent_refresh = 10; if (cr->reduce_refresh) cr->percent_refresh = 5; cr->max_qdelta_perc = 60; cr->time_for_refresh = 0; cr->motion_thresh = 32; cr->rate_boost_fac = 15; // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4) // periods of the refresh cycle, after a key frame. // Account for larger interval on base layer for temporal layers. if (cr->percent_refresh > 0 && rc->frames_since_key < (4 * cpi->svc.number_temporal_layers) * (100 / cr->percent_refresh)) { cr->rate_ratio_qdelta = 3.0; } else { cr->rate_ratio_qdelta = 2.0; if (cpi->noise_estimate.enabled && cpi->noise_estimate.level >= kMedium) { // Reduce the delta-qp if the estimated source noise is above threshold. cr->rate_ratio_qdelta = 1.7; cr->rate_boost_fac = 13; } } // For screen-content: keep rate_ratio_qdelta to 2.0 (segment#1 boost) and // percent_refresh (refresh rate) to 10. But reduce rate boost for segment#2 // (rate_boost_fac = 10 disables segment#2). if (cpi->oxcf.content == VP9E_CONTENT_SCREEN) { // Only enable feature of skipping flat_static blocks for top layer // under screen content mode. if (cpi->svc.spatial_layer_id == cpi->svc.number_spatial_layers - 1) cr->skip_flat_static_blocks = 1; cr->percent_refresh = (cr->skip_flat_static_blocks) ? 5 : 10; // Increase the amount of refresh on scene change that is encoded at max Q, // increase for a few cycles of the refresh period (~100 / percent_refresh). if (cr->counter_encode_maxq_scene_change < 30) cr->percent_refresh = (cr->skip_flat_static_blocks) ? 10 : 15; cr->rate_ratio_qdelta = 2.0; cr->rate_boost_fac = 10; } // Adjust some parameters for low resolutions. if (cm->width * cm->height <= 352 * 288) { if (rc->avg_frame_bandwidth < 3000) { cr->motion_thresh = 64; cr->rate_boost_fac = 13; } else { cr->max_qdelta_perc = 70; cr->rate_ratio_qdelta = VPXMAX(cr->rate_ratio_qdelta, 2.5); } } if (cpi->oxcf.rc_mode == VPX_VBR) { // To be adjusted for VBR mode, e.g., based on gf period and boost. // For now use smaller qp-delta (than CBR), no second boosted seg, and // turn-off (no refresh) on golden refresh (since it's already boosted). cr->percent_refresh = 10; cr->rate_ratio_qdelta = 1.5; cr->rate_boost_fac = 10; if (cpi->refresh_golden_frame == 1) { cr->percent_refresh = 0; cr->rate_ratio_qdelta = 1.0; } } // Weight for segment prior to encoding: take the average of the target // number for the frame to be encoded and the actual from the previous frame. // Use the target if its less. To be used for setting the base qp for the // frame in vp9_rc_regulate_q. target_refresh = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100; weight_segment_target = (double)(target_refresh) / num8x8bl; weight_segment = (double)((target_refresh + cr->actual_num_seg1_blocks + cr->actual_num_seg2_blocks) >> 1) / num8x8bl; if (weight_segment_target < 7 * weight_segment / 8) weight_segment = weight_segment_target; // For screen-content: don't include target for the weight segment, // since for all flat areas the segment is reset, so its more accurate // to just use the previous actual number of seg blocks for the weight. if (cpi->oxcf.content == VP9E_CONTENT_SCREEN) weight_segment = (double)(cr->actual_num_seg1_blocks + cr->actual_num_seg2_blocks) / num8x8bl; cr->weight_segment = weight_segment; } // Setup cyclic background refresh: set delta q and segmentation map. void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) { VP9_COMMON *const cm = &cpi->common; const RATE_CONTROL *const rc = &cpi->rc; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; struct segmentation *const seg = &cm->seg; int scene_change_detected = cpi->rc.high_source_sad || (cpi->use_svc && cpi->svc.high_source_sad_superframe); if (cm->current_video_frame == 0) cr->low_content_avg = 0.0; // Reset if resoluton change has occurred. if (cpi->resize_pending != 0) vp9_cyclic_refresh_reset_resize(cpi); if (!cr->apply_cyclic_refresh || (cpi->force_update_segmentation) || scene_change_detected) { // Set segmentation map to 0 and disable. unsigned char *const seg_map = cpi->segmentation_map; memset(seg_map, 0, cm->mi_rows * cm->mi_cols); vp9_disable_segmentation(&cm->seg); if (cm->frame_type == KEY_FRAME || scene_change_detected) { memset(cr->last_coded_q_map, MAXQ, cm->mi_rows * cm->mi_cols * sizeof(*cr->last_coded_q_map)); cr->sb_index = 0; cr->reduce_refresh = 0; cr->counter_encode_maxq_scene_change = 0; } return; } else { int qindex_delta = 0; int qindex2; const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth); cr->counter_encode_maxq_scene_change++; vpx_clear_system_state(); // Set rate threshold to some multiple (set to 2 for now) of the target // rate (target is given by sb64_target_rate and scaled by 256). cr->thresh_rate_sb = ((int64_t)(rc->sb64_target_rate) << 8) << 2; // Distortion threshold, quadratic in Q, scale factor to be adjusted. // q will not exceed 457, so (q * q) is within 32bit; see: // vp9_convert_qindex_to_q(), vp9_ac_quant(), ac_qlookup*[]. cr->thresh_dist_sb = ((int64_t)(q * q)) << 2; // Set up segmentation. // Clear down the segment map. vp9_enable_segmentation(&cm->seg); vp9_clearall_segfeatures(seg); // Select delta coding method. seg->abs_delta = SEGMENT_DELTADATA; // Note: setting temporal_update has no effect, as the seg-map coding method // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(), // based on the coding cost of each method. For error_resilient mode on the // last_frame_seg_map is set to 0, so if temporal coding is used, it is // relative to 0 previous map. // seg->temporal_update = 0; // Segment BASE "Q" feature is disabled so it defaults to the baseline Q. vp9_disable_segfeature(seg, CR_SEGMENT_ID_BASE, SEG_LVL_ALT_Q); // Use segment BOOST1 for in-frame Q adjustment. vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q); // Use segment BOOST2 for more aggressive in-frame Q adjustment. vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q); // Set the q delta for segment BOOST1. qindex_delta = compute_deltaq(cpi, cm->base_qindex, cr->rate_ratio_qdelta); cr->qindex_delta[1] = qindex_delta; // Compute rd-mult for segment BOOST1. qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ); cr->rdmult = vp9_compute_rd_mult(cpi, qindex2); vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q, qindex_delta); // Set a more aggressive (higher) q delta for segment BOOST2. qindex_delta = compute_deltaq( cpi, cm->base_qindex, VPXMIN(CR_MAX_RATE_TARGET_RATIO, 0.1 * cr->rate_boost_fac * cr->rate_ratio_qdelta)); cr->qindex_delta[2] = qindex_delta; vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q, qindex_delta); // Update the segmentation and refresh map. cyclic_refresh_update_map(cpi); } } int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) { return cr->rdmult; } void vp9_cyclic_refresh_reset_resize(VP9_COMP *const cpi) { const VP9_COMMON *const cm = &cpi->common; CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; memset(cr->map, 0, cm->mi_rows * cm->mi_cols); memset(cr->last_coded_q_map, MAXQ, cm->mi_rows * cm->mi_cols * sizeof(*cr->last_coded_q_map)); cr->sb_index = 0; cpi->refresh_golden_frame = 1; cpi->refresh_alt_ref_frame = 1; cr->counter_encode_maxq_scene_change = 0; } void vp9_cyclic_refresh_limit_q(const VP9_COMP *cpi, int *q) { CYCLIC_REFRESH *const cr = cpi->cyclic_refresh; // For now apply hard limit to frame-level decrease in q, if the cyclic // refresh is active (percent_refresh > 0). if (cr->percent_refresh > 0 && cpi->rc.q_1_frame - *q > 8) { *q = cpi->rc.q_1_frame - 8; } }
96408.c
#include "kernel/types.h" #include "kernel/stat.h" #include "user/user.h" /* Tips: 1. //!Use pipe to create a pipe. 2. //!Use fork to create a child. 3. Use read to read from the pipe, and write to write to the pipe. 4. Use getpid to find the process ID of the calling process. 5. Add the program to UPROGS in Makefile. 6. User programs on xv6 have a limited set of library functions available to them. You can see the list in user/user.h; the source (other than for system calls) is in user/ulib.c, user/printf.c, and user/umalloc.c. */ /* output 4: received ping 说明子进程先读 3: received pong */ int main(int argc, char const *argv[]) { int pip_ping[2]; int pip_pong[2]; int pip[2]; int pid; /* TODO:能否用一个管道实现?不行 */ /* 用两个管道实现 */ pipe(pip_ping); /* 为我们创建了一个管道 */ //!Use pipe to create a pipe. pipe(pip_pong); pipe(pip); char buf[10]; memset(buf, 0, 10); if ((pid = fork()) == 0) { /* 子进程返回0 */ //!Use fork to create a child close(pip_ping[1]); read(pip_ping[0], buf, 10); printf("%d: received %s\n", getpid(), buf); close(pip_pong[0]); write(pip_pong[1], "pong", strlen("pong")); close(pip_ping[0]); close(pip_pong[1]); } else { /* 父进程返回非0 */ close(pip_ping[0]); write(pip_ping[1], "ping", strlen("ping")); close(pip_pong[1]); read(pip_pong[0], buf, 10); printf("%d: received %s\n", getpid(), buf); close(pip_ping[1]); close(pip_pong[0]); } /* 一个管道只能实现单方面传输 */ // if ((pid = fork()) == 0) { /* 子进程返回0 */ //!Use fork to create a child // memset(buf, 0, 10); // close(pip[1]); /* 重新打开如何? */ // read(pip[0], buf, 10); // close(pip[0]); // write(pip[1], "pong", strlen("pong")); // printf("%d: received %s\n", getpid(), buf); // } // else { // memset(buf, 0, 10); // close(pip[0]); // write(pip[1], "ping", strlen("ping")); // close(pip[1]); // read(pip[0], buf, 10); // printf("%d: received %s\n", getpid(), buf); // } exit(0); /* 一定要调用exit */ }
874000.c
//------------------------------------------------------------------------------ // GB_AxB__any_ne_int32.c: matrix multiply for a single semiring //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated1/ or Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB_dev.h" #ifndef GBCUDA_DEV #include "GB.h" #include "GB_control.h" #include "GB_bracket.h" #include "GB_sort.h" #include "GB_atomics.h" #include "GB_AxB_saxpy.h" #if 1 #include "GB_AxB__include2.h" #else #include "GB_AxB__include1.h" #endif #include "GB_unused.h" #include "GB_bitmap_assign_methods.h" #include "GB_ek_slice_search.c" // This C=A*B semiring is defined by the following types and operators: // A'*B (dot2): GB (_Adot2B__any_ne_int32) // A'*B (dot3): GB (_Adot3B__any_ne_int32) // C+=A'*B (dot4): GB (_Adot4B__(none)) // A*B (saxpy bitmap): GB (_AsaxbitB__any_ne_int32) // A*B (saxpy3): GB (_Asaxpy3B__any_ne_int32) // no mask: GB (_Asaxpy3B_noM__any_ne_int32) // mask M: GB (_Asaxpy3B_M__any_ne_int32) // mask !M: GB (_Asaxpy3B_notM__any_ne_int32) // A*B (saxpy4): GB (_Asaxpy4B__(none)) // A*B (saxpy5): GB (_Asaxpy5B__(none)) // C type: bool // A type: int32_t // A pattern? 0 // B type: int32_t // B pattern? 0 // Multiply: z = (x != y) // Add: cij = t // 'any' monoid? 1 // atomic? 1 // OpenMP atomic? 0 // identity: false // terminal? 1 // terminal condition: break ; // MultAdd: z = (x != y) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ bool #define GB_ASIZE \ sizeof (int32_t) #define GB_BSIZE \ sizeof (int32_t) #define GB_CSIZE \ sizeof (bool) // # of bits in the type of C, for AVX2 and AVX512F #define GB_CNBITS \ 8 // true for int64, uint64, float, double, float complex, and double complex #define GB_CTYPE_IGNORE_OVERFLOW \ 0 // aik = Ax [pA] #define GB_GETA(aik,Ax,pA,A_iso) \ int32_t aik = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bkj = Bx [pB] #define GB_GETB(bkj,Bx,pB,B_iso) \ int32_t bkj = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // Gx [pG] = Ax [pA] #define GB_LOADA(Gx,pG,Ax,pA,A_iso) \ Gx [pG] = GBX (Ax, pA, A_iso) // Gx [pG] = Bx [pB] #define GB_LOADB(Gx,pG,Bx,pB,B_iso) \ Gx [pG] = GBX (Bx, pB, B_iso) #define GB_CX(p) \ Cx [p] // multiply operator #define GB_MULT(z, x, y, i, k, j) \ z = (x != y) // cast from a real scalar (or 2, if C is complex) to the type of C #define GB_CTYPE_CAST(x,y) \ ((bool) x) // cast from a real scalar (or 2, if A is complex) to the type of A #define GB_ATYPE_CAST(x,y) \ ((int32_t) x) // multiply-add #define GB_MULTADD(z, x, y, i, k, j) \ z = (x != y) // monoid identity value #define GB_IDENTITY \ false // 1 if the identity value can be assigned via memset, with all bytes the same #define GB_HAS_IDENTITY_BYTE \ 0 // identity byte, for memset #define GB_IDENTITY_BYTE \ (none) // true if the monoid has a terminal value #define GB_MONOID_IS_TERMINAL \ 1 // break if cij reaches the terminal value (dot product only) #define GB_DOT_TERMINAL(cij) \ break ; // simd pragma for dot-product loop vectorization #define GB_PRAGMA_SIMD_DOT(cij) \ ; // simd pragma for other loop vectorization #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // 1 for the PLUS_PAIR_(real) semirings, not for the complex case #define GB_IS_PLUS_PAIR_REAL_SEMIRING \ 0 // 1 if the semiring is accelerated with AVX2 or AVX512f #define GB_SEMIRING_HAS_AVX_IMPLEMENTATION \ 0 // declare the cij scalar (initialize cij to zero for PLUS_PAIR) #define GB_CIJ_DECLARE(cij) \ bool cij // Cx [pC] = cij #define GB_PUTC(cij,p) \ Cx [p] = cij // Cx [p] = t #define GB_CIJ_WRITE(p,t) \ Cx [p] = t // C(i,j) += t #define GB_CIJ_UPDATE(p,t) \ Cx [p] = t // x + y #define GB_ADD_FUNCTION(x,y) \ y // bit pattern for bool, 8-bit, 16-bit, and 32-bit integers #define GB_CTYPE_BITS \ 0x1L // 1 if monoid update can skipped entirely (the ANY monoid) #define GB_IS_ANY_MONOID \ 1 // 1 if monoid update is EQ #define GB_IS_EQ_MONOID \ 0 // 1 if monoid update can be done atomically, 0 otherwise #define GB_HAS_ATOMIC \ 1 // 1 if monoid update can be done with an OpenMP atomic update, 0 otherwise #if GB_COMPILER_MSC /* MS Visual Studio only has OpenMP 2.0, with fewer atomics */ #define GB_HAS_OMP_ATOMIC \ 0 #else #define GB_HAS_OMP_ATOMIC \ 0 #endif // 1 for the ANY_PAIR_ISO semiring #define GB_IS_ANY_PAIR_SEMIRING \ 0 // 1 if PAIR is the multiply operator #define GB_IS_PAIR_MULTIPLIER \ 0 // 1 if monoid is PLUS_FC32 #define GB_IS_PLUS_FC32_MONOID \ 0 // 1 if monoid is PLUS_FC64 #define GB_IS_PLUS_FC64_MONOID \ 0 // 1 if monoid is ANY_FC32 #define GB_IS_ANY_FC32_MONOID \ 0 // 1 if monoid is ANY_FC64 #define GB_IS_ANY_FC64_MONOID \ 0 // 1 if monoid is MIN for signed or unsigned integers #define GB_IS_IMIN_MONOID \ 0 // 1 if monoid is MAX for signed or unsigned integers #define GB_IS_IMAX_MONOID \ 0 // 1 if monoid is MIN for float or double #define GB_IS_FMIN_MONOID \ 0 // 1 if monoid is MAX for float or double #define GB_IS_FMAX_MONOID \ 0 // 1 for the FIRSTI or FIRSTI1 multiply operator #define GB_IS_FIRSTI_MULTIPLIER \ 0 // 1 for the FIRSTJ or FIRSTJ1 multiply operator #define GB_IS_FIRSTJ_MULTIPLIER \ 0 // 1 for the SECONDJ or SECONDJ1 multiply operator #define GB_IS_SECONDJ_MULTIPLIER \ 0 // 1 for the FIRSTI1, FIRSTJ1, SECONDI1, or SECONDJ1 multiply operators #define GB_OFFSET \ 0 // atomic compare-exchange #define GB_ATOMIC_COMPARE_EXCHANGE(target, expected, desired) \ GB_ATOMIC_COMPARE_EXCHANGE_8 (target, expected, desired) // Hx [i] = t #define GB_HX_WRITE(i,t) \ Hx [i] = t // Cx [p] = Hx [i] #define GB_CIJ_GATHER(p,i) \ Cx [p] = Hx [i] // Cx [p] += Hx [i] #define GB_CIJ_GATHER_UPDATE(p,i) \ Cx [p] = Hx [i] // Hx [i] += t #define GB_HX_UPDATE(i,t) \ Hx [i] = t // memcpy (&(Cx [p]), &(Hx [i]), len) #define GB_CIJ_MEMCPY(p,i,len) \ memcpy (Cx +(p), Hx +(i), (len) * sizeof(bool)); // disable this semiring and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ANY || GxB_NO_NE || GxB_NO_INT32 || GxB_NO_ANY_BOOL || GxB_NO_NE_INT32 || GxB_NO_ANY_NE_INT32) //------------------------------------------------------------------------------ // GB_Adot2B: C=A'*B, C<M>=A'*B, or C<!M>=A'*B: dot product method, C is bitmap //------------------------------------------------------------------------------ // if A_not_transposed is true, then C=A*B is computed where A is bitmap or full GrB_Info GB (_Adot2B__any_ne_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct, const bool A_not_transposed, const GrB_Matrix A, int64_t *restrict A_slice, const GrB_Matrix B, int64_t *restrict B_slice, int nthreads, int naslice, int nbslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot2_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // GB_Adot3B: C<M>=A'*B: masked dot product, C is sparse or hyper //------------------------------------------------------------------------------ GrB_Info GB (_Adot3B__any_ne_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const GB_task_struct *restrict TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot3_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // GB_Adot4B: C+=A'*B: dense dot product (not used for ANY_PAIR_ISO) //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_Adot4B__(none)) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict A_slice, int naslice, const GrB_Matrix B, int64_t *restrict B_slice, int nbslice, const int nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_dot4_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // GB_AsaxbitB: C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method, C is bitmap/full //------------------------------------------------------------------------------ #include "GB_AxB_saxpy3_template.h" GrB_Info GB (_AsaxbitB__any_ne_int32) ( GrB_Matrix C, // bitmap or full const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_AxB_saxpy_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // GB_Asaxpy4B: C += A*B when C is full //------------------------------------------------------------------------------ #if 0 GrB_Info GB (_Asaxpy4B__(none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int ntasks, const int nthreads, const int nfine_tasks_per_vector, const bool use_coarse_tasks, const bool use_atomics, const int64_t *A_slice, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_saxpy4_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // GB_Asaxpy5B: C += A*B when C is full, A is bitmap/full, B is sparse/hyper //------------------------------------------------------------------------------ #if 0 #if GB_DISABLE #elif ( !GB_A_IS_PATTERN ) //---------------------------------------------------------------------- // saxpy5 method with vectors of length 8 for double, 16 for single //---------------------------------------------------------------------- // AVX512F: vector registers are 512 bits, or 64 bytes, which can hold // 16 floats or 8 doubles. #define GB_V16_512 (16 * GB_CNBITS <= 512) #define GB_V8_512 ( 8 * GB_CNBITS <= 512) #define GB_V4_512 ( 4 * GB_CNBITS <= 512) #define GB_V16 GB_V16_512 #define GB_V8 GB_V8_512 #define GB_V4 GB_V4_512 #if GB_SEMIRING_HAS_AVX_IMPLEMENTATION && GB_COMPILER_SUPPORTS_AVX512F \ && GB_V4_512 GB_TARGET_AVX512F static inline void GB_AxB_saxpy5_unrolled_avx512f ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int ntasks, const int nthreads, const int64_t *B_slice, GB_Context Context ) { #include "GB_AxB_saxpy5_unrolled.c" } #endif //---------------------------------------------------------------------- // saxpy5 method with vectors of length 4 for double, 8 for single //---------------------------------------------------------------------- // AVX2: vector registers are 256 bits, or 32 bytes, which can hold // 8 floats or 4 doubles. #define GB_V16_256 (16 * GB_CNBITS <= 256) #define GB_V8_256 ( 8 * GB_CNBITS <= 256) #define GB_V4_256 ( 4 * GB_CNBITS <= 256) #undef GB_V16 #undef GB_V8 #undef GB_V4 #define GB_V16 GB_V16_256 #define GB_V8 GB_V8_256 #define GB_V4 GB_V4_256 #if GB_SEMIRING_HAS_AVX_IMPLEMENTATION && GB_COMPILER_SUPPORTS_AVX2 \ && GB_V4_256 GB_TARGET_AVX2 static inline void GB_AxB_saxpy5_unrolled_avx2 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int ntasks, const int nthreads, const int64_t *B_slice, GB_Context Context ) { #include "GB_AxB_saxpy5_unrolled.c" } #endif //---------------------------------------------------------------------- // saxpy5 method unrolled, with no vectors //---------------------------------------------------------------------- #undef GB_V16 #undef GB_V8 #undef GB_V4 #define GB_V16 0 #define GB_V8 0 #define GB_V4 0 static inline void GB_AxB_saxpy5_unrolled_vanilla ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int ntasks, const int nthreads, const int64_t *B_slice, GB_Context Context ) { #include "GB_AxB_saxpy5_unrolled.c" } #endif GrB_Info GB (_Asaxpy5B__(none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int ntasks, const int nthreads, const int64_t *B_slice, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_AxB_saxpy5_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // GB_Asaxpy3B: C=A*B, C<M>=A*B, C<!M>=A*B: saxpy method (Gustavson + Hash) //------------------------------------------------------------------------------ GrB_Info GB (_Asaxpy3B__any_ne_int32) ( GrB_Matrix C, // C<any M>=A*B, C sparse or hypersparse const GrB_Matrix M, const bool Mask_comp, const bool Mask_struct, const bool M_in_place, const GrB_Matrix A, const GrB_Matrix B, GB_saxpy3task_struct *restrict SaxpyTasks, const int ntasks, const int nfine, const int nthreads, const int do_sort, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else ASSERT (GB_IS_SPARSE (C) || GB_IS_HYPERSPARSE (C)) ; if (M == NULL) { // C = A*B, no mask return (GB (_Asaxpy3B_noM__any_ne_int32) (C, A, B, SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ; } else if (!Mask_comp) { // C<M> = A*B return (GB (_Asaxpy3B_M__any_ne_int32) (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ; } else { // C<!M> = A*B return (GB (_Asaxpy3B_notM__any_ne_int32) (C, M, Mask_struct, M_in_place, A, B, SaxpyTasks, ntasks, nfine, nthreads, do_sort, Context)) ; } #endif } //------------------------------------------------------------------------------ // GB_Asaxpy3B_M: C<M>=A*Bi: saxpy method (Gustavson + Hash) //------------------------------------------------------------------------------ #if ( !GB_DISABLE ) GrB_Info GB (_Asaxpy3B_M__any_ne_int32) ( GrB_Matrix C, // C<M>=A*B, C sparse or hypersparse const GrB_Matrix M, const bool Mask_struct, const bool M_in_place, const GrB_Matrix A, const GrB_Matrix B, GB_saxpy3task_struct *restrict SaxpyTasks, const int ntasks, const int nfine, const int nthreads, const int do_sort, GB_Context Context ) { if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B)) { // both A and B are sparse #define GB_META16 #define GB_NO_MASK 0 #define GB_MASK_COMP 0 #define GB_A_IS_SPARSE 1 #define GB_A_IS_HYPER 0 #define GB_A_IS_BITMAP 0 #define GB_A_IS_FULL 0 #define GB_B_IS_SPARSE 1 #define GB_B_IS_HYPER 0 #define GB_B_IS_BITMAP 0 #define GB_B_IS_FULL 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } else { // general case #undef GB_META16 #define GB_NO_MASK 0 #define GB_MASK_COMP 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } return (GrB_SUCCESS) ; } #endif //------------------------------------------------------------------------------ //GB_Asaxpy3B_noM: C=A*B: saxpy method (Gustavson + Hash) //------------------------------------------------------------------------------ #if ( !GB_DISABLE ) GrB_Info GB (_Asaxpy3B_noM__any_ne_int32) ( GrB_Matrix C, // C=A*B, C sparse or hypersparse const GrB_Matrix A, const GrB_Matrix B, GB_saxpy3task_struct *restrict SaxpyTasks, const int ntasks, const int nfine, const int nthreads, const int do_sort, GB_Context Context ) { if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B)) { // both A and B are sparse #define GB_META16 #define GB_NO_MASK 1 #define GB_MASK_COMP 0 #define GB_A_IS_SPARSE 1 #define GB_A_IS_HYPER 0 #define GB_A_IS_BITMAP 0 #define GB_A_IS_FULL 0 #define GB_B_IS_SPARSE 1 #define GB_B_IS_HYPER 0 #define GB_B_IS_BITMAP 0 #define GB_B_IS_FULL 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } else { // general case #undef GB_META16 #define GB_NO_MASK 1 #define GB_MASK_COMP 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } return (GrB_SUCCESS) ; } #endif //------------------------------------------------------------------------------ //GB_Asaxpy3B_notM: C<!M>=A*B: saxpy method (Gustavson + Hash) //------------------------------------------------------------------------------ #if ( !GB_DISABLE ) GrB_Info GB (_Asaxpy3B_notM__any_ne_int32) ( GrB_Matrix C, // C<!M>=A*B, C sparse or hypersparse const GrB_Matrix M, const bool Mask_struct, const bool M_in_place, const GrB_Matrix A, const GrB_Matrix B, GB_saxpy3task_struct *restrict SaxpyTasks, const int ntasks, const int nfine, const int nthreads, const int do_sort, GB_Context Context ) { if (GB_IS_SPARSE (A) && GB_IS_SPARSE (B)) { // both A and B are sparse #define GB_META16 #define GB_NO_MASK 0 #define GB_MASK_COMP 1 #define GB_A_IS_SPARSE 1 #define GB_A_IS_HYPER 0 #define GB_A_IS_BITMAP 0 #define GB_A_IS_FULL 0 #define GB_B_IS_SPARSE 1 #define GB_B_IS_HYPER 0 #define GB_B_IS_BITMAP 0 #define GB_B_IS_FULL 0 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } else { // general case #undef GB_META16 #define GB_NO_MASK 0 #define GB_MASK_COMP 1 #include "GB_meta16_definitions.h" #include "GB_AxB_saxpy3_template.c" } return (GrB_SUCCESS) ; } #endif #endif
853746.c
/*---------------------------------------------------------------------------------------------------------*/ /* */ /* Copyright(c) 2009 Nuvoton Technology Corp. All rights reserved. */ /* */ /*---------------------------------------------------------------------------------------------------------*/ #include <stdio.h> #include "M051Series.h" #include "LCD_Driver.h" #define PLLCON_SETTING SYSCLK_PLLCON_50MHz_XTAL #define PLL_CLOCK 50000000 void GPIOP0P1_IRQHandler(void) { /* Re-enable debounce function */ P1->DBEN |= GPIO_DBEN_ENABLE(3); /* Clear the interrupt */ P1->ISRC = 1 << 3; printf("P1.3 Interrupt!\n"); LCD_Print(3, "P1.3 Interrupt!"); /* Toggle LED */ P20 = P20 ^ 1; } void GPIOP2P3P4_IRQHandler(void) { /* Re-enable debounce function */ P4->DBEN |= GPIO_DBEN_ENABLE(5); /* Clear the interrupt */ P4->ISRC = 1 << 5; printf("P2P3P4 Interrupt!\n"); LCD_Print(3, "P4.5 Interrupt!"); /* Toggle LED */ P20 = P20 ^ 1; } void EINT0_IRQHandler(void) { /* Re-enable debounce function */ P3->DBEN |= GPIO_DBEN_ENABLE(2); P3->ISRC = 1 << 2; /* Toggle LED */ P20 = P20 ^ 1; printf("EINT0 Interrupt!\n"); LCD_Print(3, "EINT0 Interrupt!"); } void EINT1_IRQHandler(void) { /* Re-enable debounce function */ P3->DBEN |= GPIO_DBEN_ENABLE(3); P3->ISRC = 1 << 3; /* Toggle LED */ P20 = P20 ^ 1; printf("EINT1 Interrupt!\n"); LCD_Print(3, "EINT1 Interrupt!"); } void SYS_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init System Clock */ /*---------------------------------------------------------------------------------------------------------*/ /* Unlock protected registers */ SYS_UnlockReg(); /* Enable Internal RC clock */ SYSCLK->PWRCON |= SYSCLK_PWRCON_IRC22M_EN_Msk; /* Waiting for IRC22M clock ready */ SYS_WaitingForClockReady(SYSCLK_CLKSTATUS_IRC22M_STB_Msk); /* Switch HCLK clock source to internal RC */ SYSCLK->CLKSEL0 = SYSCLK_CLKSEL0_HCLK_IRC22M; /* Set PLL to power down mode and PLL_STB bit in CLKSTATUS register will be cleared by hardware.*/ SYSCLK->PLLCON |= SYSCLK_PLLCON_PD_Msk; /* Enable external 12MHz XTAL, 10kHz */ SYSCLK->PWRCON |= SYSCLK_PWRCON_XTL12M_EN_Msk | SYSCLK_PWRCON_IRC10K_EN_Msk; /* Enable PLL and Set PLL frequency */ SYSCLK->PLLCON = PLLCON_SETTING; /* Waiting for clock ready */ SYS_WaitingForClockReady(SYSCLK_CLKSTATUS_PLL_STB_Msk | SYSCLK_CLKSTATUS_XTL12M_STB_Msk); /* Switch HCLK clock source to PLL, STCLK to HCLK/2 */ SYSCLK->CLKSEL0 = SYSCLK_CLKSEL0_STCLK_HCLK_DIV2 | SYSCLK_CLKSEL0_HCLK_PLL; /* Enable IP clock */ SYSCLK->APBCLK = SYSCLK_APBCLK_UART0_EN_Msk | SYSCLK_APBCLK_SPI0_EN_Msk; /* IP clock source */ SYSCLK->CLKSEL1 = SYSCLK_CLKSEL1_UART_PLL; /* Update System Core Clock */ /* User can use SystemCoreClockUpdate() to calculate PllClock, SystemCoreClock and CycylesPerUs automatically. */ //SystemCoreClockUpdate(); PllClock = PLL_CLOCK; // PLL SystemCoreClock = PLL_CLOCK / 1; // HCLK CyclesPerUs = PLL_CLOCK / 1000000; // For SYS_SysTickDelay() /*---------------------------------------------------------------------------------------------------------*/ /* Init I/O Multi-function */ /*---------------------------------------------------------------------------------------------------------*/ /* Set P3 multi-function pins for UART0 RXD and TXD */ SYS->P3_MFP = SYS_MFP_P30_RXD0 | SYS_MFP_P31_TXD0; /* Set P1.4, P1.5, P1.6, P1.7 for SPI0 */ SYS->P1_MFP = SYS_MFP_P14_SPISS0 | SYS_MFP_P15_MOSI_0 | SYS_MFP_P16_MISO_0 | SYS_MFP_P17_SPICLK0; /* Lock protected registers */ SYS_LockReg(); } void UART0_Init(void) { /*---------------------------------------------------------------------------------------------------------*/ /* Init UART */ /*---------------------------------------------------------------------------------------------------------*/ UART0->BAUD = UART_BAUD_MODE2 | UART_BAUD_DIV_MODE2(PLL_CLOCK, 115200); _UART_SET_DATA_FORMAT(UART0, UART_WORD_LEN_8 | UART_PARITY_NONE | UART_STOP_BIT_1); } void GPIO_Init(void) { /* Set p2.0 as output pin */ P2->PMD = GPIO_PMD_PMD0_OUTPUT; /* Set p1.3, p4.5 as Quasi-bidirectional mode */ P1->PMD = GPIO_PMD_PMD3_QUASI; P4->PMD = GPIO_PMD_PMD5_QUASI; /* Set p1.3 as falling edge trigger and enable its interrupt */ GPIO_EnableInt(P1, 3, GPIO_INT_FALLING); NVIC_EnableIRQ(GPIO_P0P1_IRQn); /* Set p4.5 as low level trigger */ GPIO_EnableInt(P4, 5, GPIO_INT_LOW); NVIC_EnableIRQ(GPIO_P2P3P4_IRQn); /* Debounce function control */ GPIO->DBNCECON = GPIO_DBNCECON_ICLK_ON | GPIO_DBNCECON_DBCLKSRC_HCLK | GPIO_DBNCECON_DBCLKSEL_32768; P1->DBEN = GPIO_DBEN_ENABLE(3); P3->DBEN = GPIO_DBEN_ENABLE(2) | GPIO_DBEN_ENABLE(3); P4->DBEN = GPIO_DBEN_ENABLE(5); /* Configure external interrupt */ GPIO_EnableInt(P3, 2, GPIO_INT_FALLING); NVIC_EnableIRQ(EINT0_IRQn); GPIO_EnableInt(P3, 3, GPIO_INT_BOTH_EDGE); NVIC_EnableIRQ(EINT1_IRQn); } /*---------------------------------------------------------------------------------------------------------*/ /* MAIN function */ /*---------------------------------------------------------------------------------------------------------*/ int main(void) { /* Init System, IP clock and multi-function I/O */ SYS_Init(); /* Init UART0 for printf */ UART0_Init(); printf("CPU @ %dHz\n", SystemCoreClock); printf("This sample code uses PWM0, PWM1 to drive LED and uses ADC to control PWM1 duty.\n"); /* Init SPI0 and LCD */ LCD_Init(); LCD_EnableBackLight(); LCD_ClearScreen(); LCD_Print(0, "Welcome! Nuvoton"); LCD_Print(1, "This is INT test"); /*-----------------------------------------------------------------------------------------------------*/ /* GPIO Interrupt Test */ /*-----------------------------------------------------------------------------------------------------*/ printf("P13, P45, P32(INT0) and P33(INT1) are used to test interrupt\n and control LEDs(P20)\n"); /* Init P2.0 (output), P1.3, P4.5 (Quasi-bidirectional) and relative interrupts */ GPIO_Init(); /* Unlock protected registers */ SYS_UnlockReg(); /* Settings for power down (deep sleep) */ SYS_PowerDownInit(); /* Lock protected registers */ SYS_LockReg(); /* Waiting for interrupts */ while (1) { printf("Deep Sleep\n"); LCD_Print(2, "Deep Sleep"); while ((UART0->FSR & UART_FSR_TE_FLAG_Msk) == 0); /* Disable P3.2, P3.3, p1.3, p4.5 debounce to avoid double interrupts when wakeup */ P3->DBEN = 0; P1->DBEN = 0; P4->DBEN = 0; SYS_UnlockReg(); /* Settings for power down (deep sleep) */ /* Prepare to enter power down */ SYS_PowerDownInit(); /* Lock protected registers */ SYS_LockReg(); /* Hold in wakeup state when P3.2 or P1.3 or P4.5 is low. */ while((P32 == 0) || (P13 == 0) || (P45 == 0)); LCD_Print(3, " "); /* Enter power down. Only INT0, INT1 can used to wakeup system */ __WFI(); } }
50580.c
// Copyright 2014 The Go 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 <limits.h> #include <pthread.h> #include <signal.h> #include <string.h> /* for strerror */ #include <sys/param.h> #include <unistd.h> #include <stdlib.h> #include <CoreFoundation/CFBundle.h> #include <CoreFoundation/CFString.h> #include "libcgo.h" #include "libcgo_unix.h" #define magic (0xc476c475c47957UL) // inittls allocates a thread-local storage slot for g. // // It finds the first available slot using pthread_key_create and uses // it as the offset value for runtime.tlsg. static void inittls(void **tlsg, void **tlsbase) { pthread_key_t k; int i, err; err = pthread_key_create(&k, nil); if(err != 0) { fprintf(stderr, "runtime/cgo: pthread_key_create failed: %d\n", err); abort(); } //fprintf(stderr, "runtime/cgo: k = %d, tlsbase = %p\n", (int)k, tlsbase); // debug pthread_setspecific(k, (void*)magic); // The first key should be at 257. for (i=0; i<PTHREAD_KEYS_MAX; i++) { if (*(tlsbase+i) == (void*)magic) { *tlsg = (void*)(i*sizeof(void *)); pthread_setspecific(k, 0); return; } } fprintf(stderr, "runtime/cgo: could not find pthread key.\n"); abort(); } static void *threadentry(void*); static void (*setg_gcc)(void*); void _cgo_sys_thread_start(ThreadStart *ts) { pthread_attr_t attr; sigset_t ign, oset; pthread_t p; size_t size; int err; //fprintf(stderr, "runtime/cgo: _cgo_sys_thread_start: fn=%p, g=%p\n", ts->fn, ts->g); // debug sigfillset(&ign); pthread_sigmask(SIG_SETMASK, &ign, &oset); pthread_attr_init(&attr); size = 0; pthread_attr_getstacksize(&attr, &size); // Leave stacklo=0 and set stackhi=size; mstart will do the rest. ts->g->stackhi = size; err = _cgo_try_pthread_create(&p, &attr, threadentry, ts); pthread_sigmask(SIG_SETMASK, &oset, nil); if (err != 0) { fprintf(stderr, "runtime/cgo: pthread_create failed: %s\n", strerror(err)); abort(); } } extern void crosscall1(void (*fn)(void), void (*setg_gcc)(void*), void *g); static void* threadentry(void *v) { ThreadStart ts; ts = *(ThreadStart*)v; free(v); darwin_arm_init_thread_exception_port(); crosscall1(ts.fn, setg_gcc, (void*)ts.g); return nil; } // init_working_dir sets the current working directory to the app root. // By default darwin/arm processes start in "/". static void init_working_dir() { CFBundleRef bundle = CFBundleGetMainBundle(); if (bundle == NULL) { fprintf(stderr, "runtime/cgo: no main bundle\n"); return; } CFURLRef url_ref = CFBundleCopyResourceURL(bundle, CFSTR("Info"), CFSTR("plist"), NULL); if (url_ref == NULL) { fprintf(stderr, "runtime/cgo: no Info.plist URL\n"); return; } CFStringRef url_str_ref = CFURLGetString(url_ref); char buf[MAXPATHLEN]; Boolean res = CFStringGetCString(url_str_ref, buf, sizeof(buf), kCFStringEncodingUTF8); CFRelease(url_ref); if (!res) { fprintf(stderr, "runtime/cgo: cannot get URL string\n"); return; } // url is of the form "file:///path/to/Info.plist". // strip it down to the working directory "/path/to". int url_len = strlen(buf); if (url_len < sizeof("file://")+sizeof("/Info.plist")) { fprintf(stderr, "runtime/cgo: bad URL: %s\n", buf); return; } buf[url_len-sizeof("/Info.plist")+1] = 0; char *dir = &buf[0] + sizeof("file://")-1; if (chdir(dir) != 0) { fprintf(stderr, "runtime/cgo: chdir(%s) failed\n", dir); } // The test harness in go_darwin_arm_exec passes the relative working directory // in the GoExecWrapperWorkingDirectory property of the app bundle. CFStringRef wd_ref = CFBundleGetValueForInfoDictionaryKey(bundle, CFSTR("GoExecWrapperWorkingDirectory")); if (wd_ref != NULL) { if (!CFStringGetCString(wd_ref, buf, sizeof(buf), kCFStringEncodingUTF8)) { fprintf(stderr, "runtime/cgo: cannot get GoExecWrapperWorkingDirectory string\n"); return; } if (chdir(buf) != 0) { fprintf(stderr, "runtime/cgo: chdir(%s) failed\n", buf); } } } void x_cgo_init(G *g, void (*setg)(void*), void **tlsg, void **tlsbase) { pthread_attr_t attr; size_t size; //fprintf(stderr, "x_cgo_init = %p\n", &x_cgo_init); // aid debugging in presence of ASLR setg_gcc = setg; pthread_attr_init(&attr); pthread_attr_getstacksize(&attr, &size); g->stacklo = (uintptr)&attr - size + 4096; pthread_attr_destroy(&attr); // yes, tlsbase from mrs might not be correctly aligned. inittls(tlsg, (void**)((uintptr)tlsbase & ~7)); darwin_arm_init_mach_exception_handler(); darwin_arm_init_thread_exception_port(); init_working_dir(); }
160354.c
/* Copyright (c) 2015 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "nrf_drv_spi.h" #include "nrf_drv_common.h" #include "nrf_gpio.h" #include "nrf_assert.h" #include "app_util_platform.h" #ifndef NRF52 // Make sure SPIx_USE_EASY_DMA is 0 for nRF51 (if a common // "nrf_drv_config.h" file is provided for nRF51 and nRF52). #undef SPI0_USE_EASY_DMA #define SPI0_USE_EASY_DMA 0 #undef SPI1_USE_EASY_DMA #define SPI1_USE_EASY_DMA 0 #undef SPI2_USE_EASY_DMA #define SPI2_USE_EASY_DMA 0 #endif // This set of macros makes it possible to exclude parts of code when one type // of supported peripherals is not used. #if ((SPI0_ENABLED && SPI0_USE_EASY_DMA) || \ (SPI1_ENABLED && SPI1_USE_EASY_DMA) || \ (SPI2_ENABLED && SPI2_USE_EASY_DMA)) #define SPIM_IN_USE #endif #if ((SPI0_ENABLED && !SPI0_USE_EASY_DMA) || \ (SPI1_ENABLED && !SPI1_USE_EASY_DMA) || \ (SPI2_ENABLED && !SPI2_USE_EASY_DMA)) #define SPI_IN_USE #endif #if defined(SPIM_IN_USE) && defined(SPI_IN_USE) // SPIM and SPI combined #define CODE_FOR_SPIM(code) if (p_instance->use_easy_dma) { code } #define CODE_FOR_SPI(code) else { code } #elif defined(SPIM_IN_USE) && !defined(SPI_IN_USE) // SPIM only #define CODE_FOR_SPIM(code) { code } #define CODE_FOR_SPI(code) #elif !defined(SPIM_IN_USE) && defined(SPI_IN_USE) // SPI only #define CODE_FOR_SPIM(code) #define CODE_FOR_SPI(code) { code } #else #error "Wrong configuration." #endif #ifdef SPIM_IN_USE #ifdef NRF52_PAN_23 #define END_INT_MASK (NRF_SPIM_INT_ENDTX_MASK | NRF_SPIM_INT_ENDRX_MASK) #else #define END_INT_MASK NRF_SPIM_INT_END_MASK #endif #endif // Control block - driver instance local data. typedef struct { nrf_drv_spi_handler_t handler; nrf_drv_spi_evt_t evt; // Keep the struct that is ready for event handler. Less memcpy. nrf_drv_state_t state; volatile bool transfer_in_progress; // [no need for 'volatile' attribute for the following members, as they // are not concurrently used in IRQ handlers and main line code] uint8_t ss_pin; uint8_t orc; uint8_t bytes_transferred; bool tx_done : 1; bool rx_done : 1; } spi_control_block_t; static spi_control_block_t m_cb[SPI_COUNT]; static nrf_drv_spi_config_t const m_default_config[SPI_COUNT] = { #if SPI0_ENABLED NRF_DRV_SPI_DEFAULT_CONFIG(0), #endif #if SPI1_ENABLED NRF_DRV_SPI_DEFAULT_CONFIG(1), #endif #if SPI2_ENABLED NRF_DRV_SPI_DEFAULT_CONFIG(2), #endif }; #if PERIPHERAL_RESOURCE_SHARING_ENABLED #define IRQ_HANDLER_NAME(n) irq_handler_for_instance_##n #define IRQ_HANDLER(n) static void IRQ_HANDLER_NAME(n)(void) #if SPI0_ENABLED IRQ_HANDLER(0); #endif #if SPI1_ENABLED IRQ_HANDLER(1); #endif #if SPI2_ENABLED IRQ_HANDLER(2); #endif static nrf_drv_irq_handler_t const m_irq_handlers[SPI_COUNT] = { #if SPI0_ENABLED IRQ_HANDLER_NAME(0), #endif #if SPI1_ENABLED IRQ_HANDLER_NAME(1), #endif #if SPI2_ENABLED IRQ_HANDLER_NAME(2), #endif }; #else #define IRQ_HANDLER(n) void SPI##n##_IRQ_HANDLER(void) #endif // PERIPHERAL_RESOURCE_SHARING_ENABLED ret_code_t nrf_drv_spi_init(nrf_drv_spi_t const * const p_instance, nrf_drv_spi_config_t const * p_config, nrf_drv_spi_handler_t handler) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; if (p_cb->state != NRF_DRV_STATE_UNINITIALIZED) { return NRF_ERROR_INVALID_STATE; } #if PERIPHERAL_RESOURCE_SHARING_ENABLED if (nrf_drv_common_per_res_acquire(p_instance->p_registers, m_irq_handlers[p_instance->drv_inst_idx]) != NRF_SUCCESS) { return NRF_ERROR_BUSY; } #endif if (p_config == NULL) { p_config = &m_default_config[p_instance->drv_inst_idx]; } p_cb->handler = handler; uint32_t mosi_pin; uint32_t miso_pin; // Configure pins used by the peripheral: // - SCK - output with initial value corresponding with the SPI mode used: // 0 - for modes 0 and 1 (CPOL = 0), 1 - for modes 2 and 3 (CPOL = 1); // according to the reference manual guidelines this pin and its input // buffer must always be connected for the SPI to work. if (p_config->mode <= NRF_DRV_SPI_MODE_1) { nrf_gpio_pin_clear(p_config->sck_pin); } else { nrf_gpio_pin_set(p_config->sck_pin); } NRF_GPIO->PIN_CNF[p_config->sck_pin] = (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) | (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos); // - MOSI (optional) - output with initial value 0, if (p_config->mosi_pin != NRF_DRV_SPI_PIN_NOT_USED) { mosi_pin = p_config->mosi_pin; nrf_gpio_pin_clear(mosi_pin); nrf_gpio_cfg_output(mosi_pin); } else { mosi_pin = NRF_SPI_PIN_NOT_CONNECTED; } // - MISO (optional) - input, if (p_config->miso_pin != NRF_DRV_SPI_PIN_NOT_USED) { miso_pin = p_config->miso_pin; nrf_gpio_cfg_input(miso_pin, NRF_GPIO_PIN_NOPULL); } else { miso_pin = NRF_SPI_PIN_NOT_CONNECTED; } // - Slave Select (optional) - output with initial value 1 (inactive). if (p_config->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_config->ss_pin); nrf_gpio_cfg_output(p_config->ss_pin); } m_cb[p_instance->drv_inst_idx].ss_pin = p_config->ss_pin; CODE_FOR_SPIM ( NRF_SPIM_Type * p_spim = p_instance->p_registers; nrf_spim_pins_set(p_spim, p_config->sck_pin, mosi_pin, miso_pin); nrf_spim_frequency_set(p_spim, (nrf_spim_frequency_t)p_config->frequency); nrf_spim_configure(p_spim, (nrf_spim_mode_t)p_config->mode, (nrf_spim_bit_order_t)p_config->bit_order); nrf_spim_orc_set(p_spim, p_config->orc); if (p_cb->handler) { nrf_spim_int_enable(p_spim, END_INT_MASK | NRF_SPIM_INT_STOPPED_MASK); } nrf_spim_enable(p_spim); ) CODE_FOR_SPI ( NRF_SPI_Type * p_spi = p_instance->p_registers; nrf_spi_pins_set(p_spi, p_config->sck_pin, mosi_pin, miso_pin); nrf_spi_frequency_set(p_spi, (nrf_spi_frequency_t)p_config->frequency); nrf_spi_configure(p_spi, (nrf_spi_mode_t)p_config->mode, (nrf_spi_bit_order_t)p_config->bit_order); m_cb[p_instance->drv_inst_idx].orc = p_config->orc; if (p_cb->handler) { nrf_spi_int_enable(p_spi, NRF_SPI_INT_READY_MASK); } nrf_spi_enable(p_spi); ) if (p_cb->handler) { nrf_drv_common_irq_enable(p_instance->irq, p_config->irq_priority); } p_cb->transfer_in_progress = false; p_cb->state = NRF_DRV_STATE_INITIALIZED; return NRF_SUCCESS; } void nrf_drv_spi_uninit(nrf_drv_spi_t const * const p_instance) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; ASSERT(p_cb->state != NRF_DRV_STATE_UNINITIALIZED); if (p_cb->handler) { nrf_drv_common_irq_disable(p_instance->irq); } #define DISABLE_ALL 0xFFFFFFFF CODE_FOR_SPIM ( NRF_SPIM_Type * p_spim = p_instance->p_registers; if (p_cb->handler) { nrf_spim_int_disable(p_spim, DISABLE_ALL); if (p_cb->transfer_in_progress) { // Ensure that SPI is not performing any transfer. nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_STOP); while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_STOPPED)) {} p_cb->transfer_in_progress = false; } } nrf_spim_disable(p_spim); ) CODE_FOR_SPI ( NRF_SPI_Type * p_spi = p_instance->p_registers; if (p_cb->handler) { nrf_spi_int_disable(p_spi, DISABLE_ALL); } nrf_spi_disable(p_spi); ) #undef DISABLE_ALL #if PERIPHERAL_RESOURCE_SHARING_ENABLED nrf_drv_common_per_res_release(p_instance->p_registers); #endif p_cb->state = NRF_DRV_STATE_UNINITIALIZED; } ret_code_t nrf_drv_spi_transfer(nrf_drv_spi_t const * const p_instance, uint8_t const * p_tx_buffer, uint8_t tx_buffer_length, uint8_t * p_rx_buffer, uint8_t rx_buffer_length) { nrf_drv_spi_xfer_desc_t xfer_desc; xfer_desc.p_tx_buffer = p_tx_buffer; xfer_desc.p_rx_buffer = p_rx_buffer; xfer_desc.tx_length = tx_buffer_length; xfer_desc.rx_length = rx_buffer_length; return nrf_drv_spi_xfer(p_instance, &xfer_desc, 0); } static void finish_transfer(spi_control_block_t * p_cb) { // If Slave Select signal is used, this is the time to deactivate it. if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_cb->ss_pin); } // By clearing this flag before calling the handler we allow subsequent // transfers to be started directly from the handler function. p_cb->transfer_in_progress = false; p_cb->evt.type = NRF_DRV_SPI_EVENT_DONE; p_cb->handler(&p_cb->evt); } #ifdef SPI_IN_USE // This function is called from IRQ handler or, in blocking mode, directly // from the 'nrf_drv_spi_transfer' function. // It returns true as long as the transfer should be continued, otherwise (when // there is nothing more to send/receive) it returns false. static bool transfer_byte(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb) { // Read the data byte received in this transfer and store it in RX buffer, // if needed. volatile uint8_t rx_data = nrf_spi_rxd_get(p_spi); if (p_cb->bytes_transferred < p_cb->evt.data.done.rx_length) { p_cb->evt.data.done.p_rx_buffer[p_cb->bytes_transferred] = rx_data; } ++p_cb->bytes_transferred; // Check if there are more bytes to send or receive and write proper data // byte (next one from TX buffer or over-run character) to the TXD register // when needed. // NOTE - we've already used 'p_cb->bytes_transferred + 1' bytes from our // buffers, because we take advantage of double buffering of TXD // register (so in effect one byte is still being transmitted now); // see how the transfer is started in the 'nrf_drv_spi_transfer' // function. uint16_t bytes_used = p_cb->bytes_transferred + 1; if (bytes_used < p_cb->evt.data.done.tx_length) { nrf_spi_txd_set(p_spi, p_cb->evt.data.done.p_tx_buffer[bytes_used]); return true; } else if (bytes_used < p_cb->evt.data.done.rx_length) { nrf_spi_txd_set(p_spi, p_cb->orc); return true; } return (p_cb->bytes_transferred < p_cb->evt.data.done.tx_length || p_cb->bytes_transferred < p_cb->evt.data.done.rx_length); } static void spi_xfer(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb, nrf_drv_spi_xfer_desc_t const * p_xfer_desc) { p_cb->bytes_transferred = 0; nrf_spi_int_disable(p_spi, NRF_SPI_INT_READY_MASK); nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); // Start the transfer by writing some byte to the TXD register; // if TX buffer is not empty, take the first byte from this buffer, // otherwise - use over-run character. nrf_spi_txd_set(p_spi, (p_xfer_desc->tx_length > 0 ? p_xfer_desc->p_tx_buffer[0] : p_cb->orc)); // TXD register is double buffered, so next byte to be transmitted can // be written immediately, if needed, i.e. if TX or RX transfer is to // be more that 1 byte long. Again - if there is something more in TX // buffer send it, otherwise use over-run character. if (p_xfer_desc->tx_length > 1) { nrf_spi_txd_set(p_spi, p_xfer_desc->p_tx_buffer[1]); } else if (p_xfer_desc->rx_length > 1) { nrf_spi_txd_set(p_spi, p_cb->orc); } // For blocking mode (user handler not provided) wait here for READY // events (indicating that the byte from TXD register was transmitted // and a new incoming byte was moved to the RXD register) and continue // transaction until all requested bytes are transferred. // In non-blocking mode - IRQ service routine will do this stuff. if (p_cb->handler) { nrf_spi_int_enable(p_spi, NRF_SPI_INT_READY_MASK); } else { do { while (!nrf_spi_event_check(p_spi, NRF_SPI_EVENT_READY)) {} nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); } while (transfer_byte(p_spi, p_cb)); if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_cb->ss_pin); } } } #endif // SPI_IN_USE #ifdef SPIM_IN_USE __STATIC_INLINE void spim_int_enable(NRF_SPIM_Type * p_spim, bool enable) { if (!enable) { nrf_spim_int_disable(p_spim, END_INT_MASK | NRF_SPIM_INT_STOPPED_MASK); } else { nrf_spim_int_enable(p_spim, END_INT_MASK | NRF_SPIM_INT_STOPPED_MASK); } } __STATIC_INLINE void spim_list_enable_handle(NRF_SPIM_Type * p_spim, uint32_t flags) { #ifndef NRF52_PAN_46 if (NRF_DRV_SPI_FLAG_TX_POSTINC & flags) { nrf_spim_tx_list_enable(p_spim); } else { nrf_spim_tx_list_disable(p_spim); } if (NRF_DRV_SPI_FLAG_RX_POSTINC & flags) { nrf_spim_rx_list_enable(p_spim); } else { nrf_spim_rx_list_disable(p_spim); } #endif } static ret_code_t spim_xfer(NRF_SPIM_Type * p_spim, spi_control_block_t * p_cb, nrf_drv_spi_xfer_desc_t const * p_xfer_desc, uint32_t flags) { // EasyDMA requires that transfer buffers are placed in Data RAM region; // signal error if they are not. if ((p_xfer_desc->p_tx_buffer != NULL && !nrf_drv_is_in_RAM(p_xfer_desc->p_tx_buffer)) || (p_xfer_desc->p_rx_buffer != NULL && !nrf_drv_is_in_RAM(p_xfer_desc->p_rx_buffer))) { p_cb->transfer_in_progress = false; return NRF_ERROR_INVALID_ADDR; } nrf_spim_tx_buffer_set(p_spim, p_xfer_desc->p_tx_buffer, p_xfer_desc->tx_length); nrf_spim_rx_buffer_set(p_spim, p_xfer_desc->p_rx_buffer, p_xfer_desc->rx_length); #ifdef NRF52_PAN_23 nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDTX); nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDRX); #else nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_END); #endif nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_STOPPED); spim_list_enable_handle(p_spim, flags); if (!(flags & NRF_DRV_SPI_FLAG_HOLD_XFER)) { nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_START); } if (!p_cb->handler) { #ifdef NRF52_PAN_23 while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDTX) || !nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDRX)) {} #else while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_END)){} #endif // Stop the peripheral after transaction is finished. nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_STOP); while (!nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_STOPPED)) {} if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_set(p_cb->ss_pin); } } else { spim_int_enable(p_spim, !(flags & NRF_DRV_SPI_FLAG_NO_XFER_EVT_HANDLER)); } return NRF_SUCCESS; } #endif ret_code_t nrf_drv_spi_xfer(nrf_drv_spi_t const * const p_instance, nrf_drv_spi_xfer_desc_t const * p_xfer_desc, uint32_t flags) { spi_control_block_t * p_cb = &m_cb[p_instance->drv_inst_idx]; ASSERT(p_cb->state != NRF_DRV_STATE_UNINITIALIZED); ASSERT(p_tx_buffer != NULL || tx_buffer_length == 0); ASSERT(p_rx_buffer != NULL || rx_buffer_length == 0); if (p_cb->transfer_in_progress) { return NRF_ERROR_BUSY; } else { if (p_cb->handler && !(flags & (NRF_DRV_SPI_FLAG_REPEATED_XFER | NRF_DRV_SPI_FLAG_NO_XFER_EVT_HANDLER))) { p_cb->transfer_in_progress = true; } } p_cb->evt.data.done = *p_xfer_desc; p_cb->tx_done = false; p_cb->rx_done = false; if (p_cb->ss_pin != NRF_DRV_SPI_PIN_NOT_USED) { nrf_gpio_pin_clear(p_cb->ss_pin); } CODE_FOR_SPIM ( return spim_xfer(p_instance->p_registers, p_cb, p_xfer_desc, flags); ) CODE_FOR_SPI ( if (flags) { p_cb->transfer_in_progress = false; return NRF_ERROR_NOT_SUPPORTED; } spi_xfer(p_instance->p_registers, p_cb, p_xfer_desc); return NRF_SUCCESS; ) } #ifdef SPIM_IN_USE static void irq_handler_spim(NRF_SPIM_Type * p_spim, spi_control_block_t * p_cb) { ASSERT(p_cb->handler); #ifdef NRF52_PAN_23 if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_STOPPED)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_STOPPED); finish_transfer(p_cb); } else { if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDTX)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDTX); p_cb->tx_done = true; } if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_ENDRX)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_ENDRX); p_cb->rx_done = true; } if (p_cb->tx_done && p_cb->rx_done) { nrf_spim_task_trigger(p_spim, NRF_SPIM_TASK_STOP); } } #else if (nrf_spim_event_check(p_spim, NRF_SPIM_EVENT_END)) { nrf_spim_event_clear(p_spim, NRF_SPIM_EVENT_END); finish_transfer(p_cb); } #endif } uint32_t nrf_drv_spi_start_task_get(nrf_drv_spi_t const * p_instance) { NRF_SPIM_Type * p_spim = (NRF_SPIM_Type *)p_instance->p_registers; return nrf_spim_task_address_get(p_spim, NRF_SPIM_TASK_START); } uint32_t nrf_drv_spi_end_event_get(nrf_drv_spi_t const * p_instance) { NRF_SPIM_Type * p_spim = (NRF_SPIM_Type *)p_instance->p_registers; return nrf_spim_event_address_get(p_spim, NRF_SPIM_EVENT_END); } #endif // SPIM_IN_USE #ifdef SPI_IN_USE static void irq_handler_spi(NRF_SPI_Type * p_spi, spi_control_block_t * p_cb) { ASSERT(p_cb->handler); nrf_spi_event_clear(p_spi, NRF_SPI_EVENT_READY); if (!transfer_byte(p_spi, p_cb)) { finish_transfer(p_cb); } } #endif // SPI_IN_USE #if SPI0_ENABLED IRQ_HANDLER(0) { spi_control_block_t * p_cb = &m_cb[SPI0_INSTANCE_INDEX]; #if SPI0_USE_EASY_DMA irq_handler_spim(NRF_SPIM0, p_cb); #else irq_handler_spi(NRF_SPI0, p_cb); #endif } #endif // SPI0_ENABLED #if SPI1_ENABLED IRQ_HANDLER(1) { spi_control_block_t * p_cb = &m_cb[SPI1_INSTANCE_INDEX]; #if SPI1_USE_EASY_DMA irq_handler_spim(NRF_SPIM1, p_cb); #else irq_handler_spi(NRF_SPI1, p_cb); #endif } #endif // SPI1_ENABLED #if SPI2_ENABLED IRQ_HANDLER(2) { spi_control_block_t * p_cb = &m_cb[SPI2_INSTANCE_INDEX]; #if SPI2_USE_EASY_DMA irq_handler_spim(NRF_SPIM2, p_cb); #else irq_handler_spi(NRF_SPI2, p_cb); #endif } #endif // SPI2_ENABLED
461881.c
/* * Copyright (C) 2006 James Hawkins * * A test program for installing MSI products. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #define _WIN32_MSI 300 #define COBJMACROS #include <stdio.h> #include <windows.h> #include <msiquery.h> #include <msidefs.h> #include <msi.h> #include <fci.h> #include <objidl.h> #include <srrestoreptapi.h> #include <shlobj.h> #include <winsvc.h> #include <shellapi.h> #include "wine/test.h" static UINT (WINAPI *pMsiQueryComponentStateA) (LPCSTR, LPCSTR, MSIINSTALLCONTEXT, LPCSTR, INSTALLSTATE*); static UINT (WINAPI *pMsiSourceListEnumSourcesA) (LPCSTR, LPCSTR, MSIINSTALLCONTEXT, DWORD, DWORD, LPSTR, LPDWORD); static INSTALLSTATE (WINAPI *pMsiGetComponentPathExA) (LPCSTR, LPCSTR, LPCSTR, MSIINSTALLCONTEXT, LPSTR, LPDWORD); static BOOL (WINAPI *pCheckTokenMembership)(HANDLE,PSID,PBOOL); static BOOL (WINAPI *pConvertSidToStringSidA)(PSID, LPSTR*); static BOOL (WINAPI *pOpenProcessToken)( HANDLE, DWORD, PHANDLE ); static LONG (WINAPI *pRegDeleteKeyExA)(HKEY, LPCSTR, REGSAM, DWORD); static BOOL (WINAPI *pIsWow64Process)(HANDLE, PBOOL); static HMODULE hsrclient = 0; static BOOL (WINAPI *pSRRemoveRestorePoint)(DWORD); static BOOL (WINAPI *pSRSetRestorePointA)(RESTOREPOINTINFOA*, STATEMGRSTATUS*); static BOOL is_wow64; static const BOOL is_64bit = sizeof(void *) > sizeof(int); static const char *msifile = "msitest.msi"; static const char *msifile2 = "winetest2.msi"; static const char *mstfile = "winetest.mst"; static const WCHAR msifileW[] = {'m','s','i','t','e','s','t','.','m','s','i',0}; static const WCHAR msifile2W[] = {'w','i','n','e','t','e','s','t','2','.','m','s','i',0}; static CHAR CURR_DIR[MAX_PATH]; static CHAR PROG_FILES_DIR[MAX_PATH]; static CHAR PROG_FILES_DIR_NATIVE[MAX_PATH]; static CHAR COMMON_FILES_DIR[MAX_PATH]; static CHAR APP_DATA_DIR[MAX_PATH]; static CHAR WINDOWS_DIR[MAX_PATH]; /* msi database data */ static const CHAR component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "Five\t{8CC92E9D-14B2-4CA4-B2AA-B11D02078087}\tNEWDIR\t2\t\tfive.txt\n" "Four\t{FD37B4EA-7209-45C0-8917-535F35A2F080}\tCABOUTDIR\t2\t\tfour.txt\n" "One\t{783B242E-E185-4A56-AF86-C09815EC053C}\tMSITESTDIR\t2\tNOT REINSTALL\tone.txt\n" "Three\t{010B6ADD-B27D-4EDD-9B3D-34C4F7D61684}\tCHANGEDDIR\t2\t\tthree.txt\n" "Two\t{BF03D1A6-20DA-4A65-82F3-6CAC995915CE}\tFIRSTDIR\t2\t\ttwo.txt\n" "dangler\t{6091DF25-EF96-45F1-B8E9-A9B1420C7A3C}\tTARGETDIR\t4\t\tregdata\n" "component\t\tMSITESTDIR\t0\t1\tfile\n" "service_comp\t\tMSITESTDIR\t0\t1\tservice_file"; static const CHAR directory_dat[] = "Directory\tDirectory_Parent\tDefaultDir\n" "s72\tS72\tl255\n" "Directory\tDirectory\n" "CABOUTDIR\tMSITESTDIR\tcabout\n" "CHANGEDDIR\tMSITESTDIR\tchanged:second\n" "FIRSTDIR\tMSITESTDIR\tfirst\n" "MSITESTDIR\tProgramFilesFolder\tmsitest\n" "NEWDIR\tCABOUTDIR\tnew\n" "ProgramFilesFolder\tTARGETDIR\t.\n" "TARGETDIR\t\tSourceDir"; static const CHAR feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "Five\t\tFive\tThe Five Feature\t5\t3\tNEWDIR\t0\n" "Four\t\tFour\tThe Four Feature\t4\t3\tCABOUTDIR\t0\n" "One\t\tOne\tThe One Feature\t1\t3\tMSITESTDIR\t0\n" "Three\t\tThree\tThe Three Feature\t3\t3\tCHANGEDDIR\t0\n" "Two\t\tTwo\tThe Two Feature\t2\t3\tFIRSTDIR\t0\n" "feature\t\t\t\t2\t1\tTARGETDIR\t0\n" "service_feature\t\t\t\t2\t1\tTARGETDIR\t0"; static const CHAR feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "Five\tFive\n" "Four\tFour\n" "One\tOne\n" "Three\tThree\n" "Two\tTwo\n" "feature\tcomponent\n" "service_feature\tservice_comp\n"; static const CHAR file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "five.txt\tFive\tfive.txt\t1000\t\t\t16384\t5\n" "four.txt\tFour\tfour.txt\t1000\t\t\t16384\t4\n" "one.txt\tOne\tone.txt\t1000\t\t\t0\t1\n" "three.txt\tThree\tthree.txt\t1000\t\t\t0\t3\n" "two.txt\tTwo\ttwo.txt\t1000\t\t\t0\t2\n" "file\tcomponent\tfilename\t100\t\t\t8192\t1\n" "service_file\tservice_comp\tservice.exe\t100\t\t\t8192\t1"; static const CHAR install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "AllocateRegistrySpace\tNOT Installed\t1550\n" "CostFinalize\t\t1000\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "ResolveSource\t\t950\n" "MoveFiles\t\t1700\n" "InstallFiles\t\t4000\n" "DuplicateFiles\t\t4500\n" "WriteEnvironmentStrings\t\t4550\n" "CreateShortcuts\t\t4600\n" "InstallServices\t\t5000\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "WriteRegistryValues\tSourceDir And SOURCEDIR\t5000"; static const CHAR media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t3\t\t\tDISK1\t\n" "2\t5\t\tmsitest.cab\tDISK2\t\n"; static const CHAR property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "PRIMARYFOLDER\tTARGETDIR\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "MSIFASTINSTALL\t1\n"; static const CHAR aup_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "ALLUSERS\t1\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "MSIFASTINSTALL\t1\n"; static const CHAR aup2_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "ALLUSERS\t2\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "MSIFASTINSTALL\t1\n"; static const CHAR icon_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A49-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "MSIFASTINSTALL\t1\n"; static const CHAR shortcut_dat[] = "Shortcut\tDirectory_\tName\tComponent_\tTarget\tArguments\tDescription\tHotkey\tIcon_\tIconIndex\tShowCmd\tWkDir\n" "s72\ts72\tl128\ts72\ts72\tS255\tL255\tI2\tS72\tI2\tI2\tS72\n" "Shortcut\tShortcut\n" "Shortcut\tMSITESTDIR\tShortcut\tcomponent\tShortcut\t\tShortcut\t\t\t\t\t\n"; static const CHAR condition_dat[] = "Feature_\tLevel\tCondition\n" "s38\ti2\tS255\n" "Condition\tFeature_\tLevel\n" "One\t4\t1\n"; static const CHAR up_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "RemovePreviousVersions\t1\n" "MSIFASTINSTALL\t1\n"; static const CHAR up2_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.2\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "MSIFASTINSTALL\t1\n"; static const CHAR up3_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "DefaultUIFont\tDlgFont8\n" "HASUIRUN\t0\n" "INSTALLLEVEL\t3\n" "InstallMode\tTypical\n" "Manufacturer\tWine\n" "PIDTemplate\t12345<###-%%%%%%%>@@@@@\n" "ProductCode\t{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}\n" "ProductID\tnone\n" "ProductLanguage\t1033\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.2\n" "PROMPTROLLBACKCOST\tP\n" "Setup\tSetup\n" "UpgradeCode\t{4C0EAA15-0264-4E5A-8758-609EF142B92D}\n" "AdminProperties\tPOSTADMIN\n" "ROOTDRIVE\tC:\\\n" "SERVNAME\tTestService\n" "SERVDISP\tTestServiceDisp\n" "RemovePreviousVersions\t1\n" "MSIFASTINSTALL\t1\n"; static const CHAR registry_dat[] = "Registry\tRoot\tKey\tName\tValue\tComponent_\n" "s72\ti2\tl255\tL255\tL0\ts72\n" "Registry\tRegistry\n" "Apples\t1\tSOFTWARE\\Wine\\msitest\tName\timaname\tOne\n" "Oranges\t1\tSOFTWARE\\Wine\\msitest\tnumber\t#314\tTwo\n" "regdata\t1\tSOFTWARE\\Wine\\msitest\tblah\tbad\tdangler\n" "OrderTest\t1\tSOFTWARE\\Wine\\msitest\tOrderTestName\tOrderTestValue\tcomponent"; static const CHAR service_install_dat[] = "ServiceInstall\tName\tDisplayName\tServiceType\tStartType\tErrorControl\t" "LoadOrderGroup\tDependencies\tStartName\tPassword\tArguments\tComponent_\tDescription\n" "s72\ts255\tL255\ti4\ti4\ti4\tS255\tS255\tS255\tS255\tS255\ts72\tL255\n" "ServiceInstall\tServiceInstall\n" "TestService\t[SERVNAME]\t[SERVDISP]\t2\t3\t0\t\t\tTestService\t\t\tservice_comp\t\t"; static const CHAR service_control_dat[] = "ServiceControl\tName\tEvent\tArguments\tWait\tComponent_\n" "s72\tl255\ti2\tL255\tI2\ts72\n" "ServiceControl\tServiceControl\n" "ServiceControl\tTestService\t8\t\t0\tservice_comp"; /* tables for test_continuouscabs */ static const CHAR cc_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\t1\tmaximus\n" "augustus\t\tMSITESTDIR\t0\t1\taugustus\n" "caesar\t\tMSITESTDIR\t0\t1\tcaesar\n"; static const CHAR cc2_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\t1\tmaximus\n" "augustus\t\tMSITESTDIR\t0\t0\taugustus\n" "caesar\t\tMSITESTDIR\t0\t1\tcaesar\n"; static const CHAR cc_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "feature\t\t\t\t2\t1\tTARGETDIR\t0"; static const CHAR cc_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\tmaximus\n" "feature\taugustus\n" "feature\tcaesar"; static const CHAR cc_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1\n" "augustus\taugustus\taugustus\t50000\t\t\t16384\t2\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t12"; static const CHAR cc2_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1\n" "augustus\taugustus\taugustus\t50000\t\t\t16384\t2\n" "tiberius\tmaximus\ttiberius\t500\t\t\t16384\t3\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t12"; static const CHAR cc_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t10\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2.cab\tDISK2\t\n" "3\t12\t\ttest3.cab\tDISK3\t\n"; static const CHAR cc3_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t10\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2_.cab\tDISK2\t\n" "3\t12\t\ttest3.cab\tDISK3\t\n"; static const CHAR co_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1\n" "augustus\taugustus\taugustus\t50000\t\t\t16384\t2\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t3"; static const CHAR co_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t10\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2.cab\tDISK2\t\n" "3\t3\t\ttest3.cab\tDISK3\t\n"; static const CHAR co2_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t10\t\ttest1.cab\tDISK1\t\n" "2\t12\t\ttest3.cab\tDISK3\t\n" "3\t2\t\ttest2.cab\tDISK2\t\n"; static const CHAR mm_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t512\t1\n" "augustus\taugustus\taugustus\t500\t\t\t512\t2\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t3"; static const CHAR mm_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t3\t\ttest1.cab\tDISK1\t\n"; static const CHAR ss_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t2\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2.cab\tDISK2\t\n" "3\t12\t\ttest3.cab\tDISK3\t\n"; /* tables for test_uiLevelFlags */ static const CHAR ui_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\tHASUIRUN=1\tmaximus\n" "augustus\t\tMSITESTDIR\t0\t1\taugustus\n" "caesar\t\tMSITESTDIR\t0\t1\tcaesar\n"; static const CHAR ui_install_ui_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallUISequence\tAction\n" "SetUIProperty\t\t5\n" "ExecuteAction\t\t1100\n"; static const CHAR ui_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "SetUIProperty\t51\tHASUIRUN\t1\t\n"; static const CHAR rof_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\t1\tmaximus\n"; static const CHAR rof_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "feature\t\tFeature\tFeature\t2\t1\tTARGETDIR\t0\n" "montecristo\t\tFeature\tFeature\t2\t1\tTARGETDIR\t0"; static const CHAR rof_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\tmaximus\n" "montecristo\tmaximus"; static const CHAR rof_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t8192\t1"; static const CHAR rof_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t1\t\t\tDISK1\t\n"; static const CHAR rofc_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1"; static const CHAR rofc_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t1\t\ttest1.cab\tDISK1\t\n"; static const CHAR sdp_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "AllocateRegistrySpace\tNOT Installed\t1550\n" "CostFinalize\t\t1000\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "InstallFiles\t\t4000\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "SetDirProperty\t\t950"; static const CHAR sdp_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "SetDirProperty\t51\tMSITESTDIR\t[CommonFilesFolder]msitest\\\t\n"; static const CHAR pv_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "CostFinalize\t\t1000\n" "InstallValidate\t\t1400\n" "InstallInitialize\t\t1500\n" "InstallFiles\t\t4000\n" "InstallFinalize\t\t6600\n"; static const CHAR cie_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\t1\tmaximus\n" "augustus\t\tMSITESTDIR\t0\t1\taugustus\n" "caesar\t\tMSITESTDIR\t0\t1\tcaesar\n" "gaius\t\tMSITESTDIR\t0\t1\tgaius\n"; static const CHAR cie_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\tmaximus\n" "feature\taugustus\n" "feature\tcaesar\n" "feature\tgaius"; static const CHAR cie_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1\n" "augustus\taugustus\taugustus\t50000\t\t\t16384\t2\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t12\n" "gaius\tgaius\tgaius\t500\t\t\t8192\t11"; static const CHAR cie_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t1\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2.cab\tDISK2\t\n" "3\t12\t\ttest3.cab\tDISK3\t\n"; static const CHAR ci_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t{DF2CBABC-3BCC-47E5-A998-448D1C0C895B}\tMSITESTDIR\t0\tUILevel=5\tmaximus\n"; static const CHAR ci2_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\taugustus"; static const CHAR ci2_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "augustus\taugustus\taugustus\t500\t\t\t8192\t1"; static const CHAR pp_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "CostFinalize\t\t1000\n" "InstallValidate\t\t1400\n" "InstallInitialize\t\t1500\n" "ProcessComponents\tPROCESS_COMPONENTS=1 Or FULL=1\t1600\n" "UnpublishFeatures\tUNPUBLISH_FEATURES=1 Or FULL=1\t1800\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterUser\tREGISTER_USER=1 Or FULL=1\t6000\n" "RegisterProduct\tREGISTER_PRODUCT=1 Or FULL=1\t6100\n" "PublishFeatures\tPUBLISH_FEATURES=1 Or FULL=1\t6300\n" "PublishProduct\tPUBLISH_PRODUCT=1 Or FULL=1\t6400\n" "InstallFinalize\t\t6600"; static const CHAR tp_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\tprop=\"val\"\taugustus\n"; static const CHAR cwd_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\t\taugustus\n"; static const CHAR adm_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\tPOSTADMIN=1\taugustus"; static const CHAR adm_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "SetPOSTADMIN\t51\tPOSTADMIN\t1\t\n"; static const CHAR adm_admin_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "AdminExecuteSequence\tAction\n" "CostFinalize\t\t1000\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "SetPOSTADMIN\t\t950\n" "InstallFiles\t\t4000\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100"; static const CHAR amp_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\tMYPROP=2718 and MyProp=42\taugustus\n"; static const CHAR rem_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "CostFinalize\t\t1000\n" "InstallValidate\t\t1400\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "UnpublishFeatures\t\t1800\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterProduct\t\t6100\n" "PublishFeatures\t\t6300\n" "PublishProduct\t\t6400\n" "InstallFinalize\t\t6600"; static const CHAR mc_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "maximus\t\tMSITESTDIR\t0\t1\tmaximus\n" "augustus\t\tMSITESTDIR\t0\t1\taugustus\n" "caesar\t\tMSITESTDIR\t0\t1\tcaesar\n" "gaius\t\tMSITESTDIR\t0\tGAIUS=1\tgaius\n" "tiberius\t\tMSITESTDIR\t0\t\ttiberius\n"; static const CHAR mc_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "maximus\tmaximus\tmaximus\t500\t\t\t16384\t1\n" "augustus\taugustus\taugustus\t500\t\t\t0\t2\n" "caesar\tcaesar\tcaesar\t500\t\t\t16384\t3\n" "gaius\tgaius\tgaius\t500\t\t\t16384\t4\n" "tiberius\ttiberius\ttiberius\t500\t\t\t0\t5\n"; static const CHAR mc_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t1\t\ttest1.cab\tDISK1\t\n" "2\t2\t\ttest2.cab\tDISK2\t\n" "3\t3\t\ttest3.cab\tDISK3\t\n" "4\t4\t\ttest3.cab\tDISK3\t\n" "5\t5\t\ttest4.cab\tDISK4\t\n"; static const CHAR mc_file_hash_dat[] = "File_\tOptions\tHashPart1\tHashPart2\tHashPart3\tHashPart4\n" "s72\ti2\ti4\ti4\ti4\ti4\n" "MsiFileHash\tFile_\n" "caesar\t0\t850433704\t-241429251\t675791761\t-1221108824"; static const CHAR wrv_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\t\taugustus\n"; static const CHAR ca51_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tMSITESTDIR\t0\tMYPROP=42\taugustus\n"; static const CHAR ca51_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "ValidateProductID\t\t700\n" "GoodSetProperty\t\t725\n" "BadSetProperty\t\t750\n" "CostInitialize\t\t800\n" "ResolveSource\t\t810\n" "FileCost\t\t900\n" "SetSourceDir\tSRCDIR\t910\n" "CostFinalize\t\t1000\n" "InstallValidate\t\t1400\n" "InstallInitialize\t\t1500\n" "InstallFiles\t\t4000\n" "InstallFinalize\t\t6600"; static const CHAR ca51_custom_action_dat[] = "Action\tType\tSource\tTarget\n" "s72\ti2\tS64\tS0\n" "CustomAction\tAction\n" "GoodSetProperty\t51\tMYPROP\t42\n" "BadSetProperty\t51\t\tMYPROP\n" "SetSourceDir\t51\tSourceDir\t[SRCDIR]\n"; static const CHAR is_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "one\t\t\t\t2\t1\t\t0\n" /* favorLocal */ "two\t\t\t\t2\t1\t\t1\n" /* favorSource */ "three\t\t\t\t2\t1\t\t4\n" /* favorAdvertise */ "four\t\t\t\t2\t0\t\t0"; /* disabled */ static const CHAR is_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "alpha\t\tMSITESTDIR\t0\t\talpha_file\n" /* favorLocal:Local */ "beta\t\tMSITESTDIR\t1\t\tbeta_file\n" /* favorLocal:Source */ "gamma\t\tMSITESTDIR\t2\t\tgamma_file\n" /* favorLocal:Optional */ "theta\t\tMSITESTDIR\t0\t\ttheta_file\n" /* favorSource:Local */ "delta\t\tMSITESTDIR\t1\t\tdelta_file\n" /* favorSource:Source */ "epsilon\t\tMSITESTDIR\t2\t\tepsilon_file\n" /* favorSource:Optional */ "zeta\t\tMSITESTDIR\t0\t\tzeta_file\n" /* favorAdvertise:Local */ "iota\t\tMSITESTDIR\t1\t\tiota_file\n" /* favorAdvertise:Source */ "eta\t\tMSITESTDIR\t2\t\teta_file\n" /* favorAdvertise:Optional */ "kappa\t\tMSITESTDIR\t0\t\tkappa_file\n" /* disabled:Local */ "lambda\t\tMSITESTDIR\t1\t\tlambda_file\n" /* disabled:Source */ "mu\t\tMSITESTDIR\t2\t\tmu_file\n"; /* disabled:Optional */ static const CHAR is_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "one\talpha\n" "one\tbeta\n" "one\tgamma\n" "two\ttheta\n" "two\tdelta\n" "two\tepsilon\n" "three\tzeta\n" "three\tiota\n" "three\teta\n" "four\tkappa\n" "four\tlambda\n" "four\tmu"; static const CHAR is_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "alpha_file\talpha\talpha\t500\t\t\t8192\t1\n" "beta_file\tbeta\tbeta\t500\t\t\t8291\t2\n" "gamma_file\tgamma\tgamma\t500\t\t\t8192\t3\n" "theta_file\ttheta\ttheta\t500\t\t\t8192\t4\n" "delta_file\tdelta\tdelta\t500\t\t\t8192\t5\n" "epsilon_file\tepsilon\tepsilon\t500\t\t\t8192\t6\n" "zeta_file\tzeta\tzeta\t500\t\t\t8192\t7\n" "iota_file\tiota\tiota\t500\t\t\t8192\t8\n" "eta_file\teta\teta\t500\t\t\t8192\t9\n" "kappa_file\tkappa\tkappa\t500\t\t\t8192\t10\n" "lambda_file\tlambda\tlambda\t500\t\t\t8192\t11\n" "mu_file\tmu\tmu\t500\t\t\t8192\t12"; static const CHAR is_media_dat[] = "DiskId\tLastSequence\tDiskPrompt\tCabinet\tVolumeLabel\tSource\n" "i2\ti4\tL64\tS255\tS32\tS72\n" "Media\tDiskId\n" "1\t12\t\t\tDISK1\t\n"; static const CHAR sp_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "augustus\t\tTWODIR\t0\t\taugustus\n"; static const CHAR sp_directory_dat[] = "Directory\tDirectory_Parent\tDefaultDir\n" "s72\tS72\tl255\n" "Directory\tDirectory\n" "TARGETDIR\t\tSourceDir\n" "ProgramFilesFolder\tTARGETDIR\t.\n" "MSITESTDIR\tProgramFilesFolder\tmsitest:.\n" "ONEDIR\tMSITESTDIR\t.:shortone|longone\n" "TWODIR\tONEDIR\t.:shorttwo|longtwo"; static const CHAR mcp_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "hydrogen\t{C844BD1E-1907-4C00-8BC9-150BD70DF0A1}\tMSITESTDIR\t2\t\thydrogen\n" "helium\t{5AD3C142-CEF8-490D-B569-784D80670685}\tMSITESTDIR\t2\t\thelium\n" "lithium\t{4AF28FFC-71C7-4307-BDE4-B77C5338F56F}\tMSITESTDIR\t2\tPROPVAR=42\tlithium\n"; static const CHAR mcp_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "hydroxyl\t\thydroxyl\thydroxyl\t2\t1\tTARGETDIR\t0\n" "heliox\t\theliox\theliox\t2\t5\tTARGETDIR\t0\n" "lithia\t\tlithia\tlithia\t2\t10\tTARGETDIR\t0"; static const CHAR mcp_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "hydroxyl\thydrogen\n" "heliox\thelium\n" "lithia\tlithium"; static const CHAR mcp_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "hydrogen\thydrogen\thydrogen\t0\t\t\t8192\t1\n" "helium\thelium\thelium\t0\t\t\t8192\t1\n" "lithium\tlithium\tlithium\t0\t\t\t8192\t1\n" "beryllium\tmissingcomp\tberyllium\t0\t\t\t8192\t1"; static const CHAR ai_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "five.txt\tFive\tfive.txt\t1000\t\t\t16384\t5\n" "four.txt\tFour\tfour.txt\t1000\t\t\t16384\t4\n" "one.txt\tOne\tone.txt\t1000\t\t\t16384\t1\n" "three.txt\tThree\tthree.txt\t1000\t\t\t16384\t3\n" "two.txt\tTwo\ttwo.txt\t1000\t\t\t16384\t2\n" "file\tcomponent\tfilename\t100\t\t\t8192\t1\n" "service_file\tservice_comp\tservice.exe\t100\t\t\t8192\t1"; static const CHAR ip_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "CostFinalize\t\t1000\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterUser\t\t6000\n" "RegisterProduct\t\t6100\n" "PublishFeatures\t\t6300\n" "PublishProduct\t\t6400\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "UnpublishFeatures\t\t1800\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "TestInstalledProp\tInstalled AND NOT REMOVE\t950\n"; static const CHAR ip_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "TestInstalledProp\t19\t\tTest failed\t\n"; static const CHAR aup_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "CostFinalize\t\t1000\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterUser\t\t6000\n" "RegisterProduct\t\t6100\n" "PublishFeatures\t\t6300\n" "PublishProduct\t\t6400\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "UnpublishFeatures\t\t1800\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "TestAllUsersProp\tALLUSERS AND NOT REMOVE\t50\n"; static const CHAR aup2_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "CostFinalize\t\t1000\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterUser\t\t6000\n" "RegisterProduct\t\t6100\n" "PublishFeatures\t\t6300\n" "PublishProduct\t\t6400\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "UnpublishFeatures\t\t1800\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "TestAllUsersProp\tALLUSERS=2 AND NOT REMOVE\t50\n"; static const CHAR aup3_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "CostFinalize\t\t1000\n" "ValidateProductID\t\t700\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "RemoveFiles\t\t3500\n" "InstallFiles\t\t4000\n" "RegisterUser\t\t6000\n" "RegisterProduct\t\t6100\n" "PublishFeatures\t\t6300\n" "PublishProduct\t\t6400\n" "InstallFinalize\t\t6600\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "UnpublishFeatures\t\t1800\n" "InstallValidate\t\t1400\n" "LaunchConditions\t\t100\n" "TestAllUsersProp\tALLUSERS=1 AND NOT REMOVE\t50\n"; static const CHAR aup_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "TestAllUsersProp\t19\t\tTest failed\t\n"; static const CHAR fo_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "override.txt\toverride\toverride.txt\t1000\t\t\t8192\t1\n" "preselected.txt\tpreselected\tpreselected.txt\t1000\t\t\t8192\t2\n" "notpreselected.txt\tnotpreselected\tnotpreselected.txt\t1000\t\t\t8192\t3\n"; static const CHAR fo_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "override\t\t\toverride feature\t1\t1\tMSITESTDIR\t0\n" "preselected\t\t\tpreselected feature\t1\t1\tMSITESTDIR\t0\n" "notpreselected\t\t\tnotpreselected feature\t1\t1\tMSITESTDIR\t0\n"; static const CHAR fo_condition_dat[] = "Feature_\tLevel\tCondition\n" "s38\ti2\tS255\n" "Condition\tFeature_\tLevel\n" "preselected\t0\tPreselected\n" "notpreselected\t0\tNOT Preselected\n"; static const CHAR fo_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "override\toverride\n" "preselected\tpreselected\n" "notpreselected\tnotpreselected\n"; static const CHAR fo_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "override\t{0A00FB1D-97B0-4B42-ADF0-BB8913416623}\tMSITESTDIR\t0\t\toverride.txt\n" "preselected\t{44E1DB75-605A-43DD-8CF5-CAB17F1BBD60}\tMSITESTDIR\t0\t\tpreselected.txt\n" "notpreselected\t{E1647733-5E75-400A-A92E-5E60B4D4EF9F}\tMSITESTDIR\t0\t\tnotpreselected.txt\n"; static const CHAR fo_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "SetPreselected\t51\tPreselected\t1\t\n"; static const CHAR fo_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "SetPreselected\tpreselect=1\t200\n" "CostInitialize\t\t800\n" "FileCost\t\t900\n" "CostFinalize\t\t1000\n" "InstallValidate\t\t1400\n" "InstallInitialize\t\t1500\n" "ProcessComponents\t\t1600\n" "RemoveFiles\t\t1700\n" "InstallFiles\t\t2000\n" "RegisterProduct\t\t5000\n" "PublishFeatures\t\t5100\n" "PublishProduct\t\t5200\n" "InstallFinalize\t\t6000\n"; static const CHAR uc_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "upgradecode.txt\tupgradecode\tupgradecode.txt\t1000\t\t\t8192\t1\n"; static const CHAR uc_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "upgradecode\t\t\tupgradecode feature\t1\t2\tMSITESTDIR\t0\n"; static const CHAR uc_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "upgradecode\tupgradecode\n"; static const CHAR uc_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "upgradecode\t{6952B732-2FCB-4E47-976F-989FCBD7EDFB}\tMSITESTDIR\t0\t\tupgradecode.txt\n"; static const CHAR uc_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "INSTALLLEVEL\t3\n" "ProductCode\t{E5FB1241-F547-4BA7-A60E-8E75797268D4}\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "UpgradeCode\t#UPGEADECODE#\n" "MSIFASTINSTALL\t1\n"; static const CHAR uc_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "CostInitialize\t\t200\n" "FileCost\t\t300\n" "CostFinalize\t\t400\n" "InstallInitialize\t\t500\n" "ProcessComponents\t\t600\n" "InstallValidate\t\t700\n" "RemoveFiles\t\t800\n" "InstallFiles\t\t900\n" "RegisterProduct\t\t1000\n" "PublishFeatures\t\t1100\n" "PublishProduct\t\t1200\n" "InstallFinalize\t\t1300\n"; static const char mixed_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "feature1\t\t\t\t1\t2\tMSITESTDIR\t0\n" "feature2\t\t\t\t1\t2\tMSITESTDIR\t0\n"; static const char mixed_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature1\tcomp1\n" "feature2\tcomp2\n"; static const char mixed_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "comp1\t{DE9F0EF4-0ED3-495A-8105-060C0EA457B8}\tTARGETDIR\t4\t\tregdata1\n" "comp2\t{4912DBE7-FC3A-4F91-BB5C-88F5C15C19A5}\tTARGETDIR\t260\t\tregdata2\n"; static const char mixed_registry_dat[] = "Registry\tRoot\tKey\tName\tValue\tComponent_\n" "s72\ti2\tl255\tL255\tL0\ts72\n" "Registry\tRegistry\n" "regdata1\t2\tSOFTWARE\\Wine\\msitest\ttest1\t\tcomp1\n" "regdata2\t2\tSOFTWARE\\Wine\\msitest\ttest2\t\tcomp2\n" "regdata3\t0\tCLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\t\tCLSID_Winetest32\tcomp1\n" "regdata4\t0\tCLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32\t\twinetest32.dll\tcomp1\n" "regdata5\t0\tCLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\t\tCLSID_Winetest64\tcomp2\n" "regdata6\t0\tCLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32\t\twinetest64.dll\tcomp2\n"; static const char mixed_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "CostInitialize\t\t200\n" "FileCost\t\t300\n" "CostFinalize\t\t400\n" "InstallValidate\t\t500\n" "InstallInitialize\t\t600\n" "ProcessComponents\t\t700\n" "UnpublishFeatures\t\t800\n" "RemoveRegistryValues\t\t900\n" "WriteRegistryValues\t\t1000\n" "RegisterProduct\t\t1100\n" "PublishFeatures\t\t1200\n" "PublishProduct\t\t1300\n" "InstallFinalize\t\t1400\n"; static const char vp_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "volumeprop\tcomp\tvolumeprop.txt\t1000\t\t\t8192\t1\n"; static const char vp_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "feature\t\t\t\t1\t2\tMSITESTDIR\t0\n"; static const char vp_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\tcomp\n"; static const char vp_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "comp\t{24364AE7-5B7F-496C-AF5A-54893639C567}\tMSITESTDIR\t0\t\tvolumeprop\n"; static const char vp_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "TestPrimaryVolumePath0\t19\t\tPrimaryVolumePath set before CostFinalize\t\n" "TestPrimaryVolumeSpaceAvailable0\t19\t\tPrimaryVolumeSpaceAvailable set before CostFinalize\t\n" "TestPrimaryVolumeSpaceRequired0\t19\t\tPrimaryVolumeSpaceRequired set before CostFinalize\t\n" "TestPrimaryVolumeSpaceRemaining0\t19\t\tPrimaryVolumeSpaceRemaining set before CostFinalize\t\n" "TestPrimaryVolumePath1\t19\t\tPrimaryVolumePath set before InstallValidate\t\n" "TestPrimaryVolumeSpaceAvailable1\t19\t\tPrimaryVolumeSpaceAvailable not set before InstallValidate\t\n" "TestPrimaryVolumeSpaceRequired1\t19\t\tPrimaryVolumeSpaceRequired not set before InstallValidate\t\n" "TestPrimaryVolumeSpaceRemaining1\t19\t\tPrimaryVolumeSpaceRemaining not set before InstallValidate\t\n" "TestPrimaryVolumePath2\t19\t\tPrimaryVolumePath not set after InstallValidate\t\n" "TestPrimaryVolumeSpaceAvailable2\t19\t\tPrimaryVolumeSpaceAvailable not set after InstallValidate\t\n" "TestPrimaryVolumeSpaceRequired2\t19\t\tPrimaryVolumeSpaceRequired not set after InstallValidate\t\n" "TestPrimaryVolumeSpaceRemaining2\t19\t\tPrimaryVolumeSpaceRemaining not set after InstallValidate\t\n"; static const char vp_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "CostInitialize\t\t200\n" "FileCost\t\t300\n" "TestPrimaryVolumePath0\tPrimaryVolumePath AND NOT REMOVE\t400\n" "TestPrimaryVolumeSpaceAvailable0\tPrimaryVolumeSpaceAvailable AND NOT REMOVE\t500\n" "TestPrimaryVolumeSpaceRequired0\tPrimaryVolumeSpaceRequired AND NOT REMOVE\t510\n" "TestPrimaryVolumeSpaceRemaining0\tPrimaryVolumeSpaceRemaining AND NOT REMOVE\t520\n" "CostFinalize\t\t600\n" "TestPrimaryVolumePath1\tPrimaryVolumePath AND NOT REMOVE\t600\n" "TestPrimaryVolumeSpaceAvailable1\tNOT PrimaryVolumeSpaceAvailable AND NOT REMOVE\t800\n" "TestPrimaryVolumeSpaceRequired1\tNOT PrimaryVolumeSpaceRequired AND NOT REMOVE\t810\n" "TestPrimaryVolumeSpaceRemaining1\tNOT PrimaryVolumeSpaceRemaining AND NOT REMOVE\t820\n" "InstallValidate\t\t900\n" "TestPrimaryVolumePath2\tNOT PrimaryVolumePath AND NOT REMOVE\t1000\n" "TestPrimaryVolumeSpaceAvailable2\tNOT PrimaryVolumeSpaceAvailable AND NOT REMOVE\t1100\n" "TestPrimaryVolumeSpaceRequired2\tNOT PrimaryVolumeSpaceRequired AND NOT REMOVE\t1110\n" "TestPrimaryVolumeSpaceRemaining2\tNOT PrimaryVolumeSpaceRemaining AND NOT REMOVE\t1120\n" "InstallInitialize\t\t1200\n" "ProcessComponents\t\t1300\n" "RemoveFiles\t\t1400\n" "InstallFiles\t\t1500\n" "RegisterProduct\t\t1600\n" "PublishFeatures\t\t1700\n" "PublishProduct\t\t1800\n" "InstallFinalize\t\t1900\n"; static const char shc_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "INSTALLLEVEL\t3\n" "ProductCode\t{5CD99CD0-69C7-409B-9905-82DD743CC840}\n" "ProductName\tMSITEST\n" "ProductVersion\t1.1.1\n" "MSIFASTINSTALL\t1\n"; static const char shc2_property_dat[] = "Property\tValue\n" "s72\tl0\n" "Property\tProperty\n" "INSTALLLEVEL\t3\n" "ProductCode\t{4CEFADE5-DAFB-4C21-8EF2-4ED4F139F340}\n" "ProductName\tMSITEST2\n" "ProductVersion\t1.1.1\n" "MSIFASTINSTALL\t1\n"; static const char shc_file_dat[] = "File\tComponent_\tFileName\tFileSize\tVersion\tLanguage\tAttributes\tSequence\n" "s72\ts72\tl255\ti4\tS72\tS20\tI2\ti2\n" "File\tFile\n" "sharedcomponent\tsharedcomponent\tsharedcomponent.txt\t1000\t\t\t8192\t1\n"; static const char shc_feature_dat[] = "Feature\tFeature_Parent\tTitle\tDescription\tDisplay\tLevel\tDirectory_\tAttributes\n" "s38\tS38\tL64\tL255\tI2\ti2\tS72\ti2\n" "Feature\tFeature\n" "feature\t\t\t\t1\t2\tMSITESTDIR\t0\n"; static const char shc_feature_comp_dat[] = "Feature_\tComponent_\n" "s38\ts72\n" "FeatureComponents\tFeature_\tComponent_\n" "feature\tsharedcomponent\n"; static const char shc_component_dat[] = "Component\tComponentId\tDirectory_\tAttributes\tCondition\tKeyPath\n" "s72\tS38\ts72\ti2\tS255\tS72\n" "Component\tComponent\n" "sharedcomponent\t{900A4ACB-DC6F-4795-A04B-81B530183D41}\tMSITESTDIR\t0\t\tsharedcomponent\n"; static const char shc_custom_action_dat[] = "Action\tType\tSource\tTarget\tISComments\n" "s72\ti2\tS64\tS0\tS255\n" "CustomAction\tAction\n" "TestComponentAction\t19\t\twrong component action on install\t\n"; static const char shc_install_exec_seq_dat[] = "Action\tCondition\tSequence\n" "s72\tS255\tI2\n" "InstallExecuteSequence\tAction\n" "LaunchConditions\t\t100\n" "CostInitialize\t\t200\n" "FileCost\t\t300\n" "CostFinalize\t\t600\n" "InstallValidate\t\t900\n" "InstallInitialize\t\t1200\n" "ProcessComponents\t\t1300\n" "RemoveFiles\t\t1400\n" "InstallFiles\t\t1500\n" "TestComponentAction\tNOT REMOVE AND ($sharedcomponent <> 3)\t1600\n" "RegisterProduct\t\t1700\n" "PublishFeatures\t\t1800\n" "PublishProduct\t\t1900\n" "InstallFinalize\t\t2000\n"; typedef struct _msi_table { const CHAR *filename; const CHAR *data; int size; } msi_table; #define ADD_TABLE(x) {#x".idt", x##_dat, sizeof(x##_dat)} static const msi_table tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table sc_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(property), ADD_TABLE(shortcut) }; static const msi_table ps_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(property), ADD_TABLE(condition) }; static const msi_table up_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(up_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up2_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(up2_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up3_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(up3_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up4_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(media), ADD_TABLE(property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up5_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(media), ADD_TABLE(up_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up6_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(media), ADD_TABLE(up2_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table up7_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(media), ADD_TABLE(up3_property), ADD_TABLE(registry), ADD_TABLE(service_install), ADD_TABLE(service_control) }; static const msi_table cc_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(cc_media), ADD_TABLE(property), }; static const msi_table cc2_tables[] = { ADD_TABLE(cc2_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(cc_media), ADD_TABLE(property), }; static const msi_table cc3_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(cc3_media), ADD_TABLE(property), }; static const msi_table co_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(co_file), ADD_TABLE(install_exec_seq), ADD_TABLE(co_media), ADD_TABLE(property), }; static const msi_table co2_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(co2_media), ADD_TABLE(property), }; static const msi_table mm_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(mm_file), ADD_TABLE(install_exec_seq), ADD_TABLE(mm_media), ADD_TABLE(property), }; static const msi_table ss_tables[] = { ADD_TABLE(cc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(ss_media), ADD_TABLE(property), }; static const msi_table ui_tables[] = { ADD_TABLE(ui_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cc_feature_comp), ADD_TABLE(cc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(ui_install_ui_seq), ADD_TABLE(ui_custom_action), ADD_TABLE(cc_media), ADD_TABLE(property), }; static const msi_table rof_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rof_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table rofc_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rofc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rofc_media), ADD_TABLE(property), }; static const msi_table sdp_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rof_file), ADD_TABLE(sdp_install_exec_seq), ADD_TABLE(sdp_custom_action), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table cie_tables[] = { ADD_TABLE(cie_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cie_feature_comp), ADD_TABLE(cie_file), ADD_TABLE(install_exec_seq), ADD_TABLE(cie_media), ADD_TABLE(property), }; static const msi_table tp_tables[] = { ADD_TABLE(tp_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table cwd_tables[] = { ADD_TABLE(cwd_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table adm_tables[] = { ADD_TABLE(adm_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), ADD_TABLE(adm_custom_action), ADD_TABLE(adm_admin_exec_seq), }; static const msi_table amp_tables[] = { ADD_TABLE(amp_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table mc_tables[] = { ADD_TABLE(mc_component), ADD_TABLE(directory), ADD_TABLE(cc_feature), ADD_TABLE(cie_feature_comp), ADD_TABLE(mc_file), ADD_TABLE(install_exec_seq), ADD_TABLE(mc_media), ADD_TABLE(property), ADD_TABLE(mc_file_hash), }; static const msi_table sf_tables[] = { ADD_TABLE(wrv_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table ca51_tables[] = { ADD_TABLE(ca51_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(ca51_install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), ADD_TABLE(ca51_custom_action), }; static const msi_table is_tables[] = { ADD_TABLE(is_component), ADD_TABLE(directory), ADD_TABLE(is_feature), ADD_TABLE(is_feature_comp), ADD_TABLE(is_file), ADD_TABLE(install_exec_seq), ADD_TABLE(is_media), ADD_TABLE(property), }; static const msi_table sp_tables[] = { ADD_TABLE(sp_component), ADD_TABLE(sp_directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table mcp_tables[] = { ADD_TABLE(mcp_component), ADD_TABLE(directory), ADD_TABLE(mcp_feature), ADD_TABLE(mcp_feature_comp), ADD_TABLE(mcp_file), ADD_TABLE(rem_install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table ai_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(ai_file), ADD_TABLE(install_exec_seq), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table pc_tables[] = { ADD_TABLE(ca51_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(ci2_feature_comp), ADD_TABLE(ci2_file), ADD_TABLE(install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property) }; static const msi_table ip_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(ip_install_exec_seq), ADD_TABLE(ip_custom_action), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table aup_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(aup_install_exec_seq), ADD_TABLE(aup_custom_action), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table aup2_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(aup2_install_exec_seq), ADD_TABLE(aup_custom_action), ADD_TABLE(media), ADD_TABLE(aup_property) }; static const msi_table aup3_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(aup2_install_exec_seq), ADD_TABLE(aup_custom_action), ADD_TABLE(media), ADD_TABLE(aup2_property) }; static const msi_table aup4_tables[] = { ADD_TABLE(component), ADD_TABLE(directory), ADD_TABLE(feature), ADD_TABLE(feature_comp), ADD_TABLE(file), ADD_TABLE(aup3_install_exec_seq), ADD_TABLE(aup_custom_action), ADD_TABLE(media), ADD_TABLE(aup2_property) }; static const msi_table fiu_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rof_file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property), }; static const msi_table fiuc_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rofc_file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(rofc_media), ADD_TABLE(property), }; static const msi_table fo_tables[] = { ADD_TABLE(directory), ADD_TABLE(fo_file), ADD_TABLE(fo_component), ADD_TABLE(fo_feature), ADD_TABLE(fo_condition), ADD_TABLE(fo_feature_comp), ADD_TABLE(fo_custom_action), ADD_TABLE(fo_install_exec_seq), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table icon_base_tables[] = { ADD_TABLE(ci_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rof_file), ADD_TABLE(pp_install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(icon_property), }; static const msi_table pv_tables[] = { ADD_TABLE(rof_component), ADD_TABLE(directory), ADD_TABLE(rof_feature), ADD_TABLE(rof_feature_comp), ADD_TABLE(rof_file), ADD_TABLE(pv_install_exec_seq), ADD_TABLE(rof_media), ADD_TABLE(property) }; static const msi_table uc_tables[] = { ADD_TABLE(directory), ADD_TABLE(uc_component), ADD_TABLE(uc_feature), ADD_TABLE(uc_feature_comp), ADD_TABLE(uc_file), ADD_TABLE(uc_install_exec_seq), ADD_TABLE(media), ADD_TABLE(uc_property) }; static const msi_table mixed_tables[] = { ADD_TABLE(directory), ADD_TABLE(mixed_component), ADD_TABLE(mixed_feature), ADD_TABLE(mixed_feature_comp), ADD_TABLE(mixed_install_exec_seq), ADD_TABLE(mixed_registry), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table vp_tables[] = { ADD_TABLE(directory), ADD_TABLE(vp_file), ADD_TABLE(vp_component), ADD_TABLE(vp_feature), ADD_TABLE(vp_feature_comp), ADD_TABLE(vp_custom_action), ADD_TABLE(vp_install_exec_seq), ADD_TABLE(media), ADD_TABLE(property) }; static const msi_table shc_tables[] = { ADD_TABLE(media), ADD_TABLE(directory), ADD_TABLE(shc_file), ADD_TABLE(shc_component), ADD_TABLE(shc_feature), ADD_TABLE(shc_feature_comp), ADD_TABLE(shc_custom_action), ADD_TABLE(shc_install_exec_seq), ADD_TABLE(shc_property) }; static const msi_table shc2_tables[] = { ADD_TABLE(media), ADD_TABLE(directory), ADD_TABLE(shc_file), ADD_TABLE(shc_component), ADD_TABLE(shc_feature), ADD_TABLE(shc_feature_comp), ADD_TABLE(shc_custom_action), ADD_TABLE(shc_install_exec_seq), ADD_TABLE(shc2_property) }; /* cabinet definitions */ /* make the max size large so there is only one cab file */ #define MEDIA_SIZE 0x7FFFFFFF #define FOLDER_THRESHOLD 900000 /* the FCI callbacks */ static void * CDECL mem_alloc(ULONG cb) { return HeapAlloc(GetProcessHeap(), 0, cb); } static void CDECL mem_free(void *memory) { HeapFree(GetProcessHeap(), 0, memory); } static BOOL CDECL get_next_cabinet(PCCAB pccab, ULONG cbPrevCab, void *pv) { sprintf(pccab->szCab, pv, pccab->iCab); return TRUE; } static LONG CDECL progress(UINT typeStatus, ULONG cb1, ULONG cb2, void *pv) { return 0; } static int CDECL file_placed(PCCAB pccab, char *pszFile, LONG cbFile, BOOL fContinuation, void *pv) { return 0; } static INT_PTR CDECL fci_open(char *pszFile, int oflag, int pmode, int *err, void *pv) { HANDLE handle; DWORD dwAccess = 0; DWORD dwShareMode = 0; DWORD dwCreateDisposition = OPEN_EXISTING; dwAccess = GENERIC_READ | GENERIC_WRITE; /* FILE_SHARE_DELETE is not supported by Windows Me/98/95 */ dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; if (GetFileAttributesA(pszFile) != INVALID_FILE_ATTRIBUTES) dwCreateDisposition = OPEN_EXISTING; else dwCreateDisposition = CREATE_NEW; handle = CreateFileA(pszFile, dwAccess, dwShareMode, NULL, dwCreateDisposition, 0, NULL); ok(handle != INVALID_HANDLE_VALUE, "Failed to CreateFile %s\n", pszFile); return (INT_PTR)handle; } static UINT CDECL fci_read(INT_PTR hf, void *memory, UINT cb, int *err, void *pv) { HANDLE handle = (HANDLE)hf; DWORD dwRead; BOOL res; res = ReadFile(handle, memory, cb, &dwRead, NULL); ok(res, "Failed to ReadFile\n"); return dwRead; } static UINT CDECL fci_write(INT_PTR hf, void *memory, UINT cb, int *err, void *pv) { HANDLE handle = (HANDLE)hf; DWORD dwWritten; BOOL res; res = WriteFile(handle, memory, cb, &dwWritten, NULL); ok(res, "Failed to WriteFile\n"); return dwWritten; } static int CDECL fci_close(INT_PTR hf, int *err, void *pv) { HANDLE handle = (HANDLE)hf; ok(CloseHandle(handle), "Failed to CloseHandle\n"); return 0; } static LONG CDECL fci_seek(INT_PTR hf, LONG dist, int seektype, int *err, void *pv) { HANDLE handle = (HANDLE)hf; DWORD ret; ret = SetFilePointer(handle, dist, NULL, seektype); ok(ret != INVALID_SET_FILE_POINTER, "Failed to SetFilePointer\n"); return ret; } static int CDECL fci_delete(char *pszFile, int *err, void *pv) { BOOL ret = DeleteFileA(pszFile); ok(ret, "Failed to DeleteFile %s\n", pszFile); return 0; } static void init_functionpointers(void) { HMODULE hmsi = GetModuleHandleA("msi.dll"); HMODULE hadvapi32 = GetModuleHandleA("advapi32.dll"); HMODULE hkernel32 = GetModuleHandleA("kernel32.dll"); #define GET_PROC(mod, func) \ p ## func = (void*)GetProcAddress(mod, #func); \ if(!p ## func) \ trace("GetProcAddress(%s) failed\n", #func); GET_PROC(hmsi, MsiQueryComponentStateA); GET_PROC(hmsi, MsiSourceListEnumSourcesA); GET_PROC(hmsi, MsiGetComponentPathExA); GET_PROC(hadvapi32, CheckTokenMembership); GET_PROC(hadvapi32, ConvertSidToStringSidA); GET_PROC(hadvapi32, OpenProcessToken); GET_PROC(hadvapi32, RegDeleteKeyExA) GET_PROC(hkernel32, IsWow64Process) hsrclient = LoadLibraryA("srclient.dll"); GET_PROC(hsrclient, SRRemoveRestorePoint); GET_PROC(hsrclient, SRSetRestorePointA); #undef GET_PROC } static BOOL is_process_limited(void) { SID_IDENTIFIER_AUTHORITY NtAuthority = {SECURITY_NT_AUTHORITY}; PSID Group = NULL; BOOL IsInGroup; HANDLE token; if (!pCheckTokenMembership || !pOpenProcessToken) return FALSE; if (!AllocateAndInitializeSid(&NtAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &Group) || !pCheckTokenMembership(NULL, Group, &IsInGroup)) { trace("Could not check if the current user is an administrator\n"); FreeSid(Group); return FALSE; } FreeSid(Group); if (!IsInGroup) { /* Only administrators have enough privileges for these tests */ return TRUE; } if (pOpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) { BOOL ret; TOKEN_ELEVATION_TYPE type = TokenElevationTypeDefault; DWORD size; ret = GetTokenInformation(token, TokenElevationType, &type, sizeof(type), &size); CloseHandle(token); return (ret && type == TokenElevationTypeLimited); } return FALSE; } static BOOL check_record(MSIHANDLE rec, UINT field, LPCSTR val) { CHAR buffer[0x20]; UINT r; DWORD sz; sz = sizeof buffer; r = MsiRecordGetStringA(rec, field, buffer, &sz); return (r == ERROR_SUCCESS ) && !strcmp(val, buffer); } static BOOL CDECL get_temp_file(char *pszTempName, int cbTempName, void *pv) { LPSTR tempname; tempname = HeapAlloc(GetProcessHeap(), 0, MAX_PATH); GetTempFileNameA(".", "xx", 0, tempname); if (tempname && (strlen(tempname) < (unsigned)cbTempName)) { lstrcpyA(pszTempName, tempname); HeapFree(GetProcessHeap(), 0, tempname); return TRUE; } HeapFree(GetProcessHeap(), 0, tempname); return FALSE; } static INT_PTR CDECL get_open_info(char *pszName, USHORT *pdate, USHORT *ptime, USHORT *pattribs, int *err, void *pv) { BY_HANDLE_FILE_INFORMATION finfo; FILETIME filetime; HANDLE handle; DWORD attrs; BOOL res; handle = CreateFileA(pszName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); ok(handle != INVALID_HANDLE_VALUE, "Failed to CreateFile %s\n", pszName); res = GetFileInformationByHandle(handle, &finfo); ok(res, "Expected GetFileInformationByHandle to succeed\n"); FileTimeToLocalFileTime(&finfo.ftLastWriteTime, &filetime); FileTimeToDosDateTime(&filetime, pdate, ptime); attrs = GetFileAttributesA(pszName); ok(attrs != INVALID_FILE_ATTRIBUTES, "Failed to GetFileAttributes\n"); return (INT_PTR)handle; } static BOOL add_file(HFCI hfci, const char *file, TCOMP compress) { char path[MAX_PATH]; char filename[MAX_PATH]; lstrcpyA(path, CURR_DIR); lstrcatA(path, "\\"); lstrcatA(path, file); lstrcpyA(filename, file); return FCIAddFile(hfci, path, filename, FALSE, get_next_cabinet, progress, get_open_info, compress); } static void set_cab_parameters(PCCAB pCabParams, const CHAR *name, DWORD max_size) { ZeroMemory(pCabParams, sizeof(CCAB)); pCabParams->cb = max_size; pCabParams->cbFolderThresh = FOLDER_THRESHOLD; pCabParams->setID = 0xbeef; pCabParams->iCab = 1; lstrcpyA(pCabParams->szCabPath, CURR_DIR); lstrcatA(pCabParams->szCabPath, "\\"); lstrcpyA(pCabParams->szCab, name); } static void create_cab_file(const CHAR *name, DWORD max_size, const CHAR *files) { CCAB cabParams; LPCSTR ptr; HFCI hfci; ERF erf; BOOL res; set_cab_parameters(&cabParams, name, max_size); hfci = FCICreate(&erf, file_placed, mem_alloc, mem_free, fci_open, fci_read, fci_write, fci_close, fci_seek, fci_delete, get_temp_file, &cabParams, NULL); ok(hfci != NULL, "Failed to create an FCI context\n"); ptr = files; while (*ptr) { res = add_file(hfci, ptr, tcompTYPE_MSZIP); ok(res, "Failed to add file: %s\n", ptr); ptr += lstrlenA(ptr) + 1; } res = FCIFlushCabinet(hfci, FALSE, get_next_cabinet, progress); ok(res, "Failed to flush the cabinet\n"); res = FCIDestroy(hfci); ok(res, "Failed to destroy the cabinet\n"); } static BOOL get_user_dirs(void) { HKEY hkey; DWORD type, size; if (RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders", &hkey)) return FALSE; size = MAX_PATH; if(RegQueryValueExA(hkey, "AppData", 0, &type, (LPBYTE)APP_DATA_DIR, &size)){ RegCloseKey(hkey); return FALSE; } RegCloseKey(hkey); return TRUE; } static BOOL get_system_dirs(void) { HKEY hkey; DWORD type, size; if (RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion", &hkey)) return FALSE; size = MAX_PATH; if (RegQueryValueExA(hkey, "ProgramFilesDir (x86)", 0, &type, (LPBYTE)PROG_FILES_DIR, &size) && RegQueryValueExA(hkey, "ProgramFilesDir", 0, &type, (LPBYTE)PROG_FILES_DIR, &size)) { RegCloseKey(hkey); return FALSE; } size = MAX_PATH; if (RegQueryValueExA(hkey, "CommonFilesDir (x86)", 0, &type, (LPBYTE)COMMON_FILES_DIR, &size) && RegQueryValueExA(hkey, "CommonFilesDir", 0, &type, (LPBYTE)COMMON_FILES_DIR, &size)) { RegCloseKey(hkey); return FALSE; } size = MAX_PATH; if (RegQueryValueExA(hkey, "ProgramFilesDir", 0, &type, (LPBYTE)PROG_FILES_DIR_NATIVE, &size)) { RegCloseKey(hkey); return FALSE; } RegCloseKey(hkey); if(!GetWindowsDirectoryA(WINDOWS_DIR, MAX_PATH)) return FALSE; return TRUE; } static void create_file_data(LPCSTR name, LPCSTR data, DWORD size) { HANDLE file; DWORD written; file = CreateFileA(name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); if (file == INVALID_HANDLE_VALUE) return; WriteFile(file, data, strlen(data), &written, NULL); if (size) { SetFilePointer(file, size, NULL, FILE_BEGIN); SetEndOfFile(file); } CloseHandle(file); } #define create_file(name, size) create_file_data(name, name, size) static void create_test_files(void) { CreateDirectoryA("msitest", NULL); create_file("msitest\\one.txt", 100); CreateDirectoryA("msitest\\first", NULL); create_file("msitest\\first\\two.txt", 100); CreateDirectoryA("msitest\\second", NULL); create_file("msitest\\second\\three.txt", 100); create_file("four.txt", 100); create_file("five.txt", 100); create_cab_file("msitest.cab", MEDIA_SIZE, "four.txt\0five.txt\0"); create_file("msitest\\filename", 100); create_file("msitest\\service.exe", 100); DeleteFileA("four.txt"); DeleteFileA("five.txt"); } static BOOL delete_pf(const CHAR *rel_path, BOOL is_file) { CHAR path[MAX_PATH]; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, rel_path); if (is_file) return DeleteFileA(path); else return RemoveDirectoryA(path); } static BOOL delete_pf_native(const CHAR *rel_path, BOOL is_file) { CHAR path[MAX_PATH]; lstrcpyA(path, PROG_FILES_DIR_NATIVE); lstrcatA(path, "\\"); lstrcatA(path, rel_path); if (is_file) return DeleteFileA(path); else return RemoveDirectoryA(path); } static BOOL delete_cf(const CHAR *rel_path, BOOL is_file) { CHAR path[MAX_PATH]; lstrcpyA(path, COMMON_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, rel_path); if (is_file) return DeleteFileA(path); else return RemoveDirectoryA(path); } static BOOL compare_pf_data(const char *filename, const char *data, DWORD size) { DWORD read; HANDLE handle; BOOL ret = FALSE; char *buffer, path[MAX_PATH]; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, filename); handle = CreateFileA(path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); buffer = HeapAlloc(GetProcessHeap(), 0, size); if (buffer) { ReadFile(handle, buffer, size, &read, NULL); if (read == size && !memcmp(data, buffer, size)) ret = TRUE; HeapFree(GetProcessHeap(), 0, buffer); } CloseHandle(handle); return ret; } static void delete_test_files(void) { DeleteFileA("msitest.msi"); DeleteFileA("msitest.cab"); DeleteFileA("msitest\\second\\three.txt"); DeleteFileA("msitest\\first\\two.txt"); DeleteFileA("msitest\\one.txt"); DeleteFileA("msitest\\service.exe"); DeleteFileA("msitest\\filename"); RemoveDirectoryA("msitest\\second"); RemoveDirectoryA("msitest\\first"); RemoveDirectoryA("msitest"); } static void write_file(const CHAR *filename, const char *data, int data_size) { DWORD size; HANDLE hf = CreateFileA(filename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); WriteFile(hf, data, data_size, &size, NULL); CloseHandle(hf); } static void write_msi_summary_info(MSIHANDLE db, INT version, INT wordcount, const char *template, const char *packagecode) { MSIHANDLE summary; UINT r; r = MsiGetSummaryInformationA(db, NULL, 5, &summary); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_TEMPLATE, VT_LPSTR, 0, NULL, template); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_REVNUMBER, VT_LPSTR, 0, NULL, packagecode); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_PAGECOUNT, VT_I4, version, NULL, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_WORDCOUNT, VT_I4, wordcount, NULL, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_TITLE, VT_LPSTR, 0, NULL, "MSITEST"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); /* write the summary changes back to the stream */ r = MsiSummaryInfoPersist(summary); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); MsiCloseHandle(summary); } #define create_database(name, tables, num_tables) \ create_database_wordcount(name, tables, num_tables, 100, 0, ";1033", \ "{004757CA-5092-49C2-AD20-28E1CE0DF5F2}"); #define create_database_template(name, tables, num_tables, version, template) \ create_database_wordcount(name, tables, num_tables, version, 0, template, \ "{004757CA-5092-49C2-AD20-28E1CE0DF5F2}"); static void create_database_wordcount(const CHAR *name, const msi_table *tables, int num_tables, INT version, INT wordcount, const char *template, const char *packagecode) { MSIHANDLE db; UINT r; WCHAR *nameW; int j, len; len = MultiByteToWideChar( CP_ACP, 0, name, -1, NULL, 0 ); if (!(nameW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) ))) return; MultiByteToWideChar( CP_ACP, 0, name, -1, nameW, len ); r = MsiOpenDatabaseW(nameW, MSIDBOPEN_CREATE, &db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); /* import the tables into the database */ for (j = 0; j < num_tables; j++) { const msi_table *table = &tables[j]; write_file(table->filename, table->data, (table->size - 1) * sizeof(char)); r = MsiDatabaseImportA(db, CURR_DIR, table->filename); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); DeleteFileA(table->filename); } write_msi_summary_info(db, version, wordcount, template, packagecode); r = MsiDatabaseCommit(db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); MsiCloseHandle(db); HeapFree( GetProcessHeap(), 0, nameW ); } static void check_service_is_installed(void) { SC_HANDLE scm, service; BOOL res; scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); ok(scm != NULL, "Failed to open the SC Manager\n"); service = OpenServiceA(scm, "TestService", SC_MANAGER_ALL_ACCESS); ok(service != NULL, "Failed to open TestService\n"); res = DeleteService(service); ok(res, "Failed to delete TestService\n"); CloseServiceHandle(service); CloseServiceHandle(scm); } static BOOL notify_system_change(DWORD event_type, STATEMGRSTATUS *status) { RESTOREPOINTINFOA spec; spec.dwEventType = event_type; spec.dwRestorePtType = APPLICATION_INSTALL; spec.llSequenceNumber = status->llSequenceNumber; lstrcpyA(spec.szDescription, "msitest restore point"); return pSRSetRestorePointA(&spec, status); } static void remove_restore_point(DWORD seq_number) { DWORD res; res = pSRRemoveRestorePoint(seq_number); if (res != ERROR_SUCCESS) trace("Failed to remove the restore point : %08x\n", res); } static LONG delete_key( HKEY key, LPCSTR subkey, REGSAM access ) { if (pRegDeleteKeyExA) return pRegDeleteKeyExA( key, subkey, access, 0 ); return RegDeleteKeyA( key, subkey ); } static void test_MsiInstallProduct(void) { UINT r; CHAR path[MAX_PATH]; LONG res; HKEY hkey; DWORD num, size, type; REGSAM access = KEY_ALL_ACCESS; if (is_process_limited()) { skip("process is limited\n"); return; } if (is_wow64) access |= KEY_WOW64_64KEY; MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); /* szPackagePath is NULL */ r = MsiInstallProductA(NULL, "INSTALL=ALL"); ok(r == ERROR_INVALID_PARAMETER, "Expected ERROR_INVALID_PARAMETER, got %d\n", r); /* both szPackagePath and szCommandLine are NULL */ r = MsiInstallProductA(NULL, NULL); ok(r == ERROR_INVALID_PARAMETER, "Expected ERROR_INVALID_PARAMETER, got %d\n", r); /* szPackagePath is empty */ r = MsiInstallProductA("", "INSTALL=ALL"); ok(r == ERROR_PATH_NOT_FOUND, "Expected ERROR_PATH_NOT_FOUND, got %d\n", r); create_test_files(); create_database(msifile, tables, sizeof(tables) / sizeof(msi_table)); /* install, don't publish */ r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyExA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", 0, access, &hkey); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); size = MAX_PATH; type = REG_SZ; res = RegQueryValueExA(hkey, "Name", NULL, &type, (LPBYTE)path, &size); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); ok(!lstrcmpA(path, "imaname"), "Expected imaname, got %s\n", path); size = MAX_PATH; type = REG_SZ; res = RegQueryValueExA(hkey, "blah", NULL, &type, (LPBYTE)path, &size); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); size = sizeof(num); type = REG_DWORD; res = RegQueryValueExA(hkey, "number", NULL, &type, (LPBYTE)&num, &size); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); ok(num == 314, "Expected 314, got %d\n", num); size = MAX_PATH; type = REG_SZ; res = RegQueryValueExA(hkey, "OrderTestName", NULL, &type, (LPBYTE)path, &size); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); ok(!lstrcmpA(path, "OrderTestValue"), "Expected OrderTestValue, got %s\n", path); check_service_is_installed(); delete_key(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", access); /* not published, reinstall */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); RegDeleteKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest"); create_database(msifile, up_tables, sizeof(up_tables) / sizeof(msi_table)); /* not published, RemovePreviousVersions set */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); RegDeleteKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest"); create_database(msifile, up2_tables, sizeof(up2_tables) / sizeof(msi_table)); /* not published, version number bumped */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); RegDeleteKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest"); create_database(msifile, up3_tables, sizeof(up3_tables) / sizeof(msi_table)); /* not published, RemovePreviousVersions set and version number bumped */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", res); RegDeleteKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest"); create_database(msifile, up4_tables, sizeof(up4_tables) / sizeof(msi_table)); /* install, publish product */ r = MsiInstallProductA(msifile, "PUBLISH_PRODUCT=1"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); create_database(msifile, up4_tables, sizeof(up4_tables) / sizeof(msi_table)); /* published, reinstall */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); create_database(msifile, up5_tables, sizeof(up5_tables) / sizeof(msi_table)); /* published product, RemovePreviousVersions set */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); create_database(msifile, up6_tables, sizeof(up6_tables) / sizeof(msi_table)); /* published product, version number bumped */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); create_database(msifile, up7_tables, sizeof(up7_tables) / sizeof(msi_table)); /* published product, RemovePreviousVersions set and version number bumped */ r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); res = RegOpenKeyA(HKEY_CURRENT_USER, "SOFTWARE\\Wine\\msitest", &hkey); ok(res == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", res); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); error: delete_test_files(); DeleteFileA(msifile); } static void test_MsiSetComponentState(void) { INSTALLSTATE installed, action; MSIHANDLE package; char path[MAX_PATH]; UINT r; create_database(msifile, tables, sizeof(tables) / sizeof(msi_table)); CoInitialize(NULL); lstrcpyA(path, CURR_DIR); lstrcatA(path, "\\"); lstrcatA(path, msifile); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiOpenPackageA(path, &package); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiDoActionA(package, "CostInitialize"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiDoActionA(package, "FileCost"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiDoActionA(package, "CostFinalize"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiGetComponentStateA(package, "dangler", &installed, &action); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(installed == INSTALLSTATE_ABSENT, "Expected INSTALLSTATE_ABSENT, got %d\n", installed); ok(action == INSTALLSTATE_UNKNOWN, "Expected INSTALLSTATE_UNKNOWN, got %d\n", action); r = MsiSetComponentStateA(package, "dangler", INSTALLSTATE_SOURCE); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); MsiCloseHandle(package); error: CoUninitialize(); DeleteFileA(msifile); } static void test_packagecoltypes(void) { MSIHANDLE hdb, view, rec; char path[MAX_PATH]; WCHAR pathW[MAX_PATH]; LPCSTR query; UINT r, count; create_database(msifile, tables, sizeof(tables) / sizeof(msi_table)); CoInitialize(NULL); lstrcpyA(path, CURR_DIR); lstrcatA(path, "\\"); lstrcatA(path, msifile); MultiByteToWideChar( CP_ACP, 0, path, -1, pathW, MAX_PATH ); r = MsiOpenDatabaseW(pathW, MSIDBOPEN_READONLY, &hdb); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); query = "SELECT * FROM `Media`"; r = MsiDatabaseOpenViewA( hdb, query, &view ); ok(r == ERROR_SUCCESS, "MsiDatabaseOpenView failed\n"); r = MsiViewGetColumnInfo( view, MSICOLINFO_NAMES, &rec ); count = MsiRecordGetFieldCount( rec ); ok(r == ERROR_SUCCESS, "MsiViewGetColumnInfo failed\n"); ok(count == 6, "Expected 6, got %d\n", count); ok(check_record(rec, 1, "DiskId"), "wrong column label\n"); ok(check_record(rec, 2, "LastSequence"), "wrong column label\n"); ok(check_record(rec, 3, "DiskPrompt"), "wrong column label\n"); ok(check_record(rec, 4, "Cabinet"), "wrong column label\n"); ok(check_record(rec, 5, "VolumeLabel"), "wrong column label\n"); ok(check_record(rec, 6, "Source"), "wrong column label\n"); MsiCloseHandle(rec); r = MsiViewGetColumnInfo( view, MSICOLINFO_TYPES, &rec ); count = MsiRecordGetFieldCount( rec ); ok(r == ERROR_SUCCESS, "MsiViewGetColumnInfo failed\n"); ok(count == 6, "Expected 6, got %d\n", count); ok(check_record(rec, 1, "i2"), "wrong column label\n"); ok(check_record(rec, 2, "i4"), "wrong column label\n"); ok(check_record(rec, 3, "L64"), "wrong column label\n"); ok(check_record(rec, 4, "S255"), "wrong column label\n"); ok(check_record(rec, 5, "S32"), "wrong column label\n"); ok(check_record(rec, 6, "S72"), "wrong column label\n"); MsiCloseHandle(rec); MsiCloseHandle(view); MsiCloseHandle(hdb); CoUninitialize(); DeleteFileA(msifile); } static void create_cc_test_files(void) { CCAB cabParams; HFCI hfci; ERF erf; static CHAR cab_context[] = "test%d.cab"; BOOL res; create_file("maximus", 500); create_file("augustus", 50000); create_file("tiberius", 500); create_file("caesar", 500); set_cab_parameters(&cabParams, "test1.cab", 40000); hfci = FCICreate(&erf, file_placed, mem_alloc, mem_free, fci_open, fci_read, fci_write, fci_close, fci_seek, fci_delete, get_temp_file, &cabParams, cab_context); ok(hfci != NULL, "Failed to create an FCI context\n"); res = add_file(hfci, "maximus", tcompTYPE_NONE); ok(res, "Failed to add file maximus\n"); res = add_file(hfci, "augustus", tcompTYPE_NONE); ok(res, "Failed to add file augustus\n"); res = add_file(hfci, "tiberius", tcompTYPE_NONE); ok(res, "Failed to add file tiberius\n"); res = FCIFlushCabinet(hfci, FALSE, get_next_cabinet, progress); ok(res, "Failed to flush the cabinet\n"); res = FCIDestroy(hfci); ok(res, "Failed to destroy the cabinet\n"); create_cab_file("test3.cab", MEDIA_SIZE, "caesar\0"); DeleteFileA("maximus"); DeleteFileA("augustus"); DeleteFileA("tiberius"); DeleteFileA("caesar"); } static void delete_cab_files(void) { SHFILEOPSTRUCTA shfl; CHAR path[MAX_PATH+10]; lstrcpyA(path, CURR_DIR); lstrcatA(path, "\\*.cab"); path[strlen(path) + 1] = '\0'; shfl.hwnd = NULL; shfl.wFunc = FO_DELETE; shfl.pFrom = path; shfl.pTo = NULL; shfl.fFlags = FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_NORECURSION | FOF_SILENT; SHFileOperationA(&shfl); } static void test_continuouscabs(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } create_cc_test_files(); create_database(msifile, cc_tables, sizeof(cc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } else { ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); } delete_cab_files(); DeleteFileA(msifile); create_cc_test_files(); create_database(msifile, cc2_tables, sizeof(cc2_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); } else { ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(delete_pf("msitest\\tiberius", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); } delete_cab_files(); DeleteFileA(msifile); /* Tests to show that only msi cab filename is taken in case of mismatch with the one given by previous cab */ /* Filename from cab is right and the one from msi is wrong */ create_cc_test_files(); create_database(msifile, cc3_tables, sizeof(cc3_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); } else { ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); todo_wine ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(!delete_pf("msitest\\caesar", TRUE), "File installed\n"); todo_wine ok(!delete_pf("msitest\\maximus", TRUE), "File installed\n"); todo_wine ok(!delete_pf("msitest", FALSE), "Directory created\n"); } delete_cab_files(); DeleteFileA(msifile); /* Filename from msi is right and the one from cab is wrong */ create_cc_test_files(); ok(MoveFileA("test2.cab", "test2_.cab"), "Cannot rename test2.cab to test2_.cab\n"); create_database(msifile, cc3_tables, sizeof(cc3_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); } else { ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); } error: delete_cab_files(); DeleteFileA(msifile); } static void test_caborder(void) { UINT r; create_file("imperator", 100); create_file("maximus", 500); create_file("augustus", 50000); create_file("caesar", 500); create_database(msifile, cc_tables, sizeof(cc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); create_cab_file("test1.cab", MEDIA_SIZE, "maximus\0"); create_cab_file("test2.cab", MEDIA_SIZE, "augustus\0"); create_cab_file("test3.cab", MEDIA_SIZE, "caesar\0"); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File is installed\n"); ok(!delete_pf("msitest\\caesar", TRUE), "File is installed\n"); todo_wine { ok(!delete_pf("msitest\\maximus", TRUE), "File is installed\n"); ok(!delete_pf("msitest", FALSE), "Directory is created\n"); } delete_cab_files(); create_cab_file("test1.cab", MEDIA_SIZE, "imperator\0"); create_cab_file("test2.cab", MEDIA_SIZE, "maximus\0augustus\0"); create_cab_file("test3.cab", MEDIA_SIZE, "caesar\0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "File is installed\n"); ok(!delete_pf("msitest\\augustus", TRUE), "File is installed\n"); ok(!delete_pf("msitest\\caesar", TRUE), "File is installed\n"); ok(!delete_pf("msitest", FALSE), "Directory is created\n"); delete_cab_files(); DeleteFileA(msifile); create_cc_test_files(); create_database(msifile, co_tables, sizeof(co_tables) / sizeof(msi_table)); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(!delete_pf("msitest\\caesar", TRUE), "File is installed\n"); ok(!delete_pf("msitest", FALSE), "Directory is created\n"); todo_wine { ok(!delete_pf("msitest\\augustus", TRUE), "File is installed\n"); ok(!delete_pf("msitest\\maximus", TRUE), "File is installed\n"); } delete_cab_files(); DeleteFileA(msifile); create_cc_test_files(); create_database(msifile, co2_tables, sizeof(co2_tables) / sizeof(msi_table)); r = MsiInstallProductA(msifile, NULL); ok(!delete_pf("msitest\\caesar", TRUE), "File is installed\n"); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); todo_wine { ok(!delete_pf("msitest\\augustus", TRUE), "File is installed\n"); ok(!delete_pf("msitest\\maximus", TRUE), "File is installed\n"); ok(!delete_pf("msitest", FALSE), "Directory is created\n"); } error: delete_cab_files(); DeleteFileA("imperator"); DeleteFileA("maximus"); DeleteFileA("augustus"); DeleteFileA("caesar"); DeleteFileA(msifile); } static void test_mixedmedia(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\maximus", 500); create_file("msitest\\augustus", 500); create_file("caesar", 500); create_database(msifile, mm_tables, sizeof(mm_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); create_cab_file("test1.cab", MEDIA_SIZE, "caesar\0"); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ DeleteFileA("msitest\\maximus"); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); DeleteFileA("caesar"); DeleteFileA("test1.cab"); DeleteFileA(msifile); } static void test_samesequence(void) { UINT r; create_cc_test_files(); create_database(msifile, ss_tables, sizeof(ss_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_FAILURE) { win_skip("unprivileged user?\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); if (r == ERROR_SUCCESS) { ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); } error: delete_cab_files(); DeleteFileA(msifile); } static void test_uiLevelFlags(void) { UINT r; create_cc_test_files(); create_database(msifile, ui_tables, sizeof(ui_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE | INSTALLUILEVEL_SOURCERESONLY, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_FAILURE) { win_skip("unprivileged user?\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); if (r == ERROR_SUCCESS) { ok(!delete_pf("msitest\\maximus", TRUE), "UI install occurred, but execute-only was requested.\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); } error: delete_cab_files(); DeleteFileA(msifile); } static BOOL file_matches(LPSTR path) { CHAR buf[MAX_PATH]; HANDLE file; DWORD size; file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); ZeroMemory(buf, MAX_PATH); ReadFile(file, buf, 15, &size, NULL); CloseHandle(file); return !lstrcmpA(buf, "msitest\\maximus"); } static void test_readonlyfile(void) { UINT r; DWORD size; HANDLE file; CHAR path[MAX_PATH]; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\maximus", 500); create_database(msifile, rof_tables, sizeof(rof_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest"); CreateDirectoryA(path, NULL); lstrcatA(path, "\\maximus"); file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_READONLY, NULL); WriteFile(file, "readonlyfile", strlen("readonlyfile"), &size, NULL); CloseHandle(file); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(file_matches(path), "Expected file to be overwritten\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ DeleteFileA("msitest\\maximus"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); } static void test_readonlyfile_cab(void) { UINT r; DWORD size; HANDLE file; CHAR path[MAX_PATH]; CHAR buf[16]; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("maximus", 500); create_cab_file("test1.cab", MEDIA_SIZE, "maximus\0"); DeleteFileA("maximus"); create_database(msifile, rofc_tables, sizeof(rofc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest"); CreateDirectoryA(path, NULL); lstrcatA(path, "\\maximus"); file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_READONLY, NULL); WriteFile(file, "readonlyfile", strlen("readonlyfile"), &size, NULL); CloseHandle(file); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); memset( buf, 0, sizeof(buf) ); if ((file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL)) != INVALID_HANDLE_VALUE) { ReadFile(file, buf, sizeof(buf) - 1, &size, NULL); CloseHandle(file); } ok(!memcmp( buf, "maximus", sizeof("maximus")-1 ), "Expected file to be overwritten, got '%s'\n", buf); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ delete_cab_files(); DeleteFileA("msitest\\maximus"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); } static void test_setdirproperty(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\maximus", 500); create_database(msifile, sdp_tables, sizeof(sdp_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_cf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_cf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ DeleteFileA(msifile); DeleteFileA("msitest\\maximus"); RemoveDirectoryA("msitest"); } static void test_cabisextracted(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\gaius", 500); create_file("maximus", 500); create_file("augustus", 500); create_file("caesar", 500); create_cab_file("test1.cab", MEDIA_SIZE, "maximus\0"); create_cab_file("test2.cab", MEDIA_SIZE, "augustus\0"); create_cab_file("test3.cab", MEDIA_SIZE, "caesar\0"); create_database(msifile, cie_tables, sizeof(cie_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(delete_pf("msitest\\gaius", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ delete_cab_files(); DeleteFileA(msifile); DeleteFileA("maximus"); DeleteFileA("augustus"); DeleteFileA("caesar"); DeleteFileA("msitest\\gaius"); RemoveDirectoryA("msitest"); } static BOOL file_exists(LPCSTR file) { return GetFileAttributesA(file) != INVALID_FILE_ATTRIBUTES; } static BOOL pf_exists(LPCSTR file) { CHAR path[MAX_PATH]; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, file); return file_exists(path); } static void delete_pfmsitest_files(void) { SHFILEOPSTRUCTA shfl; CHAR path[MAX_PATH+11]; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest\\*"); path[strlen(path) + 1] = '\0'; shfl.hwnd = NULL; shfl.wFunc = FO_DELETE; shfl.pFrom = path; shfl.pTo = NULL; shfl.fFlags = FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_NORECURSION | FOF_SILENT | FOF_NOERRORUI; SHFileOperationA(&shfl); lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest"); RemoveDirectoryA(path); } static UINT run_query(MSIHANDLE hdb, MSIHANDLE hrec, const char *query) { MSIHANDLE hview = 0; UINT r; r = MsiDatabaseOpenViewA(hdb, query, &hview); if(r != ERROR_SUCCESS) return r; r = MsiViewExecute(hview, hrec); if(r == ERROR_SUCCESS) r = MsiViewClose(hview); MsiCloseHandle(hview); return r; } static void set_transform_summary_info(void) { UINT r; MSIHANDLE suminfo = 0; /* build summary info */ r = MsiGetSummaryInformationA(0, mstfile, 3, &suminfo); ok(r == ERROR_SUCCESS , "Failed to open summaryinfo\n"); r = MsiSummaryInfoSetPropertyA(suminfo, PID_TITLE, VT_LPSTR, 0, NULL, "MSITEST"); ok(r == ERROR_SUCCESS, "Failed to set summary info\n"); r = MsiSummaryInfoSetPropertyA(suminfo, PID_REVNUMBER, VT_LPSTR, 0, NULL, "{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}1.1.1;" "{7DF88A48-996F-4EC8-A022-BF956F9B2CBB}1.1.1;" "{4C0EAA15-0264-4E5A-8758-609EF142B92D}"); ok(r == ERROR_SUCCESS , "Failed to set summary info\n"); r = MsiSummaryInfoSetPropertyA(suminfo, PID_PAGECOUNT, VT_I4, 100, NULL, NULL); ok(r == ERROR_SUCCESS, "Failed to set summary info\n"); r = MsiSummaryInfoPersist(suminfo); ok(r == ERROR_SUCCESS , "Failed to make summary info persist\n"); r = MsiCloseHandle(suminfo); ok(r == ERROR_SUCCESS , "Failed to close suminfo\n"); } static void generate_transform(void) { MSIHANDLE hdb1, hdb2; LPCSTR query; UINT r; /* start with two identical databases */ CopyFileA(msifile, msifile2, FALSE); r = MsiOpenDatabaseW(msifile2W, MSIDBOPEN_TRANSACT, &hdb1); ok(r == ERROR_SUCCESS , "Failed to create database\n"); r = MsiDatabaseCommit(hdb1); ok(r == ERROR_SUCCESS , "Failed to commit database\n"); r = MsiOpenDatabaseW(msifileW, MSIDBOPEN_READONLY, &hdb2); ok(r == ERROR_SUCCESS , "Failed to create database\n"); query = "INSERT INTO `Property` ( `Property`, `Value` ) VALUES ( 'prop', 'val' )"; r = run_query(hdb1, 0, query); ok(r == ERROR_SUCCESS, "failed to add property\n"); /* database needs to be committed */ MsiDatabaseCommit(hdb1); r = MsiDatabaseGenerateTransformA(hdb1, hdb2, mstfile, 0, 0); ok(r == ERROR_SUCCESS, "return code %d, should be ERROR_SUCCESS\n", r); r = MsiCreateTransformSummaryInfoA(hdb2, hdb2, mstfile, 0, 0); todo_wine ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", r); MsiCloseHandle(hdb1); MsiCloseHandle(hdb2); } /* data for generating a transform */ /* tables transform names - encoded as they would be in an msi database file */ static const WCHAR name1[] = { 0x4840, 0x3f3f, 0x4577, 0x446c, 0x3b6a, 0x45e4, 0x4824, 0 }; /* _StringData */ static const WCHAR name2[] = { 0x4840, 0x3f3f, 0x4577, 0x446c, 0x3e6a, 0x44b2, 0x482f, 0 }; /* _StringPool */ static const WCHAR name3[] = { 0x4840, 0x4559, 0x44f2, 0x4568, 0x4737, 0 }; /* Property */ /* data in each table */ static const char data1[] = /* _StringData */ "propval"; /* all the strings squashed together */ static const WCHAR data2[] = { /* _StringPool */ /* len, refs */ 0, 0, /* string 0 '' */ 4, 1, /* string 1 'prop' */ 3, 1, /* string 2 'val' */ }; static const WCHAR data3[] = { /* Property */ 0x0201, 0x0001, 0x0002, }; static const struct { LPCWSTR name; const void *data; DWORD size; } table_transform_data[] = { { name1, data1, sizeof data1 - 1 }, { name2, data2, sizeof data2 }, { name3, data3, sizeof data3 }, }; #define NUM_TRANSFORM_TABLES (sizeof table_transform_data/sizeof table_transform_data[0]) static void generate_transform_manual(void) { IStorage *stg = NULL; IStream *stm; WCHAR name[0x20]; HRESULT r; DWORD i, count; const DWORD mode = STGM_CREATE|STGM_READWRITE|STGM_DIRECT|STGM_SHARE_EXCLUSIVE; const CLSID CLSID_MsiTransform = { 0xc1082,0,0,{0xc0,0,0,0,0,0,0,0x46}}; MultiByteToWideChar(CP_ACP, 0, mstfile, -1, name, 0x20); r = StgCreateDocfile(name, mode, 0, &stg); ok(r == S_OK, "failed to create storage\n"); if (!stg) return; r = IStorage_SetClass(stg, &CLSID_MsiTransform); ok(r == S_OK, "failed to set storage type\n"); for (i=0; i<NUM_TRANSFORM_TABLES; i++) { r = IStorage_CreateStream(stg, table_transform_data[i].name, STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm); if (FAILED(r)) { ok(0, "failed to create stream %08x\n", r); continue; } r = IStream_Write(stm, table_transform_data[i].data, table_transform_data[i].size, &count); if (FAILED(r) || count != table_transform_data[i].size) ok(0, "failed to write stream\n"); IStream_Release(stm); } IStorage_Release(stg); set_transform_summary_info(); } static void test_transformprop(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, tp_tables, sizeof(tp_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory created\n"); if (0) generate_transform(); else generate_transform_manual(); r = MsiInstallProductA(msifile, "TRANSFORMS=winetest.mst"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: /* Delete the files in the temp (current) folder */ DeleteFileA(msifile); DeleteFileA(msifile2); DeleteFileA(mstfile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); } static void test_currentworkingdir(void) { UINT r; CHAR drive[MAX_PATH], path[MAX_PATH]; LPSTR ptr; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, cwd_tables, sizeof(cwd_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); CreateDirectoryA("diffdir", NULL); SetCurrentDirectoryA("diffdir"); sprintf(path, "..\\%s", msifile); r = MsiInstallProductA(path, NULL); todo_wine { ok(r == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory created\n"); } sprintf(path, "%s\\%s", CURR_DIR, msifile); r = MsiInstallProductA(path, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); lstrcpyA(drive, CURR_DIR); drive[2] = '\\'; drive[3] = '\0'; SetCurrentDirectoryA(drive); lstrcpyA(path, CURR_DIR); if (path[lstrlenA(path) - 1] != '\\') lstrcatA(path, "\\"); lstrcatA(path, msifile); ptr = strchr(path, ':'); ptr +=2; r = MsiInstallProductA(ptr, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: SetCurrentDirectoryA(CURR_DIR); DeleteFileA(msifile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); RemoveDirectoryA("diffdir"); } static void set_admin_summary_info(const WCHAR *name) { MSIHANDLE db, summary; UINT r; r = MsiOpenDatabaseW(name, MSIDBOPEN_DIRECT, &db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiGetSummaryInformationA(db, NULL, 1, &summary); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiSummaryInfoSetPropertyA(summary, PID_WORDCOUNT, VT_I4, 5, NULL, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); /* write the summary changes back to the stream */ r = MsiSummaryInfoPersist(summary); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); MsiCloseHandle(summary); r = MsiDatabaseCommit(db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); MsiCloseHandle(db); } static void test_admin(void) { UINT r; CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, adm_tables, sizeof(adm_tables) / sizeof(msi_table)); set_admin_summary_info(msifileW); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory created\n"); ok(!DeleteFileA("c:\\msitest\\augustus"), "File installed\n"); ok(!RemoveDirectoryA("c:\\msitest"), "File installed\n"); r = MsiInstallProductA(msifile, "ACTION=ADMIN"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory created\n"); todo_wine { ok(DeleteFileA("c:\\msitest\\augustus"), "File not installed\n"); ok(RemoveDirectoryA("c:\\msitest"), "File not installed\n"); } error: DeleteFileA(msifile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); } static void set_admin_property_stream(LPCSTR file) { IStorage *stg; IStream *stm; WCHAR fileW[MAX_PATH]; HRESULT hr; DWORD count; const DWORD mode = STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE; /* AdminProperties */ static const WCHAR stmname[] = {0x41ca,0x4330,0x3e71,0x44b5,0x4233,0x45f5,0x422c,0x4836,0}; static const WCHAR data[] = {'M','Y','P','R','O','P','=','2','7','1','8',' ', 'M','y','P','r','o','p','=','4','2',0}; MultiByteToWideChar(CP_ACP, 0, file, -1, fileW, MAX_PATH); hr = StgOpenStorage(fileW, NULL, mode, NULL, 0, &stg); ok(hr == S_OK, "Expected S_OK, got %d\n", hr); if (!stg) return; hr = IStorage_CreateStream(stg, stmname, STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm); ok(hr == S_OK, "Expected S_OK, got %d\n", hr); hr = IStream_Write(stm, data, sizeof(data), &count); ok(hr == S_OK, "Expected S_OK, got %d\n", hr); IStream_Release(stm); IStorage_Release(stg); } static void test_adminprops(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, amp_tables, sizeof(amp_tables) / sizeof(msi_table)); set_admin_summary_info(msifileW); set_admin_property_stream(msifile); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory created\n"); error: DeleteFileA(msifile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); } static void create_pf_data(LPCSTR file, LPCSTR data, BOOL is_file) { CHAR path[MAX_PATH]; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, file); if (is_file) create_file_data(path, data, 500); else CreateDirectoryA(path, NULL); } #define create_pf(file, is_file) create_pf_data(file, file, is_file) static void test_missingcab(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_file("maximus", 500); create_file("tiberius", 500); create_database(msifile, mc_tables, sizeof(mc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); create_cab_file("test1.cab", MEDIA_SIZE, "maximus\0"); create_cab_file("test4.cab", MEDIA_SIZE, "tiberius\0"); create_pf("msitest", FALSE); create_pf_data("msitest\\caesar", "abcdefgh", TRUE); create_pf_data("msitest\\tiberius", "abcdefgh", TRUE); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not installed\n"); ok(delete_pf("msitest\\caesar", TRUE), "File not installed\n"); ok(compare_pf_data("msitest\\tiberius", "abcdefgh", sizeof("abcdefgh")), "Wrong file contents\n"); ok(delete_pf("msitest\\tiberius", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\gaius", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); create_pf("msitest", FALSE); create_pf_data("msitest\\caesar", "abcdefgh", TRUE); create_pf_data("msitest\\tiberius", "abcdefgh", TRUE); create_pf("msitest\\gaius", TRUE); r = MsiInstallProductA(msifile, "GAIUS=1"); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); todo_wine { ok(!delete_pf("msitest\\maximus", TRUE), "File installed\n"); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); } ok(delete_pf("msitest\\caesar", TRUE), "File removed\n"); ok(compare_pf_data("msitest\\tiberius", "abcdefgh", sizeof("abcdefgh")), "Wrong file contents\n"); ok(delete_pf("msitest\\tiberius", TRUE), "File removed\n"); ok(delete_pf("msitest\\gaius", TRUE), "File removed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: delete_pf("msitest", FALSE); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); DeleteFileA("maximus"); DeleteFileA("tiberius"); DeleteFileA("test1.cab"); DeleteFileA("test4.cab"); DeleteFileA(msifile); } static void test_sourcefolder(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("augustus", 500); create_database(msifile, sf_tables, sizeof(sf_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); todo_wine { ok(!delete_pf("msitest", FALSE), "Directory created\n"); } RemoveDirectoryA("msitest"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(!delete_pf("msitest\\augustus", TRUE), "File installed\n"); todo_wine { ok(!delete_pf("msitest", FALSE), "Directory created\n"); } error: DeleteFileA(msifile); DeleteFileA("augustus"); } static void test_customaction51(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, ca51_tables, sizeof(ca51_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory created\n"); error: DeleteFileA(msifile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); } static void test_installstate(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\alpha", 500); create_file("msitest\\beta", 500); create_file("msitest\\gamma", 500); create_file("msitest\\theta", 500); create_file("msitest\\delta", 500); create_file("msitest\\epsilon", 500); create_file("msitest\\zeta", 500); create_file("msitest\\iota", 500); create_file("msitest\\eta", 500); create_file("msitest\\kappa", 500); create_file("msitest\\lambda", 500); create_file("msitest\\mu", 500); create_database(msifile, is_tables, sizeof(is_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\alpha", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\beta", TRUE), "File installed\n"); ok(delete_pf("msitest\\gamma", TRUE), "File not installed\n"); ok(delete_pf("msitest\\theta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\delta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\epsilon", TRUE), "File installed\n"); ok(!delete_pf("msitest\\zeta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\iota", TRUE), "File installed\n"); ok(!delete_pf("msitest\\eta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\kappa", TRUE), "File installed\n"); ok(!delete_pf("msitest\\lambda", TRUE), "File installed\n"); ok(!delete_pf("msitest\\mu", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "ADDLOCAL=\"one,two,three,four\""); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\alpha", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\beta", TRUE), "File installed\n"); ok(delete_pf("msitest\\gamma", TRUE), "File not installed\n"); ok(delete_pf("msitest\\theta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\delta", TRUE), "File installed\n"); ok(delete_pf("msitest\\epsilon", TRUE), "File not installed\n"); ok(delete_pf("msitest\\zeta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\iota", TRUE), "File installed\n"); ok(delete_pf("msitest\\eta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\kappa", TRUE), "File installed\n"); ok(!delete_pf("msitest\\lambda", TRUE), "File installed\n"); ok(!delete_pf("msitest\\mu", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "ADDSOURCE=\"one,two,three,four\""); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\alpha", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\beta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\gamma", TRUE), "File installed\n"); ok(delete_pf("msitest\\theta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\delta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\epsilon", TRUE), "File installed\n"); ok(delete_pf("msitest\\zeta", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\iota", TRUE), "File installed\n"); ok(!delete_pf("msitest\\eta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\kappa", TRUE), "File installed\n"); ok(!delete_pf("msitest\\lambda", TRUE), "File installed\n"); ok(!delete_pf("msitest\\mu", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "REMOVE=\"one,two,three,four\""); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\alpha", TRUE), "File installed\n"); ok(!delete_pf("msitest\\beta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\gamma", TRUE), "File installed\n"); ok(!delete_pf("msitest\\theta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\delta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\epsilon", TRUE), "File installed\n"); ok(!delete_pf("msitest\\zeta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\iota", TRUE), "File installed\n"); ok(!delete_pf("msitest\\eta", TRUE), "File installed\n"); ok(!delete_pf("msitest\\kappa", TRUE), "File installed\n"); ok(!delete_pf("msitest\\lambda", TRUE), "File installed\n"); ok(!delete_pf("msitest\\mu", TRUE), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory created\n"); error: DeleteFileA(msifile); DeleteFileA("msitest\\alpha"); DeleteFileA("msitest\\beta"); DeleteFileA("msitest\\gamma"); DeleteFileA("msitest\\theta"); DeleteFileA("msitest\\delta"); DeleteFileA("msitest\\epsilon"); DeleteFileA("msitest\\zeta"); DeleteFileA("msitest\\iota"); DeleteFileA("msitest\\eta"); DeleteFileA("msitest\\kappa"); DeleteFileA("msitest\\lambda"); DeleteFileA("msitest\\mu"); RemoveDirectoryA("msitest"); } static const struct sourcepathmap { BOOL sost; /* shortone\shorttwo */ BOOL solt; /* shortone\longtwo */ BOOL lost; /* longone\shorttwo */ BOOL lolt; /* longone\longtwo */ BOOL soste; /* shortone\shorttwo source exists */ BOOL solte; /* shortone\longtwo source exists */ BOOL loste; /* longone\shorttwo source exists */ BOOL lolte; /* longone\longtwo source exists */ UINT err; DWORD size; } spmap[256] = { {TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, ERROR_SUCCESS, 200}, {FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, ERROR_INSTALL_FAILURE, 0}, {FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, ERROR_INSTALL_FAILURE, 0}, }; static DWORD get_pf_file_size(LPCSTR file) { CHAR path[MAX_PATH]; HANDLE hfile; DWORD size; lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\"); lstrcatA(path, file); hfile = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if (hfile == INVALID_HANDLE_VALUE) return INVALID_FILE_SIZE; size = GetFileSize(hfile, NULL); CloseHandle(hfile); return size; } static void test_sourcepath(void) { UINT r, i; if (!winetest_interactive) { skip("Run in interactive mode to run source path tests.\n"); return; } create_database(msifile, sp_tables, sizeof(sp_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); for (i = 0; i < sizeof(spmap) / sizeof(spmap[0]); i++) { if (spmap[i].sost) { CreateDirectoryA("shortone", NULL); CreateDirectoryA("shortone\\shorttwo", NULL); } if (spmap[i].solt) { CreateDirectoryA("shortone", NULL); CreateDirectoryA("shortone\\longtwo", NULL); } if (spmap[i].lost) { CreateDirectoryA("longone", NULL); CreateDirectoryA("longone\\shorttwo", NULL); } if (spmap[i].lolt) { CreateDirectoryA("longone", NULL); CreateDirectoryA("longone\\longtwo", NULL); } if (spmap[i].soste) create_file("shortone\\shorttwo\\augustus", 50); if (spmap[i].solte) create_file("shortone\\longtwo\\augustus", 100); if (spmap[i].loste) create_file("longone\\shorttwo\\augustus", 150); if (spmap[i].lolte) create_file("longone\\longtwo\\augustus", 200); r = MsiInstallProductA(msifile, NULL); ok(r == spmap[i].err, "%d: Expected %d, got %d\n", i, spmap[i].err, r); ok(get_pf_file_size("msitest\\augustus") == spmap[i].size, "%d: Expected %d, got %d\n", i, spmap[i].size, get_pf_file_size("msitest\\augustus")); if (r == ERROR_SUCCESS) { ok(delete_pf("msitest\\augustus", TRUE), "%d: File not installed\n", i); ok(delete_pf("msitest", FALSE), "%d: Directory not created\n", i); } else { ok(!delete_pf("msitest\\augustus", TRUE), "%d: File installed\n", i); todo_wine ok(!delete_pf("msitest", FALSE), "%d: Directory installed\n", i); } DeleteFileA("shortone\\shorttwo\\augustus"); DeleteFileA("shortone\\longtwo\\augustus"); DeleteFileA("longone\\shorttwo\\augustus"); DeleteFileA("longone\\longtwo\\augustus"); RemoveDirectoryA("shortone\\shorttwo"); RemoveDirectoryA("shortone\\longtwo"); RemoveDirectoryA("longone\\shorttwo"); RemoveDirectoryA("longone\\longtwo"); RemoveDirectoryA("shortone"); RemoveDirectoryA("longone"); } DeleteFileA(msifile); } static void test_missingcomponent(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\hydrogen", 500); create_file("msitest\\helium", 500); create_file("msitest\\lithium", 500); create_file("beryllium", 500); create_database(msifile, mcp_tables, sizeof(mcp_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, "INSTALLLEVEL=10 PROPVAR=42"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } else if (r == ERROR_INSTALL_FAILURE) { win_skip("broken result\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(pf_exists("msitest\\hydrogen"), "File not installed\n"); ok(pf_exists("msitest\\helium"), "File not installed\n"); ok(pf_exists("msitest\\lithium"), "File not installed\n"); ok(!pf_exists("msitest\\beryllium"), "File installed\n"); ok(pf_exists("msitest"), "File not installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL INSTALLLEVEL=10 PROPVAR=42"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\hydrogen", TRUE), "File not removed\n"); ok(!delete_pf("msitest\\helium", TRUE), "File not removed\n"); ok(!delete_pf("msitest\\lithium", TRUE), "File not removed\n"); ok(!pf_exists("msitest\\beryllium"), "File installed\n"); ok(!delete_pf("msitest", FALSE), "Directory not removed\n"); error: DeleteFileA(msifile); DeleteFileA("msitest\\hydrogen"); DeleteFileA("msitest\\helium"); DeleteFileA("msitest\\lithium"); DeleteFileA("beryllium"); RemoveDirectoryA("msitest"); } static void test_sourcedirprop(void) { UINT r; CHAR props[MAX_PATH]; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, ca51_tables, sizeof(ca51_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory created\n"); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); CreateDirectoryA("altsource", NULL); CreateDirectoryA("altsource\\msitest", NULL); create_file("altsource\\msitest\\augustus", 500); sprintf(props, "SRCDIR=%s\\altsource\\", CURR_DIR); r = MsiInstallProductA(msifile, props); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory created\n"); DeleteFileA("altsource\\msitest\\augustus"); RemoveDirectoryA("altsource\\msitest"); RemoveDirectoryA("altsource"); error: DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); } static void test_adminimage(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); CreateDirectoryA("msitest\\first", NULL); CreateDirectoryA("msitest\\second", NULL); CreateDirectoryA("msitest\\cabout", NULL); CreateDirectoryA("msitest\\cabout\\new", NULL); create_file("msitest\\one.txt", 100); create_file("msitest\\first\\two.txt", 100); create_file("msitest\\second\\three.txt", 100); create_file("msitest\\cabout\\four.txt", 100); create_file("msitest\\cabout\\new\\five.txt", 100); create_file("msitest\\filename", 100); create_file("msitest\\service.exe", 100); create_database_wordcount(msifile, ai_tables, sizeof(ai_tables) / sizeof(msi_table), 100, msidbSumInfoSourceTypeAdminImage, ";1033", "{004757CA-5092-49C2-AD20-28E1CE0DF5F2}"); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: DeleteFileA("msifile"); DeleteFileA("msitest\\cabout\\new\\five.txt"); DeleteFileA("msitest\\cabout\\four.txt"); DeleteFileA("msitest\\second\\three.txt"); DeleteFileA("msitest\\first\\two.txt"); DeleteFileA("msitest\\one.txt"); DeleteFileA("msitest\\service.exe"); DeleteFileA("msitest\\filename"); RemoveDirectoryA("msitest\\cabout\\new"); RemoveDirectoryA("msitest\\cabout"); RemoveDirectoryA("msitest\\second"); RemoveDirectoryA("msitest\\first"); RemoveDirectoryA("msitest"); } static void test_propcase(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\augustus", 500); create_database(msifile, pc_tables, sizeof(pc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, "MyProp=42"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "Prop1=\"Copyright \"\"My Company\"\" 2015\" MyProp=42"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "Prop1=\"\"\"install.exe\"\" /Install\" MyProp=\"42\""); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\augustus", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: DeleteFileA(msifile); DeleteFileA("msitest\\augustus"); RemoveDirectoryA("msitest"); } static void test_int_widths( void ) { static const WCHAR msitestW[] = {'m','s','i','t','e','s','t','.','m','s','i',0}; static const WCHAR msitableW[] = {'m','s','i','t','a','b','l','e','.','i','d','t',0}; static const WCHAR slashW[] = {'\\',0}; static const char int0[] = "int0\ni0\nint0\tint0\n1"; static const char int1[] = "int1\ni1\nint1\tint1\n1"; static const char int2[] = "int2\ni2\nint2\tint2\n1"; static const char int3[] = "int3\ni3\nint3\tint3\n1"; static const char int4[] = "int4\ni4\nint4\tint4\n1"; static const char int5[] = "int5\ni5\nint5\tint5\n1"; static const char int8[] = "int8\ni8\nint8\tint8\n1"; static const struct { const char *data; unsigned int size; UINT ret; } tests[] = { { int0, sizeof(int0) - 1, ERROR_SUCCESS }, { int1, sizeof(int1) - 1, ERROR_SUCCESS }, { int2, sizeof(int2) - 1, ERROR_SUCCESS }, { int3, sizeof(int3) - 1, ERROR_FUNCTION_FAILED }, { int4, sizeof(int4) - 1, ERROR_SUCCESS }, { int5, sizeof(int5) - 1, ERROR_FUNCTION_FAILED }, { int8, sizeof(int8) - 1, ERROR_FUNCTION_FAILED } }; WCHAR tmpdir[MAX_PATH], msitable[MAX_PATH], msidb[MAX_PATH]; MSIHANDLE db; UINT r, i; GetTempPathW(MAX_PATH, tmpdir); CreateDirectoryW(tmpdir, NULL); lstrcpyW(msitable, tmpdir); lstrcatW(msitable, slashW); lstrcatW(msitable, msitableW); lstrcpyW(msidb, tmpdir); lstrcatW(msidb, slashW); lstrcatW(msidb, msitestW); r = MsiOpenDatabaseW(msidb, MSIDBOPEN_CREATE, &db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { DWORD count; HANDLE handle = CreateFileW(msitable, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); WriteFile(handle, tests[i].data, tests[i].size, &count, NULL); CloseHandle(handle); r = MsiDatabaseImportW(db, tmpdir, msitableW); ok(r == tests[i].ret, " %u expected %u, got %u\n", i, tests[i].ret, r); r = MsiDatabaseCommit(db); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); DeleteFileW(msitable); } MsiCloseHandle(db); DeleteFileW(msidb); RemoveDirectoryW(tmpdir); } static void test_shortcut(void) { UINT r; HRESULT hr; if (is_process_limited()) { skip("process is limited\n"); return; } create_test_files(); create_database(msifile, sc_tables, sizeof(sc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); hr = CoInitializeEx(NULL, COINIT_MULTITHREADED); ok(SUCCEEDED(hr), "CoInitialize failed 0x%08x\n", hr); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); CoUninitialize(); hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); ok(SUCCEEDED(hr), "CoInitialize failed 0x%08x\n", hr); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); CoUninitialize(); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); while (!delete_pf("msitest\\Shortcut.lnk", TRUE) && GetLastError() == ERROR_SHARING_VIOLATION) Sleep(1000); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: delete_test_files(); DeleteFileA(msifile); } static void test_preselected(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } create_test_files(); create_database(msifile, ps_tables, sizeof(ps_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, "ADDLOCAL=One"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File installed\n"); ok(!delete_pf("msitest\\cabout\\new", FALSE), "Directory created\n"); ok(!delete_pf("msitest\\cabout\\four.txt", TRUE), "File installed\n"); ok(!delete_pf("msitest\\cabout", FALSE), "Directory created\n"); ok(!delete_pf("msitest\\changed\\three.txt", TRUE), "File installed\n"); ok(!delete_pf("msitest\\changed", FALSE), "Directory created\n"); ok(!delete_pf("msitest\\first\\two.txt", TRUE), "File installed\n"); ok(!delete_pf("msitest\\first", FALSE), "Directory created\n"); ok(!delete_pf("msitest\\filename", TRUE), "File installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\service.exe", TRUE), "File installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(!delete_pf("msitest\\one.txt", TRUE), "File installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); error: delete_test_files(); DeleteFileA(msifile); } static void test_installed_prop(void) { static const char prodcode[] = "{7df88a48-996f-4ec8-a022-bf956f9b2cbb}"; UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } create_test_files(); create_database(msifile, ip_tables, sizeof(ip_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, "FULL=1"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); r = MsiInstallProductA(msifile, "FULL=1"); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); r = MsiConfigureProductExA(prodcode, INSTALLLEVEL_DEFAULT, INSTALLSTATE_DEFAULT, "FULL=1"); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); error: delete_test_files(); DeleteFileA(msifile); } static void test_allusers_prop(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } create_test_files(); create_database(msifile, aup_tables, sizeof(aup_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); /* ALLUSERS property unset */ r = MsiInstallProductA(msifile, "FULL=1"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); delete_test_files(); create_test_files(); create_database(msifile, aup2_tables, sizeof(aup2_tables) / sizeof(msi_table)); /* ALLUSERS property set to 1 */ r = MsiInstallProductA(msifile, "FULL=1"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); delete_test_files(); create_test_files(); create_database(msifile, aup3_tables, sizeof(aup3_tables) / sizeof(msi_table)); /* ALLUSERS property set to 2 */ r = MsiInstallProductA(msifile, "FULL=1"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\cabout\\new\\five.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout\\new", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\cabout\\four.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\cabout", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\changed\\three.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\changed", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\first\\two.txt", TRUE), "File not installed\n"); ok(delete_pf("msitest\\first", FALSE), "Directory not created\n"); ok(delete_pf("msitest\\filename", TRUE), "File not installed\n"); ok(delete_pf("msitest\\one.txt", TRUE), "File installed\n"); ok(delete_pf("msitest\\service.exe", TRUE), "File not installed\n"); ok(delete_pf("msitest", FALSE), "Directory not created\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); delete_test_files(); create_test_files(); create_database(msifile, aup4_tables, sizeof(aup4_tables) / sizeof(msi_table)); /* ALLUSERS property set to 2, conditioned on ALLUSERS = 1 */ r = MsiInstallProductA(msifile, "FULL=1"); ok(r == ERROR_INSTALL_FAILURE, "Expected ERROR_INSTALL_FAILURE, got %u\n", r); error: delete_test_files(); DeleteFileA(msifile); } static const char session_manager[] = "System\\CurrentControlSet\\Control\\Session Manager"; static const char rename_ops[] = "PendingFileRenameOperations"; static void process_pending_renames(HKEY hkey) { char *buf, *src, *dst, *buf2, *buf2ptr; DWORD size; LONG ret; BOOL found = FALSE; ret = RegQueryValueExA(hkey, rename_ops, NULL, NULL, NULL, &size); ok(!ret, "RegQueryValueExA failed %d\n", ret); buf = HeapAlloc(GetProcessHeap(), 0, size + 1); buf2ptr = buf2 = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size + 1); ret = RegQueryValueExA(hkey, rename_ops, NULL, NULL, (LPBYTE)buf, &size); buf[size] = 0; ok(!ret, "RegQueryValueExA failed %d\n", ret); if (ret) return; for (src = buf; *src; src = dst + strlen(dst) + 1) { DWORD flags = MOVEFILE_COPY_ALLOWED; BOOL fileret; dst = src + strlen(src) + 1; if (!strstr(src, "msitest")) { lstrcpyA(buf2ptr, src); buf2ptr += strlen(src) + 1; lstrcpyA(buf2ptr, dst); buf2ptr += strlen(dst) + 1; continue; } found = TRUE; if (*dst == '!') { flags |= MOVEFILE_REPLACE_EXISTING; dst++; } if (src[0] == '\\' && src[1] == '?' && src[2] == '?' && src[3] == '\\') src += 4; if (*dst) { if (dst[0] == '\\' && dst[1] == '?' && dst[2] == '?' && dst[3] == '\\') dst += 4; fileret = MoveFileExA(src, dst, flags); ok(fileret, "Failed to move file %s -> %s (%u)\n", src, dst, GetLastError()); } else { fileret = DeleteFileA(src); ok(fileret || broken(!fileret) /* win2k3 */, "Failed to delete file %s (%u)\n", src, GetLastError()); } } ok(found, "Expected a 'msitest' entry\n"); if (*buf2) RegSetValueExA(hkey, rename_ops, 0, REG_MULTI_SZ, (LPBYTE)buf2, buf2ptr + 1 - buf2); else RegDeleteValueA(hkey, rename_ops); HeapFree(GetProcessHeap(), 0, buf); HeapFree(GetProcessHeap(), 0, buf2); } static BOOL file_matches_data(LPCSTR file, LPCSTR data) { DWORD len, data_len = strlen(data); HANDLE handle; char buf[128]; handle = CreateFileA(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); ok(handle != INVALID_HANDLE_VALUE, "failed to open %s (%u)\n", file, GetLastError()); if (ReadFile(handle, buf, sizeof(buf), &len, NULL) && len >= data_len) { CloseHandle(handle); return !memcmp(buf, data, data_len); } CloseHandle(handle); return FALSE; } static void test_file_in_use(void) { UINT r; HANDLE file; HKEY hkey; char path[MAX_PATH]; if (is_process_limited()) { skip("process is limited\n"); return; } RegOpenKeyExA(HKEY_LOCAL_MACHINE, session_manager, 0, KEY_ALL_ACCESS, &hkey); CreateDirectoryA("msitest", NULL); create_file("msitest\\maximus", 500); create_database(msifile, fiu_tables, sizeof(fiu_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest"); CreateDirectoryA(path, NULL); lstrcatA(path, "\\maximus"); file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); r = MsiInstallProductA(msifile, "REBOOT=ReallySuppress FULL=1"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS_REBOOT_REQUIRED, "Expected ERROR_SUCCESS_REBOOT_REQUIRED got %u\n", r); ok(!file_matches_data(path, "msitest\\maximus"), "Expected file not to match\n"); CloseHandle(file); ok(!file_matches_data(path, "msitest\\maximus"), "Expected file not to match\n"); process_pending_renames(hkey); RegCloseKey(hkey); ok(file_matches_data(path, "msitest\\maximus"), "Expected file to match\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not present\n"); ok(delete_pf("msitest", FALSE), "Directory not present or not empty\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); error: RegCloseKey(hkey); delete_pf("msitest\\maximus", TRUE); delete_pf("msitest", FALSE); DeleteFileA("msitest\\maximus"); delete_test_files(); DeleteFileA(msifile); } static void test_file_in_use_cab(void) { UINT r; HANDLE file; HKEY hkey; char path[MAX_PATH]; if (is_process_limited()) { skip("process is limited\n"); return; } RegOpenKeyExA(HKEY_LOCAL_MACHINE, session_manager, 0, KEY_ALL_ACCESS, &hkey); CreateDirectoryA("msitest", NULL); create_file("maximus", 500); create_cab_file("test1.cab", MEDIA_SIZE, "maximus\0"); DeleteFileA("maximus"); create_database(msifile, fiuc_tables, sizeof(fiuc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); lstrcpyA(path, PROG_FILES_DIR); lstrcatA(path, "\\msitest"); CreateDirectoryA(path, NULL); lstrcatA(path, "\\maximus"); file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); r = MsiInstallProductA(msifile, "REBOOT=ReallySuppress FULL=1"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS_REBOOT_REQUIRED, "Expected ERROR_SUCCESS_REBOOT_REQUIRED got %u\n", r); ok(!file_matches_data(path, "maximus"), "Expected file not to match\n"); CloseHandle(file); ok(!file_matches_data(path, "maximus"), "Expected file not to match\n"); process_pending_renames(hkey); RegCloseKey(hkey); ok(file_matches_data(path, "maximus"), "Expected file to match\n"); ok(delete_pf("msitest\\maximus", TRUE), "File not present\n"); ok(delete_pf("msitest", FALSE), "Directory not present or not empty\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); error: RegCloseKey(hkey); delete_pf("msitest\\maximus", TRUE); delete_pf("msitest", FALSE); DeleteFileA("msitest\\maximus"); delete_cab_files(); delete_test_files(); DeleteFileA(msifile); } static void test_feature_override(void) { UINT r; REGSAM access = KEY_ALL_ACCESS; if (is_process_limited()) { skip("process is limited\n"); return; } create_test_files(); create_file("msitest\\override.txt", 1000); create_file("msitest\\preselected.txt", 1000); create_file("msitest\\notpreselected.txt", 1000); create_database(msifile, fo_tables, sizeof(fo_tables) / sizeof(msi_table)); if (is_wow64) access |= KEY_WOW64_64KEY; MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, "ADDLOCAL=override"); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(pf_exists("msitest\\override.txt"), "file not installed\n"); ok(!pf_exists("msitest\\preselected.txt"), "file installed\n"); ok(!pf_exists("msitest\\notpreselected.txt"), "file installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\override.txt", TRUE), "file not removed\n"); r = MsiInstallProductA(msifile, "preselect=1"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(pf_exists("msitest\\override.txt"), "file not installed\n"); ok(pf_exists("msitest\\preselected.txt"), "file not installed\n"); ok(!pf_exists("msitest\\notpreselected.txt"), "file installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\override.txt", TRUE), "file not removed\n"); todo_wine { ok(delete_pf("msitest\\preselected.txt", TRUE), "file removed\n"); ok(delete_pf("msitest", FALSE), "directory removed\n"); } r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(pf_exists("msitest\\override.txt"), "file not installed\n"); ok(pf_exists("msitest\\preselected.txt"), "file not installed\n"); ok(!pf_exists("msitest\\notpreselected.txt"), "file installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\override.txt", TRUE), "file not removed\n"); todo_wine { ok(delete_pf("msitest\\preselected.txt", TRUE), "file removed\n"); ok(delete_pf("msitest", FALSE), "directory removed\n"); } delete_key(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", access); error: DeleteFileA("msitest\\override.txt"); DeleteFileA("msitest\\preselected.txt"); DeleteFileA("msitest\\notpreselected.txt"); delete_test_files(); DeleteFileA(msifile); } static void test_icon_table(void) { MSIHANDLE hdb = 0, record; LPCSTR query; UINT res; CHAR path[MAX_PATH]; static const char prodcode[] = "{7DF88A49-996F-4EC8-A022-BF956F9B2CBB}"; if (is_process_limited()) { skip("process is limited\n"); return; } create_database(msifile, icon_base_tables, sizeof(icon_base_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); res = MsiOpenDatabaseW(msifileW, MSIDBOPEN_TRANSACT, &hdb); ok(res == ERROR_SUCCESS, "failed to open db: %d\n", res); query = "CREATE TABLE `Icon` (`Name` CHAR(72) NOT NULL, `Data` OBJECT NOT NULL PRIMARY KEY `Name`)"; res = run_query( hdb, 0, query ); ok(res == ERROR_SUCCESS, "Can't create Icon table: %d\n", res); create_file("icon.ico", 100); record = MsiCreateRecord(1); res = MsiRecordSetStreamA(record, 1, "icon.ico"); ok(res == ERROR_SUCCESS, "Failed to add stream data to record: %d\n", res); query = "INSERT INTO `Icon` (`Name`, `Data`) VALUES ('testicon', ?)"; res = run_query(hdb, record, query); ok(res == ERROR_SUCCESS, "Insert into Icon table failed: %d\n", res); res = MsiCloseHandle(record); ok(res == ERROR_SUCCESS, "Failed to close record handle: %d\n", res); DeleteFileA("icon.ico"); res = MsiDatabaseCommit(hdb); ok(res == ERROR_SUCCESS, "Failed to commit database: %d\n", res); res = MsiCloseHandle(hdb); ok(res == ERROR_SUCCESS, "Failed to close database: %d\n", res); /* per-user */ res = MsiInstallProductA(msifile, "PUBLISH_PRODUCT=1"); if (res == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); DeleteFileA(msifile); return; } ok(res == ERROR_SUCCESS, "Failed to do per-user install: %d\n", res); lstrcpyA(path, APP_DATA_DIR); lstrcatA(path, "\\"); lstrcatA(path, "Microsoft\\Installer\\"); lstrcatA(path, prodcode); lstrcatA(path, "\\testicon"); ok(file_exists(path), "Per-user icon file isn't where it's expected (%s)\n", path); res = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(res == ERROR_SUCCESS, "Failed to uninstall per-user\n"); ok(!file_exists(path), "Per-user icon file not removed (%s)\n", path); /* system-wide */ res = MsiInstallProductA(msifile, "PUBLISH_PRODUCT=1 ALLUSERS=1"); ok(res == ERROR_SUCCESS, "Failed to system-wide install: %d\n", res); lstrcpyA(path, WINDOWS_DIR); lstrcatA(path, "\\"); lstrcatA(path, "Installer\\"); lstrcatA(path, prodcode); lstrcatA(path, "\\testicon"); ok(file_exists(path), "System-wide icon file isn't where it's expected (%s)\n", path); res = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(res == ERROR_SUCCESS, "Failed to uninstall system-wide\n"); ok(!file_exists(path), "System-wide icon file not removed (%s)\n", path); delete_pfmsitest_files(); DeleteFileA(msifile); } static void test_package_validation(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\maximus", 500); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;1033"); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel,9999;9999"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_LANGUAGE_UNSUPPORTED, "Expected ERROR_INSTALL_LANGUAGE_UNSUPPORTED, got %u\n", r); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel,1033;9999"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_LANGUAGE_UNSUPPORTED, "Expected ERROR_INSTALL_LANGUAGE_UNSUPPORTED, got %u\n", r); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel,9999;1033"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel64,9999;1033"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel32,1033;1033"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "Intel32,9999;1033"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;9999"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_LANGUAGE_UNSUPPORTED, "Expected ERROR_INSTALL_LANGUAGE_UNSUPPORTED, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf("msitest", FALSE), "directory exists\n"); if (GetSystemDefaultLangID() == MAKELANGID( LANG_ENGLISH, SUBLANG_ENGLISH_US )) { DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;9"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;1024"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); } DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel32;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf("msitest", FALSE), "directory exists\n"); if (is_64bit && !is_wow64) { DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PACKAGE_INVALID, "Expected ERROR_INSTALL_PACKAGE_INVALID, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf("msitest", FALSE), "directory exists\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); } else if (is_wow64) { DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PACKAGE_INVALID, "Expected ERROR_INSTALL_PACKAGE_INVALID, got %u\n", r); ok(!delete_pf_native("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf_native("msitest", FALSE), "directory exists\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf_native("msitest\\maximus", TRUE), "file exists\n"); ok(delete_pf_native("msitest", FALSE), "directory exists\n"); } else { DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Intel;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "Alpha,Beta,Intel;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(delete_pf("msitest\\maximus", TRUE), "file does not exist\n"); ok(delete_pf("msitest", FALSE), "directory does not exist\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 100, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf("msitest", FALSE), "directory exists\n"); DeleteFileA(msifile); create_database_template(msifile, pv_tables, sizeof(pv_tables)/sizeof(msi_table), 200, "x64;0"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_INSTALL_PLATFORM_UNSUPPORTED, "Expected ERROR_INSTALL_PLATFORM_UNSUPPORTED, got %u\n", r); ok(!delete_pf("msitest\\maximus", TRUE), "file exists\n"); ok(!delete_pf("msitest", FALSE), "directory exists\n"); } error: /* Delete the files in the temp (current) folder */ DeleteFileA(msifile); DeleteFileA("msitest\\maximus"); RemoveDirectoryA("msitest"); } static void test_upgrade_code(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\upgradecode.txt", 1000); create_database(msifile, uc_tables, sizeof(uc_tables) / sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(pf_exists("msitest\\upgradecode.txt"), "file not installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); ok(!delete_pf("msitest\\upgradecode.txt", TRUE), "file not removed\n"); ok(!delete_pf("msitest", FALSE), "directory not removed\n"); DeleteFileA("msitest\\upgradecode.txt"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); } static void test_mixed_package(void) { UINT r; LONG res; HKEY hkey; char value[MAX_PATH]; DWORD size; if (is_process_limited()) { skip("process is limited\n"); return; } if (!is_wow64 && !is_64bit) { skip("this test must be run on 64-bit\n"); return; } MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); create_database_template(msifile, mixed_tables, sizeof(mixed_tables)/sizeof(msi_table), 200, "x64;1033"); r = MsiInstallProductA(msifile, NULL); if (r == ERROR_INSTALL_PACKAGE_REJECTED) { skip("Not enough rights to perform tests\n"); goto error; } ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(!res, "can't open 32-bit component key, got %d\n", res); res = RegQueryValueExA(hkey, "test1", NULL, NULL, NULL, NULL); ok(!res, "expected RegQueryValueEx to succeed, got %d\n", res); res = RegQueryValueExA(hkey, "test2", NULL, NULL, NULL, NULL); ok(res, "expected RegQueryValueEx to fail, got %d\n", res); RegCloseKey(hkey); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(!res, "can't open 64-bit component key, got %d\n", res); res = RegQueryValueExA(hkey, "test1", NULL, NULL, NULL, NULL); ok(res, "expected RegQueryValueEx to fail, got %d\n", res); res = RegQueryValueExA(hkey, "test2", NULL, NULL, NULL, NULL); ok(!res, "expected RegQueryValueEx to succeed, got %d\n", res); RegCloseKey(hkey); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_SUCCESS, "can't open 32-bit CLSID key, got %d\n", res); if (res == ERROR_SUCCESS) { size = sizeof(value); res = RegQueryValueExA(hkey, "", NULL, NULL, (LPBYTE)value, &size); ok(!strcmp(value, "winetest32.dll"), "got %s\n", value); RegCloseKey(hkey); } res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_SUCCESS, "can't open 64-bit CLSID key, got %d\n", res); if (res == ERROR_SUCCESS) { size = sizeof(value); res = RegQueryValueExA(hkey, "", NULL, NULL, (LPBYTE)value, &size); ok(!strcmp(value, "winetest64.dll"), "got %s\n", value); RegCloseKey(hkey); } r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND || broken(!res), "32-bit component key not removed\n"); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "64-bit component key not removed\n"); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "32-bit CLSID key not removed\n"); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "64-bit CLSID key not removed\n"); DeleteFileA( msifile ); create_database_template(msifile, mixed_tables, sizeof(mixed_tables)/sizeof(msi_table), 200, "Intel;1033"); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(!res, "can't open 32-bit component key, got %d\n", res); res = RegQueryValueExA(hkey, "test1", NULL, NULL, NULL, NULL); ok(!res, "expected RegQueryValueEx to succeed, got %d\n", res); res = RegQueryValueExA(hkey, "test2", NULL, NULL, NULL, NULL); ok(res, "expected RegQueryValueEx to fail, got %d\n", res); RegCloseKey(hkey); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(!res, "can't open 64-bit component key, got %d\n", res); res = RegQueryValueExA(hkey, "test1", NULL, NULL, NULL, NULL); ok(res, "expected RegQueryValueEx to fail, got %d\n", res); res = RegQueryValueExA(hkey, "test2", NULL, NULL, NULL, NULL); ok(!res, "expected RegQueryValueEx to succeed, got %d\n", res); RegCloseKey(hkey); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_SUCCESS, "can't open 32-bit CLSID key, got %d\n", res); if (res == ERROR_SUCCESS) { size = sizeof(value); res = RegQueryValueExA(hkey, "", NULL, NULL, (LPBYTE)value, &size); ok(!strcmp(value, "winetest32.dll"), "got %s\n", value); RegCloseKey(hkey); } res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}\\InProcServer32", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_SUCCESS, "can't open 64-bit CLSID key, got %d\n", res); if (res == ERROR_SUCCESS) { size = sizeof(value); res = RegQueryValueExA(hkey, "", NULL, NULL, (LPBYTE)value, &size); ok(!strcmp(value, "winetest64.dll"), "got %s\n", value); RegCloseKey(hkey); } r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %u\n", r); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND || broken(!res), "32-bit component key not removed\n"); res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Wine\\msitest", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "64-bit component key not removed\n"); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}", 0, KEY_ALL_ACCESS|KEY_WOW64_32KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "32-bit CLSID key not removed\n"); res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "CLSID\\{8dfef911-6885-41eb-b280-8f0304728e8b}", 0, KEY_ALL_ACCESS|KEY_WOW64_64KEY, &hkey); ok(res == ERROR_FILE_NOT_FOUND, "64-bit CLSID key not removed\n"); error: DeleteFileA( msifile ); } static void test_volume_props(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\volumeprop.txt", 1000); create_database(msifile, vp_tables, sizeof(vp_tables)/sizeof(msi_table)); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "got %u\n", r); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "got %u\n", r); DeleteFileA("msitest\\volumeprop.txt"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); } static void test_shared_component(void) { UINT r; if (is_process_limited()) { skip("process is limited\n"); return; } CreateDirectoryA("msitest", NULL); create_file("msitest\\sharedcomponent.txt", 1000); create_database_wordcount(msifile, shc_tables, sizeof(shc_tables)/sizeof(shc_tables[0]), 100, 0, ";", "{A8826420-FD72-4E61-9E15-C1944CF4CBE1}"); create_database_wordcount(msifile2, shc2_tables, sizeof(shc2_tables)/sizeof(shc2_tables[0]), 100, 0, ";", "{A8B50B30-0E8A-4ACD-B3CF-1A5DC58B2739}"); MsiSetInternalUI(INSTALLUILEVEL_NONE, NULL); r = MsiInstallProductA(msifile, NULL); ok(r == ERROR_SUCCESS, "got %u\n", r); ok(pf_exists("msitest\\sharedcomponent.txt"), "file not installed\n"); r = MsiInstallProductA(msifile2, NULL); ok(r == ERROR_SUCCESS, "got %u\n", r); ok(pf_exists("msitest\\sharedcomponent.txt"), "file not installed\n"); r = MsiInstallProductA(msifile, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "got %u\n", r); ok(pf_exists("msitest\\sharedcomponent.txt"), "file removed\n"); r = MsiInstallProductA(msifile2, "REMOVE=ALL"); ok(r == ERROR_SUCCESS, "got %u\n", r); ok(!pf_exists("msitest\\sharedcomponent.txt"), "file not removed\n"); DeleteFileA("msitest\\sharedcomponent.txt"); RemoveDirectoryA("msitest"); DeleteFileA(msifile); DeleteFileA(msifile2); } START_TEST(install) { DWORD len; char temp_path[MAX_PATH], prev_path[MAX_PATH], log_file[MAX_PATH]; STATEMGRSTATUS status; BOOL ret = FALSE; init_functionpointers(); if (pIsWow64Process) pIsWow64Process(GetCurrentProcess(), &is_wow64); GetCurrentDirectoryA(MAX_PATH, prev_path); GetTempPathA(MAX_PATH, temp_path); SetCurrentDirectoryA(temp_path); lstrcpyA(CURR_DIR, temp_path); len = lstrlenA(CURR_DIR); if(len && (CURR_DIR[len - 1] == '\\')) CURR_DIR[len - 1] = 0; ok(get_system_dirs(), "failed to retrieve system dirs\n"); ok(get_user_dirs(), "failed to retrieve user dirs\n"); /* Create a restore point ourselves so we circumvent the multitude of restore points * that would have been created by all the installation and removal tests. * * This is not needed on version 5.0 where setting MSIFASTINSTALL prevents the * creation of restore points. */ if (pSRSetRestorePointA && !pMsiGetComponentPathExA) { memset(&status, 0, sizeof(status)); ret = notify_system_change(BEGIN_NESTED_SYSTEM_CHANGE, &status); } /* Create only one log file and don't append. We have to pass something * for the log mode for this to work. The logfile needs to have an absolute * path otherwise we still end up with some extra logfiles as some tests * change the current directory. */ lstrcpyA(log_file, temp_path); lstrcatA(log_file, "\\msitest.log"); MsiEnableLogA(INSTALLLOGMODE_FATALEXIT, log_file, 0); if (pSRSetRestorePointA) /* test has side-effects on win2k3 that cause failures in following tests */ test_MsiInstallProduct(); test_MsiSetComponentState(); test_packagecoltypes(); test_continuouscabs(); test_caborder(); test_mixedmedia(); test_samesequence(); test_uiLevelFlags(); test_readonlyfile(); test_readonlyfile_cab(); test_setdirproperty(); test_cabisextracted(); test_transformprop(); test_currentworkingdir(); test_admin(); test_adminprops(); test_missingcab(); test_sourcefolder(); test_customaction51(); test_installstate(); test_sourcepath(); test_missingcomponent(); test_sourcedirprop(); test_adminimage(); test_propcase(); test_int_widths(); test_shortcut(); test_preselected(); test_installed_prop(); test_file_in_use(); test_file_in_use_cab(); test_allusers_prop(); test_feature_override(); test_icon_table(); test_package_validation(); test_upgrade_code(); test_mixed_package(); test_volume_props(); test_shared_component(); DeleteFileA(log_file); if (pSRSetRestorePointA && !pMsiGetComponentPathExA && ret) { ret = notify_system_change(END_NESTED_SYSTEM_CHANGE, &status); if (ret) remove_restore_point(status.llSequenceNumber); } FreeLibrary(hsrclient); SetCurrentDirectoryA(prev_path); }
648319.c
/* * palinfo.c * * Prints processor specific information reported by PAL. * This code is based on specification of PAL as of the * Intel IA-64 Architecture Software Developer's Manual v1.0. * * * Copyright (C) 2000-2001, 2003 Hewlett-Packard Co * Stephane Eranian <[email protected]> * Copyright (C) 2004 Intel Corporation * Ashok Raj <[email protected]> * * 05/26/2000 S.Eranian initial release * 08/21/2000 S.Eranian updated to July 2000 PAL specs * 02/05/2001 S.Eranian fixed module support * 10/23/2001 S.Eranian updated pal_perf_mon_info bug fixes * 03/24/2004 Ashok Raj updated to work with CPU Hotplug * 10/26/2006 Russ Anderson updated processor features to rev 2.2 spec */ #include <linux/types.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/proc_fs.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/efi.h> #include <linux/notifier.h> #include <linux/cpu.h> #include <linux/cpumask.h> #include <asm/pal.h> #include <asm/sal.h> #include <asm/page.h> #include <asm/processor.h> #include <linux/smp.h> MODULE_AUTHOR("Stephane Eranian <[email protected]>"); MODULE_DESCRIPTION("/proc interface to IA-64 PAL"); MODULE_LICENSE("GPL"); #define PALINFO_VERSION "0.5" typedef int (*palinfo_func_t)(char*); typedef struct { const char *name; /* name of the proc entry */ palinfo_func_t proc_read; /* function to call for reading */ struct proc_dir_entry *entry; /* registered entry (removal) */ } palinfo_entry_t; /* * A bunch of string array to get pretty printing */ static char *cache_types[] = { "", /* not used */ "Instruction", "Data", "Data/Instruction" /* unified */ }; static const char *cache_mattrib[]={ "WriteThrough", "WriteBack", "", /* reserved */ "" /* reserved */ }; static const char *cache_st_hints[]={ "Temporal, level 1", "Reserved", "Reserved", "Non-temporal, all levels", "Reserved", "Reserved", "Reserved", "Reserved" }; static const char *cache_ld_hints[]={ "Temporal, level 1", "Non-temporal, level 1", "Reserved", "Non-temporal, all levels", "Reserved", "Reserved", "Reserved", "Reserved" }; static const char *rse_hints[]={ "enforced lazy", "eager stores", "eager loads", "eager loads and stores" }; #define RSE_HINTS_COUNT ARRAY_SIZE(rse_hints) static const char *mem_attrib[]={ "WB", /* 000 */ "SW", /* 001 */ "010", /* 010 */ "011", /* 011 */ "UC", /* 100 */ "UCE", /* 101 */ "WC", /* 110 */ "NaTPage" /* 111 */ }; /* * Take a 64bit vector and produces a string such that * if bit n is set then 2^n in clear text is generated. The adjustment * to the right unit is also done. * * Input: * - a pointer to a buffer to hold the string * - a 64-bit vector * Ouput: * - a pointer to the end of the buffer * */ static char * bitvector_process(char *p, u64 vector) { int i,j; const char *units[]={ "", "K", "M", "G", "T" }; for (i=0, j=0; i < 64; i++ , j=i/10) { if (vector & 0x1) { p += sprintf(p, "%d%s ", 1 << (i-j*10), units[j]); } vector >>= 1; } return p; } /* * Take a 64bit vector and produces a string such that * if bit n is set then register n is present. The function * takes into account consecutive registers and prints out ranges. * * Input: * - a pointer to a buffer to hold the string * - a 64-bit vector * Ouput: * - a pointer to the end of the buffer * */ static char * bitregister_process(char *p, u64 *reg_info, int max) { int i, begin, skip = 0; u64 value = reg_info[0]; value >>= i = begin = ffs(value) - 1; for(; i < max; i++ ) { if (i != 0 && (i%64) == 0) value = *++reg_info; if ((value & 0x1) == 0 && skip == 0) { if (begin <= i - 2) p += sprintf(p, "%d-%d ", begin, i-1); else p += sprintf(p, "%d ", i-1); skip = 1; begin = -1; } else if ((value & 0x1) && skip == 1) { skip = 0; begin = i; } value >>=1; } if (begin > -1) { if (begin < 127) p += sprintf(p, "%d-127", begin); else p += sprintf(p, "127"); } return p; } static int power_info(char *page) { s64 status; char *p = page; u64 halt_info_buffer[8]; pal_power_mgmt_info_u_t *halt_info =(pal_power_mgmt_info_u_t *)halt_info_buffer; int i; status = ia64_pal_halt_info(halt_info); if (status != 0) return 0; for (i=0; i < 8 ; i++ ) { if (halt_info[i].pal_power_mgmt_info_s.im == 1) { p += sprintf(p, "Power level %d:\n" "\tentry_latency : %d cycles\n" "\texit_latency : %d cycles\n" "\tpower consumption : %d mW\n" "\tCache+TLB coherency : %s\n", i, halt_info[i].pal_power_mgmt_info_s.entry_latency, halt_info[i].pal_power_mgmt_info_s.exit_latency, halt_info[i].pal_power_mgmt_info_s.power_consumption, halt_info[i].pal_power_mgmt_info_s.co ? "Yes" : "No"); } else { p += sprintf(p,"Power level %d: not implemented\n",i); } } return p - page; } static int cache_info(char *page) { char *p = page; u64 i, levels, unique_caches; pal_cache_config_info_t cci; int j, k; s64 status; if ((status = ia64_pal_cache_summary(&levels, &unique_caches)) != 0) { printk(KERN_ERR "ia64_pal_cache_summary=%ld\n", status); return 0; } p += sprintf(p, "Cache levels : %ld\nUnique caches : %ld\n\n", levels, unique_caches); for (i=0; i < levels; i++) { for (j=2; j >0 ; j--) { /* even without unification some level may not be present */ if ((status=ia64_pal_cache_config_info(i,j, &cci)) != 0) { continue; } p += sprintf(p, "%s Cache level %lu:\n" "\tSize : %u bytes\n" "\tAttributes : ", cache_types[j+cci.pcci_unified], i+1, cci.pcci_cache_size); if (cci.pcci_unified) p += sprintf(p, "Unified "); p += sprintf(p, "%s\n", cache_mattrib[cci.pcci_cache_attr]); p += sprintf(p, "\tAssociativity : %d\n" "\tLine size : %d bytes\n" "\tStride : %d bytes\n", cci.pcci_assoc, 1<<cci.pcci_line_size, 1<<cci.pcci_stride); if (j == 1) p += sprintf(p, "\tStore latency : N/A\n"); else p += sprintf(p, "\tStore latency : %d cycle(s)\n", cci.pcci_st_latency); p += sprintf(p, "\tLoad latency : %d cycle(s)\n" "\tStore hints : ", cci.pcci_ld_latency); for(k=0; k < 8; k++ ) { if ( cci.pcci_st_hints & 0x1) p += sprintf(p, "[%s]", cache_st_hints[k]); cci.pcci_st_hints >>=1; } p += sprintf(p, "\n\tLoad hints : "); for(k=0; k < 8; k++ ) { if (cci.pcci_ld_hints & 0x1) p += sprintf(p, "[%s]", cache_ld_hints[k]); cci.pcci_ld_hints >>=1; } p += sprintf(p, "\n\tAlias boundary : %d byte(s)\n" "\tTag LSB : %d\n" "\tTag MSB : %d\n", 1<<cci.pcci_alias_boundary, cci.pcci_tag_lsb, cci.pcci_tag_msb); /* when unified, data(j=2) is enough */ if (cci.pcci_unified) break; } } return p - page; } static int vm_info(char *page) { char *p = page; u64 tr_pages =0, vw_pages=0, tc_pages; u64 attrib; pal_vm_info_1_u_t vm_info_1; pal_vm_info_2_u_t vm_info_2; pal_tc_info_u_t tc_info; ia64_ptce_info_t ptce; const char *sep; int i, j; s64 status; if ((status = ia64_pal_vm_summary(&vm_info_1, &vm_info_2)) !=0) { printk(KERN_ERR "ia64_pal_vm_summary=%ld\n", status); } else { p += sprintf(p, "Physical Address Space : %d bits\n" "Virtual Address Space : %d bits\n" "Protection Key Registers(PKR) : %d\n" "Implemented bits in PKR.key : %d\n" "Hash Tag ID : 0x%x\n" "Size of RR.rid : %d\n" "Max Purges : ", vm_info_1.pal_vm_info_1_s.phys_add_size, vm_info_2.pal_vm_info_2_s.impl_va_msb+1, vm_info_1.pal_vm_info_1_s.max_pkr+1, vm_info_1.pal_vm_info_1_s.key_size, vm_info_1.pal_vm_info_1_s.hash_tag_id, vm_info_2.pal_vm_info_2_s.rid_size); if (vm_info_2.pal_vm_info_2_s.max_purges == PAL_MAX_PURGES) p += sprintf(p, "unlimited\n"); else p += sprintf(p, "%d\n", vm_info_2.pal_vm_info_2_s.max_purges ? vm_info_2.pal_vm_info_2_s.max_purges : 1); } if (ia64_pal_mem_attrib(&attrib) == 0) { p += sprintf(p, "Supported memory attributes : "); sep = ""; for (i = 0; i < 8; i++) { if (attrib & (1 << i)) { p += sprintf(p, "%s%s", sep, mem_attrib[i]); sep = ", "; } } p += sprintf(p, "\n"); } if ((status = ia64_pal_vm_page_size(&tr_pages, &vw_pages)) !=0) { printk(KERN_ERR "ia64_pal_vm_page_size=%ld\n", status); } else { p += sprintf(p, "\nTLB walker : %simplemented\n" "Number of DTR : %d\n" "Number of ITR : %d\n" "TLB insertable page sizes : ", vm_info_1.pal_vm_info_1_s.vw ? "" : "not ", vm_info_1.pal_vm_info_1_s.max_dtr_entry+1, vm_info_1.pal_vm_info_1_s.max_itr_entry+1); p = bitvector_process(p, tr_pages); p += sprintf(p, "\nTLB purgeable page sizes : "); p = bitvector_process(p, vw_pages); } if ((status=ia64_get_ptce(&ptce)) != 0) { printk(KERN_ERR "ia64_get_ptce=%ld\n", status); } else { p += sprintf(p, "\nPurge base address : 0x%016lx\n" "Purge outer loop count : %d\n" "Purge inner loop count : %d\n" "Purge outer loop stride : %d\n" "Purge inner loop stride : %d\n", ptce.base, ptce.count[0], ptce.count[1], ptce.stride[0], ptce.stride[1]); p += sprintf(p, "TC Levels : %d\n" "Unique TC(s) : %d\n", vm_info_1.pal_vm_info_1_s.num_tc_levels, vm_info_1.pal_vm_info_1_s.max_unique_tcs); for(i=0; i < vm_info_1.pal_vm_info_1_s.num_tc_levels; i++) { for (j=2; j>0 ; j--) { tc_pages = 0; /* just in case */ /* even without unification, some levels may not be present */ if ((status=ia64_pal_vm_info(i,j, &tc_info, &tc_pages)) != 0) { continue; } p += sprintf(p, "\n%s Translation Cache Level %d:\n" "\tHash sets : %d\n" "\tAssociativity : %d\n" "\tNumber of entries : %d\n" "\tFlags : ", cache_types[j+tc_info.tc_unified], i+1, tc_info.tc_num_sets, tc_info.tc_associativity, tc_info.tc_num_entries); if (tc_info.tc_pf) p += sprintf(p, "PreferredPageSizeOptimized "); if (tc_info.tc_unified) p += sprintf(p, "Unified "); if (tc_info.tc_reduce_tr) p += sprintf(p, "TCReduction"); p += sprintf(p, "\n\tSupported page sizes: "); p = bitvector_process(p, tc_pages); /* when unified date (j=2) is enough */ if (tc_info.tc_unified) break; } } } p += sprintf(p, "\n"); return p - page; } static int register_info(char *page) { char *p = page; u64 reg_info[2]; u64 info; u64 phys_stacked; pal_hints_u_t hints; u64 iregs, dregs; char *info_type[]={ "Implemented AR(s)", "AR(s) with read side-effects", "Implemented CR(s)", "CR(s) with read side-effects", }; for(info=0; info < 4; info++) { if (ia64_pal_register_info(info, &reg_info[0], &reg_info[1]) != 0) return 0; p += sprintf(p, "%-32s : ", info_type[info]); p = bitregister_process(p, reg_info, 128); p += sprintf(p, "\n"); } if (ia64_pal_rse_info(&phys_stacked, &hints) == 0) { p += sprintf(p, "RSE stacked physical registers : %ld\n" "RSE load/store hints : %ld (%s)\n", phys_stacked, hints.ph_data, hints.ph_data < RSE_HINTS_COUNT ? rse_hints[hints.ph_data]: "(??)"); } if (ia64_pal_debug_info(&iregs, &dregs)) return 0; p += sprintf(p, "Instruction debug register pairs : %ld\n" "Data debug register pairs : %ld\n", iregs, dregs); return p - page; } static const char *proc_features[]={ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL, "Unimplemented instruction address fault", "INIT, PMI, and LINT pins", "Simple unimplemented instr addresses", "Variable P-state performance", "Virtual machine features implemented", "XIP,XPSR,XFS implemented", "XR1-XR3 implemented", "Disable dynamic predicate prediction", "Disable processor physical number", "Disable dynamic data cache prefetch", "Disable dynamic inst cache prefetch", "Disable dynamic branch prediction", NULL, NULL, NULL, NULL, "Disable P-states", "Enable MCA on Data Poisoning", "Enable vmsw instruction", "Enable extern environmental notification", "Disable BINIT on processor time-out", "Disable dynamic power management (DPM)", "Disable coherency", "Disable cache", "Enable CMCI promotion", "Enable MCA to BINIT promotion", "Enable MCA promotion", "Enable BERR promotion" }; static int processor_info(char *page) { char *p = page; const char **v = proc_features; u64 avail=1, status=1, control=1; int i; s64 ret; if ((ret=ia64_pal_proc_get_features(&avail, &status, &control)) != 0) return 0; for(i=0; i < 64; i++, v++,avail >>=1, status >>=1, control >>=1) { if ( ! *v ) continue; p += sprintf(p, "%-40s : %s%s %s\n", *v, avail & 0x1 ? "" : "NotImpl", avail & 0x1 ? (status & 0x1 ? "On" : "Off"): "", avail & 0x1 ? (control & 0x1 ? "Ctrl" : "NoCtrl"): ""); } return p - page; } static const char *bus_features[]={ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL, NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, NULL,NULL, "Request Bus Parking", "Bus Lock Mask", "Enable Half Transfer", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, "Enable Cache Line Repl. Shared", "Enable Cache Line Repl. Exclusive", "Disable Transaction Queuing", "Disable Response Error Checking", "Disable Bus Error Checking", "Disable Bus Requester Internal Error Signalling", "Disable Bus Requester Error Signalling", "Disable Bus Initialization Event Checking", "Disable Bus Initialization Event Signalling", "Disable Bus Address Error Checking", "Disable Bus Address Error Signalling", "Disable Bus Data Error Checking" }; static int bus_info(char *page) { char *p = page; const char **v = bus_features; pal_bus_features_u_t av, st, ct; u64 avail, status, control; int i; s64 ret; if ((ret=ia64_pal_bus_get_features(&av, &st, &ct)) != 0) return 0; avail = av.pal_bus_features_val; status = st.pal_bus_features_val; control = ct.pal_bus_features_val; for(i=0; i < 64; i++, v++, avail >>=1, status >>=1, control >>=1) { if ( ! *v ) continue; p += sprintf(p, "%-48s : %s%s %s\n", *v, avail & 0x1 ? "" : "NotImpl", avail & 0x1 ? (status & 0x1 ? "On" : "Off"): "", avail & 0x1 ? (control & 0x1 ? "Ctrl" : "NoCtrl"): ""); } return p - page; } static int version_info(char *page) { pal_version_u_t min_ver, cur_ver; char *p = page; if (ia64_pal_version(&min_ver, &cur_ver) != 0) return 0; p += sprintf(p, "PAL_vendor : 0x%02x (min=0x%02x)\n" "PAL_A : %02x.%02x (min=%02x.%02x)\n" "PAL_B : %02x.%02x (min=%02x.%02x)\n", cur_ver.pal_version_s.pv_pal_vendor, min_ver.pal_version_s.pv_pal_vendor, cur_ver.pal_version_s.pv_pal_a_model, cur_ver.pal_version_s.pv_pal_a_rev, min_ver.pal_version_s.pv_pal_a_model, min_ver.pal_version_s.pv_pal_a_rev, cur_ver.pal_version_s.pv_pal_b_model, cur_ver.pal_version_s.pv_pal_b_rev, min_ver.pal_version_s.pv_pal_b_model, min_ver.pal_version_s.pv_pal_b_rev); return p - page; } static int perfmon_info(char *page) { char *p = page; u64 pm_buffer[16]; pal_perf_mon_info_u_t pm_info; if (ia64_pal_perf_mon_info(pm_buffer, &pm_info) != 0) return 0; p += sprintf(p, "PMC/PMD pairs : %d\n" "Counter width : %d bits\n" "Cycle event number : %d\n" "Retired event number : %d\n" "Implemented PMC : ", pm_info.pal_perf_mon_info_s.generic, pm_info.pal_perf_mon_info_s.width, pm_info.pal_perf_mon_info_s.cycles, pm_info.pal_perf_mon_info_s.retired); p = bitregister_process(p, pm_buffer, 256); p += sprintf(p, "\nImplemented PMD : "); p = bitregister_process(p, pm_buffer+4, 256); p += sprintf(p, "\nCycles count capable : "); p = bitregister_process(p, pm_buffer+8, 256); p += sprintf(p, "\nRetired bundles count capable : "); #ifdef CONFIG_ITANIUM /* * PAL_PERF_MON_INFO reports that only PMC4 can be used to count CPU_CYCLES * which is wrong, both PMC4 and PMD5 support it. */ if (pm_buffer[12] == 0x10) pm_buffer[12]=0x30; #endif p = bitregister_process(p, pm_buffer+12, 256); p += sprintf(p, "\n"); return p - page; } static int frequency_info(char *page) { char *p = page; struct pal_freq_ratio proc, itc, bus; u64 base; if (ia64_pal_freq_base(&base) == -1) p += sprintf(p, "Output clock : not implemented\n"); else p += sprintf(p, "Output clock : %ld ticks/s\n", base); if (ia64_pal_freq_ratios(&proc, &bus, &itc) != 0) return 0; p += sprintf(p, "Processor/Clock ratio : %d/%d\n" "Bus/Clock ratio : %d/%d\n" "ITC/Clock ratio : %d/%d\n", proc.num, proc.den, bus.num, bus.den, itc.num, itc.den); return p - page; } static int tr_info(char *page) { char *p = page; s64 status; pal_tr_valid_u_t tr_valid; u64 tr_buffer[4]; pal_vm_info_1_u_t vm_info_1; pal_vm_info_2_u_t vm_info_2; u64 i, j; u64 max[3], pgm; struct ifa_reg { u64 valid:1; u64 ig:11; u64 vpn:52; } *ifa_reg; struct itir_reg { u64 rv1:2; u64 ps:6; u64 key:24; u64 rv2:32; } *itir_reg; struct gr_reg { u64 p:1; u64 rv1:1; u64 ma:3; u64 a:1; u64 d:1; u64 pl:2; u64 ar:3; u64 ppn:38; u64 rv2:2; u64 ed:1; u64 ig:11; } *gr_reg; struct rid_reg { u64 ig1:1; u64 rv1:1; u64 ig2:6; u64 rid:24; u64 rv2:32; } *rid_reg; if ((status = ia64_pal_vm_summary(&vm_info_1, &vm_info_2)) !=0) { printk(KERN_ERR "ia64_pal_vm_summary=%ld\n", status); return 0; } max[0] = vm_info_1.pal_vm_info_1_s.max_itr_entry+1; max[1] = vm_info_1.pal_vm_info_1_s.max_dtr_entry+1; for (i=0; i < 2; i++ ) { for (j=0; j < max[i]; j++) { status = ia64_pal_tr_read(j, i, tr_buffer, &tr_valid); if (status != 0) { printk(KERN_ERR "palinfo: pal call failed on tr[%lu:%lu]=%ld\n", i, j, status); continue; } ifa_reg = (struct ifa_reg *)&tr_buffer[2]; if (ifa_reg->valid == 0) continue; gr_reg = (struct gr_reg *)tr_buffer; itir_reg = (struct itir_reg *)&tr_buffer[1]; rid_reg = (struct rid_reg *)&tr_buffer[3]; pgm = -1 << (itir_reg->ps - 12); p += sprintf(p, "%cTR%lu: av=%d pv=%d dv=%d mv=%d\n" "\tppn : 0x%lx\n" "\tvpn : 0x%lx\n" "\tps : ", "ID"[i], j, tr_valid.pal_tr_valid_s.access_rights_valid, tr_valid.pal_tr_valid_s.priv_level_valid, tr_valid.pal_tr_valid_s.dirty_bit_valid, tr_valid.pal_tr_valid_s.mem_attr_valid, (gr_reg->ppn & pgm)<< 12, (ifa_reg->vpn & pgm)<< 12); p = bitvector_process(p, 1<< itir_reg->ps); p += sprintf(p, "\n\tpl : %d\n" "\tar : %d\n" "\trid : %x\n" "\tp : %d\n" "\tma : %d\n" "\td : %d\n", gr_reg->pl, gr_reg->ar, rid_reg->rid, gr_reg->p, gr_reg->ma, gr_reg->d); } } return p - page; } /* * List {name,function} pairs for every entry in /proc/palinfo/cpu* */ static palinfo_entry_t palinfo_entries[]={ { "version_info", version_info, }, { "vm_info", vm_info, }, { "cache_info", cache_info, }, { "power_info", power_info, }, { "register_info", register_info, }, { "processor_info", processor_info, }, { "perfmon_info", perfmon_info, }, { "frequency_info", frequency_info, }, { "bus_info", bus_info }, { "tr_info", tr_info, } }; #define NR_PALINFO_ENTRIES (int) ARRAY_SIZE(palinfo_entries) /* * this array is used to keep track of the proc entries we create. This is * required in the module mode when we need to remove all entries. The procfs code * does not do recursion of deletion * * Notes: * - +1 accounts for the cpuN directory entry in /proc/pal */ #define NR_PALINFO_PROC_ENTRIES (NR_CPUS*(NR_PALINFO_ENTRIES+1)) static struct proc_dir_entry *palinfo_proc_entries[NR_PALINFO_PROC_ENTRIES]; static struct proc_dir_entry *palinfo_dir; /* * This data structure is used to pass which cpu,function is being requested * It must fit in a 64bit quantity to be passed to the proc callback routine * * In SMP mode, when we get a request for another CPU, we must call that * other CPU using IPI and wait for the result before returning. */ typedef union { u64 value; struct { unsigned req_cpu: 32; /* for which CPU this info is */ unsigned func_id: 32; /* which function is requested */ } pal_func_cpu; } pal_func_cpu_u_t; #define req_cpu pal_func_cpu.req_cpu #define func_id pal_func_cpu.func_id #ifdef CONFIG_SMP /* * used to hold information about final function to call */ typedef struct { palinfo_func_t func; /* pointer to function to call */ char *page; /* buffer to store results */ int ret; /* return value from call */ } palinfo_smp_data_t; /* * this function does the actual final call and he called * from the smp code, i.e., this is the palinfo callback routine */ static void palinfo_smp_call(void *info) { palinfo_smp_data_t *data = (palinfo_smp_data_t *)info; if (data == NULL) { printk(KERN_ERR "palinfo: data pointer is NULL\n"); data->ret = 0; /* no output */ return; } /* does this actual call */ data->ret = (*data->func)(data->page); } /* * function called to trigger the IPI, we need to access a remote CPU * Return: * 0 : error or nothing to output * otherwise how many bytes in the "page" buffer were written */ static int palinfo_handle_smp(pal_func_cpu_u_t *f, char *page) { palinfo_smp_data_t ptr; int ret; ptr.func = palinfo_entries[f->func_id].proc_read; ptr.page = page; ptr.ret = 0; /* just in case */ /* will send IPI to other CPU and wait for completion of remote call */ if ((ret=smp_call_function_single(f->req_cpu, palinfo_smp_call, &ptr, 0, 1))) { printk(KERN_ERR "palinfo: remote CPU call from %d to %d on function %d: " "error %d\n", smp_processor_id(), f->req_cpu, f->func_id, ret); return 0; } return ptr.ret; } #else /* ! CONFIG_SMP */ static int palinfo_handle_smp(pal_func_cpu_u_t *f, char *page) { printk(KERN_ERR "palinfo: should not be called with non SMP kernel\n"); return 0; } #endif /* CONFIG_SMP */ /* * Entry point routine: all calls go through this function */ static int palinfo_read_entry(char *page, char **start, off_t off, int count, int *eof, void *data) { int len=0; pal_func_cpu_u_t *f = (pal_func_cpu_u_t *)&data; /* * in SMP mode, we may need to call another CPU to get correct * information. PAL, by definition, is processor specific */ if (f->req_cpu == get_cpu()) len = (*palinfo_entries[f->func_id].proc_read)(page); else len = palinfo_handle_smp(f, page); put_cpu(); if (len <= off+count) *eof = 1; *start = page + off; len -= off; if (len>count) len = count; if (len<0) len = 0; return len; } static void create_palinfo_proc_entries(unsigned int cpu) { # define CPUSTR "cpu%d" pal_func_cpu_u_t f; struct proc_dir_entry **pdir; struct proc_dir_entry *cpu_dir; int j; char cpustr[sizeof(CPUSTR)]; /* * we keep track of created entries in a depth-first order for * cleanup purposes. Each entry is stored into palinfo_proc_entries */ sprintf(cpustr,CPUSTR, cpu); cpu_dir = proc_mkdir(cpustr, palinfo_dir); f.req_cpu = cpu; /* * Compute the location to store per cpu entries * We dont store the top level entry in this list, but * remove it finally after removing all cpu entries. */ pdir = &palinfo_proc_entries[cpu*(NR_PALINFO_ENTRIES+1)]; *pdir++ = cpu_dir; for (j=0; j < NR_PALINFO_ENTRIES; j++) { f.func_id = j; *pdir = create_proc_read_entry( palinfo_entries[j].name, 0, cpu_dir, palinfo_read_entry, (void *)f.value); if (*pdir) (*pdir)->owner = THIS_MODULE; pdir++; } } static void remove_palinfo_proc_entries(unsigned int hcpu) { int j; struct proc_dir_entry *cpu_dir, **pdir; pdir = &palinfo_proc_entries[hcpu*(NR_PALINFO_ENTRIES+1)]; cpu_dir = *pdir; *pdir++=NULL; for (j=0; j < (NR_PALINFO_ENTRIES); j++) { if ((*pdir)) { remove_proc_entry ((*pdir)->name, cpu_dir); *pdir ++= NULL; } } if (cpu_dir) { remove_proc_entry(cpu_dir->name, palinfo_dir); } } static int palinfo_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned int hotcpu = (unsigned long)hcpu; switch (action) { case CPU_ONLINE: case CPU_ONLINE_FROZEN: create_palinfo_proc_entries(hotcpu); break; case CPU_DEAD: case CPU_DEAD_FROZEN: remove_palinfo_proc_entries(hotcpu); break; } return NOTIFY_OK; } static struct notifier_block palinfo_cpu_notifier = { .notifier_call = palinfo_cpu_callback, .priority = 0, }; static int __init palinfo_init(void) { int i = 0; printk(KERN_INFO "PAL Information Facility v%s\n", PALINFO_VERSION); palinfo_dir = proc_mkdir("pal", NULL); /* Create palinfo dirs in /proc for all online cpus */ for_each_online_cpu(i) { create_palinfo_proc_entries(i); } /* Register for future delivery via notify registration */ register_hotcpu_notifier(&palinfo_cpu_notifier); return 0; } static void __exit palinfo_exit(void) { int i = 0; /* remove all nodes: depth first pass. Could optimize this */ for_each_online_cpu(i) { remove_palinfo_proc_entries(i); } /* * Remove the top level entry finally */ remove_proc_entry(palinfo_dir->name, NULL); /* * Unregister from cpu notifier callbacks */ unregister_hotcpu_notifier(&palinfo_cpu_notifier); } module_init(palinfo_init); module_exit(palinfo_exit);
147412.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" volatile int8_t x109 = INT8_MIN; volatile int64_t t1 = -22447123374041LL; uint32_t x187 = 2U; uint32_t x425 = 400U; uint64_t x426 = UINT64_MAX; static uint64_t x428 = UINT64_MAX; int64_t x485 = INT64_MIN; int64_t t4 = -23784173146LL; uint32_t t7 = 127379U; static int64_t x617 = 4729833630468LL; int8_t x619 = 3; volatile int64_t t9 = 23737533336386LL; uint16_t x672 = 37U; uint16_t x871 = 0U; volatile uint64_t t15 = 3393882333708731LLU; uint64_t x1004 = UINT64_MAX; static uint64_t x1009 = 3LLU; int64_t x1010 = INT64_MAX; int8_t x1011 = 0; uint8_t x1307 = 1U; volatile uint32_t t19 = 25U; int16_t x1401 = INT16_MAX; int32_t x1404 = -4; int32_t x1464 = 3733510; uint8_t x1805 = UINT8_MAX; uint64_t t27 = 22095179419LLU; uint8_t x2335 = 6U; static volatile int16_t x2654 = INT16_MAX; int32_t x2655 = 0; volatile uint32_t x2785 = UINT32_MAX; static uint16_t x2787 = 1U; int8_t x2824 = 0; volatile uint64_t t35 = 11360900022438LLU; uint32_t x2977 = UINT32_MAX; int16_t x3104 = -1; int16_t x3145 = INT16_MIN; int8_t x3148 = INT8_MIN; static volatile int8_t x3154 = 0; volatile int64_t x3180 = INT64_MIN; int8_t x3321 = 4; static int8_t x3322 = 1; static volatile int32_t t42 = -7160969; volatile uint64_t x3385 = UINT64_MAX; uint32_t x3386 = 517U; int16_t x3387 = 4; volatile uint64_t t44 = 14717055LLU; int32_t t45 = -689609943; volatile uint64_t x3586 = UINT64_MAX; volatile int64_t x3672 = -1LL; int64_t t48 = -738998LL; uint8_t x3684 = UINT8_MAX; volatile int8_t x3696 = -1; int8_t x3949 = -1; int16_t x3951 = 11; volatile uint8_t x4195 = 10U; uint16_t x4238 = UINT16_MAX; static int8_t x4257 = -1; uint64_t x4310 = 1050942120LLU; uint16_t x4311 = 1U; int8_t x4415 = 0; static int64_t t62 = 9116093014LL; volatile uint32_t x4595 = 11U; uint32_t x4740 = UINT32_MAX; int64_t t64 = -7492281LL; static volatile uint64_t x4770 = 86564LLU; static volatile int8_t x4851 = 5; uint64_t t67 = 4945729156LLU; uint64_t x4866 = 68403305902549709LLU; static uint8_t x4868 = UINT8_MAX; volatile int8_t x4969 = -1; uint64_t x4970 = 109876518452118LLU; volatile uint64_t t69 = 257646318283LLU; static uint16_t x5008 = 1U; volatile uint64_t t73 = 70313819858458LLU; volatile uint64_t t74 = 114886107269521LLU; uint64_t x5234 = 51081135683LLU; volatile int8_t x5247 = 29; static volatile uint64_t t77 = 24297150LLU; volatile int64_t x5462 = 4101282435798126825LL; uint32_t x5839 = 0U; int16_t x6094 = 969; uint16_t x6252 = 1U; int64_t x6316 = INT64_MIN; volatile uint64_t t86 = 1LLU; uint8_t x6537 = UINT8_MAX; static uint16_t x6570 = UINT16_MAX; uint8_t x6571 = 6U; uint8_t x6572 = 6U; int32_t t88 = 73093; volatile uint8_t x6726 = 26U; int32_t x6728 = -1; volatile int32_t t90 = -678; int32_t x6789 = INT32_MIN; uint32_t x6791 = 0U; int32_t x6845 = -1; volatile int32_t t94 = -1; uint8_t x6859 = 2U; uint8_t x6938 = 0U; uint8_t x6939 = 14U; volatile uint16_t x7153 = 1542U; uint64_t x7154 = UINT64_MAX; static int16_t x7291 = 1; static uint32_t x7306 = 6021167U; volatile int64_t t101 = -547849LL; int32_t x7309 = -33; volatile uint8_t x7310 = UINT8_MAX; uint32_t t102 = 16245518U; uint64_t t103 = 32527633LLU; uint32_t x7630 = UINT32_MAX; int8_t x7632 = INT8_MIN; uint32_t x7786 = 112223U; volatile uint32_t x7789 = 18773215U; volatile uint64_t t109 = 215280546LLU; uint64_t x7986 = 485717266813339LLU; volatile int8_t x8137 = 0; uint64_t t114 = 59743LLU; int8_t x8241 = -1; int32_t x8244 = INT32_MIN; static volatile uint64_t x8437 = 1462754456048162LLU; int8_t x8439 = 0; static uint64_t x8450 = UINT64_MAX; volatile uint64_t t117 = 90882677LLU; int16_t x8557 = INT16_MIN; int64_t x8560 = -410LL; int8_t x8617 = -1; static volatile uint8_t x8619 = 3U; volatile uint32_t x8640 = 99293U; int64_t x8822 = INT64_MAX; int32_t x8823 = 10; int32_t x8824 = 12580495; volatile int16_t x8863 = 18; int64_t t126 = -268656697105375LL; static uint8_t x9366 = 1U; volatile uint32_t x9368 = 41U; uint16_t x9377 = 152U; int64_t t133 = 3926080454875586836LL; int8_t x9586 = 3; int64_t x9636 = -1267843340955LL; int16_t x9689 = INT16_MIN; static volatile int64_t t137 = -148308618575LL; int16_t x9889 = INT16_MAX; uint8_t x9891 = 2U; volatile uint64_t t140 = 2LLU; uint16_t x10027 = 5U; uint32_t x10106 = 2670U; volatile uint8_t x10107 = 1U; volatile int64_t t143 = -1911LL; volatile int32_t x10232 = INT32_MAX; volatile uint64_t t145 = 148171023688851502LLU; static volatile int32_t t146 = -1005135; uint32_t x10301 = 127127U; int32_t x10302 = 77; uint32_t t147 = 187819873U; uint8_t x10306 = 26U; volatile int32_t t148 = 537584295; volatile int32_t x10481 = INT32_MAX; static int16_t x10485 = INT16_MAX; static volatile uint8_t x10487 = 0U; static uint16_t x10491 = 0U; int8_t x10492 = -1; int32_t x10638 = 1; uint64_t x10640 = UINT64_MAX; uint32_t x10846 = UINT32_MAX; uint8_t x10847 = 1U; volatile uint32_t x10914 = 13U; volatile int32_t x10917 = INT32_MIN; uint32_t x10918 = 33858511U; static int64_t x11017 = 236250514695LL; int32_t x11018 = INT32_MAX; int16_t x11029 = 1309; uint32_t x11050 = 33828472U; int8_t x11052 = 59; volatile uint32_t t158 = 392U; volatile uint64_t x11233 = 15997154LLU; static volatile int16_t x11235 = 13; volatile uint16_t x11461 = 110U; uint64_t t162 = 146421549233361664LLU; int64_t x11531 = 16LL; int32_t x11545 = INT32_MIN; volatile int64_t t164 = -18524919444LL; uint64_t x11553 = 5571948677606LLU; int16_t x11554 = INT16_MAX; uint64_t x11669 = 4539238LLU; volatile uint64_t t166 = 7728847728868619LLU; static uint16_t x11872 = 16U; static volatile int32_t t168 = 44215; volatile uint8_t x11927 = 1U; static uint8_t x12014 = 127U; volatile int8_t x12530 = 3; int16_t x12626 = 28; int32_t x12660 = INT32_MIN; volatile int64_t t177 = 3272525258461254LL; int8_t x12982 = INT8_MAX; volatile uint64_t x13193 = 691793192LLU; uint32_t x13235 = 6U; int32_t x13245 = 582541; uint16_t x13283 = 0U; int8_t x13769 = -16; uint8_t x13831 = 7U; int8_t x13867 = 4; uint16_t x14086 = UINT16_MAX; static int8_t x14186 = INT8_MAX; static int32_t t199 = -68; void f0(void) { uint8_t x110 = 10U; uint16_t x111 = 0U; int32_t x112 = -1411; int32_t t0 = -114; t0 = ((x109+(x110>>x111))*x112); if (t0 != 166498) { NG(); } else { ; } } void f1(void) { static int16_t x137 = -1; int16_t x138 = 1; int16_t x139 = 1; int64_t x140 = 162266600857861387LL; t1 = ((x137+(x138>>x139))*x140); if (t1 != -162266600857861387LL) { NG(); } else { ; } } void f2(void) { int64_t x185 = 15399450669689LL; uint32_t x186 = 2280856U; int16_t x188 = 1; volatile int64_t t2 = -5289371970LL; t2 = ((x185+(x186>>x187))*x188); if (t2 != 15399451239903LL) { NG(); } else { ; } } void f3(void) { uint16_t x427 = 55U; volatile uint64_t t3 = 6986797LLU; t3 = ((x425+(x426>>x427))*x428); if (t3 != 18446744073709550705LLU) { NG(); } else { ; } } void f4(void) { uint32_t x486 = 96401U; uint8_t x487 = 12U; int64_t x488 = -1LL; t4 = ((x485+(x486>>x487))*x488); if (t4 != 9223372036854775785LL) { NG(); } else { ; } } void f5(void) { static int16_t x497 = 1; uint8_t x498 = UINT8_MAX; uint8_t x499 = 8U; static volatile int64_t x500 = -1LL; static int64_t t5 = 15051LL; t5 = ((x497+(x498>>x499))*x500); if (t5 != -1LL) { NG(); } else { ; } } void f6(void) { volatile int64_t x553 = INT64_MIN; int64_t x554 = 168LL; uint8_t x555 = 1U; static int8_t x556 = 1; static int64_t t6 = 98912064769231222LL; t6 = ((x553+(x554>>x555))*x556); if (t6 != -9223372036854775724LL) { NG(); } else { ; } } void f7(void) { int32_t x589 = -31; static uint32_t x590 = UINT32_MAX; volatile uint8_t x591 = 3U; int16_t x592 = INT16_MIN; t7 = ((x589+(x590>>x591))*x592); if (t7 != 1048576U) { NG(); } else { ; } } void f8(void) { int8_t x605 = INT8_MAX; static uint64_t x606 = 15270392103LLU; static int8_t x607 = 1; static int8_t x608 = INT8_MIN; static volatile uint64_t t8 = 5LLU; t8 = ((x605+(x606>>x607))*x608); if (t8 != 18446743096404440832LLU) { NG(); } else { ; } } void f9(void) { int16_t x618 = INT16_MAX; int64_t x620 = -895522LL; t9 = ((x617+(x618>>x619))*x620); if (t9 != -4235670076091126886LL) { NG(); } else { ; } } void f10(void) { int8_t x669 = INT8_MIN; static int32_t x670 = 7; static uint8_t x671 = 29U; static int32_t t10 = 427384484; t10 = ((x669+(x670>>x671))*x672); if (t10 != -4736) { NG(); } else { ; } } void f11(void) { int16_t x741 = INT16_MIN; uint8_t x742 = 44U; int8_t x743 = 0; int8_t x744 = -4; int32_t t11 = 221793; t11 = ((x741+(x742>>x743))*x744); if (t11 != 130896) { NG(); } else { ; } } void f12(void) { uint64_t x869 = UINT64_MAX; volatile uint8_t x870 = 5U; int64_t x872 = INT64_MIN; static uint64_t t12 = 7041857839LLU; t12 = ((x869+(x870>>x871))*x872); if (t12 != 0LLU) { NG(); } else { ; } } void f13(void) { int16_t x877 = INT16_MIN; static volatile uint64_t x878 = 5606089473906021923LLU; uint16_t x879 = 37U; static int64_t x880 = -1406LL; volatile uint64_t t13 = 42215351LLU; t13 = ((x877+(x878>>x879))*x880); if (t13 != 18446744016405348810LLU) { NG(); } else { ; } } void f14(void) { volatile int8_t x889 = INT8_MIN; static uint32_t x890 = UINT32_MAX; static int8_t x891 = 1; int16_t x892 = 7; volatile uint32_t t14 = 845038029U; t14 = ((x889+(x890>>x891))*x892); if (t14 != 2147482745U) { NG(); } else { ; } } void f15(void) { int32_t x913 = -1; uint64_t x914 = 233433340137LLU; int8_t x915 = 3; static uint16_t x916 = 7U; t15 = ((x913+(x914>>x915))*x916); if (t15 != 204254172612LLU) { NG(); } else { ; } } void f16(void) { int32_t x917 = INT32_MIN; volatile int16_t x918 = INT16_MAX; static volatile int16_t x919 = 1; int8_t x920 = -1; int32_t t16 = 450294348; t16 = ((x917+(x918>>x919))*x920); if (t16 != 2147467265) { NG(); } else { ; } } void f17(void) { static int64_t x1001 = 12527510592621290LL; uint32_t x1002 = 852613281U; int8_t x1003 = 1; static uint64_t t17 = 49418027840843189LLU; t17 = ((x1001+(x1002>>x1003))*x1004); if (t17 != 18434216562690623686LLU) { NG(); } else { ; } } void f18(void) { volatile int32_t x1012 = INT32_MIN; uint64_t t18 = 180721531607LLU; t18 = ((x1009+(x1010>>x1011))*x1012); if (t18 != 18446744069414584320LLU) { NG(); } else { ; } } void f19(void) { uint32_t x1305 = UINT32_MAX; static int32_t x1306 = 3759; static volatile uint8_t x1308 = 4U; t19 = ((x1305+(x1306>>x1307))*x1308); if (t19 != 7512U) { NG(); } else { ; } } void f20(void) { uint16_t x1341 = 4U; static int32_t x1342 = 483813193; volatile uint8_t x1343 = 0U; int8_t x1344 = 1; volatile int32_t t20 = 0; t20 = ((x1341+(x1342>>x1343))*x1344); if (t20 != 483813197) { NG(); } else { ; } } void f21(void) { static uint32_t x1402 = 18U; int8_t x1403 = 26; uint32_t t21 = 1U; t21 = ((x1401+(x1402>>x1403))*x1404); if (t21 != 4294836228U) { NG(); } else { ; } } void f22(void) { uint32_t x1461 = 126U; uint32_t x1462 = UINT32_MAX; static int8_t x1463 = 0; uint32_t t22 = 369368651U; t22 = ((x1461+(x1462>>x1463))*x1464); if (t22 != 466688750U) { NG(); } else { ; } } void f23(void) { int32_t x1497 = INT32_MIN; volatile uint32_t x1498 = 967U; volatile uint32_t x1499 = 8U; uint64_t x1500 = 366LLU; uint64_t t23 = 271591LLU; t23 = ((x1497+(x1498>>x1499))*x1500); if (t23 != 785979016266LLU) { NG(); } else { ; } } void f24(void) { int32_t x1806 = 33; volatile int16_t x1807 = 0; volatile uint8_t x1808 = 0U; volatile int32_t t24 = 1529; t24 = ((x1805+(x1806>>x1807))*x1808); if (t24 != 0) { NG(); } else { ; } } void f25(void) { int32_t x1865 = 7190; uint32_t x1866 = 40U; volatile uint8_t x1867 = 14U; int32_t x1868 = -318169530; uint32_t t25 = 1027U; t25 = ((x1865+(x1866>>x1867))*x1868); if (t25 != 1578648068U) { NG(); } else { ; } } void f26(void) { int8_t x2085 = INT8_MAX; uint16_t x2086 = 697U; int8_t x2087 = 2; int16_t x2088 = INT16_MIN; static int32_t t26 = 0; t26 = ((x2085+(x2086>>x2087))*x2088); if (t26 != -9863168) { NG(); } else { ; } } void f27(void) { int16_t x2169 = -1; int16_t x2170 = INT16_MAX; uint8_t x2171 = 12U; uint64_t x2172 = 49612701LLU; t27 = ((x2169+(x2170>>x2171))*x2172); if (t27 != 297676206LLU) { NG(); } else { ; } } void f28(void) { int16_t x2333 = -10354; volatile int16_t x2334 = 393; uint32_t x2336 = 12U; uint32_t t28 = 534906U; t28 = ((x2333+(x2334>>x2335))*x2336); if (t28 != 4294843120U) { NG(); } else { ; } } void f29(void) { volatile int8_t x2445 = -12; int64_t x2446 = INT64_MAX; static uint8_t x2447 = 3U; int32_t x2448 = -1; int64_t t29 = -11113900527930847LL; t29 = ((x2445+(x2446>>x2447))*x2448); if (t29 != -1152921504606846963LL) { NG(); } else { ; } } void f30(void) { int8_t x2561 = INT8_MIN; static int32_t x2562 = 5349; uint8_t x2563 = 10U; uint8_t x2564 = UINT8_MAX; int32_t t30 = -23107; t30 = ((x2561+(x2562>>x2563))*x2564); if (t30 != -31365) { NG(); } else { ; } } void f31(void) { uint16_t x2585 = 2782U; volatile uint16_t x2586 = UINT16_MAX; uint16_t x2587 = 0U; int8_t x2588 = -18; static int32_t t31 = -13161939; t31 = ((x2585+(x2586>>x2587))*x2588); if (t31 != -1229706) { NG(); } else { ; } } void f32(void) { int64_t x2653 = 1366535LL; uint16_t x2656 = UINT16_MAX; volatile int64_t t32 = 66626364421LL; t32 = ((x2653+(x2654>>x2655))*x2656); if (t32 != 91703256570LL) { NG(); } else { ; } } void f33(void) { static uint8_t x2786 = UINT8_MAX; volatile int32_t x2788 = INT32_MIN; volatile uint32_t t33 = 409599U; t33 = ((x2785+(x2786>>x2787))*x2788); if (t33 != 0U) { NG(); } else { ; } } void f34(void) { volatile int64_t x2821 = -1LL; uint32_t x2822 = 1196748871U; static volatile int16_t x2823 = 1; static volatile int64_t t34 = 6LL; t34 = ((x2821+(x2822>>x2823))*x2824); if (t34 != 0LL) { NG(); } else { ; } } void f35(void) { int32_t x2917 = -1; int64_t x2918 = INT64_MAX; int8_t x2919 = 56; uint64_t x2920 = 380026571842LLU; t35 = ((x2917+(x2918>>x2919))*x2920); if (t35 != 47883348052092LLU) { NG(); } else { ; } } void f36(void) { uint8_t x2978 = 49U; uint16_t x2979 = 11U; static uint8_t x2980 = UINT8_MAX; static uint32_t t36 = 30U; t36 = ((x2977+(x2978>>x2979))*x2980); if (t36 != 4294967041U) { NG(); } else { ; } } void f37(void) { uint64_t x3101 = UINT64_MAX; int16_t x3102 = INT16_MAX; volatile uint16_t x3103 = 14U; uint64_t t37 = 338LLU; t37 = ((x3101+(x3102>>x3103))*x3104); if (t37 != 0LLU) { NG(); } else { ; } } void f38(void) { volatile uint64_t x3146 = UINT64_MAX; int8_t x3147 = 6; volatile uint64_t t38 = 11915190110LLU; t38 = ((x3145+(x3146>>x3147))*x3148); if (t38 != 4194432LLU) { NG(); } else { ; } } void f39(void) { static uint64_t x3153 = 282LLU; volatile int16_t x3155 = 0; volatile int32_t x3156 = INT32_MAX; volatile uint64_t t39 = 19LLU; t39 = ((x3153+(x3154>>x3155))*x3156); if (t39 != 605590388454LLU) { NG(); } else { ; } } void f40(void) { static uint32_t x3173 = 0U; int16_t x3174 = 115; int16_t x3175 = 15; uint64_t x3176 = UINT64_MAX; volatile uint64_t t40 = 337347874522407619LLU; t40 = ((x3173+(x3174>>x3175))*x3176); if (t40 != 0LLU) { NG(); } else { ; } } void f41(void) { int16_t x3177 = INT16_MIN; volatile uint64_t x3178 = 248558LLU; static volatile uint16_t x3179 = 2U; uint64_t t41 = 6421222390595749LLU; t41 = ((x3177+(x3178>>x3179))*x3180); if (t41 != 9223372036854775808LLU) { NG(); } else { ; } } void f42(void) { volatile uint32_t x3323 = 18U; volatile uint8_t x3324 = 0U; t42 = ((x3321+(x3322>>x3323))*x3324); if (t42 != 0) { NG(); } else { ; } } void f43(void) { static int16_t x3337 = INT16_MIN; int64_t x3338 = 208287LL; volatile uint64_t x3339 = 2LLU; uint8_t x3340 = UINT8_MAX; int64_t t43 = 67933179185LL; t43 = ((x3337+(x3338>>x3339))*x3340); if (t43 != 4922265LL) { NG(); } else { ; } } void f44(void) { uint64_t x3388 = UINT64_MAX; t44 = ((x3385+(x3386>>x3387))*x3388); if (t44 != 18446744073709551585LLU) { NG(); } else { ; } } void f45(void) { uint16_t x3425 = 22U; uint16_t x3426 = 1U; volatile int8_t x3427 = 1; volatile int8_t x3428 = INT8_MIN; t45 = ((x3425+(x3426>>x3427))*x3428); if (t45 != -2816) { NG(); } else { ; } } void f46(void) { volatile int64_t x3585 = INT64_MIN; int8_t x3587 = 8; int8_t x3588 = INT8_MIN; static uint64_t t46 = 709068245LLU; t46 = ((x3585+(x3586>>x3587))*x3588); if (t46 != 9223372036854775936LLU) { NG(); } else { ; } } void f47(void) { static int16_t x3593 = INT16_MIN; int64_t x3594 = 1032129020350LL; uint16_t x3595 = 1U; static uint64_t x3596 = 56359LLU; uint64_t t47 = 26277676LLU; t47 = ((x3593+(x3594>>x3595))*x3596); if (t47 != 29084877882181113LLU) { NG(); } else { ; } } void f48(void) { uint8_t x3669 = 15U; static int64_t x3670 = INT64_MAX; static uint8_t x3671 = 1U; t48 = ((x3669+(x3670>>x3671))*x3672); if (t48 != -4611686018427387918LL) { NG(); } else { ; } } void f49(void) { uint16_t x3681 = 4808U; uint64_t x3682 = 3015222161983LLU; uint8_t x3683 = 40U; static uint64_t t49 = 476146748763497LLU; t49 = ((x3681+(x3682>>x3683))*x3684); if (t49 != 1226550LLU) { NG(); } else { ; } } void f50(void) { uint64_t x3689 = 91975133963LLU; volatile int64_t x3690 = 42LL; int8_t x3691 = 2; int32_t x3692 = 10665868; uint64_t t50 = 17027724247LLU; t50 = ((x3689+(x3690>>x3691))*x3692); if (t50 != 980994638238333564LLU) { NG(); } else { ; } } void f51(void) { int64_t x3693 = INT64_MIN; uint32_t x3694 = UINT32_MAX; static uint8_t x3695 = 31U; volatile int64_t t51 = INT64_MAX; t51 = ((x3693+(x3694>>x3695))*x3696); if (t51 != INT64_MAX) { NG(); } else { ; } } void f52(void) { volatile uint64_t x3950 = UINT64_MAX; static int64_t x3952 = 31658926848158LL; uint64_t t52 = 2382617604LLU; t52 = ((x3949+(x3950>>x3951))*x3952); if (t52 != 1423074164395380420LLU) { NG(); } else { ; } } void f53(void) { int64_t x3981 = -1LL; uint8_t x3982 = 3U; uint32_t x3983 = 3U; int64_t x3984 = -1LL; int64_t t53 = 1552252LL; t53 = ((x3981+(x3982>>x3983))*x3984); if (t53 != 1LL) { NG(); } else { ; } } void f54(void) { volatile uint64_t x4125 = 202000LLU; static volatile uint16_t x4126 = UINT16_MAX; int16_t x4127 = 1; volatile int64_t x4128 = 1004057413988LL; volatile uint64_t t54 = 217201117076247LLU; t54 = ((x4125+(x4126>>x4127))*x4128); if (t54 != 235719546909720796LLU) { NG(); } else { ; } } void f55(void) { uint16_t x4193 = 448U; volatile uint16_t x4194 = 4U; uint64_t x4196 = 287625LLU; volatile uint64_t t55 = 2142LLU; t55 = ((x4193+(x4194>>x4195))*x4196); if (t55 != 128856000LLU) { NG(); } else { ; } } void f56(void) { int64_t x4221 = INT64_MIN; int64_t x4222 = INT64_MAX; uint16_t x4223 = 3U; volatile int8_t x4224 = -1; volatile int64_t t56 = -51644352LL; t56 = ((x4221+(x4222>>x4223))*x4224); if (t56 != 8070450532247928833LL) { NG(); } else { ; } } void f57(void) { volatile uint64_t x4237 = UINT64_MAX; uint64_t x4239 = 0LLU; uint16_t x4240 = 15U; volatile uint64_t t57 = 1LLU; t57 = ((x4237+(x4238>>x4239))*x4240); if (t57 != 983010LLU) { NG(); } else { ; } } void f58(void) { int8_t x4258 = 0; int16_t x4259 = 0; volatile int16_t x4260 = -6; int32_t t58 = -503212; t58 = ((x4257+(x4258>>x4259))*x4260); if (t58 != 6) { NG(); } else { ; } } void f59(void) { int16_t x4309 = -3559; volatile int64_t x4312 = -6590686791970060LL; volatile uint64_t t59 = 1350916LLU; t59 = ((x4309+(x4310>>x4311))*x4312); if (t59 != 13948016925367780LLU) { NG(); } else { ; } } void f60(void) { uint32_t x4413 = 2781337U; static volatile uint8_t x4414 = UINT8_MAX; int8_t x4416 = INT8_MIN; static uint32_t t60 = 49008057U; t60 = ((x4413+(x4414>>x4415))*x4416); if (t60 != 3938923520U) { NG(); } else { ; } } void f61(void) { int64_t x4453 = -1LL; uint8_t x4454 = 22U; uint8_t x4455 = 1U; volatile uint8_t x4456 = UINT8_MAX; volatile int64_t t61 = -10512213LL; t61 = ((x4453+(x4454>>x4455))*x4456); if (t61 != 2550LL) { NG(); } else { ; } } void f62(void) { int64_t x4573 = 41LL; uint8_t x4574 = 108U; volatile uint16_t x4575 = 13U; volatile int64_t x4576 = -1LL; t62 = ((x4573+(x4574>>x4575))*x4576); if (t62 != -41LL) { NG(); } else { ; } } void f63(void) { uint16_t x4593 = 109U; volatile int16_t x4594 = INT16_MAX; int8_t x4596 = -1; int32_t t63 = 95; t63 = ((x4593+(x4594>>x4595))*x4596); if (t63 != -124) { NG(); } else { ; } } void f64(void) { uint32_t x4737 = 1210832U; int64_t x4738 = INT64_MAX; volatile int16_t x4739 = 40; t64 = ((x4737+(x4738>>x4739))*x4740); if (t64 != 41229276555347505LL) { NG(); } else { ; } } void f65(void) { uint32_t x4769 = 29699U; int16_t x4771 = 0; int8_t x4772 = INT8_MIN; volatile uint64_t t65 = 1LLU; t65 = ((x4769+(x4770>>x4771))*x4772); if (t65 != 18446744073694669952LLU) { NG(); } else { ; } } void f66(void) { uint16_t x4773 = 0U; int16_t x4774 = INT16_MAX; volatile uint16_t x4775 = 5U; int16_t x4776 = INT16_MIN; static int32_t t66 = 170096; t66 = ((x4773+(x4774>>x4775))*x4776); if (t66 != -33521664) { NG(); } else { ; } } void f67(void) { volatile int64_t x4849 = 1702280554785421318LL; static uint64_t x4850 = 7515234LLU; uint64_t x4852 = UINT64_MAX; t67 = ((x4849+(x4850>>x4851))*x4852); if (t67 != 16744463518923895447LLU) { NG(); } else { ; } } void f68(void) { int64_t x4865 = INT64_MIN; uint16_t x4867 = 27U; static uint64_t t68 = 1131LLU; t68 = ((x4865+(x4866>>x4867))*x4868); if (t68 != 9223372166814083273LLU) { NG(); } else { ; } } void f69(void) { uint16_t x4971 = 8U; volatile int64_t x4972 = INT64_MIN; t69 = ((x4969+(x4970>>x4971))*x4972); if (t69 != 0LLU) { NG(); } else { ; } } void f70(void) { int8_t x4981 = INT8_MIN; int64_t x4982 = 1453LL; static uint64_t x4983 = 43LLU; volatile uint16_t x4984 = 17U; int64_t t70 = 84008LL; t70 = ((x4981+(x4982>>x4983))*x4984); if (t70 != -2176LL) { NG(); } else { ; } } void f71(void) { int64_t x5005 = INT64_MIN; uint64_t x5006 = 310087869500LLU; uint16_t x5007 = 43U; volatile uint64_t t71 = 257828839403470573LLU; t71 = ((x5005+(x5006>>x5007))*x5008); if (t71 != 9223372036854775808LLU) { NG(); } else { ; } } void f72(void) { int32_t x5057 = INT32_MAX; uint32_t x5058 = UINT32_MAX; volatile int8_t x5059 = 0; static uint64_t x5060 = UINT64_MAX; volatile uint64_t t72 = 2260LLU; t72 = ((x5057+(x5058>>x5059))*x5060); if (t72 != 18446744071562067970LLU) { NG(); } else { ; } } void f73(void) { uint8_t x5101 = UINT8_MAX; uint64_t x5102 = UINT64_MAX; uint8_t x5103 = 1U; static volatile int8_t x5104 = INT8_MIN; t73 = ((x5101+(x5102>>x5103))*x5104); if (t73 != 18446744073709519104LLU) { NG(); } else { ; } } void f74(void) { volatile uint64_t x5209 = 5LLU; volatile uint16_t x5210 = 13427U; static int32_t x5211 = 14; static int8_t x5212 = -25; t74 = ((x5209+(x5210>>x5211))*x5212); if (t74 != 18446744073709551491LLU) { NG(); } else { ; } } void f75(void) { int8_t x5233 = -26; uint8_t x5235 = 0U; volatile int32_t x5236 = INT32_MAX; uint64_t t75 = 42945788258052LLU; t75 = ((x5233+(x5234>>x5235))*x5236); if (t75 != 17462183125048342999LLU) { NG(); } else { ; } } void f76(void) { int16_t x5245 = INT16_MIN; uint32_t x5246 = 1682624411U; uint64_t x5248 = UINT64_MAX; uint64_t t76 = 109541149836LLU; t76 = ((x5245+(x5246>>x5247))*x5248); if (t76 != 18446744069414617085LLU) { NG(); } else { ; } } void f77(void) { int64_t x5249 = INT64_MIN; static volatile uint16_t x5250 = 4086U; uint16_t x5251 = 1U; static uint64_t x5252 = UINT64_MAX; t77 = ((x5249+(x5250>>x5251))*x5252); if (t77 != 9223372036854773765LLU) { NG(); } else { ; } } void f78(void) { uint16_t x5257 = UINT16_MAX; uint64_t x5258 = 2LLU; static int8_t x5259 = 11; int64_t x5260 = -1LL; volatile uint64_t t78 = 2270259035877784LLU; t78 = ((x5257+(x5258>>x5259))*x5260); if (t78 != 18446744073709486081LLU) { NG(); } else { ; } } void f79(void) { int16_t x5357 = -1; static int8_t x5358 = 0; uint8_t x5359 = 3U; uint16_t x5360 = UINT16_MAX; int32_t t79 = 16; t79 = ((x5357+(x5358>>x5359))*x5360); if (t79 != -65535) { NG(); } else { ; } } void f80(void) { uint32_t x5461 = 90122U; uint16_t x5463 = 2U; int16_t x5464 = -1; int64_t t80 = 4370676400733LL; t80 = ((x5461+(x5462>>x5463))*x5464); if (t80 != -1025320608949621828LL) { NG(); } else { ; } } void f81(void) { int64_t x5509 = 1LL; volatile int64_t x5510 = 2215043210824407LL; volatile int16_t x5511 = 38; static uint64_t x5512 = 868213655621421LLU; static uint64_t t81 = 1029189768491800519LLU; t81 = ((x5509+(x5510>>x5511))*x5512); if (t81 != 6996933850653031839LLU) { NG(); } else { ; } } void f82(void) { int64_t x5561 = -1LL; int32_t x5562 = 77687586; uint8_t x5563 = 31U; uint32_t x5564 = UINT32_MAX; static volatile int64_t t82 = 73LL; t82 = ((x5561+(x5562>>x5563))*x5564); if (t82 != -4294967295LL) { NG(); } else { ; } } void f83(void) { int64_t x5837 = 3563237184LL; static int8_t x5838 = 3; int32_t x5840 = INT32_MIN; volatile int64_t t83 = 1260485304811081278LL; t83 = ((x5837+(x5838>>x5839))*x5840); if (t83 != -7651993593028018176LL) { NG(); } else { ; } } void f84(void) { int32_t x6093 = -14836; int8_t x6095 = 0; int8_t x6096 = -1; int32_t t84 = 1; t84 = ((x6093+(x6094>>x6095))*x6096); if (t84 != 13867) { NG(); } else { ; } } void f85(void) { static uint16_t x6249 = 0U; int32_t x6250 = INT32_MAX; volatile uint8_t x6251 = 1U; static volatile int32_t t85 = -241271; t85 = ((x6249+(x6250>>x6251))*x6252); if (t85 != 1073741823) { NG(); } else { ; } } void f86(void) { int64_t x6313 = INT64_MIN; uint64_t x6314 = UINT64_MAX; static volatile int8_t x6315 = 1; t86 = ((x6313+(x6314>>x6315))*x6316); if (t86 != 9223372036854775808LLU) { NG(); } else { ; } } void f87(void) { int8_t x6538 = 0; uint16_t x6539 = 1U; int32_t x6540 = -102; int32_t t87 = -1; t87 = ((x6537+(x6538>>x6539))*x6540); if (t87 != -26010) { NG(); } else { ; } } void f88(void) { static int16_t x6569 = 11282; t88 = ((x6569+(x6570>>x6571))*x6572); if (t88 != 73830) { NG(); } else { ; } } void f89(void) { int8_t x6589 = INT8_MIN; static volatile uint16_t x6590 = UINT16_MAX; static uint8_t x6591 = 3U; uint32_t x6592 = UINT32_MAX; uint32_t t89 = 45718U; t89 = ((x6589+(x6590>>x6591))*x6592); if (t89 != 4294959233U) { NG(); } else { ; } } void f90(void) { int16_t x6725 = -1; volatile int32_t x6727 = 0; t90 = ((x6725+(x6726>>x6727))*x6728); if (t90 != -25) { NG(); } else { ; } } void f91(void) { uint32_t x6790 = 2U; uint16_t x6792 = 30646U; volatile uint32_t t91 = 3238682U; t91 = ((x6789+(x6790>>x6791))*x6792); if (t91 != 61292U) { NG(); } else { ; } } void f92(void) { static volatile int8_t x6793 = INT8_MIN; static volatile uint32_t x6794 = 272561U; uint16_t x6795 = 6U; static uint16_t x6796 = 26136U; volatile uint32_t t92 = 6538442U; t92 = ((x6793+(x6794>>x6795))*x6796); if (t92 != 107941680U) { NG(); } else { ; } } void f93(void) { uint16_t x6837 = 1U; uint32_t x6838 = 1470749U; static int64_t x6839 = 0LL; static int8_t x6840 = 54; volatile uint32_t t93 = 401017993U; t93 = ((x6837+(x6838>>x6839))*x6840); if (t93 != 79420500U) { NG(); } else { ; } } void f94(void) { volatile int8_t x6846 = INT8_MAX; uint16_t x6847 = 6U; volatile int32_t x6848 = -1; t94 = ((x6845+(x6846>>x6847))*x6848); if (t94 != 0) { NG(); } else { ; } } void f95(void) { uint8_t x6857 = 0U; uint64_t x6858 = 1249282750248LLU; volatile int32_t x6860 = INT32_MAX; volatile uint64_t t95 = 23277LLU; t95 = ((x6857+(x6858>>x6859))*x6860); if (t95 != 6620782505647440438LLU) { NG(); } else { ; } } void f96(void) { uint16_t x6937 = 0U; static int8_t x6940 = 11; volatile int32_t t96 = -86973868; t96 = ((x6937+(x6938>>x6939))*x6940); if (t96 != 0) { NG(); } else { ; } } void f97(void) { int16_t x7029 = 307; int64_t x7030 = INT64_MAX; uint16_t x7031 = 2U; uint64_t x7032 = 3850502734LLU; static uint64_t t97 = 6404081LLU; t97 = ((x7029+(x7030>>x7031))*x7032); if (t97 != 13835059233536000316LLU) { NG(); } else { ; } } void f98(void) { uint32_t x7155 = 2U; int64_t x7156 = INT64_MIN; static volatile uint64_t t98 = 879062LLU; t98 = ((x7153+(x7154>>x7155))*x7156); if (t98 != 9223372036854775808LLU) { NG(); } else { ; } } void f99(void) { uint64_t x7285 = 628059042419288LLU; volatile int16_t x7286 = INT16_MAX; volatile int16_t x7287 = 1; static int16_t x7288 = INT16_MAX; volatile uint64_t t99 = 15165704LLU; t99 = ((x7285+(x7286>>x7287))*x7288); if (t99 != 2132866569780080041LLU) { NG(); } else { ; } } void f100(void) { uint64_t x7289 = UINT64_MAX; uint32_t x7290 = 3487U; volatile int64_t x7292 = INT64_MAX; uint64_t t100 = 368571LLU; t100 = ((x7289+(x7290>>x7291))*x7292); if (t100 != 18446744073709549874LLU) { NG(); } else { ; } } void f101(void) { int32_t x7305 = INT32_MIN; static int8_t x7307 = 2; int64_t x7308 = -1LL; t101 = ((x7305+(x7306>>x7307))*x7308); if (t101 != -2148988939LL) { NG(); } else { ; } } void f102(void) { uint8_t x7311 = 2U; static uint32_t x7312 = UINT32_MAX; t102 = ((x7309+(x7310>>x7311))*x7312); if (t102 != 4294967266U) { NG(); } else { ; } } void f103(void) { static int32_t x7337 = -1; uint64_t x7338 = UINT64_MAX; int8_t x7339 = 0; int64_t x7340 = INT64_MIN; t103 = ((x7337+(x7338>>x7339))*x7340); if (t103 != 0LLU) { NG(); } else { ; } } void f104(void) { static uint32_t x7537 = 80U; int32_t x7538 = 59; static uint32_t x7539 = 1U; int32_t x7540 = -3969; uint32_t t104 = 490U; t104 = ((x7537+(x7538>>x7539))*x7540); if (t104 != 4294534675U) { NG(); } else { ; } } void f105(void) { static int16_t x7629 = INT16_MIN; uint8_t x7631 = 27U; volatile uint32_t t105 = 6U; t105 = ((x7629+(x7630>>x7631))*x7632); if (t105 != 4190336U) { NG(); } else { ; } } void f106(void) { uint16_t x7785 = 1U; volatile uint8_t x7787 = 0U; uint64_t x7788 = UINT64_MAX; static volatile uint64_t t106 = 3199LLU; t106 = ((x7785+(x7786>>x7787))*x7788); if (t106 != 18446744073709439392LLU) { NG(); } else { ; } } void f107(void) { uint16_t x7790 = 106U; int8_t x7791 = 28; uint16_t x7792 = 7U; static uint32_t t107 = 641901U; t107 = ((x7789+(x7790>>x7791))*x7792); if (t107 != 131412505U) { NG(); } else { ; } } void f108(void) { int16_t x7793 = INT16_MIN; volatile int32_t x7794 = 31; int8_t x7795 = 5; volatile uint64_t x7796 = 525782005LLU; volatile uint64_t t108 = 52609269276926LLU; t108 = ((x7793+(x7794>>x7795))*x7796); if (t108 != 18446726844884811776LLU) { NG(); } else { ; } } void f109(void) { uint64_t x7853 = UINT64_MAX; static int32_t x7854 = INT32_MAX; uint32_t x7855 = 2U; uint32_t x7856 = 13U; t109 = ((x7853+(x7854>>x7855))*x7856); if (t109 != 6979321830LLU) { NG(); } else { ; } } void f110(void) { uint16_t x7937 = 72U; volatile uint32_t x7938 = 44554802U; uint64_t x7939 = 0LLU; int16_t x7940 = INT16_MIN; uint32_t t110 = 2338U; t110 = ((x7937+(x7938>>x7939))*x7940); if (t110 != 314769408U) { NG(); } else { ; } } void f111(void) { volatile int16_t x7985 = INT16_MIN; uint32_t x7987 = 2U; int64_t x7988 = -988711988802LL; uint64_t t111 = 14797699364LLU; t111 = ((x7985+(x7986>>x7987))*x7988); if (t111 != 1924411419436607924LLU) { NG(); } else { ; } } void f112(void) { volatile int16_t x8085 = INT16_MAX; uint32_t x8086 = 473U; uint8_t x8087 = 0U; volatile uint32_t x8088 = UINT32_MAX; volatile uint32_t t112 = 2330U; t112 = ((x8085+(x8086>>x8087))*x8088); if (t112 != 4294934056U) { NG(); } else { ; } } void f113(void) { int8_t x8129 = -1; static uint16_t x8130 = 791U; uint64_t x8131 = 4LLU; int16_t x8132 = INT16_MIN; int32_t t113 = -202616121; t113 = ((x8129+(x8130>>x8131))*x8132); if (t113 != -1572864) { NG(); } else { ; } } void f114(void) { uint64_t x8138 = 151LLU; int8_t x8139 = 9; volatile int32_t x8140 = 384; t114 = ((x8137+(x8138>>x8139))*x8140); if (t114 != 0LLU) { NG(); } else { ; } } void f115(void) { static volatile uint8_t x8242 = 1U; uint8_t x8243 = 0U; volatile int32_t t115 = 6860; t115 = ((x8241+(x8242>>x8243))*x8244); if (t115 != 0) { NG(); } else { ; } } void f116(void) { uint32_t x8438 = UINT32_MAX; int64_t x8440 = -1LL; volatile uint64_t t116 = 100343669965LLU; t116 = ((x8437+(x8438>>x8439))*x8440); if (t116 != 18445281314958536159LLU) { NG(); } else { ; } } void f117(void) { static int16_t x8449 = INT16_MAX; int8_t x8451 = 0; int32_t x8452 = -42218; t117 = ((x8449+(x8450>>x8451))*x8452); if (t117 != 18446744072326236628LLU) { NG(); } else { ; } } void f118(void) { int32_t x8558 = INT32_MAX; static uint16_t x8559 = 2U; int64_t t118 = 2263659LL; t118 = ((x8557+(x8558>>x8559))*x8560); if (t118 != -220103638630LL) { NG(); } else { ; } } void f119(void) { int16_t x8569 = INT16_MIN; uint64_t x8570 = UINT64_MAX; int8_t x8571 = 54; static int32_t x8572 = INT32_MIN; uint64_t t119 = 1530029LLU; t119 = ((x8569+(x8570>>x8571))*x8572); if (t119 != 68171868405760LLU) { NG(); } else { ; } } void f120(void) { volatile uint32_t x8618 = 777U; int32_t x8620 = INT32_MIN; static volatile uint32_t t120 = 142839978U; t120 = ((x8617+(x8618>>x8619))*x8620); if (t120 != 0U) { NG(); } else { ; } } void f121(void) { int32_t x8637 = -1; volatile uint64_t x8638 = UINT64_MAX; int64_t x8639 = 1LL; uint64_t t121 = 16LLU; t121 = ((x8637+(x8638>>x8639))*x8640); if (t121 != 9223372036854577222LLU) { NG(); } else { ; } } void f122(void) { uint32_t x8753 = 42680350U; uint32_t x8754 = UINT32_MAX; volatile uint64_t x8755 = 12LLU; volatile int16_t x8756 = -1405; uint32_t t122 = 1639770756U; t122 = ((x8753+(x8754>>x8755))*x8756); if (t122 != 2985369815U) { NG(); } else { ; } } void f123(void) { uint64_t x8821 = 242493LLU; volatile uint64_t t123 = 1503751992877LLU; t123 = ((x8821+(x8822>>x8823))*x8824); if (t123 != 15123090599379519108LLU) { NG(); } else { ; } } void f124(void) { uint8_t x8861 = 39U; uint64_t x8862 = UINT64_MAX; uint16_t x8864 = 15U; uint64_t t124 = 7785LLU; t124 = ((x8861+(x8862>>x8863))*x8864); if (t124 != 1055531162665530LLU) { NG(); } else { ; } } void f125(void) { volatile uint64_t x8985 = 1184717831594LLU; uint32_t x8986 = UINT32_MAX; uint8_t x8987 = 15U; uint16_t x8988 = 1U; volatile uint64_t t125 = 4841514288LLU; t125 = ((x8985+(x8986>>x8987))*x8988); if (t125 != 1184717962665LLU) { NG(); } else { ; } } void f126(void) { int64_t x9025 = -147LL; static int8_t x9026 = 58; int8_t x9027 = 24; uint16_t x9028 = 37U; t126 = ((x9025+(x9026>>x9027))*x9028); if (t126 != -5439LL) { NG(); } else { ; } } void f127(void) { static int8_t x9105 = INT8_MIN; uint32_t x9106 = UINT32_MAX; static uint32_t x9107 = 0U; int16_t x9108 = 1; uint32_t t127 = 15U; t127 = ((x9105+(x9106>>x9107))*x9108); if (t127 != 4294967167U) { NG(); } else { ; } } void f128(void) { int8_t x9277 = INT8_MIN; uint32_t x9278 = 2U; volatile uint8_t x9279 = 2U; uint8_t x9280 = UINT8_MAX; volatile uint32_t t128 = 476214720U; t128 = ((x9277+(x9278>>x9279))*x9280); if (t128 != 4294934656U) { NG(); } else { ; } } void f129(void) { int16_t x9365 = -1; uint64_t x9367 = 0LLU; volatile uint32_t t129 = 258670U; t129 = ((x9365+(x9366>>x9367))*x9368); if (t129 != 0U) { NG(); } else { ; } } void f130(void) { static uint64_t x9378 = 145919LLU; int8_t x9379 = 1; int8_t x9380 = INT8_MAX; uint64_t t130 = 9LLU; t130 = ((x9377+(x9378>>x9379))*x9380); if (t130 != 9285097LLU) { NG(); } else { ; } } void f131(void) { volatile int32_t x9449 = INT32_MIN; int32_t x9450 = 1; uint64_t x9451 = 6LLU; static int64_t x9452 = -1LL; static int64_t t131 = -261903188767728584LL; t131 = ((x9449+(x9450>>x9451))*x9452); if (t131 != 2147483648LL) { NG(); } else { ; } } void f132(void) { uint64_t x9473 = 787142886892230094LLU; uint8_t x9474 = 0U; uint16_t x9475 = 0U; uint16_t x9476 = UINT16_MAX; static uint64_t t132 = 48997781814597231LLU; t132 = ((x9473+(x9474>>x9475))*x9476); if (t132 != 8312662390392891954LLU) { NG(); } else { ; } } void f133(void) { uint32_t x9529 = 144527U; static volatile int64_t x9530 = 153611705771326LL; int16_t x9531 = 30; int16_t x9532 = -4508; t133 = ((x9529+(x9530>>x9531))*x9532); if (t133 != -1296451212LL) { NG(); } else { ; } } void f134(void) { int16_t x9561 = 16; uint32_t x9562 = 0U; uint8_t x9563 = 13U; uint64_t x9564 = 1994866391941LLU; static uint64_t t134 = 28648950410761739LLU; t134 = ((x9561+(x9562>>x9563))*x9564); if (t134 != 31917862271056LLU) { NG(); } else { ; } } void f135(void) { int16_t x9585 = INT16_MAX; uint16_t x9587 = 10U; uint64_t x9588 = UINT64_MAX; static volatile uint64_t t135 = 5851436916390843042LLU; t135 = ((x9585+(x9586>>x9587))*x9588); if (t135 != 18446744073709518849LLU) { NG(); } else { ; } } void f136(void) { volatile uint64_t x9633 = 5LLU; int16_t x9634 = INT16_MAX; int8_t x9635 = 4; volatile uint64_t t136 = 237343394709508635LLU; t136 = ((x9633+(x9634>>x9635))*x9636); if (t136 != 18444142459173911956LLU) { NG(); } else { ; } } void f137(void) { uint8_t x9690 = 25U; volatile int16_t x9691 = 2; static int64_t x9692 = -1LL; t137 = ((x9689+(x9690>>x9691))*x9692); if (t137 != 32762LL) { NG(); } else { ; } } void f138(void) { uint8_t x9733 = UINT8_MAX; int16_t x9734 = INT16_MAX; uint8_t x9735 = 30U; int16_t x9736 = INT16_MAX; volatile int32_t t138 = 160; t138 = ((x9733+(x9734>>x9735))*x9736); if (t138 != 8355585) { NG(); } else { ; } } void f139(void) { int16_t x9749 = -1; uint16_t x9750 = 4815U; uint8_t x9751 = 1U; uint32_t x9752 = 20227U; uint32_t t139 = 659171818U; t139 = ((x9749+(x9750>>x9751))*x9752); if (t139 != 48666162U) { NG(); } else { ; } } void f140(void) { static uint64_t x9890 = 139619399023LLU; uint8_t x9892 = 7U; t140 = ((x9889+(x9890>>x9891))*x9892); if (t140 != 244334177654LLU) { NG(); } else { ; } } void f141(void) { int16_t x10001 = INT16_MAX; static volatile uint64_t x10002 = UINT64_MAX; int16_t x10003 = 0; static int32_t x10004 = INT32_MIN; static uint64_t t141 = 103LLU; t141 = ((x10001+(x10002>>x10003))*x10004); if (t141 != 18446673709260341248LLU) { NG(); } else { ; } } void f142(void) { int64_t x10025 = 125430719758LL; volatile uint8_t x10026 = UINT8_MAX; static int8_t x10028 = 1; volatile int64_t t142 = -79389LL; t142 = ((x10025+(x10026>>x10027))*x10028); if (t142 != 125430719765LL) { NG(); } else { ; } } void f143(void) { volatile int64_t x10105 = 492LL; int16_t x10108 = INT16_MIN; t143 = ((x10105+(x10106>>x10107))*x10108); if (t143 != -59867136LL) { NG(); } else { ; } } void f144(void) { uint8_t x10205 = 1U; static uint8_t x10206 = UINT8_MAX; uint8_t x10207 = 3U; volatile uint8_t x10208 = UINT8_MAX; static int32_t t144 = -1; t144 = ((x10205+(x10206>>x10207))*x10208); if (t144 != 8160) { NG(); } else { ; } } void f145(void) { uint64_t x10229 = 1356823999818LLU; uint32_t x10230 = 859141105U; uint16_t x10231 = 11U; t145 = ((x10229+(x10230>>x10231))*x10232); if (t145 != 17619432767571256328LLU) { NG(); } else { ; } } void f146(void) { int32_t x10297 = -82571; uint8_t x10298 = 0U; uint8_t x10299 = 4U; static int8_t x10300 = INT8_MAX; t146 = ((x10297+(x10298>>x10299))*x10300); if (t146 != -10486517) { NG(); } else { ; } } void f147(void) { volatile uint8_t x10303 = 2U; int32_t x10304 = INT32_MAX; t147 = ((x10301+(x10302>>x10303))*x10304); if (t147 != 4294840150U) { NG(); } else { ; } } void f148(void) { uint8_t x10305 = UINT8_MAX; int16_t x10307 = 1; uint16_t x10308 = 5U; t148 = ((x10305+(x10306>>x10307))*x10308); if (t148 != 1340) { NG(); } else { ; } } void f149(void) { uint64_t x10482 = UINT64_MAX; static int8_t x10483 = 0; int64_t x10484 = INT64_MAX; uint64_t t149 = 3LLU; t149 = ((x10481+(x10482>>x10483))*x10484); if (t149 != 18446744071562067970LLU) { NG(); } else { ; } } void f150(void) { uint8_t x10486 = UINT8_MAX; volatile uint8_t x10488 = 11U; int32_t t150 = 1210999; t150 = ((x10485+(x10486>>x10487))*x10488); if (t150 != 363242) { NG(); } else { ; } } void f151(void) { int32_t x10489 = 3867454; static uint64_t x10490 = UINT64_MAX; uint64_t t151 = 1377226791898565891LLU; t151 = ((x10489+(x10490>>x10491))*x10492); if (t151 != 18446744073705684163LLU) { NG(); } else { ; } } void f152(void) { int64_t x10637 = -1LL; static uint8_t x10639 = 10U; static volatile uint64_t t152 = 8047491070580516594LLU; t152 = ((x10637+(x10638>>x10639))*x10640); if (t152 != 1LLU) { NG(); } else { ; } } void f153(void) { int32_t x10845 = -1; static volatile uint16_t x10848 = 2U; volatile uint32_t t153 = 14645667U; t153 = ((x10845+(x10846>>x10847))*x10848); if (t153 != 4294967292U) { NG(); } else { ; } } void f154(void) { int32_t x10913 = INT32_MIN; int8_t x10915 = 2; volatile int8_t x10916 = -1; uint32_t t154 = 0U; t154 = ((x10913+(x10914>>x10915))*x10916); if (t154 != 2147483645U) { NG(); } else { ; } } void f155(void) { volatile uint8_t x10919 = 1U; uint32_t x10920 = 6130U; uint32_t t155 = 39U; t155 = ((x10917+(x10918>>x10919))*x10920); if (t155 != 697118046U) { NG(); } else { ; } } void f156(void) { int8_t x11019 = 26; int8_t x11020 = -10; int64_t t156 = 461622644432555554LL; t156 = ((x11017+(x11018>>x11019))*x11020); if (t156 != -2362505147260LL) { NG(); } else { ; } } void f157(void) { uint32_t x11030 = 2111764482U; volatile uint32_t x11031 = 3U; int8_t x11032 = INT8_MIN; volatile uint32_t t157 = 635U; t157 = ((x11029+(x11030>>x11031))*x11032); if (t157 != 571339136U) { NG(); } else { ; } } void f158(void) { int32_t x11049 = 33796592; int8_t x11051 = 1; t158 = ((x11049+(x11050>>x11051))*x11052); if (t158 != 2991938852U) { NG(); } else { ; } } void f159(void) { static int32_t x11101 = 1622; uint32_t x11102 = UINT32_MAX; uint8_t x11103 = 2U; static int32_t x11104 = INT32_MAX; volatile uint32_t t159 = 2133U; t159 = ((x11101+(x11102>>x11103))*x11104); if (t159 != 1073740203U) { NG(); } else { ; } } void f160(void) { uint32_t x11234 = 938U; uint8_t x11236 = 126U; volatile uint64_t t160 = 13646LLU; t160 = ((x11233+(x11234>>x11235))*x11236); if (t160 != 2015641404LLU) { NG(); } else { ; } } void f161(void) { static int32_t x11269 = 1251; int16_t x11270 = 838; uint16_t x11271 = 1U; int16_t x11272 = INT16_MIN; int32_t t161 = 24; t161 = ((x11269+(x11270>>x11271))*x11272); if (t161 != -54722560) { NG(); } else { ; } } void f162(void) { volatile uint16_t x11462 = UINT16_MAX; int8_t x11463 = 0; uint64_t x11464 = 458743166LLU; t162 = ((x11461+(x11462>>x11463))*x11464); if (t162 != 30114195132070LLU) { NG(); } else { ; } } void f163(void) { volatile uint16_t x11529 = 17U; uint8_t x11530 = 0U; static int8_t x11532 = INT8_MIN; static volatile int32_t t163 = 1578; t163 = ((x11529+(x11530>>x11531))*x11532); if (t163 != -2176) { NG(); } else { ; } } void f164(void) { volatile int64_t x11546 = INT64_MAX; uint8_t x11547 = 16U; uint8_t x11548 = 31U; t164 = ((x11545+(x11546>>x11547))*x11548); if (t164 != 4362795567022049LL) { NG(); } else { ; } } void f165(void) { static uint8_t x11555 = 15U; int64_t x11556 = INT64_MAX; volatile uint64_t t165 = 17636855881685824LLU; t165 = ((x11553+(x11554>>x11555))*x11556); if (t165 != 18446738501760874010LLU) { NG(); } else { ; } } void f166(void) { volatile int64_t x11670 = 1318833031294LL; static volatile uint8_t x11671 = 13U; int16_t x11672 = -81; t166 = ((x11669+(x11670>>x11671))*x11672); if (t166 != 18446744060301654178LLU) { NG(); } else { ; } } void f167(void) { volatile int32_t x11777 = -330; uint64_t x11778 = 343022127656LLU; int16_t x11779 = 1; int32_t x11780 = INT32_MAX; uint64_t t167 = 3840986LLU; t167 = ((x11777+(x11778>>x11779))*x11780); if (t167 != 17829066741052136502LLU) { NG(); } else { ; } } void f168(void) { volatile int32_t x11869 = 0; uint8_t x11870 = UINT8_MAX; int16_t x11871 = 26; t168 = ((x11869+(x11870>>x11871))*x11872); if (t168 != 0) { NG(); } else { ; } } void f169(void) { uint32_t x11925 = UINT32_MAX; uint64_t x11926 = 15372812395LLU; int8_t x11928 = -6; static uint64_t t169 = 2484729LLU; t169 = ((x11925+(x11926>>x11927))*x11928); if (t169 != 18446744001821310664LLU) { NG(); } else { ; } } void f170(void) { static volatile int64_t x12013 = INT64_MIN; uint8_t x12015 = 1U; int8_t x12016 = -1; int64_t t170 = -7921348LL; t170 = ((x12013+(x12014>>x12015))*x12016); if (t170 != 9223372036854775745LL) { NG(); } else { ; } } void f171(void) { volatile int16_t x12173 = INT16_MIN; static volatile uint8_t x12174 = 1U; int8_t x12175 = 1; volatile int8_t x12176 = -1; volatile int32_t t171 = -810296303; t171 = ((x12173+(x12174>>x12175))*x12176); if (t171 != 32768) { NG(); } else { ; } } void f172(void) { int16_t x12217 = INT16_MIN; uint32_t x12218 = 22238U; uint32_t x12219 = 0U; static int64_t x12220 = -1LL; int64_t t172 = 403468505523000628LL; t172 = ((x12217+(x12218>>x12219))*x12220); if (t172 != -4294956766LL) { NG(); } else { ; } } void f173(void) { int8_t x12277 = INT8_MIN; static uint32_t x12278 = 83U; uint8_t x12279 = 0U; uint16_t x12280 = 1918U; static uint32_t t173 = 107448257U; t173 = ((x12277+(x12278>>x12279))*x12280); if (t173 != 4294880986U) { NG(); } else { ; } } void f174(void) { uint64_t x12517 = 1194075474LLU; uint64_t x12518 = 12486191222058LLU; static int8_t x12519 = 1; int64_t x12520 = INT64_MIN; uint64_t t174 = 4534705910063796LLU; t174 = ((x12517+(x12518>>x12519))*x12520); if (t174 != 9223372036854775808LLU) { NG(); } else { ; } } void f175(void) { int16_t x12529 = -52; static volatile uint8_t x12531 = 0U; int8_t x12532 = -3; int32_t t175 = -329796; t175 = ((x12529+(x12530>>x12531))*x12532); if (t175 != 147) { NG(); } else { ; } } void f176(void) { int32_t x12625 = -1; uint16_t x12627 = 21U; volatile int8_t x12628 = -1; int32_t t176 = -494504567; t176 = ((x12625+(x12626>>x12627))*x12628); if (t176 != 1) { NG(); } else { ; } } void f177(void) { int64_t x12657 = -1LL; static int16_t x12658 = INT16_MAX; uint8_t x12659 = 3U; t177 = ((x12657+(x12658>>x12659))*x12660); if (t177 != -8791798054912LL) { NG(); } else { ; } } void f178(void) { uint8_t x12705 = 3U; int8_t x12706 = 0; static uint16_t x12707 = 9U; int64_t x12708 = -1LL; volatile int64_t t178 = 450535LL; t178 = ((x12705+(x12706>>x12707))*x12708); if (t178 != -3LL) { NG(); } else { ; } } void f179(void) { volatile int32_t x12761 = -1; int8_t x12762 = 0; volatile uint8_t x12763 = 0U; static int16_t x12764 = -1; int32_t t179 = -65; t179 = ((x12761+(x12762>>x12763))*x12764); if (t179 != 1) { NG(); } else { ; } } void f180(void) { int8_t x12821 = -1; int8_t x12822 = 0; int16_t x12823 = 0; static volatile uint32_t x12824 = UINT32_MAX; volatile uint32_t t180 = 7835801U; t180 = ((x12821+(x12822>>x12823))*x12824); if (t180 != 1U) { NG(); } else { ; } } void f181(void) { static uint16_t x12861 = UINT16_MAX; int16_t x12862 = 13989; uint64_t x12863 = 7LLU; uint8_t x12864 = 28U; volatile int32_t t181 = -110182012; t181 = ((x12861+(x12862>>x12863))*x12864); if (t181 != 1838032) { NG(); } else { ; } } void f182(void) { static int16_t x12981 = 3; int64_t x12983 = 0LL; uint8_t x12984 = 86U; int32_t t182 = 483; t182 = ((x12981+(x12982>>x12983))*x12984); if (t182 != 11180) { NG(); } else { ; } } void f183(void) { int16_t x13194 = INT16_MAX; uint8_t x13195 = 10U; volatile uint8_t x13196 = 34U; uint64_t t183 = 6412835116LLU; t183 = ((x13193+(x13194>>x13195))*x13196); if (t183 != 23520969582LLU) { NG(); } else { ; } } void f184(void) { int8_t x13233 = -3; static uint64_t x13234 = UINT64_MAX; uint32_t x13236 = 14162U; uint64_t t184 = 30960291704386247LLU; t184 = ((x13233+(x13234>>x13235))*x13236); if (t184 != 5188146770730754744LLU) { NG(); } else { ; } } void f185(void) { static uint16_t x13246 = 2069U; static uint8_t x13247 = 1U; uint8_t x13248 = 15U; static volatile int32_t t185 = 1588; t185 = ((x13245+(x13246>>x13247))*x13248); if (t185 != 8753625) { NG(); } else { ; } } void f186(void) { uint32_t x13281 = UINT32_MAX; uint8_t x13282 = 7U; volatile int8_t x13284 = INT8_MAX; static volatile uint32_t t186 = 172049U; t186 = ((x13281+(x13282>>x13283))*x13284); if (t186 != 762U) { NG(); } else { ; } } void f187(void) { static int64_t x13313 = -62907194691135LL; int64_t x13314 = 896LL; int8_t x13315 = 20; static uint8_t x13316 = 34U; volatile int64_t t187 = 2680LL; t187 = ((x13313+(x13314>>x13315))*x13316); if (t187 != -2138844619498590LL) { NG(); } else { ; } } void f188(void) { int16_t x13321 = -1; static uint32_t x13322 = 16U; int8_t x13323 = 0; int32_t x13324 = 413020786; uint32_t t188 = 11832031U; t188 = ((x13321+(x13322>>x13323))*x13324); if (t188 != 1900344494U) { NG(); } else { ; } } void f189(void) { uint64_t x13405 = 19LLU; volatile uint32_t x13406 = 19U; uint8_t x13407 = 30U; uint16_t x13408 = UINT16_MAX; static uint64_t t189 = 264369605364541LLU; t189 = ((x13405+(x13406>>x13407))*x13408); if (t189 != 1245165LLU) { NG(); } else { ; } } void f190(void) { int8_t x13749 = -1; uint64_t x13750 = 36285817LLU; uint8_t x13751 = 5U; int32_t x13752 = 28175; volatile uint64_t t190 = 988123072992397064LLU; t190 = ((x13749+(x13750>>x13751))*x13752); if (t190 != 31948477750LLU) { NG(); } else { ; } } void f191(void) { static uint64_t x13770 = 2915LLU; static int32_t x13771 = 27; volatile uint32_t x13772 = 6436217U; volatile uint64_t t191 = 100567LLU; t191 = ((x13769+(x13770>>x13771))*x13772); if (t191 != 18446744073606572144LLU) { NG(); } else { ; } } void f192(void) { static uint64_t x13829 = 1479299180235967LLU; uint16_t x13830 = 31U; static int8_t x13832 = INT8_MAX; uint64_t t192 = 67753889456760262LLU; t192 = ((x13829+(x13830>>x13831))*x13832); if (t192 != 187870995889967809LLU) { NG(); } else { ; } } void f193(void) { uint8_t x13837 = 0U; volatile uint16_t x13838 = 22U; uint8_t x13839 = 3U; int16_t x13840 = INT16_MIN; volatile int32_t t193 = -4079802; t193 = ((x13837+(x13838>>x13839))*x13840); if (t193 != -65536) { NG(); } else { ; } } void f194(void) { int16_t x13865 = INT16_MAX; uint64_t x13866 = 7LLU; volatile uint64_t x13868 = UINT64_MAX; uint64_t t194 = 38704503092LLU; t194 = ((x13865+(x13866>>x13867))*x13868); if (t194 != 18446744073709518849LLU) { NG(); } else { ; } } void f195(void) { int32_t x13953 = -2686; static volatile uint32_t x13954 = 92635383U; uint8_t x13955 = 1U; int64_t x13956 = -1LL; volatile int64_t t195 = -13396315LL; t195 = ((x13953+(x13954>>x13955))*x13956); if (t195 != -46315005LL) { NG(); } else { ; } } void f196(void) { static int16_t x14085 = INT16_MIN; volatile int8_t x14087 = 1; int16_t x14088 = -1; volatile int32_t t196 = 3758292; t196 = ((x14085+(x14086>>x14087))*x14088); if (t196 != 1) { NG(); } else { ; } } void f197(void) { int16_t x14129 = INT16_MIN; int16_t x14130 = 43; static int8_t x14131 = 1; int32_t x14132 = -133; int32_t t197 = -2896521; t197 = ((x14129+(x14130>>x14131))*x14132); if (t197 != 4355351) { NG(); } else { ; } } void f198(void) { int16_t x14157 = INT16_MAX; int64_t x14158 = 5729843LL; uint16_t x14159 = 24U; uint16_t x14160 = 3U; volatile int64_t t198 = 35LL; t198 = ((x14157+(x14158>>x14159))*x14160); if (t198 != 98301LL) { NG(); } else { ; } } void f199(void) { uint16_t x14185 = 6U; volatile uint8_t x14187 = 10U; int8_t x14188 = 1; t199 = ((x14185+(x14186>>x14187))*x14188); if (t199 != 6) { NG(); } else { ; } } int main(void) { 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(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
307640.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. */ /* bttester.c - Bluetooth Tester */ /* * Copyright (c) 2015-2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "syscfg/syscfg.h" #include "console/console.h" #include "bttester_pipe.h" #include "bttester.h" #define CMD_QUEUED 2 static struct os_eventq avail_queue; static struct os_eventq *cmds_queue; static struct os_event bttester_ev[CMD_QUEUED]; struct btp_buf { struct os_event *ev; union { u8_t data[BTP_MTU]; struct btp_hdr hdr; }; }; static struct btp_buf cmd_buf[CMD_QUEUED]; static void supported_commands(u8_t *data, u16_t len) { u8_t buf[1]; struct core_read_supported_commands_rp *rp = (void *) buf; memset(buf, 0, sizeof(buf)); tester_set_bit(buf, CORE_READ_SUPPORTED_COMMANDS); tester_set_bit(buf, CORE_READ_SUPPORTED_SERVICES); tester_set_bit(buf, CORE_REGISTER_SERVICE); tester_set_bit(buf, CORE_UNREGISTER_SERVICE); tester_send(BTP_SERVICE_ID_CORE, CORE_READ_SUPPORTED_COMMANDS, BTP_INDEX_NONE, (u8_t *) rp, sizeof(buf)); } static void supported_services(u8_t *data, u16_t len) { u8_t buf[1]; struct core_read_supported_services_rp *rp = (void *) buf; memset(buf, 0, sizeof(buf)); tester_set_bit(buf, BTP_SERVICE_ID_CORE); tester_set_bit(buf, BTP_SERVICE_ID_GAP); tester_set_bit(buf, BTP_SERVICE_ID_GATT); #if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) tester_set_bit(buf, BTP_SERVICE_ID_L2CAP); #endif /* MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) */ #if MYNEWT_VAL(BLE_MESH) tester_set_bit(buf, BTP_SERVICE_ID_MESH); #endif /* MYNEWT_VAL(BLE_MESH) */ tester_send(BTP_SERVICE_ID_CORE, CORE_READ_SUPPORTED_SERVICES, BTP_INDEX_NONE, (u8_t *) rp, sizeof(buf)); } static void register_service(u8_t *data, u16_t len) { struct core_register_service_cmd *cmd = (void *) data; u8_t status; switch (cmd->id) { case BTP_SERVICE_ID_GAP: status = tester_init_gap(); /* Rsp with success status will be handled by bt enable cb */ if (status == BTP_STATUS_FAILED) { goto rsp; } return; case BTP_SERVICE_ID_GATT: status = tester_init_gatt(); break; #if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) case BTP_SERVICE_ID_L2CAP: status = tester_init_l2cap(); break; #endif /* MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) */ #if MYNEWT_VAL(BLE_MESH) case BTP_SERVICE_ID_MESH: status = tester_init_mesh(); break; #endif /* MYNEWT_VAL(BLE_MESH) */ default: status = BTP_STATUS_FAILED; break; } rsp: tester_rsp(BTP_SERVICE_ID_CORE, CORE_REGISTER_SERVICE, BTP_INDEX_NONE, status); } static void unregister_service(u8_t *data, u16_t len) { struct core_unregister_service_cmd *cmd = (void *) data; u8_t status; switch (cmd->id) { case BTP_SERVICE_ID_GAP: status = tester_unregister_gap(); break; case BTP_SERVICE_ID_GATT: status = tester_unregister_gatt(); break; #if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) case BTP_SERVICE_ID_L2CAP: status = tester_unregister_l2cap(); break; #endif /* MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) */ #if MYNEWT_VAL(BLE_MESH) case BTP_SERVICE_ID_MESH: status = tester_unregister_mesh(); break; #endif /* MYNEWT_VAL(BLE_MESH) */ default: status = BTP_STATUS_FAILED; break; } tester_rsp(BTP_SERVICE_ID_CORE, CORE_UNREGISTER_SERVICE, BTP_INDEX_NONE, status); } static void handle_core(u8_t opcode, u8_t index, u8_t *data, u16_t len) { if (index != BTP_INDEX_NONE) { tester_rsp(BTP_SERVICE_ID_CORE, opcode, index, BTP_STATUS_FAILED); return; } switch (opcode) { case CORE_READ_SUPPORTED_COMMANDS: supported_commands(data, len); return; case CORE_READ_SUPPORTED_SERVICES: supported_services(data, len); return; case CORE_REGISTER_SERVICE: register_service(data, len); return; case CORE_UNREGISTER_SERVICE: unregister_service(data, len); return; default: tester_rsp(BTP_SERVICE_ID_CORE, opcode, BTP_INDEX_NONE, BTP_STATUS_UNKNOWN_CMD); return; } } static void cmd_handler(struct os_event *ev) { u16_t len; struct btp_buf *cmd; if (!ev || !ev->ev_arg) { return; } cmd = ev->ev_arg; len = sys_le16_to_cpu(cmd->hdr.len); if (MYNEWT_VAL(BTTESTER_BTP_LOG)) { console_printf("[DBG] received %d bytes: %s\n", sizeof(cmd->hdr) + len, bt_hex(cmd->data, sizeof(cmd->hdr) + len)); } /* TODO * verify if service is registered before calling handler */ switch (cmd->hdr.service) { case BTP_SERVICE_ID_CORE: handle_core(cmd->hdr.opcode, cmd->hdr.index, cmd->hdr.data, len); break; case BTP_SERVICE_ID_GAP: tester_handle_gap(cmd->hdr.opcode, cmd->hdr.index, cmd->hdr.data, len); break; case BTP_SERVICE_ID_GATT: tester_handle_gatt(cmd->hdr.opcode, cmd->hdr.index, cmd->hdr.data, len); break; #if MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) case BTP_SERVICE_ID_L2CAP: tester_handle_l2cap(cmd->hdr.opcode, cmd->hdr.index, cmd->hdr.data, len); break; #endif /* MYNEWT_VAL(BLE_L2CAP_COC_MAX_NUM) */ #if MYNEWT_VAL(BLE_MESH) case BTP_SERVICE_ID_MESH: tester_handle_mesh(cmd->hdr.opcode, cmd->hdr.index, cmd->hdr.data, len); break; #endif /* MYNEWT_VAL(BLE_MESH) */ default: tester_rsp(cmd->hdr.service, cmd->hdr.opcode, cmd->hdr.index, BTP_STATUS_FAILED); break; } os_eventq_put(&avail_queue, ev); } static u8_t *recv_cb(u8_t *buf, size_t *off) { struct btp_hdr *cmd = (void *) buf; struct os_event *new_ev; struct btp_buf *new_buf, *old_buf; u16_t len; if (*off < sizeof(*cmd)) { return buf; } len = sys_le16_to_cpu(cmd->len); if (len > BTP_MTU - sizeof(*cmd)) { SYS_LOG_ERR("BT tester: invalid packet length"); *off = 0; return buf; } if (*off < sizeof(*cmd) + len) { return buf; } new_ev = os_eventq_get_no_wait(&avail_queue); if (!new_ev) { SYS_LOG_ERR("BT tester: RX overflow"); *off = 0; return buf; } old_buf = CONTAINER_OF(buf, struct btp_buf, data); os_eventq_put(cmds_queue, old_buf->ev); new_buf = new_ev->ev_arg; *off = 0; return new_buf->data; } static void avail_queue_init(void) { int i; os_eventq_init(&avail_queue); for (i = 0; i < CMD_QUEUED; i++) { cmd_buf[i].ev = &bttester_ev[i]; bttester_ev[i].ev_cb = cmd_handler; bttester_ev[i].ev_arg = &cmd_buf[i]; os_eventq_put(&avail_queue, &bttester_ev[i]); } } void bttester_evq_set(struct os_eventq *evq) { cmds_queue = evq; } void tester_init(void) { struct os_event *ev; struct btp_buf *buf; avail_queue_init(); bttester_evq_set(os_eventq_dflt_get()); ev = os_eventq_get(&avail_queue); buf = ev->ev_arg; if (bttester_pipe_init()) { SYS_LOG_ERR("Failed to initialize pipe"); return; } bttester_pipe_register(buf->data, BTP_MTU, recv_cb); tester_send(BTP_SERVICE_ID_CORE, CORE_EV_IUT_READY, BTP_INDEX_NONE, NULL, 0); } void tester_send(u8_t service, u8_t opcode, u8_t index, u8_t *data, size_t len) { struct btp_hdr msg; msg.service = service; msg.opcode = opcode; msg.index = index; msg.len = len; bttester_pipe_send((u8_t *)&msg, sizeof(msg)); if (data && len) { bttester_pipe_send(data, len); } if (MYNEWT_VAL(BTTESTER_BTP_LOG)) { console_printf("[DBG] send %d bytes hdr: %s\n", sizeof(msg), bt_hex((char *) &msg, sizeof(msg))); if (data && len) { console_printf("[DBG] send %d bytes data: %s\n", len, bt_hex((char *) data, len)); } } } void tester_rsp(u8_t service, u8_t opcode, u8_t index, u8_t status) { struct btp_status s; if (status == BTP_STATUS_SUCCESS) { tester_send(service, opcode, index, NULL, 0); return; } s.code = status; tester_send(service, BTP_STATUS, index, (u8_t *) &s, sizeof(s)); }
320106.c
/* * Copyright 2019 University of Washington, Max Planck Institute for * Software Systems, and The University of Texas at Austin * * 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 <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <errno.h> #define __USE_GNU #include <dlfcn.h> #include <pthread.h> #include <sys/select.h> #include <sys/syscall.h> #include <unistd.h> #include <fcntl.h> #include <utils.h> #include <tas_sockets.h> static inline void ensure_init(void); /* Function pointers to the libc functions */ static int (*libc_socket)(int domain, int type, int protocol) = NULL; static int (*libc_close)(int sockfd) = NULL; static int (*libc_shutdown)(int sockfd, int how) = NULL; static int (*libc_bind)(int sockfd, const struct sockaddr *addr, socklen_t addrlen) = NULL; static int (*libc_connect)(int sockfd, const struct sockaddr *addr, socklen_t addrlen) = NULL; static int (*libc_listen)(int sockfd, int backlog) = NULL; static int (*libc_accept4)(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) = NULL; static int (*libc_accept)(int sockfd, struct sockaddr *addr, socklen_t *addrlen) = NULL; static int (*libc_fcntl)(int sockfd, int cmd, ...) = NULL; static int (*libc_fcntl64)(int sockfd, int cmd, ...) = NULL; static int (*libc_getsockopt)(int sockfd, int level, int optname, void *optval, socklen_t *optlen) = NULL; static int (*libc_setsockopt)(int sockfd, int level, int optname, const void *optval, socklen_t optlen) = NULL; static int (*libc_getsockname)(int sockfd, struct sockaddr *addr, socklen_t *addrlen) = NULL; static int (*libc_getpeername)(int sockfd, struct sockaddr *addr, socklen_t *addrlen) = NULL; static ssize_t (*libc_read)(int fd, void *buf, size_t count) = NULL; static ssize_t (*libc_recv)(int sockfd, void *buf, size_t len, int flags) = NULL; static ssize_t (*libc_recvfrom)(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) = NULL; static ssize_t (*libc_recvmsg)(int sockfd, struct msghdr *msg, int flags) = NULL; static ssize_t (*libc_readv)(int sockfd, const struct iovec *iov, int iovcnt) = NULL; static ssize_t (*libc_pread)(int sockfd, void *buf, size_t count, off_t offset) = NULL; static ssize_t (*libc_write)(int fd, const void *buf, size_t count) = NULL; static ssize_t (*libc_send)(int sockfd, const void *buf, size_t len, int flags) = NULL; static ssize_t (*libc_sendto)(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen) = NULL; static ssize_t (*libc_sendmsg)(int sockfd, const struct msghdr *msg, int flags) = NULL; static ssize_t (*libc_writev)(int sockfd, const struct iovec *iov, int iovcnt) = NULL; static ssize_t (*libc_pwrite)(int sockfd, const void *buf, size_t count, off_t offset) = NULL; static ssize_t (*libc_sendfile)(int sockfd, int in_fd, off_t *offset, size_t len) = NULL; static long (*libc_syscall)(long num, ...) = NULL; int socket(int domain, int type, int protocol) { ensure_init(); /* if not a TCP socket, pass call to libc */ if (domain != AF_INET || (type & ~(SOCK_NONBLOCK | SOCK_CLOEXEC)) != SOCK_STREAM) { return libc_socket(domain, type, protocol); } return tas_socket(domain, type, protocol); } int close(int sockfd) { int ret; ensure_init(); if ((ret = tas_close(sockfd)) == -1 && errno == EBADF) { return libc_close(sockfd); } return ret; } int shutdown(int sockfd, int how) { int ret; ensure_init(); if ((ret = tas_shutdown(sockfd, how)) == -1 && errno == EBADF) { return libc_shutdown(sockfd, how); } return ret; } int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { int ret; ensure_init(); if ((ret = tas_bind(sockfd, addr, addrlen)) == -1 && errno == EBADF) { return libc_bind(sockfd, addr, addrlen); } return ret; } int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen) { int ret; ensure_init(); if ((ret = tas_connect(sockfd, addr, addrlen)) == -1 && errno == EBADF) { return libc_connect(sockfd, addr, addrlen); } return ret; } int listen(int sockfd, int backlog) { int ret; ensure_init(); if ((ret = tas_listen(sockfd, backlog)) == -1 && errno == EBADF) { return libc_listen(sockfd, backlog); } return ret; } int accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) { int ret; ensure_init(); if ((ret = tas_accept4(sockfd, addr, addrlen, flags)) == -1 && errno == EBADF) { return libc_accept4(sockfd, addr, addrlen, flags); } return ret; } int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { int ret; ensure_init(); if ((ret = tas_accept(sockfd, addr, addrlen)) == -1 && errno == EBADF) { return libc_accept(sockfd, addr, addrlen); } return ret; } static int vfcntl(int sockfd, int cmd, va_list val, int is_64) { int ret, arg_i; void *arg_p; /* this is pretty ugly, but unfortunately there is no other way to interpose * on variadic functions and pass along all arguments. */ switch (cmd) { /* these take no argument */ case F_GETFD: case F_GETFL: case F_GETOWN: case F_GETSIG: case F_GETLEASE: case F_GETPIPE_SZ: #ifdef F_GET_SEALS case F_GET_SEALS: #endif if ((ret = tas_fcntl(sockfd, cmd)) == -1 && errno == EBADF) { if (is_64) ret = libc_fcntl64(sockfd, cmd); else ret = libc_fcntl(sockfd, cmd); } break; /* these take int as an argument */ case F_DUPFD: case F_DUPFD_CLOEXEC: case F_SETFD: case F_SETFL: case F_SETOWN: case F_SETSIG: case F_SETLEASE: case F_NOTIFY: case F_SETPIPE_SZ: #ifdef F_ADD_SEALS case F_ADD_SEALS: #endif arg_i = va_arg(val, int); if ((ret = tas_fcntl(sockfd, cmd, arg_i)) == -1 && errno == EBADF) { if (is_64) ret = libc_fcntl64(sockfd, cmd, arg_i); else ret = libc_fcntl(sockfd, cmd, arg_i); } break; /* these take a pointer as an argument */ case F_SETLK: case F_SETLKW: case F_GETLK: case F_OFD_SETLK: case F_OFD_SETLKW: case F_OFD_GETLK: case F_GETOWN_EX: case F_SETOWN_EX: #ifdef F_GET_RW_HINT case F_GET_RW_HINT: case F_SET_RW_HINT: #endif #ifdef F_GET_FILE_RW_HINT case F_GET_FILE_RW_HINT: case F_SET_FILE_RW_HINT: #endif arg_p = va_arg(val, void *); if ((ret = tas_fcntl(sockfd, cmd, arg_p)) == -1 && errno == EBADF) { if (is_64) ret = libc_fcntl64(sockfd, cmd, arg_p); else ret = libc_fcntl(sockfd, cmd, arg_p); } break; /* unsupported */ default: fprintf(stderr, "tas fcntl wrapper: unsupported cmd (%u)\n", cmd); errno = EINVAL; ret = -1; break; } return ret; } int fcntl(int sockfd, int cmd, ...) { int ret; va_list val; ensure_init(); va_start(val, cmd); ret = vfcntl(sockfd, cmd, val, 0); va_end(val); return ret; } int fcntl64(int sockfd, int cmd, ...) { int ret; va_list val; ensure_init(); va_start(val, cmd); ret = vfcntl(sockfd, cmd, val, 1); va_end(val); return ret; } int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen) { int ret; ensure_init(); if ((ret = tas_getsockopt(sockfd, level, optname, optval, optlen)) == -1 && errno == EBADF) { return libc_getsockopt(sockfd, level, optname, optval, optlen); } return ret; } int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen) { int ret; ensure_init(); if ((ret = tas_setsockopt(sockfd, level, optname, optval, optlen)) == -1 && errno == EBADF) { return libc_setsockopt(sockfd, level, optname, optval, optlen); } return ret; } int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { int ret; ensure_init(); if ((ret = tas_getsockname(sockfd, addr, addrlen)) == -1 && errno == EBADF) { return libc_getsockname(sockfd, addr, addrlen); } return ret; } int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen) { int ret; ensure_init(); if ((ret = tas_getpeername(sockfd, addr, addrlen)) == -1 && errno == EBADF) { return libc_getpeername(sockfd, addr, addrlen); } return ret; } ssize_t read(int sockfd, void *buf, size_t count) { ssize_t ret; ensure_init(); if ((ret = tas_read(sockfd, buf, count)) == -1 && errno == EBADF) { return libc_read(sockfd, buf, count); } return ret; } ssize_t recv(int sockfd, void *buf, size_t len, int flags) { ssize_t ret; ensure_init(); if ((ret = tas_recv(sockfd, buf, len, flags)) == -1 && errno == EBADF) { return libc_recv(sockfd, buf, len, flags); } return ret; } ssize_t recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen) { ssize_t ret; ensure_init(); if ((ret = tas_recvfrom(sockfd, buf, len, flags, src_addr, addrlen)) == -1 && errno == EBADF) { return libc_recvfrom(sockfd, buf, len, flags, src_addr, addrlen); } return ret; } ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags) { ssize_t ret; ensure_init(); if ((ret = tas_recvmsg(sockfd, msg, flags)) == -1 && errno == EBADF) { return libc_recvmsg(sockfd, msg, flags); } return ret; } ssize_t readv(int sockfd, const struct iovec *iov, int iovcnt) { ssize_t ret; ensure_init(); if ((ret = tas_readv(sockfd, iov, iovcnt)) == -1 && errno == EBADF) { return libc_readv(sockfd, iov, iovcnt); } return ret; } ssize_t pread(int sockfd, void *buf, size_t count, off_t offset) { ssize_t ret; ensure_init(); if ((ret = tas_pread(sockfd, buf, count, offset)) == -1 && errno == EBADF) { return libc_pread(sockfd, buf, count, offset); } return ret; } ssize_t write(int sockfd, const void *buf, size_t count) { ssize_t ret; ensure_init(); if ((ret = tas_write(sockfd, buf, count)) == -1 && errno == EBADF) { return libc_write(sockfd, buf, count); } return ret; } ssize_t send(int sockfd, const void *buf, size_t len, int flags) { ssize_t ret; ensure_init(); if ((ret = tas_send(sockfd, buf, len, flags)) == -1 && errno == EBADF) { return libc_send(sockfd, buf, len, flags); } return ret; } ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen) { ssize_t ret; ensure_init(); if ((ret = tas_sendto(sockfd, buf, len, flags, dest_addr, addrlen)) == -1 && errno == EBADF) { return libc_sendto(sockfd, buf, len, flags, dest_addr, addrlen); } return ret; } ssize_t sendmsg(int sockfd, const struct msghdr *msg, int flags) { ssize_t ret; ensure_init(); if ((ret = tas_sendmsg(sockfd, msg, flags)) == -1 && errno == EBADF) { return libc_sendmsg(sockfd, msg, flags); } return ret; } ssize_t writev(int sockfd, const struct iovec *iov, int iovcnt) { ssize_t ret; ensure_init(); if ((ret = tas_writev(sockfd, iov, iovcnt)) == -1 && errno == EBADF) { return libc_writev(sockfd, iov, iovcnt); } return ret; } ssize_t pwrite(int sockfd, const void *buf, size_t count, off_t offset) { ssize_t ret; ensure_init(); if ((ret = tas_pwrite(sockfd, buf, count, offset)) == -1 && errno == EBADF) { return libc_pwrite(sockfd, buf, count, offset); } return ret; } ssize_t sendfile(int sockfd, int in_fd, off_t *offset, size_t len) { ssize_t ret; ensure_init(); if ((ret = tas_sendfile(sockfd, in_fd, offset, len)) == -1 && errno == EBADF) { return libc_sendfile(sockfd, in_fd, offset, len); } return ret; } int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { ensure_init(); return tas_select(nfds, readfds, writefds, exceptfds, timeout); } int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *timeout, const sigset_t *sigmask) { ensure_init(); return tas_pselect(nfds, readfds, writefds, exceptfds, timeout, sigmask); } int epoll_create(int size) { ensure_init(); return tas_epoll_create(size); } int epoll_create1(int flags) { ensure_init(); return tas_epoll_create1(flags); } int epoll_ctl(int epfd, int op, int fd, struct epoll_event *event) { ensure_init(); return tas_epoll_ctl(epfd, op, fd, event); } int epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout) { ensure_init(); return tas_epoll_wait(epfd, events, maxevents, timeout); } int epoll_pwait(int epfd, struct epoll_event *events, int maxevents, int timeout, const sigset_t *sigmask) { ensure_init(); return tas_epoll_pwait(epfd, events, maxevents, timeout, sigmask); } int poll(struct pollfd *fds, nfds_t nfds, int timeout) { ensure_init(); return tas_poll(fds, nfds, timeout); } int ppoll(struct pollfd *fds, nfds_t nfds, const struct timespec *tmo_p, const sigset_t *sigmask) { ensure_init(); return tas_ppoll(fds, nfds, tmo_p, sigmask); } int dup(int oldfd) { return tas_dup(oldfd); } int dup2(int oldfd, int newfd) { return tas_dup2(oldfd, newfd); } int dup3(int oldfd, int newfd, int flags) { return tas_dup3(oldfd, newfd, flags); } /* I really apologize to anyone reading this particular piece of code. * So apparently there is code out there that calls some socket calls directly * with syscall (nodejs being one example). In this case these get past our * interposition layer and break things. */ long syscall(long number, ...) { long ret; va_list val; long arg1, arg2, arg3, arg4, arg5, arg6; ensure_init(); /* pray to god that this is safe on X86-64... */ va_start(val, number); arg1 = va_arg(val, long); arg2 = va_arg(val, long); arg3 = va_arg(val, long); arg4 = va_arg(val, long); arg5 = va_arg(val, long); arg6 = va_arg(val, long); va_end(val); switch (number) { case SYS_socket: return socket((int) arg1, (int) arg2, (int) arg3); case SYS_close: return close((int) arg1); case SYS_shutdown: return shutdown((int) arg1, (int) arg2); case SYS_bind: return bind((int) arg1, (const struct sockaddr *) (uintptr_t) arg2, (socklen_t) arg3); case SYS_connect: return connect((int) arg1, (const struct sockaddr *) (uintptr_t) arg2, (socklen_t) arg3); case SYS_listen: return listen((int) arg1, (int) arg2); case SYS_accept4: return accept4((int) arg1, (struct sockaddr *) (uintptr_t) arg2, (socklen_t *) (uintptr_t) arg3, (int) arg4); case SYS_accept: return accept((int) arg1, (struct sockaddr *) (uintptr_t) arg2, (socklen_t *) (uintptr_t) arg3); case SYS_fcntl: va_start(val, number); (void) va_arg(val, long); (void) va_arg(val, long); ret = vfcntl((int) arg1, (int) arg2, val, 0); va_end(val); return ret; #ifdef SYS_fcntl64 case SYS_fcntl64: va_start(val, number); (void) va_arg(val, long); (void) va_arg(val, long); ret = vfcntl((int) arg1, (int) arg2, val, 1); va_end(val); return ret; #endif case SYS_getsockopt: return getsockopt((int) arg1, (int) arg2, (int) arg3, (void *) (uintptr_t) arg4, (socklen_t *) (uintptr_t) arg5); case SYS_setsockopt: return setsockopt((int) arg1, (int) arg2, (int) arg3, (const void *) (uintptr_t) arg4, (socklen_t) arg5); case SYS_getsockname: return getsockname((int) arg1, (struct sockaddr *) (uintptr_t) arg2, (socklen_t *) (uintptr_t) arg3); case SYS_getpeername: return getpeername((int) arg1, (struct sockaddr *) (uintptr_t) arg2, (socklen_t *) (uintptr_t) arg3); case SYS_read: return read((int) arg1, (void *) (uintptr_t) arg2, (size_t) arg3); #ifdef SYS_recv case SYS_recv: return recv((int) arg1, (void *) (uintptr_t) arg2, (size_t) arg3, (int) arg4); #endif case SYS_recvfrom: return recvfrom((int) arg1, (void *) (uintptr_t) arg2, (size_t) arg3, (int) arg4, (struct sockaddr *) (uintptr_t) arg5, (socklen_t *) (uintptr_t) arg6); case SYS_recvmsg: return recvmsg((int) arg1, (struct msghdr *) (uintptr_t) arg2, (int) arg3); case SYS_readv: return readv((int) arg1, (struct iovec *) (uintptr_t) arg2, (int) arg3); case SYS_pread64: return pread((int) arg1, (void *) (uintptr_t) arg2, (size_t) arg3, (off_t) arg4); case SYS_write: return write((int) arg1, (const void *) (uintptr_t) arg2, (size_t) arg3); #ifdef SYS_send case SYS_send: return send((int) arg1, (const void *) (uintptr_t) arg2, (size_t) arg3, (int) arg4); #endif case SYS_sendto: return sendto((int) arg1,(const void *) (uintptr_t) arg2, (size_t) arg3, (int) arg4, (const struct sockaddr *) (uintptr_t) arg5, (socklen_t) arg6); case SYS_sendmsg: return sendmsg((int) arg1, (const struct msghdr *) (uintptr_t) arg2, (int) arg3); case SYS_writev: return writev((int) arg1, (const struct iovec *) (uintptr_t) arg2, (int) arg3); case SYS_pwrite64: return pwrite((int) arg1, (const void *) (uintptr_t) arg2, (size_t) arg3, (off_t) arg4); case SYS_sendfile: return sendfile((int) arg1, (int) arg2, (off_t *) (uintptr_t) arg3, (size_t) arg4); case SYS_select: return select((int) arg1, (fd_set *) (uintptr_t) arg2, (fd_set *) (uintptr_t) arg3, (fd_set *) (uintptr_t) arg4, (struct timeval *) (uintptr_t) arg5); case SYS_pselect6: fprintf(stderr, "tas syscall(): warning our pselect6 does not update " "timeout value\n"); return pselect((int) arg1, (fd_set *) (uintptr_t) arg2, (fd_set *) (uintptr_t) arg3, (fd_set *) (uintptr_t) arg4, (struct timespec *) (uintptr_t) arg5, (const sigset_t *) (uintptr_t) arg6); case SYS_epoll_create: return epoll_create((int) arg1); case SYS_epoll_create1: return epoll_create1((int) arg1); case SYS_epoll_ctl: return epoll_ctl((int) arg1, (int) arg2, (int) arg3, (struct epoll_event *) (uintptr_t) arg4); case SYS_epoll_wait: return epoll_wait((int) arg1, (struct epoll_event *) (uintptr_t) arg2, (int) arg3, (int) arg4); case SYS_epoll_pwait: return epoll_pwait((int) arg1, (struct epoll_event *) (uintptr_t) arg2, (int) arg3, (int) arg4, (const sigset_t *) (uintptr_t) arg5); case SYS_poll: return poll((struct pollfd *) (uintptr_t) arg1, (nfds_t) arg2, (int) arg3); case SYS_ppoll: return ppoll((struct pollfd *) (uintptr_t) arg1, (nfds_t) arg2, (const struct timespec *) (uintptr_t) arg3, (const sigset_t *) (uintptr_t) arg4); case SYS_dup: return dup((int) arg1); case SYS_dup2: return dup2((int) arg1, (int) arg2); case SYS_dup3: return dup3((int) arg1, (int) arg2, (int) arg3); } return libc_syscall(number, arg1, arg2, arg3, arg4, arg5, arg6); } /******************************************************************************/ /* Helper functions */ static void *bind_symbol(const char *sym) { void *ptr; if ((ptr = dlsym(RTLD_NEXT, sym)) == NULL) { fprintf(stderr, "flextcp socket interpose: dlsym failed (%s)\n", sym); abort(); } return ptr; } static void init(void) { libc_socket = bind_symbol("socket"); libc_close = bind_symbol("close"); libc_shutdown = bind_symbol("shutdown"); libc_bind = bind_symbol("bind"); libc_connect = bind_symbol("connect"); libc_listen = bind_symbol("listen"); libc_accept4 = bind_symbol("accept4"); libc_accept = bind_symbol("accept"); libc_fcntl = bind_symbol("fcntl"); libc_fcntl64 = dlsym(RTLD_NEXT, "fcntl64"); if (libc_fcntl64 == NULL) libc_fcntl64 = libc_fcntl; libc_getsockopt = bind_symbol("getsockopt"); libc_setsockopt = bind_symbol("setsockopt"); libc_getsockname = bind_symbol("getsockname"); libc_getpeername = bind_symbol("getpeername"); libc_read = bind_symbol("read"); libc_recv = bind_symbol("recv"); libc_recvfrom = bind_symbol("recvfrom"); libc_recvmsg = bind_symbol("recvmsg"); libc_readv = bind_symbol("readv"); libc_pread = bind_symbol("pread"); libc_write = bind_symbol("write"); libc_send = bind_symbol("send"); libc_sendto = bind_symbol("sendto"); libc_sendmsg = bind_symbol("sendmsg"); libc_writev = bind_symbol("writev"); libc_pwrite = bind_symbol("pwrite"); libc_sendfile = bind_symbol("sendfile"); libc_syscall = bind_symbol("syscall"); if (tas_init() != 0) { abort(); } } static inline void ensure_init(void) { static volatile uint32_t init_cnt = 0; static volatile uint8_t init_done = 0; static __thread uint8_t in_init = 0; if (init_done == 0) { /* during init the socket functions will be used to connect to the kernel on * a unix socket, so make sure that runs through. */ if (in_init) { return; } if (__sync_fetch_and_add(&init_cnt, 1) == 0) { in_init = 1; init(); in_init = 0; MEM_BARRIER(); init_done = 1; } else { while (init_done == 0) { pthread_yield(); } MEM_BARRIER(); } } }
894546.c
//------------------------------------------------------------------------------ // Simple C99 cimgui+sokol starter project for Win32, Linux and macOS. //------------------------------------------------------------------------------ #include "sokol_app.h" #include "sokol_gfx.h" #include "sokol_time.h" #include "sokol_glue.h" #define CIMGUI_DEFINE_ENUMS_AND_STRUCTS #include "cimgui.h" #include "sokol_imgui.h" static struct { uint64_t laptime; sg_pass_action pass_action; } state; static void init(void) { sg_setup(&(sg_desc){ .context = sapp_sgcontext() }); stm_setup(); simgui_setup(&(simgui_desc_t){ 0 }); // initial clear color state.pass_action = (sg_pass_action) { .colors[0] = { .action = SG_ACTION_CLEAR, .value = { 0.0f, 0.5f, 1.0f, 1.0 } } }; } static void frame(void) { const int width = sapp_width(); const int height = sapp_height(); const double delta_time = stm_sec(stm_round_to_common_refresh_rate(stm_laptime(&state.laptime))); simgui_new_frame(width, height, delta_time); /*=== UI CODE STARTS HERE ===*/ igSetNextWindowPos((ImVec2){10,10}, ImGuiCond_Once, (ImVec2){0,0}); igSetNextWindowSize((ImVec2){400, 100}, ImGuiCond_Once); igBegin("Hello Dear ImGui!", 0, ImGuiWindowFlags_None); igColorEdit3("Background", &state.pass_action.colors[0].value.r, ImGuiColorEditFlags_None); igEnd(); /*=== UI CODE ENDS HERE ===*/ sg_begin_default_pass(&state.pass_action, width, height); simgui_render(); sg_end_pass(); sg_commit(); } static void cleanup(void) { simgui_shutdown(); sg_shutdown(); } static void event(const sapp_event* ev) { simgui_handle_event(ev); } sapp_desc sokol_main(int argc, char* argv[]) { (void)argc; (void)argv; return (sapp_desc){ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .event_cb = event, .window_title = "Hello Sokol + Dear ImGui", .width = 800, .height = 600, }; }
286931.c
/* * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) * From ASN.1 module "NR-RRC-Definitions" * found in "asn/nr-rrc-15.6.0.asn1" * `asn1c -fcompound-names -pdu=all -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D rrc` */ #include "ASN_RRC_CSI-IM-ResourceId.h" int ASN_RRC_CSI_IM_ResourceId_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { long value; if(!sptr) { ASN__CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } value = *(const long *)sptr; if((value >= 0 && value <= 31)) { /* Constraint check succeeded */ return 0; } else { ASN__CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using NativeInteger, * so here we adjust the DEF accordingly. */ asn_per_constraints_t asn_PER_type_ASN_RRC_CSI_IM_ResourceId_constr_1 CC_NOTUSED = { { APC_CONSTRAINED, 5, 5, 0, 31 } /* (0..31) */, { APC_UNCONSTRAINED, -1, -1, 0, 0 }, 0, 0 /* No PER value map */ }; static const ber_tlv_tag_t asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) }; asn_TYPE_descriptor_t asn_DEF_ASN_RRC_CSI_IM_ResourceId = { "CSI-IM-ResourceId", "CSI-IM-ResourceId", &asn_OP_NativeInteger, asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1, sizeof(asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1) /sizeof(asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1[0]), /* 1 */ asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1, /* Same as above */ sizeof(asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1) /sizeof(asn_DEF_ASN_RRC_CSI_IM_ResourceId_tags_1[0]), /* 1 */ { 0, &asn_PER_type_ASN_RRC_CSI_IM_ResourceId_constr_1, ASN_RRC_CSI_IM_ResourceId_constraint }, 0, 0, /* No members */ 0 /* No specifics */ };
51608.c
/* $OpenBSD: sftp-server.c,v 1.94 2011/06/17 21:46:16 djm Exp $ */ /* * Copyright (c) 2000-2004 Markus Friedl. All rights reserved. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "includes.h" #include <sys/types.h> #include <sys/param.h> #include <sys/stat.h> #ifdef HAVE_SYS_TIME_H # include <sys/time.h> #endif #ifdef HAVE_SYS_MOUNT_H #include <sys/mount.h> #endif #ifdef HAVE_SYS_STATVFS_H #include <sys/statvfs.h> #endif #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <pwd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pwd.h> #include <time.h> #include <unistd.h> #include <stdarg.h> #include "xmalloc.h" #include "buffer.h" #include "log.h" #include "misc.h" #include "uidswap.h" #include "sftp.h" #include "sftp-common.h" /* helper */ #define get_int64() buffer_get_int64(&iqueue); #define get_int() buffer_get_int(&iqueue); #define get_string(lenp) buffer_get_string(&iqueue, lenp); /* Our verbosity */ LogLevel log_level = SYSLOG_LEVEL_ERROR; /* Our client */ struct passwd *pw = NULL; char *client_addr = NULL; /* input and output queue */ Buffer iqueue; Buffer oqueue; /* Version of client */ u_int version; /* Disable writes */ int readonly; /* portable attributes, etc. */ typedef struct Stat Stat; struct Stat { char *name; char *long_name; Attrib attrib; }; static int errno_to_portable(int unixerrno) { int ret = 0; switch (unixerrno) { case 0: ret = SSH2_FX_OK; break; case ENOENT: case ENOTDIR: case EBADF: case ELOOP: ret = SSH2_FX_NO_SUCH_FILE; break; case EPERM: case EACCES: case EFAULT: ret = SSH2_FX_PERMISSION_DENIED; break; case ENAMETOOLONG: case EINVAL: ret = SSH2_FX_BAD_MESSAGE; break; case ENOSYS: ret = SSH2_FX_OP_UNSUPPORTED; break; default: ret = SSH2_FX_FAILURE; break; } return ret; } static int flags_from_portable(int pflags) { int flags = 0; if ((pflags & SSH2_FXF_READ) && (pflags & SSH2_FXF_WRITE)) { flags = O_RDWR; } else if (pflags & SSH2_FXF_READ) { flags = O_RDONLY; } else if (pflags & SSH2_FXF_WRITE) { flags = O_WRONLY; } if (pflags & SSH2_FXF_CREAT) flags |= O_CREAT; if (pflags & SSH2_FXF_TRUNC) flags |= O_TRUNC; if (pflags & SSH2_FXF_EXCL) flags |= O_EXCL; return flags; } static const char * string_from_portable(int pflags) { static char ret[128]; *ret = '\0'; #define PAPPEND(str) { \ if (*ret != '\0') \ strlcat(ret, ",", sizeof(ret)); \ strlcat(ret, str, sizeof(ret)); \ } if (pflags & SSH2_FXF_READ) PAPPEND("READ") if (pflags & SSH2_FXF_WRITE) PAPPEND("WRITE") if (pflags & SSH2_FXF_CREAT) PAPPEND("CREATE") if (pflags & SSH2_FXF_TRUNC) PAPPEND("TRUNCATE") if (pflags & SSH2_FXF_EXCL) PAPPEND("EXCL") return ret; } static Attrib * get_attrib(void) { return decode_attrib(&iqueue); } /* handle handles */ typedef struct Handle Handle; struct Handle { int use; DIR *dirp; int fd; char *name; u_int64_t bytes_read, bytes_write; int next_unused; }; enum { HANDLE_UNUSED, HANDLE_DIR, HANDLE_FILE }; Handle *handles = NULL; u_int num_handles = 0; int first_unused_handle = -1; static void handle_unused(int i) { handles[i].use = HANDLE_UNUSED; handles[i].next_unused = first_unused_handle; first_unused_handle = i; } static int handle_new(int use, const char *name, int fd, DIR *dirp) { int i; if (first_unused_handle == -1) { if (num_handles + 1 <= num_handles) return -1; num_handles++; handles = xrealloc(handles, num_handles, sizeof(Handle)); handle_unused(num_handles - 1); } i = first_unused_handle; first_unused_handle = handles[i].next_unused; handles[i].use = use; handles[i].dirp = dirp; handles[i].fd = fd; handles[i].name = xstrdup(name); handles[i].bytes_read = handles[i].bytes_write = 0; return i; } static int handle_is_ok(int i, int type) { return i >= 0 && (u_int)i < num_handles && handles[i].use == type; } static int handle_to_string(int handle, char **stringp, int *hlenp) { if (stringp == NULL || hlenp == NULL) return -1; *stringp = xmalloc(sizeof(int32_t)); put_u32(*stringp, handle); *hlenp = sizeof(int32_t); return 0; } static int handle_from_string(const char *handle, u_int hlen) { int val; if (hlen != sizeof(int32_t)) return -1; val = get_u32(handle); if (handle_is_ok(val, HANDLE_FILE) || handle_is_ok(val, HANDLE_DIR)) return val; return -1; } static char * handle_to_name(int handle) { if (handle_is_ok(handle, HANDLE_DIR)|| handle_is_ok(handle, HANDLE_FILE)) return handles[handle].name; return NULL; } static DIR * handle_to_dir(int handle) { if (handle_is_ok(handle, HANDLE_DIR)) return handles[handle].dirp; return NULL; } static int handle_to_fd(int handle) { if (handle_is_ok(handle, HANDLE_FILE)) return handles[handle].fd; return -1; } static void handle_update_read(int handle, ssize_t bytes) { if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0) handles[handle].bytes_read += bytes; } static void handle_update_write(int handle, ssize_t bytes) { if (handle_is_ok(handle, HANDLE_FILE) && bytes > 0) handles[handle].bytes_write += bytes; } static u_int64_t handle_bytes_read(int handle) { if (handle_is_ok(handle, HANDLE_FILE)) return (handles[handle].bytes_read); return 0; } static u_int64_t handle_bytes_write(int handle) { if (handle_is_ok(handle, HANDLE_FILE)) return (handles[handle].bytes_write); return 0; } static int handle_close(int handle) { int ret = -1; if (handle_is_ok(handle, HANDLE_FILE)) { ret = close(handles[handle].fd); xfree(handles[handle].name); handle_unused(handle); } else if (handle_is_ok(handle, HANDLE_DIR)) { ret = closedir(handles[handle].dirp); xfree(handles[handle].name); handle_unused(handle); } else { errno = ENOENT; } return ret; } static void handle_log_close(int handle, char *emsg) { if (handle_is_ok(handle, HANDLE_FILE)) { logit("%s%sclose \"%s\" bytes read %llu written %llu", emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ", handle_to_name(handle), (unsigned long long)handle_bytes_read(handle), (unsigned long long)handle_bytes_write(handle)); } else { logit("%s%sclosedir \"%s\"", emsg == NULL ? "" : emsg, emsg == NULL ? "" : " ", handle_to_name(handle)); } } static void handle_log_exit(void) { u_int i; for (i = 0; i < num_handles; i++) if (handles[i].use != HANDLE_UNUSED) handle_log_close(i, "forced"); } static int get_handle(void) { char *handle; int val = -1; u_int hlen; handle = get_string(&hlen); if (hlen < 256) val = handle_from_string(handle, hlen); xfree(handle); return val; } /* send replies */ static void send_msg(Buffer *m) { int mlen = buffer_len(m); buffer_put_int(&oqueue, mlen); buffer_append(&oqueue, buffer_ptr(m), mlen); buffer_consume(m, mlen); } static const char * status_to_message(u_int32_t status) { const char *status_messages[] = { "Success", /* SSH_FX_OK */ "End of file", /* SSH_FX_EOF */ "No such file", /* SSH_FX_NO_SUCH_FILE */ "Permission denied", /* SSH_FX_PERMISSION_DENIED */ "Failure", /* SSH_FX_FAILURE */ "Bad message", /* SSH_FX_BAD_MESSAGE */ "No connection", /* SSH_FX_NO_CONNECTION */ "Connection lost", /* SSH_FX_CONNECTION_LOST */ "Operation unsupported", /* SSH_FX_OP_UNSUPPORTED */ "Unknown error" /* Others */ }; return (status_messages[MIN(status,SSH2_FX_MAX)]); } static void send_status(u_int32_t id, u_int32_t status) { Buffer msg; debug3("request %u: sent status %u", id, status); if (log_level > SYSLOG_LEVEL_VERBOSE || (status != SSH2_FX_OK && status != SSH2_FX_EOF)) logit("sent status %s", status_to_message(status)); buffer_init(&msg); buffer_put_char(&msg, SSH2_FXP_STATUS); buffer_put_int(&msg, id); buffer_put_int(&msg, status); if (version >= 3) { buffer_put_cstring(&msg, status_to_message(status)); buffer_put_cstring(&msg, ""); } send_msg(&msg); buffer_free(&msg); } static void send_data_or_handle(char type, u_int32_t id, const char *data, int dlen) { Buffer msg; buffer_init(&msg); buffer_put_char(&msg, type); buffer_put_int(&msg, id); buffer_put_string(&msg, data, dlen); send_msg(&msg); buffer_free(&msg); } static void send_data(u_int32_t id, const char *data, int dlen) { debug("request %u: sent data len %d", id, dlen); send_data_or_handle(SSH2_FXP_DATA, id, data, dlen); } static void send_handle(u_int32_t id, int handle) { char *string; int hlen; handle_to_string(handle, &string, &hlen); debug("request %u: sent handle handle %d", id, handle); send_data_or_handle(SSH2_FXP_HANDLE, id, string, hlen); xfree(string); } static void send_names(u_int32_t id, int count, const Stat *stats) { Buffer msg; int i; buffer_init(&msg); buffer_put_char(&msg, SSH2_FXP_NAME); buffer_put_int(&msg, id); buffer_put_int(&msg, count); debug("request %u: sent names count %d", id, count); for (i = 0; i < count; i++) { buffer_put_cstring(&msg, stats[i].name); buffer_put_cstring(&msg, stats[i].long_name); encode_attrib(&msg, &stats[i].attrib); } send_msg(&msg); buffer_free(&msg); } static void send_attrib(u_int32_t id, const Attrib *a) { Buffer msg; debug("request %u: sent attrib have 0x%x", id, a->flags); buffer_init(&msg); buffer_put_char(&msg, SSH2_FXP_ATTRS); buffer_put_int(&msg, id); encode_attrib(&msg, a); send_msg(&msg); buffer_free(&msg); } static void send_statvfs(u_int32_t id, struct statvfs *st) { Buffer msg; u_int64_t flag; flag = (st->f_flag & ST_RDONLY) ? SSH2_FXE_STATVFS_ST_RDONLY : 0; flag |= (st->f_flag & ST_NOSUID) ? SSH2_FXE_STATVFS_ST_NOSUID : 0; buffer_init(&msg); buffer_put_char(&msg, SSH2_FXP_EXTENDED_REPLY); buffer_put_int(&msg, id); buffer_put_int64(&msg, st->f_bsize); buffer_put_int64(&msg, st->f_frsize); buffer_put_int64(&msg, st->f_blocks); buffer_put_int64(&msg, st->f_bfree); buffer_put_int64(&msg, st->f_bavail); buffer_put_int64(&msg, st->f_files); buffer_put_int64(&msg, st->f_ffree); buffer_put_int64(&msg, st->f_favail); buffer_put_int64(&msg, FSID_TO_ULONG(st->f_fsid)); buffer_put_int64(&msg, flag); buffer_put_int64(&msg, st->f_namemax); send_msg(&msg); buffer_free(&msg); } /* parse incoming */ static void process_init(void) { Buffer msg; version = get_int(); verbose("received client version %u", version); buffer_init(&msg); buffer_put_char(&msg, SSH2_FXP_VERSION); buffer_put_int(&msg, SSH2_FILEXFER_VERSION); /* POSIX rename extension */ buffer_put_cstring(&msg, "[email protected]"); buffer_put_cstring(&msg, "1"); /* version */ /* statvfs extension */ buffer_put_cstring(&msg, "[email protected]"); buffer_put_cstring(&msg, "2"); /* version */ /* fstatvfs extension */ buffer_put_cstring(&msg, "[email protected]"); buffer_put_cstring(&msg, "2"); /* version */ /* hardlink extension */ buffer_put_cstring(&msg, "[email protected]"); buffer_put_cstring(&msg, "1"); /* version */ send_msg(&msg); buffer_free(&msg); } static void process_open(void) { u_int32_t id, pflags; Attrib *a; char *name; int handle, fd, flags, mode, status = SSH2_FX_FAILURE; id = get_int(); name = get_string(NULL); pflags = get_int(); /* portable flags */ debug3("request %u: open flags %d", id, pflags); a = get_attrib(); flags = flags_from_portable(pflags); mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm : 0666; logit("open \"%s\" flags %s mode 0%o", name, string_from_portable(pflags), mode); if (readonly && ((flags & O_ACCMODE) == O_WRONLY || (flags & O_ACCMODE) == O_RDWR)) status = SSH2_FX_PERMISSION_DENIED; else { fd = open(name, flags, mode); if (fd < 0) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_FILE, name, fd, NULL); if (handle < 0) { close(fd); } else { send_handle(id, handle); status = SSH2_FX_OK; } } } if (status != SSH2_FX_OK) send_status(id, status); xfree(name); } static void process_close(void) { u_int32_t id; int handle, ret, status = SSH2_FX_FAILURE; id = get_int(); handle = get_handle(); debug3("request %u: close handle %u", id, handle); handle_log_close(handle, NULL); ret = handle_close(handle); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; send_status(id, status); } static void process_read(void) { char buf[64*1024]; u_int32_t id, len; int handle, fd, ret, status = SSH2_FX_FAILURE; u_int64_t off; id = get_int(); handle = get_handle(); off = get_int64(); len = get_int(); debug("request %u: read \"%s\" (handle %d) off %llu len %d", id, handle_to_name(handle), handle, (unsigned long long)off, len); if (len > sizeof buf) { len = sizeof buf; debug2("read change len %d", len); } fd = handle_to_fd(handle); if (fd >= 0) { if (lseek(fd, off, SEEK_SET) < 0) { error("process_read: seek failed"); status = errno_to_portable(errno); } else { ret = read(fd, buf, len); if (ret < 0) { status = errno_to_portable(errno); } else if (ret == 0) { status = SSH2_FX_EOF; } else { send_data(id, buf, ret); status = SSH2_FX_OK; handle_update_read(handle, ret); } } } if (status != SSH2_FX_OK) send_status(id, status); } static void process_write(void) { u_int32_t id; u_int64_t off; u_int len; int handle, fd, ret, status; char *data; id = get_int(); handle = get_handle(); off = get_int64(); data = get_string(&len); debug("request %u: write \"%s\" (handle %d) off %llu len %d", id, handle_to_name(handle), handle, (unsigned long long)off, len); fd = handle_to_fd(handle); if (fd < 0) status = SSH2_FX_FAILURE; else if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { if (lseek(fd, off, SEEK_SET) < 0) { status = errno_to_portable(errno); error("process_write: seek failed"); } else { /* XXX ATOMICIO ? */ ret = write(fd, data, len); if (ret < 0) { error("process_write: write failed"); status = errno_to_portable(errno); } else if ((size_t)ret == len) { status = SSH2_FX_OK; handle_update_write(handle, ret); } else { debug2("nothing at all written"); status = SSH2_FX_FAILURE; } } } send_status(id, status); xfree(data); } static void process_do_stat(int do_lstat) { Attrib a; struct stat st; u_int32_t id; char *name; int ret, status = SSH2_FX_FAILURE; id = get_int(); name = get_string(NULL); debug3("request %u: %sstat", id, do_lstat ? "l" : ""); verbose("%sstat name \"%s\"", do_lstat ? "l" : "", name); ret = do_lstat ? lstat(name, &st) : stat(name, &st); if (ret < 0) { status = errno_to_portable(errno); } else { stat_to_attrib(&st, &a); send_attrib(id, &a); status = SSH2_FX_OK; } if (status != SSH2_FX_OK) send_status(id, status); xfree(name); } static void process_stat(void) { process_do_stat(0); } static void process_lstat(void) { process_do_stat(1); } static void process_fstat(void) { Attrib a; struct stat st; u_int32_t id; int fd, ret, handle, status = SSH2_FX_FAILURE; id = get_int(); handle = get_handle(); debug("request %u: fstat \"%s\" (handle %u)", id, handle_to_name(handle), handle); fd = handle_to_fd(handle); if (fd >= 0) { ret = fstat(fd, &st); if (ret < 0) { status = errno_to_portable(errno); } else { stat_to_attrib(&st, &a); send_attrib(id, &a); status = SSH2_FX_OK; } } if (status != SSH2_FX_OK) send_status(id, status); } static struct timeval * attrib_to_tv(const Attrib *a) { static struct timeval tv[2]; tv[0].tv_sec = a->atime; tv[0].tv_usec = 0; tv[1].tv_sec = a->mtime; tv[1].tv_usec = 0; return tv; } static void process_setstat(void) { Attrib *a; u_int32_t id; char *name; int status = SSH2_FX_OK, ret; id = get_int(); name = get_string(NULL); a = get_attrib(); debug("request %u: setstat name \"%s\"", id, name); if (readonly) { status = SSH2_FX_PERMISSION_DENIED; a->flags = 0; } if (a->flags & SSH2_FILEXFER_ATTR_SIZE) { logit("set \"%s\" size %llu", name, (unsigned long long)a->size); ret = truncate(name, a->size); if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) { logit("set \"%s\" mode %04o", name, a->perm); ret = chmod(name, a->perm & 07777); if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { char buf[64]; time_t t = a->mtime; strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S", localtime(&t)); logit("set \"%s\" modtime %s", name, buf); ret = utimes(name, attrib_to_tv(a)); if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { logit("set \"%s\" owner %lu group %lu", name, (u_long)a->uid, (u_long)a->gid); ret = chown(name, a->uid, a->gid); if (ret == -1) status = errno_to_portable(errno); } send_status(id, status); xfree(name); } static void process_fsetstat(void) { Attrib *a; u_int32_t id; int handle, fd, ret; int status = SSH2_FX_OK; id = get_int(); handle = get_handle(); a = get_attrib(); debug("request %u: fsetstat handle %d", id, handle); fd = handle_to_fd(handle); if (fd < 0) status = SSH2_FX_FAILURE; else if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { char *name = handle_to_name(handle); if (a->flags & SSH2_FILEXFER_ATTR_SIZE) { logit("set \"%s\" size %llu", name, (unsigned long long)a->size); ret = ftruncate(fd, a->size); if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) { logit("set \"%s\" mode %04o", name, a->perm); #ifdef HAVE_FCHMOD ret = fchmod(fd, a->perm & 07777); #else ret = chmod(name, a->perm & 07777); #endif if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_ACMODTIME) { char buf[64]; time_t t = a->mtime; strftime(buf, sizeof(buf), "%Y%m%d-%H:%M:%S", localtime(&t)); logit("set \"%s\" modtime %s", name, buf); #ifdef HAVE_FUTIMES ret = futimes(fd, attrib_to_tv(a)); #else ret = utimes(name, attrib_to_tv(a)); #endif if (ret == -1) status = errno_to_portable(errno); } if (a->flags & SSH2_FILEXFER_ATTR_UIDGID) { logit("set \"%s\" owner %lu group %lu", name, (u_long)a->uid, (u_long)a->gid); #ifdef HAVE_FCHOWN ret = fchown(fd, a->uid, a->gid); #else ret = chown(name, a->uid, a->gid); #endif if (ret == -1) status = errno_to_portable(errno); } } send_status(id, status); } static void process_opendir(void) { DIR *dirp = NULL; char *path; int handle, status = SSH2_FX_FAILURE; u_int32_t id; id = get_int(); path = get_string(NULL); debug3("request %u: opendir", id); logit("opendir \"%s\"", path); dirp = opendir(path); if (dirp == NULL) { status = errno_to_portable(errno); } else { handle = handle_new(HANDLE_DIR, path, 0, dirp); if (handle < 0) { closedir(dirp); } else { send_handle(id, handle); status = SSH2_FX_OK; } } if (status != SSH2_FX_OK) send_status(id, status); xfree(path); } static void process_readdir(void) { DIR *dirp; struct dirent *dp; char *path; int handle; u_int32_t id; id = get_int(); handle = get_handle(); debug("request %u: readdir \"%s\" (handle %d)", id, handle_to_name(handle), handle); dirp = handle_to_dir(handle); path = handle_to_name(handle); if (dirp == NULL || path == NULL) { send_status(id, SSH2_FX_FAILURE); } else { struct stat st; char pathname[MAXPATHLEN]; Stat *stats; int nstats = 10, count = 0, i; stats = xcalloc(nstats, sizeof(Stat)); while ((dp = readdir(dirp)) != NULL) { if (count >= nstats) { nstats *= 2; stats = xrealloc(stats, nstats, sizeof(Stat)); } /* XXX OVERFLOW ? */ snprintf(pathname, sizeof pathname, "%s%s%s", path, strcmp(path, "/") ? "/" : "", dp->d_name); if (lstat(pathname, &st) < 0) continue; stat_to_attrib(&st, &(stats[count].attrib)); stats[count].name = xstrdup(dp->d_name); stats[count].long_name = ls_file(dp->d_name, &st, 0, 0); count++; /* send up to 100 entries in one message */ /* XXX check packet size instead */ if (count == 100) break; } if (count > 0) { send_names(id, count, stats); for (i = 0; i < count; i++) { xfree(stats[i].name); xfree(stats[i].long_name); } } else { send_status(id, SSH2_FX_EOF); } xfree(stats); } } static void process_remove(void) { char *name; u_int32_t id; int status = SSH2_FX_FAILURE; int ret; id = get_int(); name = get_string(NULL); debug3("request %u: remove", id); logit("remove name \"%s\"", name); if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = unlink(name); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(name); } static void process_mkdir(void) { Attrib *a; u_int32_t id; char *name; int ret, mode, status = SSH2_FX_FAILURE; id = get_int(); name = get_string(NULL); a = get_attrib(); mode = (a->flags & SSH2_FILEXFER_ATTR_PERMISSIONS) ? a->perm & 07777 : 0777; debug3("request %u: mkdir", id); logit("mkdir name \"%s\" mode 0%o", name, mode); if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = mkdir(name, mode); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(name); } static void process_rmdir(void) { u_int32_t id; char *name; int ret, status; id = get_int(); name = get_string(NULL); debug3("request %u: rmdir", id); logit("rmdir name \"%s\"", name); if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = rmdir(name); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(name); } static void process_realpath(void) { char resolvedname[MAXPATHLEN]; u_int32_t id; char *path; id = get_int(); path = get_string(NULL); if (path[0] == '\0') { xfree(path); path = xstrdup("."); } debug3("request %u: realpath", id); verbose("realpath \"%s\"", path); if (realpath(path, resolvedname) == NULL) { send_status(id, errno_to_portable(errno)); } else { Stat s; attrib_clear(&s.attrib); s.name = s.long_name = resolvedname; send_names(id, 1, &s); } xfree(path); } static void process_rename(void) { u_int32_t id; char *oldpath, *newpath; int status; struct stat sb; id = get_int(); oldpath = get_string(NULL); newpath = get_string(NULL); debug3("request %u: rename", id); logit("rename old \"%s\" new \"%s\"", oldpath, newpath); status = SSH2_FX_FAILURE; if (readonly) status = SSH2_FX_PERMISSION_DENIED; else if (lstat(oldpath, &sb) == -1) status = errno_to_portable(errno); else if (S_ISREG(sb.st_mode)) { /* Race-free rename of regular files */ if (link(oldpath, newpath) == -1) { if (errno == EOPNOTSUPP || errno == ENOSYS #ifdef EXDEV || errno == EXDEV #endif #ifdef LINK_OPNOTSUPP_ERRNO || errno == LINK_OPNOTSUPP_ERRNO #endif ) { struct stat st; /* * fs doesn't support links, so fall back to * stat+rename. This is racy. */ if (stat(newpath, &st) == -1) { if (rename(oldpath, newpath) == -1) status = errno_to_portable(errno); else status = SSH2_FX_OK; } } else { status = errno_to_portable(errno); } } else if (unlink(oldpath) == -1) { status = errno_to_portable(errno); /* clean spare link */ unlink(newpath); } else status = SSH2_FX_OK; } else if (stat(newpath, &sb) == -1) { if (rename(oldpath, newpath) == -1) status = errno_to_portable(errno); else status = SSH2_FX_OK; } send_status(id, status); xfree(oldpath); xfree(newpath); } static void process_readlink(void) { u_int32_t id; int len; char buf[MAXPATHLEN]; char *path; id = get_int(); path = get_string(NULL); debug3("request %u: readlink", id); verbose("readlink \"%s\"", path); if ((len = readlink(path, buf, sizeof(buf) - 1)) == -1) send_status(id, errno_to_portable(errno)); else { Stat s; buf[len] = '\0'; attrib_clear(&s.attrib); s.name = s.long_name = buf; send_names(id, 1, &s); } xfree(path); } static void process_symlink(void) { u_int32_t id; char *oldpath, *newpath; int ret, status; id = get_int(); oldpath = get_string(NULL); newpath = get_string(NULL); debug3("request %u: symlink", id); logit("symlink old \"%s\" new \"%s\"", oldpath, newpath); /* this will fail if 'newpath' exists */ if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = symlink(oldpath, newpath); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(oldpath); xfree(newpath); } static void process_extended_posix_rename(u_int32_t id) { char *oldpath, *newpath; int ret, status; oldpath = get_string(NULL); newpath = get_string(NULL); debug3("request %u: posix-rename", id); logit("posix-rename old \"%s\" new \"%s\"", oldpath, newpath); if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = rename(oldpath, newpath); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(oldpath); xfree(newpath); } static void process_extended_statvfs(u_int32_t id) { char *path; struct statvfs st; path = get_string(NULL); debug3("request %u: statfs", id); logit("statfs \"%s\"", path); if (statvfs(path, &st) != 0) send_status(id, errno_to_portable(errno)); else send_statvfs(id, &st); xfree(path); } static void process_extended_fstatvfs(u_int32_t id) { int handle, fd; struct statvfs st; handle = get_handle(); debug("request %u: fstatvfs \"%s\" (handle %u)", id, handle_to_name(handle), handle); if ((fd = handle_to_fd(handle)) < 0) { send_status(id, SSH2_FX_FAILURE); return; } if (fstatvfs(fd, &st) != 0) send_status(id, errno_to_portable(errno)); else send_statvfs(id, &st); } static void process_extended_hardlink(u_int32_t id) { char *oldpath, *newpath; int ret, status; oldpath = get_string(NULL); newpath = get_string(NULL); debug3("request %u: hardlink", id); logit("hardlink old \"%s\" new \"%s\"", oldpath, newpath); if (readonly) status = SSH2_FX_PERMISSION_DENIED; else { ret = link(oldpath, newpath); status = (ret == -1) ? errno_to_portable(errno) : SSH2_FX_OK; } send_status(id, status); xfree(oldpath); xfree(newpath); } static void process_extended(void) { u_int32_t id; char *request; id = get_int(); request = get_string(NULL); if (strcmp(request, "[email protected]") == 0) process_extended_posix_rename(id); else if (strcmp(request, "[email protected]") == 0) process_extended_statvfs(id); else if (strcmp(request, "[email protected]") == 0) process_extended_fstatvfs(id); else if (strcmp(request, "[email protected]") == 0) process_extended_hardlink(id); else send_status(id, SSH2_FX_OP_UNSUPPORTED); /* MUST */ xfree(request); } /* stolen from ssh-agent */ static void process(void) { u_int msg_len; u_int buf_len; u_int consumed; u_int type; u_char *cp; buf_len = buffer_len(&iqueue); if (buf_len < 5) return; /* Incomplete message. */ cp = buffer_ptr(&iqueue); msg_len = get_u32(cp); if (msg_len > SFTP_MAX_MSG_LENGTH) { error("bad message from %s local user %s", client_addr, pw->pw_name); sftp_server_cleanup_exit(11); } if (buf_len < msg_len + 4) return; buffer_consume(&iqueue, 4); buf_len -= 4; type = buffer_get_char(&iqueue); switch (type) { case SSH2_FXP_INIT: process_init(); break; case SSH2_FXP_OPEN: process_open(); break; case SSH2_FXP_CLOSE: process_close(); break; case SSH2_FXP_READ: process_read(); break; case SSH2_FXP_WRITE: process_write(); break; case SSH2_FXP_LSTAT: process_lstat(); break; case SSH2_FXP_FSTAT: process_fstat(); break; case SSH2_FXP_SETSTAT: process_setstat(); break; case SSH2_FXP_FSETSTAT: process_fsetstat(); break; case SSH2_FXP_OPENDIR: process_opendir(); break; case SSH2_FXP_READDIR: process_readdir(); break; case SSH2_FXP_REMOVE: process_remove(); break; case SSH2_FXP_MKDIR: process_mkdir(); break; case SSH2_FXP_RMDIR: process_rmdir(); break; case SSH2_FXP_REALPATH: process_realpath(); break; case SSH2_FXP_STAT: process_stat(); break; case SSH2_FXP_RENAME: process_rename(); break; case SSH2_FXP_READLINK: process_readlink(); break; case SSH2_FXP_SYMLINK: process_symlink(); break; case SSH2_FXP_EXTENDED: process_extended(); break; default: error("Unknown message %d", type); break; } /* discard the remaining bytes from the current packet */ if (buf_len < buffer_len(&iqueue)) { error("iqueue grew unexpectedly"); sftp_server_cleanup_exit(255); } consumed = buf_len - buffer_len(&iqueue); if (msg_len < consumed) { error("msg_len %d < consumed %d", msg_len, consumed); sftp_server_cleanup_exit(255); } if (msg_len > consumed) buffer_consume(&iqueue, msg_len - consumed); } /* Cleanup handler that logs active handles upon normal exit */ void sftp_server_cleanup_exit(int i) { if (pw != NULL && client_addr != NULL) { handle_log_exit(); logit("session closed for local user %s from [%s]", pw->pw_name, client_addr); } _exit(i); } static void sftp_server_usage(void) { extern char *__progname; fprintf(stderr, "usage: %s [-ehR] [-f log_facility] [-l log_level] [-u umask]\n", __progname); exit(1); } int sftp_server_main(int argc, char **argv, struct passwd *user_pw) { fd_set *rset, *wset; int in, out, max, ch, skipargs = 0, log_stderr = 0; ssize_t len, olen, set_size; SyslogFacility log_facility = SYSLOG_FACILITY_AUTH; char *cp, buf[4*4096]; long mask; extern char *optarg; extern char *__progname; __progname = ssh_get_progname(argv[0]); log_init(__progname, log_level, log_facility, log_stderr); while (!skipargs && (ch = getopt(argc, argv, "f:l:u:cehR")) != -1) { switch (ch) { case 'R': readonly = 1; break; case 'c': /* * Ignore all arguments if we are invoked as a * shell using "sftp-server -c command" */ skipargs = 1; break; case 'e': log_stderr = 1; break; case 'l': log_level = log_level_number(optarg); if (log_level == SYSLOG_LEVEL_NOT_SET) error("Invalid log level \"%s\"", optarg); break; case 'f': log_facility = log_facility_number(optarg); if (log_facility == SYSLOG_FACILITY_NOT_SET) error("Invalid log facility \"%s\"", optarg); break; case 'u': errno = 0; mask = strtol(optarg, &cp, 8); if (mask < 0 || mask > 0777 || *cp != '\0' || cp == optarg || (mask == 0 && errno != 0)) fatal("Invalid umask \"%s\"", optarg); (void)umask((mode_t)mask); break; case 'h': default: sftp_server_usage(); } } log_init(__progname, log_level, log_facility, log_stderr); if ((cp = getenv("SSH_CONNECTION")) != NULL) { client_addr = xstrdup(cp); if ((cp = strchr(client_addr, ' ')) == NULL) { error("Malformed SSH_CONNECTION variable: \"%s\"", getenv("SSH_CONNECTION")); sftp_server_cleanup_exit(255); } *cp = '\0'; } else client_addr = xstrdup("UNKNOWN"); pw = pwcopy(user_pw); logit("session opened for local user %s from [%s]", pw->pw_name, client_addr); in = STDIN_FILENO; out = STDOUT_FILENO; #ifdef HAVE_CYGWIN setmode(in, O_BINARY); setmode(out, O_BINARY); #endif max = 0; if (in > max) max = in; if (out > max) max = out; buffer_init(&iqueue); buffer_init(&oqueue); set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask); rset = (fd_set *)xmalloc(set_size); wset = (fd_set *)xmalloc(set_size); for (;;) { memset(rset, 0, set_size); memset(wset, 0, set_size); /* * Ensure that we can read a full buffer and handle * the worst-case length packet it can generate, * otherwise apply backpressure by stopping reads. */ if (buffer_check_alloc(&iqueue, sizeof(buf)) && buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) FD_SET(in, rset); olen = buffer_len(&oqueue); if (olen > 0) FD_SET(out, wset); if (select(max+1, rset, wset, NULL, NULL) < 0) { if (errno == EINTR) continue; error("select: %s", strerror(errno)); sftp_server_cleanup_exit(2); } /* copy stdin to iqueue */ if (FD_ISSET(in, rset)) { len = read(in, buf, sizeof buf); if (len == 0) { debug("read eof"); sftp_server_cleanup_exit(0); } else if (len < 0) { error("read: %s", strerror(errno)); sftp_server_cleanup_exit(1); } else { buffer_append(&iqueue, buf, len); } } /* send oqueue to stdout */ if (FD_ISSET(out, wset)) { len = write(out, buffer_ptr(&oqueue), olen); if (len < 0) { error("write: %s", strerror(errno)); sftp_server_cleanup_exit(1); } else { buffer_consume(&oqueue, len); } } /* * Process requests from client if we can fit the results * into the output buffer, otherwise stop processing input * and let the output queue drain. */ if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) process(); } }
526678.c
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "v1beta1_lease_list.h" v1beta1_lease_list_t *v1beta1_lease_list_create( char *api_version, list_t *items, char *kind, v1_list_meta_t *metadata ) { v1beta1_lease_list_t *v1beta1_lease_list_local_var = malloc(sizeof(v1beta1_lease_list_t)); if (!v1beta1_lease_list_local_var) { return NULL; } v1beta1_lease_list_local_var->api_version = api_version; v1beta1_lease_list_local_var->items = items; v1beta1_lease_list_local_var->kind = kind; v1beta1_lease_list_local_var->metadata = metadata; return v1beta1_lease_list_local_var; } void v1beta1_lease_list_free(v1beta1_lease_list_t *v1beta1_lease_list) { if(NULL == v1beta1_lease_list){ return ; } listEntry_t *listEntry; if (v1beta1_lease_list->api_version) { free(v1beta1_lease_list->api_version); v1beta1_lease_list->api_version = NULL; } if (v1beta1_lease_list->items) { list_ForEach(listEntry, v1beta1_lease_list->items) { v1beta1_lease_free(listEntry->data); } list_free(v1beta1_lease_list->items); v1beta1_lease_list->items = NULL; } if (v1beta1_lease_list->kind) { free(v1beta1_lease_list->kind); v1beta1_lease_list->kind = NULL; } if (v1beta1_lease_list->metadata) { v1_list_meta_free(v1beta1_lease_list->metadata); v1beta1_lease_list->metadata = NULL; } free(v1beta1_lease_list); } cJSON *v1beta1_lease_list_convertToJSON(v1beta1_lease_list_t *v1beta1_lease_list) { cJSON *item = cJSON_CreateObject(); // v1beta1_lease_list->api_version if(v1beta1_lease_list->api_version) { if(cJSON_AddStringToObject(item, "apiVersion", v1beta1_lease_list->api_version) == NULL) { goto fail; //String } } // v1beta1_lease_list->items if (!v1beta1_lease_list->items) { goto fail; } cJSON *items = cJSON_AddArrayToObject(item, "items"); if(items == NULL) { goto fail; //nonprimitive container } listEntry_t *itemsListEntry; if (v1beta1_lease_list->items) { list_ForEach(itemsListEntry, v1beta1_lease_list->items) { cJSON *itemLocal = v1beta1_lease_convertToJSON(itemsListEntry->data); if(itemLocal == NULL) { goto fail; } cJSON_AddItemToArray(items, itemLocal); } } // v1beta1_lease_list->kind if(v1beta1_lease_list->kind) { if(cJSON_AddStringToObject(item, "kind", v1beta1_lease_list->kind) == NULL) { goto fail; //String } } // v1beta1_lease_list->metadata if(v1beta1_lease_list->metadata) { cJSON *metadata_local_JSON = v1_list_meta_convertToJSON(v1beta1_lease_list->metadata); if(metadata_local_JSON == NULL) { goto fail; //model } cJSON_AddItemToObject(item, "metadata", metadata_local_JSON); if(item->child == NULL) { goto fail; } } return item; fail: if (item) { cJSON_Delete(item); } return NULL; } v1beta1_lease_list_t *v1beta1_lease_list_parseFromJSON(cJSON *v1beta1_lease_listJSON){ v1beta1_lease_list_t *v1beta1_lease_list_local_var = NULL; // v1beta1_lease_list->api_version cJSON *api_version = cJSON_GetObjectItemCaseSensitive(v1beta1_lease_listJSON, "apiVersion"); if (api_version) { if(!cJSON_IsString(api_version)) { goto end; //String } } // v1beta1_lease_list->items cJSON *items = cJSON_GetObjectItemCaseSensitive(v1beta1_lease_listJSON, "items"); if (!items) { goto end; } list_t *itemsList; cJSON *items_local_nonprimitive; if(!cJSON_IsArray(items)){ goto end; //nonprimitive container } itemsList = list_create(); cJSON_ArrayForEach(items_local_nonprimitive,items ) { if(!cJSON_IsObject(items_local_nonprimitive)){ goto end; } v1beta1_lease_t *itemsItem = v1beta1_lease_parseFromJSON(items_local_nonprimitive); list_addElement(itemsList, itemsItem); } // v1beta1_lease_list->kind cJSON *kind = cJSON_GetObjectItemCaseSensitive(v1beta1_lease_listJSON, "kind"); if (kind) { if(!cJSON_IsString(kind)) { goto end; //String } } // v1beta1_lease_list->metadata cJSON *metadata = cJSON_GetObjectItemCaseSensitive(v1beta1_lease_listJSON, "metadata"); v1_list_meta_t *metadata_local_nonprim = NULL; if (metadata) { metadata_local_nonprim = v1_list_meta_parseFromJSON(metadata); //nonprimitive } v1beta1_lease_list_local_var = v1beta1_lease_list_create ( api_version ? strdup(api_version->valuestring) : NULL, itemsList, kind ? strdup(kind->valuestring) : NULL, metadata ? metadata_local_nonprim : NULL ); return v1beta1_lease_list_local_var; end: if (metadata_local_nonprim) { v1_list_meta_free(metadata_local_nonprim); metadata_local_nonprim = NULL; } return NULL; }
229173.c
/** ****************************************************************************** * @file GPIO/GPIO_IOToggle/stm32f4xx_it.c * @author MCD Application Team * @version V1.8.0 * @date 04-November-2016 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2016 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 "stm32f4xx_it.h" /** @addtogroup STM32F4xx_StdPeriph_Examples * @{ */ /** @addtogroup GPIO_IOToggle * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f40xx.s/startup_stm32f427x.s/startup_stm32f429x.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
9052.c
/* $OpenLDAP$ */ /* This work is part of OpenLDAP Software <http://www.openldap.org/>. * * Copyright 1998-2018 The OpenLDAP Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ /* Portions Copyright (C) 1999, 2000 Novell, Inc. All Rights Reserved. * * THIS WORK IS SUBJECT TO U.S. AND INTERNATIONAL COPYRIGHT LAWS AND * TREATIES. USE, MODIFICATION, AND REDISTRIBUTION OF THIS WORK IS SUBJECT * TO VERSION 2.0.1 OF THE OPENLDAP PUBLIC LICENSE, A COPY OF WHICH IS * AVAILABLE AT HTTP://WWW.OPENLDAP.ORG/LICENSE.HTML OR IN THE FILE "LICENSE" * IN THE TOP-LEVEL DIRECTORY OF THE DISTRIBUTION. ANY USE OR EXPLOITATION * OF THIS WORK OTHER THAN AS AUTHORIZED IN VERSION 2.0.1 OF THE OPENLDAP * PUBLIC LICENSE, OR OTHER PRIOR WRITTEN CONSENT FROM NOVELL, COULD SUBJECT * THE PERPETRATOR TO CRIMINAL AND CIVIL LIABILITY. *--- * Note: A verbatim copy of version 2.0.1 of the OpenLDAP Public License * can be found in the file "build/LICENSE-2.0.1" in this distribution * of OpenLDAP Software. */ /* * UTF-8 Conversion Routines * * These routines convert between Wide Character and UTF-8, * or between MultiByte and UTF-8 encodings. * * Both single character and string versions of the functions are provided. * All functions return -1 if the character or string cannot be converted. */ #include "portable.h" #if SIZEOF_WCHAR_T >= 4 /* These routines assume ( sizeof(wchar_t) >= 4 ) */ #include <ac/stdlib.h> /* For wctomb, wcstombs, mbtowc, mbstowcs */ #include <ac/string.h> #include <ac/time.h> /* for time_t */ #include <ldap_utf8.h> #include <stdio.h> #include "ldap-int.h" static unsigned char mask[] = {0, 0x7f, 0x1f, 0x0f, 0x07, 0x03, 0x01}; /*----------------------------------------------------------------------------- UTF-8 Format Summary ASCII chars 7 bits 0xxxxxxx 2-character UTF-8 sequence: 11 bits 110xxxxx 10xxxxxx 3-character UTF-8 16 bits 1110xxxx 10xxxxxx 10xxxxxx 4-char UTF-8 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx 5-char UTF-8 26 bits 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 6-char UTF-8 31 bits 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx Unicode address space (0 - 0x10FFFF) 21 bits ISO-10646 address space (0 - 0x7FFFFFFF) 31 bits Note: This code does not prevent UTF-8 sequences which are longer than necessary from being decoded. */ /*----------------------------------------------------------------------------- Convert a UTF-8 character to a wide char. Return the length of the UTF-8 input character in bytes. */ int ldap_x_utf8_to_wc(wchar_t* wchar, const char* utf8char) { int utflen, i; wchar_t ch; if (utf8char == NULL) return -1; /* Get UTF-8 sequence length from 1st byte */ utflen = LDAP_UTF8_CHARLEN2(utf8char, utflen); if (utflen == 0 || utflen > (int)LDAP_MAX_UTF8_LEN) return -1; /* First byte minus length tag */ ch = (wchar_t)(utf8char[0] & mask[utflen]); for (i = 1; i < utflen; i++) { /* Subsequent bytes must start with 10 */ if ((utf8char[i] & 0xc0) != 0x80) return -1; ch <<= 6; /* 6 bits of data in each subsequent byte */ ch |= (wchar_t)(utf8char[i] & 0x3f); } if (wchar) *wchar = ch; return utflen; } /*----------------------------------------------------------------------------- Convert a UTF-8 string to a wide char string. No more than 'count' wide chars will be written to the output buffer. Return the size of the converted string in wide chars, excl null terminator. */ int ldap_x_utf8s_to_wcs(wchar_t* wcstr, const char* utf8str, size_t count) { size_t wclen = 0; int utflen, i; wchar_t ch; /* If input ptr is NULL or empty... */ if (utf8str == NULL || !*utf8str) { if (wcstr) *wcstr = 0; return 0; } /* Examine next UTF-8 character. If output buffer is NULL, ignore count */ while (*utf8str && (wcstr == NULL || wclen < count)) { /* Get UTF-8 sequence length from 1st byte */ utflen = LDAP_UTF8_CHARLEN2(utf8str, utflen); if (utflen == 0 || utflen > (int)LDAP_MAX_UTF8_LEN) return -1; /* First byte minus length tag */ ch = (wchar_t)(utf8str[0] & mask[utflen]); for (i = 1; i < utflen; i++) { /* Subsequent bytes must start with 10 */ if ((utf8str[i] & 0xc0) != 0x80) return -1; ch <<= 6; /* 6 bits of data in each subsequent byte */ ch |= (wchar_t)(utf8str[i] & 0x3f); } if (wcstr) wcstr[wclen] = ch; utf8str += utflen; /* Move to next UTF-8 character */ wclen++; /* Count number of wide chars stored/required */ } /* Add null terminator if there's room in the buffer. */ if (wcstr && wclen < count) wcstr[wclen] = 0; return wclen; } /*----------------------------------------------------------------------------- Convert one wide char to a UTF-8 character. Return the length of the converted UTF-8 character in bytes. No more than 'count' bytes will be written to the output buffer. */ int ldap_x_wc_to_utf8(char* utf8char, wchar_t wchar, size_t count) { int len = 0; if (utf8char == NULL) /* Just determine the required UTF-8 char length. */ { /* Ignore count */ if (wchar < 0) return -1; if (wchar < 0x80) return 1; if (wchar < 0x800) return 2; if (wchar < 0x10000) return 3; if (wchar < 0x200000) return 4; if (wchar < 0x4000000) return 5; #if SIZEOF_WCHAR_T > 4 /* UL is not strictly needed by ANSI C */ if (wchar < (wchar_t)0x80000000UL) #endif /* SIZEOF_WCHAR_T > 4 */ return 6; return -1; } if (wchar < 0) { /* Invalid wide character */ len = -1; } else if (wchar < 0x80) { if (count >= 1) { utf8char[len++] = (char)wchar; } } else if (wchar < 0x800) { if (count >= 2) { utf8char[len++] = 0xc0 | (wchar >> 6); utf8char[len++] = 0x80 | (wchar & 0x3f); } } else if (wchar < 0x10000) { if (count >= 3) { utf8char[len++] = 0xe0 | (wchar >> 12); utf8char[len++] = 0x80 | ((wchar >> 6) & 0x3f); utf8char[len++] = 0x80 | (wchar & 0x3f); } } else if (wchar < 0x200000) { if (count >= 4) { utf8char[len++] = 0xf0 | (wchar >> 18); utf8char[len++] = 0x80 | ((wchar >> 12) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 6) & 0x3f); utf8char[len++] = 0x80 | (wchar & 0x3f); } } else if (wchar < 0x4000000) { if (count >= 5) { utf8char[len++] = 0xf8 | (wchar >> 24); utf8char[len++] = 0x80 | ((wchar >> 18) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 12) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 6) & 0x3f); utf8char[len++] = 0x80 | (wchar & 0x3f); } } else #if SIZEOF_WCHAR_T > 4 /* UL is not strictly needed by ANSI C */ if (wchar < (wchar_t)0x80000000UL) #endif /* SIZEOF_WCHAR_T > 4 */ { if (count >= 6) { utf8char[len++] = 0xfc | (wchar >> 30); utf8char[len++] = 0x80 | ((wchar >> 24) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 18) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 12) & 0x3f); utf8char[len++] = 0x80 | ((wchar >> 6) & 0x3f); utf8char[len++] = 0x80 | (wchar & 0x3f); } #if SIZEOF_WCHAR_T > 4 } else { len = -1; #endif /* SIZEOF_WCHAR_T > 4 */ } return len; } /*----------------------------------------------------------------------------- Convert a wide char string to a UTF-8 string. No more than 'count' bytes will be written to the output buffer. Return the # of bytes written to the output buffer, excl null terminator. */ int ldap_x_wcs_to_utf8s(char* utf8str, const wchar_t* wcstr, size_t count) { int len = 0; int n; char* p = utf8str; wchar_t empty = 0; /* To avoid use of L"" construct */ if (wcstr == NULL) /* Treat input ptr NULL as an empty string */ wcstr = &empty; if (utf8str == NULL) /* Just compute size of output, excl null */ { while (*wcstr) { /* Get UTF-8 size of next wide char */ n = ldap_x_wc_to_utf8(NULL, *wcstr++, LDAP_MAX_UTF8_LEN); if (n == -1) return -1; len += n; } return len; } /* Do the actual conversion. */ n = 1; /* In case of empty wcstr */ while (*wcstr) { n = ldap_x_wc_to_utf8(p, *wcstr++, count); if (n <= 0) /* If encoding error (-1) or won't fit (0), quit */ break; p += n; count -= n; /* Space left in output buffer */ } /* If not enough room for last character, pad remainder with null so that return value = original count, indicating buffer full. */ if (n == 0) { while (count--) *p++ = 0; } /* Add a null terminator if there's room. */ else if (count) *p = 0; if (n == -1) /* Conversion encountered invalid wide char. */ return -1; /* Return the number of bytes written to output buffer, excl null. */ return (p - utf8str); } #ifdef ANDROID int wctomb(char* s, wchar_t wc) { return wcrtomb(s, wc, NULL); } int mbtowc(wchar_t* pwc, const char* s, size_t n) { return mbrtowc(pwc, s, n, NULL); } #endif /*----------------------------------------------------------------------------- Convert a UTF-8 character to a MultiByte character. Return the size of the converted character in bytes. */ int ldap_x_utf8_to_mb(char* mbchar, const char* utf8char, int (*f_wctomb)(char* mbchar, wchar_t wchar)) { wchar_t wchar; int n; char tmp[6]; /* Large enough for biggest multibyte char */ if (f_wctomb == NULL) /* If no conversion function was given... */ f_wctomb = wctomb; /* use the local ANSI C function */ /* First convert UTF-8 char to a wide char */ n = ldap_x_utf8_to_wc(&wchar, utf8char); if (n == -1) return -1; /* Invalid UTF-8 character */ if (mbchar == NULL) n = f_wctomb(tmp, wchar); else n = f_wctomb(mbchar, wchar); return n; } /*----------------------------------------------------------------------------- Convert a UTF-8 string to a MultiByte string. No more than 'count' bytes will be written to the output buffer. Return the size of the converted string in bytes, excl null terminator. */ int ldap_x_utf8s_to_mbs(char* mbstr, const char* utf8str, size_t count, size_t (*f_wcstombs)(char* mbstr, const wchar_t* wcstr, size_t count)) { wchar_t* wcs; size_t wcsize; int n; if (f_wcstombs == NULL) /* If no conversion function was given... */ f_wcstombs = wcstombs; /* use the local ANSI C function */ if (utf8str == NULL || *utf8str == 0) /* NULL or empty input string */ { if (mbstr) *mbstr = 0; return 0; } /* Allocate memory for the maximum size wchar string that we could get. */ wcsize = strlen(utf8str) + 1; wcs = (wchar_t*)LDAP_MALLOC(wcsize * sizeof(wchar_t)); if (wcs == NULL) return -1; /* Memory allocation failure. */ /* First convert the UTF-8 string to a wide char string */ n = ldap_x_utf8s_to_wcs(wcs, utf8str, wcsize); /* Then convert wide char string to multi-byte string */ if (n != -1) { n = f_wcstombs(mbstr, wcs, count); } LDAP_FREE(wcs); return n; } /*----------------------------------------------------------------------------- Convert a MultiByte character to a UTF-8 character. 'mbsize' indicates the number of bytes of 'mbchar' to check. Returns the number of bytes written to the output character. */ int ldap_x_mb_to_utf8(char* utf8char, const char* mbchar, size_t mbsize, int (*f_mbtowc)(wchar_t* wchar, const char* mbchar, size_t count)) { wchar_t wchar; int n; if (f_mbtowc == NULL) /* If no conversion function was given... */ f_mbtowc = mbtowc; /* use the local ANSI C function */ if (mbsize == 0) /* 0 is not valid. */ return -1; if (mbchar == NULL || *mbchar == 0) { if (utf8char) *utf8char = 0; return 1; } /* First convert the MB char to a Wide Char */ n = f_mbtowc(&wchar, mbchar, mbsize); if (n == -1) return -1; /* Convert the Wide Char to a UTF-8 character. */ n = ldap_x_wc_to_utf8(utf8char, wchar, LDAP_MAX_UTF8_LEN); return n; } /*----------------------------------------------------------------------------- Convert a MultiByte string to a UTF-8 string. No more than 'count' bytes will be written to the output buffer. Return the size of the converted string in bytes, excl null terminator. */ int ldap_x_mbs_to_utf8s(char* utf8str, const char* mbstr, size_t count, size_t (*f_mbstowcs)(wchar_t* wcstr, const char* mbstr, size_t count)) { wchar_t* wcs; int n; size_t wcsize; if (mbstr == NULL) /* Treat NULL input string as an empty string */ mbstr = ""; if (f_mbstowcs == NULL) /* If no conversion function was given... */ f_mbstowcs = mbstowcs; /* use the local ANSI C function */ /* Allocate memory for the maximum size wchar string that we could get. */ wcsize = strlen(mbstr) + 1; wcs = (wchar_t*)LDAP_MALLOC(wcsize * sizeof(wchar_t)); if (wcs == NULL) return -1; /* First convert multi-byte string to a wide char string */ n = f_mbstowcs(wcs, mbstr, wcsize); /* Convert wide char string to UTF-8 string */ if (n != -1) { n = ldap_x_wcs_to_utf8s(utf8str, wcs, count); } LDAP_FREE(wcs); return n; } #endif /* SIZEOF_WCHAR_T >= 4 */
875388.c
/* Copyright (C) 2002 M. Marques, A. Castro, A. Rubio, G. Bertsch, M. Oliveira This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. $Id$ */ #include <config.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <gsl/gsl_errno.h> #include <gsl/gsl_math.h> #include <gsl/gsl_min.h> #include <gsl/gsl_multimin.h> #include "string_f.h" /* A. First, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself and its gradient. */ /* This is a type used to communicate with Fortran; func_d is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func_d)(const int*, const double*, double*, const int*, double*); typedef struct{ func_d func; } param_fdf_t; /* Compute both f and df together. */ static void my_fdf (const gsl_vector *v, void *params, double *f, gsl_vector *df) { double *x, *gradient, ff2; int i, dim, getgrad; param_fdf_t * p; p = (param_fdf_t *) params; dim = v->size; x = (double *)malloc(dim*sizeof(double)); gradient = (double *)malloc(dim*sizeof(double)); for(i=0; i<dim; i++) x[i] = gsl_vector_get(v, i); getgrad = (df == NULL) ? 0 : 1; p->func(&dim, x, &ff2, &getgrad, gradient); if(f != NULL) *f = ff2; if(df != NULL){ for(i=0; i<dim; i++) gsl_vector_set(df, i, gradient[i]); } free(x); free(gradient); } static double my_f (const gsl_vector *v, void *params) { double val; my_fdf(v, params, &val, NULL); return val; } /* The gradient of f, df = (df/dx, df/dy). */ static void my_df (const gsl_vector *v, void *params, gsl_vector *df) { my_fdf(v, params, NULL, df); } typedef void (*print_f_ptr)(const int*, const int*, const double*, const double*, const double*, const double*); int FC_FUNC_(oct_minimize, OCT_MINIMIZE) (const int *method, const int *dim, double *point, const double *step, const double *line_tol, const double *tolgrad, const double *toldr, const int *maxiter, func_d f, const print_f_ptr write_info, double *minimum) { int iter = 0; int status; double maxgrad, maxdr; int i; double * oldpoint; double * grad; const gsl_multimin_fdfminimizer_type *T = NULL; gsl_multimin_fdfminimizer *s; gsl_vector *x; gsl_vector *absgrad, *absdr; gsl_multimin_function_fdf my_func; param_fdf_t p; p.func = f; oldpoint = (double *) malloc(*dim * sizeof(double)); grad = (double *) malloc(*dim * sizeof(double)); my_func.f = &my_f; my_func.df = &my_df; my_func.fdf = &my_fdf; my_func.n = *dim; my_func.params = (void *) &p; /* Starting point */ x = gsl_vector_alloc (*dim); for(i=0; i<*dim; i++) gsl_vector_set (x, i, point[i]); /* Allocate space for the gradient */ absgrad = gsl_vector_alloc (*dim); absdr = gsl_vector_alloc (*dim); //GSL recommends line_tol = 0.1; switch(*method){ case 1: T = gsl_multimin_fdfminimizer_steepest_descent; break; case 2: T = gsl_multimin_fdfminimizer_conjugate_fr; break; case 3: T = gsl_multimin_fdfminimizer_conjugate_pr; break; case 4: T = gsl_multimin_fdfminimizer_vector_bfgs; break; case 5: T = gsl_multimin_fdfminimizer_vector_bfgs2; break; } s = gsl_multimin_fdfminimizer_alloc (T, *dim); gsl_multimin_fdfminimizer_set (s, &my_func, x, *step, *line_tol); do { iter++; for(i=0; i<*dim; i++) oldpoint[i] = point[i]; /* Iterate */ status = gsl_multimin_fdfminimizer_iterate (s); /* Get current minimum, point and gradient */ *minimum = gsl_multimin_fdfminimizer_minimum(s); for(i=0; i<*dim; i++) point[i] = gsl_vector_get(gsl_multimin_fdfminimizer_x(s), i); for(i=0; i<*dim; i++) grad[i] = gsl_vector_get(gsl_multimin_fdfminimizer_gradient(s), i); /* Compute convergence criteria */ for(i=0; i<*dim; i++) gsl_vector_set(absdr, i, fabs(point[i]-oldpoint[i])); maxdr = gsl_vector_max(absdr); for(i=0; i<*dim; i++) gsl_vector_set(absgrad, i, fabs(grad[i])); maxgrad = gsl_vector_max(absgrad); /* Print information */ write_info(&iter, dim, minimum, &maxdr, &maxgrad, point); /* Store infomation for next iteration */ for(i=0; i<*dim; i++) oldpoint[i] = point[i]; if (status) break; if ( (maxgrad <= *tolgrad) || (maxdr <= *toldr) ) status = GSL_SUCCESS; else status = GSL_CONTINUE; } while (status == GSL_CONTINUE && iter <= *maxiter); if(status == GSL_CONTINUE) status = 1025; gsl_multimin_fdfminimizer_free (s); gsl_vector_free (x); gsl_vector_free(absgrad); gsl_vector_free(absdr); free(oldpoint); free(grad); return status; } /* B. Second, the interface to the gsl function that calculates the minimum of a one-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; func1 is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*func1)(const double*, double*); typedef struct{ func1 func; } param_f1_t; double fn1(double x, void * params) { param_f1_t * p = (param_f1_t* ) params; double fx; p->func(&x, &fx); return fx; } void FC_FUNC_(oct_1dminimize, OCT_1DMINIMIZE)(double *a, double *b, double *m, func1 f, int *status) { int iter = 0; int max_iter = 100; const gsl_min_fminimizer_type *T; gsl_min_fminimizer *s; gsl_function F; param_f1_t p; p.func = f; F.function = &fn1; F.params = (void *) &p; T = gsl_min_fminimizer_brent; s = gsl_min_fminimizer_alloc (T); *status = gsl_min_fminimizer_set (s, &F, *m, *a, *b); gsl_set_error_handler_off(); do { iter++; *status = gsl_min_fminimizer_iterate (s); *m = gsl_min_fminimizer_x_minimum (s); *a = gsl_min_fminimizer_x_lower (s); *b = gsl_min_fminimizer_x_upper (s); *status = gsl_min_test_interval (*a, *b, 0.00001, 0.0); /*if (*status == GSL_SUCCESS) printf ("Converged:\n");*/ /*printf ("%5d [%.7f, %.7f] %.7f \n", iter, *a, *b,*m);*/ } while (*status == GSL_CONTINUE && iter < max_iter); gsl_min_fminimizer_free(s); } /* C. Third, the interface to the gsl function that calculates the minimum of an N-dimensional function, with the knowledge of the function itself, but not its gradient. */ /* This is a type used to communicate with Fortran; funcn is the type of the interface to a Fortran subroutine that calculates the function and its gradient. */ typedef void (*funcn)(int*, double*, double*); typedef struct{ funcn func; } param_fn_t; double fn(const gsl_vector *v, void * params) { double val; double *x; int i, dim; param_fn_t * p; p = (param_fn_t *) params; dim = v->size; x = (double *)malloc(dim*sizeof(double)); for(i=0; i<dim; i++) x[i] = gsl_vector_get(v, i); p->func(&dim, x, &val); free(x); return val; } typedef void (*print_f_fn_ptr)(const int*, const int*, const double*, const double*, const double*); int FC_FUNC_(oct_minimize_direct, OCT_MINIMIZE_DIRECT) (const int *method, const int *dim, double *point, const double *step, const double *toldr, const int *maxiter, funcn f, const print_f_fn_ptr write_info, double *minimum) { int iter = 0, status, i; double size; const gsl_multimin_fminimizer_type *T = NULL; gsl_multimin_fminimizer *s = NULL; gsl_vector *x, *ss; gsl_multimin_function my_func; param_fn_t p; p.func = f; my_func.f = &fn; my_func.n = *dim; my_func.params = (void *) &p; /* Set the initial vertex size vector */ ss = gsl_vector_alloc (*dim); gsl_vector_set_all (ss, *step); /* Starting point */ x = gsl_vector_alloc (*dim); for(i=0; i<*dim; i++) gsl_vector_set (x, i, point[i]); switch(*method){ case 6: T = gsl_multimin_fminimizer_nmsimplex; break; } s = gsl_multimin_fminimizer_alloc (T, *dim); gsl_multimin_fminimizer_set (s, &my_func, x, ss); do { iter++; status = gsl_multimin_fminimizer_iterate(s); if(status) break; *minimum = gsl_multimin_fminimizer_minimum(s); for(i=0; i<*dim; i++) point[i] = gsl_vector_get(gsl_multimin_fminimizer_x(s), i); size = gsl_multimin_fminimizer_size (s); status = gsl_multimin_test_size (size, *toldr); write_info(&iter, dim, minimum, &size, point); } while (status == GSL_CONTINUE && iter < *maxiter); if(status == GSL_CONTINUE) status = 1025; gsl_vector_free(x); gsl_vector_free(ss); gsl_multimin_fminimizer_free(s); return status; }
97780.c
/********************************************************************* * Filename: sha256.c * Author: Brad Conte (brad AT bradconte.com) * Copyright: * Disclaimer: This code is presented "as is" without any guarantees. * Details: Implementation of the SHA-256 hashing algorithm. SHA-256 is one of the three algorithms in the SHA2 specification. The others, SHA-384 and SHA-512, are not offered in this implementation. Algorithm specification can be found here: * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf This implementation uses little endian byte order. *********************************************************************/ /*************************** HEADER FILES ***************************/ #include <stdlib.h> #include <memory.h> #include "sha256.h" /****************************** MACROS ******************************/ #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22)) #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25)) #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) /**************************** VARIABLES *****************************/ static const WORD32 k[64] = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 }; /*********************** FUNCTION DEFINITIONS ***********************/ void sha256_transform(SHA256_CTX *ctx, const BYTE data[]) { WORD32 a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; for (i = 0, j = 0; i < 16; ++i, j += 4) m[i] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | (data[j + 3]); for ( ; i < 64; ++i) m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3]; e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7]; for (i = 0; i < 64; ++i) { t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; t2 = EP0(a) + MAJ(a,b,c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c; ctx->state[3] += d; ctx->state[4] += e; ctx->state[5] += f; ctx->state[6] += g; ctx->state[7] += h; } void sha256_init(SHA256_CTX *ctx) { ctx->datalen = 0; ctx->bitlen = 0; ctx->state[0] = 0x6a09e667; ctx->state[1] = 0xbb67ae85; ctx->state[2] = 0x3c6ef372; ctx->state[3] = 0xa54ff53a; ctx->state[4] = 0x510e527f; ctx->state[5] = 0x9b05688c; ctx->state[6] = 0x1f83d9ab; ctx->state[7] = 0x5be0cd19; } void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len) { WORD32 i; for (i = 0; i < len; ++i) { ctx->data[ctx->datalen] = data[i]; ctx->datalen++; if (ctx->datalen == 64) { sha256_transform(ctx, ctx->data); ctx->bitlen += 512; ctx->datalen = 0; } } } void sha256_final(SHA256_CTX *ctx, BYTE hash[]) { WORD32 i; i = ctx->datalen; // Pad whatever data is left in the buffer. if (ctx->datalen < 56) { ctx->data[i++] = 0x80; while (i < 56) ctx->data[i++] = 0x00; } else { ctx->data[i++] = 0x80; while (i < 64) ctx->data[i++] = 0x00; sha256_transform(ctx, ctx->data); memset(ctx->data, 0, 56); } // Append to the padding the total message's length in bits and transform. ctx->bitlen += ctx->datalen * 8; ctx->data[63] = ctx->bitlen; ctx->data[62] = ctx->bitlen >> 8; ctx->data[61] = ctx->bitlen >> 16; ctx->data[60] = ctx->bitlen >> 24; ctx->data[59] = ctx->bitlen >> 32; ctx->data[58] = ctx->bitlen >> 40; ctx->data[57] = ctx->bitlen >> 48; ctx->data[56] = ctx->bitlen >> 56; sha256_transform(ctx, ctx->data); // Since this implementation uses little endian byte ordering and SHA uses big endian, // reverse all the bytes when copying the final state to the output hash. for (i = 0; i < 4; ++i) { hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; } }
681287.c
#define GRUB_TARGET_WORDSIZE 32 #define XX 32 #define grub_le_to_cpu_addr grub_le_to_cpu32 #define ehdrXX ehdr32 #define grub_xen_get_infoXX grub_xen_get_info32 #define FOR_ELF_PHDRS FOR_ELF32_PHDRS #include "xen_fileXX.c"
380952.c
/* Copyright (c) 2003-2004, Roger Dingledine * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2018, The Tor Project, Inc. */ /* See LICENSE for licensing information */ #include "orconfig.h" #include "lib/process/restrict.h" #include "lib/intmath/cmp.h" #include "lib/log/torlog.h" #include "lib/log/util_bug.h" #include "lib/net/socket.h" #ifdef HAVE_SYS_MMAN_H #include <sys/mman.h> #endif #include <errno.h> #include <stdlib.h> #include <string.h> /* We only use the linux prctl for now. There is no Win32 support; this may * also work on various BSD systems and Mac OS X - send testing feedback! * * On recent Gnu/Linux kernels it is possible to create a system-wide policy * that will prevent non-root processes from attaching to other processes * unless they are the parent process; thus gdb can attach to programs that * they execute but they cannot attach to other processes running as the same * user. The system wide policy may be set with the sysctl * kernel.yama.ptrace_scope or by inspecting * /proc/sys/kernel/yama/ptrace_scope and it is 1 by default on Ubuntu 11.04. * * This ptrace scope will be ignored on Gnu/Linux for users with * CAP_SYS_PTRACE and so it is very likely that root will still be able to * attach to the Tor process. */ /** Attempt to disable debugger attachment: return 1 on success, -1 on * failure, and 0 if we don't know how to try on this platform. */ int tor_disable_debugger_attach(void) { int r = -1; log_debug(LD_CONFIG, "Attemping to disable debugger attachment to Tor for " "unprivileged users."); #if defined(__linux__) && defined(HAVE_SYS_PRCTL_H) \ && defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) #define TRIED_TO_DISABLE r = prctl(PR_SET_DUMPABLE, 0); #elif defined(__APPLE__) && defined(PT_DENY_ATTACH) #define TRIED_TO_ATTACH r = ptrace(PT_DENY_ATTACH, 0, 0, 0); #endif /* defined(__linux__) && defined(HAVE_SYS_PRCTL_H) ... || ... */ // XXX: TODO - Mac OS X has dtrace and this may be disabled. // XXX: TODO - Windows probably has something similar #ifdef TRIED_TO_DISABLE if (r == 0) { log_debug(LD_CONFIG,"Debugger attachment disabled for " "unprivileged users."); return 1; } else { log_warn(LD_CONFIG, "Unable to disable debugger attaching: %s", strerror(errno)); } #endif /* defined(TRIED_TO_DISABLE) */ #undef TRIED_TO_DISABLE return r; } #if defined(HAVE_MLOCKALL) && HAVE_DECL_MLOCKALL && defined(RLIMIT_MEMLOCK) #define HAVE_UNIX_MLOCKALL #endif #ifdef HAVE_UNIX_MLOCKALL /** Attempt to raise the current and max rlimit to infinity for our process. * This only needs to be done once and can probably only be done when we have * not already dropped privileges. */ static int tor_set_max_memlock(void) { /* Future consideration for Windows is probably SetProcessWorkingSetSize * This is similar to setting the memory rlimit of RLIMIT_MEMLOCK * http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx */ struct rlimit limit; /* RLIM_INFINITY is -1 on some platforms. */ limit.rlim_cur = RLIM_INFINITY; limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_MEMLOCK, &limit) == -1) { if (errno == EPERM) { log_warn(LD_GENERAL, "You appear to lack permissions to change memory " "limits. Are you root?"); } log_warn(LD_GENERAL, "Unable to raise RLIMIT_MEMLOCK: %s", strerror(errno)); return -1; } return 0; } #endif /* defined(HAVE_UNIX_MLOCKALL) */ /** Attempt to lock all current and all future memory pages. * This should only be called once and while we're privileged. * Like mlockall() we return 0 when we're successful and -1 when we're not. * Unlike mlockall() we return 1 if we've already attempted to lock memory. */ int tor_mlockall(void) { static int memory_lock_attempted = 0; if (memory_lock_attempted) { return 1; } memory_lock_attempted = 1; /* * Future consideration for Windows may be VirtualLock * VirtualLock appears to implement mlock() but not mlockall() * * http://msdn.microsoft.com/en-us/library/aa366895(VS.85).aspx */ #ifdef HAVE_UNIX_MLOCKALL if (tor_set_max_memlock() == 0) { log_debug(LD_GENERAL, "RLIMIT_MEMLOCK is now set to RLIM_INFINITY."); } if (mlockall(MCL_CURRENT|MCL_FUTURE) == 0) { log_info(LD_GENERAL, "Insecure OS paging is effectively disabled."); return 0; } else { if (errno == ENOSYS) { /* Apple - it's 2009! I'm looking at you. Grrr. */ log_notice(LD_GENERAL, "It appears that mlockall() is not available on " "your platform."); } else if (errno == EPERM) { log_notice(LD_GENERAL, "It appears that you lack the permissions to " "lock memory. Are you root?"); } log_notice(LD_GENERAL, "Unable to lock all current and future memory " "pages: %s", strerror(errno)); return -1; } #else /* !(defined(HAVE_UNIX_MLOCKALL)) */ log_warn(LD_GENERAL, "Unable to lock memory pages. mlockall() unsupported?"); return -1; #endif /* defined(HAVE_UNIX_MLOCKALL) */ } /** Number of extra file descriptors to keep in reserve beyond those that we * tell Tor it's allowed to use. */ #define ULIMIT_BUFFER 32 /* keep 32 extra fd's beyond ConnLimit_ */ /** Learn the maximum allowed number of file descriptors, and tell the * system we want to use up to that number. (Some systems have a low soft * limit, and let us set it higher.) We compute this by finding the largest * number that we can use. * * If the limit is below the reserved file descriptor value (ULIMIT_BUFFER), * return -1 and <b>max_out</b> is untouched. * * If we can't find a number greater than or equal to <b>limit</b>, then we * fail by returning -1 and <b>max_out</b> is untouched. * * If we are unable to set the limit value because of setrlimit() failing, * return 0 and <b>max_out</b> is set to the current maximum value returned * by getrlimit(). * * Otherwise, return 0 and store the maximum we found inside <b>max_out</b> * and set <b>max_sockets</b> with that value as well.*/ int set_max_file_descriptors(rlim_t limit, int *max_out) { if (limit < ULIMIT_BUFFER) { log_warn(LD_CONFIG, "ConnLimit must be at least %d. Failing.", ULIMIT_BUFFER); return -1; } /* Define some maximum connections values for systems where we cannot * automatically determine a limit. Re Cygwin, see * http://archives.seul.org/or/talk/Aug-2006/msg00210.html * For an iPhone, 9999 should work. For Windows and all other unknown * systems we use 15000 as the default. */ #ifndef HAVE_GETRLIMIT #if defined(CYGWIN) || defined(__CYGWIN__) const char *platform = "Cygwin"; const unsigned long MAX_CONNECTIONS = 3200; #elif defined(_WIN32) const char *platform = "Windows"; const unsigned long MAX_CONNECTIONS = 15000; #else const char *platform = "unknown platforms with no getrlimit()"; const unsigned long MAX_CONNECTIONS = 15000; #endif /* defined(CYGWIN) || defined(__CYGWIN__) || ... */ log_fn(LOG_INFO, LD_NET, "This platform is missing getrlimit(). Proceeding."); if (limit > MAX_CONNECTIONS) { log_warn(LD_CONFIG, "We do not support more than %lu file descriptors " "on %s. Tried to raise to %lu.", (unsigned long)MAX_CONNECTIONS, platform, (unsigned long)limit); return -1; } limit = MAX_CONNECTIONS; #else /* !(!defined(HAVE_GETRLIMIT)) */ struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { log_warn(LD_NET, "Could not get maximum number of file descriptors: %s", strerror(errno)); return -1; } if (rlim.rlim_max < limit) { log_warn(LD_CONFIG,"We need %lu file descriptors available, and we're " "limited to %lu. Please change your ulimit -n.", (unsigned long)limit, (unsigned long)rlim.rlim_max); return -1; } if (rlim.rlim_max > rlim.rlim_cur) { log_info(LD_NET,"Raising max file descriptors from %lu to %lu.", (unsigned long)rlim.rlim_cur, (unsigned long)rlim.rlim_max); } /* Set the current limit value so if the attempt to set the limit to the * max fails at least we'll have a valid value of maximum sockets. */ *max_out = (int)rlim.rlim_cur - ULIMIT_BUFFER; set_max_sockets(*max_out); rlim.rlim_cur = rlim.rlim_max; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { int couldnt_set = 1; const int setrlimit_errno = errno; #ifdef OPEN_MAX uint64_t try_limit = OPEN_MAX - ULIMIT_BUFFER; if (errno == EINVAL && try_limit < (uint64_t) rlim.rlim_cur) { /* On some platforms, OPEN_MAX is the real limit, and getrlimit() is * full of nasty lies. I'm looking at you, OSX 10.5.... */ rlim.rlim_cur = MIN((rlim_t) try_limit, rlim.rlim_cur); if (setrlimit(RLIMIT_NOFILE, &rlim) == 0) { if (rlim.rlim_cur < (rlim_t)limit) { log_warn(LD_CONFIG, "We are limited to %lu file descriptors by " "OPEN_MAX (%lu), and ConnLimit is %lu. Changing " "ConnLimit; sorry.", (unsigned long)try_limit, (unsigned long)OPEN_MAX, (unsigned long)limit); } else { log_info(LD_CONFIG, "Dropped connection limit to %lu based on " "OPEN_MAX (%lu); Apparently, %lu was too high and rlimit " "lied to us.", (unsigned long)try_limit, (unsigned long)OPEN_MAX, (unsigned long)rlim.rlim_max); } couldnt_set = 0; } } #endif /* defined(OPEN_MAX) */ if (couldnt_set) { log_warn(LD_CONFIG,"Couldn't set maximum number of file descriptors: %s", strerror(setrlimit_errno)); } } /* leave some overhead for logs, etc, */ limit = rlim.rlim_cur; #endif /* !defined(HAVE_GETRLIMIT) */ if (limit > INT_MAX) limit = INT_MAX; tor_assert(max_out); *max_out = (int)limit - ULIMIT_BUFFER; set_max_sockets(*max_out); return 0; }
992525.c
#include "genfun.h" #include "genname.h" #include "gencall.h" #include "gentrace.h" #include "gencontrol.h" #include "genexpr.h" #include "genreference.h" #include "../pass/names.h" #include "../type/assemble.h" #include "../type/subtype.h" #include "../type/reify.h" #include "../type/lookup.h" #include "../../libponyrt/ds/fun.h" #include "../../libponyrt/mem/pool.h" #include "../../libponyrt/mem/heap.h" #include "ponyassert.h" #include <string.h> static void compile_method_free(void* p) { POOL_FREE(compile_method_t, p); } static void name_param(compile_t* c, reach_type_t* t, reach_method_t* m, LLVMValueRef func, const char* name, unsigned index, size_t line, size_t pos) { compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; LLVMValueRef value = LLVMGetParam(func, index); LLVMSetValueName(value, name); LLVMValueRef alloc = LLVMBuildAlloca(c->builder, c_t->mem_type, name); value = gen_assign_cast(c, c_t->mem_type, value, t->ast_cap); LLVMBuildStore(c->builder, value, alloc); codegen_setlocal(c, name, alloc); LLVMMetadataRef info; if(index == 0) { info = LLVMDIBuilderCreateArtificialVariable(c->di, c_m->di_method, name, index + 1, c_m->di_file, (unsigned)ast_line(m->fun->ast), c_t->di_type); } else { #if PONY_LLVM >= 700 info = LLVMDIBuilderCreateParameterVariable(c->di, c_m->di_method, name, strlen(name), index + 1, c_m->di_file, (unsigned)ast_line(m->fun->ast), c_t->di_type, false, LLVMDIFlagZero); #else info = LLVMDIBuilderCreateParameterVariable(c->di, c_m->di_method, name, index + 1, c_m->di_file, (unsigned)ast_line(m->fun->ast), c_t->di_type); #endif } LLVMMetadataRef expr = LLVMDIBuilderCreateExpression(c->di, NULL, 0); LLVMDIBuilderInsertDeclare(c->di, alloc, info, expr, (unsigned)line, (unsigned)pos, c_m->di_method, LLVMGetInsertBlock(c->builder)); } static void name_params(compile_t* c, reach_type_t* t, reach_method_t* m, LLVMValueRef func) { unsigned offset = 0; if(m->cap != TK_AT) { // Name the receiver 'this'. name_param(c, t, m, func, c->str_this, 0, ast_line(m->fun->ast), ast_pos(m->fun->ast)); offset = 1; } ast_t* params = ast_childidx(m->fun->ast, 3); ast_t* param = ast_child(params); // Name each parameter. for(size_t i = 0; i < m->param_count; i++) { reach_param_t* r_param = &m->params[i]; name_param(c, r_param->type, m, func, r_param->name, (unsigned)i + offset, ast_line(param), ast_pos(param)); param = ast_sibling(param); } } static void make_signature(compile_t* c, reach_type_t* t, reach_method_name_t* n, reach_method_t* m, bool message_type) { // Count the parameters, including the receiver if the method isn't bare. size_t count = m->param_count; size_t offset = 0; if(m->cap != TK_AT) { count++; offset++; } size_t tparam_size = count * sizeof(LLVMTypeRef); if(message_type) tparam_size += tparam_size + (2 * sizeof(LLVMTypeRef)); LLVMTypeRef* tparams = (LLVMTypeRef*)ponyint_pool_alloc_size(tparam_size); LLVMTypeRef* mparams = NULL; if(message_type) mparams = &tparams[count]; bool bare_void = false; compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; if(m->cap == TK_AT) { bare_void = is_none(m->result->ast); } else { // Get a type for the receiver. tparams[0] = c_t->use_type; } // Get a type for each parameter. for(size_t i = 0; i < m->param_count; i++) { compile_type_t* p_c_t = (compile_type_t*)m->params[i].type->c_type; tparams[i + offset] = p_c_t->use_type; if(message_type) mparams[i + offset + 2] = p_c_t->mem_type; } // Generate the function type. // Bare methods returning None return void to maintain compatibility with C. // Class constructors return void to avoid clobbering nocapture information. if(bare_void || (n->name == c->str__final) || ((ast_id(m->fun->ast) == TK_NEW) && (t->underlying == TK_CLASS))) c_m->func_type = LLVMFunctionType(c->void_type, tparams, (int)count, false); else c_m->func_type = LLVMFunctionType( ((compile_type_t*)m->result->c_type)->use_type, tparams, (int)count, false); if(message_type) { mparams[0] = c->i32; mparams[1] = c->i32; mparams[2] = c->void_ptr; c_m->msg_type = LLVMStructTypeInContext(c->context, mparams, (int)count + 2, false); } ponyint_pool_free_size(tparam_size, tparams); } static void make_function_debug(compile_t* c, reach_type_t* t, reach_method_t* m, LLVMValueRef func) { // Count the parameters, including the receiver and the result. size_t count = m->param_count + 1; size_t offset = 1; if(m->cap != TK_AT) { count++; offset++; } size_t md_size = count * sizeof(reach_type_t*); LLVMMetadataRef* md = (LLVMMetadataRef*)ponyint_pool_alloc_size(md_size); compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; md[0] = ((compile_type_t*)m->result->c_type)->di_type; if(m->cap != TK_AT) md[1] = c_t->di_type; for(size_t i = 0; i < m->param_count; i++) md[i + offset] = ((compile_type_t*)m->params[i].type->c_type)->di_type; c_m->di_file = c_t->di_file; #if PONY_LLVM >= 700 LLVMMetadataRef subroutine = LLVMDIBuilderCreateSubroutineType(c->di, c_m->di_file, md, (unsigned int)count, LLVMDIFlagZero); #else LLVMMetadataRef type_array = LLVMDIBuilderGetOrCreateTypeArray(c->di, md, count); LLVMMetadataRef subroutine = LLVMDIBuilderCreateSubroutineType(c->di, c_m->di_file, type_array); #endif LLVMMetadataRef scope; if(c_t->di_type_embed != NULL) scope = c_t->di_type_embed; else scope = c_t->di_type; #ifdef _MSC_VER // CodeView on Windows doesn't like "non-class" methods if (c_t->primitive != NULL) { scope = LLVMDIBuilderCreateNamespace(c->di, c->di_unit, t->name, c_t->di_file, (unsigned)ast_line(t->ast)); } #endif ast_t* id = ast_childidx(m->fun->ast, 1); c_m->di_method = LLVMDIBuilderCreateMethod(c->di, scope, ast_name(id), m->full_name, c_m->di_file, (unsigned)ast_line(m->fun->ast), subroutine, func, c->opt->release); ponyint_pool_free_size(md_size, md); } static void make_prototype(compile_t* c, reach_type_t* t, reach_method_name_t* n, reach_method_t* m) { if(m->intrinsic) return; // Behaviours and actor constructors also have handler functions. bool handler = false; bool is_trait = false; switch(ast_id(m->fun->ast)) { case TK_NEW: handler = t->underlying == TK_ACTOR; break; case TK_BE: handler = true; break; default: {} } switch(t->underlying) { case TK_PRIMITIVE: case TK_STRUCT: case TK_CLASS: case TK_ACTOR: break; case TK_UNIONTYPE: case TK_ISECTTYPE: case TK_INTERFACE: case TK_TRAIT: is_trait = true; break; default: pony_assert(0); return; } make_signature(c, t, n, m, handler || is_trait); if(is_trait) return; compile_method_t* c_m = (compile_method_t*)m->c_method; if(!handler) { // Generate the function prototype. c_m->func = codegen_addfun(c, m->full_name, c_m->func_type, true); genfun_param_attrs(c, t, m, c_m->func); make_function_debug(c, t, m, c_m->func); } else { size_t count = LLVMCountParamTypes(c_m->func_type); size_t buf_size = count * sizeof(LLVMTypeRef); LLVMTypeRef* tparams = (LLVMTypeRef*)ponyint_pool_alloc_size(buf_size); LLVMGetParamTypes(c_m->func_type, tparams); // Generate the sender prototype. const char* sender_name = genname_be(m->full_name); c_m->func = codegen_addfun(c, sender_name, c_m->func_type, true); genfun_param_attrs(c, t, m, c_m->func); // If the method is a forwarding mangling, we don't need the handler. if(!m->forwarding) { // Change the return type to void for the handler. LLVMTypeRef handler_type = LLVMFunctionType(c->void_type, tparams, (int)count, false); // Generate the handler prototype. c_m->func_handler = codegen_addfun(c, m->full_name, handler_type, true); genfun_param_attrs(c, t, m, c_m->func_handler); make_function_debug(c, t, m, c_m->func_handler); } ponyint_pool_free_size(buf_size, tparams); } compile_type_t* c_t = (compile_type_t*)t->c_type; if(n->name == c->str__final) { // Store the finaliser and use the C calling convention and an external // linkage. pony_assert(c_t->final_fn == NULL); c_t->final_fn = c_m->func; LLVMSetFunctionCallConv(c_m->func, LLVMCCallConv); LLVMSetLinkage(c_m->func, LLVMExternalLinkage); } else if(n->name == c->str__serialise_space) { c_t->custom_serialise_space_fn = c_m->func; LLVMSetFunctionCallConv(c_m->func, LLVMCCallConv); LLVMSetLinkage(c_m->func, LLVMExternalLinkage); } else if(n->name == c->str__serialise) { c_t->custom_serialise_fn = c_m->func; } else if(n->name == c->str__deserialise) { c_t->custom_deserialise_fn = c_m->func; LLVMSetFunctionCallConv(c_m->func, LLVMCCallConv); LLVMSetLinkage(c_m->func, LLVMExternalLinkage); } if(n->cap == TK_AT) { LLVMSetFunctionCallConv(c_m->func, LLVMCCallConv); LLVMSetLinkage(c_m->func, LLVMExternalLinkage); LLVMSetUnnamedAddr(c_m->func, false); if(t->bare_method == m) { pony_assert(c_t->instance == NULL); c_t->instance = LLVMConstBitCast(c_m->func, c->void_ptr); } } } static void add_dispatch_case(compile_t* c, reach_type_t* t, reach_param_t* params, uint32_t index, LLVMValueRef handler, LLVMTypeRef fun_type, LLVMTypeRef msg_type) { // Add a case to the dispatch function to handle this message. compile_type_t* c_t = (compile_type_t*)t->c_type; codegen_startfun(c, c_t->dispatch_fn, NULL, NULL, NULL, false); LLVMBasicBlockRef block = codegen_block(c, "handler"); LLVMValueRef id = LLVMConstInt(c->i32, index, false); LLVMAddCase(c_t->dispatch_switch, id, block); // Destructure the message. LLVMPositionBuilderAtEnd(c->builder, block); LLVMValueRef ctx = LLVMGetParam(c_t->dispatch_fn, 0); LLVMValueRef this_ptr = LLVMGetParam(c_t->dispatch_fn, 1); LLVMValueRef msg = LLVMBuildBitCast(c->builder, LLVMGetParam(c_t->dispatch_fn, 2), msg_type, ""); size_t count = LLVMCountParamTypes(fun_type); size_t params_buf_size = count * sizeof(LLVMTypeRef); LLVMTypeRef* param_types = (LLVMTypeRef*)ponyint_pool_alloc_size(params_buf_size); LLVMGetParamTypes(fun_type, param_types); size_t args_buf_size = count * sizeof(LLVMValueRef); LLVMValueRef* args = (LLVMValueRef*)ponyint_pool_alloc_size(args_buf_size); args[0] = LLVMBuildBitCast(c->builder, this_ptr, c_t->use_type, ""); for(int i = 1; i < (int)count; i++) { LLVMValueRef field = LLVMBuildStructGEP(c->builder, msg, i + 2, ""); args[i] = LLVMBuildLoad(c->builder, field, ""); args[i] = gen_assign_cast(c, param_types[i], args[i], params[i - 1].type->ast_cap); } // Trace the message. bool need_trace = false; for(size_t i = 0; i < count - 1; i++) { if(gentrace_needed(c, params[i].ast, params[i].ast)) { need_trace = true; break; } } if(need_trace) { gencall_runtime(c, "pony_gc_recv", &ctx, 1, ""); for(size_t i = 1; i < count; i++) gentrace(c, ctx, args[i], args[i], params[i - 1].ast, params[i - 1].ast); gencall_runtime(c, "pony_recv_done", &ctx, 1, ""); } // Call the handler. codegen_call(c, handler, args, count, true); LLVMBuildRetVoid(c->builder); codegen_finishfun(c); ponyint_pool_free_size(args_buf_size, args); ponyint_pool_free_size(params_buf_size, param_types); } static void call_embed_finalisers(compile_t* c, reach_type_t* t, ast_t* call_location, LLVMValueRef obj) { uint32_t base = 0; if(t->underlying != TK_STRUCT) base++; if(t->underlying == TK_ACTOR) base++; for(uint32_t i = 0; i < t->field_count; i++) { reach_field_t* field = &t->fields[i]; if(!field->embed) continue; LLVMValueRef final_fn = ((compile_type_t*)field->type->c_type)->final_fn; if(final_fn == NULL) continue; LLVMValueRef field_ref = LLVMBuildStructGEP(c->builder, obj, base + i, ""); codegen_debugloc(c, call_location); LLVMBuildCall(c->builder, final_fn, &field_ref, 1, ""); codegen_debugloc(c, NULL); } } static bool genfun_fun(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; pony_assert(c_m->func != NULL); AST_GET_CHILDREN(m->fun->ast, cap, id, typeparams, params, result, can_error, body); codegen_startfun(c, c_m->func, c_m->di_file, c_m->di_method, m->fun, ast_id(cap) == TK_AT); name_params(c, t, m, c_m->func); bool finaliser = c_m->func == c_t->final_fn; if(finaliser) call_embed_finalisers(c, t, body, gen_this(c, NULL)); LLVMValueRef value = gen_expr(c, body); if(value == NULL) return false; if(value != GEN_NOVALUE) { ast_t* r_result = deferred_reify(m->fun, result, c->opt); if(finaliser || ((ast_id(cap) == TK_AT) && is_none(r_result))) { ast_free_unattached(r_result); codegen_scope_lifetime_end(c); codegen_debugloc(c, ast_childlast(body)); LLVMBuildRetVoid(c->builder); } else { LLVMTypeRef f_type = LLVMGetElementType(LLVMTypeOf(c_m->func)); LLVMTypeRef r_type = LLVMGetReturnType(f_type); ast_t* body_type = deferred_reify(m->fun, ast_type(body), c->opt); LLVMValueRef ret = gen_assign_cast(c, r_type, value, body_type); ast_free_unattached(body_type); ast_free_unattached(r_result); if(ret == NULL) return false; codegen_scope_lifetime_end(c); codegen_debugloc(c, ast_childlast(body)); LLVMBuildRet(c->builder, ret); } codegen_debugloc(c, NULL); } codegen_finishfun(c); return true; } static bool genfun_be(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_method_t* c_m = (compile_method_t*)m->c_method; pony_assert(c_m->func != NULL); pony_assert(c_m->func_handler != NULL); AST_GET_CHILDREN(m->fun->ast, cap, id, typeparams, params, result, can_error, body); // Generate the handler. codegen_startfun(c, c_m->func_handler, c_m->di_file, c_m->di_method, m->fun, false); name_params(c, t, m, c_m->func_handler); LLVMValueRef value = gen_expr(c, body); if(value == NULL) return false; codegen_scope_lifetime_end(c); if(value != GEN_NOVALUE) LLVMBuildRetVoid(c->builder); codegen_finishfun(c); // Generate the sender. codegen_startfun(c, c_m->func, NULL, NULL, m->fun, false); size_t buf_size = (m->param_count + 1) * sizeof(LLVMValueRef); LLVMValueRef* param_vals = (LLVMValueRef*)ponyint_pool_alloc_size(buf_size); LLVMGetParams(c_m->func, param_vals); // Send the arguments in a message to 'this'. gen_send_message(c, m, param_vals, params); // Return None. LLVMBuildRet(c->builder, c->none_instance); codegen_finishfun(c); ponyint_pool_free_size(buf_size, param_vals); // Add the dispatch case. LLVMTypeRef msg_type_ptr = LLVMPointerType(c_m->msg_type, 0); add_dispatch_case(c, t, m->params, m->vtable_index, c_m->func_handler, c_m->func_type, msg_type_ptr); return true; } static bool genfun_new(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; pony_assert(c_m->func != NULL); AST_GET_CHILDREN(m->fun->ast, cap, id, typeparams, params, result, can_error, body); codegen_startfun(c, c_m->func, c_m->di_file, c_m->di_method, m->fun, false); name_params(c, t, m, c_m->func); LLVMValueRef value = gen_expr(c, body); if(value == NULL) return false; // Return 'this'. if(c_t->primitive == NULL) value = LLVMGetParam(c_m->func, 0); codegen_scope_lifetime_end(c); codegen_debugloc(c, ast_childlast(body)); if(t->underlying == TK_CLASS) LLVMBuildRetVoid(c->builder); else LLVMBuildRet(c->builder, value); codegen_debugloc(c, NULL); codegen_finishfun(c); return true; } static bool genfun_newbe(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_method_t* c_m = (compile_method_t*)m->c_method; pony_assert(c_m->func != NULL); pony_assert(c_m->func_handler != NULL); AST_GET_CHILDREN(m->fun->ast, cap, id, typeparams, params, result, can_error, body); // Generate the handler. codegen_startfun(c, c_m->func_handler, c_m->di_file, c_m->di_method, m->fun, false); name_params(c, t, m, c_m->func_handler); LLVMValueRef value = gen_expr(c, body); if(value == NULL) return false; codegen_scope_lifetime_end(c); LLVMBuildRetVoid(c->builder); codegen_finishfun(c); // Generate the sender. codegen_startfun(c, c_m->func, NULL, NULL, m->fun, false); size_t buf_size = (m->param_count + 1) * sizeof(LLVMValueRef); LLVMValueRef* param_vals = (LLVMValueRef*)ponyint_pool_alloc_size(buf_size); LLVMGetParams(c_m->func, param_vals); // Send the arguments in a message to 'this'. gen_send_message(c, m, param_vals, params); // Return 'this'. LLVMBuildRet(c->builder, param_vals[0]); codegen_finishfun(c); ponyint_pool_free_size(buf_size, param_vals); // Add the dispatch case. LLVMTypeRef msg_type_ptr = LLVMPointerType(c_m->msg_type, 0); add_dispatch_case(c, t, m->params, m->vtable_index, c_m->func_handler, c_m->func_type, msg_type_ptr); return true; } static void copy_subordinate(reach_method_t* m) { compile_method_t* c_m = (compile_method_t*)m->c_method; reach_method_t* m2 = m->subordinate; while(m2 != NULL) { compile_method_t* c_m2 = (compile_method_t*)m2->c_method; c_m2->func_type = c_m->func_type; c_m2->func = c_m->func; m2 = m2->subordinate; } } static void genfun_implicit_final_prototype(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; c_m->func_type = LLVMFunctionType(c->void_type, &c_t->use_type, 1, false); c_m->func = codegen_addfun(c, m->full_name, c_m->func_type, true); c_t->final_fn = c_m->func; LLVMSetFunctionCallConv(c_m->func, LLVMCCallConv); LLVMSetLinkage(c_m->func, LLVMExternalLinkage); } static bool genfun_implicit_final(compile_t* c, reach_type_t* t, reach_method_t* m) { compile_method_t* c_m = (compile_method_t*)m->c_method; codegen_startfun(c, c_m->func, NULL, NULL, NULL, false); call_embed_finalisers(c, t, NULL, gen_this(c, NULL)); LLVMBuildRetVoid(c->builder); codegen_finishfun(c); return true; } static bool genfun_allocator(compile_t* c, reach_type_t* t) { switch(t->underlying) { case TK_PRIMITIVE: case TK_STRUCT: case TK_CLASS: case TK_ACTOR: break; default: return true; } compile_type_t* c_t = (compile_type_t*)t->c_type; // No allocator for machine word types or pointers. if((c_t->primitive != NULL) || is_pointer(t->ast) || is_nullable_pointer(t->ast)) return true; const char* funname = genname_alloc(t->name); LLVMTypeRef ftype = LLVMFunctionType(c_t->use_type, NULL, 0, false); LLVMValueRef fun = codegen_addfun(c, funname, ftype, true); if(t->underlying != TK_PRIMITIVE) { LLVMTypeRef elem = LLVMGetElementType(c_t->use_type); size_t size = (size_t)LLVMABISizeOfType(c->target_data, elem); LLVM_DECLARE_ATTRIBUTEREF(noalias_attr, noalias, 0); LLVM_DECLARE_ATTRIBUTEREF(deref_attr, dereferenceable, size); LLVM_DECLARE_ATTRIBUTEREF(align_attr, align, HEAP_MIN); LLVMAddAttributeAtIndex(fun, LLVMAttributeReturnIndex, noalias_attr); LLVMAddAttributeAtIndex(fun, LLVMAttributeReturnIndex, deref_attr); LLVMAddAttributeAtIndex(fun, LLVMAttributeReturnIndex, align_attr); } codegen_startfun(c, fun, NULL, NULL, NULL, false); LLVMValueRef result; switch(t->underlying) { case TK_PRIMITIVE: case TK_STRUCT: case TK_CLASS: // Allocate the object or return the global instance. result = gencall_alloc(c, t, NULL); break; case TK_ACTOR: // Allocate the actor. result = gencall_create(c, t, NULL); break; default: pony_assert(0); return false; } LLVMBuildRet(c->builder, result); codegen_finishfun(c); return true; } static bool genfun_forward(compile_t* c, reach_type_t* t, reach_method_name_t* n, reach_method_t* m) { compile_method_t* c_m = (compile_method_t*)m->c_method; pony_assert(c_m->func != NULL); reach_method_t* m2 = reach_method(t, m->cap, n->name, m->typeargs); pony_assert(m2 != NULL); pony_assert(m2 != m); compile_method_t* c_m2 = (compile_method_t*)m2->c_method; codegen_startfun(c, c_m->func, c_m->di_file, c_m->di_method, m->fun, m->cap == TK_AT); int count = LLVMCountParams(c_m->func); size_t buf_size = count * sizeof(LLVMValueRef); LLVMValueRef* args = (LLVMValueRef*)ponyint_pool_alloc_size(buf_size); args[0] = LLVMGetParam(c_m->func, 0); for(int i = 1; i < count; i++) { LLVMValueRef value = LLVMGetParam(c_m->func, i); args[i] = gen_assign_cast(c, ((compile_type_t*)m2->params[i - 1].type->c_type)->use_type, value, m->params[i - 1].type->ast_cap); } codegen_debugloc(c, m2->fun->ast); LLVMValueRef ret = codegen_call(c, c_m2->func, args, count, m->cap != TK_AT); codegen_debugloc(c, NULL); ret = gen_assign_cast(c, ((compile_type_t*)m->result->c_type)->use_type, ret, m2->result->ast_cap); LLVMBuildRet(c->builder, ret); codegen_finishfun(c); ponyint_pool_free_size(buf_size, args); return true; } static bool genfun_method(compile_t* c, reach_type_t* t, reach_method_name_t* n, reach_method_t* m) { if(m->intrinsic) { if(m->internal && (n->name == c->str__final)) { if(!genfun_implicit_final(c, t, m)) return false; } } else if(m->forwarding) { if(!genfun_forward(c, t, n, m)) return false; } else { switch(ast_id(m->fun->ast)) { case TK_NEW: if(t->underlying == TK_ACTOR) { if(!genfun_newbe(c, t, m)) return false; } else { if(!genfun_new(c, t, m)) return false; } break; case TK_BE: if(!genfun_be(c, t, m)) return false; break; case TK_FUN: if(!genfun_fun(c, t, m)) return false; break; default: pony_assert(0); return false; } } return true; } void genfun_param_attrs(compile_t* c, reach_type_t* t, reach_method_t* m, LLVMValueRef fun) { LLVM_DECLARE_ATTRIBUTEREF(noalias_attr, noalias, 0); LLVM_DECLARE_ATTRIBUTEREF(readonly_attr, readonly, 0); LLVMValueRef param = LLVMGetFirstParam(fun); reach_type_t* type = t; token_id cap = m->cap; int i = 0; int offset = 1; if(cap == TK_AT) { i = 1; offset = 0; } while(param != NULL) { LLVMTypeRef m_type = LLVMTypeOf(param); if(LLVMGetTypeKind(m_type) == LLVMPointerTypeKind) { if(i > 0) { type = m->params[i-1].type; cap = m->params[i-1].cap; } else if(ast_id(m->fun->ast) == TK_NEW) { param = LLVMGetNextParam(param); ++i; continue; } if(type->underlying != TK_ACTOR) { switch(cap) { case TK_ISO: LLVMAddAttributeAtIndex(fun, i + offset, noalias_attr); break; case TK_TRN: case TK_REF: break; case TK_VAL: case TK_TAG: case TK_BOX: LLVMAddAttributeAtIndex(fun, i + offset, readonly_attr); break; default: pony_assert(0); break; } } } param = LLVMGetNextParam(param); ++i; } } void genfun_allocate_compile_methods(compile_t* c, reach_type_t* t) { (void)c; size_t i = HASHMAP_BEGIN; reach_method_name_t* n; while((n = reach_method_names_next(&t->methods, &i)) != NULL) { size_t j = HASHMAP_BEGIN; reach_method_t* m; while((m = reach_mangled_next(&n->r_mangled, &j)) != NULL) { compile_method_t* c_m = POOL_ALLOC(compile_method_t); memset(c_m, 0, sizeof(compile_method_t)); c_m->free_fn = compile_method_free; m->c_method = (compile_opaque_t*)c_m; } } } bool genfun_method_sigs(compile_t* c, reach_type_t* t) { size_t i = HASHMAP_BEGIN; reach_method_name_t* n; while((n = reach_method_names_next(&t->methods, &i)) != NULL) { size_t j = HASHMAP_BEGIN; reach_method_t* m; while((m = reach_mangled_next(&n->r_mangled, &j)) != NULL) { if(m->internal && (n->name == c->str__final)) genfun_implicit_final_prototype(c, t, m); else make_prototype(c, t, n, m); copy_subordinate(m); } } if(!genfun_allocator(c, t)) return false; return true; } bool genfun_method_bodies(compile_t* c, reach_type_t* t) { switch(t->underlying) { case TK_PRIMITIVE: case TK_STRUCT: case TK_CLASS: case TK_ACTOR: break; default: return true; } size_t i = HASHMAP_BEGIN; reach_method_name_t* n; while((n = reach_method_names_next(&t->methods, &i)) != NULL) { size_t j = HASHMAP_BEGIN; reach_method_t* m; while((m = reach_mangled_next(&n->r_mangled, &j)) != NULL) { if(!genfun_method(c, t, n, m)) { if(errors_get_count(c->opt->check.errors) == 0) { pony_assert(m->fun != NULL); ast_error(c->opt->check.errors, m->fun->ast, "internal failure: code generation failed for method %s", m->full_name); } return false; } } } return true; } static bool need_primitive_call(compile_t* c, const char* method) { size_t i = HASHMAP_BEGIN; reach_type_t* t; while((t = reach_types_next(&c->reach->types, &i)) != NULL) { if(t->underlying != TK_PRIMITIVE) continue; reach_method_name_t* n = reach_method_name(t, method); if(n == NULL) continue; return true; } return false; } static void primitive_call(compile_t* c, const char* method) { size_t i = HASHMAP_BEGIN; reach_type_t* t; while((t = reach_types_next(&c->reach->types, &i)) != NULL) { if(t->underlying != TK_PRIMITIVE) continue; reach_method_t* m = reach_method(t, TK_NONE, method, NULL); if(m == NULL) continue; compile_type_t* c_t = (compile_type_t*)t->c_type; compile_method_t* c_m = (compile_method_t*)m->c_method; LLVMValueRef value = codegen_call(c, c_m->func, &c_t->instance, 1, true); if(c->str__final == method) LLVMSetInstructionCallConv(value, LLVMCCallConv); } } void genfun_primitive_calls(compile_t* c) { LLVMTypeRef fn_type = NULL; if(need_primitive_call(c, c->str__init)) { fn_type = LLVMFunctionType(c->void_type, NULL, 0, false); const char* fn_name = genname_program_fn(c->filename, "primitives_init"); c->primitives_init = LLVMAddFunction(c->module, fn_name, fn_type); codegen_startfun(c, c->primitives_init, NULL, NULL, NULL, false); primitive_call(c, c->str__init); LLVMBuildRetVoid(c->builder); codegen_finishfun(c); } if(need_primitive_call(c, c->str__final)) { if(fn_type == NULL) fn_type = LLVMFunctionType(c->void_type, NULL, 0, false); const char* fn_name = genname_program_fn(c->filename, "primitives_final"); c->primitives_final = LLVMAddFunction(c->module, fn_name, fn_type); codegen_startfun(c, c->primitives_final, NULL, NULL, NULL, false); primitive_call(c, c->str__final); LLVMBuildRetVoid(c->builder); codegen_finishfun(c); } }
308656.c
#include <pebble.h> static Window *s_window; static TextLayer *s_time_layer; static GBitmap *s_background_image; static BitmapLayer *s_background_image_layer; static void handle_minute_tick(struct tm *tick_time, TimeUnits units_changed) { // Create a long-lived buffer static char buffer[] = "00:00"; clock_copy_time_string(buffer, sizeof(buffer)); // Display this time on the TextLayer text_layer_set_text(s_time_layer, buffer); } static void main_window_load(Window *window) { time_t t = time(NULL); struct tm * tm = localtime(&t); GRect frame = GRect(0, 0, 144, 168); window_set_background_color(window, GColorBlack); // Init the background image s_background_image = gbitmap_create_with_resource( RESOURCE_ID_XO_BACKGROUND ); s_background_image_layer = bitmap_layer_create(frame); bitmap_layer_set_bitmap(s_background_image_layer, s_background_image); layer_add_child(window_get_root_layer(window), bitmap_layer_get_layer(s_background_image_layer)); // Init the text layer used for the time s_time_layer = text_layer_create(GRect(2, 168-23, 144-4, 23)); text_layer_set_text_color(s_time_layer, GColorWhite); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); text_layer_set_background_color(s_time_layer, GColorClear); text_layer_set_font(s_time_layer, fonts_load_custom_font(resource_get_handle(RESOURCE_ID_FONT_ROBOTO_BOLD_SUBSET_20))); layer_add_child(window_get_root_layer(window), text_layer_get_layer(s_time_layer)); // Register with TickTimerService tick_timer_service_subscribe(MINUTE_UNIT, handle_minute_tick); handle_minute_tick(tm, ~0); } static void main_window_unload(Window *window) { gbitmap_destroy(s_background_image); bitmap_layer_destroy(s_background_image_layer); text_layer_destroy(s_time_layer); tick_timer_service_unsubscribe(); } static void init() { // Create main Window element and assign to pointer s_window = window_create(); // Set handlers to manage the elements inside the Window window_set_window_handlers(s_window, (WindowHandlers) { .load = main_window_load, .unload = main_window_unload }); // Show the Window on the watch, with animated=true window_stack_push(s_window, true /* Animated */); } static void deinit() { // Destroy Window window_destroy(s_window); } int main(void) { init(); app_event_loop(); deinit(); }
148404.c
/*------------------------------------------------------------------------- * * nodeForeignscan.c * Routines to support scans of foreign tables * * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * * IDENTIFICATION * src/backend/executor/nodeForeignscan.c * *------------------------------------------------------------------------- */ /* * INTERFACE ROUTINES * * ExecForeignScan scans a foreign table. * ExecInitForeignScan creates and initializes state info. * ExecReScanForeignScan rescans the foreign relation. * ExecEndForeignScan releases any resources allocated. */ #include "postgres.h" #include "executor/executor.h" #include "executor/nodeForeignscan.h" #include "foreign/fdwapi.h" #include "utils/memutils.h" #include "utils/rel.h" #include "optimizer/var.h" static TupleTableSlot *ForeignNext(ForeignScanState *node); static bool ForeignRecheck(ForeignScanState *node, TupleTableSlot *slot); /* ---------------------------------------------------------------- * ForeignNext * * This is a workhorse for ExecForeignScan * ---------------------------------------------------------------- */ static TupleTableSlot * ForeignNext(ForeignScanState *node) { TupleTableSlot *slot; ForeignScan *plan = (ForeignScan *) node->ss.ps.plan; ExprContext *econtext = node->ss.ps.ps_ExprContext; MemoryContext oldcontext; /* Call the Iterate function in short-lived context */ oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory); if (plan->operation != CMD_SELECT) slot = node->fdwroutine->IterateDirectModify(node); else slot = node->fdwroutine->IterateForeignScan(node); MemoryContextSwitchTo(oldcontext); /* * If any system columns are requested, we have to force the tuple into * physical-tuple form to avoid "cannot extract system attribute from * virtual tuple" errors later. We also insert a valid value for * tableoid, which is the only actually-useful system column. */ if (plan->fsSystemCol && !TupIsNull(slot)) { (void) ExecMaterializeSlot(slot); //tup->t_tableOid = RelationGetRelid(node->ss.ss_currentRelation); /* * CDB: Label each row with a synthetic ctid if needed for subquery dedup. */ if (node->cdb_want_ctid && !TupIsNull(slot)) { slot_set_ctid_from_fake(slot, &node->cdb_fake_ctid); } } return slot; } /* * ForeignRecheck -- access method routine to recheck a tuple in EvalPlanQual */ static bool ForeignRecheck(ForeignScanState *node, TupleTableSlot *slot) { FdwRoutine *fdwroutine = node->fdwroutine; ExprContext *econtext; /* * extract necessary information from foreign scan node */ econtext = node->ss.ps.ps_ExprContext; /* Does the tuple meet the remote qual condition? */ econtext->ecxt_scantuple = slot; ResetExprContext(econtext); /* * If an outer join is pushed down, RecheckForeignScan may need to store a * different tuple in the slot, because a different set of columns may go * to NULL upon recheck. Otherwise, it shouldn't need to change the slot * contents, just return true or false to indicate whether the quals still * pass. For simple cases, setting fdw_recheck_quals may be easier than * providing this callback. */ if (fdwroutine->RecheckForeignScan && !fdwroutine->RecheckForeignScan(node, slot)) return false; return ExecQual(node->fdw_recheck_quals, econtext, false); } /* ---------------------------------------------------------------- * ExecForeignScan(node) * * Fetches the next tuple from the FDW, checks local quals, and * returns it. * We call the ExecScan() routine and pass it the appropriate * access method functions. * ---------------------------------------------------------------- */ TupleTableSlot * ExecForeignScan(ForeignScanState *node) { return ExecScan((ScanState *) node, (ExecScanAccessMtd) ForeignNext, (ExecScanRecheckMtd) ForeignRecheck); } /* ---------------------------------------------------------------- * ExecInitForeignScan * ---------------------------------------------------------------- */ ForeignScanState * ExecInitForeignScan(ForeignScan *node, EState *estate, int eflags) { ForeignScanState *scanstate; Relation currentRelation = NULL; Index scanrelid = node->scan.scanrelid; Index tlistvarno; FdwRoutine *fdwroutine; /* check for unsupported flags */ Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK))); /* * create state structure */ scanstate = makeNode(ForeignScanState); scanstate->ss.ps.plan = (Plan *) node; scanstate->ss.ps.state = estate; /* * Miscellaneous initialization * * create expression context for node */ ExecAssignExprContext(estate, &scanstate->ss.ps); //scanstate->ss.ps.ps_TupFromTlist = false; /* * initialize child expressions */ scanstate->ss.ps.targetlist = (List *) ExecInitExpr((Expr *) node->scan.plan.targetlist, (PlanState *) scanstate); scanstate->ss.ps.qual = (List *) ExecInitExpr((Expr *) node->scan.plan.qual, (PlanState *) scanstate); scanstate->fdw_recheck_quals = (List *) ExecInitExpr((Expr *) node->fdw_recheck_quals, (PlanState *) scanstate); /* Check if targetlist or qual contains a var node referencing the ctid column */ scanstate->cdb_want_ctid = contain_ctid_var_reference(&node->scan); ItemPointerSetInvalid(&scanstate->cdb_fake_ctid); /* * tuple table initialization * * In GPDB, cannot use ExecInitScanTupleSlot() on foreign scans of join * relations. */ ExecInitResultTupleSlot(estate, &scanstate->ss.ps); if (scanrelid > 0) ExecInitScanTupleSlot(estate, &scanstate->ss); else scanstate->ss.ss_ScanTupleSlot = ExecAllocTableSlot(&estate->es_tupleTable); /* * open the base relation, if any, and acquire an appropriate lock on it; * also acquire function pointers from the FDW's handler */ if (scanrelid > 0) { currentRelation = ExecOpenScanRelation(estate, scanrelid, eflags); scanstate->ss.ss_currentRelation = currentRelation; fdwroutine = GetFdwRoutineForRelation(currentRelation, true); } else { /* We can't use the relcache, so get fdwroutine the hard way */ fdwroutine = GetFdwRoutineByServerId(node->fs_server); } /* * Determine the scan tuple type. If the FDW provided a targetlist * describing the scan tuples, use that; else use base relation's rowtype. */ if (node->fdw_scan_tlist != NIL || currentRelation == NULL) { TupleDesc scan_tupdesc; scan_tupdesc = ExecTypeFromTL(node->fdw_scan_tlist, false); ExecAssignScanType(&scanstate->ss, scan_tupdesc); /* Node's targetlist will contain Vars with varno = INDEX_VAR */ tlistvarno = INDEX_VAR; } else { ExecAssignScanType(&scanstate->ss, RelationGetDescr(currentRelation)); /* Node's targetlist will contain Vars with varno = scanrelid */ tlistvarno = scanrelid; } /* * Initialize result tuple type and projection info. */ ExecAssignResultTypeFromTL(&scanstate->ss.ps); ExecAssignScanProjectionInfoWithVarno(&scanstate->ss, tlistvarno); /* * Initialize FDW-related state. */ scanstate->fdwroutine = fdwroutine; scanstate->fdw_state = NULL; /* Initialize any outer plan. */ if (outerPlan(node)) outerPlanState(scanstate) = ExecInitNode(outerPlan(node), estate, eflags); /* * Tell the FDW to initialize the scan. */ if (node->operation != CMD_SELECT) fdwroutine->BeginDirectModify(scanstate, eflags); else fdwroutine->BeginForeignScan(scanstate, eflags); return scanstate; } /* ---------------------------------------------------------------- * ExecEndForeignScan * * frees any storage allocated through C routines. * ---------------------------------------------------------------- */ void ExecEndForeignScan(ForeignScanState *node) { ForeignScan *plan = (ForeignScan *) node->ss.ps.plan; /* Let the FDW shut down */ if (plan->operation != CMD_SELECT) node->fdwroutine->EndDirectModify(node); else { if (!node->is_squelched) node->fdwroutine->EndForeignScan(node); } /* Shut down any outer plan. */ if (outerPlanState(node)) ExecEndNode(outerPlanState(node)); /* Free the exprcontext */ ExecFreeExprContext(&node->ss.ps); /* clean out the tuple table */ ExecClearTuple(node->ss.ps.ps_ResultTupleSlot); ExecClearTuple(node->ss.ss_ScanTupleSlot); /* close the relation. */ if (node->ss.ss_currentRelation) ExecCloseScanRelation(node->ss.ss_currentRelation); } /* ---------------------------------------------------------------- * ExecReScanForeignScan * * Rescans the relation. * ---------------------------------------------------------------- */ void ExecReScanForeignScan(ForeignScanState *node) { PlanState *outerPlan = outerPlanState(node); ItemPointerSet(&node->cdb_fake_ctid, 0, 0); node->fdwroutine->ReScanForeignScan(node); /* * If chgParam of subnode is not null then plan will be re-scanned by * first ExecProcNode. outerPlan may also be NULL, in which case there is * nothing to rescan at all. */ if (outerPlan != NULL && outerPlan->chgParam == NULL) ExecReScan(outerPlan); ExecScanReScan(&node->ss); } /* ---------------------------------------------------------------- * ExecForeignScanEstimate * * Informs size of the parallel coordination information, if any * ---------------------------------------------------------------- */ void ExecForeignScanEstimate(ForeignScanState *node, ParallelContext *pcxt) { FdwRoutine *fdwroutine = node->fdwroutine; if (fdwroutine->EstimateDSMForeignScan) { node->pscan_len = fdwroutine->EstimateDSMForeignScan(node, pcxt); shm_toc_estimate_chunk(&pcxt->estimator, node->pscan_len); shm_toc_estimate_keys(&pcxt->estimator, 1); } } /* ---------------------------------------------------------------- * ExecForeignScanInitializeDSM * * Initialize the parallel coordination information * ---------------------------------------------------------------- */ void ExecForeignScanInitializeDSM(ForeignScanState *node, ParallelContext *pcxt) { FdwRoutine *fdwroutine = node->fdwroutine; if (fdwroutine->InitializeDSMForeignScan) { int plan_node_id = node->ss.ps.plan->plan_node_id; void *coordinate; coordinate = shm_toc_allocate(pcxt->toc, node->pscan_len); fdwroutine->InitializeDSMForeignScan(node, pcxt, coordinate); shm_toc_insert(pcxt->toc, plan_node_id, coordinate); } } /* ---------------------------------------------------------------- * ExecForeignScanInitializeDSM * * Initialization according to the parallel coordination information * ---------------------------------------------------------------- */ void ExecForeignScanInitializeWorker(ForeignScanState *node, shm_toc *toc) { FdwRoutine *fdwroutine = node->fdwroutine; if (fdwroutine->InitializeWorkerForeignScan) { int plan_node_id = node->ss.ps.plan->plan_node_id; void *coordinate; coordinate = shm_toc_lookup(toc, plan_node_id); fdwroutine->InitializeWorkerForeignScan(node, toc, coordinate); } } /* ---------------------------------------------------------------- * ExecSquelchForeignScan * * Performs identically to ExecEndForeignScan except that * closure errors are ignored. This function is called for * normal termination when the external data source is NOT * exhausted (such as for a LIMIT clause). * ---------------------------------------------------------------- */ void ExecSquelchForeignScan(ForeignScanState *node) { ForeignScan *plan = (ForeignScan *) node->ss.ps.plan; node->is_squelched = true; if (plan->operation == CMD_SELECT) node->fdwroutine->EndForeignScan(node); }
660449.c
#define LOOP_TO_0(ID, N, BODY) {int ID; switch(N){\ case 7: ID=7;{BODY};\ case 6: ID=6;{BODY};\ case 5: ID=5;{BODY};\ case 4: ID=4;{BODY};\ case 3: ID=3;{BODY};\ case 2: ID=2;{BODY};\ case 1: ID=1;{BODY};\ case 0: ID=0;{BODY};\ }} #define LOOP_TO(ID, START, END, BODY) \ LOOP_TO_0(ID, (END)-(START), ID=(END)-ID; BODY) #define LOOP_DOWNTO(ID, START, END, BODY) \ LOOP_TO_0(ID, (START)-(END), ID=(END)+ID; BODY) #include "stdio.h" #include "stdlib.h" int main(){ printf("2 to 4: "); LOOP_TO(i, 2, 4, printf("%d, ", i); ); printf("\n5 to 3: "); LOOP_DOWNTO(j, 5, 3, printf("%d, ", j); ); printf("\n"); }
98796.c
/** * @file fw_update.c * @author TheSomeMan * @date 2021-05-30 * @copyright Ruuvi Innovations Ltd, license BSD-3-Clause. */ #include "fw_update.h" #include <string.h> #include "http.h" #include "esp_type_wrapper.h" #include "cJSON.h" #include "cjson_wrap.h" #include "wifi_manager.h" #include "http_server.h" #include "esp_ota_ops_patched.h" #include "nrf52fw.h" #include "leds.h" #include "adv_post.h" #define LOG_LOCAL_LEVEL LOG_LEVEL_DEBUG #include "log.h" #define GW_GWUI_PARTITION_2 GW_GWUI_PARTITION "_2" #define GW_NRF_PARTITION_2 GW_NRF_PARTITION "_2" #define FW_UPDATE_DELAY_AFTER_OPERATION_WITH_FLASH_MS (20) #define FW_UPDATE_URL_MAX_LEN (128U) #define FW_UPDATE_PERCENTAGE_50 (50U) #define FW_UPDATE_PERCENTAGE_100 (100U) #define FW_UPDATE_DELAY_BEFORE_REBOOT_MS (5U * 1000U) typedef struct fw_update_config_t { char url[FW_UPDATE_URL_MAX_LEN + 1]; } fw_update_config_t; typedef struct fw_update_data_partition_info_t { const esp_partition_t *const p_partition; size_t offset; bool is_error; } fw_update_data_partition_info_t; typedef struct fw_update_ota_partition_info_t { const esp_partition_t *const p_partition; esp_ota_handle_t out_handle; bool is_error; } fw_update_ota_partition_info_t; typedef enum fw_update_stage_e { FW_UPDATE_STAGE_NONE = 0, FW_UPDATE_STAGE_1 = 1, FW_UPDATE_STAGE_2 = 2, FW_UPDATE_STAGE_3 = 3, FW_UPDATE_STAGE_4 = 4, FW_UPDATE_STAGE_SUCCESSFUL = 5, FW_UPDATE_STAGE_FAILED = 6, } fw_update_stage_e; typedef uint32_t fw_update_percentage_t; static void fw_update_set_extra_info_for_status_json( const enum fw_update_stage_e fw_updating_stage, const fw_update_percentage_t fw_updating_percentage); static const char TAG[] = "fw_update"; static ruuvi_flash_info_t g_ruuvi_flash_info; static fw_update_config_t g_fw_update_cfg; static fw_update_stage_e g_update_progress_stage; static fw_updating_reason_e g_fw_updating_reason; static const esp_partition_t * find_data_fat_partition_by_name(const char *const p_partition_name) { esp_partition_iterator_t iter = esp_partition_find( ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, p_partition_name); if (NULL == iter) { LOG_ERR("Can't find partition: %s", p_partition_name); return NULL; } const esp_partition_t *p_partition = esp_partition_get(iter); esp_partition_iterator_release(iter); return p_partition; } static bool fw_update_read_flash_info_internal(ruuvi_flash_info_t *const p_flash_info) { p_flash_info->is_valid = false; p_flash_info->running_partition_state = ESP_OTA_IMG_UNDEFINED; p_flash_info->p_app_desc = esp_ota_get_app_description(); LOG_INFO("Project name : %s", p_flash_info->p_app_desc->project_name); LOG_INFO("Firmware version : %s", p_flash_info->p_app_desc->version); p_flash_info->p_boot_partition = esp_ota_get_boot_partition(); if (NULL == p_flash_info->p_boot_partition) { LOG_ERR("There is no boot partition info"); return false; } LOG_INFO("Boot partition: %s", p_flash_info->p_boot_partition->label); p_flash_info->p_running_partition = esp_ota_get_running_partition(); if (NULL == p_flash_info->p_running_partition) { LOG_ERR("There is no running partition info"); return false; } LOG_INFO("Currently running partition: %s", p_flash_info->p_running_partition->label); esp_err_t err = esp_ota_get_state_partition( p_flash_info->p_running_partition, &p_flash_info->running_partition_state); if (ESP_OK != err) { LOG_ERR_ESP(err, "%s failed", "esp_ota_get_state_partition"); return false; } switch (p_flash_info->running_partition_state) { case ESP_OTA_IMG_NEW: LOG_INFO("Currently running partition state: %s", "NEW"); break; case ESP_OTA_IMG_PENDING_VERIFY: LOG_INFO("Currently running partition state: %s", "PENDING_VERIFY"); break; case ESP_OTA_IMG_VALID: LOG_INFO("Currently running partition state: %s", "VALID"); break; case ESP_OTA_IMG_INVALID: LOG_INFO("Currently running partition state: %s", "INVALID"); break; case ESP_OTA_IMG_ABORTED: LOG_INFO("Currently running partition state: %s", "ABORTED"); break; case ESP_OTA_IMG_UNDEFINED: LOG_INFO("Currently running partition state: %s", "UNDEFINED"); break; default: LOG_INFO( "Currently running partition state: UNKNOWN (%d)", (printf_int_t)p_flash_info->running_partition_state); break; } p_flash_info->p_next_update_partition = esp_ota_get_next_update_partition(p_flash_info->p_running_partition); if (NULL == p_flash_info->p_next_update_partition) { LOG_ERR("Can't find next partition for updating"); return false; } LOG_INFO( "Next update partition: %s: address 0x%08x, size 0x%x", p_flash_info->p_next_update_partition->label, p_flash_info->p_next_update_partition->address, p_flash_info->p_next_update_partition->size); p_flash_info->is_ota0_active = (0 == strcmp("ota_0", p_flash_info->p_running_partition->label)) ? true : false; const char *const p_gwui_parition_name = p_flash_info->is_ota0_active ? GW_GWUI_PARTITION_2 : GW_GWUI_PARTITION; p_flash_info->p_next_fatfs_gwui_partition = find_data_fat_partition_by_name(p_gwui_parition_name); if (NULL == p_flash_info->p_next_fatfs_gwui_partition) { return false; } LOG_INFO( "Next fatfs_gwui partition: %s: address 0x%08x, size 0x%x", p_flash_info->p_next_fatfs_gwui_partition->label, p_flash_info->p_next_fatfs_gwui_partition->address, p_flash_info->p_next_fatfs_gwui_partition->size); const char *const p_fatfs_nrf52_partition_name = p_flash_info->is_ota0_active ? GW_NRF_PARTITION_2 : GW_NRF_PARTITION; p_flash_info->p_next_fatfs_nrf52_partition = find_data_fat_partition_by_name(p_fatfs_nrf52_partition_name); if (NULL == p_flash_info->p_next_fatfs_nrf52_partition) { return false; } LOG_INFO( "Next fatfs_nrf52 partition: %s: address 0x%08x, size 0x%x", p_flash_info->p_next_fatfs_nrf52_partition->label, p_flash_info->p_next_fatfs_nrf52_partition->address, p_flash_info->p_next_fatfs_nrf52_partition->size); p_flash_info->is_valid = true; return true; } bool fw_update_read_flash_info(void) { ruuvi_flash_info_t *p_flash_info = &g_ruuvi_flash_info; fw_update_read_flash_info_internal(p_flash_info); return p_flash_info->is_valid; } bool fw_update_mark_app_valid_cancel_rollback(void) { ruuvi_flash_info_t *p_flash_info = &g_ruuvi_flash_info; if (ESP_OTA_IMG_PENDING_VERIFY == p_flash_info->running_partition_state) { LOG_INFO("Mark current OTA partition valid and cancel rollback"); const esp_err_t err = esp_ota_mark_app_valid_cancel_rollback(); if (ESP_OK != err) { LOG_ERR_ESP(err, "%s failed", "esp_ota_mark_app_valid_cancel_rollback"); return false; } p_flash_info->running_partition_state = ESP_OTA_IMG_VALID; } return true; } const char * fw_update_get_current_fatfs_nrf52_partition_name(void) { const ruuvi_flash_info_t *const p_flash_info = &g_ruuvi_flash_info; return p_flash_info->is_ota0_active ? GW_NRF_PARTITION : GW_NRF_PARTITION_2; } const char * fw_update_get_current_fatfs_gwui_partition_name(void) { const ruuvi_flash_info_t *const p_flash_info = &g_ruuvi_flash_info; return p_flash_info->is_ota0_active ? GW_GWUI_PARTITION : GW_GWUI_PARTITION_2; } ruuvi_esp32_fw_ver_str_t fw_update_get_cur_version(void) { const ruuvi_flash_info_t *const p_flash_info = &g_ruuvi_flash_info; ruuvi_esp32_fw_ver_str_t version_str = { 0 }; snprintf(&version_str.buf[0], sizeof(version_str.buf), "%s", p_flash_info->p_app_desc->version); return version_str; } esp_err_t erase_partition_with_sleep(const esp_partition_t *const p_partition) { assert(p_partition != NULL); if ((p_partition->size % SPI_FLASH_SEC_SIZE) != 0) { return ESP_ERR_INVALID_SIZE; } size_t offset = 0; while (offset < p_partition->size) { const uint32_t sector_address = p_partition->address + offset; const esp_err_t err = esp_flash_erase_region(p_partition->flash_chip, sector_address, SPI_FLASH_SEC_SIZE); if (ESP_OK != err) { LOG_ERR_ESP(err, "Failed to erase sector at 0x%08x", (printf_uint_t)(p_partition->address + offset)); return err; } const fw_update_percentage_t percentage = (offset * FW_UPDATE_PERCENTAGE_50) / p_partition->size; fw_update_set_extra_info_for_status_json(g_update_progress_stage, percentage); vTaskDelay(pdMS_TO_TICKS(FW_UPDATE_DELAY_AFTER_OPERATION_WITH_FLASH_MS)); offset += SPI_FLASH_SEC_SIZE; } return ESP_OK; } static bool fw_update_handle_http_resp_code( const http_resp_code_e http_resp_code, const uint8_t *const p_buf, const size_t buf_size, bool *const p_result) { if (HTTP_RESP_CODE_200 != http_resp_code) { if (HTTP_RESP_CODE_302 == http_resp_code) { LOG_INFO("Got HTTP error %d: Redirect to another location", (printf_int_t)http_resp_code); *p_result = true; return true; } LOG_ERR("Got HTTP error %d: %.*s", (printf_int_t)http_resp_code, (printf_int_t)buf_size, (const char *)p_buf); *p_result = false; return true; } return false; } static bool fw_update_data_partition_cb_on_recv_data( const uint8_t *const p_buf, const size_t buf_size, const size_t offset, const size_t content_length, const http_resp_code_e http_resp_code, void *const p_user_data) { fw_update_data_partition_info_t *const p_info = p_user_data; if (p_info->is_error) { return false; } bool result = false; if (fw_update_handle_http_resp_code(http_resp_code, p_buf, buf_size, &result)) { if (!result) { p_info->is_error = true; } return result; } LOG_INFO( "Write to data partition %s, offset %lu, size %lu", p_info->p_partition->label, (printf_ulong_t)offset, (printf_ulong_t)buf_size); const fw_update_percentage_t percentage = FW_UPDATE_PERCENTAGE_50 + (((offset + buf_size) * FW_UPDATE_PERCENTAGE_50) / content_length); fw_update_set_extra_info_for_status_json(g_update_progress_stage, percentage); const esp_err_t err = esp_partition_write(p_info->p_partition, p_info->offset, p_buf, buf_size); vTaskDelay(pdMS_TO_TICKS(FW_UPDATE_DELAY_AFTER_OPERATION_WITH_FLASH_MS)); if (ESP_OK != err) { p_info->is_error = true; LOG_ERR_ESP( err, "Failed to write to partition %s at offset %lu", p_info->p_partition->label, (printf_ulong_t)p_info->offset); return false; } p_info->offset += buf_size; return true; } static bool fw_update_data_partition(const esp_partition_t *const p_partition, const char *const p_url) { LOG_INFO( "Update partition %s (address 0x%08x, size 0x%x) from %s", p_partition->label, p_partition->address, p_partition->size, p_url); fw_update_data_partition_info_t fw_update_info = { .p_partition = p_partition, .offset = 0, .is_error = false, }; LOG_INFO("fw_update_data_partition: Erase partition"); esp_err_t err = erase_partition_with_sleep(p_partition); if (ESP_OK != err) { LOG_ERR_ESP( err, "Failed to erase partition %s, address 0x%08x, size 0x%x", p_partition->label, p_partition->address, p_partition->size); return false; } LOG_INFO("fw_update_data_partition: Download and write partition data"); const bool flag_feed_task_watchdog = false; if (!http_download( p_url, HTTP_DOWNLOAD_TIMEOUT_SECONDS, &fw_update_data_partition_cb_on_recv_data, &fw_update_info, flag_feed_task_watchdog)) { LOG_ERR("Failed to update partition %s - failed to download %s", p_partition->label, p_url); return false; } if (fw_update_info.is_error) { LOG_ERR("Failed to update partition %s - some problem during writing", p_partition->label); return false; } LOG_INFO("Partition %s has been successfully updated", p_partition->label); return true; } bool fw_update_fatfs_gwui(const char *const p_url) { const esp_partition_t *const p_partition = g_ruuvi_flash_info.p_next_fatfs_gwui_partition; if (NULL == p_partition) { LOG_ERR("Can't find partition to update fatfs_gwui"); return false; } return fw_update_data_partition(p_partition, p_url); } bool fw_update_fatfs_nrf52(const char *const p_url) { const esp_partition_t *const p_partition = g_ruuvi_flash_info.p_next_fatfs_nrf52_partition; if (NULL == p_partition) { LOG_ERR("Can't find partition to update fatfs_nrf52"); return false; } return fw_update_data_partition(p_partition, p_url); } static bool fw_update_ota_partition_cb_on_recv_data( const uint8_t *const p_buf, const size_t buf_size, const size_t offset, const size_t content_length, const http_resp_code_e http_resp_code, void *const p_user_data) { fw_update_ota_partition_info_t *const p_info = p_user_data; if (p_info->is_error) { LOG_INFO("Drop data after an error, offset %lu, size %lu", (printf_ulong_t)offset, (printf_ulong_t)buf_size); return false; } bool result = false; if (fw_update_handle_http_resp_code(http_resp_code, p_buf, buf_size, &result)) { if (!result) { p_info->is_error = true; } return result; } LOG_INFO( "Write to OTA-partition %s, offset %lu, size %lu", p_info->p_partition->label, (printf_ulong_t)offset, (printf_ulong_t)buf_size); const fw_update_percentage_t percentage = FW_UPDATE_PERCENTAGE_50 + (((offset + buf_size) * FW_UPDATE_PERCENTAGE_50) / content_length); fw_update_set_extra_info_for_status_json(g_update_progress_stage, percentage); const esp_err_t err = esp_ota_write_patched(p_info->out_handle, p_buf, buf_size); vTaskDelay(pdMS_TO_TICKS(FW_UPDATE_DELAY_AFTER_OPERATION_WITH_FLASH_MS)); if (ESP_OK != err) { p_info->is_error = true; LOG_ERR_ESP(err, "Failed to write to OTA-partition %s", p_info->p_partition->label); return false; } return true; } static bool fw_update_ota_partition( const esp_partition_t *const p_partition, const esp_ota_handle_t out_handle, const char *const p_url) { LOG_INFO( "Update OTA-partition %s (address 0x%08x, size 0x%x) from %s", p_partition->label, p_partition->address, p_partition->size, p_url); fw_update_ota_partition_info_t fw_update_info = { .p_partition = p_partition, .out_handle = out_handle, .is_error = false, }; const bool flag_feed_task_watchdog = false; if (!http_download( p_url, HTTP_DOWNLOAD_TIMEOUT_SECONDS, &fw_update_ota_partition_cb_on_recv_data, &fw_update_info, flag_feed_task_watchdog)) { LOG_ERR("Failed to update OTA-partition %s - failed to download %s", p_partition->label, p_url); return false; } if (fw_update_info.is_error) { LOG_ERR("Failed to update OTA-partition %s - some problem during writing", p_partition->label); return false; } fw_update_set_extra_info_for_status_json(g_update_progress_stage, FW_UPDATE_PERCENTAGE_100); LOG_INFO("OTA-partition %s has been successfully updated", p_partition->label); return true; } static bool fw_update_ota(const char *const p_url) { const esp_partition_t *const p_partition = g_ruuvi_flash_info.p_next_update_partition; if (NULL == p_partition) { LOG_ERR("Can't find partition to update firmware"); return false; } LOG_INFO("fw_update_ota: Erase partition"); esp_ota_handle_t out_handle = 0; esp_err_t err = esp_ota_begin_patched(p_partition, &out_handle); if (ESP_OK != err) { LOG_ERR("%s failed", "esp_ota_begin"); return false; } LOG_INFO("fw_update_ota: Download and write partition data"); const bool res = fw_update_ota_partition(p_partition, out_handle, p_url); LOG_INFO("fw_update_ota: Finish writing to partition"); err = esp_ota_end_patched(out_handle); if (ESP_OK != err) { LOG_ERR("%s failed", "esp_ota_end"); return false; } return res; } static bool json_fw_update_copy_string_val( const cJSON *const p_json_root, const char *const p_attr_name, char *const p_buf, const size_t buf_len, const bool flag_log_err_if_not_found) { if (!json_wrap_copy_string_val(p_json_root, p_attr_name, p_buf, buf_len)) { if (flag_log_err_if_not_found) { LOG_ERR("%s not found", p_attr_name); } return false; } LOG_DBG("%s: %s", p_attr_name, p_buf); return true; } static bool json_fw_update_parse(const cJSON *const p_json_root, fw_update_config_t *const p_cfg) { if (!json_fw_update_copy_string_val(p_json_root, "url", p_cfg->url, sizeof(p_cfg->url), true)) { return false; } return true; } bool json_fw_update_parse_http_body(const char *const p_body) { cJSON *p_json_root = cJSON_Parse(p_body); if (NULL == p_json_root) { LOG_ERR("Failed to parse json or no memory"); return false; } const bool ret = json_fw_update_parse(p_json_root, &g_fw_update_cfg); cJSON_Delete(p_json_root); return ret; } static void fw_update_set_extra_info_for_status_json( const enum fw_update_stage_e fw_updating_stage, const fw_update_percentage_t fw_updating_percentage) { char extra_info_buf[JSON_NETWORK_EXTRA_INFO_SIZE]; if (FW_UPDATE_STAGE_NONE == fw_updating_stage) { extra_info_buf[0] = '\0'; } else { snprintf( extra_info_buf, sizeof(extra_info_buf), "\"fw_updating\":%u,\"percentage\":%u", (printf_uint_t)fw_updating_stage, (printf_uint_t)fw_updating_percentage); } wifi_manager_set_extra_info_for_status_json(extra_info_buf); } void fw_update_set_extra_info_for_status_json_update_start(void) { fw_update_set_extra_info_for_status_json(FW_UPDATE_STAGE_1, 0); } void fw_update_set_extra_info_for_status_json_update_successful(void) { char extra_info_buf[JSON_NETWORK_EXTRA_INFO_SIZE]; snprintf(extra_info_buf, sizeof(extra_info_buf), "\"fw_updating\":%u", (printf_uint_t)FW_UPDATE_STAGE_SUCCESSFUL); wifi_manager_set_extra_info_for_status_json(extra_info_buf); } void fw_update_set_extra_info_for_status_json_update_failed(const char *const p_message) { char extra_info_buf[JSON_NETWORK_EXTRA_INFO_SIZE]; snprintf( extra_info_buf, sizeof(extra_info_buf), "\"fw_updating\":%u,\"message\":\"%s\"", (printf_uint_t)FW_UPDATE_STAGE_FAILED, (NULL != p_message) ? p_message : ""); wifi_manager_set_extra_info_for_status_json(extra_info_buf); } void fw_update_nrf52fw_cb_progress(const size_t num_bytes_flashed, const size_t total_size, void *const p_param) { (void)p_param; const fw_update_percentage_t percentage = (num_bytes_flashed * FW_UPDATE_PERCENTAGE_100) / total_size; fw_update_set_extra_info_for_status_json(g_update_progress_stage, percentage); } void fw_update_set_stage_nrf52_updating(void) { g_update_progress_stage = FW_UPDATE_STAGE_4; fw_update_set_extra_info_for_status_json(g_update_progress_stage, 0); } static bool fw_update_do_actions(void) { g_update_progress_stage = FW_UPDATE_STAGE_1; fw_update_set_extra_info_for_status_json(g_update_progress_stage, 0); char url[sizeof(g_fw_update_cfg.url) + 32]; snprintf(url, sizeof(url), "%s/%s", g_fw_update_cfg.url, "ruuvi_gateway_esp.bin"); LOG_INFO("fw_update_ota"); if (!fw_update_ota(url)) { LOG_ERR("%s failed", "fw_update_ota"); fw_update_set_extra_info_for_status_json_update_failed("Failed to update OTA"); return false; } g_update_progress_stage = FW_UPDATE_STAGE_2; fw_update_set_extra_info_for_status_json(g_update_progress_stage, 0); snprintf(url, sizeof(url), "%s/%s", g_fw_update_cfg.url, "fatfs_gwui.bin"); LOG_INFO("fw_update_fatfs_gwui"); if (!fw_update_fatfs_gwui(url)) { LOG_ERR("%s failed", "fw_update_fatfs_gwui"); fw_update_set_extra_info_for_status_json_update_failed("Failed to update GWUI"); return false; } g_update_progress_stage = FW_UPDATE_STAGE_3; fw_update_set_extra_info_for_status_json(g_update_progress_stage, 0); snprintf(url, sizeof(url), "%s/%s", g_fw_update_cfg.url, "fatfs_nrf52.bin"); LOG_INFO("fw_update_fatfs_nrf52"); if (!fw_update_fatfs_nrf52(url)) { LOG_ERR("%s failed", "fw_update_fatfs_nrf52"); fw_update_set_extra_info_for_status_json_update_failed("Failed to update nRF52"); return false; } LOG_INFO("esp_ota_set_boot_partition"); const esp_err_t err = esp_ota_set_boot_partition(g_ruuvi_flash_info.p_next_update_partition); if (ESP_OK != err) { LOG_ERR_ESP(err, "%s failed", "esp_ota_set_boot_partition"); fw_update_set_extra_info_for_status_json_update_failed("Failed to switch boot partition"); return false; } g_ruuvi_flash_info.p_boot_partition = g_ruuvi_flash_info.p_next_update_partition; g_ruuvi_flash_info.is_ota0_active = !g_ruuvi_flash_info.is_ota0_active; fw_update_set_stage_nrf52_updating(); leds_indication_on_nrf52_fw_updating(); LOG_INFO("nrf52fw_update_fw_if_necessary"); nrf52fw_update_fw_if_necessary( fw_update_get_current_fatfs_nrf52_partition_name(), &fw_update_nrf52fw_cb_progress, NULL, NULL, NULL, NULL); if (wifi_manager_is_connected_to_wifi_or_ethernet()) { leds_indication_on_network_ok(); } else { leds_indication_network_no_connection(); } fw_update_set_extra_info_for_status_json_update_successful(); return true; } static void fw_update_task(void) { LOG_INFO("Firmware updating started, URL: %s", g_fw_update_cfg.url); adv_post_stop(); http_server_disable_ap_stopping_by_timeout(); if (!wifi_manager_is_ap_active()) { LOG_INFO("WiFi AP is not active - start WiFi AP"); wifi_manager_start_ap(); leds_indication_on_hotspot_activation(); } else { LOG_INFO("WiFi AP is already active"); } if (!fw_update_do_actions()) { LOG_ERR("Firmware updating failed"); g_fw_updating_reason = FW_UPDATE_REASON_NONE; } else { switch (g_fw_updating_reason) { case FW_UPDATE_REASON_NONE: LOG_INFO("Firmware updating completed successfully (unknown reason)"); break; case FW_UPDATE_REASON_AUTO: LOG_INFO("Firmware updating completed successfully (auto-updating)"); settings_write_flag_rebooting_after_auto_update(true); break; case FW_UPDATE_REASON_MANUAL_VIA_HOTSPOT: LOG_INFO("Firmware updating completed successfully (manual updating via WiFi hotspot)"); settings_write_flag_force_start_wifi_hotspot(true); break; case FW_UPDATE_REASON_MANUAL_VIA_LAN: LOG_INFO("Firmware updating completed successfully (manual updating via LAN)"); break; } LOG_INFO("Wait 5 seconds before reboot"); vTaskDelay(pdMS_TO_TICKS(FW_UPDATE_DELAY_BEFORE_REBOOT_MS)); } LOG_INFO("Restart system"); esp_restart(); } bool fw_update_is_url_valid(void) { const char url_prefix[] = "http"; if (0 != strncmp(g_fw_update_cfg.url, url_prefix, strlen(url_prefix))) { return false; } return true; } ATTR_PRINTF(1, 2) void fw_update_set_url(const char *const p_url_fmt, ...) { va_list ap; va_start(ap, p_url_fmt); vsnprintf(g_fw_update_cfg.url, sizeof(g_fw_update_cfg.url), p_url_fmt, ap); va_end(ap); } const char * fw_update_get_url(void) { return g_fw_update_cfg.url; } bool fw_update_run(const fw_updating_reason_e fw_updating_reason) { const uint32_t stack_size_for_fw_update_task = 6 * 1024; g_fw_updating_reason = fw_updating_reason; if (!os_task_create_finite_without_param(&fw_update_task, "fw_update_task", stack_size_for_fw_update_task, 1)) { LOG_ERR("Can't create thread"); g_fw_updating_reason = FW_UPDATE_REASON_NONE; return false; } return true; }
10892.c
/**************************************************************************** * net/icmpv6/icmpv6_autoconfig.c * * Copyright (C) 2015 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> #include <stdint.h> #include <string.h> #include <time.h> #include <errno.h> #include <debug.h> #include <net/ethernet.h> #include <nuttx/net/net.h> #include <nuttx/net/netdev.h> #include "devif/devif.h" #include "netdev/netdev.h" #include "icmpv6/icmpv6.h" #ifdef CONFIG_NET_ICMPv6_AUTOCONF /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #define CONFIG_ICMPv6_AUTOCONF_DELAYSEC \ (CONFIG_ICMPv6_AUTOCONF_DELAYMSEC / 1000) #define CONFIG_ICMPv6_AUTOCONF_DELAYNSEC \ ((CONFIG_ICMPv6_AUTOCONF_DELAYMSEC - 1000*CONFIG_ICMPv6_AUTOCONF_DELAYSEC) * 1000000) /**************************************************************************** * Private Types ****************************************************************************/ /* This structure holds the state of the send operation until it can be * operated upon from the interrupt level. */ struct icmpv6_router_s { FAR struct devif_callback_s *snd_cb; /* Reference to callback instance */ sem_t snd_sem; /* Used to wake up the waiting thread */ volatile bool snd_sent; /* True: if request sent */ bool snd_advertise; /* True: Send Neighbor Advertisement */ #ifdef CONFIG_NETDEV_MULTINIC uint8_t snd_ifname[IFNAMSIZ]; /* Interface name */ #endif int16_t snd_result; /* Result of the send */ }; /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: icmpv6_router_terminate ****************************************************************************/ static void icmpv6_router_terminate(FAR struct icmpv6_router_s *state, int result) { /* Don't allow any further call backs. */ state->snd_sent = true; state->snd_result = (int16_t)result; state->snd_cb->flags = 0; state->snd_cb->priv = NULL; state->snd_cb->event = NULL; /* Wake up the waiting thread */ sem_post(&state->snd_sem); } /**************************************************************************** * Name: icmpv6_router_interrupt ****************************************************************************/ static uint16_t icmpv6_router_interrupt(FAR struct net_driver_s *dev, FAR void *pvconn, FAR void *priv, uint16_t flags) { FAR struct icmpv6_router_s *state = (FAR struct icmpv6_router_s *)priv; ninfo("flags: %04x sent: %d\n", flags, state->snd_sent); if (state) { /* Check if the network is still up */ if ((flags & NETDEV_DOWN) != 0) { nerr("ERROR: Interface is down\n"); icmpv6_router_terminate(state, -ENETUNREACH); return flags; } /* Check if the outgoing packet is available. It may have been claimed * by a send interrupt serving a different thread -OR- if the output * buffer currently contains unprocessed incoming data. In these cases * we will just have to wait for the next polling cycle. */ else if (dev->d_sndlen > 0 || (flags & ICMPv6_NEWDATA) != 0) { /* Another thread has beat us sending data or the buffer is busy, * Check for a timeout. If not timed out, wait for the next * polling cycle and check again. */ /* REVISIT: No timeout. Just wait for the next polling cycle */ return flags; } /* It looks like we are good to send the data */ /* Copy the packet data into the device packet buffer and send it */ if (state->snd_advertise) { /* Send the ICMPv6 Neighbor Advertisement message */ icmpv6_advertise(dev, g_ipv6_allnodes); } else { /* Send the ICMPv6 Router Solicitation message */ icmpv6_rsolicit(dev); } /* Make sure no additional Router Solicitation overwrites this one. * This flag will be cleared in icmpv6_out(). */ IFF_SET_NOARP(dev->d_flags); /* Don't allow any further call backs. */ icmpv6_router_terminate(state, OK); } return flags; } /**************************************************************************** * Name: icmpv6_send_message * * Description: * Send an ICMPv6 Router Solicitation to resolve an IPv6 address. * * Parameters: * dev - The device to use to send the solicitation * advertise - True: Send the Neighbor Advertisement message * * Returned Value: * Zero (OK) is returned on success; On error a negated errno value is * returned. * * Assumptions: * The network is locked. * ****************************************************************************/ static int icmpv6_send_message(FAR struct net_driver_s *dev, bool advertise) { struct icmpv6_router_s state; int ret; /* Initialize the state structure. This is done with interrupts * disabled */ (void)sem_init(&state.snd_sem, 0, 0); /* Doesn't really fail */ #ifdef CONFIG_NETDEV_MULTINIC /* Remember the routing device name */ strncpy((FAR char *)state.snd_ifname, (FAR const char *)dev->d_ifname, IFNAMSIZ); #endif /* Allocate resources to receive a callback. This and the following * initialization is performed with the network lock because we don't * want anything to happen until we are ready. */ state.snd_cb = icmpv6_callback_alloc(dev); if (!state.snd_cb) { nerr("ERROR: Failed to allocate a cllback\n"); ret = -ENOMEM; goto errout_with_semaphore; } /* Arm the callback */ state.snd_sent = false; state.snd_result = -EBUSY; state.snd_advertise = advertise; state.snd_cb->flags = (ICMPv6_POLL | NETDEV_DOWN); state.snd_cb->priv = (FAR void *)&state; state.snd_cb->event = icmpv6_router_interrupt; /* Notify the device driver that new TX data is available. */ dev->d_txavail(dev); /* Wait for the send to complete or an error to occur: NOTES: (1) * net_lockedwait will also terminate if a signal is received, (2) * interrupts may be disabled! They will be re-enabled while the * task sleeps and automatically re-enabled when the task restarts. */ do { (void)net_lockedwait(&state.snd_sem); } while (!state.snd_sent); ret = state.snd_result; icmpv6_callback_free(dev, state.snd_cb); errout_with_semaphore: sem_destroy(&state.snd_sem); return ret; } /**************************************************************************** * Name: icmpv6_wait_radvertise * * Description: * Wait for the receipt of the Router Advertisement matching the Router * Solicitation that we just sent. * * Parameters: * dev - The device to use to send the solicitation * notify - The pre-initialized notification structure * save - We will need this to temporarily release the net lock * * Returned Value: * Zero (OK) is returned on success; On error a negated errno value is * returned. * * Assumptions: * The network is locked. * ****************************************************************************/ static int icmpv6_wait_radvertise(FAR struct net_driver_s *dev, FAR struct icmpv6_rnotify_s *notify, net_lock_t *save) { struct timespec delay; int ret; /* Wait for response to the Router Advertisement to be received. The * optimal delay would be the work case round trip time. * NOTE: The network is locked. */ delay.tv_sec = CONFIG_ICMPv6_AUTOCONF_DELAYSEC; delay.tv_nsec = CONFIG_ICMPv6_AUTOCONF_DELAYNSEC; ret = icmpv6_rwait(notify, &delay); /* icmpv6_wait will return OK if and only if the matching Router * Advertisement is received. Otherwise, it will return -ETIMEDOUT. */ return ret; } /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: icmpv6_autoconfig * * Description: * Perform IPv6 auto-configuration to assign an IPv6 address to this * device. * * Stateless auto-configuration exploits several other features in IPv6, * including link-local addresses, multi-casting, the Neighbor Discovery * protocol, and the ability to generate the interface identifier of an * address from the underlying data link layer address. The general idea * is to have a device generate a temporary address until it can determine * the characteristics of the network it is on, and then create a permanent * address it can use based on that information. * * Parameters: * dev - The device driver structure to assign the address to * * Return: * Zero (OK) is returned on success; A negated errno value is returned on * any failure. * ****************************************************************************/ int icmpv6_autoconfig(FAR struct net_driver_s *dev) { #ifndef CONFIG_NET_ETHERNET /* Only Ethernet supported for now */ nerr("ERROR: Only Ethernet is supported\n"); return -ENOSYS; #else /* CONFIG_NET_ETHERNET */ struct icmpv6_rnotify_s notify; net_ipv6addr_t lladdr; net_lock_t save; int retries; int ret; /* Sanity checks */ DEBUGASSERT(dev); ninfo("Auto-configuring %s\n", dev->d_ifname); #ifdef CONFIG_NET_MULTILINK /* Only Ethernet devices are supported for now */ if (dev->d_lltype != NET_LL_ETHERNET) { nerr("ERROR: Only Ethernet is supported\n"); return -ENOSYS; } #endif /* The interface should be in the down state */ save = net_lock(); netdev_ifdown(dev); net_unlock(save); /* IPv6 Stateless Autoconfiguration * Reference: http://www.tcpipguide.com/free/t_IPv6AutoconfigurationandRenumbering.htm * * The following is a summary of the steps a device takes when using * stateless auto-configuration: * * 1. Link-Local Address Generation: The device generates a link-local * address. Recall that this is one of the two types of local-use IPv6 * addresses. Link-local addresses have "1111 1110 10" for the first * ten bits. The generated address uses those ten bits followed by 54 * zeroes and then the 64 bit interface identifier. Typically this * will be derived from the data link layer (MAC) address. * * IEEE 802 MAC addresses, used by Ethernet and other IEEE 802 Project * networking technologies, have 48 bits. The IEEE has also defined a * format called the 64-bit extended unique identifier, abbreviated * EUI-64. To get the modified EUI-64 interface ID for a device, you * simply take the EUI-64 address and change the 7th bit from the left * (the"universal/local" or "U/L" bit) from a zero to a one. * * 128 112 96 80 64 48 32 16 * ---- ---- ---- ---- ---- ---- ---- ---- * fe80 0000 0000 0000 0000 xxxx xxxx xxxx */ lladdr[0] = HTONS(0xfe80); /* 10-bit address + 6 zeroes */ memset(&lladdr[1], 0, 4 * sizeof(uint16_t)); /* 64 more zeroes */ memcpy(&lladdr[5], dev->d_mac.ether_addr_octet, sizeof(struct ether_addr)); /* 48-bit Ethernet address */ ninfo("lladdr=%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x\n", lladdr[0], lladdr[1], lladdr[2], lladdr[3], lladdr[4], lladdr[6], lladdr[6], lladdr[7]); #ifdef CONFIG_NET_ICMPv6_NEIGHBOR /* Bring the interface up with no IP address */ save = net_lock(); netdev_ifup(dev); net_unlock(save); /* 2. Link-Local Address Uniqueness Test: The node tests to ensure that * the address it generated isn't for some reason already in use on the * local network. (This is very unlikely to be an issue if the link-local * address came from a MAC address but more likely if it was based on a * generated token.) It sends a Neighbor Solicitation message using the * Neighbor Discovery (ND) protocol. It then listens for a Neighbor * Advertisement in response that indicates that another device is * already using its link-local address; if so, either a new address * must be generated, or auto-configuration fails and another method * must be employed. */ ret = icmpv6_neighbor(lladdr); /* Take the interface back down */ save = net_lock(); netdev_ifdown(dev); net_unlock(save); if (ret == OK) { /* Hmmm... someone else responded to our Neighbor Solicitation. We * have not back-up plan in place. Just bail. */ nerr("ERROR: IP conflict\n"); return -EEXIST; } #endif /* 3. Link-Local Address Assignment: Assuming the uniqueness test passes, * the device assigns the link-local address to its IP interface. This * address can be used for communication on the local network, but not * on the wider Internet (since link-local addresses are not routed). */ save = net_lock(); net_ipv6addr_copy(dev->d_ipv6addr, lladdr); /* Bring the interface up with the new, temporary IP address */ netdev_ifup(dev); /* 4. Router Contact: The node next attempts to contact a local router for * more information on continuing the configuration. This is done either * by listening for Router Advertisement messages sent periodically by * routers, or by sending a specific Router Solicitation to ask a router * for information on what to do next. */ for (retries = 0; retries < CONFIG_ICMPv6_AUTOCONF_MAXTRIES; retries++) { /* Set up the Router Advertisement BEFORE we send the Router * Solicitation. */ icmpv6_rwait_setup(dev, &notify); /* Send the ICMPv6 Router solicitation message */ ret = icmpv6_send_message(dev, false); if (ret < 0) { nerr("ERROR: Failed send router solicitation: %d\n", ret); break; } /* Wait to receive the Router Advertisement message */ ret = icmpv6_wait_radvertise(dev, &notify, &save); if (ret != -ETIMEDOUT) { /* ETIMEDOUT is the only expected failure. We will retry on that * case only. */ break; } ninfo("Timed out... retrying %d\n", retries + 1); } /* Check for failures. Note: On successful return, the network will be * in the down state, but not in the event of failures. */ if (ret < 0) { nerr("ERROR: Failed to get the router advertisement: %d (retries=%d)\n", ret, retries); /* Claim the link local address as ours by sending the ICMPv6 Neighbor * Advertisement message. */ ret = icmpv6_send_message(dev, true); if (ret < 0) { nerr("ERROR: Failed send neighbor advertisement: %d\n", ret); netdev_ifdown(dev); } /* No off-link communications; No router address. */ net_ipv6addr_copy(dev->d_ipv6draddr, g_ipv6_allzeroaddr); /* Set a netmask for the local link address */ net_ipv6addr_copy(dev->d_ipv6netmask, g_ipv6_llnetmask); /* Leave the network up and return success (even though things did not * work out quite the way we wanted). */ net_unlock(save); return ret; } /* 5. Router Direction: The router provides direction to the node on how to * proceed with the auto-configuration. It may tell the node that on this * network "stateful" auto-configuration is in use, and tell it the * address of a DHCP server to use. Alternately, it will tell the host * how to determine its global Internet address. * * 6. Global Address Configuration: Assuming that stateless auto- * configuration is in use on the network, the host will configure * itself with its globally-unique Internet address. This address is * generally formed from a network prefix provided to the host by the * router, combined with the device's identifier as generated in the * first step. */ /* On success, the new address was already set (in icmpv_rnotify()). We * need only to bring the network back to the up state and return success. */ netdev_ifup(dev); net_unlock(save); return OK; #endif /* CONFIG_NET_ETHERNET */ } #endif /* CONFIG_NET_ICMPv6_AUTOCONF */
6044.c
/* CF3 Copyright (c) 2015 ishiura-lab. Released under the MIT license. https://github.com/ishiura-compiler/CF3/MIT-LICENSE.md */ #include<stdio.h> #include<stdint.h> #include<stdlib.h> #include"test1.h" static int16_t x21 = INT16_MIN; int32_t x22 = 585918; static volatile uint64_t t0 = 79058625325LLU; int8_t x33 = INT8_MAX; static volatile uint16_t x34 = 3641U; static int32_t x35 = 21; int32_t x105 = -165447; volatile int32_t t3 = -9729; uint8_t x231 = 1U; uint8_t x232 = 17U; int8_t x290 = -1; int32_t x292 = 0; volatile uint64_t t7 = 85666092LLU; uint64_t x497 = UINT64_MAX; int16_t x581 = -3770; uint32_t t9 = UINT32_MAX; uint32_t x598 = 3040668U; volatile uint32_t x657 = 105U; uint16_t x658 = UINT16_MAX; volatile uint32_t t12 = UINT32_MAX; uint8_t x740 = 13U; uint64_t x793 = 413805959LLU; volatile uint64_t t14 = 21891165185LLU; uint16_t x845 = UINT16_MAX; uint64_t x1397 = 17LLU; int32_t x1551 = INT32_MIN; uint32_t x1575 = 3675U; static uint8_t x1576 = 7U; int16_t x1744 = 0; int32_t t27 = 146; volatile uint64_t t28 = 65040958832995LLU; volatile uint8_t x1900 = 8U; static volatile int16_t x2083 = INT16_MAX; int32_t x2084 = 0; volatile uint64_t x2131 = UINT64_MAX; uint64_t x2132 = 8LLU; static int8_t x2136 = 1; uint8_t x2209 = 0U; int32_t x2211 = INT32_MIN; volatile uint32_t t38 = UINT32_MAX; uint8_t x2242 = 6U; volatile int8_t x2296 = 60; static uint32_t x2356 = 3U; int8_t x2413 = -1; int8_t x2416 = 22; int32_t x2432 = 41; uint64_t x2475 = UINT64_MAX; static int32_t x2567 = INT32_MAX; int32_t x2605 = INT32_MIN; volatile int64_t x2607 = INT64_MIN; int64_t x2614 = 510LL; volatile uint16_t x2616 = 1U; volatile uint32_t x2694 = 13318U; volatile uint64_t x2717 = UINT64_MAX; volatile uint8_t x2914 = 4U; volatile int64_t x3021 = -32286485771059614LL; int64_t x3022 = -1LL; volatile int16_t x3043 = 0; static int8_t x3044 = 24; int16_t x3150 = INT16_MAX; static uint64_t t60 = 495233986LLU; static volatile uint8_t x3196 = 1U; volatile uint64_t t61 = 15172LLU; uint32_t x3232 = 6U; uint64_t x3287 = 1LLU; static volatile uint32_t t68 = 156334884U; static int64_t x3357 = INT64_MAX; volatile int16_t x3421 = -1; static int8_t x3464 = 44; int64_t t71 = 34249206LL; int16_t x3466 = INT16_MIN; int8_t x3843 = -1; volatile uint64_t t76 = 3383883957962LLU; static volatile int64_t t77 = -978916549374LL; volatile int16_t x4033 = 0; volatile int32_t t78 = -3309580; int64_t x4114 = INT64_MAX; uint16_t x4115 = 7232U; uint16_t x4142 = 0U; uint8_t x4380 = 2U; volatile int64_t t87 = 4780038980LL; uint16_t x4510 = 142U; static volatile uint64_t x4511 = 1LLU; uint8_t x4530 = 0U; static int16_t x4531 = 22; uint8_t x4532 = 0U; uint64_t x4795 = 238870LLU; uint32_t x4796 = 44U; volatile uint32_t t93 = 548U; uint16_t x4863 = 4U; int32_t x5118 = INT32_MIN; volatile uint64_t t97 = 4570472791107653969LLU; volatile int8_t x5133 = INT8_MIN; uint64_t x5139 = 63837410266LLU; uint16_t x5150 = 506U; uint32_t t100 = 47949330U; static uint32_t x5183 = 45171073U; static volatile uint16_t x5424 = 0U; static volatile uint64_t t104 = 64724562329328264LLU; static int16_t x5718 = -1842; uint32_t x5733 = 31175U; volatile int32_t t107 = 50554582; uint32_t x5797 = UINT32_MAX; int8_t x5799 = INT8_MIN; static uint16_t x5919 = 14891U; uint64_t t111 = 11640417623452364LLU; static int8_t x5976 = 15; volatile uint32_t t114 = 858U; int64_t x6222 = -1269320322480584LL; static volatile int8_t x6223 = -29; static uint64_t t115 = 6LLU; int8_t x6457 = INT8_MAX; int8_t x6460 = 52; static uint8_t x6518 = UINT8_MAX; static volatile uint8_t x6520 = 25U; static volatile uint32_t x6543 = UINT32_MAX; static int8_t x6544 = 3; static int16_t x6701 = INT16_MIN; int32_t x6702 = -1; uint64_t t120 = 45872716895LLU; uint64_t t121 = 3557717113731684632LLU; int32_t x6775 = -1932; uint32_t x6950 = UINT32_MAX; int8_t x7092 = 1; uint32_t x7135 = 1U; volatile int32_t x7241 = INT32_MIN; static int16_t x7242 = INT16_MIN; volatile int64_t x7244 = 51LL; uint64_t t128 = 83390359LLU; volatile int64_t t131 = 1537815959881LL; int32_t x7489 = -1; uint64_t x7490 = 5LLU; uint64_t x7491 = UINT64_MAX; static uint64_t t134 = 858LLU; int64_t x7526 = -69855370LL; static volatile uint64_t x7527 = 8408206LLU; volatile int16_t x7596 = 13; uint16_t x7709 = UINT16_MAX; uint8_t x7736 = 5U; static uint32_t x7768 = 2U; volatile int16_t x7809 = INT16_MAX; uint64_t t145 = 6997013LLU; int64_t x7906 = INT64_MIN; static uint16_t x7908 = 0U; int64_t t148 = 834392LL; int16_t x8049 = -1; uint32_t t151 = 29962U; int8_t x8121 = INT8_MIN; uint64_t x8122 = 0LLU; static uint8_t x8251 = UINT8_MAX; uint32_t x8278 = 273334873U; int64_t t157 = -1793723673580367LL; volatile uint32_t t158 = 1820090414U; volatile uint32_t t159 = 3871U; uint64_t x8393 = UINT64_MAX; int64_t t161 = 907774254LL; volatile int32_t x8442 = INT32_MIN; volatile uint32_t x8527 = 1929789429U; volatile uint8_t x8593 = 17U; volatile uint32_t x8594 = 4897U; volatile uint64_t t166 = 1LLU; volatile int32_t x8728 = 14; uint8_t x8731 = 127U; uint16_t x8732 = 44U; int8_t x8740 = 1; int32_t x8816 = 27; static uint8_t x8821 = 1U; uint8_t x8951 = 4U; uint16_t x8952 = 2U; int64_t x8973 = -510676LL; uint32_t x9014 = UINT32_MAX; volatile int32_t x9150 = -1; uint8_t x9151 = 58U; int32_t x9253 = INT32_MAX; volatile uint32_t t180 = 38158573U; static uint16_t x9386 = UINT16_MAX; static volatile int16_t x9387 = INT16_MAX; uint16_t x9392 = 12U; volatile int64_t x9405 = -1393LL; int8_t x9406 = INT8_MIN; uint32_t x9407 = UINT32_MAX; uint32_t x9408 = 15U; int8_t x9486 = -1; volatile int8_t x9500 = 11; int64_t t187 = 383837LL; int8_t x9697 = INT8_MAX; int16_t x9699 = INT16_MIN; volatile uint64_t t189 = 1560054LLU; uint8_t x9733 = UINT8_MAX; static volatile int32_t t193 = -14478; volatile uint32_t x10077 = 203231785U; volatile uint32_t t198 = 56115033U; void f0(void) { static uint64_t x23 = 721107703LLU; uint8_t x24 = 13U; t0 = (((x21^x22)|x23)>>x24); if (t0 != 2251799813685243LLU) { NG(); } else { ; } } void f1(void) { int8_t x36 = 2; int32_t t1 = -5317157; t1 = (((x33^x34)|x35)>>x36); if (t1 != 917) { NG(); } else { ; } } void f2(void) { int16_t x106 = -354; volatile uint8_t x107 = 1U; volatile uint8_t x108 = 1U; int32_t t2 = -7240669; t2 = (((x105^x106)|x107)>>x108); if (t2 != 82835) { NG(); } else { ; } } void f3(void) { uint8_t x109 = 1U; int8_t x110 = INT8_MAX; static int16_t x111 = INT16_MAX; uint8_t x112 = 17U; t3 = (((x109^x110)|x111)>>x112); if (t3 != 0) { NG(); } else { ; } } void f4(void) { int8_t x229 = INT8_MIN; int32_t x230 = -1; int32_t t4 = -1412; t4 = (((x229^x230)|x231)>>x232); if (t4 != 0) { NG(); } else { ; } } void f5(void) { volatile int64_t x257 = -14LL; int64_t x258 = -350887LL; uint64_t x259 = UINT64_MAX; volatile uint8_t x260 = 0U; uint64_t t5 = UINT64_MAX; t5 = (((x257^x258)|x259)>>x260); if (t5 != UINT64_MAX) { NG(); } else { ; } } void f6(void) { int16_t x289 = INT16_MIN; volatile uint64_t x291 = 377LLU; volatile uint64_t t6 = 16938018090674695LLU; t6 = (((x289^x290)|x291)>>x292); if (t6 != 32767LLU) { NG(); } else { ; } } void f7(void) { uint64_t x441 = 4677685805LLU; int64_t x442 = -204896399364LL; int64_t x443 = -29LL; uint8_t x444 = 3U; t7 = (((x441^x442)|x443)>>x444); if (t7 != 2305843009213693950LLU) { NG(); } else { ; } } void f8(void) { int16_t x498 = -1; volatile int32_t x499 = INT32_MAX; uint8_t x500 = 5U; uint64_t t8 = 1531LLU; t8 = (((x497^x498)|x499)>>x500); if (t8 != 67108863LLU) { NG(); } else { ; } } void f9(void) { int16_t x582 = INT16_MIN; uint32_t x583 = UINT32_MAX; uint16_t x584 = 0U; t9 = (((x581^x582)|x583)>>x584); if (t9 != UINT32_MAX) { NG(); } else { ; } } void f10(void) { int8_t x597 = INT8_MAX; int8_t x599 = INT8_MAX; static int16_t x600 = 2; uint32_t t10 = 237U; t10 = (((x597^x598)|x599)>>x600); if (t10 != 760191U) { NG(); } else { ; } } void f11(void) { uint8_t x653 = 7U; uint8_t x654 = 6U; int8_t x655 = INT8_MAX; volatile uint8_t x656 = 3U; int32_t t11 = 12; t11 = (((x653^x654)|x655)>>x656); if (t11 != 15) { NG(); } else { ; } } void f12(void) { uint32_t x659 = UINT32_MAX; volatile int16_t x660 = 0; t12 = (((x657^x658)|x659)>>x660); if (t12 != UINT32_MAX) { NG(); } else { ; } } void f13(void) { int8_t x737 = 14; int32_t x738 = 2226124; static uint8_t x739 = 5U; static int32_t t13 = -10932612; t13 = (((x737^x738)|x739)>>x740); if (t13 != 271) { NG(); } else { ; } } void f14(void) { volatile int64_t x794 = INT64_MIN; int64_t x795 = INT64_MIN; static int16_t x796 = 2; t14 = (((x793^x794)|x795)>>x796); if (t14 != 2305843009317145441LLU) { NG(); } else { ; } } void f15(void) { uint8_t x846 = UINT8_MAX; uint64_t x847 = UINT64_MAX; int32_t x848 = 1; volatile uint64_t t15 = 128961088875577LLU; t15 = (((x845^x846)|x847)>>x848); if (t15 != 9223372036854775807LLU) { NG(); } else { ; } } void f16(void) { static int8_t x873 = INT8_MIN; uint32_t x874 = 190222U; static volatile int8_t x875 = INT8_MIN; int16_t x876 = 1; volatile uint32_t t16 = 897844791U; t16 = (((x873^x874)|x875)>>x876); if (t16 != 2147483591U) { NG(); } else { ; } } void f17(void) { uint64_t x953 = 26LLU; int32_t x954 = INT32_MIN; int32_t x955 = -6206; int8_t x956 = 4; static uint64_t t17 = 12270780366LLU; t17 = (((x953^x954)|x955)>>x956); if (t17 != 1152921504606846589LLU) { NG(); } else { ; } } void f18(void) { int16_t x1017 = 0; uint64_t x1018 = 46LLU; static uint32_t x1019 = 5707U; int8_t x1020 = 1; volatile uint64_t t18 = 107999LLU; t18 = (((x1017^x1018)|x1019)>>x1020); if (t18 != 2871LLU) { NG(); } else { ; } } void f19(void) { static uint64_t x1077 = UINT64_MAX; uint64_t x1078 = UINT64_MAX; volatile int32_t x1079 = INT32_MAX; int8_t x1080 = 0; volatile uint64_t t19 = 43350836LLU; t19 = (((x1077^x1078)|x1079)>>x1080); if (t19 != 2147483647LLU) { NG(); } else { ; } } void f20(void) { uint64_t x1149 = UINT64_MAX; uint8_t x1150 = 18U; volatile int8_t x1151 = -1; volatile int64_t x1152 = 7LL; uint64_t t20 = 810820587469LLU; t20 = (((x1149^x1150)|x1151)>>x1152); if (t20 != 144115188075855871LLU) { NG(); } else { ; } } void f21(void) { uint64_t x1173 = UINT64_MAX; uint16_t x1174 = 2927U; int64_t x1175 = INT64_MIN; static volatile int16_t x1176 = 39; static uint64_t t21 = 233686027LLU; t21 = (((x1173^x1174)|x1175)>>x1176); if (t21 != 33554431LLU) { NG(); } else { ; } } void f22(void) { volatile int8_t x1398 = INT8_MIN; int16_t x1399 = 460; int8_t x1400 = 1; volatile uint64_t t22 = 5839476LLU; t22 = (((x1397^x1398)|x1399)>>x1400); if (t22 != 9223372036854775790LLU) { NG(); } else { ; } } void f23(void) { static int64_t x1481 = INT64_MAX; int8_t x1482 = 0; uint32_t x1483 = 56U; uint64_t x1484 = 1LLU; volatile int64_t t23 = -7266929425769LL; t23 = (((x1481^x1482)|x1483)>>x1484); if (t23 != 4611686018427387903LL) { NG(); } else { ; } } void f24(void) { uint64_t x1549 = UINT64_MAX; int64_t x1550 = INT64_MAX; uint8_t x1552 = 26U; volatile uint64_t t24 = 943861238LLU; t24 = (((x1549^x1550)|x1551)>>x1552); if (t24 != 274877906912LLU) { NG(); } else { ; } } void f25(void) { int8_t x1573 = INT8_MIN; uint32_t x1574 = 435U; volatile uint32_t t25 = 66680U; t25 = (((x1573^x1574)|x1575)>>x1576); if (t25 != 33554428U) { NG(); } else { ; } } void f26(void) { static uint64_t x1741 = 860023568LLU; int16_t x1742 = INT16_MIN; uint16_t x1743 = 25340U; volatile uint64_t t26 = 13813234774LLU; t26 = (((x1741^x1742)|x1743)>>x1744); if (t26 != 18446744072849550332LLU) { NG(); } else { ; } } void f27(void) { static int32_t x1761 = 29; volatile uint16_t x1762 = 1U; uint16_t x1763 = 14U; static uint16_t x1764 = 26U; t27 = (((x1761^x1762)|x1763)>>x1764); if (t27 != 0) { NG(); } else { ; } } void f28(void) { int64_t x1781 = -1LL; uint64_t x1782 = 570222LLU; static uint64_t x1783 = 1802LLU; int16_t x1784 = 24; t28 = (((x1781^x1782)|x1783)>>x1784); if (t28 != 1099511627775LLU) { NG(); } else { ; } } void f29(void) { uint64_t x1897 = UINT64_MAX; uint8_t x1898 = UINT8_MAX; static int32_t x1899 = INT32_MIN; uint64_t t29 = 17557LLU; t29 = (((x1897^x1898)|x1899)>>x1900); if (t29 != 72057594037927935LLU) { NG(); } else { ; } } void f30(void) { static uint8_t x1905 = 3U; volatile uint64_t x1906 = 17448439133825LLU; int8_t x1907 = INT8_MIN; int32_t x1908 = 1; volatile uint64_t t30 = 27274317LLU; t30 = (((x1905^x1906)|x1907)>>x1908); if (t30 != 9223372036854775745LLU) { NG(); } else { ; } } void f31(void) { volatile uint16_t x1921 = 31464U; volatile uint8_t x1922 = 1U; uint32_t x1923 = 2409737U; int8_t x1924 = 0; uint32_t t31 = 8775373U; t31 = (((x1921^x1922)|x1923)>>x1924); if (t31 != 2424809U) { NG(); } else { ; } } void f32(void) { uint64_t x2069 = 0LLU; volatile int32_t x2070 = INT32_MIN; uint8_t x2071 = 3U; uint16_t x2072 = 1U; uint64_t t32 = 15437049326LLU; t32 = (((x2069^x2070)|x2071)>>x2072); if (t32 != 9223372035781033985LLU) { NG(); } else { ; } } void f33(void) { int32_t x2081 = INT32_MAX; volatile uint8_t x2082 = 30U; static int32_t t33 = INT32_MAX; t33 = (((x2081^x2082)|x2083)>>x2084); if (t33 != INT32_MAX) { NG(); } else { ; } } void f34(void) { volatile int64_t x2121 = 431026150LL; static uint64_t x2122 = 47785357732LLU; volatile uint16_t x2123 = UINT16_MAX; volatile uint16_t x2124 = 31U; volatile uint64_t t34 = 398000769410067LLU; t34 = (((x2121^x2122)|x2123)>>x2124); if (t34 != 22LLU) { NG(); } else { ; } } void f35(void) { volatile uint32_t x2129 = 2539U; int32_t x2130 = 209290180; uint64_t t35 = 64450596LLU; t35 = (((x2129^x2130)|x2131)>>x2132); if (t35 != 72057594037927935LLU) { NG(); } else { ; } } void f36(void) { uint32_t x2133 = UINT32_MAX; int8_t x2134 = 33; int32_t x2135 = INT32_MIN; volatile uint32_t t36 = 24642U; t36 = (((x2133^x2134)|x2135)>>x2136); if (t36 != 2147483631U) { NG(); } else { ; } } void f37(void) { int8_t x2153 = INT8_MIN; volatile uint64_t x2154 = 118976794917LLU; int16_t x2155 = INT16_MAX; volatile int16_t x2156 = 0; static uint64_t t37 = 1958LLU; t37 = (((x2153^x2154)|x2155)>>x2156); if (t37 != 18446743954732777471LLU) { NG(); } else { ; } } void f38(void) { uint32_t x2210 = UINT32_MAX; int32_t x2212 = 0; t38 = (((x2209^x2210)|x2211)>>x2212); if (t38 != UINT32_MAX) { NG(); } else { ; } } void f39(void) { uint32_t x2241 = 1U; int32_t x2243 = INT32_MAX; volatile uint8_t x2244 = 5U; static volatile uint32_t t39 = 58288171U; t39 = (((x2241^x2242)|x2243)>>x2244); if (t39 != 67108863U) { NG(); } else { ; } } void f40(void) { volatile int8_t x2293 = INT8_MIN; int64_t x2294 = INT64_MIN; uint8_t x2295 = 16U; volatile int64_t t40 = 105832286039665210LL; t40 = (((x2293^x2294)|x2295)>>x2296); if (t40 != 7LL) { NG(); } else { ; } } void f41(void) { uint32_t x2297 = 707492U; int16_t x2298 = -1; uint32_t x2299 = 1562499186U; uint32_t x2300 = 1U; static volatile uint32_t t41 = 96277008U; t41 = (((x2297^x2298)|x2299)>>x2300); if (t41 != 2147155517U) { NG(); } else { ; } } void f42(void) { uint64_t x2353 = UINT64_MAX; int64_t x2354 = -1LL; volatile int64_t x2355 = INT64_MAX; uint64_t t42 = 4055779595LLU; t42 = (((x2353^x2354)|x2355)>>x2356); if (t42 != 1152921504606846975LLU) { NG(); } else { ; } } void f43(void) { int8_t x2414 = INT8_MIN; volatile int8_t x2415 = 2; int32_t t43 = -72661; t43 = (((x2413^x2414)|x2415)>>x2416); if (t43 != 0) { NG(); } else { ; } } void f44(void) { volatile uint64_t x2429 = 2685118LLU; uint16_t x2430 = UINT16_MAX; volatile int64_t x2431 = INT64_MIN; uint64_t t44 = 14869878LLU; t44 = (((x2429^x2430)|x2431)>>x2432); if (t44 != 4194304LLU) { NG(); } else { ; } } void f45(void) { static int32_t x2473 = INT32_MIN; static volatile uint64_t x2474 = UINT64_MAX; volatile uint8_t x2476 = 29U; uint64_t t45 = 198980422119948940LLU; t45 = (((x2473^x2474)|x2475)>>x2476); if (t45 != 34359738367LLU) { NG(); } else { ; } } void f46(void) { volatile uint8_t x2489 = 0U; volatile int64_t x2490 = INT64_MAX; static uint32_t x2491 = UINT32_MAX; volatile uint8_t x2492 = 44U; int64_t t46 = -470781380584875LL; t46 = (((x2489^x2490)|x2491)>>x2492); if (t46 != 524287LL) { NG(); } else { ; } } void f47(void) { volatile int16_t x2565 = -25; int64_t x2566 = INT64_MIN; uint64_t x2568 = 27LLU; int64_t t47 = -17094315885651776LL; t47 = (((x2565^x2566)|x2567)>>x2568); if (t47 != 68719476735LL) { NG(); } else { ; } } void f48(void) { volatile int16_t x2581 = INT16_MIN; int32_t x2582 = -1; uint16_t x2583 = 0U; volatile int64_t x2584 = 26LL; int32_t t48 = 9912615; t48 = (((x2581^x2582)|x2583)>>x2584); if (t48 != 0) { NG(); } else { ; } } void f49(void) { volatile uint64_t x2606 = UINT64_MAX; volatile int64_t x2608 = 0LL; volatile uint64_t t49 = 795614331LLU; t49 = (((x2605^x2606)|x2607)>>x2608); if (t49 != 9223372039002259455LLU) { NG(); } else { ; } } void f50(void) { volatile uint16_t x2613 = 0U; uint16_t x2615 = 1U; int64_t t50 = 96239431LL; t50 = (((x2613^x2614)|x2615)>>x2616); if (t50 != 255LL) { NG(); } else { ; } } void f51(void) { int8_t x2693 = INT8_MAX; uint16_t x2695 = 7338U; int16_t x2696 = 0; static volatile uint32_t t51 = 235257501U; t51 = (((x2693^x2694)|x2695)>>x2696); if (t51 != 15611U) { NG(); } else { ; } } void f52(void) { uint32_t x2718 = UINT32_MAX; uint32_t x2719 = 24177U; int16_t x2720 = 7; volatile uint64_t t52 = 999172775445002136LLU; t52 = (((x2717^x2718)|x2719)>>x2720); if (t52 != 144115188042301628LLU) { NG(); } else { ; } } void f53(void) { uint64_t x2789 = UINT64_MAX; uint32_t x2790 = 1U; int16_t x2791 = INT16_MAX; volatile int8_t x2792 = 1; static uint64_t t53 = 5LLU; t53 = (((x2789^x2790)|x2791)>>x2792); if (t53 != 9223372036854775807LLU) { NG(); } else { ; } } void f54(void) { volatile uint8_t x2913 = UINT8_MAX; int32_t x2915 = INT32_MAX; uint16_t x2916 = 2U; static volatile int32_t t54 = 150307516; t54 = (((x2913^x2914)|x2915)>>x2916); if (t54 != 536870911) { NG(); } else { ; } } void f55(void) { static int64_t x2969 = INT64_MIN; volatile int64_t x2970 = INT64_MIN; static uint32_t x2971 = 1695557U; static volatile uint16_t x2972 = 56U; int64_t t55 = 271440187946LL; t55 = (((x2969^x2970)|x2971)>>x2972); if (t55 != 0LL) { NG(); } else { ; } } void f56(void) { uint32_t x3023 = 137396542U; static int16_t x3024 = 47; int64_t t56 = -1248869826796116LL; t56 = (((x3021^x3022)|x3023)>>x3024); if (t56 != 229LL) { NG(); } else { ; } } void f57(void) { uint8_t x3029 = 18U; uint32_t x3030 = UINT32_MAX; int8_t x3031 = INT8_MAX; uint8_t x3032 = 3U; uint32_t t57 = 825831358U; t57 = (((x3029^x3030)|x3031)>>x3032); if (t57 != 536870911U) { NG(); } else { ; } } void f58(void) { uint8_t x3041 = UINT8_MAX; static volatile uint64_t x3042 = 1049935352299235947LLU; volatile uint64_t t58 = 22977707268LLU; t58 = (((x3041^x3042)|x3043)>>x3044); if (t58 != 62581023710LLU) { NG(); } else { ; } } void f59(void) { volatile int8_t x3057 = INT8_MIN; uint32_t x3058 = UINT32_MAX; int32_t x3059 = INT32_MIN; uint32_t x3060 = 7U; uint32_t t59 = 19U; t59 = (((x3057^x3058)|x3059)>>x3060); if (t59 != 16777216U) { NG(); } else { ; } } void f60(void) { static volatile uint64_t x3149 = 28450078309748LLU; int64_t x3151 = INT64_MIN; uint16_t x3152 = 0U; t60 = (((x3149^x3150)|x3151)>>x3152); if (t60 != 9223400486933086859LLU) { NG(); } else { ; } } void f61(void) { static volatile int16_t x3193 = -1153; uint64_t x3194 = 168LLU; int16_t x3195 = INT16_MIN; t61 = (((x3193^x3194)|x3195)>>x3196); if (t61 != 9223372036854775275LLU) { NG(); } else { ; } } void f62(void) { int16_t x3225 = 36; volatile int32_t x3226 = 0; uint8_t x3227 = 71U; static volatile uint16_t x3228 = 1U; int32_t t62 = 149; t62 = (((x3225^x3226)|x3227)>>x3228); if (t62 != 51) { NG(); } else { ; } } void f63(void) { uint8_t x3229 = 66U; static uint32_t x3230 = UINT32_MAX; static volatile uint64_t x3231 = 61402684LLU; volatile uint64_t t63 = 402282117LLU; t63 = (((x3229^x3230)|x3231)>>x3232); if (t63 != 67108862LLU) { NG(); } else { ; } } void f64(void) { static int64_t x3241 = 1233797712336350186LL; static int32_t x3242 = INT32_MAX; volatile int8_t x3243 = 1; uint32_t x3244 = 1U; int64_t t64 = 8LL; t64 = (((x3241^x3242)|x3243)>>x3244); if (t64 != 616898857233566218LL) { NG(); } else { ; } } void f65(void) { int8_t x3261 = INT8_MAX; static int64_t x3262 = INT64_MAX; int16_t x3263 = INT16_MAX; uint16_t x3264 = 0U; int64_t t65 = INT64_MAX; t65 = (((x3261^x3262)|x3263)>>x3264); if (t65 != INT64_MAX) { NG(); } else { ; } } void f66(void) { uint16_t x3285 = 13U; int16_t x3286 = -1; int32_t x3288 = 3; uint64_t t66 = 18539LLU; t66 = (((x3285^x3286)|x3287)>>x3288); if (t66 != 2305843009213693950LLU) { NG(); } else { ; } } void f67(void) { uint64_t x3289 = UINT64_MAX; int16_t x3290 = 15; volatile uint8_t x3291 = 16U; uint8_t x3292 = 60U; static uint64_t t67 = 326365714LLU; t67 = (((x3289^x3290)|x3291)>>x3292); if (t67 != 15LLU) { NG(); } else { ; } } void f68(void) { uint16_t x3325 = 815U; uint32_t x3326 = 510U; uint32_t x3327 = UINT32_MAX; volatile uint8_t x3328 = 3U; t68 = (((x3325^x3326)|x3327)>>x3328); if (t68 != 536870911U) { NG(); } else { ; } } void f69(void) { static volatile uint64_t x3358 = UINT64_MAX; volatile int64_t x3359 = INT64_MAX; uint64_t x3360 = 0LLU; uint64_t t69 = UINT64_MAX; t69 = (((x3357^x3358)|x3359)>>x3360); if (t69 != UINT64_MAX) { NG(); } else { ; } } void f70(void) { static int32_t x3422 = -886082905; uint64_t x3423 = 19181227730960LLU; volatile int8_t x3424 = 30; uint64_t t70 = 180495408LLU; t70 = (((x3421^x3422)|x3423)>>x3424); if (t70 != 17863LLU) { NG(); } else { ; } } void f71(void) { static uint32_t x3461 = 5U; uint8_t x3462 = 3U; int64_t x3463 = INT64_MAX; t71 = (((x3461^x3462)|x3463)>>x3464); if (t71 != 524287LL) { NG(); } else { ; } } void f72(void) { uint32_t x3465 = UINT32_MAX; uint8_t x3467 = 84U; int16_t x3468 = 0; uint32_t t72 = 3U; t72 = (((x3465^x3466)|x3467)>>x3468); if (t72 != 32767U) { NG(); } else { ; } } void f73(void) { uint8_t x3649 = 0U; uint16_t x3650 = UINT16_MAX; volatile int64_t x3651 = 2270757837924311918LL; uint8_t x3652 = 3U; int64_t t73 = -1217LL; t73 = (((x3649^x3650)|x3651)>>x3652); if (t73 != 283844729740541951LL) { NG(); } else { ; } } void f74(void) { volatile uint64_t x3705 = UINT64_MAX; uint16_t x3706 = 54U; volatile uint64_t x3707 = 26LLU; uint16_t x3708 = 2U; static uint64_t t74 = 5415932689444375LLU; t74 = (((x3705^x3706)|x3707)>>x3708); if (t74 != 4611686018427387894LLU) { NG(); } else { ; } } void f75(void) { uint16_t x3841 = UINT16_MAX; uint64_t x3842 = UINT64_MAX; uint32_t x3844 = 5U; uint64_t t75 = 3247273729LLU; t75 = (((x3841^x3842)|x3843)>>x3844); if (t75 != 576460752303423487LLU) { NG(); } else { ; } } void f76(void) { static uint64_t x3865 = UINT64_MAX; int8_t x3866 = INT8_MIN; int32_t x3867 = INT32_MIN; int16_t x3868 = 0; t76 = (((x3865^x3866)|x3867)>>x3868); if (t76 != 18446744071562068095LLU) { NG(); } else { ; } } void f77(void) { static int64_t x3929 = INT64_MIN; volatile int64_t x3930 = -1LL; int8_t x3931 = 0; int8_t x3932 = 3; t77 = (((x3929^x3930)|x3931)>>x3932); if (t77 != 1152921504606846975LL) { NG(); } else { ; } } void f78(void) { int32_t x4034 = 0; volatile int16_t x4035 = INT16_MAX; uint32_t x4036 = 4U; t78 = (((x4033^x4034)|x4035)>>x4036); if (t78 != 2047) { NG(); } else { ; } } void f79(void) { volatile int32_t x4053 = INT32_MAX; uint64_t x4054 = 230849298250391LLU; static int32_t x4055 = INT32_MIN; static int16_t x4056 = 63; uint64_t t79 = 202860716LLU; t79 = (((x4053^x4054)|x4055)>>x4056); if (t79 != 1LLU) { NG(); } else { ; } } void f80(void) { int64_t x4065 = INT64_MIN; int32_t x4066 = INT32_MIN; int8_t x4067 = 1; volatile int8_t x4068 = 1; static int64_t t80 = 1074608340787LL; t80 = (((x4065^x4066)|x4067)>>x4068); if (t80 != 4611686017353646080LL) { NG(); } else { ; } } void f81(void) { volatile int64_t x4073 = INT64_MIN; uint64_t x4074 = 1403540896LLU; int16_t x4075 = INT16_MIN; static uint16_t x4076 = 61U; volatile uint64_t t81 = 58699573089173746LLU; t81 = (((x4073^x4074)|x4075)>>x4076); if (t81 != 7LLU) { NG(); } else { ; } } void f82(void) { uint64_t x4113 = UINT64_MAX; volatile uint8_t x4116 = 52U; volatile uint64_t t82 = 13723LLU; t82 = (((x4113^x4114)|x4115)>>x4116); if (t82 != 2048LLU) { NG(); } else { ; } } void f83(void) { static uint64_t x4141 = UINT64_MAX; static int16_t x4143 = INT16_MAX; uint8_t x4144 = 0U; static uint64_t t83 = UINT64_MAX; t83 = (((x4141^x4142)|x4143)>>x4144); if (t83 != UINT64_MAX) { NG(); } else { ; } } void f84(void) { int16_t x4313 = 5; volatile uint64_t x4314 = UINT64_MAX; int32_t x4315 = 191110; uint16_t x4316 = 0U; uint64_t t84 = 108364804LLU; t84 = (((x4313^x4314)|x4315)>>x4316); if (t84 != 18446744073709551614LLU) { NG(); } else { ; } } void f85(void) { int64_t x4317 = INT64_MIN; uint64_t x4318 = UINT64_MAX; uint32_t x4319 = UINT32_MAX; uint32_t x4320 = 15U; volatile uint64_t t85 = 74431029171LLU; t85 = (((x4317^x4318)|x4319)>>x4320); if (t85 != 281474976710655LLU) { NG(); } else { ; } } void f86(void) { uint8_t x4377 = UINT8_MAX; int16_t x4378 = 0; volatile uint16_t x4379 = 652U; int32_t t86 = -114356418; t86 = (((x4377^x4378)|x4379)>>x4380); if (t86 != 191) { NG(); } else { ; } } void f87(void) { volatile int8_t x4385 = 10; int8_t x4386 = 22; int64_t x4387 = 944LL; uint32_t x4388 = 0U; t87 = (((x4385^x4386)|x4387)>>x4388); if (t87 != 956LL) { NG(); } else { ; } } void f88(void) { int64_t x4505 = -101910250LL; int64_t x4506 = INT64_MIN; volatile uint64_t x4507 = UINT64_MAX; int8_t x4508 = 1; volatile uint64_t t88 = 1063210793109795447LLU; t88 = (((x4505^x4506)|x4507)>>x4508); if (t88 != 9223372036854775807LLU) { NG(); } else { ; } } void f89(void) { uint16_t x4509 = 2U; uint8_t x4512 = 57U; static volatile uint64_t t89 = 136LLU; t89 = (((x4509^x4510)|x4511)>>x4512); if (t89 != 0LLU) { NG(); } else { ; } } void f90(void) { static int16_t x4529 = 5573; int32_t t90 = -2; t90 = (((x4529^x4530)|x4531)>>x4532); if (t90 != 5591) { NG(); } else { ; } } void f91(void) { int8_t x4749 = -1; int32_t x4750 = INT32_MIN; uint16_t x4751 = UINT16_MAX; static uint16_t x4752 = 5U; volatile int32_t t91 = 323157212; t91 = (((x4749^x4750)|x4751)>>x4752); if (t91 != 67108863) { NG(); } else { ; } } void f92(void) { static uint16_t x4793 = UINT16_MAX; static uint64_t x4794 = 347524762797852LLU; uint64_t t92 = 6006473283211089LLU; t92 = (((x4793^x4794)|x4795)>>x4796); if (t92 != 19LLU) { NG(); } else { ; } } void f93(void) { int32_t x4849 = INT32_MIN; uint8_t x4850 = 4U; static uint32_t x4851 = 119021U; static volatile uint8_t x4852 = 14U; t93 = (((x4849^x4850)|x4851)>>x4852); if (t93 != 131079U) { NG(); } else { ; } } void f94(void) { uint64_t x4861 = UINT64_MAX; uint8_t x4862 = UINT8_MAX; uint8_t x4864 = 0U; uint64_t t94 = 6982502995626265715LLU; t94 = (((x4861^x4862)|x4863)>>x4864); if (t94 != 18446744073709551364LLU) { NG(); } else { ; } } void f95(void) { uint32_t x4945 = 14U; uint64_t x4946 = UINT64_MAX; int64_t x4947 = INT64_MAX; volatile uint8_t x4948 = 20U; volatile uint64_t t95 = 262825521LLU; t95 = (((x4945^x4946)|x4947)>>x4948); if (t95 != 17592186044415LLU) { NG(); } else { ; } } void f96(void) { static uint32_t x5093 = 27852910U; volatile uint16_t x5094 = UINT16_MAX; static int32_t x5095 = INT32_MAX; volatile uint16_t x5096 = 0U; volatile uint32_t t96 = 194497U; t96 = (((x5093^x5094)|x5095)>>x5096); if (t96 != 2147483647U) { NG(); } else { ; } } void f97(void) { static int16_t x5117 = INT16_MIN; uint64_t x5119 = 2097618984LLU; volatile uint32_t x5120 = 2U; t97 = (((x5117^x5118)|x5119)>>x5120); if (t97 != 536864778LLU) { NG(); } else { ; } } void f98(void) { uint8_t x5134 = 45U; uint32_t x5135 = 1U; uint32_t x5136 = 2U; uint32_t t98 = 760U; t98 = (((x5133^x5134)|x5135)>>x5136); if (t98 != 1073741803U) { NG(); } else { ; } } void f99(void) { volatile int32_t x5137 = 1020; volatile int64_t x5138 = INT64_MAX; int32_t x5140 = 9; uint64_t t99 = 3828906041024LLU; t99 = (((x5137^x5138)|x5139)>>x5140); if (t99 != 18014398509481983LLU) { NG(); } else { ; } } void f100(void) { uint32_t x5149 = 1090736U; uint8_t x5151 = 22U; volatile uint8_t x5152 = 12U; t100 = (((x5149^x5150)|x5151)>>x5152); if (t100 != 266U) { NG(); } else { ; } } void f101(void) { uint16_t x5181 = 527U; static int8_t x5182 = INT8_MAX; uint8_t x5184 = 1U; static volatile uint32_t t101 = 165U; t101 = (((x5181^x5182)|x5183)>>x5184); if (t101 != 22585848U) { NG(); } else { ; } } void f102(void) { int8_t x5213 = INT8_MIN; int64_t x5214 = -77499LL; uint32_t x5215 = 1U; volatile uint8_t x5216 = 1U; static int64_t t102 = -19330506093103310LL; t102 = (((x5213^x5214)|x5215)>>x5216); if (t102 != 38754LL) { NG(); } else { ; } } void f103(void) { int8_t x5421 = -1; int16_t x5422 = -1; uint64_t x5423 = 56165902158283LLU; static uint64_t t103 = 172090127LLU; t103 = (((x5421^x5422)|x5423)>>x5424); if (t103 != 56165902158283LLU) { NG(); } else { ; } } void f104(void) { int16_t x5589 = -6722; uint16_t x5590 = 58U; uint64_t x5591 = 59LLU; static uint8_t x5592 = 1U; t104 = (((x5589^x5590)|x5591)>>x5592); if (t104 != 9223372036854772447LLU) { NG(); } else { ; } } void f105(void) { int16_t x5717 = INT16_MIN; uint16_t x5719 = 428U; volatile uint8_t x5720 = 13U; int32_t t105 = -1; t105 = (((x5717^x5718)|x5719)>>x5720); if (t105 != 3) { NG(); } else { ; } } void f106(void) { static uint8_t x5734 = UINT8_MAX; volatile uint64_t x5735 = UINT64_MAX; uint8_t x5736 = 17U; volatile uint64_t t106 = 998152631LLU; t106 = (((x5733^x5734)|x5735)>>x5736); if (t106 != 140737488355327LLU) { NG(); } else { ; } } void f107(void) { static uint16_t x5749 = 944U; uint8_t x5750 = 27U; uint8_t x5751 = UINT8_MAX; volatile uint8_t x5752 = 3U; t107 = (((x5749^x5750)|x5751)>>x5752); if (t107 != 127) { NG(); } else { ; } } void f108(void) { volatile uint64_t x5798 = 124354849588274LLU; int32_t x5800 = 0; volatile uint64_t t108 = 5LLU; t108 = (((x5797^x5798)|x5799)>>x5800); if (t108 != 18446744073709551565LLU) { NG(); } else { ; } } void f109(void) { static int16_t x5917 = INT16_MAX; int32_t x5918 = INT32_MAX; uint8_t x5920 = 7U; int32_t t109 = 139; t109 = (((x5917^x5918)|x5919)>>x5920); if (t109 != 16777076) { NG(); } else { ; } } void f110(void) { static uint32_t x5937 = UINT32_MAX; static int8_t x5938 = INT8_MIN; uint32_t x5939 = UINT32_MAX; int32_t x5940 = 0; volatile uint32_t t110 = UINT32_MAX; t110 = (((x5937^x5938)|x5939)>>x5940); if (t110 != UINT32_MAX) { NG(); } else { ; } } void f111(void) { volatile int32_t x5953 = INT32_MIN; volatile int16_t x5954 = -1; uint64_t x5955 = 2239568512525606LLU; volatile uint8_t x5956 = 26U; t111 = (((x5953^x5954)|x5955)>>x5956); if (t111 != 33372191LLU) { NG(); } else { ; } } void f112(void) { static uint32_t x5973 = 234U; int32_t x5974 = INT32_MAX; int16_t x5975 = -1; uint32_t t112 = 2040716496U; t112 = (((x5973^x5974)|x5975)>>x5976); if (t112 != 131071U) { NG(); } else { ; } } void f113(void) { static int16_t x6185 = INT16_MIN; uint64_t x6186 = 229123549877LLU; volatile uint64_t x6187 = 3069267690LLU; volatile uint8_t x6188 = 1U; uint64_t t113 = 80928LLU; t113 = (((x6185^x6186)|x6187)>>x6188); if (t113 != 9223371922434078591LLU) { NG(); } else { ; } } void f114(void) { int8_t x6213 = INT8_MIN; volatile uint32_t x6214 = UINT32_MAX; uint16_t x6215 = UINT16_MAX; volatile uint8_t x6216 = 7U; t114 = (((x6213^x6214)|x6215)>>x6216); if (t114 != 511U) { NG(); } else { ; } } void f115(void) { uint64_t x6221 = 1208035961491LLU; uint16_t x6224 = 1U; t115 = (((x6221^x6222)|x6223)>>x6224); if (t115 != 9223372036854775797LLU) { NG(); } else { ; } } void f116(void) { int64_t x6458 = INT64_MAX; static uint32_t x6459 = 144941U; volatile int64_t t116 = -19241086LL; t116 = (((x6457^x6458)|x6459)>>x6460); if (t116 != 2047LL) { NG(); } else { ; } } void f117(void) { volatile int64_t x6517 = 15225858681093LL; uint16_t x6519 = UINT16_MAX; int64_t t117 = -202LL; t117 = (((x6517^x6518)|x6519)>>x6520); if (t117 != 453765LL) { NG(); } else { ; } } void f118(void) { uint32_t x6541 = 898832U; uint64_t x6542 = 12025395886170859LLU; uint64_t t118 = 48668367023424025LLU; t118 = (((x6541^x6542)|x6543)>>x6544); if (t118 != 1503174665961471LLU) { NG(); } else { ; } } void f119(void) { int64_t x6703 = INT64_MAX; int8_t x6704 = 1; int64_t t119 = 23023468888867LL; t119 = (((x6701^x6702)|x6703)>>x6704); if (t119 != 4611686018427387903LL) { NG(); } else { ; } } void f120(void) { int64_t x6709 = -1LL; uint64_t x6710 = 119581LLU; uint64_t x6711 = UINT64_MAX; volatile int8_t x6712 = 4; t120 = (((x6709^x6710)|x6711)>>x6712); if (t120 != 1152921504606846975LLU) { NG(); } else { ; } } void f121(void) { volatile int16_t x6757 = 727; volatile int64_t x6758 = INT64_MAX; uint64_t x6759 = 3574856LLU; static uint8_t x6760 = 0U; t121 = (((x6757^x6758)|x6759)>>x6760); if (t121 != 9223372036854775144LLU) { NG(); } else { ; } } void f122(void) { volatile int16_t x6773 = 275; static uint32_t x6774 = UINT32_MAX; uint8_t x6776 = 4U; uint32_t t122 = 9721342U; t122 = (((x6773^x6774)|x6775)>>x6776); if (t122 != 268435439U) { NG(); } else { ; } } void f123(void) { int16_t x6837 = INT16_MIN; int16_t x6838 = INT16_MIN; static int8_t x6839 = 1; int32_t x6840 = 1; volatile int32_t t123 = 19; t123 = (((x6837^x6838)|x6839)>>x6840); if (t123 != 0) { NG(); } else { ; } } void f124(void) { int32_t x6949 = -1; uint64_t x6951 = 696887430LLU; volatile uint8_t x6952 = 2U; volatile uint64_t t124 = 49806LLU; t124 = (((x6949^x6950)|x6951)>>x6952); if (t124 != 174221857LLU) { NG(); } else { ; } } void f125(void) { uint64_t x7089 = 278686337132477LLU; volatile int8_t x7090 = INT8_MIN; int8_t x7091 = -2; static volatile uint64_t t125 = 3158289450721351740LLU; t125 = (((x7089^x7090)|x7091)>>x7092); if (t125 != 9223372036854775807LLU) { NG(); } else { ; } } void f126(void) { uint64_t x7133 = 16015737358LLU; uint8_t x7134 = 15U; static volatile uint16_t x7136 = 6U; volatile uint64_t t126 = 3542609433LLU; t126 = (((x7133^x7134)|x7135)>>x7136); if (t126 != 250245896LLU) { NG(); } else { ; } } void f127(void) { uint8_t x7233 = UINT8_MAX; static uint64_t x7234 = 14365333LLU; int8_t x7235 = 53; static uint32_t x7236 = 10U; uint64_t t127 = 305096127431940LLU; t127 = (((x7233^x7234)|x7235)>>x7236); if (t127 != 14028LLU) { NG(); } else { ; } } void f128(void) { static uint64_t x7243 = 3897580702115395LLU; t128 = (((x7241^x7242)|x7243)>>x7244); if (t128 != 1LLU) { NG(); } else { ; } } void f129(void) { uint16_t x7381 = 4005U; static int16_t x7382 = 1; static int64_t x7383 = 19295821234255189LL; int8_t x7384 = 1; int64_t t129 = -154LL; t129 = (((x7381^x7382)|x7383)>>x7384); if (t129 != 9647910617128954LL) { NG(); } else { ; } } void f130(void) { volatile int64_t x7405 = -430577326089LL; static volatile int64_t x7406 = 10LL; volatile uint64_t x7407 = 287710LLU; int16_t x7408 = 2; volatile uint64_t t130 = 132303LLU; t130 = (((x7405^x7406)|x7407)>>x7408); if (t130 != 4611685910783056383LLU) { NG(); } else { ; } } void f131(void) { int32_t x7421 = -1; int8_t x7422 = -11; int64_t x7423 = INT64_MAX; int8_t x7424 = 33; t131 = (((x7421^x7422)|x7423)>>x7424); if (t131 != 1073741823LL) { NG(); } else { ; } } void f132(void) { static uint8_t x7441 = UINT8_MAX; uint8_t x7442 = 1U; uint32_t x7443 = UINT32_MAX; uint8_t x7444 = 0U; volatile uint32_t t132 = UINT32_MAX; t132 = (((x7441^x7442)|x7443)>>x7444); if (t132 != UINT32_MAX) { NG(); } else { ; } } void f133(void) { volatile int32_t x7461 = -12; int64_t x7462 = -1LL; int16_t x7463 = 42; int16_t x7464 = 8; volatile int64_t t133 = 8493494067LL; t133 = (((x7461^x7462)|x7463)>>x7464); if (t133 != 0LL) { NG(); } else { ; } } void f134(void) { uint16_t x7492 = 4U; t134 = (((x7489^x7490)|x7491)>>x7492); if (t134 != 1152921504606846975LLU) { NG(); } else { ; } } void f135(void) { uint8_t x7505 = 8U; static uint8_t x7506 = 3U; uint8_t x7507 = UINT8_MAX; volatile uint16_t x7508 = 3U; int32_t t135 = -60380; t135 = (((x7505^x7506)|x7507)>>x7508); if (t135 != 31) { NG(); } else { ; } } void f136(void) { int8_t x7525 = INT8_MAX; int16_t x7528 = 9; volatile uint64_t t136 = 44576547057LLU; t136 = (((x7525^x7526)|x7527)>>x7528); if (t136 != 36028797018827567LLU) { NG(); } else { ; } } void f137(void) { int8_t x7581 = INT8_MIN; uint64_t x7582 = 13520LLU; static volatile int16_t x7583 = 211; uint8_t x7584 = 12U; uint64_t t137 = 30LLU; t137 = (((x7581^x7582)|x7583)>>x7584); if (t137 != 4503599627370492LLU) { NG(); } else { ; } } void f138(void) { uint16_t x7589 = 0U; uint16_t x7590 = 2U; int64_t x7591 = INT64_MAX; int16_t x7592 = 47; volatile int64_t t138 = 11947422LL; t138 = (((x7589^x7590)|x7591)>>x7592); if (t138 != 65535LL) { NG(); } else { ; } } void f139(void) { uint16_t x7593 = 1U; uint16_t x7594 = UINT16_MAX; int16_t x7595 = 481; volatile int32_t t139 = -197597; t139 = (((x7593^x7594)|x7595)>>x7596); if (t139 != 7) { NG(); } else { ; } } void f140(void) { uint64_t x7705 = UINT64_MAX; uint64_t x7706 = UINT64_MAX; int8_t x7707 = -2; uint64_t x7708 = 2LLU; uint64_t t140 = 644LLU; t140 = (((x7705^x7706)|x7707)>>x7708); if (t140 != 4611686018427387903LLU) { NG(); } else { ; } } void f141(void) { uint8_t x7710 = UINT8_MAX; int16_t x7711 = INT16_MAX; static uint64_t x7712 = 15LLU; int32_t t141 = -4; t141 = (((x7709^x7710)|x7711)>>x7712); if (t141 != 1) { NG(); } else { ; } } void f142(void) { int8_t x7733 = -1; volatile int32_t x7734 = -229; uint64_t x7735 = UINT64_MAX; static uint64_t t142 = 56240712007505LLU; t142 = (((x7733^x7734)|x7735)>>x7736); if (t142 != 576460752303423487LLU) { NG(); } else { ; } } void f143(void) { static int16_t x7765 = 2193; int32_t x7766 = INT32_MAX; int8_t x7767 = INT8_MAX; int32_t t143 = -2000950; t143 = (((x7765^x7766)|x7767)>>x7768); if (t143 != 536870367) { NG(); } else { ; } } void f144(void) { uint64_t x7789 = UINT64_MAX; uint8_t x7790 = UINT8_MAX; int16_t x7791 = INT16_MAX; uint16_t x7792 = 0U; uint64_t t144 = UINT64_MAX; t144 = (((x7789^x7790)|x7791)>>x7792); if (t144 != UINT64_MAX) { NG(); } else { ; } } void f145(void) { uint64_t x7810 = 48517515314080458LLU; int8_t x7811 = 0; uint32_t x7812 = 37U; t145 = (((x7809^x7810)|x7811)>>x7812); if (t145 != 353011LLU) { NG(); } else { ; } } void f146(void) { uint64_t x7893 = 60808240819708100LLU; int32_t x7894 = INT32_MIN; volatile int8_t x7895 = -1; static volatile int64_t x7896 = 0LL; volatile uint64_t t146 = UINT64_MAX; t146 = (((x7893^x7894)|x7895)>>x7896); if (t146 != UINT64_MAX) { NG(); } else { ; } } void f147(void) { uint32_t x7897 = UINT32_MAX; static int64_t x7898 = INT64_MAX; int8_t x7899 = INT8_MAX; int16_t x7900 = 7; volatile int64_t t147 = 45835991716298735LL; t147 = (((x7897^x7898)|x7899)>>x7900); if (t147 != 72057594004373504LL) { NG(); } else { ; } } void f148(void) { int16_t x7905 = -15; int16_t x7907 = 13367; t148 = (((x7905^x7906)|x7907)>>x7908); if (t148 != 9223372036854775799LL) { NG(); } else { ; } } void f149(void) { static int8_t x7925 = -1; uint32_t x7926 = UINT32_MAX; volatile uint8_t x7927 = UINT8_MAX; int8_t x7928 = 13; uint32_t t149 = 1063981U; t149 = (((x7925^x7926)|x7927)>>x7928); if (t149 != 0U) { NG(); } else { ; } } void f150(void) { int32_t x7945 = INT32_MIN; int32_t x7946 = INT32_MIN; uint64_t x7947 = UINT64_MAX; static int16_t x7948 = 0; volatile uint64_t t150 = UINT64_MAX; t150 = (((x7945^x7946)|x7947)>>x7948); if (t150 != UINT64_MAX) { NG(); } else { ; } } void f151(void) { volatile int16_t x8050 = INT16_MIN; uint32_t x8051 = 158377882U; uint8_t x8052 = 1U; t151 = (((x8049^x8050)|x8051)>>x8052); if (t151 != 79200255U) { NG(); } else { ; } } void f152(void) { static int64_t x8123 = -1LL; uint16_t x8124 = 39U; uint64_t t152 = 35837321LLU; t152 = (((x8121^x8122)|x8123)>>x8124); if (t152 != 33554431LLU) { NG(); } else { ; } } void f153(void) { volatile uint16_t x8189 = UINT16_MAX; uint16_t x8190 = 316U; int32_t x8191 = INT32_MAX; int8_t x8192 = 28; int32_t t153 = 2927685; t153 = (((x8189^x8190)|x8191)>>x8192); if (t153 != 7) { NG(); } else { ; } } void f154(void) { volatile int16_t x8213 = INT16_MAX; volatile uint8_t x8214 = UINT8_MAX; volatile uint8_t x8215 = UINT8_MAX; int32_t x8216 = 7; volatile int32_t t154 = -25; t154 = (((x8213^x8214)|x8215)>>x8216); if (t154 != 255) { NG(); } else { ; } } void f155(void) { static int32_t x8249 = INT32_MAX; volatile int64_t x8250 = 253578701LL; uint8_t x8252 = 8U; int64_t t155 = 2200717432106022LL; t155 = (((x8249^x8250)|x8251)>>x8252); if (t155 != 7398066LL) { NG(); } else { ; } } void f156(void) { int16_t x8277 = -4; int64_t x8279 = 1946296139292633354LL; uint8_t x8280 = 6U; int64_t t156 = 3742303126809779035LL; t156 = (((x8277^x8278)|x8279)>>x8280); if (t156 != 30410877186332150LL) { NG(); } else { ; } } void f157(void) { int8_t x8345 = INT8_MIN; static int32_t x8346 = INT32_MIN; int64_t x8347 = 87LL; static volatile int8_t x8348 = 5; t157 = (((x8345^x8346)|x8347)>>x8348); if (t157 != 67108862LL) { NG(); } else { ; } } void f158(void) { uint32_t x8361 = UINT32_MAX; static volatile uint32_t x8362 = 398030354U; static uint16_t x8363 = 12790U; uint32_t x8364 = 6U; t158 = (((x8361^x8362)|x8363)>>x8364); if (t158 != 60889831U) { NG(); } else { ; } } void f159(void) { static uint32_t x8369 = 299369652U; uint16_t x8370 = UINT16_MAX; int8_t x8371 = -1; int8_t x8372 = 1; t159 = (((x8369^x8370)|x8371)>>x8372); if (t159 != 2147483647U) { NG(); } else { ; } } void f160(void) { uint64_t x8394 = 3682686228154787LLU; int32_t x8395 = INT32_MAX; static volatile int16_t x8396 = 16; uint64_t t160 = 86LLU; t160 = (((x8393^x8394)|x8395)>>x8396); if (t160 != 281418783391743LLU) { NG(); } else { ; } } void f161(void) { volatile int64_t x8397 = -309257098874485LL; static int16_t x8398 = -1; uint32_t x8399 = 1694225093U; static uint8_t x8400 = 40U; t161 = (((x8397^x8398)|x8399)>>x8400); if (t161 != 281LL) { NG(); } else { ; } } void f162(void) { static int32_t x8441 = INT32_MAX; uint32_t x8443 = UINT32_MAX; int8_t x8444 = 0; uint32_t t162 = UINT32_MAX; t162 = (((x8441^x8442)|x8443)>>x8444); if (t162 != UINT32_MAX) { NG(); } else { ; } } void f163(void) { int32_t x8525 = -1; int8_t x8526 = -2; static uint16_t x8528 = 0U; uint32_t t163 = 122U; t163 = (((x8525^x8526)|x8527)>>x8528); if (t163 != 1929789429U) { NG(); } else { ; } } void f164(void) { int8_t x8595 = 25; uint8_t x8596 = 0U; static volatile uint32_t t164 = 931U; t164 = (((x8593^x8594)|x8595)>>x8596); if (t164 != 4921U) { NG(); } else { ; } } void f165(void) { uint32_t x8597 = 101740404U; uint32_t x8598 = UINT32_MAX; static uint32_t x8599 = 15737608U; int64_t x8600 = 3LL; static uint32_t t165 = 1964346U; t165 = (((x8597^x8598)|x8599)>>x8600); if (t165 != 524285553U) { NG(); } else { ; } } void f166(void) { int64_t x8665 = 4117LL; volatile int32_t x8666 = -1; uint64_t x8667 = 10610305673062889LLU; volatile uint8_t x8668 = 3U; t166 = (((x8665^x8666)|x8667)>>x8668); if (t166 != 2305843009213693437LLU) { NG(); } else { ; } } void f167(void) { uint32_t x8725 = 191U; int16_t x8726 = INT16_MAX; static volatile int8_t x8727 = -2; volatile uint32_t t167 = 4287442U; t167 = (((x8725^x8726)|x8727)>>x8728); if (t167 != 262143U) { NG(); } else { ; } } void f168(void) { static uint64_t x8729 = 163162LLU; volatile int64_t x8730 = INT64_MIN; volatile uint64_t t168 = 88LLU; t168 = (((x8729^x8730)|x8731)>>x8732); if (t168 != 524288LLU) { NG(); } else { ; } } void f169(void) { int32_t x8737 = -1; uint64_t x8738 = 580LLU; uint8_t x8739 = 14U; uint64_t t169 = 16622422761LLU; t169 = (((x8737^x8738)|x8739)>>x8740); if (t169 != 9223372036854775519LLU) { NG(); } else { ; } } void f170(void) { static volatile int64_t x8813 = -235922230682349LL; volatile int16_t x8814 = INT16_MIN; uint16_t x8815 = UINT16_MAX; int64_t t170 = -4LL; t170 = (((x8813^x8814)|x8815)>>x8816); if (t170 != 1757757LL) { NG(); } else { ; } } void f171(void) { int16_t x8822 = 1; uint64_t x8823 = UINT64_MAX; uint8_t x8824 = 34U; volatile uint64_t t171 = 19250252403568089LLU; t171 = (((x8821^x8822)|x8823)>>x8824); if (t171 != 1073741823LLU) { NG(); } else { ; } } void f172(void) { uint16_t x8901 = UINT16_MAX; static int64_t x8902 = INT64_MAX; uint16_t x8903 = 893U; uint8_t x8904 = 1U; int64_t t172 = 3861LL; t172 = (((x8901^x8902)|x8903)>>x8904); if (t172 != 4611686018427355582LL) { NG(); } else { ; } } void f173(void) { volatile int64_t x8949 = 4240593672402138801LL; static uint8_t x8950 = UINT8_MAX; int64_t t173 = -543828821937099LL; t173 = (((x8949^x8950)|x8951)>>x8952); if (t173 != 1060148418100534675LL) { NG(); } else { ; } } void f174(void) { uint64_t x8961 = 28172708310491194LLU; int16_t x8962 = -114; static volatile int64_t x8963 = INT64_MIN; static volatile int16_t x8964 = 1; uint64_t t174 = 421678243158201LLU; t174 = (((x8961^x8962)|x8963)>>x8964); if (t174 != 9209285682699530202LLU) { NG(); } else { ; } } void f175(void) { int8_t x8974 = INT8_MIN; volatile uint8_t x8975 = 1U; volatile uint8_t x8976 = 0U; static int64_t t175 = -99818543554LL; t175 = (((x8973^x8974)|x8975)>>x8976); if (t175 != 510637LL) { NG(); } else { ; } } void f176(void) { int16_t x9013 = -5; volatile int8_t x9015 = -28; uint8_t x9016 = 1U; uint32_t t176 = 1104467424U; t176 = (((x9013^x9014)|x9015)>>x9016); if (t176 != 2147483634U) { NG(); } else { ; } } void f177(void) { int16_t x9149 = INT16_MIN; static int32_t x9152 = 0; volatile int32_t t177 = -14952514; t177 = (((x9149^x9150)|x9151)>>x9152); if (t177 != 32767) { NG(); } else { ; } } void f178(void) { static int8_t x9193 = INT8_MIN; static volatile int64_t x9194 = INT64_MIN; static int8_t x9195 = INT8_MAX; uint8_t x9196 = 5U; volatile int64_t t178 = 368621814427913LL; t178 = (((x9193^x9194)|x9195)>>x9196); if (t178 != 288230376151711743LL) { NG(); } else { ; } } void f179(void) { int16_t x9205 = 6534; static uint8_t x9206 = 1U; uint64_t x9207 = 8416333LLU; uint8_t x9208 = 1U; static volatile uint64_t t179 = 4128346LLU; t179 = (((x9205^x9206)|x9207)>>x9208); if (t179 != 4210407LLU) { NG(); } else { ; } } void f180(void) { uint16_t x9254 = 4U; static volatile uint32_t x9255 = 3810228U; int8_t x9256 = 1; t180 = (((x9253^x9254)|x9255)>>x9256); if (t180 != 1073741823U) { NG(); } else { ; } } void f181(void) { uint32_t x9309 = 50996179U; int64_t x9310 = INT64_MAX; uint64_t x9311 = UINT64_MAX; volatile uint8_t x9312 = 1U; volatile uint64_t t181 = 21664267110568315LLU; t181 = (((x9309^x9310)|x9311)>>x9312); if (t181 != 9223372036854775807LLU) { NG(); } else { ; } } void f182(void) { volatile int8_t x9325 = INT8_MIN; uint32_t x9326 = UINT32_MAX; volatile int32_t x9327 = -1; uint16_t x9328 = 1U; volatile uint32_t t182 = 68343150U; t182 = (((x9325^x9326)|x9327)>>x9328); if (t182 != 2147483647U) { NG(); } else { ; } } void f183(void) { volatile uint32_t x9385 = UINT32_MAX; uint16_t x9388 = 22U; static volatile uint32_t t183 = 283U; t183 = (((x9385^x9386)|x9387)>>x9388); if (t183 != 1023U) { NG(); } else { ; } } void f184(void) { volatile uint8_t x9389 = 118U; volatile int64_t x9390 = INT64_MAX; volatile uint8_t x9391 = 7U; int64_t t184 = -7LL; t184 = (((x9389^x9390)|x9391)>>x9392); if (t184 != 2251799813685247LL) { NG(); } else { ; } } void f185(void) { static int64_t t185 = -1LL; t185 = (((x9405^x9406)|x9407)>>x9408); if (t185 != 131071LL) { NG(); } else { ; } } void f186(void) { volatile uint64_t x9485 = 31LLU; int64_t x9487 = INT64_MIN; int16_t x9488 = 1; uint64_t t186 = 1163875602LLU; t186 = (((x9485^x9486)|x9487)>>x9488); if (t186 != 9223372036854775792LLU) { NG(); } else { ; } } void f187(void) { int16_t x9497 = INT16_MIN; volatile int32_t x9498 = -241529; volatile int64_t x9499 = 3607LL; t187 = (((x9497^x9498)|x9499)>>x9500); if (t187 != 123LL) { NG(); } else { ; } } void f188(void) { volatile int64_t x9689 = -1LL; static int64_t x9690 = INT64_MIN; int16_t x9691 = 7242; uint32_t x9692 = 2U; static int64_t t188 = 567LL; t188 = (((x9689^x9690)|x9691)>>x9692); if (t188 != 2305843009213693951LL) { NG(); } else { ; } } void f189(void) { volatile uint64_t x9698 = 894689LLU; int8_t x9700 = 1; t189 = (((x9697^x9698)|x9699)>>x9700); if (t189 != 9223372036854764367LLU) { NG(); } else { ; } } void f190(void) { int32_t x9705 = INT32_MIN; uint64_t x9706 = 245083LLU; int16_t x9707 = 4; static uint64_t x9708 = 39LLU; volatile uint64_t t190 = 3347795623829177LLU; t190 = (((x9705^x9706)|x9707)>>x9708); if (t190 != 33554431LLU) { NG(); } else { ; } } void f191(void) { static uint32_t x9709 = 96595U; int32_t x9710 = -1; volatile int8_t x9711 = INT8_MIN; volatile uint64_t x9712 = 13LLU; volatile uint32_t t191 = 4U; t191 = (((x9709^x9710)|x9711)>>x9712); if (t191 != 524287U) { NG(); } else { ; } } void f192(void) { int8_t x9713 = -1; static volatile uint64_t x9714 = 65905955203482717LLU; int32_t x9715 = 943; static uint8_t x9716 = 2U; uint64_t t192 = 5175766858176753416LLU; t192 = (((x9713^x9714)|x9715)>>x9716); if (t192 != 4595209529626517227LLU) { NG(); } else { ; } } void f193(void) { static int32_t x9734 = 5; static int8_t x9735 = 7; int32_t x9736 = 3; t193 = (((x9733^x9734)|x9735)>>x9736); if (t193 != 31) { NG(); } else { ; } } void f194(void) { volatile uint8_t x9805 = 0U; uint64_t x9806 = 533153591706564LLU; uint16_t x9807 = 29U; uint16_t x9808 = 2U; static volatile uint64_t t194 = 33134LLU; t194 = (((x9805^x9806)|x9807)>>x9808); if (t194 != 133288397926647LLU) { NG(); } else { ; } } void f195(void) { static uint8_t x9933 = 7U; uint8_t x9934 = 8U; uint32_t x9935 = 38U; uint16_t x9936 = 1U; uint32_t t195 = 313990U; t195 = (((x9933^x9934)|x9935)>>x9936); if (t195 != 23U) { NG(); } else { ; } } void f196(void) { uint64_t x9949 = 1608112LLU; int64_t x9950 = INT64_MAX; static volatile int32_t x9951 = 72; uint8_t x9952 = 1U; volatile uint64_t t196 = 3376819LLU; t196 = (((x9949^x9950)|x9951)>>x9952); if (t196 != 4611686018426583847LLU) { NG(); } else { ; } } void f197(void) { static volatile uint8_t x9957 = 47U; uint64_t x9958 = UINT64_MAX; static uint64_t x9959 = 41LLU; static uint8_t x9960 = 45U; uint64_t t197 = 85333668802LLU; t197 = (((x9957^x9958)|x9959)>>x9960); if (t197 != 524287LLU) { NG(); } else { ; } } void f198(void) { volatile int32_t x10078 = 7; int32_t x10079 = 1; uint16_t x10080 = 0U; t198 = (((x10077^x10078)|x10079)>>x10080); if (t198 != 203231791U) { NG(); } else { ; } } void f199(void) { static uint8_t x10101 = UINT8_MAX; uint64_t x10102 = 84LLU; static int16_t x10103 = INT16_MAX; int8_t x10104 = 2; volatile uint64_t t199 = 1315LLU; t199 = (((x10101^x10102)|x10103)>>x10104); if (t199 != 8191LLU) { NG(); } else { ; } } int main(void) { 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(); f32(); f33(); f34(); f35(); f36(); f37(); f38(); f39(); f40(); f41(); f42(); f43(); f44(); f45(); f46(); f47(); f48(); f49(); f50(); f51(); f52(); f53(); f54(); f55(); f56(); f57(); f58(); f59(); f60(); f61(); f62(); f63(); f64(); f65(); f66(); f67(); f68(); f69(); f70(); f71(); f72(); f73(); f74(); f75(); f76(); f77(); f78(); f79(); f80(); f81(); f82(); f83(); f84(); f85(); f86(); f87(); f88(); f89(); f90(); f91(); f92(); f93(); f94(); f95(); f96(); f97(); f98(); f99(); f100(); f101(); f102(); f103(); f104(); f105(); f106(); f107(); f108(); f109(); f110(); f111(); f112(); f113(); f114(); f115(); f116(); f117(); f118(); f119(); f120(); f121(); f122(); f123(); f124(); f125(); f126(); f127(); f128(); f129(); f130(); f131(); f132(); f133(); f134(); f135(); f136(); f137(); f138(); f139(); f140(); f141(); f142(); f143(); f144(); f145(); f146(); f147(); f148(); f149(); f150(); f151(); f152(); f153(); f154(); f155(); f156(); f157(); f158(); f159(); f160(); f161(); f162(); f163(); f164(); f165(); f166(); f167(); f168(); f169(); f170(); f171(); f172(); f173(); f174(); f175(); f176(); f177(); f178(); f179(); f180(); f181(); f182(); f183(); f184(); f185(); f186(); f187(); f188(); f189(); f190(); f191(); f192(); f193(); f194(); f195(); f196(); f197(); f198(); f199(); return 0; }
226165.c
f32 test(shape_t *s) { s32 temp_v0; temp_v0 = s->type; if (temp_v0 != 0) { if (temp_v0 != 1) { if (temp_v0 != 2) { return 0.0f; } return s->origin.x + s->unkC; } return s->origin.x + s->unkC; } return s->origin.x + s->unkC; }
289927.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <time.h> static unsigned long progress_max; static unsigned int progress_pcent; static unsigned long progress_n_upd; static unsigned int progress_prevsec; static struct timespec progress_start; #define PROGRESS_CHARS 50 void progress_init(unsigned long count) { unsigned int i; progress_max = count; progress_pcent = 0; progress_n_upd = ULONG_MAX; progress_prevsec = UINT_MAX; printf("\r["); for (i = 0; i < PROGRESS_CHARS; i++) printf(" "); printf("] 0%%"); fflush(stdout); clock_gettime(CLOCK_MONOTONIC, &progress_start);} void progress_tick(unsigned long cur) { unsigned int pcent, i, pos, sec; struct timespec now; pcent = (cur * 100) / progress_max; if (progress_pcent == pcent && cur < progress_n_upd && cur < progress_max) return; progress_pcent = pcent; pos = (pcent * PROGRESS_CHARS) / 101; clock_gettime(CLOCK_MONOTONIC, &now); printf("\r["); for (i = 0; i <= pos; i++) printf("="); for (; i < PROGRESS_CHARS; i++) printf(" "); printf("] %d%%", pcent); sec = now.tv_sec - progress_start.tv_sec; if (sec >= 5 && pcent > 0) { unsigned int persec = cur / sec; unsigned int rem_sec; if (!persec) persec = 1; progress_n_upd = cur + persec; rem_sec = ((sec * 100) + (pcent / 2)) / pcent - sec; if (rem_sec > progress_prevsec) rem_sec = progress_prevsec; progress_prevsec = rem_sec; if (rem_sec < 60) printf(" ETA:%ds ", rem_sec); else { printf(" ETA:%d:%02d:%02d ", rem_sec / 3600, (rem_sec / 60) % 60, rem_sec % 60); } } fflush(stdout); } void progress_end(void) { printf("\n"); }
79158.c
// SPDX-License-Identifier: BSD-3-Clause // // Copyright(c) 2019 Intel Corporation. All rights reserved. // // Author: Tomasz Lauda <[email protected]> #include <sof/audio/component.h> #include <sof/bit.h> #include <sof/drivers/interrupt.h> #include <sof/drivers/timer.h> #include <sof/lib/alloc.h> #include <sof/lib/cpu.h> #include <sof/lib/dma.h> #include <sof/lib/memory.h> #include <sof/lib/notifier.h> #include <sof/platform.h> #include <sof/schedule/ll_schedule.h> #include <sof/schedule/ll_schedule_domain.h> #include <sof/schedule/schedule.h> #include <sof/schedule/task.h> #include <ipc/topology.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> struct dma_domain_data { int irq; struct pipeline_task *task; void (*handler)(void *arg); void *arg; }; struct dma_domain { struct dma *dma_array; /* pointer to scheduling DMAs */ uint32_t num_dma; /* number of scheduling DMAs */ bool aggregated_irq; /* true if aggregated interrupts */ /* mask of currently running channels */ uint32_t channel_mask[PLATFORM_NUM_DMACS][CONFIG_CORE_COUNT]; /* array of arguments for aggregated mode */ struct dma_domain_data *arg[PLATFORM_NUM_DMACS][CONFIG_CORE_COUNT]; /* array of registered channels data */ struct dma_domain_data data[PLATFORM_NUM_DMACS][PLATFORM_MAX_DMA_CHAN]; }; const struct ll_schedule_domain_ops dma_multi_chan_domain_ops; /** * \brief Generic DMA interrupt handler. * \param[in,out] data Pointer to DMA domain data. */ static void dma_multi_chan_domain_irq_handler(void *data) { struct dma_domain_data *domain_data = data; /* just call registered handler */ domain_data->handler(domain_data->arg); } /** * \brief Registers and enables selected DMA interrupt. * \param[in,out] data Pointer to DMA domain data. * \param[in,out] handler Pointer to DMA interrupt handler. * \return Error code. */ static int dma_multi_chan_domain_irq_register(struct dma_domain_data *data, void (*handler)(void *arg)) { int ret; tr_info(&ll_tr, "dma_multi_chan_domain_irq_register()"); /* always go through dma_multi_chan_domain_irq_handler, * so we have different arg registered for every channel */ ret = interrupt_register(data->irq, dma_multi_chan_domain_irq_handler, data); if (ret < 0) return ret; interrupt_enable(data->irq, data); return 0; } /** * \brief Registers task to DMA domain. * \param[in,out] domain Pointer to schedule domain. * \param[in] period Period of the scheduled task. * \param[in,out] task Task to be registered. * \param[in,out] handler Pointer to DMA interrupt handler. * \param[in,out] arg Pointer to DMA interrupt handler's argument. * \return Error code. * * Keeps track of potential double registrations and handles non aggregated * DMA interrupts (different irq number per DMA channel). */ static int dma_multi_chan_domain_register(struct ll_schedule_domain *domain, uint64_t period, struct task *task, void (*handler)(void *arg), void *arg) { struct dma_domain *dma_domain = ll_sch_domain_get_pdata(domain); struct pipeline_task *pipe_task = pipeline_task_get(task); struct dma *dmas = dma_domain->dma_array; int core = cpu_get_id(); int ret = 0; int i; int j; tr_info(&ll_tr, "dma_multi_chan_domain_register()"); /* check if task should be registered */ if (!pipe_task->registrable) goto out; for (i = 0; i < dma_domain->num_dma; ++i) { for (j = 0; j < dmas[i].plat_data.channels; ++j) { /* channel not set as scheduling source */ if (!dma_is_scheduling_source(&dmas[i].chan[j])) continue; /* channel not running */ if (dmas[i].chan[j].status != COMP_STATE_ACTIVE) continue; /* channel owned by different core */ if (core != dmas[i].chan[j].core) continue; /* channel has been already running */ if (dma_domain->channel_mask[i][core] & BIT(j)) continue; dma_interrupt(&dmas[i].chan[j], DMA_IRQ_CLEAR); /* register only if not aggregated or not registered */ if (!dma_domain->aggregated_irq || !dma_domain->channel_mask[i][core]) { ret = dma_multi_chan_domain_irq_register( &dma_domain->data[i][j], handler); if (ret < 0) goto out; dma_domain->data[i][j].handler = handler; dma_domain->data[i][j].arg = arg; /* needed to unregister aggregated interrupts */ dma_domain->arg[i][core] = &dma_domain->data[i][j]; } interrupt_clear_mask(dma_domain->data[i][j].irq, BIT(j)); dma_interrupt(&dmas[i].chan[j], DMA_IRQ_UNMASK); dma_domain->data[i][j].task = pipe_task; dma_domain->channel_mask[i][core] |= BIT(j); goto out; } } out: return ret; } /** * \brief Unregisters and disables selected DMA interrupt. * \param[in,out] data data Pointer to DMA domain data. */ static void dma_multi_chan_domain_irq_unregister(struct dma_domain_data *data) { tr_info(&ll_tr, "dma_multi_chan_domain_irq_unregister()"); interrupt_disable(data->irq, data); interrupt_unregister(data->irq, data); } /** * \brief Unregisters task from DMA domain. * \param[in,out] domain Pointer to schedule domain. * \param[in,out] task Task to be unregistered from the domain.. * \param[in] num_tasks Number of currently scheduled tasks. * \return Error code. */ static int dma_multi_chan_domain_unregister(struct ll_schedule_domain *domain, struct task *task, uint32_t num_tasks) { struct dma_domain *dma_domain = ll_sch_domain_get_pdata(domain); struct pipeline_task *pipe_task = pipeline_task_get(task); struct dma *dmas = dma_domain->dma_array; int core = cpu_get_id(); int i; int j; tr_info(&ll_tr, "dma_multi_chan_domain_unregister()"); /* check if task should be unregistered */ if (!pipe_task->registrable) return 0; for (i = 0; i < dma_domain->num_dma; ++i) { for (j = 0; j < dmas[i].plat_data.channels; ++j) { /* channel not set as scheduling source */ if (!dma_is_scheduling_source(&dmas[i].chan[j])) continue; /* channel still running */ if (dmas[i].chan[j].status == COMP_STATE_ACTIVE) continue; /* channel owned by different core */ if (core != dmas[i].chan[j].core) continue; /* channel hasn't been running */ if (!(dma_domain->channel_mask[i][core] & BIT(j))) continue; dma_interrupt(&dmas[i].chan[j], DMA_IRQ_MASK); dma_interrupt(&dmas[i].chan[j], DMA_IRQ_CLEAR); interrupt_clear_mask(dma_domain->data[i][j].irq, BIT(j)); dma_domain->data[i][j].task = NULL; dma_domain->channel_mask[i][core] &= ~BIT(j); /* unregister interrupt */ if (!dma_domain->aggregated_irq) dma_multi_chan_domain_irq_unregister( &dma_domain->data[i][j]); else if (!dma_domain->channel_mask[i][core]) dma_multi_chan_domain_irq_unregister( dma_domain->arg[i][core]); return 0; } } /* task in running or unregistered at all, can't unregister it */ return -EINVAL; } /** * \brief Checks if given task should be executed. * \param[in,out] domain Pointer to schedule domain. * \param[in,out] task Task to be checked. * \return True is task should be executed, false otherwise. */ static bool dma_multi_chan_domain_is_pending(struct ll_schedule_domain *domain, struct task *task, struct comp_dev **comp) { struct dma_domain *dma_domain = ll_sch_domain_get_pdata(domain); struct pipeline_task *pipe_task = pipeline_task_get(task); struct dma *dmas = dma_domain->dma_array; struct ll_task_pdata *pdata; uint32_t status; int i; int j; for (i = 0; i < dma_domain->num_dma; ++i) { for (j = 0; j < dmas[i].plat_data.channels; ++j) { if (!*comp) { status = dma_interrupt(&dmas[i].chan[j], DMA_IRQ_STATUS_GET); if (!status) continue; *comp = dma_domain->data[i][j].task->sched_comp; } else if (!dma_domain->data[i][j].task || dma_domain->data[i][j].task->sched_comp != *comp) { continue; } /* not the same scheduling component */ if (dma_domain->data[i][j].task->sched_comp != pipe_task->sched_comp) continue; /* Schedule task based on the frequency they * were configured with, not time (task.start) * * There are cases when a DMA transfer from a DAI * is finished earlier than task.start and, * without full_sync mode, this task will not * be scheduled */ if (domain->full_sync) { pdata = ll_sch_get_pdata(&pipe_task->task); pdata->skip_cnt++; if (pdata->skip_cnt == pdata->ratio) pdata->skip_cnt = 0; if (pdata->skip_cnt != 0) continue; } else { /* it's too soon for this task */ if (!pipe_task->registrable && pipe_task->task.start > platform_timer_get_atomic(timer_get())) continue; } notifier_event(&dmas[i].chan[j], NOTIFIER_ID_DMA_IRQ, NOTIFIER_TARGET_CORE_LOCAL, &dmas[i].chan[j], sizeof(struct dma_chan_data)); /* clear interrupt */ if (pipe_task->registrable) { dma_interrupt(&dmas[i].chan[j], DMA_IRQ_CLEAR); interrupt_clear_mask(dma_domain->data[i][j].irq, BIT(j)); } return true; } } return false; } /** * \brief Initializes DMA multichannel scheduling domain. * \param[in,out] dma_array Array of DMAs to be scheduled on. * \param[in] num_dma Number of DMAs passed as dma_array. * \param[in] clk Platform clock to base calculations on. * \param[in] aggregated_irq True if all DMAs share the same interrupt line. * \return Pointer to initialized scheduling domain object. */ struct ll_schedule_domain *dma_multi_chan_domain_init(struct dma *dma_array, uint32_t num_dma, int clk, bool aggregated_irq) { struct ll_schedule_domain *domain; struct dma_domain *dma_domain; struct dma *dma; int i; int j; tr_info(&ll_tr, "dma_multi_chan_domain_init(): num_dma %d, clk %d, aggregated_irq %d", num_dma, clk, aggregated_irq); domain = domain_init(SOF_SCHEDULE_LL_DMA, clk, true, &dma_multi_chan_domain_ops); dma_domain = rzalloc(SOF_MEM_ZONE_SYS_SHARED, 0, SOF_MEM_CAPS_RAM, sizeof(*dma_domain)); dma_domain->dma_array = dma_array; dma_domain->num_dma = num_dma; dma_domain->aggregated_irq = aggregated_irq; /* retrieve IRQ numbers for each DMA channel */ for (i = 0; i < num_dma; ++i) { dma = &dma_array[i]; for (j = 0; j < dma->plat_data.channels; ++j) dma_domain->data[i][j].irq = interrupt_get_irq( dma_chan_irq(dma, j), dma_chan_irq_name(dma, j)); } ll_sch_domain_set_pdata(domain, dma_domain); return domain; } const struct ll_schedule_domain_ops dma_multi_chan_domain_ops = { .domain_register = dma_multi_chan_domain_register, .domain_unregister = dma_multi_chan_domain_unregister, .domain_is_pending = dma_multi_chan_domain_is_pending, .domain_set = NULL, .domain_enable = NULL, .domain_disable = NULL, .domain_clear = NULL, };
201623.c
/* * ************************************************************** * Copyright (c) 2017-2022, Aastha Mehta <[email protected]> * All rights reserved. * * This source code is licensed under the BSD-style license found * in the LICENSE file in the root directory of this source tree. * ************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <assert.h> #include "utils/list.h" #include "utils/hashtable.h" #include "utils/format.h" #include "common/config.h" #include "common/session.h" #include "common/qapla_policy.h" #include "common/tuple.h" #include "common/db.h" #include "policyapi/dlog_pred.h" #include "policyapi/sql_pred.h" #include "dlog_pi/dlog_pi_env.h" #include "dlog_pi/dlog_pi.h" #include "sql_pi/sql_pol_eval.h" #include "sql_pi/sql_rewrite.h" #include "query_info_int.h" #include "metadata.h" #include "pol_cluster.h" #include "pol_vector.h" #include "pol_eval_utils.h" #include "pol_eval.h" #include <antlr3.h> #include <glib.h> void error_print_col_link(FILE *f, col_sym_t *cs) { fprintf(f, "conflicting policies in link cluster, " "all bits set to 0 due to col: %s:%s.%s(%d.%d)\n", sym_field(cs, name), sym_field(cs, db_tname), sym_field(cs, db_cname), sym_field(cs, db_tid), sym_field(cs, db_cid)); } int is_aggr_query(query_info_int_t *qi) { context_t *firstC = get_first_context(&qi->pc); if (!firstC) return -1; return firstC->is_aggr_query; } int aggr_query_get_pvec(query_info_int_t *qi, PVEC *pv) { context_t *firstC = get_first_context(&qi->pc); if (!firstC || !firstC->is_aggr_query) return -1; metadata_t *qm = &qi->qm; cluster_t *aggr_cluster; list_t *cluster_list = metadata_get_cluster_list(qm); int n_cluster = metadata_get_num_clusters(qm); int cnt = 0; list_for_each_entry(aggr_cluster, cluster_list, cluster_listp) { cnt++; if (cnt == n_cluster) break; } PVEC c_g_pvec = -1, g_tmp_pv = 0, log_tmp_pv = 0; symbol_t *sym; col_sym_t *cs; list_t *cs_list, *col_list; int ret = 0, fail = 0; col_list = &firstC->symbol_list[SYM_COL]; list_for_each_entry(sym, col_list, symbol_listp) { cs_list = &sym->col_sym_list; list_for_each_entry(cs, cs_list, col_sym_listp) { g_tmp_pv = 0; ret = cluster_get_pid_for_col(aggr_cluster, cs, &g_tmp_pv); if (ret < 0) { fail = 1; break; } c_g_pvec &= g_tmp_pv; #if DEBUG printf("cs:(%s,%s) tmp: %lu, new pv: %lu\n", sym_field(cs, db_tname), sym_field(cs, db_cname), g_tmp_pv, c_g_pvec); #endif } if (fail == 1) break; } // query does not satisfy aggregate policy if (fail == 1) return -1; #if DEBUG printf("aggr pvec: 0x%lx\n", c_g_pvec); #endif // conflicting policies detected if (c_g_pvec == 0) return -1; int16_t least_pid = -1; PVEC tmp_pv = 0; least_pid = get_least_restrictive_pid(aggr_cluster, c_g_pvec); #if DEBUG printf("aggr least pid: %d\n", least_pid); #endif if (least_pid < 0) return -1; tmp_pv |= ((PVEC) 1 << least_pid); c_g_pvec = tmp_pv; #if 0 // more than one aggregate policy applicable to query int16_t pid = get_pid_from_pvec(c_g_pvec); if (pid < 0) return -1; #endif *pv = c_g_pvec; return 0; } int get_col_list_for_eval(list_t *actual_list, list_t *expected_list, list_t *unexpected_list) { symbol_t *a_sym; col_sym_t *a_cs, *match_cs; list_t *a_cs_list; list_t *mark_list = NULL; int expected = -1; if (!list_empty(unexpected_list)) { mark_list = unexpected_list; expected = 0; } else if (!list_empty(expected_list)) { mark_list = expected_list; expected = 1; } if (mark_list) { list_for_each_entry(a_sym, actual_list, symbol_listp) { a_cs_list = &a_sym->col_sym_list; list_for_each_entry(a_cs, a_cs_list, col_sym_listp) { if (exists_col_sym_in_list(a_cs, mark_list, 0, &match_cs) == 0) a_cs->is_expected = expected; else a_cs->is_expected = !expected; a_cs->is_set = 1; } } } else { list_for_each_entry(a_sym, actual_list, symbol_listp) { a_cs_list = &a_sym->col_sym_list; list_for_each_entry(a_cs, a_cs_list, col_sym_listp) { a_cs->is_expected = 1; a_cs->is_set = 1; } } } return 0; } int query_get_pvec(query_info_int_t *qi, PVEC *pv) { context_t *currC = get_curr_context(&qi->pc); if (!currC) return -1; list_t *col_list = &currC->symbol_list[SYM_COL]; list_t *expected_list = qstr_get_expected_col_list(&qi->qstr); list_t *unexpected_list = qstr_get_unexpected_col_list(&qi->qstr); get_col_list_for_eval(col_list, expected_list, unexpected_list); metadata_t *qm = &qi->qm; int n_cluster = metadata_get_num_clusters(qm) - 1; cluster_t *false_cluster = metadata_get_false_cluster(qm); PVEC *c_g_pvec = (PVEC *) malloc(sizeof(PVEC) * n_cluster); uint8_t *c_used = (uint8_t *) malloc(sizeof(uint8_t) * n_cluster); uint8_t *c_type = (uint8_t *) malloc(sizeof(uint8_t) * n_cluster); cluster_t **cluster = (cluster_t **) malloc(sizeof(cluster_t *) * n_cluster); memset(c_g_pvec, 0, sizeof(PVEC) * n_cluster); memset(c_used, 0, sizeof(uint8_t) * n_cluster); memset(c_type, 0, sizeof(uint8_t) * n_cluster); memset(cluster, 0, sizeof(cluster_t *) * n_cluster); int i, seen_one = 0; symbol_t *sym; col_sym_t *cs; list_t *cs_list; PVEC g_tmp_pv = 0, log_tmp_pv = 0, final_pv = -1; cluster_t *tmp_c; int cluster_id = 0, cluster_op = -1; int ret, fail = 0; list_for_each_entry(sym, col_list, symbol_listp) { cs_list = &sym->col_sym_list; seen_one = 0; list_for_each_entry(cs, cs_list, col_sym_listp) { g_tmp_pv = 0; // don't include pvec of columns not expected in the result if (cs->is_expected == 0) continue; // ignore symbols from constant queries int tid = sym_field(cs, db_tid); if (tid == DUAL_TID) continue; ret = metadata_lookup_cluster_pvec(qm, cs, &tmp_c, &g_tmp_pv); if (ret < 0) { #if DEBUG int orig_qlen = 0; char *orig_q = qstr_get_orig_query(&qi->qstr, &orig_qlen); fprintf(stderr, "[%lu] failed policy lookup for col: %s:%s.%s(%d.%d), ..... Q:%s\n", getpid(), sym_field(cs, name), sym_field(cs, db_tname), sym_field(cs, db_cname), sym_field(cs, db_tid), sym_field(cs, db_cid), orig_q); #endif #if 0 // no explicit policy defined; apply default false policy on col's table fail = 1; cluster_id = cluster_get_id(false_cluster); cluster_op = cluster_get_op_type(false_cluster); c_type[cluster_id] = cluster_op; if (!c_used[cluster_id]) { cluster[cluster_id] = false_cluster; c_g_pvec[cluster_id] = 0; c_used[cluster_id] = 1; } list_t tab_cs_list; list_init(&tab_cs_list); col_sym_t *tab_cs, *tmp_cs; tmp_cs = list_entry(cs_list->next, col_sym_t, col_sym_listp); tab_cs = (col_sym_t *) malloc(sizeof(col_sym_t)); init_col_sym(tab_cs); int tid = sym_field(tmp_cs, db_tid); set_col_sym_tid_cid(tab_cs, tid, tid); list_insert(&tab_cs_list, &tab_cs->col_sym_listp); g_tmp_pv = 0; ret = cluster_get_pid_for_col_list(false_cluster, &tab_cs_list, &g_tmp_pv); c_g_pvec[cluster_id] |= g_tmp_pv; free_col_sym(&tab_cs); #endif } else { cluster_id = cluster_get_id(tmp_c); cluster_op = cluster_get_op_type(tmp_c); c_type[cluster_id] = cluster_op; if (!c_used[cluster_id]) { cluster[cluster_id] = tmp_c; if (cluster_op == OP_AND) c_g_pvec[cluster_id] = -1; else c_g_pvec[cluster_id] = 0; c_used[cluster_id] = 1; } if (cluster_op == OP_AND) { c_g_pvec[cluster_id] &= g_tmp_pv; if (c_g_pvec[cluster_id] == 0) { error_print_col_link(qi->log_info.f, cs); } } else { c_g_pvec[cluster_id] |= g_tmp_pv; } } #if DEBUG printf("cs:(%s,%s) cluster: %d, op: %d, tmp: %lu, new pv: %lu\n", sym_field(cs, db_tname), sym_field(cs, db_cname), cluster_id, cluster_op, g_tmp_pv, c_g_pvec[cluster_id]); #endif } } #if 0 if (fail) { if (c_type) free(c_type); if (c_used) free(c_used); if (cluster) free(cluster); if (c_g_pvec) free(c_g_pvec); return -1; } #endif // if more than one policies set in a lattice, pick the least restrictive one int16_t least_pid = -1; PVEC tmp_pvec = 0; for (i = 0; i < n_cluster; i++) { if (!cluster[i]) continue; if (c_type[i] == OP_OR) continue; if (c_g_pvec[i] == 0) { fprintf(qi->log_info.f, "Qapla ERROR!! link policy is false, cluster: %d\n", i); } least_pid = get_least_restrictive_pid(cluster[i], c_g_pvec[i]); if (least_pid < 0) continue; tmp_pvec |= ((PVEC) 1 << least_pid); #if DEBUG printf("%d. least pid: %d\n", i, least_pid); #endif c_g_pvec[i] = tmp_pvec; } // policies from different clusters are independent, // all of them must be applied in conjunction, set all bits final_pv = 0; int any_policy = 0; for (i = 0; i < n_cluster; i++) { if (!c_used[i]) continue; final_pv |= c_g_pvec[i]; any_policy = 1; } if (c_type) free(c_type); if (c_used) free(c_used); if (cluster) free(cluster); if (c_g_pvec) free(c_g_pvec); if (any_policy) { *pv = final_pv; return 0; } return -1; } int get_sql_clauses_in_pol(qapla_policy_t *qp, query_info_int_t *qi, uint64_t tid, char **q, int *qlen) { int i, dlog_ret, sql_ret = 0; // == init dlog interpreter env == dlog_pi_env_t env; dlog_ret = dlog_pi_env_init(&env, qp, QP_PERM_READ, &qi->session); int num_clause = qapla_get_num_perm_clauses(qp, QP_PERM_READ); char **sql_resolved = (char **) malloc(sizeof(char *) * num_clause); int *sql_resolved_len = (int *) malloc(sizeof(int) * num_clause); memset(sql_resolved, 0, sizeof(char *) * num_clause); memset(sql_resolved_len, 0, sizeof(int) * num_clause); int n_valid_clause = 0; char *newquery; int newquery_len = 0; char *or_str = (char *) "or"; int or_str_len = strlen("or") + 1; char *false_str = (char *) "1=0"; char *true_str = (char *) "1=1"; int false_str_len = strlen(false_str); int true_str_len = strlen(true_str); qapla_policy_t out_qp_buf, *out_qp; out_qp = &out_qp_buf; // split sql_parse_params into per-tid? list_t sym_list; list_init(&sym_list); symbol_t *sym = (symbol_t *) malloc(sizeof(symbol_t)); init_symbol(sym); set_sym_field(sym, db_tid, tid); list_insert(&sym_list, &sym->symbol_listp); for (i = 0; i < num_clause; i++) { dlog_ret = dlog_pi_evaluate(qp, QP_PERM_READ, i, &env); if (dlog_ret != DLOG_PI_GRANTED_PERM) continue; #if (CONFIG_REFMON == RM_CACHE_FULL_POLICY) memset(&out_qp_buf, 0, sizeof(qapla_policy_t)); sql_ret = sql_parse_params(qp, QP_PERM_READ, i, &env, out_qp, &sym_list); if (sql_ret == SQL_PI_FAILURE) { dlog_pi_env_unsetAllVars(&env); continue; } if (sql_ret == SQL_PI_DISALLOWED) { sql_resolved[n_valid_clause] = strndup(false_str, false_str_len); sql_resolved_len[n_valid_clause] = false_str_len + 1; } else if (sql_ret == SQL_PI_GRANTED_PERM) { sql_resolved[n_valid_clause] = strndup(true_str, true_str_len); sql_resolved_len[n_valid_clause] = true_str_len + 1; } else { char *cls = qapla_get_perm_clause_start(out_qp, QP_PERM_READ, CTYPE_SQL, 0); #else char *cls = qapla_get_perm_clause_start(qp, QP_PERM_READ, CTYPE_SQL, i); #endif dlog_pi_op_t *sql_op = (dlog_pi_op_t *) cls; char *sql = get_var_length_ptr(&sql_op->tuple, 1); uint16_t sql_len = get_var_length_ptr_len(&sql_op->tuple, 1); sql_resolved[n_valid_clause] = (char *) malloc(sql_len); memset(sql_resolved[n_valid_clause], 0, sql_len); memcpy(sql_resolved[n_valid_clause], sql, sql_len - 1); sql_resolved_len[n_valid_clause] = sql_len; #if (CONFIG_REFMON == RM_CACHE_FULL_POLICY) } #endif newquery_len += sql_resolved_len[n_valid_clause]; n_valid_clause++; // unset env before evaluating next clause dlog_pi_env_unsetAllVars(&env); } if (n_valid_clause > 0) newquery_len += ((n_valid_clause - 1) * or_str_len); else newquery_len += false_str_len + 1; newquery_len += 2; // for adding parantheses newquery = (char *) malloc(newquery_len); memset(newquery, 0, newquery_len); char *ptr = newquery; memcpy(ptr, "(", 1); ptr += 1; if (n_valid_clause > 0) { for(i = 0; i < n_valid_clause - 1; i++) { memcpy(ptr, sql_resolved[i], sql_resolved_len[i]-1); ptr += (sql_resolved_len[i] - 1); memcpy(ptr, " ", 1); ptr += 1; memcpy(ptr, or_str, or_str_len - 1); ptr += (or_str_len - 1); memcpy(ptr, " ", 1); ptr += 1; } memcpy(ptr, sql_resolved[i], sql_resolved_len[i] - 1); ptr += (sql_resolved_len[i] - 1); } else { memcpy(ptr, false_str, false_str_len); ptr += false_str_len; } memcpy(ptr, ")", 1); ptr += 1; #if DEBUG printf("computed new query len: %d, ptr-newquery: %d\n", newquery_len, (int) (ptr - newquery)); #endif *q = newquery; *qlen = newquery_len; dlog_pi_env_cleanup(&env); list_remove(&sym->symbol_listp); list_init(&sym_list); free(sym); sym = NULL; for (i = 0; i < n_valid_clause; i++) free(sql_resolved[i]); free(sql_resolved); free(sql_resolved_len); return 0; } int add_sql_to_table(char **curr_q, int *curr_qlen, char *q, int qlen) { if (!curr_q || !q || !curr_qlen || !qlen) return -1; char *and_str = (char *) "AND"; int and_str_len = strlen("AND"); int new_qlen = qlen; new_qlen = new_qlen + (*curr_qlen > 0 ? (*curr_qlen+and_str_len+1) : 0); char *new_q = (char *) malloc(new_qlen); memset(new_q, 0, new_qlen); char *ptr = new_q; if (*curr_qlen) { memcpy(ptr, *curr_q, *curr_qlen - 1); ptr += *curr_qlen - 1; memcpy(ptr, " ", 1); ptr += 1; memcpy(ptr, and_str, and_str_len); ptr += and_str_len; memcpy(ptr, " ", 1); ptr += 1; } memcpy(ptr, q, qlen - 1); ptr += qlen - 1; if (*curr_qlen) { free(*curr_q); } *curr_q = new_q; *curr_qlen = new_qlen; return 0; } int query_pvec_get_policy_list(query_info_int_t *qi, PVEC pv, qapla_policy_t ***pol_list, int *n_pol_list) { int i, pid_it, is_set, n_pid = 0; PVEC i_pvec = 0; uint16_t *pid; qapla_policy_t **qp; for (i = 0; i < MAX_POLICIES; i++) { i_pvec = (PVEC) (pv >> i); is_set = (int) (i_pvec & 1); if (is_set == 0) continue; #if DEBUG printf("query apply policy, pid: %d\n", i); #endif n_pid++; } pid = (uint16_t *) malloc(sizeof(uint16_t) * n_pid); qp = (qapla_policy_t **) malloc(sizeof(qapla_policy_t *) * n_pid); pid_it = 0; for (i = 0; i < MAX_POLICIES; i++) { i_pvec = (PVEC) (pv >> i); is_set = (int) (i_pvec & 1); if (is_set == 0) continue; pid[pid_it] = (uint16_t) i; qp[pid_it] = (qapla_policy_t *) get_pol_for_pid(&qi->qm, pid[pid_it]); pid_it++; } *pol_list = qp; *n_pol_list = n_pid; free(pid); return 0; } int free_policy_list(qapla_policy_t ***pol_list, int n_pol_list) { if (!pol_list || !(*pol_list)) return 0; qapla_policy_t **qp = *pol_list; free(qp); *pol_list = NULL; return 0; } int dedupe_col_list(list_t *dedupe_list, col_sym_t *cs) { col_sym_t *dedupe_cs, *match_cs; if (exists_col_sym_in_list(cs, dedupe_list, 0, &match_cs) == 0) return 1; dedupe_cs = dup_col_sym(cs); list_insert(dedupe_list, &dedupe_cs->col_sym_listp); return 0; } static int get_sql_for_table(char **curr_q, int *curr_qlen, char *tname, db_t *schema, char **p_arr, int *p_len_arr, int n_pid, list_t *expected_col_list, list_t *unexpected_col_list, list_t *actual_list) { if (!curr_q) return -1; char *select_str = (char *) "select "; char *all_str = (char *) "* "; char *from_str = (char *) "from "; char *where_str = (char *) "where "; char *and_str = (char *) "AND "; int select_str_len = strlen(select_str); int all_str_len = strlen(all_str); int from_str_len = strlen(from_str); int where_str_len = strlen(where_str); int and_str_len = strlen(and_str); int tname_str_len = strlen(tname); int all_expected = 0; int i, j = 0; int n_valid_pol = 0; int new_qlen = 0; char *new_q = NULL, *ptr; int tid = get_schema_table_id(schema, tname); int n_col = get_schema_num_col_in_table_id(schema, tid); int select_col_str_len = n_col * MAX_NAME_LEN; int curr_select_col_str_len = 0; int first_col = 1; char *select_col_str = (char *) malloc(select_col_str_len); memset(select_col_str, 0, select_col_str_len); list_t dedupe_cs_list; list_init(&dedupe_cs_list); if ((!expected_col_list || list_empty(expected_col_list)) && (!unexpected_col_list || list_empty(unexpected_col_list))) all_expected = 1; for (i = 0; i < n_pid; i++) { if (p_arr[i] && p_len_arr[i]) { n_valid_pol++; new_qlen += (p_len_arr[i] - 1); new_qlen += 1; // +1 for space after each policy string } } new_qlen += (n_valid_pol - 1) * and_str_len; new_qlen += select_str_len + from_str_len + where_str_len + tname_str_len + 1; if (all_expected) new_qlen += all_str_len; else { // compute new_qlen taking into account the expected and unexpected list symbol_t *a_sym; col_sym_t *a_cs; list_t *a_cs_list; list_for_each_entry(a_sym, actual_list, symbol_listp) { a_cs_list = &a_sym->col_sym_list; list_for_each_entry(a_cs, a_cs_list, col_sym_listp) { if (sym_field(a_cs, db_tid) != tid) continue; if (dedupe_col_list(&dedupe_cs_list, a_cs)) continue; if (!first_col) { sprintf(select_col_str + curr_select_col_str_len, ", "); curr_select_col_str_len = strlen(select_col_str); } if (a_cs->is_expected) { sprintf(select_col_str + curr_select_col_str_len, "%s.%s", tname, sym_field(a_cs, db_cname)); curr_select_col_str_len = strlen(select_col_str); if (first_col) first_col = 0; } else if (a_cs->is_set && a_cs->is_expected == 0) { sprintf(select_col_str + curr_select_col_str_len, "null %s", sym_field(a_cs, db_cname)); curr_select_col_str_len = strlen(select_col_str); if (first_col) first_col = 0; } else { assert(0); } } } curr_select_col_str_len = strlen(select_col_str); new_qlen += strlen(select_col_str) + 1; // +1 for adding a space after the list } new_q = (char *) malloc(new_qlen); memset(new_q, 0, new_qlen); ptr = new_q; memcpy(ptr, select_str, select_str_len); ptr += select_str_len; if (all_expected) { memcpy(ptr, all_str, all_str_len); ptr += all_str_len; } else { memcpy(ptr, select_col_str, curr_select_col_str_len); ptr += curr_select_col_str_len; memcpy(ptr, " ", 1); ptr += 1; } memcpy(ptr, from_str, from_str_len); ptr += from_str_len; memcpy(ptr, tname, tname_str_len); ptr += tname_str_len; memcpy(ptr, " ", 1); ptr += 1; memcpy(ptr, where_str, where_str_len); ptr += where_str_len; j = 0; for (i = 0; i < n_pid; i++) { if (p_arr[i] && p_len_arr[i]) { j++; memcpy(ptr, p_arr[i], p_len_arr[i] - 1); ptr += p_len_arr[i] - 1; if (j == n_valid_pol) break; memcpy(ptr, " ", 1); ptr += 1; memcpy(ptr, and_str, and_str_len); ptr += and_str_len; } } *curr_q = new_q; *curr_qlen = new_qlen; // cleanup allocated memory if (select_col_str) free(select_col_str); cleanup_col_sym_list(&dedupe_cs_list); return 0; } int get_resolved_sql_pol(query_info_int_t *qi, qapla_policy_t **qp, int n_pid, qapla_perm_id_t perm, char ***tab_sql_str, int **tab_sql_str_len, int *n_tab_sql, list_t *table_list) { if (!qp || !(*qp)) return -1; context_t *currC = get_curr_context(&qi->pc); list_t *tab_list = &currC->symbol_list[SYM_TAB]; list_t *actual_list = &currC->symbol_list[SYM_COL]; qstr_t *qstr = &qi->qstr; list_t *expected_list = qstr_get_expected_col_list(qstr); list_t *unexpected_list = qstr_get_unexpected_col_list(qstr); int is_match = 0; int ret, i; // count # tables in query, for which policies must be applied uint64_t tid; char *tname; symbol_t *new_tsym; int n_tab = 0; uint64_t tab_arr[10]; // approx., there may not be more than 10 tables in a single query int max_tab = 10; memset(tab_arr, 0, sizeof(uint64_t) * max_tab); ret = get_distinct_table_array(tab_arr, &n_tab, max_tab, tab_list); assert(!ret); for (i = 0; i < n_tab; i++) { tid = tab_arr[i]; assert(((int)tid >= 0) && ((int) tid != DUAL_TID)); //if ((int) tid < 0) // continue; tname = get_schema_table_name(&qi->schema, (int) tid); new_tsym = (symbol_t *) malloc(sizeof(symbol_t)); init_symbol(new_tsym); set_sym_str_field(new_tsym, db_tname, tname); set_sym_field(new_tsym, db_tid, tid); list_insert_at_tail(table_list, &new_tsym->symbol_listp); } // array of final policy string for each table char **tab_sql = (char **) malloc(sizeof(char *) * n_tab); int *tab_sql_len = (int *) malloc(sizeof(int) * n_tab); memset(tab_sql, 0, sizeof(char *) * n_tab); memset(tab_sql_len, 0, sizeof(int) * n_tab); int tab_idx = 0; // array to hold policy strings to be appended to a table char **pol_for_tab = (char **) malloc(sizeof(char *) * n_pid); int *pol_for_tab_len = (int *) malloc(sizeof(int) * n_pid); memset(pol_for_tab, 0, sizeof(char *) * n_pid); memset(pol_for_tab_len, 0, sizeof(int) * n_pid); /* * for each tid * for each policy qp in pvec list * if policy applied to cs.db_tid * for each clause in qp * if eval(qp.dlog) = success * add qp.sql to pol_buf with an OR * append pol_buf to tab_pol_buf[db_tid] with an AND */ int tab_it; int q_pid; for (tab_it = 0; tab_it < n_tab; tab_it++) { tid = tab_arr[tab_it]; tname = get_schema_table_name(&qi->schema, tid); tab_idx = get_table_index(tab_arr, n_tab, tid); memset(pol_for_tab, 0, sizeof(char *) * n_pid); for (i = 0; i < n_pid; i++) { is_match = match_sql_table_in_pol(qp[i], perm, tid); #if DEBUG q_pid = qapla_get_policy_id(qp[i]); printf("query tid: %d pol id: %d, match: %d\n", tid, q_pid, is_match); #endif if (!is_match) continue; ret = get_sql_clauses_in_pol(qp[i], qi, tid, &pol_for_tab[i], &pol_for_tab_len[i]); } get_sql_for_table(&tab_sql[tab_idx], &tab_sql_len[tab_idx], tname, &qi->schema, pol_for_tab, pol_for_tab_len, n_pid, expected_list, unexpected_list, actual_list); for (i = 0; i < n_pid; i++) { if (pol_for_tab[i] && pol_for_tab_len[i]) { free(pol_for_tab[i]); pol_for_tab[i] = NULL; pol_for_tab_len[i] = 0; } } } *tab_sql_str = tab_sql; *tab_sql_str_len = tab_sql_len; *n_tab_sql = n_tab; if (pol_for_tab) { for (i = 0; i < n_pid; i++) { if (pol_for_tab[i] && pol_for_tab_len[i]) free(pol_for_tab[i]); } free(pol_for_tab); } if (pol_for_tab_len) free(pol_for_tab_len); return 0; }
955725.c
/* * Trabalho 3 de Oficina de Programação * Vytor S.B. Calixto */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_mixer.h> #include <time.h> #include "predio.h" #include "libpredio.h" #include "global.h" //Lê os parâmetros passados na linha de comando, retorna false caso ocorra um erro bool lerParametros(int argc, char **argv); //Retorna true se o SDL inicializou de forma correta, false caso contrário bool iniciaSDL(); //Libera da memória as texturas, janelas, renderers e termina o SDL void fechaSDL(); //Lida com os eventos de teclado durante o jogo void validaEventos(SDL_Event event); //Retorna true se Jirobaldo está numa posição válida no mapa bool jirobaldoValido(); //Renderiza texto void renderText(TTF_Font *fonte, char *texto, SDL_Rect aux, SDL_Color cor, int align); //Renderiza a barra de informações (baldes, passos, andar) void renderInfoBar(SDL_Rect aux); //Retorna true se a posição atual do Jirobaldo é a saída bool isSaida(); //Gera um novo Edificio (Edificio é a antiga estrutura Predio na solução do Flávio) void novoEdificio(Edificio *edificio); //Tela de abertura void splashScreen(); //Tela de encerramento void fimJogo(); //Encerramento ruim void jiroDeath(); //Função para esperar o tempo correto void renderDelay(Uint32 renderTime); int main(int argc, char **argv){ bool quit = false; SDL_Event event; SDL_Rect aux; Uint32 renderTime, ticks = 0; //Tempo inicial //Lê os parâmetros da linha de comando if(!lerParametros(argc, argv)){ puts("ERRO: Digite um número inteira na entrada"); return 1; } //Lê o arquivo do prédio if(arquivo == NULL){ puts("ERRO: Nenhum arquivo foi especificado."); return 1; } if(!novoPredio(&predio, arquivo)){ puts("ERRO: Não foi possível criar o prédio. O arquivo é válido?"); return 1; } /* * Edificio é a "antiga" struct Predio na solução do Flávio. */ Edificio edificio; novoEdificio(&edificio); //Inicia SDL if(!iniciaSDL()){ puts("ERRO: não foi possível iniciar o SDL"); return 1; } //Cria a janela e o renderizador window = SDL_CreateWindow("Jirobaldo: Sobrevivente", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); screen = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); //Carrega as texturas do prédio e do Jirobaldo carregarTexturasPredio(screen, &predio); carregarTexturasJirobaldo(screen, &predio.jirobaldo); //Carrega fontes e sons titleFont = TTF_OpenFont("data/fonts/Plane-Crash.ttf", 48); water = Mix_LoadWAV("data/audio/water-splash.wav"); titleTheme = Mix_LoadMUS("data/audio/bost-imagine-the-fire.ogg"); fire = Mix_LoadMUS("data/audio/fire.wav"); doors = Mix_LoadMUS("data/audio/light-my-fire.ogg"); footstep = Mix_LoadWAV("data/audio/footstep3.wav"); Mix_PlayMusic(titleTheme, -1); //SplashScreen splashScreen(); //Gera a solução resp = predio_resolve(&edificio); if(resp->len < 0){ puts("ERRO: o mapa não tem solução"); return 1; } //Rect auxiliar para gerar as texturas dos andares aux.h = (predio.h >= predio.w) ? (gameViewport.h/predio.h) : (gameViewport.w/predio.w); aux.w = aux.h; aux.x = 0; aux.y = 0; /* * Gera as texturas do andares (para mapas grandes pode demorar um pouco, * mas compensa na velocidade de renderização) */ gerarTexturasAndares(screen, &predio, aux); /* * Loop princpial: * Render do mapa * Lida com os eventos: * Se for simulador lida com a jogabilidade * Se for resolvedor, avança/retrocede um passo */ Mix_FadeOutMusic(2000); Mix_PlayMusic(fire, -1); while(!quit){ renderTime = SDL_GetTicks(); SDL_SetRenderDrawColor(screen, 0, 0, 0, 255); SDL_RenderClear(screen); //Renderiza a barra de status SDL_RenderSetViewport(screen, &infoBarViewport); aux.h = INFO_BAR_HEIGHT; aux.x = 0; aux.y = 0; renderInfoBar(aux); //Renderiza o 'jogo' principal aux.h = (predio.h >= predio.w) ? (gameViewport.h/predio.h) : (gameViewport.w/predio.w); aux.w = aux.h; SDL_RenderSetViewport(screen, &gameViewport); renderAndarPredio(screen, &predio, predio.jirobaldo.z, aux); //Renderiza o mini-mapa do andar de cima if(predio.jirobaldo.z-1 >= 0){ aux.h = downMapViewport.h/predio.h; aux.w = aux.h; SDL_RenderSetViewport(screen, &downMapViewport); renderAndarPredio(screen, &predio, predio.jirobaldo.z - 1, aux); } //Renderiza o mini-mapa do andar de baixo if(predio.jirobaldo.z+1 < predio.altura){ aux.h = topMapViewport.h/predio.h; aux.w = aux.h; SDL_RenderSetViewport(screen, &topMapViewport); renderAndarPredio(screen, &predio, predio.jirobaldo.z + 1, aux); } SDL_RenderPresent(screen); //Se for resolvedor, com passos por segundo > 0 e tiver passado o tempo para renderizar if(isModoResolvedor && passosPorSegundo > 0 && (SDL_GetTicks() - ticks >= (1000/passosPorSegundo))){ ticks = SDL_GetTicks(); //Empilha um evento com valor da seta direita SDL_Event evento; SDL_zero(evento); evento.type = SDL_KEYDOWN; evento.key.keysym.sym = SDLK_RIGHT; SDL_PushEvent(&evento); } quit = (bool) isSaida(); while(SDL_PollEvent(&event)){ if(event.type == SDL_QUIT){ quit = true; }else{ validaEventos(event); } } renderDelay(renderTime); } if(passos >= resp->len){ //Animação de fim de jogo Mix_PlayMusic(doors, -1); fimJogo(); } Mix_HaltMusic(); fechaSDL(); return 0; } bool lerParametros(int argc, char **argv){ int c; while((c = getopt(argc, argv, "sf:")) != -1){ switch(c){ case 's': isModoResolvedor = true; break; case 'f': passosPorSegundo = atof(optarg); if(passosPorSegundo != atoi(optarg)){ passosPorSegundo = 0; return false; } break; } } isModoResolvedor = (passosPorSegundo > 0); if(optind < argc){ arquivo = argv[optind]; } return true; } bool iniciaSDL(){ if(SDL_Init(SDL_INIT_VIDEO) < 0){ return false; } if(!IMG_Init(IMG_INIT_PNG)){ return false; } if(TTF_Init() < 0){ return false; } if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1){ return false; } //Define as dimensões das viewports infoBarViewport.x = 0; infoBarViewport.y = 0; infoBarViewport.w = SCREEN_WIDTH; infoBarViewport.h = INFO_BAR_HEIGHT; gameViewport.x = 0; gameViewport.y = INFO_BAR_HEIGHT; gameViewport.w = SCREEN_WIDTH - (SCREEN_WIDTH*0.2); gameViewport.h = SCREEN_HEIGHT - INFO_BAR_HEIGHT; topMapViewport.x = SCREEN_WIDTH - (SCREEN_WIDTH*0.2); topMapViewport.y = INFO_BAR_HEIGHT; topMapViewport.w = (SCREEN_WIDTH*0.2); topMapViewport.h = (SCREEN_WIDTH*0.2); downMapViewport.x = SCREEN_WIDTH - (SCREEN_WIDTH*0.2); downMapViewport.y = INFO_BAR_HEIGHT + (SCREEN_WIDTH*0.2) + 10; //10px para separar os mapas downMapViewport.w = (SCREEN_WIDTH*0.2); downMapViewport.h = (SCREEN_WIDTH*0.2); return true; } void fechaSDL(){ Mix_FreeMusic(titleTheme); Mix_FreeMusic(fire); Mix_FreeMusic(doors); Mix_FreeChunk(footstep); Mix_FreeChunk(water); SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); TTF_CloseFont(titleFont); Mix_CloseAudio(); TTF_Quit(); IMG_Quit(); SDL_Quit(); } void validaEventos(SDL_Event event){ int x = predio.jirobaldo.x; int y = predio.jirobaldo.y; int z = predio.jirobaldo.z; //Se for resolvedor, aceita apenas eventos das setas para direita e esquerda if(isModoResolvedor){ if(event.type == SDL_KEYDOWN && (event.key.keysym.sym == SDLK_RIGHT || event.key.keysym.sym == SDLK_LEFT)){ int passo; int tecla = event.key.keysym.sym; if(tecla == SDLK_RIGHT){ passo = resp->p[passos]; if(passos < resp->len) passos++; }else if(tecla == SDLK_LEFT && passosPorSegundo == 0){ if(passos > 0) passos--; else return; passo = resp->p[passos]; }else{ return; } switch(passo){ case PASSO_CIMA: predio.jirobaldo.face = (tecla == SDLK_RIGHT) ? FACE_NORTH : FACE_SOUTH; predio.jirobaldo.isAnimating = true; tecla == SDLK_RIGHT ? predio.jirobaldo.x-- : predio.jirobaldo.x++; break; case PASSO_BAIXO: predio.jirobaldo.face = (tecla == SDLK_RIGHT) ? FACE_SOUTH : FACE_NORTH; predio.jirobaldo.isAnimating = true; tecla == SDLK_RIGHT ? predio.jirobaldo.x++ : predio.jirobaldo.x--; break; case PASSO_ESQUERDA: predio.jirobaldo.face = (tecla == SDLK_RIGHT) ? FACE_WEST : FACE_EAST; predio.jirobaldo.isAnimating = true; tecla == SDLK_RIGHT ? predio.jirobaldo.y-- : predio.jirobaldo.y++; break; case PASSO_DIREITA: predio.jirobaldo.face = (tecla == SDLK_RIGHT) ? FACE_EAST : FACE_WEST; predio.jirobaldo.isAnimating = true; tecla == SDLK_RIGHT ? predio.jirobaldo.y++ : predio.jirobaldo.y--; break; case PASSO_SOBE: tecla == SDLK_RIGHT ? predio.jirobaldo.z++ : predio.jirobaldo.z--; break; case PASSO_DESCE: tecla == SDLK_RIGHT ? predio.jirobaldo.z-- : predio.jirobaldo.z++; break; case PASSO_ENCHE: Mix_PlayChannel(-1, water, 0); tecla == SDLK_RIGHT ? predio.jirobaldo.baldes++ : predio.jirobaldo.baldes--; break; } jirobaldoValido(); } }else{ if(event.type == SDL_KEYDOWN){ switch(event.key.keysym.sym){ case SDLK_LEFT: predio.jirobaldo.y--; if(jirobaldoValido()){ predio.jirobaldo.face = FACE_WEST; predio.jirobaldo.isAnimating = true; passos++; Mix_PlayChannel(-1, footstep, 0); }else{ predio.jirobaldo.y++; } break; case SDLK_RIGHT: predio.jirobaldo.y++; if(jirobaldoValido()){ predio.jirobaldo.face = FACE_EAST; predio.jirobaldo.isAnimating = true; passos++; Mix_PlayChannel(-1, footstep, 0); }else{ predio.jirobaldo.y--; } break; case SDLK_UP: predio.jirobaldo.x--; if(jirobaldoValido()){ predio.jirobaldo.face = FACE_NORTH; predio.jirobaldo.isAnimating = true; passos++; Mix_PlayChannel(-1, footstep, 0); }else{ predio.jirobaldo.x++; } break; case SDLK_DOWN: predio.jirobaldo.x++; if(jirobaldoValido()){ predio.jirobaldo.face = FACE_SOUTH; predio.jirobaldo.isAnimating = true; passos++; Mix_PlayChannel(-1, footstep, 0); }else{ predio.jirobaldo.x--; } break; case SDLK_x: if(predio.pisos[z].pontos[x][y] == 'U' || predio.pisos[z].pontos[x][y] == 'E'){ predio.jirobaldo.z++; passos++; } break; case SDLK_z: if(predio.pisos[z].pontos[x][y] == 'D' || predio.pisos[z].pontos[x][y] == 'E'){ predio.jirobaldo.z--; passos++; } break; case SDLK_SPACE: if(predio.pisos[z].pontos[x][y] == 'T'){ predio.jirobaldo.baldes++; if(predio.jirobaldo.baldes > predio.jirobaldo.MAX_BALDES){ predio.jirobaldo.baldes--; }else{ Mix_PlayChannel(-1, water, 0); passos++; } } break; case SDLK_RETURN: predio.jirobaldo.x = predio.jirobaldo.sx; predio.jirobaldo.y = predio.jirobaldo.sy; predio.jirobaldo.z = predio.jirobaldo.sz; predio.jirobaldo.baldes = 0; passos = 0; break; } } } } bool jirobaldoValido(){ int x = predio.jirobaldo.x; int y = predio.jirobaldo.y; int z = predio.jirobaldo.z; int baldes = predio.jirobaldo.baldes; if(isPontoNoAndar(&predio.pisos[z], x, y)){ if(predio.pisos[z].pontos[x][y] == 'F'){ if(baldes > 0){ predio.jirobaldo.baldes--; }else{ return false; } } } return (isPontoNoAndar(&predio.pisos[z], x, y)) && (predio.pisos[z].pontos[x][y] != '#'); } void renderText(TTF_Font *fonte, char *texto, SDL_Rect aux, SDL_Color cor, int align){ SDL_Surface *tmp; SDL_Texture *textoTex; SDL_Rect textoRect; tmp = TTF_RenderUTF8_Solid(fonte, texto, cor); textoTex = SDL_CreateTextureFromSurface(screen, tmp); textoRect.w = tmp->w; textoRect.h = tmp->h; textoRect.x = 0; textoRect.y = 0; aux.w = textoRect.w/2; if(align == 1){ aux.x = SCREEN_WIDTH/2 - aux.w/2; }else if(align == 2){ aux.x = SCREEN_WIDTH - aux.w; } SDL_RenderCopy(screen, textoTex, &textoRect, &aux); SDL_FreeSurface(tmp); SDL_DestroyTexture(textoTex); } void renderInfoBar(SDL_Rect aux){ char baldes[20]; sprintf(baldes, "baldes: %d/%d", predio.jirobaldo.baldes, predio.jirobaldo.MAX_BALDES); renderText(titleFont, baldes, aux, (SDL_Color) {200, 200, 200}, 0); char andar[20]; sprintf(andar, "andar: %d/%d", predio.jirobaldo.z + 1, predio.altura); renderText(titleFont, andar, aux, (SDL_Color) {200, 200, 200}, 1); char moves[20]; sprintf(moves, "moves: %d", passos); renderText(titleFont, moves, aux, (SDL_Color) {200, 200, 200}, 2); } bool isSaida(){ int x = predio.jirobaldo.x; int y = predio.jirobaldo.y; int z = predio.jirobaldo.z; bool animating = isModoResolvedor ? false : predio.jirobaldo.isAnimating; return (predio.pisos[z].pontos[x][y] == 'S' && ! animating); } void novoEdificio(Edificio *edificio){ int i, j; FILE *file = fopen(arquivo, "r"); fscanf(file, "%d %d %d %d", &(edificio->A), &(edificio->W), &(edificio->H), &(edificio->B)); for(i = 0; i < edificio->A; i++){ for(j = 0; j < edificio->H; j++){ fscanf(file, "%s", edificio->m[i][j]); } } fclose(file); } void splashScreen(){ SDL_Texture *title, *subtitle; SDL_Rect titleRect, subtitleRect; SDL_Surface *tmp; Uint8 alpha = 0; tmp = TTF_RenderUTF8_Solid(titleFont, "jirobaldo", (SDL_Color) {180, 0, 0}); title = SDL_CreateTextureFromSurface(screen, tmp); SDL_SetTextureAlphaMod(title, alpha); titleRect.w = tmp->w; titleRect.h = tmp->h; titleRect.x = SCREEN_WIDTH/2 - titleRect.w/2; titleRect.y = SCREEN_HEIGHT/2 - titleRect.h/2; SDL_FreeSurface(tmp); tmp = TTF_RenderUTF8_Solid(titleFont, "sobrevivente", (SDL_Color) {200, 200, 200}); subtitle = SDL_CreateTextureFromSurface(screen, tmp); SDL_SetTextureAlphaMod(subtitle, alpha); subtitleRect.w = tmp->w; subtitleRect.h = tmp->h; subtitleRect.x = SCREEN_WIDTH/2 - subtitleRect.w/2; subtitleRect.y = titleRect.y + subtitleRect.h; SDL_FreeSurface(tmp); while(alpha < 255){ SDL_SetRenderDrawColor(screen, 0, 0, 0, 255); SDL_RenderClear(screen); SDL_RenderCopy(screen, title, NULL, &titleRect); SDL_RenderCopy(screen, subtitle, NULL, &subtitleRect); SDL_RenderPresent(screen); alpha+=3; SDL_SetTextureAlphaMod(title, alpha); SDL_SetTextureAlphaMod(subtitle, alpha); SDL_Delay(1000/30); } SDL_DestroyTexture(title); SDL_DestroyTexture(subtitle); } void fimJogo(){ SDL_Texture *congrats; SDL_Rect congratsRect, jiroRect; SDL_Surface *tmp; Uint8 alpha = 0; bool quit = false; SDL_Event event; tmp = TTF_RenderUTF8_Solid(titleFont, "jirobaldo vive", (SDL_Color) {255, 165, 0}); congrats = SDL_CreateTextureFromSurface(screen, tmp); SDL_SetTextureAlphaMod(congrats, alpha); congratsRect.w = tmp->w; congratsRect.h = tmp->h; congratsRect.x = SCREEN_WIDTH/2 - congratsRect.w/2; congratsRect.y = SCREEN_HEIGHT/2 - congratsRect.h/2; jiroRect.w = 64; jiroRect.h = 64; jiroRect.x = SCREEN_WIDTH/2 - jiroRect.w/2; jiroRect.y = congratsRect.y + jiroRect.h; SDL_FreeSurface(tmp); predio.jirobaldo.face = FACE_SOUTH; predio.jirobaldo.isAnimating = true; predio.jirobaldo.frame = 0; SDL_RenderSetViewport(screen, NULL); while(!quit){ SDL_SetRenderDrawColor(screen, 0, 0, 0, 255); SDL_RenderClear(screen); SDL_RenderCopy(screen, congrats, NULL, &congratsRect); renderDanceJirobaldo(screen, &predio.jirobaldo, jiroRect); SDL_RenderPresent(screen); alpha+=5; SDL_SetTextureAlphaMod(congrats, alpha); while(SDL_PollEvent(&event)){ if(event.type == SDL_QUIT){ quit = true; } } SDL_Delay(1000/30); } SDL_DestroyTexture(congrats); } void renderDelay(Uint32 renderTime){ Uint32 t = SDL_GetTicks(); Uint32 delay = 1000/30; //"30 fps" Uint32 render = t - renderTime; if(isModoResolvedor && passosPorSegundo > 30 && passosPorSegundo <= 1000){ delay = 1000/passosPorSegundo; }else if(passosPorSegundo > 1000){ delay = 1; } if(render < delay){ SDL_Delay(delay - render - 1); } }
972063.c
/*************************************************************************** Konami IC 033906 (PCI bridge) ***************************************************************************/ #include "emu.h" #include "k033906.h" #include "video/voodoo.h" #include "devhelpr.h" //************************************************************************** // LIVE DEVICE //************************************************************************** // device type definition const device_type K033906 = &device_creator<k033906_device>; //------------------------------------------------- // k033906_device - constructor //------------------------------------------------- k033906_device::k033906_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : device_t(mconfig, K033906, "Konami 033906", tag, owner, clock) { } //------------------------------------------------- // device_config_complete - perform any // operations now that the configuration is // complete //------------------------------------------------- void k033906_device::device_config_complete() { // inherit a copy of the static data const k033906_interface *intf = reinterpret_cast<const k033906_interface *>(static_config()); if (intf != NULL) { *static_cast<k033906_interface *>(this) = *intf; } // or initialize to defaults if none provided else { m_voodoo_tag = NULL; } } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void k033906_device::device_start() { m_voodoo = machine().device(m_voodoo_tag); m_reg = auto_alloc_array(machine(), UINT32, 256); m_ram = auto_alloc_array(machine(), UINT32, 32768); m_reg_set = 0; save_pointer(NAME(m_reg), 256); save_pointer(NAME(m_ram), 32768); save_item(NAME(m_reg_set)); } WRITE_LINE_DEVICE_HANDLER_TRAMPOLINE(k033906, k033906_set_reg) { m_reg_set = state & 1; } UINT32 k033906_device::k033906_reg_r(int reg) { switch (reg) { case 0x00: return 0x0001121a; // PCI Vendor ID (0x121a = 3dfx), Device ID (0x0001 = Voodoo) case 0x02: return 0x04000000; // Revision ID case 0x04: return m_reg[0x04]; // memBaseAddr case 0x0f: return m_reg[0x0f]; // interrupt_line, interrupt_pin, min_gnt, max_lat default: fatalerror("%s: k033906_reg_r: %08X", machine().describe_context(), reg); } return 0; } void k033906_device::k033906_reg_w(int reg, UINT32 data) { switch (reg) { case 0x00: break; case 0x01: // command register break; case 0x04: // memBaseAddr { if (data == 0xffffffff) { m_reg[0x04] = 0xff000000; } else { m_reg[0x04] = data & 0xff000000; } break; } case 0x0f: // interrupt_line, interrupt_pin, min_gnt, max_lat { m_reg[0x0f] = data; break; } case 0x10: // initEnable { voodoo_set_init_enable(m_voodoo, data); break; } case 0x11: // busSnoop0 case 0x12: // busSnoop1 break; case 0x38: // ??? break; default: fatalerror("%s:K033906_w: %08X, %08X", machine().describe_context(), data, reg); } } READ32_DEVICE_HANDLER_TRAMPOLINE(k033906, k033906_r) { if(m_reg_set) { return k033906_reg_r(offset); } else { return m_ram[offset]; } } WRITE32_DEVICE_HANDLER_TRAMPOLINE(k033906, k033906_w) { if(m_reg_set) { k033906_reg_w(offset, data); } else { m_ram[offset] = data; } }
646087.c
/* Figura 6.9: fig06_09.c Lança um dado de 6 lados 6000 vezes */ #include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 7 /* função main inicia a execução do programa */ int main(void) { int face; /* valor aleatório de 1 - 6 do dado (face do dado) */ int roll; /* contador de lançamentos de 1-6000 */ int frequency[SIZE] = { 0 }; /* limpa contadores */ srand(time( NULL )); /* semente do gerador de números aleatórios */ /* rola dado 6000 vezes */ for (roll = 1; roll <= 6000; roll++) { face = 1 + rand() % 6; //almentando o valor do elemento na posicao face(a posicao que o face vai receber) ++frequency[face]; /* substitui switch de 26 linhas da Fig. 5.8 */ } /* fim do for */ printf("%s%17s\n", "Face", "Frequency"); /* mostra elementos de frequência 1-6 em formato tabular */ for ( face = 1; face < SIZE; face++ ) { printf("%4d%17d\n", face, frequency[ face ] ); } /* fim do for */ return 0; /* indica conclusão bem-sucedida */ } /* fim do main */
107900.c
// SPDX-License-Identifier: GPL-2.0-only /* * fs/kernfs/dir.c - kernfs directory implementation * * Copyright (c) 2001-3 Patrick Mochel * Copyright (c) 2007 SUSE Linux Products GmbH * Copyright (c) 2007, 2013 Tejun Heo <[email protected]> */ #include <linux/sched.h> #include <linux/fs.h> #include <linux/namei.h> #include <linux/idr.h> #include <linux/slab.h> #include <linux/security.h> #include <linux/hash.h> #include "kernfs-internal.h" static DEFINE_SPINLOCK(kernfs_rename_lock); /* kn->parent and ->name */ static char kernfs_pr_cont_buf[PATH_MAX]; /* protected by rename_lock */ static DEFINE_SPINLOCK(kernfs_idr_lock); /* root->ino_idr */ #define rb_to_kn(X) rb_entry((X), struct kernfs_node, rb) static bool kernfs_active(struct kernfs_node *kn) { lockdep_assert_held(&kernfs_root(kn)->kernfs_rwsem); return atomic_read(&kn->active) >= 0; } static bool kernfs_lockdep(struct kernfs_node *kn) { #ifdef CONFIG_DEBUG_LOCK_ALLOC return kn->flags & KERNFS_LOCKDEP; #else return false; #endif } static int kernfs_name_locked(struct kernfs_node *kn, char *buf, size_t buflen) { if (!kn) return strlcpy(buf, "(null)", buflen); return strlcpy(buf, kn->parent ? kn->name : "/", buflen); } /* kernfs_node_depth - compute depth from @from to @to */ static size_t kernfs_depth(struct kernfs_node *from, struct kernfs_node *to) { size_t depth = 0; while (to->parent && to != from) { depth++; to = to->parent; } return depth; } static struct kernfs_node *kernfs_common_ancestor(struct kernfs_node *a, struct kernfs_node *b) { size_t da, db; struct kernfs_root *ra = kernfs_root(a), *rb = kernfs_root(b); if (ra != rb) return NULL; da = kernfs_depth(ra->kn, a); db = kernfs_depth(rb->kn, b); while (da > db) { a = a->parent; da--; } while (db > da) { b = b->parent; db--; } /* worst case b and a will be the same at root */ while (b != a) { b = b->parent; a = a->parent; } return a; } /** * kernfs_path_from_node_locked - find a pseudo-absolute path to @kn_to, * where kn_from is treated as root of the path. * @kn_from: kernfs node which should be treated as root for the path * @kn_to: kernfs node to which path is needed * @buf: buffer to copy the path into * @buflen: size of @buf * * We need to handle couple of scenarios here: * [1] when @kn_from is an ancestor of @kn_to at some level * kn_from: /n1/n2/n3 * kn_to: /n1/n2/n3/n4/n5 * result: /n4/n5 * * [2] when @kn_from is on a different hierarchy and we need to find common * ancestor between @kn_from and @kn_to. * kn_from: /n1/n2/n3/n4 * kn_to: /n1/n2/n5 * result: /../../n5 * OR * kn_from: /n1/n2/n3/n4/n5 [depth=5] * kn_to: /n1/n2/n3 [depth=3] * result: /../.. * * [3] when @kn_to is NULL result will be "(null)" * * Returns the length of the full path. If the full length is equal to or * greater than @buflen, @buf contains the truncated path with the trailing * '\0'. On error, -errno is returned. */ static int kernfs_path_from_node_locked(struct kernfs_node *kn_to, struct kernfs_node *kn_from, char *buf, size_t buflen) { struct kernfs_node *kn, *common; const char parent_str[] = "/.."; size_t depth_from, depth_to, len = 0; int i, j; if (!kn_to) return strlcpy(buf, "(null)", buflen); if (!kn_from) kn_from = kernfs_root(kn_to)->kn; if (kn_from == kn_to) return strlcpy(buf, "/", buflen); if (!buf) return -EINVAL; common = kernfs_common_ancestor(kn_from, kn_to); if (WARN_ON(!common)) return -EINVAL; depth_to = kernfs_depth(common, kn_to); depth_from = kernfs_depth(common, kn_from); buf[0] = '\0'; for (i = 0; i < depth_from; i++) len += strlcpy(buf + len, parent_str, len < buflen ? buflen - len : 0); /* Calculate how many bytes we need for the rest */ for (i = depth_to - 1; i >= 0; i--) { for (kn = kn_to, j = 0; j < i; j++) kn = kn->parent; len += strlcpy(buf + len, "/", len < buflen ? buflen - len : 0); len += strlcpy(buf + len, kn->name, len < buflen ? buflen - len : 0); } return len; } /** * kernfs_name - obtain the name of a given node * @kn: kernfs_node of interest * @buf: buffer to copy @kn's name into * @buflen: size of @buf * * Copies the name of @kn into @buf of @buflen bytes. The behavior is * similar to strlcpy(). It returns the length of @kn's name and if @buf * isn't long enough, it's filled upto @buflen-1 and nul terminated. * * Fills buffer with "(null)" if @kn is NULL. * * This function can be called from any context. */ int kernfs_name(struct kernfs_node *kn, char *buf, size_t buflen) { unsigned long flags; int ret; spin_lock_irqsave(&kernfs_rename_lock, flags); ret = kernfs_name_locked(kn, buf, buflen); spin_unlock_irqrestore(&kernfs_rename_lock, flags); return ret; } /** * kernfs_path_from_node - build path of node @to relative to @from. * @from: parent kernfs_node relative to which we need to build the path * @to: kernfs_node of interest * @buf: buffer to copy @to's path into * @buflen: size of @buf * * Builds @to's path relative to @from in @buf. @from and @to must * be on the same kernfs-root. If @from is not parent of @to, then a relative * path (which includes '..'s) as needed to reach from @from to @to is * returned. * * Returns the length of the full path. If the full length is equal to or * greater than @buflen, @buf contains the truncated path with the trailing * '\0'. On error, -errno is returned. */ int kernfs_path_from_node(struct kernfs_node *to, struct kernfs_node *from, char *buf, size_t buflen) { unsigned long flags; int ret; spin_lock_irqsave(&kernfs_rename_lock, flags); ret = kernfs_path_from_node_locked(to, from, buf, buflen); spin_unlock_irqrestore(&kernfs_rename_lock, flags); return ret; } EXPORT_SYMBOL_GPL(kernfs_path_from_node); /** * pr_cont_kernfs_name - pr_cont name of a kernfs_node * @kn: kernfs_node of interest * * This function can be called from any context. */ void pr_cont_kernfs_name(struct kernfs_node *kn) { unsigned long flags; spin_lock_irqsave(&kernfs_rename_lock, flags); kernfs_name_locked(kn, kernfs_pr_cont_buf, sizeof(kernfs_pr_cont_buf)); pr_cont("%s", kernfs_pr_cont_buf); spin_unlock_irqrestore(&kernfs_rename_lock, flags); } /** * pr_cont_kernfs_path - pr_cont path of a kernfs_node * @kn: kernfs_node of interest * * This function can be called from any context. */ void pr_cont_kernfs_path(struct kernfs_node *kn) { unsigned long flags; int sz; spin_lock_irqsave(&kernfs_rename_lock, flags); sz = kernfs_path_from_node_locked(kn, NULL, kernfs_pr_cont_buf, sizeof(kernfs_pr_cont_buf)); if (sz < 0) { pr_cont("(error)"); goto out; } if (sz >= sizeof(kernfs_pr_cont_buf)) { pr_cont("(name too long)"); goto out; } pr_cont("%s", kernfs_pr_cont_buf); out: spin_unlock_irqrestore(&kernfs_rename_lock, flags); } /** * kernfs_get_parent - determine the parent node and pin it * @kn: kernfs_node of interest * * Determines @kn's parent, pins and returns it. This function can be * called from any context. */ struct kernfs_node *kernfs_get_parent(struct kernfs_node *kn) { struct kernfs_node *parent; unsigned long flags; spin_lock_irqsave(&kernfs_rename_lock, flags); parent = kn->parent; kernfs_get(parent); spin_unlock_irqrestore(&kernfs_rename_lock, flags); return parent; } /** * kernfs_name_hash * @name: Null terminated string to hash * @ns: Namespace tag to hash * * Returns 31 bit hash of ns + name (so it fits in an off_t ) */ static unsigned int kernfs_name_hash(const char *name, const void *ns) { unsigned long hash = init_name_hash(ns); unsigned int len = strlen(name); while (len--) hash = partial_name_hash(*name++, hash); hash = end_name_hash(hash); hash &= 0x7fffffffU; /* Reserve hash numbers 0, 1 and INT_MAX for magic directory entries */ if (hash < 2) hash += 2; if (hash >= INT_MAX) hash = INT_MAX - 1; return hash; } static int kernfs_name_compare(unsigned int hash, const char *name, const void *ns, const struct kernfs_node *kn) { if (hash < kn->hash) return -1; if (hash > kn->hash) return 1; if (ns < kn->ns) return -1; if (ns > kn->ns) return 1; return strcmp(name, kn->name); } static int kernfs_sd_compare(const struct kernfs_node *left, const struct kernfs_node *right) { return kernfs_name_compare(left->hash, left->name, left->ns, right); } /** * kernfs_link_sibling - link kernfs_node into sibling rbtree * @kn: kernfs_node of interest * * Link @kn into its sibling rbtree which starts from * @kn->parent->dir.children. * * Locking: * kernfs_rwsem held exclusive * * RETURNS: * 0 on susccess -EEXIST on failure. */ static int kernfs_link_sibling(struct kernfs_node *kn) { struct rb_node **node = &kn->parent->dir.children.rb_node; struct rb_node *parent = NULL; while (*node) { struct kernfs_node *pos; int result; pos = rb_to_kn(*node); parent = *node; result = kernfs_sd_compare(kn, pos); if (result < 0) node = &pos->rb.rb_left; else if (result > 0) node = &pos->rb.rb_right; else return -EEXIST; } /* add new node and rebalance the tree */ rb_link_node(&kn->rb, parent, node); rb_insert_color(&kn->rb, &kn->parent->dir.children); /* successfully added, account subdir number */ if (kernfs_type(kn) == KERNFS_DIR) kn->parent->dir.subdirs++; kernfs_inc_rev(kn->parent); return 0; } /** * kernfs_unlink_sibling - unlink kernfs_node from sibling rbtree * @kn: kernfs_node of interest * * Try to unlink @kn from its sibling rbtree which starts from * kn->parent->dir.children. Returns %true if @kn was actually * removed, %false if @kn wasn't on the rbtree. * * Locking: * kernfs_rwsem held exclusive */ static bool kernfs_unlink_sibling(struct kernfs_node *kn) { if (RB_EMPTY_NODE(&kn->rb)) return false; if (kernfs_type(kn) == KERNFS_DIR) kn->parent->dir.subdirs--; kernfs_inc_rev(kn->parent); rb_erase(&kn->rb, &kn->parent->dir.children); RB_CLEAR_NODE(&kn->rb); return true; } /** * kernfs_get_active - get an active reference to kernfs_node * @kn: kernfs_node to get an active reference to * * Get an active reference of @kn. This function is noop if @kn * is NULL. * * RETURNS: * Pointer to @kn on success, NULL on failure. */ struct kernfs_node *kernfs_get_active(struct kernfs_node *kn) { if (unlikely(!kn)) return NULL; if (!atomic_inc_unless_negative(&kn->active)) return NULL; if (kernfs_lockdep(kn)) rwsem_acquire_read(&kn->dep_map, 0, 1, _RET_IP_); return kn; } /** * kernfs_put_active - put an active reference to kernfs_node * @kn: kernfs_node to put an active reference to * * Put an active reference to @kn. This function is noop if @kn * is NULL. */ void kernfs_put_active(struct kernfs_node *kn) { int v; if (unlikely(!kn)) return; if (kernfs_lockdep(kn)) rwsem_release(&kn->dep_map, _RET_IP_); v = atomic_dec_return(&kn->active); if (likely(v != KN_DEACTIVATED_BIAS)) return; wake_up_all(&kernfs_root(kn)->deactivate_waitq); } /** * kernfs_drain - drain kernfs_node * @kn: kernfs_node to drain * * Drain existing usages and nuke all existing mmaps of @kn. Mutiple * removers may invoke this function concurrently on @kn and all will * return after draining is complete. */ static void kernfs_drain(struct kernfs_node *kn) __releases(&kernfs_root(kn)->kernfs_rwsem) __acquires(&kernfs_root(kn)->kernfs_rwsem) { struct kernfs_root *root = kernfs_root(kn); lockdep_assert_held_write(&root->kernfs_rwsem); WARN_ON_ONCE(kernfs_active(kn)); up_write(&root->kernfs_rwsem); if (kernfs_lockdep(kn)) { rwsem_acquire(&kn->dep_map, 0, 0, _RET_IP_); if (atomic_read(&kn->active) != KN_DEACTIVATED_BIAS) lock_contended(&kn->dep_map, _RET_IP_); } /* but everyone should wait for draining */ wait_event(root->deactivate_waitq, atomic_read(&kn->active) == KN_DEACTIVATED_BIAS); if (kernfs_lockdep(kn)) { lock_acquired(&kn->dep_map, _RET_IP_); rwsem_release(&kn->dep_map, _RET_IP_); } kernfs_drain_open_files(kn); down_write(&root->kernfs_rwsem); } /** * kernfs_get - get a reference count on a kernfs_node * @kn: the target kernfs_node */ void kernfs_get(struct kernfs_node *kn) { if (kn) { WARN_ON(!atomic_read(&kn->count)); atomic_inc(&kn->count); } } EXPORT_SYMBOL_GPL(kernfs_get); /** * kernfs_put - put a reference count on a kernfs_node * @kn: the target kernfs_node * * Put a reference count of @kn and destroy it if it reached zero. */ void kernfs_put(struct kernfs_node *kn) { struct kernfs_node *parent; struct kernfs_root *root; if (!kn || !atomic_dec_and_test(&kn->count)) return; root = kernfs_root(kn); repeat: /* * Moving/renaming is always done while holding reference. * kn->parent won't change beneath us. */ parent = kn->parent; WARN_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS, "kernfs_put: %s/%s: released with incorrect active_ref %d\n", parent ? parent->name : "", kn->name, atomic_read(&kn->active)); if (kernfs_type(kn) == KERNFS_LINK) kernfs_put(kn->symlink.target_kn); kfree_const(kn->name); if (kn->iattr) { simple_xattrs_free(&kn->iattr->xattrs); kmem_cache_free(kernfs_iattrs_cache, kn->iattr); } spin_lock(&kernfs_idr_lock); idr_remove(&root->ino_idr, (u32)kernfs_ino(kn)); spin_unlock(&kernfs_idr_lock); kmem_cache_free(kernfs_node_cache, kn); kn = parent; if (kn) { if (atomic_dec_and_test(&kn->count)) goto repeat; } else { /* just released the root kn, free @root too */ idr_destroy(&root->ino_idr); kfree(root); } } EXPORT_SYMBOL_GPL(kernfs_put); /** * kernfs_node_from_dentry - determine kernfs_node associated with a dentry * @dentry: the dentry in question * * Return the kernfs_node associated with @dentry. If @dentry is not a * kernfs one, %NULL is returned. * * While the returned kernfs_node will stay accessible as long as @dentry * is accessible, the returned node can be in any state and the caller is * fully responsible for determining what's accessible. */ struct kernfs_node *kernfs_node_from_dentry(struct dentry *dentry) { if (dentry->d_sb->s_op == &kernfs_sops) return kernfs_dentry_node(dentry); return NULL; } static struct kernfs_node *__kernfs_new_node(struct kernfs_root *root, struct kernfs_node *parent, const char *name, umode_t mode, kuid_t uid, kgid_t gid, unsigned flags) { struct kernfs_node *kn; u32 id_highbits; int ret; name = kstrdup_const(name, GFP_KERNEL); if (!name) return NULL; kn = kmem_cache_zalloc(kernfs_node_cache, GFP_KERNEL); if (!kn) goto err_out1; idr_preload(GFP_KERNEL); spin_lock(&kernfs_idr_lock); ret = idr_alloc_cyclic(&root->ino_idr, kn, 1, 0, GFP_ATOMIC); if (ret >= 0 && ret < root->last_id_lowbits) root->id_highbits++; id_highbits = root->id_highbits; root->last_id_lowbits = ret; spin_unlock(&kernfs_idr_lock); idr_preload_end(); if (ret < 0) goto err_out2; kn->id = (u64)id_highbits << 32 | ret; atomic_set(&kn->count, 1); atomic_set(&kn->active, KN_DEACTIVATED_BIAS); RB_CLEAR_NODE(&kn->rb); kn->name = name; kn->mode = mode; kn->flags = flags; if (!uid_eq(uid, GLOBAL_ROOT_UID) || !gid_eq(gid, GLOBAL_ROOT_GID)) { struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID, .ia_uid = uid, .ia_gid = gid, }; ret = __kernfs_setattr(kn, &iattr); if (ret < 0) goto err_out3; } if (parent) { ret = security_kernfs_init_security(parent, kn); if (ret) goto err_out3; } return kn; err_out3: idr_remove(&root->ino_idr, (u32)kernfs_ino(kn)); err_out2: kmem_cache_free(kernfs_node_cache, kn); err_out1: kfree_const(name); return NULL; } struct kernfs_node *kernfs_new_node(struct kernfs_node *parent, const char *name, umode_t mode, kuid_t uid, kgid_t gid, unsigned flags) { struct kernfs_node *kn; kn = __kernfs_new_node(kernfs_root(parent), parent, name, mode, uid, gid, flags); if (kn) { kernfs_get(parent); kn->parent = parent; } return kn; } /* * kernfs_find_and_get_node_by_id - get kernfs_node from node id * @root: the kernfs root * @id: the target node id * * @id's lower 32bits encode ino and upper gen. If the gen portion is * zero, all generations are matched. * * RETURNS: * NULL on failure. Return a kernfs node with reference counter incremented */ struct kernfs_node *kernfs_find_and_get_node_by_id(struct kernfs_root *root, u64 id) { struct kernfs_node *kn; ino_t ino = kernfs_id_ino(id); u32 gen = kernfs_id_gen(id); spin_lock(&kernfs_idr_lock); kn = idr_find(&root->ino_idr, (u32)ino); if (!kn) goto err_unlock; if (sizeof(ino_t) >= sizeof(u64)) { /* we looked up with the low 32bits, compare the whole */ if (kernfs_ino(kn) != ino) goto err_unlock; } else { /* 0 matches all generations */ if (unlikely(gen && kernfs_gen(kn) != gen)) goto err_unlock; } /* * ACTIVATED is protected with kernfs_mutex but it was clear when * @kn was added to idr and we just wanna see it set. No need to * grab kernfs_mutex. */ if (unlikely(!(kn->flags & KERNFS_ACTIVATED) || !atomic_inc_not_zero(&kn->count))) goto err_unlock; spin_unlock(&kernfs_idr_lock); return kn; err_unlock: spin_unlock(&kernfs_idr_lock); return NULL; } /** * kernfs_add_one - add kernfs_node to parent without warning * @kn: kernfs_node to be added * * The caller must already have initialized @kn->parent. This * function increments nlink of the parent's inode if @kn is a * directory and link into the children list of the parent. * * RETURNS: * 0 on success, -EEXIST if entry with the given name already * exists. */ int kernfs_add_one(struct kernfs_node *kn) { struct kernfs_node *parent = kn->parent; struct kernfs_root *root = kernfs_root(parent); struct kernfs_iattrs *ps_iattr; bool has_ns; int ret; down_write(&root->kernfs_rwsem); ret = -EINVAL; has_ns = kernfs_ns_enabled(parent); if (WARN(has_ns != (bool)kn->ns, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n", has_ns ? "required" : "invalid", parent->name, kn->name)) goto out_unlock; if (kernfs_type(parent) != KERNFS_DIR) goto out_unlock; ret = -ENOENT; if (parent->flags & KERNFS_EMPTY_DIR) goto out_unlock; if ((parent->flags & KERNFS_ACTIVATED) && !kernfs_active(parent)) goto out_unlock; kn->hash = kernfs_name_hash(kn->name, kn->ns); ret = kernfs_link_sibling(kn); if (ret) goto out_unlock; /* Update timestamps on the parent */ ps_iattr = parent->iattr; if (ps_iattr) { ktime_get_real_ts64(&ps_iattr->ia_ctime); ps_iattr->ia_mtime = ps_iattr->ia_ctime; } up_write(&root->kernfs_rwsem); /* * Activate the new node unless CREATE_DEACTIVATED is requested. * If not activated here, the kernfs user is responsible for * activating the node with kernfs_activate(). A node which hasn't * been activated is not visible to userland and its removal won't * trigger deactivation. */ if (!(kernfs_root(kn)->flags & KERNFS_ROOT_CREATE_DEACTIVATED)) kernfs_activate(kn); return 0; out_unlock: up_write(&root->kernfs_rwsem); return ret; } /** * kernfs_find_ns - find kernfs_node with the given name * @parent: kernfs_node to search under * @name: name to look for * @ns: the namespace tag to use * * Look for kernfs_node with name @name under @parent. Returns pointer to * the found kernfs_node on success, %NULL on failure. */ static struct kernfs_node *kernfs_find_ns(struct kernfs_node *parent, const unsigned char *name, const void *ns) { struct rb_node *node = parent->dir.children.rb_node; bool has_ns = kernfs_ns_enabled(parent); unsigned int hash; lockdep_assert_held(&kernfs_root(parent)->kernfs_rwsem); if (has_ns != (bool)ns) { WARN(1, KERN_WARNING "kernfs: ns %s in '%s' for '%s'\n", has_ns ? "required" : "invalid", parent->name, name); return NULL; } hash = kernfs_name_hash(name, ns); while (node) { struct kernfs_node *kn; int result; kn = rb_to_kn(node); result = kernfs_name_compare(hash, name, ns, kn); if (result < 0) node = node->rb_left; else if (result > 0) node = node->rb_right; else return kn; } return NULL; } static struct kernfs_node *kernfs_walk_ns(struct kernfs_node *parent, const unsigned char *path, const void *ns) { size_t len; char *p, *name; lockdep_assert_held_read(&kernfs_root(parent)->kernfs_rwsem); /* grab kernfs_rename_lock to piggy back on kernfs_pr_cont_buf */ spin_lock_irq(&kernfs_rename_lock); len = strlcpy(kernfs_pr_cont_buf, path, sizeof(kernfs_pr_cont_buf)); if (len >= sizeof(kernfs_pr_cont_buf)) { spin_unlock_irq(&kernfs_rename_lock); return NULL; } p = kernfs_pr_cont_buf; while ((name = strsep(&p, "/")) && parent) { if (*name == '\0') continue; parent = kernfs_find_ns(parent, name, ns); } spin_unlock_irq(&kernfs_rename_lock); return parent; } /** * kernfs_find_and_get_ns - find and get kernfs_node with the given name * @parent: kernfs_node to search under * @name: name to look for * @ns: the namespace tag to use * * Look for kernfs_node with name @name under @parent and get a reference * if found. This function may sleep and returns pointer to the found * kernfs_node on success, %NULL on failure. */ struct kernfs_node *kernfs_find_and_get_ns(struct kernfs_node *parent, const char *name, const void *ns) { struct kernfs_node *kn; struct kernfs_root *root = kernfs_root(parent); down_read(&root->kernfs_rwsem); kn = kernfs_find_ns(parent, name, ns); kernfs_get(kn); up_read(&root->kernfs_rwsem); return kn; } EXPORT_SYMBOL_GPL(kernfs_find_and_get_ns); /** * kernfs_walk_and_get_ns - find and get kernfs_node with the given path * @parent: kernfs_node to search under * @path: path to look for * @ns: the namespace tag to use * * Look for kernfs_node with path @path under @parent and get a reference * if found. This function may sleep and returns pointer to the found * kernfs_node on success, %NULL on failure. */ struct kernfs_node *kernfs_walk_and_get_ns(struct kernfs_node *parent, const char *path, const void *ns) { struct kernfs_node *kn; struct kernfs_root *root = kernfs_root(parent); down_read(&root->kernfs_rwsem); kn = kernfs_walk_ns(parent, path, ns); kernfs_get(kn); up_read(&root->kernfs_rwsem); return kn; } /** * kernfs_create_root - create a new kernfs hierarchy * @scops: optional syscall operations for the hierarchy * @flags: KERNFS_ROOT_* flags * @priv: opaque data associated with the new directory * * Returns the root of the new hierarchy on success, ERR_PTR() value on * failure. */ struct kernfs_root *kernfs_create_root(struct kernfs_syscall_ops *scops, unsigned int flags, void *priv) { struct kernfs_root *root; struct kernfs_node *kn; root = kzalloc(sizeof(*root), GFP_KERNEL); if (!root) return ERR_PTR(-ENOMEM); idr_init(&root->ino_idr); init_rwsem(&root->kernfs_rwsem); INIT_LIST_HEAD(&root->supers); /* * On 64bit ino setups, id is ino. On 32bit, low 32bits are ino. * High bits generation. The starting value for both ino and * genenration is 1. Initialize upper 32bit allocation * accordingly. */ if (sizeof(ino_t) >= sizeof(u64)) root->id_highbits = 0; else root->id_highbits = 1; kn = __kernfs_new_node(root, NULL, "", S_IFDIR | S_IRUGO | S_IXUGO, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, KERNFS_DIR); if (!kn) { idr_destroy(&root->ino_idr); kfree(root); return ERR_PTR(-ENOMEM); } kn->priv = priv; kn->dir.root = root; root->syscall_ops = scops; root->flags = flags; root->kn = kn; init_waitqueue_head(&root->deactivate_waitq); if (!(root->flags & KERNFS_ROOT_CREATE_DEACTIVATED)) kernfs_activate(kn); return root; } /** * kernfs_destroy_root - destroy a kernfs hierarchy * @root: root of the hierarchy to destroy * * Destroy the hierarchy anchored at @root by removing all existing * directories and destroying @root. */ void kernfs_destroy_root(struct kernfs_root *root) { /* * kernfs_remove holds kernfs_rwsem from the root so the root * shouldn't be freed during the operation. */ kernfs_get(root->kn); kernfs_remove(root->kn); kernfs_put(root->kn); /* will also free @root */ } /** * kernfs_create_dir_ns - create a directory * @parent: parent in which to create a new directory * @name: name of the new directory * @mode: mode of the new directory * @uid: uid of the new directory * @gid: gid of the new directory * @priv: opaque data associated with the new directory * @ns: optional namespace tag of the directory * * Returns the created node on success, ERR_PTR() value on failure. */ struct kernfs_node *kernfs_create_dir_ns(struct kernfs_node *parent, const char *name, umode_t mode, kuid_t uid, kgid_t gid, void *priv, const void *ns) { struct kernfs_node *kn; int rc; /* allocate */ kn = kernfs_new_node(parent, name, mode | S_IFDIR, uid, gid, KERNFS_DIR); if (!kn) return ERR_PTR(-ENOMEM); kn->dir.root = parent->dir.root; kn->ns = ns; kn->priv = priv; /* link in */ rc = kernfs_add_one(kn); if (!rc) return kn; kernfs_put(kn); return ERR_PTR(rc); } /** * kernfs_create_empty_dir - create an always empty directory * @parent: parent in which to create a new directory * @name: name of the new directory * * Returns the created node on success, ERR_PTR() value on failure. */ struct kernfs_node *kernfs_create_empty_dir(struct kernfs_node *parent, const char *name) { struct kernfs_node *kn; int rc; /* allocate */ kn = kernfs_new_node(parent, name, S_IRUGO|S_IXUGO|S_IFDIR, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID, KERNFS_DIR); if (!kn) return ERR_PTR(-ENOMEM); kn->flags |= KERNFS_EMPTY_DIR; kn->dir.root = parent->dir.root; kn->ns = NULL; kn->priv = NULL; /* link in */ rc = kernfs_add_one(kn); if (!rc) return kn; kernfs_put(kn); return ERR_PTR(rc); } static int kernfs_dop_revalidate(struct dentry *dentry, unsigned int flags) { struct kernfs_node *kn; struct kernfs_root *root; if (flags & LOOKUP_RCU) return -ECHILD; /* Negative hashed dentry? */ if (d_really_is_negative(dentry)) { struct kernfs_node *parent; /* If the kernfs parent node has changed discard and * proceed to ->lookup. */ spin_lock(&dentry->d_lock); parent = kernfs_dentry_node(dentry->d_parent); if (parent) { spin_unlock(&dentry->d_lock); root = kernfs_root(parent); down_read(&root->kernfs_rwsem); if (kernfs_dir_changed(parent, dentry)) { up_read(&root->kernfs_rwsem); return 0; } up_read(&root->kernfs_rwsem); } else spin_unlock(&dentry->d_lock); /* The kernfs parent node hasn't changed, leave the * dentry negative and return success. */ return 1; } kn = kernfs_dentry_node(dentry); root = kernfs_root(kn); down_read(&root->kernfs_rwsem); /* The kernfs node has been deactivated */ if (!kernfs_active(kn)) goto out_bad; /* The kernfs node has been moved? */ if (kernfs_dentry_node(dentry->d_parent) != kn->parent) goto out_bad; /* The kernfs node has been renamed */ if (strcmp(dentry->d_name.name, kn->name) != 0) goto out_bad; /* The kernfs node has been moved to a different namespace */ if (kn->parent && kernfs_ns_enabled(kn->parent) && kernfs_info(dentry->d_sb)->ns != kn->ns) goto out_bad; up_read(&root->kernfs_rwsem); return 1; out_bad: up_read(&root->kernfs_rwsem); return 0; } const struct dentry_operations kernfs_dops = { .d_revalidate = kernfs_dop_revalidate, }; static struct dentry *kernfs_iop_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct kernfs_node *parent = dir->i_private; struct kernfs_node *kn; struct kernfs_root *root; struct inode *inode = NULL; const void *ns = NULL; root = kernfs_root(parent); down_read(&root->kernfs_rwsem); if (kernfs_ns_enabled(parent)) ns = kernfs_info(dir->i_sb)->ns; kn = kernfs_find_ns(parent, dentry->d_name.name, ns); /* attach dentry and inode */ if (kn) { /* Inactive nodes are invisible to the VFS so don't * create a negative. */ if (!kernfs_active(kn)) { up_read(&root->kernfs_rwsem); return NULL; } inode = kernfs_get_inode(dir->i_sb, kn); if (!inode) inode = ERR_PTR(-ENOMEM); } /* * Needed for negative dentry validation. * The negative dentry can be created in kernfs_iop_lookup() * or transforms from positive dentry in dentry_unlink_inode() * called from vfs_rmdir(). */ if (!IS_ERR(inode)) kernfs_set_rev(parent, dentry); up_read(&root->kernfs_rwsem); /* instantiate and hash (possibly negative) dentry */ return d_splice_alias(inode, dentry); } static int kernfs_iop_mkdir(struct user_namespace *mnt_userns, struct inode *dir, struct dentry *dentry, umode_t mode) { struct kernfs_node *parent = dir->i_private; struct kernfs_syscall_ops *scops = kernfs_root(parent)->syscall_ops; int ret; if (!scops || !scops->mkdir) return -EPERM; if (!kernfs_get_active(parent)) return -ENODEV; ret = scops->mkdir(parent, dentry->d_name.name, mode); kernfs_put_active(parent); return ret; } static int kernfs_iop_rmdir(struct inode *dir, struct dentry *dentry) { struct kernfs_node *kn = kernfs_dentry_node(dentry); struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops; int ret; if (!scops || !scops->rmdir) return -EPERM; if (!kernfs_get_active(kn)) return -ENODEV; ret = scops->rmdir(kn); kernfs_put_active(kn); return ret; } static int kernfs_iop_rename(struct user_namespace *mnt_userns, struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry, unsigned int flags) { struct kernfs_node *kn = kernfs_dentry_node(old_dentry); struct kernfs_node *new_parent = new_dir->i_private; struct kernfs_syscall_ops *scops = kernfs_root(kn)->syscall_ops; int ret; if (flags) return -EINVAL; if (!scops || !scops->rename) return -EPERM; if (!kernfs_get_active(kn)) return -ENODEV; if (!kernfs_get_active(new_parent)) { kernfs_put_active(kn); return -ENODEV; } ret = scops->rename(kn, new_parent, new_dentry->d_name.name); kernfs_put_active(new_parent); kernfs_put_active(kn); return ret; } const struct inode_operations kernfs_dir_iops = { .lookup = kernfs_iop_lookup, .permission = kernfs_iop_permission, .setattr = kernfs_iop_setattr, .getattr = kernfs_iop_getattr, .listxattr = kernfs_iop_listxattr, .mkdir = kernfs_iop_mkdir, .rmdir = kernfs_iop_rmdir, .rename = kernfs_iop_rename, }; static struct kernfs_node *kernfs_leftmost_descendant(struct kernfs_node *pos) { struct kernfs_node *last; while (true) { struct rb_node *rbn; last = pos; if (kernfs_type(pos) != KERNFS_DIR) break; rbn = rb_first(&pos->dir.children); if (!rbn) break; pos = rb_to_kn(rbn); } return last; } /** * kernfs_next_descendant_post - find the next descendant for post-order walk * @pos: the current position (%NULL to initiate traversal) * @root: kernfs_node whose descendants to walk * * Find the next descendant to visit for post-order traversal of @root's * descendants. @root is included in the iteration and the last node to be * visited. */ static struct kernfs_node *kernfs_next_descendant_post(struct kernfs_node *pos, struct kernfs_node *root) { struct rb_node *rbn; lockdep_assert_held_write(&kernfs_root(root)->kernfs_rwsem); /* if first iteration, visit leftmost descendant which may be root */ if (!pos) return kernfs_leftmost_descendant(root); /* if we visited @root, we're done */ if (pos == root) return NULL; /* if there's an unvisited sibling, visit its leftmost descendant */ rbn = rb_next(&pos->rb); if (rbn) return kernfs_leftmost_descendant(rb_to_kn(rbn)); /* no sibling left, visit parent */ return pos->parent; } /** * kernfs_activate - activate a node which started deactivated * @kn: kernfs_node whose subtree is to be activated * * If the root has KERNFS_ROOT_CREATE_DEACTIVATED set, a newly created node * needs to be explicitly activated. A node which hasn't been activated * isn't visible to userland and deactivation is skipped during its * removal. This is useful to construct atomic init sequences where * creation of multiple nodes should either succeed or fail atomically. * * The caller is responsible for ensuring that this function is not called * after kernfs_remove*() is invoked on @kn. */ void kernfs_activate(struct kernfs_node *kn) { struct kernfs_node *pos; struct kernfs_root *root = kernfs_root(kn); down_write(&root->kernfs_rwsem); pos = NULL; while ((pos = kernfs_next_descendant_post(pos, kn))) { if (pos->flags & KERNFS_ACTIVATED) continue; WARN_ON_ONCE(pos->parent && RB_EMPTY_NODE(&pos->rb)); WARN_ON_ONCE(atomic_read(&pos->active) != KN_DEACTIVATED_BIAS); atomic_sub(KN_DEACTIVATED_BIAS, &pos->active); pos->flags |= KERNFS_ACTIVATED; } up_write(&root->kernfs_rwsem); } static void __kernfs_remove(struct kernfs_node *kn) { struct kernfs_node *pos; lockdep_assert_held_write(&kernfs_root(kn)->kernfs_rwsem); /* * Short-circuit if non-root @kn has already finished removal. * This is for kernfs_remove_self() which plays with active ref * after removal. */ if (!kn || (kn->parent && RB_EMPTY_NODE(&kn->rb))) return; pr_debug("kernfs %s: removing\n", kn->name); /* prevent any new usage under @kn by deactivating all nodes */ pos = NULL; while ((pos = kernfs_next_descendant_post(pos, kn))) if (kernfs_active(pos)) atomic_add(KN_DEACTIVATED_BIAS, &pos->active); /* deactivate and unlink the subtree node-by-node */ do { pos = kernfs_leftmost_descendant(kn); /* * kernfs_drain() drops kernfs_rwsem temporarily and @pos's * base ref could have been put by someone else by the time * the function returns. Make sure it doesn't go away * underneath us. */ kernfs_get(pos); /* * Drain iff @kn was activated. This avoids draining and * its lockdep annotations for nodes which have never been * activated and allows embedding kernfs_remove() in create * error paths without worrying about draining. */ if (kn->flags & KERNFS_ACTIVATED) kernfs_drain(pos); else WARN_ON_ONCE(atomic_read(&kn->active) != KN_DEACTIVATED_BIAS); /* * kernfs_unlink_sibling() succeeds once per node. Use it * to decide who's responsible for cleanups. */ if (!pos->parent || kernfs_unlink_sibling(pos)) { struct kernfs_iattrs *ps_iattr = pos->parent ? pos->parent->iattr : NULL; /* update timestamps on the parent */ if (ps_iattr) { ktime_get_real_ts64(&ps_iattr->ia_ctime); ps_iattr->ia_mtime = ps_iattr->ia_ctime; } kernfs_put(pos); } kernfs_put(pos); } while (pos != kn); } /** * kernfs_remove - remove a kernfs_node recursively * @kn: the kernfs_node to remove * * Remove @kn along with all its subdirectories and files. */ void kernfs_remove(struct kernfs_node *kn) { struct kernfs_root *root = kernfs_root(kn); down_write(&root->kernfs_rwsem); __kernfs_remove(kn); up_write(&root->kernfs_rwsem); } /** * kernfs_break_active_protection - break out of active protection * @kn: the self kernfs_node * * The caller must be running off of a kernfs operation which is invoked * with an active reference - e.g. one of kernfs_ops. Each invocation of * this function must also be matched with an invocation of * kernfs_unbreak_active_protection(). * * This function releases the active reference of @kn the caller is * holding. Once this function is called, @kn may be removed at any point * and the caller is solely responsible for ensuring that the objects it * dereferences are accessible. */ void kernfs_break_active_protection(struct kernfs_node *kn) { /* * Take out ourself out of the active ref dependency chain. If * we're called without an active ref, lockdep will complain. */ kernfs_put_active(kn); } /** * kernfs_unbreak_active_protection - undo kernfs_break_active_protection() * @kn: the self kernfs_node * * If kernfs_break_active_protection() was called, this function must be * invoked before finishing the kernfs operation. Note that while this * function restores the active reference, it doesn't and can't actually * restore the active protection - @kn may already or be in the process of * being removed. Once kernfs_break_active_protection() is invoked, that * protection is irreversibly gone for the kernfs operation instance. * * While this function may be called at any point after * kernfs_break_active_protection() is invoked, its most useful location * would be right before the enclosing kernfs operation returns. */ void kernfs_unbreak_active_protection(struct kernfs_node *kn) { /* * @kn->active could be in any state; however, the increment we do * here will be undone as soon as the enclosing kernfs operation * finishes and this temporary bump can't break anything. If @kn * is alive, nothing changes. If @kn is being deactivated, the * soon-to-follow put will either finish deactivation or restore * deactivated state. If @kn is already removed, the temporary * bump is guaranteed to be gone before @kn is released. */ atomic_inc(&kn->active); if (kernfs_lockdep(kn)) rwsem_acquire(&kn->dep_map, 0, 1, _RET_IP_); } /** * kernfs_remove_self - remove a kernfs_node from its own method * @kn: the self kernfs_node to remove * * The caller must be running off of a kernfs operation which is invoked * with an active reference - e.g. one of kernfs_ops. This can be used to * implement a file operation which deletes itself. * * For example, the "delete" file for a sysfs device directory can be * implemented by invoking kernfs_remove_self() on the "delete" file * itself. This function breaks the circular dependency of trying to * deactivate self while holding an active ref itself. It isn't necessary * to modify the usual removal path to use kernfs_remove_self(). The * "delete" implementation can simply invoke kernfs_remove_self() on self * before proceeding with the usual removal path. kernfs will ignore later * kernfs_remove() on self. * * kernfs_remove_self() can be called multiple times concurrently on the * same kernfs_node. Only the first one actually performs removal and * returns %true. All others will wait until the kernfs operation which * won self-removal finishes and return %false. Note that the losers wait * for the completion of not only the winning kernfs_remove_self() but also * the whole kernfs_ops which won the arbitration. This can be used to * guarantee, for example, all concurrent writes to a "delete" file to * finish only after the whole operation is complete. */ bool kernfs_remove_self(struct kernfs_node *kn) { bool ret; struct kernfs_root *root = kernfs_root(kn); down_write(&root->kernfs_rwsem); kernfs_break_active_protection(kn); /* * SUICIDAL is used to arbitrate among competing invocations. Only * the first one will actually perform removal. When the removal * is complete, SUICIDED is set and the active ref is restored * while kernfs_rwsem for held exclusive. The ones which lost * arbitration waits for SUICIDED && drained which can happen only * after the enclosing kernfs operation which executed the winning * instance of kernfs_remove_self() finished. */ if (!(kn->flags & KERNFS_SUICIDAL)) { kn->flags |= KERNFS_SUICIDAL; __kernfs_remove(kn); kn->flags |= KERNFS_SUICIDED; ret = true; } else { wait_queue_head_t *waitq = &kernfs_root(kn)->deactivate_waitq; DEFINE_WAIT(wait); while (true) { prepare_to_wait(waitq, &wait, TASK_UNINTERRUPTIBLE); if ((kn->flags & KERNFS_SUICIDED) && atomic_read(&kn->active) == KN_DEACTIVATED_BIAS) break; up_write(&root->kernfs_rwsem); schedule(); down_write(&root->kernfs_rwsem); } finish_wait(waitq, &wait); WARN_ON_ONCE(!RB_EMPTY_NODE(&kn->rb)); ret = false; } /* * This must be done while kernfs_rwsem held exclusive; otherwise, * waiting for SUICIDED && deactivated could finish prematurely. */ kernfs_unbreak_active_protection(kn); up_write(&root->kernfs_rwsem); return ret; } /** * kernfs_remove_by_name_ns - find a kernfs_node by name and remove it * @parent: parent of the target * @name: name of the kernfs_node to remove * @ns: namespace tag of the kernfs_node to remove * * Look for the kernfs_node with @name and @ns under @parent and remove it. * Returns 0 on success, -ENOENT if such entry doesn't exist. */ int kernfs_remove_by_name_ns(struct kernfs_node *parent, const char *name, const void *ns) { struct kernfs_node *kn; struct kernfs_root *root; if (!parent) { WARN(1, KERN_WARNING "kernfs: can not remove '%s', no directory\n", name); return -ENOENT; } root = kernfs_root(parent); down_write(&root->kernfs_rwsem); kn = kernfs_find_ns(parent, name, ns); if (kn) __kernfs_remove(kn); up_write(&root->kernfs_rwsem); if (kn) return 0; else return -ENOENT; } /** * kernfs_rename_ns - move and rename a kernfs_node * @kn: target node * @new_parent: new parent to put @sd under * @new_name: new name * @new_ns: new namespace tag */ int kernfs_rename_ns(struct kernfs_node *kn, struct kernfs_node *new_parent, const char *new_name, const void *new_ns) { struct kernfs_node *old_parent; struct kernfs_root *root; const char *old_name = NULL; int error; /* can't move or rename root */ if (!kn->parent) return -EINVAL; root = kernfs_root(kn); down_write(&root->kernfs_rwsem); error = -ENOENT; if (!kernfs_active(kn) || !kernfs_active(new_parent) || (new_parent->flags & KERNFS_EMPTY_DIR)) goto out; error = 0; if ((kn->parent == new_parent) && (kn->ns == new_ns) && (strcmp(kn->name, new_name) == 0)) goto out; /* nothing to rename */ error = -EEXIST; if (kernfs_find_ns(new_parent, new_name, new_ns)) goto out; /* rename kernfs_node */ if (strcmp(kn->name, new_name) != 0) { error = -ENOMEM; new_name = kstrdup_const(new_name, GFP_KERNEL); if (!new_name) goto out; } else { new_name = NULL; } /* * Move to the appropriate place in the appropriate directories rbtree. */ kernfs_unlink_sibling(kn); kernfs_get(new_parent); /* rename_lock protects ->parent and ->name accessors */ spin_lock_irq(&kernfs_rename_lock); old_parent = kn->parent; kn->parent = new_parent; kn->ns = new_ns; if (new_name) { old_name = kn->name; kn->name = new_name; } spin_unlock_irq(&kernfs_rename_lock); kn->hash = kernfs_name_hash(kn->name, kn->ns); kernfs_link_sibling(kn); kernfs_put(old_parent); kfree_const(old_name); error = 0; out: up_write(&root->kernfs_rwsem); return error; } /* Relationship between mode and the DT_xxx types */ static inline unsigned char dt_type(struct kernfs_node *kn) { return (kn->mode >> 12) & 15; } static int kernfs_dir_fop_release(struct inode *inode, struct file *filp) { kernfs_put(filp->private_data); return 0; } static struct kernfs_node *kernfs_dir_pos(const void *ns, struct kernfs_node *parent, loff_t hash, struct kernfs_node *pos) { if (pos) { int valid = kernfs_active(pos) && pos->parent == parent && hash == pos->hash; kernfs_put(pos); if (!valid) pos = NULL; } if (!pos && (hash > 1) && (hash < INT_MAX)) { struct rb_node *node = parent->dir.children.rb_node; while (node) { pos = rb_to_kn(node); if (hash < pos->hash) node = node->rb_left; else if (hash > pos->hash) node = node->rb_right; else break; } } /* Skip over entries which are dying/dead or in the wrong namespace */ while (pos && (!kernfs_active(pos) || pos->ns != ns)) { struct rb_node *node = rb_next(&pos->rb); if (!node) pos = NULL; else pos = rb_to_kn(node); } return pos; } static struct kernfs_node *kernfs_dir_next_pos(const void *ns, struct kernfs_node *parent, ino_t ino, struct kernfs_node *pos) { pos = kernfs_dir_pos(ns, parent, ino, pos); if (pos) { do { struct rb_node *node = rb_next(&pos->rb); if (!node) pos = NULL; else pos = rb_to_kn(node); } while (pos && (!kernfs_active(pos) || pos->ns != ns)); } return pos; } static int kernfs_fop_readdir(struct file *file, struct dir_context *ctx) { struct dentry *dentry = file->f_path.dentry; struct kernfs_node *parent = kernfs_dentry_node(dentry); struct kernfs_node *pos = file->private_data; struct kernfs_root *root; const void *ns = NULL; if (!dir_emit_dots(file, ctx)) return 0; root = kernfs_root(parent); down_read(&root->kernfs_rwsem); if (kernfs_ns_enabled(parent)) ns = kernfs_info(dentry->d_sb)->ns; for (pos = kernfs_dir_pos(ns, parent, ctx->pos, pos); pos; pos = kernfs_dir_next_pos(ns, parent, ctx->pos, pos)) { const char *name = pos->name; unsigned int type = dt_type(pos); int len = strlen(name); ino_t ino = kernfs_ino(pos); ctx->pos = pos->hash; file->private_data = pos; kernfs_get(pos); up_read(&root->kernfs_rwsem); if (!dir_emit(ctx, name, len, ino, type)) return 0; down_read(&root->kernfs_rwsem); } up_read(&root->kernfs_rwsem); file->private_data = NULL; ctx->pos = INT_MAX; return 0; } const struct file_operations kernfs_dir_fops = { .read = generic_read_dir, .iterate_shared = kernfs_fop_readdir, .release = kernfs_dir_fop_release, .llseek = generic_file_llseek, };
421593.c
/* Module object implementation */ #include "Python.h" #include "structmember.h" typedef struct { PyObject_HEAD PyObject *md_dict; } PyModuleObject; static PyMemberDef module_members[] = { {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY}, {0} }; PyObject * PyModule_New(const char *name) { PyModuleObject *m; PyObject *nameobj; m = PyObject_GC_New(PyModuleObject, &PyModule_Type); if (m == NULL) return NULL; nameobj = PyString_FromString(name); m->md_dict = PyDict_New(); if (m->md_dict == NULL || nameobj == NULL) goto fail; if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0) goto fail; if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0) goto fail; if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0) goto fail; Py_DECREF(nameobj); PyObject_GC_Track(m); return (PyObject *)m; fail: Py_XDECREF(nameobj); Py_DECREF(m); return NULL; } PyObject * PyModule_GetDict(PyObject *m) { PyObject *d; if (!PyModule_Check(m)) { PyErr_BadInternalCall(); return NULL; } d = ((PyModuleObject *)m) -> md_dict; if (d == NULL) ((PyModuleObject *)m) -> md_dict = d = PyDict_New(); return d; } char * PyModule_GetName(PyObject *m) { PyObject *d; PyObject *nameobj; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (nameobj = PyDict_GetItemString(d, "__name__")) == NULL || !PyString_Check(nameobj)) { PyErr_SetString(PyExc_SystemError, "nameless module"); return NULL; } return PyString_AsString(nameobj); } char * PyModule_GetFilename(PyObject *m) { PyObject *d; PyObject *fileobj; if (!PyModule_Check(m)) { PyErr_BadArgument(); return NULL; } d = ((PyModuleObject *)m)->md_dict; if (d == NULL || (fileobj = PyDict_GetItemString(d, "__file__")) == NULL || !PyString_Check(fileobj)) { PyErr_SetString(PyExc_SystemError, "module filename missing"); return NULL; } return PyString_AsString(fileobj); } void _PyModule_Clear(PyObject *m) { /* To make the execution order of destructors for global objects a bit more predictable, we first zap all objects whose name starts with a single underscore, before we clear the entire dictionary. We zap them by replacing them with None, rather than deleting them from the dictionary, to avoid rehashing the dictionary (to some extent). */ Py_ssize_t pos; PyObject *key, *value; PyObject *d; d = ((PyModuleObject *)m)->md_dict; if (d == NULL) return; /* First, clear only names starting with a single underscore */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyString_Check(key)) { char *s = PyString_AsString(key); if (s[0] == '_' && s[1] != '_') { if (Py_VerboseFlag > 1) PySys_WriteStderr("# clear[1] %s\n", s); if (PyDict_SetItem(d, key, Py_None) != 0) PyErr_Clear(); } } } /* Next, clear all names except for __builtins__ */ pos = 0; while (PyDict_Next(d, &pos, &key, &value)) { if (value != Py_None && PyString_Check(key)) { char *s = PyString_AsString(key); if (s[0] != '_' || strcmp(s, "__builtins__") != 0) { if (Py_VerboseFlag > 1) PySys_WriteStderr("# clear[2] %s\n", s); if (PyDict_SetItem(d, key, Py_None) != 0) PyErr_Clear(); } } } /* Note: we leave __builtins__ in place, so that destructors of non-global objects defined in this module can still use builtins, in particularly 'None'. */ } /* Methods */ static int module_init(PyModuleObject *m, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"name", "doc", NULL}; PyObject *dict, *name = Py_None, *doc = Py_None; if (!PyArg_ParseTupleAndKeywords(args, kwds, "S|O:module.__init__", kwlist, &name, &doc)) return -1; dict = m->md_dict; if (dict == NULL) { dict = PyDict_New(); if (dict == NULL) return -1; m->md_dict = dict; } if (PyDict_SetItemString(dict, "__name__", name) < 0) return -1; if (PyDict_SetItemString(dict, "__doc__", doc) < 0) return -1; return 0; } static void module_dealloc(PyModuleObject *m) { PyObject_GC_UnTrack(m); if (m->md_dict != NULL) { _PyModule_Clear((PyObject *)m); Py_DECREF(m->md_dict); } Py_TYPE(m)->tp_free((PyObject *)m); } static PyObject * module_repr(PyModuleObject *m) { char *name; char *filename; name = PyModule_GetName((PyObject *)m); if (name == NULL) { PyErr_Clear(); name = "?"; } filename = PyModule_GetFilename((PyObject *)m); if (filename == NULL) { PyErr_Clear(); return PyString_FromFormat("<module '%s' (built-in)>", name); } return PyString_FromFormat("<module '%s' from '%s'>", name, filename); } /* We only need a traverse function, no clear function: If the module is in a cycle, md_dict will be cleared as well, which will break the cycle. */ static int module_traverse(PyModuleObject *m, visitproc visit, void *arg) { Py_VISIT(m->md_dict); return 0; } PyDoc_STRVAR(module_doc, "module(name[, doc])\n\ \n\ Create a module object.\n\ The name must be a string; the optional doc argument can have any type."); PyTypeObject PyModule_Type = { PyVarObject_HEAD_INIT(&PyType_Type, 0) "module", /* tp_name */ sizeof(PyModuleObject), /* tp_size */ 0, /* tp_itemsize */ (destructor)module_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)module_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags */ module_doc, /* tp_doc */ (traverseproc)module_traverse, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ module_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ offsetof(PyModuleObject, md_dict), /* tp_dictoffset */ (initproc)module_init, /* tp_init */ PyType_GenericAlloc, /* tp_alloc */ PyType_GenericNew, /* tp_new */ PyObject_GC_Del, /* tp_free */ };
726938.c
/* Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Tdi3Expt.C Data base info. Ken Klare, LANL CTR-7 (c)1990 */ #include <dbidef.h> #include <libroutines.h> #include <mdsdescrip.h> #include <mdsshr.h> #include <stdio.h> #include <string.h> #include <treeshr.h> /*-------------------------------------------------------------- Default path name. */ int Tdi3MdsDefault(struct descriptor *in_ptr __attribute__((unused)), struct descriptor_xd *out_ptr) { char value[4096]; static const dtype_t dtype = DTYPE_T; int retlen, status; struct dbi_itm lst[] = {{sizeof(value), DbiDEFAULT, 0, 0}, {0, DbiEND_OF_LIST, 0, 0}}; length_t len; lst[0].pointer = (uint8_t *)value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); if (STATUS_OK) { len = (length_t)retlen; status = MdsGet1DxS(&len, &dtype, out_ptr); } if (STATUS_OK) memcpy(out_ptr->pointer->pointer, value, len); return status; } /*-------------------------------------------------------------- Experiment name. */ int Tdi3Expt(struct descriptor *in_ptr __attribute__((unused)), struct descriptor_xd *out_ptr) { char value[39 - 7]; int retlen, status; static const dtype_t dtype = DTYPE_T; struct dbi_itm lst[] = {{sizeof(value), DbiNAME, 0, 0}, {0, DbiEND_OF_LIST, 0, 0}}; length_t len; lst[0].pointer = (unsigned char *)value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); if (STATUS_OK) { len = (length_t)retlen; status = MdsGet1DxS(&len, &dtype, out_ptr); } if (STATUS_OK) memcpy(out_ptr->pointer->pointer, value, len); return status; } /*-------------------------------------------------------------- Shot number identifier. */ int Tdi3Shot(struct descriptor *in_ptr __attribute__((unused)), struct descriptor_xd *out_ptr) { int value; int retlen, status; static const dtype_t dtype = DTYPE_L; struct dbi_itm lst[] = {{sizeof(value), DbiSHOTID, 0, 0}, {0, DbiEND_OF_LIST, 0, 0}}; length_t len; lst[0].pointer = (unsigned char *)&value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); if (STATUS_OK) { len = (length_t)retlen; status = MdsGet1DxS(&len, &dtype, out_ptr); } if (STATUS_OK) *(int *)out_ptr->pointer->pointer = value; return status; } /*-------------------------------------------------------------- Shot number identifier converted to string. */ int Tdi3Shotname(struct descriptor *in_ptr __attribute__((unused)), struct descriptor_xd *out_ptr) { int value; int retlen, status; struct dbi_itm lst[] = {{sizeof(value), DbiSHOTID, 0, 0}, {0, DbiEND_OF_LIST, 0, 0}}; DESCRIPTOR(dmodel, "MODEL"); char string[15]; lst[0].pointer = (unsigned char *)&value; lst[0].return_length_address = &retlen; status = TreeGetDbi(lst); if (value != -1) { sprintf(string, "%d", value); dmodel.pointer = string; dmodel.length = (unsigned short)strlen(string); } if (STATUS_OK) status = MdsCopyDxXd((struct descriptor *)&dmodel, out_ptr); return status; }
418011.c
/** * Copyright (c) 2014 - 2020, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @brief BLE Heart Rate Collector application main file. * * This file contains the source code for a sample heart rate collector. */ #include <stdint.h> #include <stdio.h> #include <string.h> #include "nordic_common.h" #include "nrf_sdm.h" #include "ble.h" #include "ble_hci.h" #include "ble_db_discovery.h" #include "ble_srv_common.h" #include "nrf_sdh.h" #include "nrf_sdh_ble.h" #include "nrf_sdh_soc.h" #include "nrf_pwr_mgmt.h" #include "app_util.h" #include "app_error.h" #include "peer_manager.h" #include "peer_manager_handler.h" #include "ble_hrs_c.h" #include "ble_bas_c.h" #include "app_util.h" #include "app_timer.h" #include "bsp_btn_ble.h" #include "fds.h" #include "nrf_fstorage.h" #include "ble_conn_state.h" #include "nrf_ble_gatt.h" #include "nrf_ble_lesc.h" #include "nrf_log.h" #include "nrf_log_ctrl.h" #include "nrf_log_default_backends.h" #include "nrf_ble_scan.h" #define APP_BLE_CONN_CFG_TAG 1 /**< A tag identifying the SoftDevice BLE configuration. */ #define APP_BLE_OBSERVER_PRIO 3 /**< Application's BLE observer priority. You shouldn't need to modify this value. */ #define APP_SOC_OBSERVER_PRIO 1 /**< Applications' SoC observer priority. You shouldn't need to modify this value. */ #define LESC_DEBUG_MODE 0 /**< Set to 1 to use LESC debug keys, allows you to use a sniffer to inspect traffic. */ #define SEC_PARAM_BOND 1 /**< Perform bonding. */ #define SEC_PARAM_MITM 0 /**< Man In The Middle protection not required. */ #define SEC_PARAM_LESC 1 /**< LE Secure Connections enabled. */ #define SEC_PARAM_KEYPRESS 0 /**< Keypress notifications not enabled. */ #define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE /**< No I/O capabilities. */ #define SEC_PARAM_OOB 0 /**< Out Of Band data not available. */ #define SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size in octets. */ #define SEC_PARAM_MAX_KEY_SIZE 16 /**< Maximum encryption key size in octets. */ #define SCAN_DURATION_WITELIST 3000 /**< Duration of the scanning in units of 10 milliseconds. */ #define TARGET_UUID BLE_UUID_HEART_RATE_SERVICE /**< Target device uuid that application is looking for. */ /**@brief Macro to unpack 16bit unsigned UUID from octet stream. */ #define UUID16_EXTRACT(DST, SRC) \ do \ { \ (*(DST)) = (SRC)[1]; \ (*(DST)) <<= 8; \ (*(DST)) |= (SRC)[0]; \ } while (0) NRF_BLE_GQ_DEF(m_ble_gatt_queue, /**< BLE GATT Queue instance. */ NRF_SDH_BLE_CENTRAL_LINK_COUNT, NRF_BLE_GQ_QUEUE_SIZE); BLE_HRS_C_DEF(m_hrs_c); /**< Structure used to identify the heart rate client module. */ BLE_BAS_C_DEF(m_bas_c); /**< Structure used to identify the Battery Service client module. */ NRF_BLE_GATT_DEF(m_gatt); /**< GATT module instance. */ BLE_DB_DISCOVERY_DEF(m_db_disc); /**< DB discovery module instance. */ NRF_BLE_SCAN_DEF(m_scan); /**< Scanning module instance. */ static uint16_t m_conn_handle; /**< Current connection handle. */ static bool m_whitelist_disabled; /**< True if whitelist has been temporarily disabled. */ static bool m_memory_access_in_progress; /**< Flag to keep track of ongoing operations on persistent memory. */ /**< Scan parameters requested for scanning and connection. */ static ble_gap_scan_params_t const m_scan_param = { .active = 0x01, #if (NRF_SD_BLE_API_VERSION > 7) .interval_us = NRF_BLE_SCAN_SCAN_INTERVAL * UNIT_0_625_MS, .window_us = NRF_BLE_SCAN_SCAN_WINDOW * UNIT_0_625_MS, #else .interval = NRF_BLE_SCAN_SCAN_INTERVAL, .window = NRF_BLE_SCAN_SCAN_WINDOW, #endif // (NRF_SD_BLE_API_VERSION > 7) .filter_policy = BLE_GAP_SCAN_FP_WHITELIST, .timeout = SCAN_DURATION_WITELIST, .scan_phys = BLE_GAP_PHY_1MBPS, }; /**@brief Names which the central applications will scan for, and which will be advertised by the peripherals. * if these are set to empty strings, the UUIDs defined below will be used */ static char const m_target_periph_name[] = ""; /**< If you want to connect to a peripheral using a given advertising name, type its name here. */ static bool is_connect_per_addr = false; /**< If you want to connect to a peripheral with a given address, set this to true and put the correct address in the variable below. */ static ble_gap_addr_t const m_target_periph_addr = { /* Possible values for addr_type: BLE_GAP_ADDR_TYPE_PUBLIC, BLE_GAP_ADDR_TYPE_RANDOM_STATIC, BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE, BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */ .addr_type = BLE_GAP_ADDR_TYPE_RANDOM_STATIC, .addr = {0x8D, 0xFE, 0x23, 0x86, 0x77, 0xD9} }; static void scan_start(void); /**@brief Function for asserts in the SoftDevice. * * @details This function will be called in case of an assert in the SoftDevice. * * @warning This handler is an example only and does not fit a final product. You need to analyze * how your product is supposed to react in case of Assert. * @warning On assert from the SoftDevice, the system can only recover on reset. * * @param[in] line_num Line number of the failing ASSERT call. * @param[in] p_file_name File name of the failing ASSERT call. */ void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name) { app_error_handler(0xDEADBEEF, line_num, p_file_name); } /**@brief Function for handling the Heart Rate Service Client and Battery Service Client errors. * * @param[in] nrf_error Error code containing information about what went wrong. */ static void service_error_handler(uint32_t nrf_error) { APP_ERROR_HANDLER(nrf_error); } /**@brief Function for handling database discovery events. * * @details This function is callback function to handle events from the database discovery module. * Depending on the UUIDs that are discovered, this function should forward the events * to their respective services. * * @param[in] p_event Pointer to the database discovery event. */ static void db_disc_handler(ble_db_discovery_evt_t * p_evt) { ble_hrs_on_db_disc_evt(&m_hrs_c, p_evt); ble_bas_on_db_disc_evt(&m_bas_c, p_evt); } /**@brief Function for handling Peer Manager events. * * @param[in] p_evt Peer Manager event. */ static void pm_evt_handler(pm_evt_t const * p_evt) { pm_handler_on_pm_evt(p_evt); pm_handler_flash_clean(p_evt); switch (p_evt->evt_id) { case PM_EVT_PEERS_DELETE_SUCCEEDED: // Bonds are deleted. Start scanning. scan_start(); break; default: break; } } /** * @brief Function for shutdown events. * * @param[in] event Shutdown type. */ static bool shutdown_handler(nrf_pwr_mgmt_evt_t event) { ret_code_t err_code; err_code = bsp_indication_set(BSP_INDICATE_IDLE); APP_ERROR_CHECK(err_code); switch (event) { case NRF_PWR_MGMT_EVT_PREPARE_WAKEUP: // Prepare wakeup buttons. err_code = bsp_btn_ble_sleep_mode_prepare(); APP_ERROR_CHECK(err_code); break; default: break; } return true; } NRF_PWR_MGMT_HANDLER_REGISTER(shutdown_handler, APP_SHUTDOWN_HANDLER_PRIORITY); /**@brief Function for handling BLE events. * * @param[in] p_ble_evt Bluetooth stack event. * @param[in] p_context Unused. */ static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context) { ret_code_t err_code; ble_gap_evt_t const * p_gap_evt = &p_ble_evt->evt.gap_evt; switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: { NRF_LOG_INFO("Connected."); // Discover peer's services. err_code = ble_db_discovery_start(&m_db_disc, p_ble_evt->evt.gap_evt.conn_handle); APP_ERROR_CHECK(err_code); err_code = bsp_indication_set(BSP_INDICATE_CONNECTED); APP_ERROR_CHECK(err_code); if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT) { scan_start(); } } break; case BLE_GAP_EVT_DISCONNECTED: { NRF_LOG_INFO("Disconnected, reason 0x%x.", p_gap_evt->params.disconnected.reason); err_code = bsp_indication_set(BSP_INDICATE_IDLE); APP_ERROR_CHECK(err_code); if (ble_conn_state_central_conn_count() < NRF_SDH_BLE_CENTRAL_LINK_COUNT) { scan_start(); } } break; case BLE_GAP_EVT_TIMEOUT: { if (p_gap_evt->params.timeout.src == BLE_GAP_TIMEOUT_SRC_CONN) { NRF_LOG_INFO("Connection Request timed out."); } } break; case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST: // Accepting parameters requested by peer. err_code = sd_ble_gap_conn_param_update(p_gap_evt->conn_handle, &p_gap_evt->params.conn_param_update_request.conn_params); APP_ERROR_CHECK(err_code); break; case BLE_GAP_EVT_PHY_UPDATE_REQUEST: { NRF_LOG_DEBUG("PHY update request."); ble_gap_phys_t const phys = { .rx_phys = BLE_GAP_PHY_AUTO, .tx_phys = BLE_GAP_PHY_AUTO, }; err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys); APP_ERROR_CHECK(err_code); } break; case BLE_GATTC_EVT_TIMEOUT: // Disconnect on GATT Client timeout event. NRF_LOG_DEBUG("GATT Client Timeout."); err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION); APP_ERROR_CHECK(err_code); break; case BLE_GATTS_EVT_TIMEOUT: // Disconnect on GATT Server timeout event. NRF_LOG_DEBUG("GATT Server Timeout."); err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION); APP_ERROR_CHECK(err_code); break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: NRF_LOG_DEBUG("BLE_GAP_EVT_SEC_PARAMS_REQUEST"); break; case BLE_GAP_EVT_AUTH_KEY_REQUEST: NRF_LOG_INFO("BLE_GAP_EVT_AUTH_KEY_REQUEST"); break; case BLE_GAP_EVT_LESC_DHKEY_REQUEST: NRF_LOG_INFO("BLE_GAP_EVT_LESC_DHKEY_REQUEST"); break; case BLE_GAP_EVT_AUTH_STATUS: NRF_LOG_INFO("BLE_GAP_EVT_AUTH_STATUS: status=0x%x bond=0x%x lv4: %d kdist_own:0x%x kdist_peer:0x%x", p_ble_evt->evt.gap_evt.params.auth_status.auth_status, p_ble_evt->evt.gap_evt.params.auth_status.bonded, p_ble_evt->evt.gap_evt.params.auth_status.sm1_levels.lv4, *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_own), *((uint8_t *)&p_ble_evt->evt.gap_evt.params.auth_status.kdist_peer)); break; default: break; } } /**@brief SoftDevice SoC event handler. * * @param[in] evt_id SoC event. * @param[in] p_context Context. */ static void soc_evt_handler(uint32_t evt_id, void * p_context) { switch (evt_id) { case NRF_EVT_FLASH_OPERATION_SUCCESS: /* fall through */ case NRF_EVT_FLASH_OPERATION_ERROR: if (m_memory_access_in_progress) { m_memory_access_in_progress = false; scan_start(); } break; default: // No implementation needed. break; } } /**@brief Function for initializing the BLE stack. * * @details Initializes the SoftDevice and the BLE event interrupt. */ static void ble_stack_init(void) { ret_code_t err_code; err_code = nrf_sdh_enable_request(); APP_ERROR_CHECK(err_code); // Configure the BLE stack using the default settings. // Fetch the start address of the application RAM. uint32_t ram_start = 0; err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start); APP_ERROR_CHECK(err_code); // Enable BLE stack. err_code = nrf_sdh_ble_enable(&ram_start); APP_ERROR_CHECK(err_code); // Register handlers for BLE and SoC events. NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL); NRF_SDH_SOC_OBSERVER(m_soc_observer, APP_SOC_OBSERVER_PRIO, soc_evt_handler, NULL); } /**@brief Function for the Peer Manager initialization. */ static void peer_manager_init(void) { ble_gap_sec_params_t sec_param; ret_code_t err_code; err_code = pm_init(); APP_ERROR_CHECK(err_code); memset(&sec_param, 0, sizeof(ble_gap_sec_params_t)); // Security parameters to be used for all security procedures. sec_param.bond = SEC_PARAM_BOND; sec_param.mitm = SEC_PARAM_MITM; sec_param.lesc = SEC_PARAM_LESC; sec_param.keypress = SEC_PARAM_KEYPRESS; sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES; sec_param.oob = SEC_PARAM_OOB; sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE; sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE; sec_param.kdist_own.enc = 1; sec_param.kdist_own.id = 1; sec_param.kdist_peer.enc = 1; sec_param.kdist_peer.id = 1; err_code = pm_sec_params_set(&sec_param); APP_ERROR_CHECK(err_code); err_code = pm_register(pm_evt_handler); APP_ERROR_CHECK(err_code); } /** @brief Clear bonding information from persistent storage */ static void delete_bonds(void) { ret_code_t err_code; NRF_LOG_INFO("Erase bonds!"); err_code = pm_peers_delete(); APP_ERROR_CHECK(err_code); } /**@brief Function for disabling the use of whitelist for scanning. */ static void whitelist_disable(void) { if (!m_whitelist_disabled) { NRF_LOG_INFO("Whitelist temporarily disabled."); m_whitelist_disabled = true; nrf_ble_scan_stop(); scan_start(); } } /**@brief Function for handling events from the BSP module. * * @param[in] event Event generated by button press. */ void bsp_event_handler(bsp_event_t event) { ret_code_t err_code; switch (event) { case BSP_EVENT_SLEEP: nrf_pwr_mgmt_shutdown(NRF_PWR_MGMT_SHUTDOWN_GOTO_SYSOFF); break; case BSP_EVENT_DISCONNECT: err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION); if (err_code != NRF_ERROR_INVALID_STATE) { APP_ERROR_CHECK(err_code); } break; case BSP_EVENT_WHITELIST_OFF: whitelist_disable(); break; default: break; } } /**@brief Heart Rate Collector Handler. */ static void hrs_c_evt_handler(ble_hrs_c_t * p_hrs_c, ble_hrs_c_evt_t * p_hrs_c_evt) { ret_code_t err_code; switch (p_hrs_c_evt->evt_type) { case BLE_HRS_C_EVT_DISCOVERY_COMPLETE: { NRF_LOG_DEBUG("Heart rate service discovered."); err_code = ble_hrs_c_handles_assign(p_hrs_c, p_hrs_c_evt->conn_handle, &p_hrs_c_evt->params.peer_db); APP_ERROR_CHECK(err_code); // Initiate bonding. err_code = pm_conn_secure(p_hrs_c_evt->conn_handle, false); if (err_code != NRF_ERROR_BUSY) { APP_ERROR_CHECK(err_code); } // Heart rate service discovered. Enable notification of Heart Rate Measurement. err_code = ble_hrs_c_hrm_notif_enable(p_hrs_c); APP_ERROR_CHECK(err_code); } break; case BLE_HRS_C_EVT_HRM_NOTIFICATION: { NRF_LOG_INFO("Heart Rate = %d.", p_hrs_c_evt->params.hrm.hr_value); if (p_hrs_c_evt->params.hrm.rr_intervals_cnt != 0) { uint32_t rr_avg = 0; for (uint32_t i = 0; i < p_hrs_c_evt->params.hrm.rr_intervals_cnt; i++) { rr_avg += p_hrs_c_evt->params.hrm.rr_intervals[i]; } rr_avg = rr_avg / p_hrs_c_evt->params.hrm.rr_intervals_cnt; NRF_LOG_DEBUG("rr_interval (avg) = %d.", rr_avg); } } break; default: break; } } /**@brief Battery level Collector Handler. */ static void bas_c_evt_handler(ble_bas_c_t * p_bas_c, ble_bas_c_evt_t * p_bas_c_evt) { ret_code_t err_code; switch (p_bas_c_evt->evt_type) { case BLE_BAS_C_EVT_DISCOVERY_COMPLETE: { err_code = ble_bas_c_handles_assign(p_bas_c, p_bas_c_evt->conn_handle, &p_bas_c_evt->params.bas_db); APP_ERROR_CHECK(err_code); // Battery service discovered. Enable notification of Battery Level. NRF_LOG_DEBUG("Battery Service discovered. Reading battery level."); err_code = ble_bas_c_bl_read(p_bas_c); APP_ERROR_CHECK(err_code); NRF_LOG_DEBUG("Enabling Battery Level Notification."); err_code = ble_bas_c_bl_notif_enable(p_bas_c); APP_ERROR_CHECK(err_code); } break; case BLE_BAS_C_EVT_BATT_NOTIFICATION: NRF_LOG_INFO("Battery Level received %d %%.", p_bas_c_evt->params.battery_level); break; case BLE_BAS_C_EVT_BATT_READ_RESP: NRF_LOG_INFO("Battery Level Read as %d %%.", p_bas_c_evt->params.battery_level); break; default: break; } } /** * @brief Heart rate collector initialization. */ static void hrs_c_init(void) { ble_hrs_c_init_t hrs_c_init_obj; hrs_c_init_obj.evt_handler = hrs_c_evt_handler; hrs_c_init_obj.error_handler = service_error_handler; hrs_c_init_obj.p_gatt_queue = &m_ble_gatt_queue; ret_code_t err_code = ble_hrs_c_init(&m_hrs_c, &hrs_c_init_obj); APP_ERROR_CHECK(err_code); } /** * @brief Battery level collector initialization. */ static void bas_c_init(void) { ble_bas_c_init_t bas_c_init_obj; bas_c_init_obj.evt_handler = bas_c_evt_handler; bas_c_init_obj.error_handler = service_error_handler; bas_c_init_obj.p_gatt_queue = &m_ble_gatt_queue; ret_code_t err_code = ble_bas_c_init(&m_bas_c, &bas_c_init_obj); APP_ERROR_CHECK(err_code); } /** * @brief Database discovery collector initialization. */ static void db_discovery_init(void) { ble_db_discovery_init_t db_init; memset(&db_init, 0, sizeof(db_init)); db_init.evt_handler = db_disc_handler; db_init.p_gatt_queue = &m_ble_gatt_queue; ret_code_t err_code = ble_db_discovery_init(&db_init); APP_ERROR_CHECK(err_code); } /**@brief Retrieve a list of peer manager peer IDs. * * @param[inout] p_peers The buffer where to store the list of peer IDs. * @param[inout] p_size In: The size of the @p p_peers buffer. * Out: The number of peers copied in the buffer. */ static void peer_list_get(pm_peer_id_t * p_peers, uint32_t * p_size) { pm_peer_id_t peer_id; uint32_t peers_to_copy; peers_to_copy = (*p_size < BLE_GAP_WHITELIST_ADDR_MAX_COUNT) ? *p_size : BLE_GAP_WHITELIST_ADDR_MAX_COUNT; peer_id = pm_next_peer_id_get(PM_PEER_ID_INVALID); *p_size = 0; while ((peer_id != PM_PEER_ID_INVALID) && (peers_to_copy--)) { p_peers[(*p_size)++] = peer_id; peer_id = pm_next_peer_id_get(peer_id); } } static void whitelist_load() { ret_code_t ret; pm_peer_id_t peers[8]; uint32_t peer_cnt; memset(peers, PM_PEER_ID_INVALID, sizeof(peers)); peer_cnt = (sizeof(peers) / sizeof(pm_peer_id_t)); // Load all peers from flash and whitelist them. peer_list_get(peers, &peer_cnt); ret = pm_whitelist_set(peers, peer_cnt); APP_ERROR_CHECK(ret); // Setup the device identies list. // Some SoftDevices do not support this feature. ret = pm_device_identities_list_set(peers, peer_cnt); if (ret != NRF_ERROR_NOT_SUPPORTED) { APP_ERROR_CHECK(ret); } } static void on_whitelist_req(void) { ret_code_t err_code; // Whitelist buffers. ble_gap_addr_t whitelist_addrs[8]; ble_gap_irk_t whitelist_irks[8]; memset(whitelist_addrs, 0x00, sizeof(whitelist_addrs)); memset(whitelist_irks, 0x00, sizeof(whitelist_irks)); uint32_t addr_cnt = (sizeof(whitelist_addrs) / sizeof(ble_gap_addr_t)); uint32_t irk_cnt = (sizeof(whitelist_irks) / sizeof(ble_gap_irk_t)); // Reload the whitelist and whitelist all peers. whitelist_load(); // Get the whitelist previously set using pm_whitelist_set(). err_code = pm_whitelist_get(whitelist_addrs, &addr_cnt, whitelist_irks, &irk_cnt); if (((addr_cnt == 0) && (irk_cnt == 0)) || (m_whitelist_disabled)) { // Don't use whitelist. err_code = nrf_ble_scan_params_set(&m_scan, NULL); APP_ERROR_CHECK(err_code); } } /**@brief Function to start scanning. */ static void scan_start(void) { ret_code_t err_code; if (nrf_fstorage_is_busy(NULL)) { m_memory_access_in_progress = true; return; } NRF_LOG_INFO("Starting scan."); err_code = nrf_ble_scan_start(&m_scan); APP_ERROR_CHECK(err_code); err_code = bsp_indication_set(BSP_INDICATE_SCANNING); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing buttons and leds. * * @param[out] p_erase_bonds Will be true if the clear bonding button was pressed to wake the application up. */ static void buttons_leds_init(bool * p_erase_bonds) { ret_code_t err_code; bsp_event_t startup_event; err_code = bsp_init(BSP_INIT_LEDS | BSP_INIT_BUTTONS, bsp_event_handler); APP_ERROR_CHECK(err_code); err_code = bsp_btn_ble_init(NULL, &startup_event); APP_ERROR_CHECK(err_code); *p_erase_bonds = (startup_event == BSP_EVENT_CLEAR_BONDING_DATA); } /**@brief Function for initializing the nrf log module. */ static void log_init(void) { ret_code_t err_code = NRF_LOG_INIT(NULL); APP_ERROR_CHECK(err_code); NRF_LOG_DEFAULT_BACKENDS_INIT(); } /**@brief Function for initializing the power management module. */ static void power_management_init(void) { ret_code_t err_code; err_code = nrf_pwr_mgmt_init(); APP_ERROR_CHECK(err_code); } /**@brief GATT module event handler. */ static void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt) { switch (p_evt->evt_id) { case NRF_BLE_GATT_EVT_ATT_MTU_UPDATED: { NRF_LOG_INFO("GATT ATT MTU on connection 0x%x changed to %d.", p_evt->conn_handle, p_evt->params.att_mtu_effective); } break; case NRF_BLE_GATT_EVT_DATA_LENGTH_UPDATED: { NRF_LOG_INFO("Data length for connection 0x%x updated to %d.", p_evt->conn_handle, p_evt->params.data_length); } break; default: break; } } static void scan_evt_handler(scan_evt_t const * p_scan_evt) { ret_code_t err_code; switch(p_scan_evt->scan_evt_id) { case NRF_BLE_SCAN_EVT_WHITELIST_REQUEST: { on_whitelist_req(); m_whitelist_disabled = false; } break; case NRF_BLE_SCAN_EVT_CONNECTING_ERROR: { err_code = p_scan_evt->params.connecting_err.err_code; APP_ERROR_CHECK(err_code); } break; case NRF_BLE_SCAN_EVT_SCAN_TIMEOUT: { NRF_LOG_INFO("Scan timed out."); scan_start(); } break; case NRF_BLE_SCAN_EVT_FILTER_MATCH: break; case NRF_BLE_SCAN_EVT_WHITELIST_ADV_REPORT: break; default: break; } } /**@brief Function for initializing the timer. */ static void timer_init(void) { ret_code_t err_code = app_timer_init(); APP_ERROR_CHECK(err_code); } /**@brief Function for initializing the GATT module. */ static void gatt_init(void) { ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler); APP_ERROR_CHECK(err_code); } /**@brief Function for initialization scanning and setting filters. */ static void scan_init(void) { ret_code_t err_code; nrf_ble_scan_init_t init_scan; memset(&init_scan, 0, sizeof(init_scan)); init_scan.p_scan_param = &m_scan_param; init_scan.connect_if_match = true; init_scan.conn_cfg_tag = APP_BLE_CONN_CFG_TAG; err_code = nrf_ble_scan_init(&m_scan, &init_scan, scan_evt_handler); APP_ERROR_CHECK(err_code); ble_uuid_t uuid = { .uuid = TARGET_UUID, .type = BLE_UUID_TYPE_BLE, }; err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_UUID_FILTER, &uuid); APP_ERROR_CHECK(err_code); if (strlen(m_target_periph_name) != 0) { err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_NAME_FILTER, m_target_periph_name); APP_ERROR_CHECK(err_code); } if (is_connect_per_addr) { err_code = nrf_ble_scan_filter_set(&m_scan, SCAN_ADDR_FILTER, m_target_periph_addr.addr); APP_ERROR_CHECK(err_code); } err_code = nrf_ble_scan_filters_enable(&m_scan, NRF_BLE_SCAN_ALL_FILTER, false); APP_ERROR_CHECK(err_code); } /**@brief Function for handling the idle state (main loop). * * @details Handle any pending log operation(s), then sleep until the next event occurs. */ static void idle_state_handle(void) { ret_code_t err_code; err_code = nrf_ble_lesc_request_handler(); APP_ERROR_CHECK(err_code); NRF_LOG_FLUSH(); nrf_pwr_mgmt_run(); } /**@brief Function for starting a scan, or instead trigger it from peer manager (after * deleting bonds). * * @param[in] p_erase_bonds Pointer to a bool to determine if bonds will be deleted before scanning. */ void scanning_start(bool * p_erase_bonds) { // Start scanning for peripherals and initiate connection // with devices that advertise GATT Service UUID. if (*p_erase_bonds == true) { // Scan is started by the PM_EVT_PEERS_DELETE_SUCCEEDED event. delete_bonds(); } else { scan_start(); } } int main(void) { bool erase_bonds; // Initialize. log_init(); timer_init(); power_management_init(); buttons_leds_init(&erase_bonds); ble_stack_init(); gatt_init(); peer_manager_init(); db_discovery_init(); hrs_c_init(); bas_c_init(); scan_init(); // Start execution. NRF_LOG_INFO("Heart Rate collector example started."); scanning_start(&erase_bonds); // Enter main loop. for (;;) { idle_state_handle(); } }
157548.c
/* packet-ansi_637.c * Routines for ANSI IS-637-A/D (SMS) dissection * * Copyright 2003, Michael Lum <mlum [AT] telostech.com> * In association with Telos Technology Inc. * Copyright 2013, Michael Lum <michael.lum [AT] starsolutions.com> * In association with Star Solutions, Inc. (Updated for some of IS-637-D and CMAS) * * Title 3GPP2 Other * * Short Message Service * 3GPP2 C.S0015-0 TIA/EIA-637-A * 3GPP2 C.S0015-C v1.0 TIA/EIA-637-D * 3GPP2 C.R1001-H v1.0 TSB-58-I (or J?) * * For CMAS See: * TIA-1149.1 or * (520-10030206__Editor_TIA-1149-0-1_CMASoverCDMA_Publication.pdf) * * Wireshark - Network traffic analyzer * By Gerald Combs <[email protected]> * Copyright 1998 Gerald Combs * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "config.h" #include <epan/packet.h> #include <epan/expert.h> #include <epan/strutil.h> #include <epan/to_str.h> #include "packet-gsm_sms.h" #include "packet-ansi_a.h" void proto_register_ansi_637(void); void proto_reg_handoff_ansi_637(void); static const char *ansi_proto_name_tele = "ANSI IS-637-A (SMS) Teleservice Layer"; static const char *ansi_proto_name_trans = "ANSI IS-637-A (SMS) Transport Layer"; static const char *ansi_proto_name_short = "IS-637-A"; /* * Masks the number of bits given by len starting at the given offset * MBoffset should be from 0 to 7 and MBlen 1 to 8 * MASK_B(0, 1) = 0x80 * MASK_B(0, 8) = 0xff * MASK_B(4, 3) = 0x0e * MASK_B(7, 1) = 0x01 */ #define MASK_B(MBoffset, MBlen) \ ((0xff >> (MBoffset)) & (0xff << (8 - ((MBoffset) + (MBlen))))) static const value_string ansi_tele_msg_type_strings[] = { { 1, "Deliver (mobile-terminated only)" }, { 2, "Submit (mobile-originated only)" }, { 3, "Cancellation (mobile-originated only)" }, { 4, "Delivery Acknowledgement (mobile-terminated only)" }, { 5, "User Acknowledgement (either direction)" }, { 6, "Read Acknowledgement (either direction)" }, { 7, "Deliver Report (mobile-originated only)" }, { 8, "Submit Report (mobile-terminated only)" }, { 0, NULL } }; static const value_string ansi_tele_msg_header_ind_strings[] = { { 0, "The User Data field contains only the short message" }, { 1, "The User Data field contains a Header in addition to the short message" }, { 0, NULL } }; static const value_string ansi_tele_msg_status_strings[] = { { 0x00, "Message accepted" }, { 0x01, "Message deposited to Internet" }, { 0x02, "Message delivered" }, { 0x03, "Message cancelled" }, { 0x84, "Network congestion" }, { 0x85, "Network error" }, { 0x9f, "Unknown error" }, { 0xc4, "Network congestion" }, { 0xc5, "Network error" }, { 0xc6, "Cancel failed" }, { 0xc7, "Blocked destination" }, { 0xc8, "Text too long" }, { 0xc9, "Duplicate message" }, { 0xca, "Invalid destination" }, { 0xcd, "Message expired" }, { 0xdf, "Unknown error" }, { 0, NULL } }; static value_string_ext ansi_tele_msg_status_strings_ext = VALUE_STRING_EXT_INIT(ansi_tele_msg_status_strings); static const value_string ansi_tele_id_strings[] = { { 1, "Reserved for maintenance" }, { 4096, "AMPS Extended Protocol Enhanced Services" }, { 4097, "CDMA Cellular Paging Teleservice" }, { 4098, "CDMA Cellular Messaging Teleservice" }, { 4099, "CDMA Voice Mail Notification" }, { 4100, "CDMA Wireless Application Protocol (WAP)" }, { 4101, "CDMA Wireless Enhanced Messaging Teleservice (WEMT)" }, { 0, NULL } }; #define INTERNAL_BROADCAST_TELE_ID 65535 static const value_string ansi_tele_param_strings[] = { { 0x00, "Message Identifier" }, { 0x01, "User Data" }, { 0x02, "User Response Code" }, { 0x03, "Message Center Time Stamp" }, { 0x04, "Validity Period - Absolute" }, { 0x05, "Validity Period - Relative" }, { 0x06, "Deferred Delivery Time - Absolute" }, { 0x07, "Deferred Delivery Time - Relative" }, { 0x08, "Priority Indicator" }, { 0x09, "Privacy Indicator" }, { 0x0a, "Reply Option" }, { 0x0b, "Number of Messages" }, { 0x0c, "Alert on Message Delivery" }, { 0x0d, "Language Indicator" }, { 0x0e, "Call-Back Number" }, { 0x0f, "Message Display Mode" }, { 0x10, "Multiple Encoding User Data" }, { 0x11, "Message Deposit Index" }, { 0x12, "Service Category Program Data" }, { 0x13, "Service Category Program Results" }, { 0x14, "Message status" }, { 0x15, "TP-Failure cause" }, { 0x16, "Enhanced VMN" }, { 0x17, "Enhanced VMN Ack" }, { 0, NULL } }; static value_string_ext ansi_tele_param_strings_ext = VALUE_STRING_EXT_INIT(ansi_tele_param_strings); #define ANSI_TRANS_MSG_TYPE_BROADCAST 1 static const value_string ansi_trans_msg_type_strings[] = { { 0, "Point-to-Point" }, { 1, "Broadcast" }, { 2, "Acknowledge" }, { 0, NULL } }; static const value_string ansi_trans_param_strings[] = { { 0x00, "Teleservice Identifier" }, { 0x01, "Service Category" }, { 0x02, "Originating Address" }, { 0x03, "Originating Subaddress" }, { 0x04, "Destination Address" }, { 0x05, "Destination Subaddress" }, { 0x06, "Bearer Reply Option" }, { 0x07, "Cause Codes" }, { 0x08, "Bearer Data" }, { 0, NULL } }; static const value_string ansi_tele_month_strings[] = { { 0, "January" }, { 1, "February" }, { 2, "March" }, { 3, "April" }, { 4, "May" }, { 5, "June" }, { 6, "July" }, { 7, "August" }, { 8, "September" }, { 9, "October" }, { 10, "November" }, { 11, "December" }, { 0, NULL } }; static const value_string ansi_trans_subaddr_odd_even_ind_strings[] = { { 0x00, "Even" }, { 0x01, "Odd" }, { 0, NULL } }; static const true_false_string tfs_digit_mode_8bit_4bit = { "8-bit ASCII", "4-bit DTMF" }; static const true_false_string tfs_number_mode_data_ansi_t1 = { "Data Network Address", "ANSI T1.607" }; /* * from Table 2.7.1.3.2.4-4. Representation of DTMF Digits * 3GPP2 C.S0005-C (IS-2000 aka cdma2000) */ static const unsigned char air_digits[] = { /* 0 1 2 3 4 5 6 7 8 9 a b c d e f */ '?','1','2','3','4','5','6','7','8','9','0','*','#','?','?','?' }; /* Initialize the protocol and registered fields */ static int proto_ansi_637_tele = -1; static int proto_ansi_637_trans = -1; static int hf_ansi_637_trans_param_id = -1; static int hf_ansi_637_trans_length = -1; static int hf_ansi_637_trans_bin_addr = -1; static int hf_ansi_637_trans_tele_id = -1; static int hf_ansi_637_trans_srvc_cat = -1; static int hf_ansi_637_trans_addr_param_digit_mode = -1; static int hf_ansi_637_trans_addr_param_number_mode = -1; static int hf_ansi_637_trans_addr_param_ton = -1; static int hf_ansi_637_trans_addr_param_plan = -1; static int hf_ansi_637_trans_addr_param_num_fields = -1; static int hf_ansi_637_trans_addr_param_number = -1; static int hf_ansi_637_trans_subaddr_type = -1; static int hf_ansi_637_trans_subaddr_odd_even_ind = -1; static int hf_ansi_637_trans_subaddr_num_fields = -1; static int hf_ansi_637_trans_bearer_reply_seq_num = -1; static int hf_ansi_637_trans_cause_codes_seq_num = -1; static int hf_ansi_637_trans_cause_codes_error_class = -1; static int hf_ansi_637_trans_cause_codes_code = -1; static int hf_ansi_637_tele_msg_type = -1; static int hf_ansi_637_tele_msg_id = -1; static int hf_ansi_637_tele_length = -1; static int hf_ansi_637_tele_msg_status = -1; static int hf_ansi_637_tele_msg_header_ind = -1; static int hf_ansi_637_tele_msg_rsvd = -1; static int hf_ansi_637_tele_subparam_id = -1; static int hf_ansi_637_tele_user_data_text = -1; static int hf_ansi_637_tele_user_data_encoding = -1; static int hf_ansi_637_tele_user_data_message_type = -1; static int hf_ansi_637_tele_user_data_num_fields = -1; static int hf_ansi_637_tele_response_code = -1; static int hf_ansi_637_tele_message_center_ts_year = -1; static int hf_ansi_637_tele_message_center_ts_month = -1; static int hf_ansi_637_tele_message_center_ts_day = -1; static int hf_ansi_637_tele_message_center_ts_hours = -1; static int hf_ansi_637_tele_message_center_ts_minutes = -1; static int hf_ansi_637_tele_message_center_ts_seconds = -1; static int hf_ansi_637_tele_validity_period_ts_year = -1; static int hf_ansi_637_tele_validity_period_ts_month = -1; static int hf_ansi_637_tele_validity_period_ts_day = -1; static int hf_ansi_637_tele_validity_period_ts_hours = -1; static int hf_ansi_637_tele_validity_period_ts_minutes = -1; static int hf_ansi_637_tele_validity_period_ts_seconds = -1; static int hf_ansi_637_tele_validity_period_relative_validity = -1; static int hf_ansi_637_tele_deferred_del_ts_year = -1; static int hf_ansi_637_tele_deferred_del_ts_month = -1; static int hf_ansi_637_tele_deferred_del_ts_day = -1; static int hf_ansi_637_tele_deferred_del_ts_hours = -1; static int hf_ansi_637_tele_deferred_del_ts_minutes = -1; static int hf_ansi_637_tele_deferred_del_ts_seconds = -1; static int hf_ansi_637_tele_deferred_del_relative = -1; static int hf_ansi_637_tele_priority_indicator = -1; static int hf_ansi_637_tele_privacy_indicator = -1; static int hf_ansi_637_tele_reply_option_user_ack_req = -1; static int hf_ansi_637_tele_reply_option_dak_req = -1; static int hf_ansi_637_tele_reply_option_read_ack_req = -1; static int hf_ansi_637_tele_reply_option_report_req = -1; static int hf_ansi_637_tele_num_messages = -1; static int hf_ansi_637_tele_alert_msg_delivery_priority = -1; static int hf_ansi_637_tele_language = -1; static int hf_ansi_637_tele_cb_num_digit_mode = -1; static int hf_ansi_637_tele_cb_num_ton = -1; static int hf_ansi_637_tele_cb_num_plan = -1; static int hf_ansi_637_tele_cb_num_num_fields = -1; static int hf_ansi_637_tele_cb_num_num_fields07f8 = -1; static int hf_ansi_637_tele_cb_num_number = -1; static int hf_ansi_637_tele_msg_display_mode = -1; static int hf_ansi_637_tele_msg_deposit_idx = -1; static int hf_ansi_637_tele_srvc_cat_prog_results_srvc_cat = -1; static int hf_ansi_637_tele_srvc_cat_prog_results_result = -1; static int hf_ansi_637_tele_msg_status_error_class = -1; static int hf_ansi_637_tele_msg_status_code = -1; static int hf_ansi_637_tele_tp_failure_cause_value = -1; static int hf_ansi_637_reserved_bits_8_generic = -1; static int hf_ansi_637_reserved_bits_8_03 = -1; static int hf_ansi_637_reserved_bits_8_07 = -1; static int hf_ansi_637_reserved_bits_8_0f = -1; static int hf_ansi_637_reserved_bits_8_3f = -1; static int hf_ansi_637_reserved_bits_8_7f = -1; static int hf_ansi_637_reserved_bits_16_generic = -1; static int hf_ansi_637_tele_cmas_encoding = -1; static int hf_ansi_637_tele_cmas_num_fields = -1; static int hf_ansi_637_tele_cmas_protocol_version = -1; static int hf_ansi_637_tele_cmas_record_type = -1; static int hf_ansi_637_tele_cmas_record_len = -1; static int hf_ansi_637_tele_cmas_char_set = -1; static int hf_ansi_637_tele_cmas_category = -1; static int hf_ansi_637_tele_cmas_response_type = -1; static int hf_ansi_637_tele_cmas_severity = -1; static int hf_ansi_637_tele_cmas_urgency = -1; static int hf_ansi_637_tele_cmas_certainty = -1; static int hf_ansi_637_tele_cmas_identifier = -1; static int hf_ansi_637_tele_cmas_alert_handling = -1; static int hf_ansi_637_tele_cmas_expires_year = -1; static int hf_ansi_637_tele_cmas_expires_month = -1; static int hf_ansi_637_tele_cmas_expires_day = -1; static int hf_ansi_637_tele_cmas_expires_hours = -1; static int hf_ansi_637_tele_cmas_expires_minutes = -1; static int hf_ansi_637_tele_cmas_expires_seconds = -1; static int hf_ansi_637_tele_cmas_language = -1; static int hf_ansi_637_tele_cmas_text = -1; static int hf_ansi_637_tele_mult_enc_user_data_encoding = -1; static int hf_ansi_637_tele_mult_enc_user_data_num_fields = -1; static int hf_ansi_637_tele_mult_enc_user_data_text = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_encoding = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_operation_code = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_category = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_language = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_max_messages = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_alert_option = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_num_fields = -1; static int hf_ansi_637_tele_srvc_cat_prog_data_text = -1; static int hf_ansi_637_msb_first_field = -1; static int hf_ansi_637_lsb_last_field = -1; /* Initialize the subtree pointers */ static gint ett_ansi_637_tele = -1; static gint ett_ansi_637_trans = -1; static gint ett_ansi_637_header_ind = -1; static gint ett_params = -1; static expert_field ei_ansi_637_extraneous_data = EI_INIT; static expert_field ei_ansi_637_short_data = EI_INIT; static expert_field ei_ansi_637_unexpected_length = EI_INIT; static expert_field ei_ansi_637_unknown_encoding = EI_INIT; static expert_field ei_ansi_637_failed_conversion = EI_INIT; static expert_field ei_ansi_637_unknown_cmas_record_type = EI_INIT; static expert_field ei_ansi_637_unknown_trans_parameter = EI_INIT; static expert_field ei_ansi_637_no_trans_parameter_dissector = EI_INIT; static expert_field ei_ansi_637_unknown_tele_parameter = EI_INIT; static expert_field ei_ansi_637_no_tele_parameter_dissector = EI_INIT; static dissector_handle_t ansi_637_tele_handle; static dissector_handle_t ansi_637_trans_handle; static guint32 ansi_637_trans_tele_id; static char ansi_637_bigbuf[1024]; static dissector_table_t tele_dissector_table; static proto_tree *g_tree; /* PARAM FUNCTIONS */ #define EXTRANEOUS_DATA_CHECK(edc_len, edc_max_len) \ if ((edc_len) > (edc_max_len)) \ { \ proto_tree_add_expert(tree, pinfo, &ei_ansi_637_extraneous_data, \ tvb, offset, (edc_len) - (edc_max_len)); \ } #define SHORT_DATA_CHECK(sdc_len, sdc_min_len) \ if ((sdc_len) < (sdc_min_len)) \ { \ proto_tree_add_expert(tree, pinfo, &ei_ansi_637_short_data, \ tvb, offset, (sdc_len)); \ return; \ } #define EXACT_DATA_CHECK(edc_len, edc_eq_len) \ if ((edc_len) != (edc_eq_len)) \ { \ proto_tree_add_expert(tree, pinfo, &ei_ansi_637_unexpected_length, \ tvb, offset, (edc_len)); \ return; \ } /* * text decoding helper * * there are 'unused_bits' bits remaining in the octet at 'offset' */ static void text_decoder(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 offset, guint8 encoding, guint8 num_fields, guint16 num_bits, guint8 unused_bits, guint8 fill_bits, int hf_index) { guint8 bit; guint32 required_octs; tvbuff_t *tvb_out = NULL; GIConv cd; GError *l_conv_error = NULL; gchar *ustr = NULL; /* * has to be big enough to hold all of the 'shifted' bits */ required_octs = (num_bits + fill_bits + 7) / 8; /* * shift the bits to octet alignment in 'buf' */ tvb_out = tvb_new_octet_aligned(tvb, (offset * 8) + (8 - unused_bits), (required_octs * 8)); add_new_data_source(pinfo, tvb_out, "Characters"); switch (encoding) { default: proto_tree_add_expert(tree, pinfo, &ei_ansi_637_unknown_encoding, tvb, offset, required_octs); return; case 0x00: /* Octet, unspecified */ proto_tree_add_string(tree, hf_index, tvb_out, 0, required_octs, tvb_bytes_to_str(wmem_packet_scope(), tvb_out, 0, required_octs)); break; case 0x02: /* 7-bit ASCII */ offset = 0; bit = 0; proto_tree_add_ascii_7bits_item(tree, hf_index, tvb_out, (offset << 3) + bit, num_fields); break; case 0x03: /* IA5 */ offset = 0; bit = 0; ustr = tvb_get_ascii_7bits_string(wmem_packet_scope(), tvb_out, (offset << 3) + bit, num_fields); IA5_7BIT_decode(ansi_637_bigbuf, ustr, num_fields); proto_tree_add_string(tree, hf_index, tvb_out, 0, required_octs, ansi_637_bigbuf); break; case 0x04: /* UNICODE */ offset = 0; proto_tree_add_item(tree, hf_index, tvb_out, offset, num_fields*2, ENC_UCS_2|ENC_BIG_ENDIAN); break; case 0x07: /* Latin/Hebrew */ offset = 0; proto_tree_add_item(tree, hf_index, tvb_out, offset, num_fields, ENC_ISO_8859_8|ENC_NA); break; case 0x08: /* Latin */ offset = 0; proto_tree_add_item(tree, hf_index, tvb_out, offset, num_fields, ENC_ISO_8859_1|ENC_NA); break; case 0x09: /* GSM 7-bit default alphabet */ offset = 0; bit = fill_bits; proto_tree_add_ts_23_038_7bits_item(tree, hf_index, tvb_out, (offset << 3) + bit, num_fields); break; case 0x10: /* KSC5601 (Korean) */ offset = 0; if ((cd = g_iconv_open("UTF-8", "EUC-KR")) != (GIConv) -1) { ustr = g_convert_with_iconv(tvb_get_ptr(tvb_out, offset, required_octs), required_octs , cd , NULL , NULL , &l_conv_error); if (!l_conv_error) { proto_tree_add_string(tree, hf_index, tvb_out, offset, required_octs, ustr); } else { proto_tree_add_expert_format(tree, pinfo, &ei_ansi_637_failed_conversion, tvb_out, offset, required_octs, "Failed iconv conversion on EUC-KR - (report to wireshark.org)"); } if (ustr) { g_free(ustr); } g_iconv_close(cd); } break; } } static void tele_param_timestamp(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, int hf_year, int hf_month, int hf_day, int hf_hours, int hf_minutes, int hf_seconds) { guint8 oct; guint16 temp; const gchar *str = NULL; EXACT_DATA_CHECK(len, 6); oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f); temp += ((temp < 96) ? 2000 : 1900); proto_tree_add_uint_format_value(tree, hf_year, tvb, offset, 1, oct, "%u (%02x)", temp, oct); offset += 1; oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f) - 1; str = val_to_str_const(temp, ansi_tele_month_strings, "Invalid"); proto_tree_add_uint_format_value(tree, hf_month, tvb, offset, 1, oct, "%s (%02x)", str, oct); offset += 1; oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f); proto_tree_add_uint_format_value(tree, hf_day, tvb, offset, 1, oct, "%u", temp); offset += 1; oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f); proto_tree_add_uint_format_value(tree, hf_hours, tvb, offset, 1, oct, "%u", temp); offset += 1; oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f); proto_tree_add_uint_format_value(tree, hf_minutes, tvb, offset, 1, oct, "%u", temp); offset += 1; oct = tvb_get_guint8(tvb, offset); temp = (((oct & 0xf0) >> 4) * 10) + (oct & 0x0f); proto_tree_add_uint_format_value(tree, hf_seconds, tvb, offset, 1, oct, "%u", temp); } static void tele_param_msg_id(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p) { EXACT_DATA_CHECK(len, 3); proto_tree_add_item(tree, hf_ansi_637_tele_msg_type, tvb, offset, 3, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_msg_id, tvb, offset, 3, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_msg_header_ind, tvb, offset, 3, ENC_BIG_ENDIAN); if ((tvb_get_guint8(tvb, offset + 2) & 0x08) == 0x08) { *has_private_data_p = TRUE; } proto_tree_add_item(tree, hf_ansi_637_tele_msg_rsvd, tvb, offset, 3, ENC_BIG_ENDIAN); } /* * for record types 0, 1, 2 and 3 for unknowns */ #define NUM_CMAS_PARAM 4 static gint ett_tia_1149_cmas_param[NUM_CMAS_PARAM]; /* * Special dissection for CMAS Message as defined in TIA-1149 */ static const value_string cmas_category_strings[] = { { 0x00, "Geo (Geophysical including landslide)" }, { 0x01, "Met (Meteorological including flood)" }, { 0x02, "Safety (General emergency and public safety)" }, { 0x03, "Security (Law enforcement, military, homeland and local/private security)" }, { 0x04, "Rescue (Rescue and recovery)" }, { 0x05, "Fire (Fire suppression and rescue)" }, { 0x06, "Health (Medical and public health)" }, { 0x07, "Env (Pollution and other environmental)" }, { 0x08, "Transport (Public and private transportation)" }, { 0x09, "Infra (Utility, telecommunication, other nontransport infrastructure)" }, { 0x0a, "CBRNE (Chemical, Biological, Radiological, Nuclear or High-Yield Explosive threat or attack)" }, { 0x0b, "Other (Other events)" }, { 0, NULL } }; static const value_string cmas_response_type_strings[] = { { 0x00, "Shelter (Take shelter in place)" }, { 0x01, "Evacuate (Relocate)" }, { 0x02, "Prepare (Make preparations)" }, { 0x03, "Execute (Execute a pre-planned activity)" }, { 0x04, "Monitor (Attend to information sources)" }, { 0x05, "Avoid (Avoid hazard)" }, { 0x06, "Assess (Evaluate the information in this message. This value SHOULD NOT be used in public warning applications.)" }, { 0x07, "None (No action recommended)" }, { 0, NULL } }; static const value_string cmas_severity_strings[] = { { 0x00, "Extreme (Extraordinary threat to life or property)" }, { 0x01, "Severe (Significant threat to life or property)" }, { 0, NULL } }; static const value_string cmas_urgency_strings[] = { { 0x00, "Immediate (Responsive action should be taken immediately)" }, { 0x01, "Expected (Responsive action should be taken soon - within the next hour)" }, { 0, NULL } }; static const value_string cmas_certainty_strings[] = { { 0x00, "Observed (Determined to have occurred or to be ongoing)" }, { 0x01, "Likely (Likely. Probability > ~50%)" }, { 0, NULL } }; static void tele_param_user_data_cmas(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { proto_tree *subtree; guint8 oct, oct2; guint8 encoding; guint8 num_fields; guint8 reserved_bits; guint8 unused_bits; guint8 record_type; guint8 record_len; guint8 subtree_idx; guint16 num_bits; guint32 value; guint32 temp_offset; guint32 required_octs; tvbuff_t *tvb_out = NULL; const gchar *str = NULL; SHORT_DATA_CHECK(len, 2); value = tvb_get_ntohs(tvb, offset); /* * must be encoded as 'Octet, unspecified' */ if ((value & 0xf800) != 0) { proto_tree_add_expert(tree, pinfo, &ei_ansi_637_unknown_encoding, tvb, offset, len); return; } proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_cmas_encoding, tvb, offset, 2, value, "%s (%u)", val_to_str_const((value & 0xf800) >> 11, ansi_tsb58_encoding_vals, "Error"), (value & 0xf800) >> 11); proto_tree_add_item(tree, hf_ansi_637_tele_cmas_num_fields, tvb, offset, 2, ENC_BIG_ENDIAN); num_fields = (value & 0x07f8) >> 3; offset += 2; /* NOTE: there are now 3 bits remaining in 'value' */ unused_bits = 3; required_octs = num_fields; tvb_out = tvb_new_octet_aligned(tvb, ((offset - 1) * 8) + (8 - unused_bits), (required_octs * 8)); add_new_data_source(pinfo, tvb_out, "CMAS Message"); temp_offset = offset; offset = 0; proto_tree_add_item(tree, hf_ansi_637_tele_cmas_protocol_version, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; while ((required_octs - offset) > 2) { record_type = tvb_get_guint8(tvb_out, offset); subtree_idx = record_type; switch (record_type) { default: str = "Reserved"; subtree_idx = 3; break; case 0x00: str = "Type 0 Elements (Alert Text)"; break; case 0x01: str = "Type 1 Elements"; break; case 0x02: str = "Type 2 Elements"; break; } record_len = tvb_get_guint8(tvb_out, offset + 1); subtree = proto_tree_add_subtree(tree, tvb_out, offset, record_len + 2, ett_tia_1149_cmas_param[subtree_idx], NULL, str); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_record_type, tvb_out, offset, 1, record_type, "%s", str); offset += 1; proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_record_len, tvb_out, offset, 1, record_len, "%u", record_len); offset += 1; switch (record_type) { default: proto_tree_add_expert(subtree, pinfo, &ei_ansi_637_unknown_cmas_record_type, tvb_out, offset, record_len); offset += record_len; break; case 0x00: encoding = (tvb_get_guint8(tvb_out, offset) & 0xf8) >> 3; str = val_to_str_const(encoding, ansi_tsb58_encoding_vals, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_char_set, tvb_out, offset, 1, encoding, "%s (%u)", str, encoding); num_bits = (record_len * 8) - 5; switch (encoding) { case 0x04: /* UNICODE */ /* 16-bit encodings */ num_fields = num_bits / 16; reserved_bits = 3; break; case 0x00: /* Octet, unspecified */ case 0x10: /* KSC5601 (Korean) */ case 0x07: /* Latin/Hebrew */ case 0x08: /* Latin */ /* 8-bit encodings */ num_fields = num_bits / 8; reserved_bits = 3; break; default: /* 7-bit encodings */ num_fields = num_bits / 7; if ((num_bits % 7) == 0) { oct2 = tvb_get_guint8(tvb_out, offset + record_len - 1); if ((oct2 & 0x7f) == 0) { /* * the entire last 7 bits are reserved */ num_fields--; } } reserved_bits = num_bits - (num_fields * 7); break; } temp_offset = offset; if (num_fields) { text_decoder(tvb_out, pinfo, subtree, temp_offset, encoding, num_fields, num_bits, 3 /* (5 bits used from 'temp_offset' octet for encoding */, 0, hf_ansi_637_tele_cmas_text); } offset += (record_len - 1); if (reserved_bits > 0) proto_tree_add_bits_item(subtree, hf_ansi_637_reserved_bits_8_generic, tvb_out, (offset*8)+(8-reserved_bits), reserved_bits, ENC_NA); offset += 1; break; case 0x01: oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_const(oct, cmas_category_strings, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_category, tvb_out, offset, 1, oct, "%s (%u)", str, oct); offset += 1; oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_const(oct, cmas_response_type_strings, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_response_type, tvb_out, offset, 1, oct, "%s (%u)", str, oct); offset += 1; oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_const((oct & 0xf0) >> 4, cmas_severity_strings, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_severity, tvb_out, offset, 1, oct, "%s (%u)", str, (oct & 0xf0) >> 4); str = val_to_str_const(oct & 0x0f, cmas_urgency_strings, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_urgency, tvb_out, offset, 1, oct, "%s (%u)", str, oct & 0x0f); offset += 1; oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_const((oct & 0xf0) >> 4, cmas_certainty_strings, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_certainty, tvb_out, offset, 1, oct, "%s (%u)", str, (oct & 0xf0) >> 4); proto_tree_add_item(subtree, hf_ansi_637_reserved_bits_8_0f, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; break; case 0x02: proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_identifier, tvb_out, offset, 2, ENC_BIG_ENDIAN); offset += 2; proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_alert_handling, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; oct = tvb_get_guint8(tvb_out, offset); /* * TIA-1149 does not say whether this should be encoded in the same way as IS-637 * I.e. year = oct + ((oct < 96) ? 2000 : 1900); */ value = oct + ((oct < 96) ? 2000 : 1900); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_expires_year, tvb_out, offset, 1, oct, "%u (%02x)", value, oct); offset += 1; oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_const(oct - 1, ansi_tele_month_strings, "Invalid"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_expires_month, tvb_out, offset, 1, oct, "%s (%02x)", str, oct); offset += 1; proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_expires_day, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_expires_hours, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_expires_minutes, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; proto_tree_add_item(subtree, hf_ansi_637_tele_cmas_expires_seconds, tvb_out, offset, 1, ENC_BIG_ENDIAN); offset += 1; oct = tvb_get_guint8(tvb_out, offset); str = val_to_str_ext_const(oct, &ansi_tsb58_language_ind_vals_ext, "Reserved"); proto_tree_add_uint_format_value(subtree, hf_ansi_637_tele_cmas_language, tvb_out, offset, 1, oct, "%s (%u)", str, oct); offset += 1; break; } } EXTRANEOUS_DATA_CHECK(required_octs, offset); offset += temp_offset; /* move 'offset' back to the correct spot in 'tvb' */ proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_07, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_user_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p) { guint8 encoding; guint8 encoding_bit_len; guint8 num_fields; guint8 unused_bits; guint8 fill_bits; guint16 reserved_bits; guint32 value; guint32 orig_offset; guint32 saved_offset; guint32 required_octs; const gchar *str; tvbuff_t *tvb_out; enum character_set cset; SHORT_DATA_CHECK(len, 2); orig_offset = offset; reserved_bits = len * 8; value = tvb_get_ntohs(tvb, offset); encoding = (guint8) ((value & 0xf800) >> 11); str = val_to_str_const(encoding, ansi_tsb58_encoding_vals, "Reserved"); switch (encoding) { case 0x00: case 0x05: case 0x06: case 0x07: case 0x08: case 0x10: encoding_bit_len = 8; cset = OTHER; break; case 0x01: case 0x02: case 0x03: default: encoding_bit_len = 7; cset = ASCII_7BITS; break; case 0x04: encoding_bit_len = 16; cset = OTHER; break; case 0x09: encoding_bit_len = 7; cset = GSM_7BITS; break; } proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_user_data_encoding, tvb, offset, 2, value, "%s (%u)", str, encoding); reserved_bits -= 5; if (encoding == 0x01) { proto_tree_add_item(tree, hf_ansi_637_tele_user_data_message_type, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 1; value = tvb_get_ntohs(tvb, offset); reserved_bits -= 8; } proto_tree_add_item(tree, hf_ansi_637_tele_user_data_num_fields, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 1; num_fields = (value & 0x07f8) >> 3; reserved_bits -= 8 + (num_fields * encoding_bit_len); /* NOTE: there are now 3 bits remaining in 'value' */ unused_bits = 3; fill_bits = 0; /* * ALL of this is for header support ! */ if (*has_private_data_p == TRUE) { gsm_sms_udh_fields_t udh_fields; gint32 num_udh_bits; memset(&udh_fields, 0, sizeof(udh_fields)); value = tvb_get_ntohs(tvb, offset); /* * 'length' split across two octets +1 for the length octet itself * (dis_field_udh() will start at the length offset) */ required_octs = ((value & 0x07f8) >> 3) + 1; /* * need fill bits */ if (encoding_bit_len == 7) { /* * not the same formula as dis_field_udh() because we are including * the length octet in the calculation but the result is the same */ fill_bits = 7 - ((required_octs * 8) % 7); } num_udh_bits = (required_octs * 8) + fill_bits; tvb_out = tvb_new_octet_aligned(tvb, (offset * 8) + (8 - unused_bits), num_udh_bits); add_new_data_source(pinfo, tvb_out, "Header"); saved_offset = offset + required_octs; offset = 0; fill_bits = 0; if (encoding_bit_len == 16) { /* the NUM_FIELD value represents the number of characters in Unicode encoding. Let's translate it into bytes */ num_fields <<= 1; } dis_field_udh(tvb_out, pinfo, tree, &offset, &required_octs, &num_fields, cset, &fill_bits, &udh_fields); offset = saved_offset; if (encoding_bit_len == 7) { switch (cset) { case GSM_7BITS: case OTHER: break; case ASCII_7BITS: if (fill_bits > unused_bits) { /* this branch was NOT tested */ offset += 1; unused_bits = 8 - (fill_bits - unused_bits); } else if (fill_bits > 0) { /* this branch was tested */ unused_bits = unused_bits - fill_bits; } if (unused_bits == 0) { /* this branch was NOT tested */ offset += 1; unused_bits = 8; } break; } } else if (encoding_bit_len == 16) { /* compute the number of Unicode characters now that UDH is taken into account */ num_fields >>= 1; } if (udh_fields.frags > 0) { col_append_fstr(pinfo->cinfo, COL_INFO, " (Short Message fragment %u of %u)", udh_fields.frag, udh_fields.frags); } } if (num_fields) { text_decoder(tvb, pinfo, tree, offset, encoding, num_fields, num_fields * encoding_bit_len, unused_bits, fill_bits, hf_ansi_637_tele_user_data_text); } if (reserved_bits > 0) { /* * unlike for CMAS, the bits that can be reserved will always be * at the end of an octet so we don't have to worry about them * spanning two octets */ switch (cset) { case GSM_7BITS: { crumb_spec_t crumbs[3]; guint8 i = 0; guint bits_offset; if (reserved_bits > 3) { bits_offset = ((orig_offset + len - 2)*8)+5; crumbs[i].crumb_bit_offset = 0; crumbs[i++].crumb_bit_length = reserved_bits - 3; crumbs[i].crumb_bit_offset = 8; } else { bits_offset = ((orig_offset + len - 1)*8)+5; crumbs[i].crumb_bit_offset = 0; } crumbs[i++].crumb_bit_length = 3; crumbs[i].crumb_bit_offset = 0; crumbs[i].crumb_bit_length = 0; proto_tree_add_split_bits_item_ret_val(tree, hf_ansi_637_reserved_bits_16_generic, tvb, bits_offset, crumbs, NULL); } break; default: proto_tree_add_bits_item(tree, hf_ansi_637_reserved_bits_8_generic, tvb, ((orig_offset + len - 1)*8)+(8-reserved_bits), reserved_bits, ENC_NA); /* LSBs */ break; } } } static void tele_param_rsp_code(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_response_code, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_message_center_timestamp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 6); tele_param_timestamp(tvb, pinfo, tree, len, offset, hf_ansi_637_tele_message_center_ts_year, hf_ansi_637_tele_message_center_ts_month, hf_ansi_637_tele_message_center_ts_day, hf_ansi_637_tele_message_center_ts_hours, hf_ansi_637_tele_message_center_ts_minutes, hf_ansi_637_tele_message_center_ts_seconds); } static void tele_param_validity_period_abs(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 6); tele_param_timestamp(tvb, pinfo, tree, len, offset, hf_ansi_637_tele_validity_period_ts_year, hf_ansi_637_tele_validity_period_ts_month, hf_ansi_637_tele_validity_period_ts_day, hf_ansi_637_tele_validity_period_ts_hours, hf_ansi_637_tele_validity_period_ts_minutes, hf_ansi_637_tele_validity_period_ts_seconds); } static void tele_param_timestamp_rel(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len _U_, guint32 offset, int hf) { guint8 oct; guint32 value = 0; const gchar *str = NULL; const gchar *str2 = NULL; oct = tvb_get_guint8(tvb, offset); switch (oct) { case 245: str = "Indefinite"; break; case 246: str = "Immediate"; break; case 247: str = "Valid until mobile becomes inactive/Deliver when mobile next becomes active"; break; case 248: str = "Valid until registration area changes, discard if not registered" ; break; default: if (oct <= 143) { value = (oct + 1) * 5; str2 = "Minutes"; break; } else if ((oct >= 144) && (oct <= 167)) { value = (oct - 143) * 30; str2 = "Minutes + 12 Hours"; break; } else if ((oct >= 168) && (oct <= 196)) { value = oct - 166; str2 = "Days"; break; } else if ((oct >= 197) && (oct <= 244)) { value = oct - 192; str2 = "Weeks"; break; } else { str = "Reserved"; break; } } if (str != NULL) { proto_tree_add_uint_format_value(tree, hf, tvb, offset, 1, oct, "%s", str); } else { proto_tree_add_uint_format_value(tree, hf, tvb, offset, 1, oct, "%u %s", value, str2); } } static void tele_param_validity_period_rel(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); tele_param_timestamp_rel(tvb, pinfo, tree, len, offset, hf_ansi_637_tele_validity_period_relative_validity); } static void tele_param_deferred_del_abs(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 6); tele_param_timestamp(tvb, pinfo, tree, len, offset, hf_ansi_637_tele_deferred_del_ts_year, hf_ansi_637_tele_deferred_del_ts_month, hf_ansi_637_tele_deferred_del_ts_day, hf_ansi_637_tele_deferred_del_ts_hours, hf_ansi_637_tele_deferred_del_ts_minutes, hf_ansi_637_tele_deferred_del_ts_seconds); } static void tele_param_deferred_del_rel(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); tele_param_timestamp_rel(tvb, pinfo, tree, len, offset, hf_ansi_637_tele_deferred_del_relative); } static const value_string tele_param_priority_ind_strings[] = { { 0, "Normal" }, { 1, "Interactive" }, { 2, "Urgent" }, { 3, "Emergency" }, { 0, NULL } }; static void tele_param_pri_ind(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_priority_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_3f, tvb, offset, 1, ENC_BIG_ENDIAN); } static const value_string tele_param_privacy_ind_strings[] = { { 0, "Not restricted (privacy level 0)" }, { 1, "Restricted (privacy level 1)" }, { 2, "Confidential (privacy level 2)" }, { 3, "Secret (privacy level 3)" }, { 0, NULL } }; static void tele_param_priv_ind(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_privacy_indicator, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_3f, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_reply_opt(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_reply_option_user_ack_req, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_reply_option_dak_req, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_reply_option_read_ack_req, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_reply_option_report_req, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_0f, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_num_messages(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint8 oct; EXACT_DATA_CHECK(len, 1); oct = tvb_get_guint8(tvb, offset); proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_num_messages, tvb, offset, 1, ((oct & 0xf0) >> 4) * 10 + (oct & 0x0f), "%u%u", (oct & 0xf0) >> 4, oct & 0x0f); } static const value_string tele_param_alert_priority_strings[] = { { 0, "Use Mobile default alert" }, { 1, "Use Low-priority alert" }, { 2, "Use Medium-priority alert" }, { 3, "Use High-priority alert" }, { 0, NULL } }; static void tele_param_alert(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_alert_msg_delivery_priority, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_3f, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_lang_ind(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint8 oct; const gchar *str = NULL; EXACT_DATA_CHECK(len, 1); oct = tvb_get_guint8(tvb, offset); str = val_to_str_ext_const(oct, &ansi_tsb58_language_ind_vals_ext, "Reserved"); proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_language, tvb, offset, 1, oct, "%s (%u)", str, oct); } static void tele_param_cb_num(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint8 oct, oct2, num_fields, odd; guint8 *poctets; guint32 saved_offset; guint32 required_octs; guint32 i; SHORT_DATA_CHECK(len, 2); proto_tree_add_item(tree, hf_ansi_637_tele_cb_num_digit_mode, tvb, offset, 1, ENC_BIG_ENDIAN); oct = tvb_get_guint8(tvb, offset); if (oct & 0x80) { proto_tree_add_item(tree, hf_ansi_637_tele_cb_num_ton, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_cb_num_plan, tvb, offset, 1, ENC_BIG_ENDIAN); offset += 1; proto_tree_add_item(tree, hf_ansi_637_tele_cb_num_num_fields, tvb, offset, 1, ENC_BIG_ENDIAN); num_fields = tvb_get_guint8(tvb, offset); if (num_fields == 0) return; SHORT_DATA_CHECK(len - 2, num_fields); offset += 1; poctets = tvb_get_string_enc(wmem_packet_scope(), tvb, offset, num_fields, ENC_ASCII|ENC_NA); proto_tree_add_string_format(tree, hf_ansi_637_tele_cb_num_number, tvb, offset, num_fields, (gchar *) poctets, "Number: %s", (gchar *) format_text(poctets, num_fields)); } else { offset += 1; oct2 = tvb_get_guint8(tvb, offset); num_fields = ((oct & 0x7f) << 1) | ((oct2 & 0x80) >> 7); proto_tree_add_item(tree, hf_ansi_637_tele_cb_num_num_fields07f8, tvb, offset, 2, ENC_BIG_ENDIAN); oct = oct2; odd = FALSE; if (num_fields > 0) { i = (num_fields - 1) * 4; required_octs = (i / 8) + ((i % 8) ? 1 : 0); SHORT_DATA_CHECK(len - 2, required_octs); odd = num_fields & 0x01; memset((void *) ansi_637_bigbuf, 0, sizeof(ansi_637_bigbuf)); saved_offset = offset; offset += 1; i = 0; while (i < num_fields) { ansi_637_bigbuf[i] = air_digits[(oct & 0x78) >> 3]; i += 1; if (i >= num_fields) break; oct2 = tvb_get_guint8(tvb, offset); offset += 1; ansi_637_bigbuf[i] = air_digits[((oct & 0x07) << 1) | ((oct2 & 0x80) >> 7)]; oct = oct2; i += 1; } proto_tree_add_string_format(tree, hf_ansi_637_tele_cb_num_number, tvb, saved_offset, offset - saved_offset, ansi_637_bigbuf, "Number: %s", ansi_637_bigbuf); } proto_tree_add_item(tree, odd ? hf_ansi_637_reserved_bits_8_07 : hf_ansi_637_reserved_bits_8_7f, tvb, offset - 1, 1, ENC_BIG_ENDIAN); } } static const value_string tele_param_msg_display_mode_strings[] = { { 0, "Immediate Display: The mobile station is to display the received message as soon as possible." }, { 1, "Mobile default setting: The mobile station is to display the received message based on a pre-defined mode in the mobile station." }, { 2, "User Invoke: The mobile station is to display the received message based on the mode selected by the user." }, { 3, "Reserved" }, { 0, NULL } }; static void tele_param_disp_mode(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_msg_display_mode, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_3f, tvb, offset, 1, ENC_BIG_ENDIAN); } static void tele_param_mult_enc_user_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint64 encoding; guint8 encoding_bit_len; guint64 num_fields; guint8 unused_bits; guint8 fill_bits; guint16 reserved_bits; guint32 orig_offset; enum character_set cset = OTHER; SHORT_DATA_CHECK(len, 2); orig_offset = offset; offset <<= 3; reserved_bits = len * 8; while (reserved_bits > 7) { proto_tree_add_bits_ret_val(tree, hf_ansi_637_tele_mult_enc_user_data_encoding, tvb, offset, 5, &encoding, ENC_BIG_ENDIAN); switch (encoding) { case 0x00: case 0x05: case 0x06: case 0x07: case 0x08: case 0x10: encoding_bit_len = 8; cset = OTHER; break; case 0x01: case 0x02: case 0x03: default: encoding_bit_len = 7; cset = ASCII_7BITS; break; case 0x04: encoding_bit_len = 16; cset = OTHER; break; case 0x09: encoding_bit_len = 7; cset = GSM_7BITS; break; } offset += 5; reserved_bits -= 5; proto_tree_add_bits_ret_val(tree, hf_ansi_637_tele_mult_enc_user_data_num_fields, tvb, offset, 8, &num_fields, ENC_BIG_ENDIAN); offset += 8; reserved_bits -= 8; unused_bits = (offset & 0x07) ? 8 - (offset & 0x07) : 0; fill_bits = 0; if (num_fields) { text_decoder(tvb, pinfo, tree, offset>>3, (guint8)encoding, (guint8)num_fields, (guint8)num_fields * encoding_bit_len, unused_bits, fill_bits, hf_ansi_637_tele_mult_enc_user_data_text); offset += (guint8)num_fields * encoding_bit_len; reserved_bits -= (guint8)num_fields * encoding_bit_len; } } if (reserved_bits > 0) { /* * unlike for CMAS, the bits that can be reserved will always be * at the end of an octet so we don't have to worry about them * spanning two octets */ switch (cset) { case GSM_7BITS: { crumb_spec_t crumbs[3]; guint8 i = 0; guint bits_offset; if (reserved_bits > 3) { bits_offset = ((orig_offset + len - 2)*8)+5; crumbs[i].crumb_bit_offset = 0; crumbs[i++].crumb_bit_length = reserved_bits - 3; crumbs[i].crumb_bit_offset = 8; } else { bits_offset = ((orig_offset + len - 1)*8)+5; crumbs[i].crumb_bit_offset = 0; } crumbs[i++].crumb_bit_length = 3; crumbs[i].crumb_bit_offset = 0; crumbs[i].crumb_bit_length = 0; proto_tree_add_split_bits_item_ret_val(tree, hf_ansi_637_reserved_bits_16_generic, tvb, bits_offset, crumbs, NULL); } break; default: proto_tree_add_bits_item(tree, hf_ansi_637_reserved_bits_8_generic, tvb, ((orig_offset + len - 1)*8)+(8-reserved_bits), reserved_bits, ENC_NA); /* LSBs */ break; } } } static void tele_param_msg_deposit_idx(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 2); proto_tree_add_item(tree, hf_ansi_637_tele_msg_deposit_idx, tvb, offset, 2, ENC_BIG_ENDIAN); } static const value_string tele_param_srvc_cat_prog_data_op_code_vals[] = { { 0x00, "Delete the Service Category" }, { 0x01, "Add the Service Category" }, { 0x02, "Clear all Service Categories" }, { 0x00, NULL} }; static const value_string tele_param_srvc_cat_prog_data_alert_option_vals[] = { { 0x00, "No alert" }, { 0x01, "Mobile Station default alert" }, { 0x02, "Vibrate alert once" }, { 0x03, "Vibrate alert - repeat" }, { 0x04, "Visual alert once" }, { 0x05, "Visual alert - repeat" }, { 0x06, "Low-priority alert once" }, { 0x07, "Low-priority alert - repeat" }, { 0x08, "Medium-priority alert once" }, { 0x09, "Medium-priority alert - repeat" }, { 0x0a, "High-priority alert once" }, { 0x0b, "High-priority alert - repeat" }, { 0x00, NULL} }; static void tele_param_srvc_cat_prog_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint64 encoding; guint8 encoding_bit_len; guint64 num_fields; guint8 unused_bits; guint8 fill_bits; guint16 reserved_bits; guint32 orig_offset; enum character_set cset = OTHER; SHORT_DATA_CHECK(len, 2); orig_offset = offset; offset <<= 3; reserved_bits = len * 8; proto_tree_add_bits_ret_val(tree, hf_ansi_637_tele_srvc_cat_prog_data_encoding, tvb, offset, 5, &encoding, ENC_BIG_ENDIAN); switch (encoding) { case 0x00: case 0x05: case 0x06: case 0x07: case 0x08: case 0x10: encoding_bit_len = 8; cset = OTHER; break; case 0x01: case 0x02: case 0x03: default: encoding_bit_len = 7; cset = ASCII_7BITS; break; case 0x04: encoding_bit_len = 16; cset = OTHER; break; case 0x09: encoding_bit_len = 7; cset = GSM_7BITS; break; } offset += 5; reserved_bits -= 5; while (reserved_bits > 7) { proto_tree_add_bits_item(tree, hf_ansi_637_tele_srvc_cat_prog_data_operation_code, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; reserved_bits -= 4; proto_tree_add_bits_item(tree, hf_ansi_637_tele_srvc_cat_prog_data_category, tvb, offset, 16, ENC_BIG_ENDIAN); offset += 16; reserved_bits -= 16; proto_tree_add_bits_item(tree, hf_ansi_637_tele_srvc_cat_prog_data_language, tvb, offset, 8, ENC_BIG_ENDIAN); offset += 8; reserved_bits -= 8; proto_tree_add_bits_item(tree, hf_ansi_637_tele_srvc_cat_prog_data_max_messages, tvb, offset, 8, ENC_BIG_ENDIAN); offset += 8; reserved_bits -= 8; proto_tree_add_bits_item(tree, hf_ansi_637_tele_srvc_cat_prog_data_alert_option, tvb, offset, 4, ENC_BIG_ENDIAN); offset += 4; reserved_bits -= 4; proto_tree_add_bits_ret_val(tree, hf_ansi_637_tele_srvc_cat_prog_data_num_fields, tvb, offset, 8, &num_fields, ENC_BIG_ENDIAN); offset += 8; reserved_bits -= 8; unused_bits = (offset & 0x07) ? 8 - (offset & 0x07) : 0; fill_bits = 0; if (num_fields) { text_decoder(tvb, pinfo, tree, offset>>3, (guint8)encoding, (guint8)num_fields, (guint8)num_fields * encoding_bit_len, unused_bits, fill_bits, hf_ansi_637_tele_srvc_cat_prog_data_text); offset += (guint8)num_fields * encoding_bit_len; reserved_bits -= (guint8)num_fields * encoding_bit_len; } } if (reserved_bits > 0) { /* * unlike for CMAS, the bits that can be reserved will always be * at the end of an octet so we don't have to worry about them * spanning two octets */ switch (cset) { case GSM_7BITS: { crumb_spec_t crumbs[3]; guint8 i = 0; guint bits_offset; if (reserved_bits > 3) { bits_offset = ((orig_offset + len - 2)*8)+5; crumbs[i].crumb_bit_offset = 0; crumbs[i++].crumb_bit_length = reserved_bits - 3; crumbs[i].crumb_bit_offset = 8; } else { bits_offset = ((orig_offset + len - 1)*8)+5; crumbs[i].crumb_bit_offset = 0; } crumbs[i++].crumb_bit_length = 3; crumbs[i].crumb_bit_offset = 0; crumbs[i].crumb_bit_length = 0; proto_tree_add_split_bits_item_ret_val(tree, hf_ansi_637_reserved_bits_16_generic, tvb, bits_offset, crumbs, NULL); } break; default: proto_tree_add_bits_item(tree, hf_ansi_637_reserved_bits_8_generic, tvb, ((orig_offset + len - 1)*8)+(8-reserved_bits), reserved_bits, ENC_NA); /* LSBs */ break; } } } static const value_string tele_param_srvc_cat_prog_results_result_strings[] = { { 0x00, "Programming successful" }, { 0x01, "Service Category memory limit exceeded" }, { 0x02, "Service Category limit exceeded" }, { 0x03, "Category already programmed" }, { 0x04, "Category not previously programmed" }, { 0x05, "Invalid MAX_MESSAGES" }, { 0x06, "Invalid ALERT_OPTION" }, { 0x07, "Invalid Service Category name" }, { 0x08, "Unspecified programming failure" }, { 0x09, "Reserved" }, { 0x0a, "Reserved" }, { 0x0b, "Reserved" }, { 0x0c, "Reserved" }, { 0x0d, "Reserved" }, { 0x0e, "Reserved" }, { 0x0f, "Reserved" }, { 0, NULL } }; static void tele_param_srvc_cat_prog_results(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint32 curr_offset; guint32 value; const gchar *str = NULL; curr_offset = offset; while ((len - (curr_offset - offset)) >= 3) { value = tvb_get_ntohs(tvb, curr_offset); str = val_to_str_const(value, ansi_tsb58_srvc_cat_vals, "Reserved"); proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_srvc_cat_prog_results_srvc_cat, tvb, curr_offset, 2, value, "%s (%u)", str, value); curr_offset += 2; proto_tree_add_item(tree, hf_ansi_637_tele_srvc_cat_prog_results_result, tvb, curr_offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_0f, tvb, curr_offset, 1, ENC_BIG_ENDIAN); curr_offset += 1; } EXTRANEOUS_DATA_CHECK(len, curr_offset - offset); } /* Adamek Jan - IS637C Message status decoding procedure */ static const value_string tele_param_msg_status_error_class_strings[] = { { 0x00, "No Error" }, { 0x01, "Reserved" }, { 0x02, "Temporary Condition" }, { 0x03, "Permanent Condition" }, { 0, NULL } }; static void tele_param_msg_status(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { guint8 oct; guint8 msg_status_code; const gchar *str = NULL; EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_msg_status, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_tele_msg_status_error_class, tvb, offset, 1, ENC_BIG_ENDIAN); oct = tvb_get_guint8(tvb, offset); msg_status_code = (oct & 0x3f); switch ((oct & 0xc0) >> 6) { case 0x00: switch (msg_status_code) { case 0x00: str = "Message accepted"; break; case 0x01: str = "Message deposited to Internet"; break; case 0x02: str = "Message delivered"; break; case 0x03: str = "Message cancelled"; break; default: str = "Reserved"; break; } break; case 0x02: switch (msg_status_code) { case 0x04: str = "Network congestion"; break; case 0x05: str = "Network error"; break; case 0x1f: str = "Unknown error"; break; default: str = "Reserved"; break; } break; case 0x03: switch (msg_status_code) { case 0x04: str = "Network congestion"; break; case 0x05: str = "Network error"; break; case 0x06: str = "Cancel failed"; break; case 0x07: str = "Blocked destination"; break; case 0x08: str = "Text too long"; break; case 0x09: str = "Duplicate message"; break; case 0x0a: str = "Invalid destination"; break; case 0x0d: str = "Message expired"; break; case 0x1f: str = "Unknown error"; break; default: str = "Reserved"; break; } break; default: str = "Reserved"; break; } proto_tree_add_uint_format_value(tree, hf_ansi_637_tele_msg_status_code, tvb, offset, 1, oct, "%s (%u)", str, msg_status_code); } static void tele_param_tp_failure_cause(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p _U_) { EXACT_DATA_CHECK(len, 1); proto_tree_add_item(tree, hf_ansi_637_tele_tp_failure_cause_value, tvb, offset, 1, ENC_BIG_ENDIAN); } #define NUM_TELE_PARAM (sizeof(ansi_tele_param_strings)/sizeof(value_string)) static gint ett_ansi_637_tele_param[NUM_TELE_PARAM]; static void (*ansi_637_tele_param_fcn[])(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gboolean *has_private_data_p) = { tele_param_msg_id, /* Message Identifier */ tele_param_user_data, /* User Data */ tele_param_rsp_code, /* User Response Code */ tele_param_message_center_timestamp,/* Message Center Time Stamp */ tele_param_validity_period_abs, /* Validity Period - Absolute */ tele_param_validity_period_rel, /* Validity Period - Relative */ tele_param_deferred_del_abs, /* Deferred Delivery Time - Absolute */ tele_param_deferred_del_rel, /* Deferred Delivery Time - Relative */ tele_param_pri_ind, /* Priority Indicator */ tele_param_priv_ind, /* Privacy Indicator */ tele_param_reply_opt, /* Reply Option */ tele_param_num_messages, /* Number of Messages */ tele_param_alert, /* Alert on Message Delivery */ tele_param_lang_ind, /* Language Indicator */ tele_param_cb_num, /* Call-Back Number */ tele_param_disp_mode, /* Message Display Mode */ tele_param_mult_enc_user_data, /* Multiple Encoding User Data */ tele_param_msg_deposit_idx, /* Message Deposit Index */ tele_param_srvc_cat_prog_data, /* Service Category Program Data */ tele_param_srvc_cat_prog_results, /* Service Category Program Results */ tele_param_msg_status, /* Message status */ tele_param_tp_failure_cause, /* TP-Failure cause */ NULL, /* Enhanced VMN */ NULL /* Enhanced VMN Ack */ }; static void trans_param_tele_id(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gchar *add_string, int string_len) { guint32 value; const gchar *str = NULL; EXACT_DATA_CHECK(len, 2); value = tvb_get_ntohs(tvb, offset); ansi_637_trans_tele_id = value; str = try_val_to_str(value, ansi_tele_id_strings); if (NULL == str) { switch (value) { case 1: str = "Reserved for maintenance"; break; case 4102: str = "CDMA Service Category Programming Teleservice (SCPT)"; break; case 4103: str = "CDMA Card Application Toolkit Protocol Teleservice (CATPT)"; break; case 32513: str = "TDMA Cellular Messaging Teleservice"; break; case 32514: str = "TDMA Cellular Paging Teleservice (CPT-136)"; break; case 32515: str = "TDMA Over-the-Air Activation Teleservice (OATS)"; break; case 32520: str = "TDMA System Assisted Mobile Positioning through Satellite (SAMPS)"; break; case 32584: str = "TDMA Segmented System Assisted Mobile Positioning Service"; break; default: if ((value >= 2) && (value <= 4095)) { str = "Reserved for assignment by TIA-41"; } else if ((value >= 4104) && (value <= 4113)) { str = "Reserved for GSM1x Teleservice (CDMA)"; } else if ((value >= 4114) && (value <= 32512)) { str = "Reserved for assignment by TIA-41"; } else if ((value >= 32521) && (value <= 32575)) { str = "Reserved for assignment by this Standard for TDMA MS-based SMEs"; } else if ((value >= 49152) && (value <= 65535)) { str = "Reserved for carrier specific teleservices"; } else { str = "Unrecognized Teleservice ID"; } break; } } /* * NOT format_value because I don't need the text from the hf_ */ proto_tree_add_uint_format(tree, hf_ansi_637_trans_tele_id, tvb, offset, 2, value, "%s (%u)", str, value); g_snprintf(add_string, string_len, " - %s (%u)", str, value); } static void trans_param_srvc_cat(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gchar *add_string, int string_len) { guint32 value; const gchar *str; EXACT_DATA_CHECK(len, 2); value = tvb_get_ntohs(tvb, offset); str = val_to_str_const(value, ansi_tsb58_srvc_cat_vals, "Reserved"); proto_tree_add_uint_format_value(tree, hf_ansi_637_trans_srvc_cat, tvb, offset, 2, value, "%s (%u)", str, value); g_snprintf(add_string, string_len, " - %s (%u)", str, value); if ((value >= ANSI_TSB58_SRVC_CAT_CMAS_MIN) && (value <= ANSI_TSB58_SRVC_CAT_CMAS_MAX)) { col_append_fstr(pinfo->cinfo, COL_INFO, " - CMAS (%s)", str); } } static const value_string trans_param_addr_data_net_ton_strings[] = { { 0x00, "Unknown" }, { 0x01, "Internet Protocol (RFC 791)" }, { 0x02, "Internet Email Address (RFC 822)" }, { 0, NULL } }; static void trans_param_address(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gchar *add_string _U_, int string_len _U_) { guint8 oct, oct2, odd; gboolean email_addr; guint32 i, saved_offset, required_octs; guint64 num_fields; SHORT_DATA_CHECK(len, 2); oct = tvb_get_guint8(tvb, offset); proto_tree_add_item(tree, hf_ansi_637_trans_addr_param_digit_mode, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_trans_addr_param_number_mode, tvb, offset, 1, ENC_BIG_ENDIAN); if (oct & 0x80) { if (oct & 0x40) { email_addr = (((oct & 0x38) >> 3) == 0x02) ? TRUE : FALSE; /* * do not change to ...add_item() with VALS in hf defintion because this parameter is * used below in the 'else' with a different string array */ proto_tree_add_uint_format_value(tree, hf_ansi_637_trans_addr_param_ton, tvb, offset, 1, oct, "%s (%u)", val_to_str_const((oct & 0x38) >> 3, trans_param_addr_data_net_ton_strings, "Reserved"), (oct & 0x38) >> 3); proto_tree_add_bits_ret_val(tree, hf_ansi_637_trans_addr_param_num_fields, tvb, (offset*8)+5, 8, &num_fields, ENC_BIG_ENDIAN); if (num_fields == 0) return; offset += 1; oct = tvb_get_guint8(tvb, offset);; SHORT_DATA_CHECK(len - 2, num_fields); proto_tree_add_bits_item(tree, hf_ansi_637_msb_first_field, tvb, offset*8, 3, ENC_NA); offset += 1; i = 0; while (i < num_fields) { ansi_637_bigbuf[i] = (oct & 0x07) << 5; ansi_637_bigbuf[i] |= ((oct = tvb_get_guint8(tvb, offset + i)) & 0xf8) >> 3; i += 1; } ansi_637_bigbuf[i] = '\0'; if (email_addr) { proto_tree_add_string_format(tree, hf_ansi_637_trans_addr_param_number, tvb, offset - 1, (gint)num_fields + 1, ansi_637_bigbuf, "Number: %s", ansi_637_bigbuf); } else { proto_tree_add_bytes(tree, hf_ansi_637_trans_bin_addr, tvb, offset - 1, (gint)num_fields + 1, (guint8 *) ansi_637_bigbuf); } offset += ((guint32)num_fields - 1); proto_tree_add_bits_item(tree, hf_ansi_637_lsb_last_field, tvb, offset*8, 5, ENC_NA); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_07, tvb, offset, 1, ENC_BIG_ENDIAN); } else { /* * do not change to ...add_item() with VALS in hf definition because this parameter * is used above in the 'if' with a different string array */ proto_tree_add_uint_format_value(tree, hf_ansi_637_trans_addr_param_ton, tvb, offset, 1, oct, "%s (%u)", val_to_str_const((oct & 0x38) >> 3, ansi_a_ms_info_rec_num_type_vals, "Reserved"), (oct & 0x38) >> 3); proto_tree_add_item(tree, hf_ansi_637_trans_addr_param_plan, tvb, offset, 2, ENC_BIG_ENDIAN); offset += 1; proto_tree_add_bits_ret_val(tree, hf_ansi_637_trans_addr_param_num_fields, tvb, (offset*8)+1, 8, &num_fields, ENC_BIG_ENDIAN); offset += 1; if (num_fields == 0) return; SHORT_DATA_CHECK(len - 3, num_fields); proto_tree_add_bits_item(tree, hf_ansi_637_msb_first_field, tvb, (offset*8)+1, 7, ENC_NA); oct = tvb_get_guint8(tvb, offset); offset += 1; i = 0; while (i < num_fields) { ansi_637_bigbuf[i] = (oct & 0x7f) << 1; ansi_637_bigbuf[i] |= ((oct = tvb_get_guint8(tvb, offset + i)) & 0x80) >> 7; i += 1; } ansi_637_bigbuf[i] = '\0'; proto_tree_add_string_format(tree, hf_ansi_637_trans_addr_param_number, tvb, offset - 1, (gint)num_fields + 1, ansi_637_bigbuf, "Number: %s", ansi_637_bigbuf); offset += ((guint32)num_fields - 1); proto_tree_add_bits_item(tree, hf_ansi_637_lsb_last_field, tvb, offset*8, 1, ENC_NA); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_7f, tvb, offset, 1, ENC_BIG_ENDIAN); } } else { proto_tree_add_bits_ret_val(tree, hf_ansi_637_trans_addr_param_num_fields, tvb, (offset*8)+2, 8, &num_fields, ENC_BIG_ENDIAN); offset += 1; oct = tvb_get_guint8(tvb, offset); odd = FALSE; if (num_fields > 0) { i = ((guint32)num_fields - 1) * 4; required_octs = (i / 8) + ((i % 8) ? 1 : 0); SHORT_DATA_CHECK(len - 2, required_octs); odd = num_fields & 0x01; memset((void *) ansi_637_bigbuf, 0, sizeof(ansi_637_bigbuf)); saved_offset = offset; offset += 1; i = 0; while (i < num_fields) { ansi_637_bigbuf[i] = air_digits[(oct & 0x3c) >> 2]; i += 1; if (i >= num_fields) break; oct2 = tvb_get_guint8(tvb, offset); offset += 1; ansi_637_bigbuf[i] = air_digits[((oct & 0x03) << 2) | ((oct2 & 0xc0) >> 6)]; oct = oct2; i += 1; } proto_tree_add_string_format(tree, hf_ansi_637_trans_addr_param_number, tvb, saved_offset, offset - saved_offset, ansi_637_bigbuf, "Number: %s", ansi_637_bigbuf); } proto_tree_add_item(tree, odd ? hf_ansi_637_reserved_bits_8_03 : hf_ansi_637_reserved_bits_8_3f, tvb, offset - 1, 1, ENC_BIG_ENDIAN); } } static const value_string trans_param_subaddr_type_strings[] = { { 0x0, "NSAP (CCITT Recommendation X.213 or ISO 8348 AD2)" }, { 0x1, "User-specified" }, { 0, NULL } }; static void trans_param_subaddress(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gchar *add_string _U_, int string_len _U_) { guint8 oct, num_fields; guint32 value; guint32 i; SHORT_DATA_CHECK(len, 2); value = tvb_get_ntohs(tvb, offset); proto_tree_add_uint_format_value(tree, hf_ansi_637_trans_subaddr_type, tvb, offset, 2, value, "%s (%u)", val_to_str_const((value & 0xe000) >> 13, trans_param_subaddr_type_strings, "Reserved"), (value & 0xe000) >> 13); proto_tree_add_item(tree, hf_ansi_637_trans_subaddr_odd_even_ind, tvb, offset, 2, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_trans_subaddr_num_fields, tvb, offset, 2, ENC_BIG_ENDIAN); num_fields = (value & 0x0ff0) >> 4; if (num_fields == 0) return; SHORT_DATA_CHECK(len - 2, num_fields); proto_tree_add_bits_item(tree, hf_ansi_637_msb_first_field, tvb, (offset*8)+12, 4, ENC_NA); offset += 2; oct = value & 0x000f; i = 0; while (i < num_fields) { ansi_637_bigbuf[i] = (oct & 0x0f) << 4; ansi_637_bigbuf[i] |= ((oct = tvb_get_guint8(tvb, offset + i)) & 0xf0) >> 4; i += 1; } ansi_637_bigbuf[i] = '\0'; proto_tree_add_bytes(tree, hf_ansi_637_trans_bin_addr, tvb, offset, num_fields - 1, (guint8 *) ansi_637_bigbuf); offset += (num_fields - 1); proto_tree_add_bits_item(tree, hf_ansi_637_lsb_last_field, tvb, offset*8, 4, ENC_NA); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_0f, tvb, offset, 1, ENC_BIG_ENDIAN); } static void trans_param_bearer_reply_opt(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len _U_, guint32 offset, gchar *add_string, int string_len) { proto_tree_add_item(tree, hf_ansi_637_trans_bearer_reply_seq_num, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_reserved_bits_8_03, tvb, offset, 1, ENC_BIG_ENDIAN); g_snprintf(add_string, string_len, " - Reply Sequence Number (%u)", (tvb_get_guint8(tvb, offset) & 0xfc) >> 2); } static const value_string trans_param_cause_codes_error_class_strings[] = { { 0x00, "No Error" }, { 0x01, "Reserved" }, { 0x02, "Temporary Condition" }, { 0x03, "Permanent Condition" }, { 0, NULL } }; static void trans_param_cause_codes(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, guint len, guint32 offset, gchar *add_string, int string_len) { guint8 oct; const gchar *str; proto_tree_add_item(tree, hf_ansi_637_trans_cause_codes_seq_num, tvb, offset, 1, ENC_BIG_ENDIAN); proto_tree_add_item(tree, hf_ansi_637_trans_cause_codes_error_class, tvb, offset, 1, ENC_BIG_ENDIAN); oct = tvb_get_guint8(tvb, offset); g_snprintf(add_string, string_len, " - Reply Sequence Number (%u)", (oct & 0xfc) >> 2); if (!(oct & 0x03)) return; if (len == 1) return; offset += 1; oct = tvb_get_guint8(tvb, offset); switch (oct) { case 0: str = "Address vacant"; break; case 1: str = "Address translation failure"; break; case 2: str = "Network resource shortage"; break; case 3: str = "Network failure"; break; case 4: str = "Invalid Teleservice ID"; break; case 5: str = "Other network problem"; break; case 6: str = "Unsupported network interface"; break; case 32: str = "No page response"; break; case 33: str = "Destination busy"; break; case 34: str = "No acknowledgement"; break; case 35: str = "Destination resource shortage"; break; case 36: str = "SMS delivery postponed"; break; case 37: str = "Destination out of service"; break; case 38: str = "Destination no longer at this address"; break; case 39: str = "Other terminal problem"; break; case 64: str = "Radio interface resource shortage"; break; case 65: str = "Radio interface incompatibility"; break; case 66: str = "Other radio interface problem"; break; case 67: str = "Unsupported Base Station Capability"; break; case 96: str = "Encoding problem"; break; case 97: str = "Service origination denied"; break; case 98: str = "Service termination denied"; break; case 99: str = "Supplementary service not supported"; break; case 100: str = "Service not supported"; break; case 101: str = "Reserved"; break; case 102: str = "Missing expected parameter"; break; case 103: str = "Missing mandatory parameter"; break; case 104: str = "Unrecognized parameter value"; break; case 105: str = "Unexpected parameter value"; break; case 106: str = "User Data size error"; break; case 107: str = "Other general problems"; break; case 108: str = "Session not active"; break; default: if ((oct >= 7) && (oct <= 31)) { str = "Reserved, treat as Other network problem"; } else if ((oct >= 40) && (oct <= 47)) { str = "Reserved, treat as Other terminal problem"; } else if ((oct >= 48) && (oct <= 63)) { str = "Reserved, treat as SMS delivery postponed"; } else if ((oct >= 68) && (oct <= 95)) { str = "Reserved, treat as Other radio interface problem"; } else if ((oct >= 109) && (oct <= 223)) { str = "Reserved, treat as Other general problems"; } else { str = "Reserved for protocol extension, treat as Other general problems"; } break; } proto_tree_add_uint_format_value(tree, hf_ansi_637_trans_cause_codes_code, tvb, offset, 1, oct, "%s (%u)", str, oct); } static void trans_param_bearer_data(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree _U_, guint len, guint32 offset, gchar *add_string _U_, int string_len _U_) { tvbuff_t *tele_tvb; /* * dissect the embedded teleservice data */ tele_tvb = tvb_new_subset_length(tvb, offset, len); dissector_try_uint(tele_dissector_table, ansi_637_trans_tele_id, tele_tvb, pinfo, g_tree); } #define NUM_TRANS_PARAM (sizeof(ansi_trans_param_strings)/sizeof(value_string)) static gint ett_ansi_637_trans_param[NUM_TRANS_PARAM]; static void (*ansi_637_trans_param_fcn[])(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint len, guint32 offset, gchar *add_string, int string_len) = { trans_param_tele_id, /* Teleservice Identifier */ trans_param_srvc_cat, /* Service Category */ trans_param_address, /* Originating Address */ trans_param_subaddress, /* Originating Subaddress */ trans_param_address, /* Destination Address */ trans_param_subaddress, /* Destination Subaddress */ trans_param_bearer_reply_opt, /* Bearer Reply Option */ trans_param_cause_codes, /* Cause Codes */ trans_param_bearer_data, /* Bearer Data */ NULL, /* NONE */ }; #define NUM_TRANS_MSG_TYPE (sizeof(ansi_trans_msg_type_strings)/sizeof(value_string)) static gint ett_ansi_637_trans_msg[NUM_TRANS_MSG_TYPE]; /* GENERIC IS-637 DISSECTOR FUNCTIONS */ static gboolean dissect_ansi_637_tele_param(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 *offset, gboolean *has_private_data_p) { void (*param_fcn)(tvbuff_t *, packet_info *, proto_tree *, guint, guint32, gboolean *) = NULL; guint8 oct; guint8 len; guint32 curr_offset; gint ett_param_idx, idx; proto_tree *subtree; proto_item *item; const gchar *str = NULL; curr_offset = *offset; oct = tvb_get_guint8(tvb, curr_offset); str = try_val_to_str_idx_ext((guint32) oct, &ansi_tele_param_strings_ext, &idx); if (NULL == str) { return(FALSE); } ett_param_idx = ett_ansi_637_tele_param[idx]; param_fcn = ansi_637_tele_param_fcn[idx]; subtree = proto_tree_add_subtree(tree, tvb, curr_offset, -1, ett_param_idx, &item, str); proto_tree_add_uint(subtree, hf_ansi_637_tele_subparam_id, tvb, curr_offset, 1, oct); curr_offset += 1; len = tvb_get_guint8(tvb, curr_offset); proto_item_set_len(item, (curr_offset - *offset) + len + 1); proto_tree_add_uint(subtree, hf_ansi_637_tele_length, tvb, curr_offset, 1, len); curr_offset += 1; if (len > 0) { if (param_fcn == NULL) { proto_tree_add_expert(subtree, pinfo, &ei_ansi_637_no_tele_parameter_dissector, tvb, curr_offset, len); } else { /* * internal working (aka hack) for CMAS * * the 'User Data' subparameter is encoded in a special way for CMAS * (as per TIA-1149) * * if (Broadcast SMS && 'User Data') then call CMAS dissector */ if ((ansi_637_trans_tele_id == INTERNAL_BROADCAST_TELE_ID) && (oct == 0x01)) { param_fcn = tele_param_user_data_cmas; } (*param_fcn)(tvb, pinfo, subtree, len, curr_offset, has_private_data_p); } curr_offset += len; } *offset = curr_offset; return(TRUE); } static void dissect_ansi_637_tele_message(tvbuff_t *tvb, packet_info *pinfo, proto_tree *ansi_637_tree, gboolean *has_private_data_p) { guint8 len; guint32 curr_offset; curr_offset = 0; len = tvb_reported_length(tvb); while ((len - curr_offset) > 0) { if (!dissect_ansi_637_tele_param(tvb, pinfo, ansi_637_tree, &curr_offset, has_private_data_p)) { proto_tree_add_expert(ansi_637_tree, pinfo, &ei_ansi_637_unknown_tele_parameter, tvb, curr_offset, len - curr_offset); break; } } } static void dissect_ansi_637_tele(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_item *ansi_637_item; proto_tree *ansi_637_tree = NULL; const gchar *str = NULL; guint32 value; gboolean has_private_data = FALSE; col_set_str(pinfo->cinfo, COL_PROTOCOL, ansi_proto_name_short); /* In the interest of speed, if "tree" is NULL, don't do any work not * necessary to generate protocol tree items. */ if (tree) { g_tree = tree; value = pinfo->match_uint; /* * create the ansi_637 protocol tree */ str = try_val_to_str(value, ansi_tele_id_strings); if (NULL == str) { switch (value) { case 1: str = "Reserved for maintenance"; break; case 4102: str = "CDMA Service Category Programming Teleservice (SCPT)"; break; case 4103: str = "CDMA Card Application Toolkit Protocol Teleservice (CATPT)"; break; case 32513: str = "TDMA Cellular Messaging Teleservice"; break; case 32514: str = "TDMA Cellular Paging Teleservice (CPT-136)"; break; case 32515: str = "TDMA Over-the-Air Activation Teleservice (OATS)"; break; case 32520: str = "TDMA System Assisted Mobile Positioning through Satellite (SAMPS)"; break; case 32584: str = "TDMA Segmented System Assisted Mobile Positioning Service"; break; default: if ((value >= 2) && (value <= 4095)) { str = "Reserved for assignment by TIA-41"; } else if ((value >= 4104) && (value <= 4113)) { str = "Reserved for GSM1x Teleservice (CDMA)"; } else if ((value >= 4114) && (value <= 32512)) { str = "Reserved for assignment by TIA-41"; } else if ((value >= 32521) && (value <= 32575)) { str = "Reserved for assignment by this Standard for TDMA MS-based SMEs"; } else if ((value >= 49152) && (value <= 65535)) { str = "Reserved for carrier specific teleservices"; } else { str = "Unrecognized Teleservice ID"; } break; } } if (value == INTERNAL_BROADCAST_TELE_ID) { /* * supposed to be "Reserved for carrier specific teleservices" * but we are using it to key SMS Broadcast dissection where * there is no teleservice ID */ ansi_637_item = proto_tree_add_protocol_format(tree, proto_ansi_637_tele, tvb, 0, -1, "%s", ansi_proto_name_tele); } else { ansi_637_item = proto_tree_add_protocol_format(tree, proto_ansi_637_tele, tvb, 0, -1, "%s - %s (%u)", ansi_proto_name_tele, str, pinfo->match_uint); } ansi_637_tree = proto_item_add_subtree(ansi_637_item, ett_ansi_637_tele); dissect_ansi_637_tele_message(tvb, pinfo, ansi_637_tree, &has_private_data); } } static gboolean dissect_ansi_637_trans_param(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint32 *offset) { void (*param_fcn)(tvbuff_t *, packet_info *, proto_tree *, guint, guint32, gchar *, int) = NULL; guint8 oct; guint8 len; guint32 curr_offset; gint ett_param_idx, idx; proto_tree *subtree; proto_item *item; const gchar *str; curr_offset = *offset; oct = tvb_get_guint8(tvb, curr_offset); str = try_val_to_str_idx((guint32) oct, ansi_trans_param_strings, &idx); if (NULL == str) { return(FALSE); } ett_param_idx = ett_ansi_637_trans_param[idx]; param_fcn = ansi_637_trans_param_fcn[idx]; subtree = proto_tree_add_subtree(tree, tvb, curr_offset, -1, ett_param_idx, &item, str); proto_tree_add_uint(subtree, hf_ansi_637_trans_param_id, tvb, curr_offset, 1, oct); curr_offset += 1; len = tvb_get_guint8(tvb, curr_offset); proto_item_set_len(item, (curr_offset - *offset) + len + 1); proto_tree_add_uint(subtree, hf_ansi_637_trans_length, tvb, curr_offset, 1, len); curr_offset += 1; if (len > 0) { if (param_fcn == NULL) { proto_tree_add_expert(subtree, pinfo, &ei_ansi_637_no_trans_parameter_dissector, tvb, curr_offset, len); } else { gchar *ansi_637_add_string; ansi_637_add_string = (gchar *) wmem_alloc(wmem_packet_scope(), 1024); ansi_637_add_string[0] = '\0'; (*param_fcn)(tvb, pinfo, subtree, len, curr_offset, ansi_637_add_string, 1024); if (ansi_637_add_string[0] != '\0') { proto_item_append_text(item, "%s", ansi_637_add_string); } } curr_offset += len; } *offset = curr_offset; return(TRUE); } static void dissect_ansi_637_trans(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { proto_item *ansi_637_item; proto_tree *ansi_637_tree = NULL; guint32 curr_offset; gint idx; const gchar *str = NULL; guint8 oct; guint8 len; col_set_str(pinfo->cinfo, COL_PROTOCOL, ansi_proto_name_short); /* In the interest of speed, if "tree" is NULL, don't do any work not * necessary to generate protocol tree items. */ if (tree) { g_tree = tree; /* * reset the teleservice ID for each dissection */ ansi_637_trans_tele_id = 0; /* * create the ansi_637 protocol tree */ oct = tvb_get_guint8(tvb, 0); str = try_val_to_str_idx(oct, ansi_trans_msg_type_strings, &idx); if (NULL == str) { ansi_637_item = proto_tree_add_protocol_format(tree, proto_ansi_637_trans, tvb, 0, -1, "%s - Unrecognized Transport Layer Message Type (%u)", ansi_proto_name_trans, oct); ansi_637_tree = proto_item_add_subtree(ansi_637_item, ett_ansi_637_trans); } else { ansi_637_item = proto_tree_add_protocol_format(tree, proto_ansi_637_trans, tvb, 0, -1, "%s - %s", ansi_proto_name_trans, str); ansi_637_tree = proto_item_add_subtree(ansi_637_item, ett_ansi_637_trans_msg[idx]); if (oct == ANSI_TRANS_MSG_TYPE_BROADCAST) { /* * there is no teleservice ID for Broadcast but we want the * bearer data to be dissected * * using a reserved value to key dissector port */ ansi_637_trans_tele_id = INTERNAL_BROADCAST_TELE_ID; col_append_str(pinfo->cinfo, COL_INFO, "(BROADCAST)"); } } curr_offset = 1; len = tvb_reported_length(tvb); while ((len - curr_offset) > 0) { if (!dissect_ansi_637_trans_param(tvb, pinfo, ansi_637_tree, &curr_offset)) { proto_tree_add_expert(ansi_637_tree, pinfo, &ei_ansi_637_unknown_trans_parameter, tvb, curr_offset, len - curr_offset); break; } } } } /* Dissect SMS embedded in SIP */ static void dissect_ansi_637_trans_app(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) { col_set_str(pinfo->cinfo, COL_PROTOCOL, "/"); col_set_fence(pinfo->cinfo, COL_INFO); dissect_ansi_637_trans(tvb, pinfo, tree); } /* Register the protocol with Wireshark */ void proto_register_ansi_637(void) { guint i; /* Setup list of header fields */ static hf_register_info hf_trans[] = { { &hf_ansi_637_trans_param_id, { "Transport Param ID", "ansi_637_trans.param_id", FT_UINT8, BASE_DEC, VALS(ansi_trans_param_strings), 0, NULL, HFILL } }, { &hf_ansi_637_trans_length, { "Length", "ansi_637_trans.len", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_trans_bin_addr, { "Binary Address", "ansi_637_trans.bin_addr", FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_trans_tele_id, { "Teleservice ID", "ansi_637_trans.tele_id", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_trans_srvc_cat, { "Service Category", "ansi_637_trans.srvc_cat", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_digit_mode, { "Digit Mode", "ansi_637_trans.addr_param.digit_mode", FT_BOOLEAN, 8, TFS(&tfs_digit_mode_8bit_4bit), 0x80, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_number_mode, { "Number Mode", "ansi_637_trans.addr_param.number_mode", FT_BOOLEAN, 8, TFS(&tfs_number_mode_data_ansi_t1), 0x40, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_ton, { "Type of Number", "ansi_637_trans.addr_param.ton", FT_UINT8, BASE_DEC, NULL, 0x38, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_plan, { "Numbering Plan", "ansi_637_trans.addr_param.plan", FT_UINT16, BASE_DEC, VALS(ansi_a_ms_info_rec_num_plan_vals), 0x0780, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_num_fields, { "Number of fields", "ansi_637_trans.addr_param.num_fields", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL } }, { &hf_ansi_637_trans_addr_param_number, { "Number", "ansi_637_trans.addr_param.number", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_trans_subaddr_type, { "Type", "ansi_637_trans.subaddr.type", FT_UINT16, BASE_DEC, NULL, 0xe000, NULL, HFILL } }, { &hf_ansi_637_trans_subaddr_odd_even_ind, { "Odd/Even Indicator", "ansi_637_trans.subaddr.odd_even_ind", FT_UINT16, BASE_DEC, VALS(ansi_trans_subaddr_odd_even_ind_strings), 0x1000, NULL, HFILL } }, { &hf_ansi_637_trans_subaddr_num_fields, { "Number of fields", "ansi_637_trans.subaddr.num_fields", FT_UINT16, BASE_DEC, NULL, 0x0ff0, NULL, HFILL } }, { &hf_ansi_637_trans_bearer_reply_seq_num, { "Reply Sequence Number", "ansi_637_trans.bearer_reply.seq_num", FT_UINT8, BASE_DEC, NULL, 0xfc, NULL, HFILL } }, { &hf_ansi_637_trans_cause_codes_seq_num, { "Reply Sequence Number", "ansi_637_trans.cause_codes.seq_num", FT_UINT8, BASE_DEC, NULL, 0xfc, NULL, HFILL } }, { &hf_ansi_637_trans_cause_codes_error_class, { "Error Class", "ansi_637_trans.cause_codes.error_class", FT_UINT8, BASE_DEC, VALS(trans_param_cause_codes_error_class_strings), 0x03, NULL, HFILL } }, { &hf_ansi_637_trans_cause_codes_code, { "Cause Code", "ansi_637_trans.cause_codes.code", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } } }; static hf_register_info hf_tele[] = { { &hf_ansi_637_tele_msg_type, { "Message Type", "ansi_637_tele.msg_type", FT_UINT24, BASE_DEC, VALS(ansi_tele_msg_type_strings), 0xf00000, NULL, HFILL } }, { &hf_ansi_637_tele_msg_id, { "Message ID", "ansi_637_tele.msg_id", FT_UINT24, BASE_DEC, NULL, 0x0ffff0, NULL, HFILL } }, { &hf_ansi_637_tele_length, { "Length", "ansi_637_tele.len", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_status, { "Message Status", "ansi_637_tele.msg_status", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &ansi_tele_msg_status_strings_ext, 0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_header_ind, { "Header Indicator", "ansi_637_tele.msg_header_ind", FT_UINT24, BASE_DEC, VALS(ansi_tele_msg_header_ind_strings), 0x000008, NULL, HFILL } }, { &hf_ansi_637_tele_msg_rsvd, { "Reserved", "ansi_637_tele.msg_rsvd", FT_UINT24, BASE_DEC, NULL, 0x000007, NULL, HFILL } }, { &hf_ansi_637_tele_subparam_id, { "Teleservice Subparam ID", "ansi_637_tele.subparam_id", FT_UINT8, BASE_DEC | BASE_EXT_STRING, &ansi_tele_param_strings_ext, 0, NULL, HFILL } }, { &hf_ansi_637_tele_user_data_text, { "Encoded user data", "ansi_637_tele.user_data.text", FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_user_data_encoding, { "Encoding", "ansi_637_tele.user_data.encoding", FT_UINT16, BASE_DEC, NULL, 0xf800, NULL, HFILL } }, { &hf_ansi_637_tele_user_data_message_type, { "Message Type (see TIA/EIA/IS-91)", "ansi_637_tele.user_data.message_type", FT_UINT16, BASE_DEC, NULL, 0x07f8, NULL, HFILL } }, { &hf_ansi_637_tele_user_data_num_fields, { "Number of fields", "ansi_637_tele.user_data.num_fields", FT_UINT16, BASE_DEC, NULL, 0x07f8, NULL, HFILL } }, { &hf_ansi_637_tele_response_code, { "Response Code", "ansi_637_tele.response_code", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_year, { "Timestamp (Year)", "ansi_637_tele.message_center_ts.year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_month, { "Timestamp (Month)", "ansi_637_tele.message_center_ts.month", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_day, { "Timestamp (Day)", "ansi_637_tele.message_center_ts.day", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_hours, { "Timestamp (Hours)", "ansi_637_tele.message_center_ts.hours", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_minutes, { "Timestamp (Minutes)", "ansi_637_tele.message_center_ts.minutes", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_message_center_ts_seconds, { "Timestamp (Seconds)", "ansi_637_tele.message_center_ts.seconds", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_year, { "Timestamp (Year)", "ansi_637_tele.validity_period_ts.year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_month, { "Timestamp (Month)", "ansi_637_tele.validity_period_ts.month", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_day, { "Timestamp (Day)", "ansi_637_tele.validity_period_ts.day", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_hours, { "Timestamp (Hours)", "ansi_637_tele.validity_period_ts.hours", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_minutes, { "Timestamp (Minutes)", "ansi_637_tele.validity_period_ts.minutes", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_ts_seconds, { "Timestamp (Seconds)", "ansi_637_tele.validity_period_ts.seconds", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_validity_period_relative_validity, { "Validity", "ansi_637_tele.validity_period_relative.validity", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_year, { "Timestamp (Year)", "ansi_637_tele.deferred_del_ts.year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_month, { "Timestamp (Month)", "ansi_637_tele.deferred_del_ts.month", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_day, { "Timestamp (Day)", "ansi_637_tele.deferred_del_ts.day", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_hours, { "Timestamp (Hours)", "ansi_637_tele.deferred_del_ts.hours", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_minutes, { "Timestamp (Minutes)", "ansi_637_tele.deferred_del_ts.minutes", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_ts_seconds, { "Timestamp (Seconds)", "ansi_637_tele.deferred_del_ts.seconds", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_deferred_del_relative, { "Delivery Time", "ansi_637_tele.deferred_del.relative", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_priority_indicator, { "Priority", "ansi_637_tele.priority_indicator", FT_UINT8, BASE_DEC, VALS(tele_param_priority_ind_strings), 0xc0, NULL, HFILL } }, { &hf_ansi_637_tele_privacy_indicator, { "Privacy", "ansi_637_tele.privacy_indicator", FT_UINT8, BASE_DEC, VALS(tele_param_privacy_ind_strings), 0xc0, NULL, HFILL } }, { &hf_ansi_637_tele_reply_option_user_ack_req, { "User Acknowledgement Requested", "ansi_637_tele.reply_option.user_ack_req", FT_BOOLEAN, 8, TFS(&tfs_yes_no), 0x80, NULL, HFILL } }, { &hf_ansi_637_tele_reply_option_dak_req, { "Delivery Acknowledgement Requested", "ansi_637_tele.reply_option.dak_req", FT_BOOLEAN, 8, TFS(&tfs_yes_no), 0x40, NULL, HFILL } }, { &hf_ansi_637_tele_reply_option_read_ack_req, { "Read Acknowledgement Requested", "ansi_637_tele.reply_option.read_ack_req", FT_BOOLEAN, 8, TFS(&tfs_yes_no), 0x20, NULL, HFILL } }, { &hf_ansi_637_tele_reply_option_report_req, { "Delivery/Submit Report Requested", "ansi_637_tele.reply_option.report_req", FT_BOOLEAN, 8, TFS(&tfs_yes_no), 0x10, NULL, HFILL } }, { &hf_ansi_637_tele_num_messages, { "Number of voice mail messages", "ansi_637_tele.num_messages.count", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_alert_msg_delivery_priority, { "Privacy", "ansi_637_tele.alert_msg_delivery.priority", FT_UINT8, BASE_DEC, VALS(tele_param_alert_priority_strings), 0xc0, NULL, HFILL } }, { &hf_ansi_637_tele_language, { "Language", "ansi_637_tele.language", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_digit_mode, { "Digit Mode", "ansi_637_tele.cb_num.digit_mode", FT_BOOLEAN, 8, TFS(&tfs_digit_mode_8bit_4bit), 0x80, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_ton, { "Type of Number", "ansi_637_tele.cb_num.ton", FT_UINT8, BASE_DEC, VALS(ansi_a_ms_info_rec_num_type_vals), 0x70, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_plan, { "Numbering Plan", "ansi_637_tele.cb_num.plan", FT_UINT8, BASE_DEC, VALS(ansi_a_ms_info_rec_num_plan_vals), 0x0f, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_num_fields, { "Number of fields", "ansi_637_tele.cb_num.num_fields", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_num_fields07f8, { "Number of fields", "ansi_637_tele.cb_num.num_fields", FT_UINT8, BASE_DEC, NULL, 0x07F8, NULL, HFILL } }, { &hf_ansi_637_tele_cb_num_number, { "Call-Back Number", "ansi_637_tele.cb_num.number", FT_STRING, BASE_NONE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_display_mode, { "Message Display Mode", "ansi_637_tele.msg_display_mode", FT_UINT8, BASE_DEC, VALS(tele_param_msg_display_mode_strings), 0xc0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_deposit_idx, { "Message Deposit Index", "ansi_637_tele.msg_deposit_idx", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_results_srvc_cat, { "Service Category", "ansi_637_tele.srvc_cat_prog_results.srvc_cat", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_results_result, { "Programming Result", "ansi_637_tele.srvc_cat_prog_results.result", FT_UINT8, BASE_DEC, VALS(tele_param_srvc_cat_prog_results_result_strings), 0xf0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_status_error_class, { "Error Class", "ansi_637_tele.msg_status.error_class", FT_UINT8, BASE_DEC, VALS(tele_param_msg_status_error_class_strings), 0xc0, NULL, HFILL } }, { &hf_ansi_637_tele_msg_status_code, { "Message Status Code", "ansi_637_tele.msg_status.code", FT_UINT8, BASE_DEC, NULL, 0x3f, NULL, HFILL } }, { &hf_ansi_637_tele_tp_failure_cause_value, { "GSM SMS TP-Failure Cause", "ansi_637_tele.tp_failure_cause.value", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_generic, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_03, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0x03, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_07, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0x07, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_0f, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0x0f, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_3f, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0x3f, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_8_7f, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT8, BASE_DEC, NULL, 0x7f, NULL, HFILL } }, { &hf_ansi_637_reserved_bits_16_generic, { "Reserved bit(s)", "ansi_637_tele.reserved", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_encoding, { "Encoding", "ansi_637_tele.cmas.encoding", FT_UINT16, BASE_DEC, NULL, 0xf800, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_num_fields, { "Number of fields", "ansi_637_tele.cmas.num_fields", FT_UINT16, BASE_DEC, NULL, 0x07f8, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_protocol_version, { "CMAE_protocol_version", "ansi_637_tele.cmas.protocol_version", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_record_type, { "E_RECORD_TYPE", "ansi_637_tele.cmas.record_type", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_record_len, { "E_RECORD_LENGTH", "ansi_637_tele.cmas.record_len", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_char_set, { "CMAE_char_set", "ansi_637_tele.cmas.char_set", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_category, { "CMAE_category", "ansi_637_tele.cmas.category", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_response_type, { "CMAE_response_type", "ansi_637_tele.cmas.response_type", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_severity, { "CMAE_severity", "ansi_637_tele.cmas.severity", FT_UINT8, BASE_DEC, NULL, 0xf0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_urgency, { "CMAE_urgency", "ansi_637_tele.cmas.urgency", FT_UINT8, BASE_DEC, NULL, 0x0f, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_certainty, { "CMAE_certainty", "ansi_637_tele.cmas.certainty", FT_UINT8, BASE_DEC, NULL, 0xf0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_identifier, { "CMAE_identifier", "ansi_637_tele.cmas.identifier", FT_UINT16, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_alert_handling, { "CMAE_alert_handling", "ansi_637_tele.cmas.alert_handling", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_year, { "CMAE_expires (Year)", "ansi_637_tele.cmas.expires.year", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_month, { "CMAE_expires (Month)", "ansi_637_tele.cmas.expires.month", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_day, { "CMAE_expires (Day)", "ansi_637_tele.cmas.expires.day", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_hours, { "CMAE_expires (Hours)", "ansi_637_tele.cmas.expires.hours", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_minutes, { "CMAE_expires (Minutes)", "ansi_637_tele.cmas.expires.minutes", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_expires_seconds, { "CMAE_expires (Seconds)", "ansi_637_tele.cmas.expires.seconds", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_language, { "CMAE_language", "ansi_637_tele.cmas.language", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_cmas_text, { "CMAE_alert_text", "ansi_637_tele.cmas.text", FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_mult_enc_user_data_encoding, { "Encoding", "ansi_637_tele.mult_enc_user_data.encoding", FT_UINT8, BASE_DEC, VALS(ansi_tsb58_encoding_vals), 0, NULL, HFILL } }, { &hf_ansi_637_tele_mult_enc_user_data_num_fields, { "Number of fields", "ansi_637_tele.mult_enc_user_data.num_fields", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_mult_enc_user_data_text, { "Encoded user data", "ansi_637_tele.mult_enc_user_data.text", FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_encoding, { "Encoding", "ansi_637_tele.srvc_cat_prog_data.encoding", FT_UINT8, BASE_DEC, VALS(ansi_tsb58_encoding_vals), 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_operation_code, { "Operation code", "ansi_637_tele.srvc_cat_prog_data.operation_code", FT_UINT8, BASE_DEC, VALS(tele_param_srvc_cat_prog_data_op_code_vals), 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_category, { "Operation code", "ansi_637_tele.srvc_cat_prog_data.category", FT_UINT16, BASE_DEC|BASE_EXT_STRING, &ansi_tsb58_srvc_cat_vals_ext, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_language, { "Operation code", "ansi_637_tele.srvc_cat_prog_data.language", FT_UINT8, BASE_DEC|BASE_EXT_STRING, &ansi_tsb58_language_ind_vals_ext, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_max_messages, { "Maximum number of messages", "ansi_637_tele.srvc_cat_prog_data.max_messages", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_alert_option, { "Alert option", "ansi_637_tele.srvc_cat_prog_data.alert_option", FT_UINT8, BASE_DEC, VALS(tele_param_srvc_cat_prog_data_alert_option_vals), 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_num_fields, { "Number of fields", "ansi_637_tele.srvc_cat_prog_data.num_fields", FT_UINT8, BASE_DEC, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_tele_srvc_cat_prog_data_text, { "Encoded program data", "ansi_637_tele.srvc_cat_prog_data.text", FT_STRING, STR_UNICODE, NULL, 0, NULL, HFILL } }, { &hf_ansi_637_msb_first_field, { "Most significant bits of first field", "ansi_637_tele.msb_first_field", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, { &hf_ansi_637_lsb_last_field, { "Least significant bits of last field", "ansi_637_tele.lsb_last_field", FT_UINT8, BASE_HEX, NULL, 0x0, NULL, HFILL } }, }; static ei_register_info ei[] = { { &ei_ansi_637_extraneous_data, { "ansi_637.extraneous_data", PI_PROTOCOL, PI_NOTE, "Extraneous Data - try checking decoder variant preference or dissector bug/later version spec (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_short_data, { "ansi_637.short_data", PI_PROTOCOL, PI_NOTE, "Short Data (?) - try checking decoder variant preference or dissector bug/later version spec (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_unexpected_length, { "ansi_637.unexpected_length", PI_PROTOCOL, PI_WARN, "Unexpected Data Length - try checking decoder variant preference or dissector bug/later version spec (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_unknown_encoding, { "ansi_637.unknown_format", PI_PROTOCOL, PI_NOTE, "Encoding Unknown/Unsupported - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_failed_conversion, { "ansi_637.failed_conversion", PI_PROTOCOL, PI_WARN, "Failed iconv conversion - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_unknown_cmas_record_type, { "ansi_637.unknown_cmas_record_type", PI_PROTOCOL, PI_WARN, "Unknown CMAS record type - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_unknown_trans_parameter, { "ansi_637.unknown_trans_parameter", PI_PROTOCOL, PI_WARN, "Unknown transport layer parameter - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_no_trans_parameter_dissector, { "ansi_637.no_trans_parameter_dissector", PI_PROTOCOL, PI_WARN, "No transport layer parameter dissector - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_unknown_tele_parameter, { "ansi_637.unknown_tele_parameter", PI_PROTOCOL, PI_WARN, "Unknown teleservice layer parameter - (report to wireshark.org)", EXPFILL } }, { &ei_ansi_637_no_tele_parameter_dissector, { "ansi_637.no_tele_parameter_dissector", PI_PROTOCOL, PI_WARN, "No teleservice layer parameter dissector - (report to wireshark.org)", EXPFILL } } }; expert_module_t *expert_ansi_637; /* Setup protocol subtree array */ #define NUM_INDIVIDUAL_PARAMS 4 gint *ett[NUM_INDIVIDUAL_PARAMS+NUM_TELE_PARAM+NUM_TRANS_MSG_TYPE+NUM_TRANS_PARAM+NUM_CMAS_PARAM]; memset((void *) ett, 0, sizeof(ett)); ett[0] = &ett_ansi_637_tele; ett[1] = &ett_ansi_637_trans; ett[2] = &ett_ansi_637_header_ind; ett[3] = &ett_params; for (i=0; i < NUM_TELE_PARAM; i++) { ett_ansi_637_tele_param[i] = -1; ett[NUM_INDIVIDUAL_PARAMS+i] = &ett_ansi_637_tele_param[i]; } for (i=0; i < NUM_TRANS_MSG_TYPE; i++) { ett_ansi_637_trans_msg[i] = -1; ett[NUM_INDIVIDUAL_PARAMS+NUM_TELE_PARAM+i] = &ett_ansi_637_trans_msg[i]; } for (i=0; i < NUM_TRANS_PARAM; i++) { ett_ansi_637_trans_param[i] = -1; ett[NUM_INDIVIDUAL_PARAMS+NUM_TELE_PARAM+NUM_TRANS_MSG_TYPE+i] = &ett_ansi_637_trans_param[i]; } for (i=0; i < NUM_CMAS_PARAM; i++) { ett_tia_1149_cmas_param[i] = -1; ett[NUM_INDIVIDUAL_PARAMS+NUM_TELE_PARAM+NUM_TRANS_MSG_TYPE+NUM_TRANS_PARAM+i] = &ett_tia_1149_cmas_param[i]; } /* Register the protocol name and description */ proto_ansi_637_tele = proto_register_protocol(ansi_proto_name_tele, "ANSI IS-637-A Teleservice", "ansi_637_tele"); proto_ansi_637_trans = proto_register_protocol(ansi_proto_name_trans, "ANSI IS-637-A Transport", "ansi_637_trans"); ansi_637_tele_handle = register_dissector("ansi_637_tele", dissect_ansi_637_tele, proto_ansi_637_tele); ansi_637_trans_handle = register_dissector("ansi_637_trans", dissect_ansi_637_trans, proto_ansi_637_trans); /* Required function calls to register the header fields and subtrees used */ proto_register_field_array(proto_ansi_637_tele, hf_tele, array_length(hf_tele)); proto_register_field_array(proto_ansi_637_trans, hf_trans, array_length(hf_trans)); proto_register_subtree_array(ett, array_length(ett)); expert_ansi_637 = expert_register_protocol(proto_ansi_637_trans); expert_register_field_array(expert_ansi_637, ei, array_length(ei)); tele_dissector_table = register_dissector_table("ansi_637.tele_id", "ANSI IS-637-A Teleservice ID", FT_UINT8, BASE_DEC); } void proto_reg_handoff_ansi_637(void) { dissector_handle_t ansi_637_trans_app_handle; guint i; ansi_637_trans_app_handle = create_dissector_handle(dissect_ansi_637_trans_app, proto_ansi_637_trans); /* Dissect messages embedded in SIP */ dissector_add_string("media_type", "application/vnd.3gpp2.sms", ansi_637_trans_app_handle); /* * register for all known teleservices * '-1' is to stop before trailing '0' entry * * to add teleservices, modify 'ansi_tele_id_strings' */ for (i=0; i < ((sizeof(ansi_tele_id_strings)/sizeof(value_string))-1); i++) { /* * ANSI MAP dissector will push out teleservice ids */ dissector_add_uint("ansi_map.tele_id", ansi_tele_id_strings[i].value, ansi_637_tele_handle); /* * we will push out teleservice ids after Transport layer decode */ dissector_add_uint("ansi_637.tele_id", ansi_tele_id_strings[i].value, ansi_637_tele_handle); } /* * internal implementation add this pseudo teleservice ID for handling broadcast SMS * (which don't have teleservice IDs) */ dissector_add_uint("ansi_map.tele_id", INTERNAL_BROADCAST_TELE_ID, ansi_637_tele_handle); dissector_add_uint("ansi_637.tele_id", INTERNAL_BROADCAST_TELE_ID, ansi_637_tele_handle); /* * ANSI A-interface will push out transport layer data */ dissector_add_uint("ansi_a.sms", 0, ansi_637_trans_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 4 * tab-width: 8 * indent-tabs-mode: nil * End: * * vi: set shiftwidth=4 tabstop=8 expandtab: * :indentSize=4:tabSize=8:noTabs=true: */
658243.c
#ifndef DDEBUG #define DDEBUG 0 #endif #include "ddebug.h" /* * Copyright (C) Zhang "agentzh" Yichun */ #include "ngx_http_srcache_filter_module.h" #include "ngx_http_srcache_util.h" #include "ngx_http_srcache_var.h" #include "ngx_http_srcache_fetch.h" #include "ngx_http_srcache_store.h" #include "ngx_http_srcache_headers.h" unsigned ngx_http_srcache_used; static ngx_int_t ngx_http_srcache_pre_config(ngx_conf_t *cf); static void *ngx_http_srcache_create_loc_conf(ngx_conf_t *cf); static char *ngx_http_srcache_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child); static ngx_int_t ngx_http_srcache_post_config(ngx_conf_t *cf); static char *ngx_http_srcache_conf_set_request(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static void * ngx_http_srcache_create_main_conf(ngx_conf_t *cf); static char *ngx_http_srcache_init_main_conf(ngx_conf_t *cf, void *conf); static char * ngx_http_srcache_store_statuses(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static ngx_str_t ngx_http_srcache_hide_headers[] = { ngx_string("Connection"), ngx_string("Keep-Alive"), ngx_string("Proxy-Authenticate"), ngx_string("Proxy-Authorization"), ngx_string("TE"), ngx_string("Trailers"), ngx_string("Transfer-Encoding"), ngx_string("Upgrade"), ngx_string("Set-Cookie"), ngx_null_string }; static ngx_conf_bitmask_t ngx_http_srcache_cache_method_mask[] = { { ngx_string("GET"), NGX_HTTP_GET}, { ngx_string("HEAD"), NGX_HTTP_HEAD }, { ngx_string("POST"), NGX_HTTP_POST }, { ngx_string("PUT"), NGX_HTTP_PUT }, { ngx_string("DELETE"), NGX_HTTP_DELETE }, { ngx_null_string, 0 } }; static ngx_command_t ngx_http_srcache_commands[] = { { ngx_string("srcache_buffer"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, buf_size), NULL }, { ngx_string("srcache_fetch"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE23, ngx_http_srcache_conf_set_request, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, fetch), NULL }, { ngx_string("srcache_store"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE23, ngx_http_srcache_conf_set_request, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store), NULL }, { ngx_string("srcache_store_max_size"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store_max_size), NULL }, { ngx_string("srcache_fetch_skip"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE1, ngx_http_set_complex_value_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, fetch_skip), NULL }, { ngx_string("srcache_store_skip"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_TAKE1, ngx_http_set_complex_value_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store_skip), NULL }, { ngx_string("srcache_store_statuses"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_HTTP_LIF_CONF |NGX_CONF_1MORE, ngx_http_srcache_store_statuses, NGX_HTTP_LOC_CONF_OFFSET, 0, NULL }, { ngx_string("srcache_methods"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE, ngx_conf_set_bitmask_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, cache_methods), &ngx_http_srcache_cache_method_mask }, { ngx_string("srcache_request_cache_control"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, req_cache_control), NULL }, { ngx_string("srcache_store_private"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store_private), NULL }, { ngx_string("srcache_store_no_store"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store_no_store), NULL }, { ngx_string("srcache_store_no_cache"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, store_no_cache), NULL }, { ngx_string("srcache_response_cache_control"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, resp_cache_control), NULL }, { ngx_string("srcache_store_hide_header"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_str_array_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, hide_headers), NULL }, { ngx_string("srcache_store_pass_header"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_TAKE1, ngx_conf_set_str_array_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, pass_headers), NULL }, { ngx_string("srcache_ignore_content_encoding"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_FLAG, ngx_conf_set_flag_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, ignore_content_encoding), NULL }, { ngx_string("srcache_header_buffer_size"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF |NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, ngx_conf_set_size_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, header_buf_size), NULL }, { ngx_string("srcache_max_expire"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF |NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, ngx_conf_set_sec_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, max_expire), NULL }, { ngx_string("srcache_default_expire"), NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF |NGX_HTTP_LIF_CONF|NGX_CONF_TAKE1, ngx_conf_set_sec_slot, NGX_HTTP_LOC_CONF_OFFSET, offsetof(ngx_http_srcache_loc_conf_t, default_expire), NULL }, ngx_null_command }; static ngx_http_module_t ngx_http_srcache_filter_module_ctx = { ngx_http_srcache_pre_config, /* preconfiguration */ ngx_http_srcache_post_config, /* postconfiguration */ ngx_http_srcache_create_main_conf, /* create main configuration */ ngx_http_srcache_init_main_conf, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ ngx_http_srcache_create_loc_conf, /* create location configuration */ ngx_http_srcache_merge_loc_conf /* merge location configuration */ }; ngx_module_t ngx_http_srcache_filter_module = { NGX_MODULE_V1, &ngx_http_srcache_filter_module_ctx, /* module context */ ngx_http_srcache_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_int_t ngx_http_srcache_pre_config(ngx_conf_t *cf) { #if 1 ngx_http_srcache_used = 0; #endif return NGX_OK; } static void * ngx_http_srcache_create_loc_conf(ngx_conf_t *cf) { ngx_http_srcache_loc_conf_t *conf; conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_srcache_loc_conf_t)); if (conf == NULL) { return NULL; } /* * set by ngx_pcalloc(): * * conf->fetch_skip = NULL; * conf->store_skip = NULL; * conf->cache_methods = 0; * conf->hide_headers_hash = { NULL, 0 }; * conf->skip_content_type = 0; * conf->store_statuses = NULL; */ conf->fetch = NGX_CONF_UNSET_PTR; conf->store = NGX_CONF_UNSET_PTR; conf->buf_size = NGX_CONF_UNSET_SIZE; conf->store_max_size = NGX_CONF_UNSET_SIZE; conf->header_buf_size = NGX_CONF_UNSET_SIZE; conf->req_cache_control = NGX_CONF_UNSET; conf->resp_cache_control = NGX_CONF_UNSET; conf->store_private = NGX_CONF_UNSET; conf->store_no_store = NGX_CONF_UNSET; conf->store_no_cache = NGX_CONF_UNSET; conf->max_expire = NGX_CONF_UNSET; conf->default_expire = NGX_CONF_UNSET; conf->ignore_content_encoding = NGX_CONF_UNSET; conf->hide_headers = NGX_CONF_UNSET_PTR; conf->pass_headers = NGX_CONF_UNSET_PTR; return conf; } static char * ngx_http_srcache_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child) { ngx_http_srcache_loc_conf_t *prev = parent; ngx_http_srcache_loc_conf_t *conf = child; ngx_hash_init_t hash; ngx_conf_merge_ptr_value(conf->fetch, prev->fetch, NULL); ngx_conf_merge_ptr_value(conf->store, prev->store, NULL); ngx_conf_merge_size_value(conf->buf_size, prev->buf_size, (size_t) ngx_pagesize); ngx_conf_merge_size_value(conf->store_max_size, prev->store_max_size, 0); ngx_conf_merge_size_value(conf->header_buf_size, prev->header_buf_size, (size_t) ngx_pagesize); if (conf->fetch_skip == NULL) { conf->fetch_skip = prev->fetch_skip; } if (conf->store_skip == NULL) { conf->store_skip = prev->store_skip; } if (conf->store_statuses == NULL) { conf->store_statuses = prev->store_statuses; } if (conf->cache_methods == 0) { conf->cache_methods = prev->cache_methods; } conf->cache_methods |= NGX_HTTP_GET|NGX_HTTP_HEAD; ngx_conf_merge_value(conf->req_cache_control, prev->req_cache_control, 0); ngx_conf_merge_value(conf->resp_cache_control, prev->resp_cache_control, 1); ngx_conf_merge_value(conf->store_private, prev->store_private, 0); ngx_conf_merge_value(conf->store_no_store, prev->store_no_store, 0); ngx_conf_merge_value(conf->store_no_cache, prev->store_no_cache, 0); ngx_conf_merge_value(conf->max_expire, prev->max_expire, 0); ngx_conf_merge_value(conf->default_expire, prev->default_expire, 60); ngx_conf_merge_value(conf->ignore_content_encoding, prev->ignore_content_encoding, 0); hash.max_size = 512; hash.bucket_size = ngx_align(64, ngx_cacheline_size); hash.name = "srcache_store_hide_headers_hash"; if (ngx_http_srcache_hide_headers_hash(cf, conf, prev, ngx_http_srcache_hide_headers, &hash) != NGX_OK) { return NGX_CONF_ERROR; } return NGX_CONF_OK; } static char * ngx_http_srcache_conf_set_request(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { char *p = conf; ngx_http_srcache_request_t **rpp; ngx_http_srcache_request_t *rp; ngx_str_t *value; ngx_str_t *method_name; ngx_http_compile_complex_value_t ccv; rpp = (ngx_http_srcache_request_t **) (p + cmd->offset); if (*rpp != NGX_CONF_UNSET_PTR) { return "is duplicate"; } ngx_http_srcache_used = 1; value = cf->args->elts; *rpp = ngx_pcalloc(cf->pool, sizeof(ngx_http_srcache_request_t)); if (*rpp == NULL) { return NGX_CONF_ERROR; } rp = *rpp; method_name = &value[1]; rp->method = ngx_http_srcache_parse_method_name(&method_name); if (rp->method == NGX_HTTP_UNKNOWN) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V specifies bad HTTP method %V", &cmd->name, method_name); return NGX_CONF_ERROR; } rp->method_name = *method_name; /* compile the location arg */ if (value[2].len == 0) { ngx_memzero(&rp->location, sizeof(ngx_http_complex_value_t)); } else { ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t)); ccv.cf = cf; ccv.value = &value[2]; ccv.complex_value = &rp->location; if (ngx_http_compile_complex_value(&ccv) != NGX_OK) { return NGX_CONF_ERROR; } } if (cf->args->nelts == 2 + 1) { return NGX_CONF_OK; } /* compile the args arg */ if (value[3].len == 0) { ngx_memzero(&rp->location, sizeof(ngx_http_complex_value_t)); return NGX_CONF_OK; } ngx_memzero(&ccv, sizeof(ngx_http_compile_complex_value_t)); ccv.cf = cf; ccv.value = &value[3]; ccv.complex_value = &rp->args; if (ngx_http_compile_complex_value(&ccv) != NGX_OK) { return NGX_CONF_ERROR; } return NGX_CONF_OK; } static void * ngx_http_srcache_create_main_conf(ngx_conf_t *cf) { ngx_http_srcache_main_conf_t *smcf; smcf = ngx_pcalloc(cf->pool, sizeof(ngx_http_srcache_main_conf_t)); if (smcf == NULL) { return NULL; } /* set by ngx_pcalloc: * smcf->postponed_to_access_phase_end = 0; * smcf->headers_in_hash = { NULL, 0 }; */ return smcf; } static char * ngx_http_srcache_init_main_conf(ngx_conf_t *cf, void *conf) { ngx_http_srcache_main_conf_t *smcf = conf; ngx_array_t headers_in; ngx_hash_key_t *hk; ngx_hash_init_t hash; ngx_http_srcache_header_t *header; /* srcache_headers_in_hash */ if (ngx_array_init(&headers_in, cf->temp_pool, 32, sizeof(ngx_hash_key_t)) != NGX_OK) { return NGX_CONF_ERROR; } for (header = ngx_http_srcache_headers_in; header->name.len; header++) { hk = ngx_array_push(&headers_in); if (hk == NULL) { return NGX_CONF_ERROR; } hk->key = header->name; hk->key_hash = ngx_hash_key_lc(header->name.data, header->name.len); hk->value = header; } hash.hash = &smcf->headers_in_hash; hash.key = ngx_hash_key_lc; hash.max_size = 512; hash.bucket_size = ngx_align(64, ngx_cacheline_size); hash.name = "srcache_headers_in_hash"; hash.pool = cf->pool; hash.temp_pool = NULL; if (ngx_hash_init(&hash, headers_in.elts, headers_in.nelts) != NGX_OK) { return NGX_CONF_ERROR; } return NGX_CONF_OK; } static ngx_int_t ngx_http_srcache_post_config(ngx_conf_t *cf) { ngx_int_t rc; ngx_http_handler_pt *h; ngx_http_core_main_conf_t *cmcf; rc = ngx_http_srcache_add_variables(cf); if (rc != NGX_OK) { return rc; } if (ngx_http_srcache_used) { dd("using ngx-srcache"); /* register our output filters */ rc = ngx_http_srcache_filter_init(cf); if (rc != NGX_OK) { return rc; } cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module); /* register our access phase handler */ h = ngx_array_push(&cmcf->phases[NGX_HTTP_ACCESS_PHASE].handlers); if (h == NULL) { return NGX_ERROR; } *h = ngx_http_srcache_access_handler; } return NGX_OK; } static char * ngx_http_srcache_store_statuses(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_srcache_loc_conf_t *slcf = conf; ngx_uint_t i, n; ngx_int_t status; ngx_str_t *value; value = cf->args->elts; if (slcf->store_statuses) { return "is duplicate"; } n = cf->args->nelts - 1; slcf->store_statuses = ngx_pnalloc(cf->pool, (n + 1) * sizeof(ngx_int_t)); if (slcf->store_statuses == NULL) { return NGX_CONF_ERROR; } for (i = 1; i <= n; i++) { status = ngx_atoi(value[i].data, value[i].len); if (status == NGX_ERROR) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "status code \"%V\" is an invalid number", &value[i]); return NGX_CONF_ERROR; } if (status < 0) { ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "status code \"%V\" is not a positive number", &value[i]); return NGX_CONF_ERROR; } slcf->store_statuses[i - 1] = status; } slcf->store_statuses[i - 1] = 0; ngx_sort(slcf->store_statuses, n, sizeof(ngx_int_t), ngx_http_srcache_cmp_int); #if 0 for (i = 0; i < n; i++) { dd("status: %d", (int) slcf->store_statuses[i]); } #endif return NGX_CONF_OK; }
359996.c
/* * Test harness for bhyve instruction emulator */ #include <sys/types.h> #include <sys/errno.h> #include <assert.h> #include <stdio.h> #include <string.h> #include "vmm_stubs.h" static uint64_t vm_regs[VM_REG_LAST]; struct mem_cell { uint64_t addr; uint64_t val; }; int vm_get_register(void *ctx, int vcpu, int reg, uint64_t *retval) { if (reg >= VM_REG_GUEST_RAX && reg < VM_REG_LAST) { *retval = vm_regs[reg]; return (0); } return (EINVAL); } int vm_set_register(void *ctx, int vcpu, int reg, uint64_t val) { if (reg >= VM_REG_GUEST_RAX && reg < VM_REG_LAST) { vm_regs[reg] = reg; return (0); } return (EINVAL); } /* * Memory r/w callback functions */ int test_mread(void *vm, int cpuid, uint64_t gpa, uint64_t *rval, int rsize, void *arg) { struct mem_cell *mc; mc = arg; if (mc->addr == gpa) { *rval = mc->val; return (0); } return (EINVAL); } int test_mwrite(void *vm, int cpuid, uint64_t gpa, uint64_t wval, int wsize, void *arg) { struct mem_cell *mc; mc = arg; if (mc->addr == gpa) { mc->val = wval; return (0); } return (EINVAL); } void panic(char *str, ...) { printf("panic: %s\n", str); } main() { struct mem_cell mc; struct vie vie; uint64_t gla, gpa; int err; /* * ICLASS: AND CATEGORY: LOGICAL EXTENSION: BASE IFORM: AND_GPRv_MEMv ISA_SET: I86 * SHORT: and eax, dword ptr [ecx+0xf0] AND r16/32, r/m16/32 * (rcx = lapic address, 0xff000000) * and 0xf0(%rcx),%eax * 0x23 0x81 0xf0 0x00 0x00 0x00 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x23; vie.inst[1] = 0x81; vie.inst[2] = 0xf0; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0x00; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000aa00; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); /* * ICLASS: AND CATEGORY: LOGICAL EXTENSION: BASE IFORM: AND_MEMv_IMMz ISA_SET: I86 * SHORT: and dword ptr [eax+0xf0], 0xfffffeff AND r/m32, imm32 * (rax = lapic address, 0xff000000) * andl $0xfffffeff,0xf0(%rax) * 0x81 0xa0 0xf0 0x00 0x00 0x00 0xff 0xfe 0xff 0xff */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vie.inst[0] = 0x81; vie.inst[1] = 0xa0; vie.inst[2] = 0xf0; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0x00; vie.inst[6] = 0xff; vie.inst[7] = 0xfe; vie.inst[8] = 0xff; vie.inst[9] = 0xff; vie.num_valid = 10; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xa0aa); /* * SHORT: and dword ptr [eax+0xf0], 0xffef0000 AND r/m16, imm16 * (rax = lapic address, 0xff000000) * andl $0x0000feff,0xf0(%rax) * 0x81 0xa0 0xf0 0x00 0x00 0x00 0xff 0xfe 0x00 0x00 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vie.inst[0] = 0x81; vie.inst[1] = 0xa0; vie.inst[2] = 0xf0; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0x00; vie.inst[6] = 0xff; vie.inst[7] = 0xfe; vie.inst[8] = 0x00; vie.inst[9] = 0x00; vie.num_valid = 10; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xa0aa); /* * ICLASS: AND CATEGORY: LOGICAL EXTENSION: BASE IFORM: AND_MEMb_IMMb_80r4 ISA_SET: I86 * SHORT: and byte ptr [eax+0xf0], 0xff AND r/m8, imm8 * (rax = lapic address, 0xff000000) * andl $0xff,0xf0(%rax) * 0x80 0xa0 0xf0 0x00 0x00 0x00 0xff */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vie.inst[0] = 0x80; vie.inst[1] = 0xa0; vie.inst[2] = 0xf0; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0x00; vie.inst[6] = 0xff; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xa0aa); /* * SHORT: and byte ptr [eax+0xf0], 0xff AND r/m16/32, imm8 * (rax = lapic address, 0xff000000) * andl $0xff,0xf0(%rax) * 0x83 0xa0 0xf0 0x00 0x00 0x00 0xff */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vie.inst[0] = 0x83; vie.inst[1] = 0xa0; vie.inst[2] = 0xf0; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0x00; vie.inst[6] = 0xff; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xa0aa); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMb_GPR8 ISA_SET: I86 * SHORT: mov byte ptr [ecx+0x58ecdc05], cl MOV r/m8, r8 * mov %r8d,5827804(%rip) * 88 89 05 dc ec 58 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0x88; vie.inst[1] = 0x89; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0x00; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* *ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMv_GPRv ISA_SET: I86 * SHORT: mov dword ptr [eax+0x58ecdc05], ecx MOV r/m16/32, r16/32 * mov %r8d,5827804(%rip) * 89 88 05 dc ec 58 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0x89; vie.inst[1] = 0x88; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0x00; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_GPR8_MEMb ISA_SET: I86 * SHORT: mov cl, byte ptr [ecx+0x58ecdc05] MOV r8, r/m8 * mov %r8d,5827804(%rip) * 8a 89 05 dc ec 58 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0x8a; vie.inst[1] = 0x89; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0x00; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_GPRv_MEMv ISA_SET: I86 * SHORT: mov ecx, dword ptr [eax+0x58ecdc05] MOV r16/32, r/m16/32 * mov %r8d,5827804(%rip) * 8b 88 05 dc ec 58 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0x8b; vie.inst[1] = 0x88; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0x00; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* *ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_OrAX_MEMv ISA_SET: I86 * SHORT: mov eax, dword ptr [0x0] MOV eax, moffs 16/32 * mov %r8d,5827804(%rip) * a1 00 00 00 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 5; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0xa1; vie.inst[1] = 0x00; vie.inst[2] = 0x00; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.num_valid = 5; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* *ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMv_OrAX ISA_SET: I86 * SHORT: mov dword ptr [0x0], eax MOV moffs16/32, eax * mov %r8d,5827804(%rip) * a3 00 00 00 00 * rip -> 0xffffffff8046539d * var -> 0xffffffff809f4080 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 5; vm_regs[VM_REG_GUEST_R8] = 0xa5a5a5a5deadbeefULL; vie.inst[0] = 0xa3; vie.inst[1] = 0x00; vie.inst[2] = 0x00; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.num_valid = 5; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff000080; mc.val = 0; gpa = 0xff000080; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMv_IMMz ISA_SET: I86 * SHORT: mov dword ptr [eax+0x58ecdc05], 0xffff MOV r/m 16, imm16 * movl $0x1ef,5872021(%rip) * c7 05 95 99 59 00 ef * c7 80 05 dc ec 58 ff ff 00 00 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 9; vie.inst[0] = 0xc7; vie.inst[1] = 0x80; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0xff; vie.inst[7] = 0xff; vie.inst[7] = 0x00; vie.inst[8] = 0x00; vie.num_valid = 9; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMv_IMMz ISA_SET: I86 * SHORT: mov dword ptr [eax+0x58ecdc05], 0xffffffff MOV r/m 32, imm32 * movl $0x1ef,5872021(%rip) * c7 05 95 99 59 00 ef * c7 80 05 dc ec 58 ff ff ff ff * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 9; vie.inst[0] = 0xc7; vie.inst[1] = 0x80; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0xff; vie.inst[7] = 0xff; vie.inst[7] = 0xff; vie.inst[8] = 0xff; vie.num_valid = 9; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOV CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOV_MEMb_IMMb ISA_SET: I86 * SHORT: mov byte ptr [ecx+0x58ecdc05], 0xff MOV r/m8. imm8 * c6 81 05 dc ec 58 ff * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vie.inst[0] = 0xc6; vie.inst[1] = 0x81; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.inst[6] = 0xff; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVZX CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOVZX_GPRv_MEMb ISA_SET: I386 * SHORT: movzx ax, byte ptr [ecx+0x58ecdc05] MoVZX r16, r/m8 (Mov with Zero-extend) * 66 0f b6 81 05 dc ec 58 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 8; vie.inst[0] = 0x66; vie.inst[1] = 0x0f; vie.inst[2] = 0xb6; vie.inst[3] = 0x81; vie.inst[4] = 0x05; vie.inst[5] = 0xdc; vie.inst[6] = 0xec; vie.inst[7] = 0x58; vie.num_valid = 8; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVZX CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOVZX_GPRv_MEMb ISA_SET: I386 * SHORT: movzx eax, byte ptr [ecx+0x58ecdc05] MoVZX r32, r/m8 (Mov with Zero-extend) * 0f b6 81 05 dc ec 58 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vie.inst[0] = 0x0f; vie.inst[1] = 0xb6; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVZX CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOVZX_GPRv_MEMw ISA_SET: I386 * SHORT: movzx eax, word ptr [ecx+0x58ecdc05] MOV r16/32, r/m16 * 0f b7 81 05 dc ec 58 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vie.inst[0] = 0x0f; vie.inst[1] = 0xb7; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVSX CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOVSX_GPRv_MEMb ISA_SET: I386 * SHORT: movsx ax, byte ptr [ecx+0x58ecdc05] MOVSX r16, r/m8 * 66 0f be 81 05 dc ec 58 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 8; vie.inst[0] = 0x66; vie.inst[1] = 0x0f; vie.inst[2] = 0xbe; vie.inst[3] = 0x81; vie.inst[4] = 0x05; vie.inst[5] = 0xdc; vie.inst[6] = 0xec; vie.inst[7] = 0x58; vie.num_valid = 8; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVSX CATEGORY: DATAXFER EXTENSION: BASE IFORM: MOVSX_GPRv_MEMb ISA_SET: I386 * SHORT: movsx eax, byte ptr [ecx+0x58ecdc05] MOVSX r32, r/m8 * 0f be 81 05 dc ec 58 * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 7; vie.inst[0] = 0x0f; vie.inst[1] = 0xbe; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVSB CATEGORY: STRINGOP EXTENSION: BASE IFORM: MOVSB ISA_SET: I86 * SHORT: movsb byte ptr [di], byte ptr [si] MOVSB m8, m8 * 67 a4 move data from string to string * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 2; vie.inst[0] = 0x67; vie.inst[1] = 0xa4; vie.num_valid = 2; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVSW CATEGORY: STRINGOP EXTENSION: BASE IFORM: MOVSW ISA_SET: I86 * SHORT: movsw word ptr [edi], word ptr [esi] MOVSW m16/32, m16/32 * 66 a5 move data from string to string * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 2; vie.inst[0] = 0x66; vie.inst[1] = 0xa5; vie.num_valid = 2; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: MOVSD CATEGORY: STRINGOP EXTENSION: BASE IFORM: MOVSD ISA_SET: I386 * SHORT: movsd dword ptr [edi], dword ptr [esi] MOVSW m32, m32 * A5 move data from string to string * rip -> ffffffff813d2751 * val -> ffffffff8196c0f0 * pa -> 0xfee000f0 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; /* RIP-relative is from next instruction */ vm_regs[VM_REG_GUEST_RIP] = 0xffffffff8046539d + 1; vie.inst[0] = 0xa5; vie.num_valid = 1; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xfee000f0; mc.val = 0; gpa = 0xfee000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: OR CATEGORY: LOGICAL EXTENSION: BASE IFORM: OR_GPRv_MEMv ISA_SET: I86 * SHORT: or ax, word ptr [ecx+0x5dcec58] * (rcx = lapic address, 0xff000000) OR reg16, r/m16/32 * 66 0b 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0x0b; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: OR CATEGORY: LOGICAL EXTENSION: BASE IFORM: OR_GPRv_MEMv ISA_SET: I86 * SHORT: or eax, word ptr [ecx+0x5dcec58] * (rcx = lapic address, 0xff000000) OR reg32, r/m16/32 * 0b 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x0b; vie.inst[1] = 0x81; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: CMP CATEGORY: BINARY EXTENSION: BASE IFORM: CMP_MEMv_GPRv ISA_SET: I86 * SHORT: cmp word ptr [ecx+0x58ecdc05], ax CMP r/m16/32, reg16 * (rcx = lapic address, 0xff000000) * 66 39 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0x39; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000aa00; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: CMP CATEGORY: BINARY EXTENSION: BASE IFORM: CMP_MEMv_GPRv ISA_SET: I86 * SHORT: cmp dword ptr [ecx+0x58ecdc05], eax CMP r/m16/32, reg32 * (rcx = lapic address, 0xff000000) * 39 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x39; vie.inst[1] = 0x80; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000aa00; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: CMP CATEGORY: BINARY EXTENSION: BASE IFORM: CMP_GPRv_MEMv ISA_SET: I86 * SHORT: cmp ax, word ptr [ecx+0x58ecdc05] CMP r16, r/m16/32 * (rcx = lapic address, 0xff000000) * 66 3b 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0x3b; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000aa00; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: CMP CATEGORY: BINARY EXTENSION: BASE IFORM: CMP_GPRv_MEMv ISA_SET: I86 * SHORT: cmp eax, dword ptr [ecx+0x58ecdc05] CMP r32, r/m16/32 * (rcx = lapic address, 0xff000000) * 3b 81 05 dc ec 58 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x3b; vie.inst[1] = 0x81; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x58; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000aa00; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: BT CATEGORY: BITBYTE EXTENSION: BASE IFORM: BT_MEMv_IMMb ISA_SET: I386 * SHORT: bt word ptr [ecx+0x58ecdc05], 0xff BT r/m16, imm8 * 0x66, 0x0F, 0xBA, 0xA1, 0x05, 0xDC, 0xEC, 0x58, 0xFF */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0x0f; vie.inst[2] = 0xba; vie.inst[3] = 0xa1; vie.inst[4] = 0x05; vie.inst[5] = 0xdc; vie.inst[6] = 0xec; vie.inst[7] = 0x58; vie.inst[8] = 0xff; vie.num_valid = 9; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc);s assert(err == 0); assert(mc.val == 0xa0aa); /* * ICLASS: BT CATEGORY: BITBYTE EXTENSION: BASE IFORM: BT_MEMv_IMMb ISA_SET: I386 * SHORT: bt dword ptr [ecx+0x58ecdc05], 0xff BT r/m32, imm8 * 0x0F, 0xBA, 0xA1, 0x05, 0xDC, 0xEC, 0x58, 0xFF */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0x0f; vie.inst[1] = 0xba; vie.inst[2] = 0xa1; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x58; vie.inst[7] = 0xff; vie.num_valid = 8; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc);s assert(err == 0); assert(mc.val == 0xa0aa); /* * (rax = lapic address, 0xff000000) * mov $ff,0xf0(%rax) || mov r/m8, imm8 ( XXX Group 11 extended opcode - not just MOV ) * 0xc6 0xf0 0x00 0x00 0x00 0xff */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0xff000000; vm_regs[VM_REG_GUEST_RFLAGS]=0xff000000; vie.inst[0] = 0xc6; vie.inst[1] = 0xf0; vie.inst[2] = 0x00; vie.inst[3] = 0x00; vie.inst[4] = 0x00; vie.inst[5] = 0xff; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000f0; mc.val = 0x0000a1aa; gpa = 0xff0000f0; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xa0aa); /* * ICLASS: SUB CATEGORY: BINARY EXTENSION: BASE IFORM: SUB_GPRv_MEMv ISA_SET: I86 * SHORT: sub ax, word ptr [ecx+0x5ecdc05] SUB r16, r/m16 * 0x66 0x2b 0x81 0x05 0xdc 0xec 0x05 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0x2b; vie.inst[2] = 0x81; vie.inst[3] = 0x05; vie.inst[4] = 0xdc; vie.inst[5] = 0xec; vie.inst[6] = 0x05; vie.num_valid = 7; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: SUB CATEGORY: BINARY EXTENSION: BASE IFORM: SUB_GPRv_MEMv ISA_SET: I86 * SHORT: sub eax, dword ptr [ecx+0x5ecdc05] SUB r32, r/m32 * 0x2b 0x81 0x05 0xdc 0xec 0x05 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x2b; vie.inst[1] = 0x81; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.inst[4] = 0xec; vie.inst[5] = 0x05; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: STOSB CATEGORY: STRINGOP EXTENSION: BASE IFORM: STOSB ISA_SET: I86 * SHORT: stosb byte ptr [edi] STOS m8, r8 * 0xAA; */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0xaa; vie.num_valid = 1; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: STOSW CATEGORY: STRINGOP EXTENSION: BASE IFORM: STOSW ISA_SET: I86 * SHORT: stosw word ptr [edi] STOS m16, r16 * 0x66 0xAB */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x66; vie.inst[1] = 0xab; vie.num_valid = 2; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: STOSD CATEGORY: STRINGOP EXTENSION: BASE IFORM: STOSD ISA_SET: I386 * SHORT: stosd dword ptr [edi] STOS m32, r32 * 0xAB; */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0xab; vie.num_valid = 1; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: PUSH CATEGORY: PUSH EXTENSION: BASE IFORM: PUSH_M ISA_SET: I86 * SHORT: push dword ptr [ecx+0x5ecdc05] PUSH r/m 16/32 * 0xff 0xb1 0x05 0xdc 0xec 0x05 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0xff; vie.inst[1] = 0xb1; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.isnt[4] = 0xec; vie.inst[5] = 0x05; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); /* * ICLASS: POP CATEGORY: POP EXTENSION: BASE IFORM: POP_MEMv ISA_SET: I86 * SHORT: pop dword ptr [ecx+0x5ecdc05] POP r/m 16/32 * 0x8f 0x81 0x05 0xdc 0xec 0x05 */ memset(&vie, 0, sizeof(struct vie)); vie.base_register = VM_REG_LAST; vie.index_register = VM_REG_LAST; vm_regs[VM_REG_GUEST_RAX] = 0x0000aabb; vm_regs[VM_REG_GUEST_RCX] = 0xff000000; vie.inst[0] = 0x8f; vie.inst[1] = 0x81; vie.inst[2] = 0x05; vie.inst[3] = 0xdc; vie.isnt[4] = 0xec; vie.inst[5] = 0x05; vie.num_valid = 6; gla = 0; err = vmm_decode_instruction(NULL, 0, gla, &vie); assert(err == 0); mc.addr = 0xff0000ff; mc.val = 0x0000aa00; gpa = 0xff0000ff; err = vmm_emulate_instruction(NULL, 0, gpa, &vie, test_mread, test_mwrite, &mc); assert(err == 0); assert(mc.val == 0xdeadbeef); }
751236.c
#include "libpov.h" int main(int cgc_argc, char *cgc_argv[]) { cgc_negotiate_type1(0x0, 0x0, 0); do { //*** writing data static unsigned char write_00000_00000[] = "\x65\x01\x00\x00"; static unsigned int write_00000_00000_len = 4; unsigned char *write_00000 = NULL; unsigned int write_00000_len = 0; write_00000 = cgc_append_buf(write_00000, &write_00000_len, write_00000_00000, write_00000_00000_len); if (write_00000_len > 0) { cgc_transmit_all(1, write_00000, write_00000_len); } cgc_free(write_00000); } while (0); do { //*** writing data static unsigned char write_00001_00000[] = "\x01\x00\x00\x00\x00\x00\x00\x00\x4d\x01\x00\x00\x45\x01\x00\x00" "\x00\x00\x00\x00\x10\x01\x10\x10\x00\x00\x00\x00\x45\x01\x00\x00" "\x9d\x08\xb6\x4b\x06\x4e\x8e\x63\x6f\x89\x64\x4c\xcc\x92\x71\xfc" "\x04\x3f\x90\xe4\x57\x00\x00\x00\x01\x00\x62\x99\xeb\x21\x42\xec" "\x1b\xbf\xe6\x01\xe1\xd5\x01\xcd\x9c\xb2\xcc\xac\xdf\xf3\xf1\x24" "\x65\x01\xb4\x41\x00\xd7\x59\xc4\xaa\xb1\xd0\xe8\x8e\x01\xab\x41" "\x00\xaf\x62\x41\x00\xff\x7c\x85\x5c\xe4\xe1\xc1\x8b\xfb\xe7\xd3" "\xc5\xc6\x13\x6a\x51\x03\x6b\x0c\x4f\x9d\x13\xea\x8a\x16\xf5\xc0" "\xc7\x79\x17\x50\x51\x31\xe1\xee\x2e\x90\x4c\x8f\x1e\x7a\x2e\xff" "\xfb\xf0\x02\x02\x33\xf2\x2d\xc6\xdb\xe8\xa1\x10\xc5\x7b\x98\xe9" "\x70\x37\x6d\xe7\xab\xb3\x76\x64\xd0\x73\x03\x8a\xdd\x56\xa8\x10" "\x3e\x65\x74\x1d\x28\x9a\x44\x5b\x4b\xe1\x12\xa2\x1e\x05\x7d\xa8" "\xc7\x9c\x1f\x73\xd9\x35\x16\x20\x2f\xb6\x7d\xb3\xb0\xfc\xb5\xd2" "\x3a\x79\xa7\x74\x5e\xdf\x9c\xea\x56\x82\x8c\x52\x97\xcf\xf9\x55" "\x3f\xa0\x6e\x72\x82\x85\x76\x38\x34\x7e\x87\x83\xf6\x4b\x48\x7b" "\xf3\x7e\x3e\x73\x99\xea\x56\xb0\x7c\x0b\x9d\xda\xe7\xbd\x1b\x83" "\x16\xc2\x7e\x7c\x18\x74\x02\x0b\x11\x34\xa8\xda\x88\x71\x9e\x16" "\x4d\xed\xda\xc3\xcb\x2f\x17\x4d\xf9\xd5\x19\x6c\x3f\x73\x79\xd1" "\xd8\x8e\x50\x3c\x1d\x4c\x2b\x90\x4a\xc5\x2a\xa1\xf7\x22\xf1\x18" "\x5f\x1c\xc1\x01\xb0\xd0\x62\x42\x11\x9f\xb2\x55\x36\xe3\x8d\x30" "\x68\xcb\x81\x05\xeb\xc2\x9d\xc5\x4e\x86\xf9\x65\x50\x87\x09\x85" "\xa1\xbc\xe2\x5c\x75\x06\x2a\x3d\x16\xad\x69\x04\x9d\xad\x95\xe7" "\x7c\x84\xe5\x11\xe4"; static unsigned int write_00001_00000_len = 357; unsigned char *write_00001 = NULL; unsigned int write_00001_len = 0; write_00001 = cgc_append_buf(write_00001, &write_00001_len, write_00001_00000, write_00001_00000_len); if (write_00001_len > 0) { cgc_transmit_all(1, write_00001, write_00001_len); } cgc_free(write_00001); } while (0); do { unsigned char *read_00000; unsigned int read_00000_len; unsigned int read_00000_ptr = 0; //**** delimited read static unsigned char read_00000_delim[] = "\x0a"; read_00000 = NULL; read_00000_len = 0; int read_00000_res = cgc_delimited_read(0, &read_00000, &read_00000_len, read_00000_delim, 1); if (read_00000_res) {} //silence unused variable warning //**** read match data static unsigned char match_00000_00000[] = "\x53\x74\x61\x72\x74\x69\x6e\x67\x20\x64\x69\x73\x73\x65\x63\x74" "\x69\x6f\x6e\x2e\x2e\x2e"; read_00000_ptr += cgc_data_match(read_00000 + read_00000_ptr, read_00000_len - read_00000_ptr, match_00000_00000, 22); cgc_free(read_00000); if (read_00000_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00001; unsigned int read_00001_len; unsigned int read_00001_ptr = 0; //**** delimited read static unsigned char read_00001_delim[] = "\x3d\x3d\x3d\x3d\x0a"; read_00001 = NULL; read_00001_len = 0; int read_00001_res = cgc_delimited_read(0, &read_00001, &read_00001_len, read_00001_delim, 5); if (read_00001_res) {} //silence unused variable warning /* read match pcre: .*New Packet */ static char read_00001_00000_regex[] = "\x2e\x2a\x4e\x65\x77\x20\x50\x61\x63\x6b\x65\x74"; static match_result read_00001_00000_match; pcre *read_00001_00000_pcre = cgc_init_regex(read_00001_00000_regex); if (read_00001_00000_pcre != NULL) { int rc = cgc_regex_match(read_00001_00000_pcre, 0, read_00001 + read_00001_ptr, read_00001_len - read_00001_ptr, &read_00001_00000_match); if (rc > 0) { read_00001_ptr += read_00001_00000_match.match_end - read_00001_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00001_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00001); if (read_00001_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00002; unsigned int read_00002_len; unsigned int read_00002_ptr = 0; //**** delimited read static unsigned char read_00002_delim[] = "\x3d\x3d\x3d\x0a"; read_00002 = NULL; read_00002_len = 0; int read_00002_res = cgc_delimited_read(0, &read_00002, &read_00002_len, read_00002_delim, 4); if (read_00002_res) {} //silence unused variable warning /* read match pcre: .*===llama */ static char read_00002_00000_regex[] = "\x2e\x2a\x3d\x3d\x3d\x6c\x6c\x61\x6d\x61"; static match_result read_00002_00000_match; pcre *read_00002_00000_pcre = cgc_init_regex(read_00002_00000_regex); if (read_00002_00000_pcre != NULL) { int rc = cgc_regex_match(read_00002_00000_pcre, 0, read_00002 + read_00002_ptr, read_00002_len - read_00002_ptr, &read_00002_00000_match); if (rc > 0) { read_00002_ptr += read_00002_00000_match.match_end - read_00002_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00002_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00002); if (read_00002_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00003; unsigned int read_00003_len; unsigned int read_00003_ptr = 0; //**** delimited read static unsigned char read_00003_delim[] = "\x3d\x3d\x3d\x0a"; read_00003 = NULL; read_00003_len = 0; int read_00003_res = cgc_delimited_read(0, &read_00003, &read_00003_len, read_00003_delim, 4); if (read_00003_res) {} //silence unused variable warning /* read match pcre: .*===llamacoruscant */ static char read_00003_00000_regex[] = "\x2e\x2a\x3d\x3d\x3d\x6c\x6c\x61\x6d\x61\x63\x6f\x72\x75\x73\x63" "\x61\x6e\x74"; static match_result read_00003_00000_match; pcre *read_00003_00000_pcre = cgc_init_regex(read_00003_00000_regex); if (read_00003_00000_pcre != NULL) { int rc = cgc_regex_match(read_00003_00000_pcre, 0, read_00003 + read_00003_ptr, read_00003_len - read_00003_ptr, &read_00003_00000_match); if (rc > 0) { read_00003_ptr += read_00003_00000_match.match_end - read_00003_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00003_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00003); if (read_00003_ptr) {} //silence unused variable warning if any } while (0); do { unsigned char *read_00004; unsigned int read_00004_len; unsigned int read_00004_ptr = 0; //**** delimited read static unsigned char read_00004_delim[] = "\x3d\x3d\x3d\x0a"; read_00004 = NULL; read_00004_len = 0; int read_00004_res = cgc_delimited_read(0, &read_00004, &read_00004_len, read_00004_delim, 4); if (read_00004_res) {} //silence unused variable warning /* read match pcre: .*Dissection finished */ static char read_00004_00000_regex[] = "\x2e\x2a\x44\x69\x73\x73\x65\x63\x74\x69\x6f\x6e\x20\x66\x69\x6e" "\x69\x73\x68\x65\x64"; static match_result read_00004_00000_match; pcre *read_00004_00000_pcre = cgc_init_regex(read_00004_00000_regex); if (read_00004_00000_pcre != NULL) { int rc = cgc_regex_match(read_00004_00000_pcre, 0, read_00004 + read_00004_ptr, read_00004_len - read_00004_ptr, &read_00004_00000_match); if (rc > 0) { read_00004_ptr += read_00004_00000_match.match_end - read_00004_00000_match.match_start; } else { //this is a pov so what does this even mean? //why would we quit on failed match, just keep sending stuff. } pcre_free(read_00004_00000_pcre); } else { //this is a pov so what does this even mean? //why would we quit on failed regex compile, just keep sending stuff. } cgc_free(read_00004); if (read_00004_ptr) {} //silence unused variable warning if any } while (0); }
842594.c
/* * Copyright (c) 1999, 2000 * Politecnico di Torino. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that: (1) source code distributions * retain the above copyright notice and this paragraph in its entirety, (2) * distributions including binary code include the above copyright notice and * this paragraph in its entirety in the documentation or other materials * provided with the distribution, and (3) all advertising materials mentioning * features or use of this software display the following acknowledgement: * ``This product includes software developed by the Politecnico * di Torino, and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if defined(WIN32) #include <signal.h> #include <stdio.h> #include <windows.h> void *GetAdapterFromList(void *device, int index) { DWORD dwVersion; DWORD dwWindowsMajorVersion; char *Adapter95; WCHAR *Adapter; int i; dwVersion = GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) { // Windows '95 Adapter95 = device; for (i = 0; i < index - 1; i++) { while (*Adapter95++ != 0) ; if (*Adapter95 == 0) return NULL; } return Adapter95; } else { Adapter = (WCHAR *)device; for (i = 0; i < index - 1; i++) { while (*Adapter++ != 0) ; if (*Adapter == 0) return NULL; } return Adapter; } } void PrintDeviceList(const char *device) { DWORD dwVersion; DWORD dwWindowsMajorVersion; const WCHAR *t; const char *t95; int i = 0; int DescPos = 0; char *Desc; int n = 1; dwVersion = GetVersion(); dwWindowsMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); if (dwVersion >= 0x80000000 && dwWindowsMajorVersion >= 4) { // Windows '95 t95 = (char *)device; while (*(t95 + DescPos) != 0 || *(t95 + DescPos - 1) != 0) DescPos++; Desc = (char *)t95 + DescPos + 1; printf("\n" "Interface\tDevice\t\t\t\t\tDescription\n" "-------------------------------------------\n"); printf("%d ", n++); while (!(t95[i] == 0 && t95[i - 1] == 0)) { if (t95[i] == 0) { putchar(' '); putchar('('); while (*Desc != 0) { putchar(*Desc); Desc++; } Desc++; putchar(')'); putchar('\n'); } else putchar(t95[i]); if ((t95[i] == 0) && (t95[i + 1] != 0)) { printf("%d ", n++); } i++; } putchar('\n'); } else { // Windows NT t = (WCHAR *)device; while (*(t + DescPos) != 0 || *(t + DescPos - 1) != 0) DescPos++; DescPos <<= 1; Desc = (char *)t + DescPos + 2; printf("\n" "Interface\tDevice\t\t\t\t\tDescription\n" "----------------------------------------------------------------------------\n"); printf("%d ", n++); while (!(t[i] == 0 && t[i - 1] == 0)) { if (t[i] == 0) { putchar(' '); putchar('('); while (*Desc != 0) { putchar(*Desc); Desc++; } Desc++; putchar(')'); putchar('\n'); } else putchar(t[i]); if (t[i] == 0 && t[i + 1] != 0) printf("%d ", n++); i++; } putchar('\n'); } } #endif /* WIN32 */
776570.c
/* sign.c - sign data * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, * 2007, 2010, 2012 Free Software Foundation, Inc. * * This file is part of GnuPG. * * GnuPG is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * GnuPG is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <assert.h> #include "gpg.h" #include "options.h" #include "packet.h" #include "status.h" #include "iobuf.h" #include "keydb.h" #include "util.h" #include "main.h" #include "filter.h" #include "ttyio.h" #include "trustdb.h" #include "status.h" #include "i18n.h" #include "pkglue.h" #include "sysutils.h" #include "call-agent.h" #ifdef HAVE_DOSISH_SYSTEM #define LF "\r\n" #else #define LF "\n" #endif static int recipient_digest_algo=0; /**************** * Create notations and other stuff. It is assumed that the stings in * STRLIST are already checked to contain only printable data and have * a valid NAME=VALUE format. */ static void mk_notation_policy_etc( PKT_signature *sig, PKT_public_key *pk, PKT_secret_key *sk ) { const char *string; char *s=NULL; strlist_t pu=NULL; struct notation *nd=NULL; struct expando_args args; assert(sig->version>=4); memset(&args,0,sizeof(args)); args.pk=pk; args.sk=sk; /* notation data */ if(IS_SIG(sig) && opt.sig_notations) nd=opt.sig_notations; else if( IS_CERT(sig) && opt.cert_notations ) nd=opt.cert_notations; if(nd) { struct notation *i; for(i=nd;i;i=i->next) { i->altvalue=pct_expando(i->value,&args); if(!i->altvalue) log_error(_("WARNING: unable to %%-expand notation " "(too large). Using unexpanded.\n")); } keygen_add_notations(sig,nd); for(i=nd;i;i=i->next) { xfree(i->altvalue); i->altvalue=NULL; } } /* set policy URL */ if( IS_SIG(sig) && opt.sig_policy_url ) pu=opt.sig_policy_url; else if( IS_CERT(sig) && opt.cert_policy_url ) pu=opt.cert_policy_url; for(;pu;pu=pu->next) { string = pu->d; s=pct_expando(string,&args); if(!s) { log_error(_("WARNING: unable to %%-expand policy URL " "(too large). Using unexpanded.\n")); s=xstrdup(string); } build_sig_subpkt(sig,SIGSUBPKT_POLICY| ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0), s,strlen(s)); xfree(s); } /* preferred keyserver URL */ if( IS_SIG(sig) && opt.sig_keyserver_url ) pu=opt.sig_keyserver_url; for(;pu;pu=pu->next) { string = pu->d; s=pct_expando(string,&args); if(!s) { log_error(_("WARNING: unable to %%-expand preferred keyserver URL" " (too large). Using unexpanded.\n")); s=xstrdup(string); } build_sig_subpkt(sig,SIGSUBPKT_PREF_KS| ((pu->flags & 1)?SIGSUBPKT_FLAG_CRITICAL:0), s,strlen(s)); xfree(s); } } /* * Helper to hash a user ID packet. */ static void hash_uid (gcry_md_hd_t md, int sigversion, const PKT_user_id *uid) { if ( sigversion >= 4 ) { byte buf[5]; if(uid->attrib_data) { buf[0] = 0xd1; /* indicates an attribute packet */ buf[1] = uid->attrib_len >> 24; /* always use 4 length bytes */ buf[2] = uid->attrib_len >> 16; buf[3] = uid->attrib_len >> 8; buf[4] = uid->attrib_len; } else { buf[0] = 0xb4; /* indicates a userid packet */ buf[1] = uid->len >> 24; /* always use 4 length bytes */ buf[2] = uid->len >> 16; buf[3] = uid->len >> 8; buf[4] = uid->len; } gcry_md_write( md, buf, 5 ); } if(uid->attrib_data) gcry_md_write (md, uid->attrib_data, uid->attrib_len ); else gcry_md_write (md, uid->name, uid->len ); } /* * Helper to hash some parts from the signature */ static void hash_sigversion_to_magic (gcry_md_hd_t md, const PKT_signature *sig) { if (sig->version >= 4) gcry_md_putc (md, sig->version); gcry_md_putc (md, sig->sig_class); if (sig->version < 4) { u32 a = sig->timestamp; gcry_md_putc (md, (a >> 24) & 0xff ); gcry_md_putc (md, (a >> 16) & 0xff ); gcry_md_putc (md, (a >> 8) & 0xff ); gcry_md_putc (md, a & 0xff ); } else { byte buf[6]; size_t n; gcry_md_putc (md, sig->pubkey_algo); gcry_md_putc (md, sig->digest_algo); if (sig->hashed) { n = sig->hashed->len; gcry_md_putc (md, (n >> 8) ); gcry_md_putc (md, n ); gcry_md_write (md, sig->hashed->data, n ); n += 6; } else { gcry_md_putc (md, 0); /* always hash the length of the subpacket*/ gcry_md_putc (md, 0); n = 6; } /* add some magic */ buf[0] = sig->version; buf[1] = 0xff; buf[2] = n >> 24; /* hmmm, n is only 16 bit, so this is always 0 */ buf[3] = n >> 16; buf[4] = n >> 8; buf[5] = n; gcry_md_write (md, buf, 6); } } static int do_sign( PKT_secret_key *sk, PKT_signature *sig, gcry_md_hd_t md, int digest_algo ) { gcry_mpi_t frame; byte *dp; int rc; if( sk->timestamp > sig->timestamp ) { ulong d = sk->timestamp - sig->timestamp; log_info( d==1 ? _("key has been created %lu second " "in future (time warp or clock problem)\n") : _("key has been created %lu seconds " "in future (time warp or clock problem)\n"), d ); if( !opt.ignore_time_conflict ) return G10ERR_TIME_CONFLICT; } print_pubkey_algo_note(sk->pubkey_algo); if( !digest_algo ) digest_algo = gcry_md_get_algo (md); print_digest_algo_note( digest_algo ); dp = gcry_md_read ( md, digest_algo ); sig->digest_algo = digest_algo; sig->digest_start[0] = dp[0]; sig->digest_start[1] = dp[1]; if (sk->is_protected && sk->protect.s2k.mode == 1002) { #ifdef ENABLE_CARD_SUPPORT unsigned char *rbuf; size_t rbuflen; char *snbuf; snbuf = serialno_and_fpr_from_sk (sk->protect.iv, sk->protect.ivlen, sk); rc = agent_scd_pksign (snbuf, digest_algo, gcry_md_read (md, digest_algo), gcry_md_get_algo_dlen (digest_algo), &rbuf, &rbuflen); xfree (snbuf); if (!rc) { if (gcry_mpi_scan (&sig->data[0], GCRYMPI_FMT_USG, rbuf, rbuflen, NULL)) BUG (); xfree (rbuf); } #else return gpg_error (GPG_ERR_NOT_SUPPORTED); #endif /* ENABLE_CARD_SUPPORT */ } else { frame = encode_md_value( NULL, sk, md, digest_algo ); if (!frame) return G10ERR_GENERAL; rc = pk_sign( sk->pubkey_algo, sig->data, frame, sk->skey ); gcry_mpi_release (frame); } if (!rc && !opt.no_sig_create_check) { /* Check that the signature verification worked and nothing is * fooling us e.g. by a bug in the signature create * code or by deliberately introduced faults. */ PKT_public_key *pk = xmalloc_clear (sizeof *pk); if( get_pubkey( pk, sig->keyid ) ) rc = G10ERR_NO_PUBKEY; else { frame = encode_md_value (pk, NULL, md, sig->digest_algo ); if (!frame) rc = G10ERR_GENERAL; else rc = pk_verify (pk->pubkey_algo, frame, sig->data, pk->pkey ); gcry_mpi_release (frame); } if (rc) log_error (_("checking created signature failed: %s\n"), g10_errstr (rc)); free_public_key (pk); } if( rc ) log_error(_("signing failed: %s\n"), g10_errstr(rc) ); else { if( opt.verbose ) { char *ustr = get_user_id_string_native (sig->keyid); log_info(_("%s/%s signature from: \"%s\"\n"), openpgp_pk_algo_name (sk->pubkey_algo), gcry_md_algo_name (sig->digest_algo), ustr ); xfree(ustr); } } return rc; } int complete_sig( PKT_signature *sig, PKT_secret_key *sk, gcry_md_hd_t md ) { int rc=0; if( !(rc=check_secret_key( sk, 0 )) ) rc = do_sign( sk, sig, md, 0 ); return rc; } static int match_dsa_hash (unsigned int qbytes) { if (qbytes <= 20) return DIGEST_ALGO_SHA1; if (qbytes <= 28) return DIGEST_ALGO_SHA224; if (qbytes <= 32) return DIGEST_ALGO_SHA256; if (qbytes <= 48) return DIGEST_ALGO_SHA384; if (qbytes <= 64) return DIGEST_ALGO_SHA512; return DEFAULT_DIGEST_ALGO; /* DEFAULT_DIGEST_ALGO will certainly fail, but it's the best wrong answer we have if a digest larger than 512 bits is requested. */ } /* First try --digest-algo. If that isn't set, see if the recipient has a preferred algorithm (which is also filtered through --personal-digest-prefs). If we're making a signature without a particular recipient (i.e. signing, rather than signing+encrypting) then take the first algorithm in --personal-digest-prefs that is usable for the pubkey algorithm. If --personal-digest-prefs isn't set, then take the OpenPGP default (i.e. SHA-1). Possible improvement: Use the highest-ranked usable algorithm from the signing key prefs either before or after using the personal list? */ static int hash_for(PKT_secret_key *sk) { if( opt.def_digest_algo ) return opt.def_digest_algo; else if( recipient_digest_algo ) return recipient_digest_algo; else if(sk->pubkey_algo==PUBKEY_ALGO_DSA) { unsigned int qbytes = gcry_mpi_get_nbits (sk->skey[1]) / 8; /* It's a DSA key, so find a hash that is the same size as q or larger. If q is 160, assume it is an old DSA key and use a 160-bit hash unless --enable-dsa2 is set, in which case act like a new DSA key that just happens to have a 160-bit q (i.e. allow truncation). If q is not 160, by definition it must be a new DSA key. */ if (opt.personal_digest_prefs) { prefitem_t *prefs; if (qbytes != 20 || opt.flags.dsa2) { for (prefs=opt.personal_digest_prefs; prefs->type; prefs++) if (gcry_md_get_algo_dlen (prefs->value) >= qbytes) return prefs->value; } else { for (prefs=opt.personal_digest_prefs; prefs->type; prefs++) if (gcry_md_get_algo_dlen (prefs->value) == qbytes) return prefs->value; } } return match_dsa_hash(qbytes); } else if (sk->is_protected && sk->protect.s2k.mode == 1002 && sk->protect.ivlen == 16 && !memcmp (sk->protect.iv, "\xD2\x76\x00\x01\x24\x01\x01", 7)) { /* The sk lives on a smartcard, and old smartcards only handle SHA-1 and RIPEMD/160. Newer smartcards (v2.0) don't have this restriction anymore. Fortunately the serial number encodes the version of the card and thus we know that this key is on a v1 card. */ if(opt.personal_digest_prefs) { prefitem_t *prefs; for (prefs=opt.personal_digest_prefs;prefs->type;prefs++) if (prefs->value==DIGEST_ALGO_SHA1 || prefs->value==DIGEST_ALGO_RMD160) return prefs->value; } return DIGEST_ALGO_SHA1; } else if (PGP2 && sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 ) { /* Old-style PGP only understands MD5 */ return DIGEST_ALGO_MD5; } else if ( opt.personal_digest_prefs ) { /* It's not DSA, so we can use whatever the first hash algorithm is in the pref list */ return opt.personal_digest_prefs[0].value; } else return DEFAULT_DIGEST_ALGO; } static int only_old_style( SK_LIST sk_list ) { SK_LIST sk_rover = NULL; int old_style = 0; /* if there are only old style capable key we use the old sytle */ for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { PKT_secret_key *sk = sk_rover->sk; if( sk->pubkey_algo == PUBKEY_ALGO_RSA && sk->version < 4 ) old_style = 1; else return 0; } return old_style; } static void print_status_sig_created ( PKT_secret_key *sk, PKT_signature *sig, int what ) { byte array[MAX_FINGERPRINT_LEN], *p; char buf[100+MAX_FINGERPRINT_LEN*2]; size_t i, n; sprintf(buf, "%c %d %d %02x %lu ", what, sig->pubkey_algo, sig->digest_algo, sig->sig_class, (ulong)sig->timestamp ); fingerprint_from_sk( sk, array, &n ); p = buf + strlen(buf); for(i=0; i < n ; i++ ) sprintf(p+2*i, "%02X", array[i] ); write_status_text( STATUS_SIG_CREATED, buf ); } /* * Loop over the secret certificates in SK_LIST and build the one pass * signature packets. OpenPGP says that the data should be bracket by * the onepass-sig and signature-packet; so we build these onepass * packet here in reverse order */ static int write_onepass_sig_packets (SK_LIST sk_list, IOBUF out, int sigclass ) { int skcount; SK_LIST sk_rover; for (skcount=0, sk_rover=sk_list; sk_rover; sk_rover = sk_rover->next) skcount++; for (; skcount; skcount--) { PKT_secret_key *sk; PKT_onepass_sig *ops; PACKET pkt; int i, rc; for (i=0, sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { if (++i == skcount) break; } sk = sk_rover->sk; ops = xmalloc_clear (sizeof *ops); ops->sig_class = sigclass; ops->digest_algo = hash_for (sk); ops->pubkey_algo = sk->pubkey_algo; keyid_from_sk (sk, ops->keyid); ops->last = (skcount == 1); init_packet(&pkt); pkt.pkttype = PKT_ONEPASS_SIG; pkt.pkt.onepass_sig = ops; rc = build_packet (out, &pkt); free_packet (&pkt); if (rc) { log_error ("build onepass_sig packet failed: %s\n", g10_errstr(rc)); return rc; } } return 0; } /* * Helper to write the plaintext (literal data) packet */ static int write_plaintext_packet (IOBUF out, IOBUF inp, const char *fname, int ptmode) { PKT_plaintext *pt = NULL; u32 filesize; int rc = 0; if (!opt.no_literal) pt=setup_plaintext_name(fname,inp); /* try to calculate the length of the data */ if ( !iobuf_is_pipe_filename (fname) && *fname ) { off_t tmpsize; int overflow; if( !(tmpsize = iobuf_get_filelength(inp, &overflow)) && !overflow && opt.verbose) log_info (_("WARNING: `%s' is an empty file\n"), fname); /* We can't encode the length of very large files because OpenPGP uses only 32 bit for file sizes. So if the size of a file is larger than 2^32 minus some bytes for packet headers, we switch to partial length encoding. */ if ( tmpsize < (IOBUF_FILELENGTH_LIMIT - 65536) ) filesize = tmpsize; else filesize = 0; /* Because the text_filter modifies the length of the * data, it is not possible to know the used length * without a double read of the file - to avoid that * we simple use partial length packets. */ if ( ptmode == 't' ) filesize = 0; } else filesize = opt.set_filesize? opt.set_filesize : 0; /* stdin */ if (!opt.no_literal) { PACKET pkt; pt->timestamp = make_timestamp (); pt->mode = ptmode; pt->len = filesize; pt->new_ctb = !pt->len && !RFC1991; pt->buf = inp; init_packet(&pkt); pkt.pkttype = PKT_PLAINTEXT; pkt.pkt.plaintext = pt; /*cfx.datalen = filesize? calc_packet_length( &pkt ) : 0;*/ if( (rc = build_packet (out, &pkt)) ) log_error ("build_packet(PLAINTEXT) failed: %s\n", g10_errstr(rc) ); pt->buf = NULL; } else { byte copy_buffer[4096]; int bytes_copied; while ((bytes_copied = iobuf_read(inp, copy_buffer, 4096)) != -1) if ( (rc=iobuf_write(out, copy_buffer, bytes_copied)) ) { log_error ("copying input to output failed: %s\n", gpg_strerror (rc)); break; } wipememory(copy_buffer,4096); /* burn buffer */ } /* fixme: it seems that we never freed pt/pkt */ return rc; } /* * Write the signatures from the SK_LIST to OUT. HASH must be a non-finalized * hash which will not be changes here. */ static int write_signature_packets (SK_LIST sk_list, IOBUF out, gcry_md_hd_t hash, int sigclass, u32 timestamp, u32 duration, int status_letter) { SK_LIST sk_rover; /* loop over the secret certificates */ for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) { PKT_secret_key *sk; PKT_signature *sig; gcry_md_hd_t md; int rc; sk = sk_rover->sk; /* build the signature packet */ sig = xmalloc_clear (sizeof *sig); if(opt.force_v3_sigs || RFC1991) sig->version=3; else if(duration || opt.sig_policy_url || opt.sig_notations || opt.sig_keyserver_url) sig->version=4; else sig->version=sk->version; keyid_from_sk (sk, sig->keyid); sig->digest_algo = hash_for(sk); sig->pubkey_algo = sk->pubkey_algo; if(timestamp) sig->timestamp = timestamp; else sig->timestamp = make_timestamp(); if(duration) sig->expiredate = sig->timestamp+duration; sig->sig_class = sigclass; if (gcry_md_copy (&md, hash)) BUG (); if (sig->version >= 4) { build_sig_subpkt_from_sig (sig); mk_notation_policy_etc (sig, NULL, sk); } hash_sigversion_to_magic (md, sig); gcry_md_final (md); rc = do_sign( sk, sig, md, hash_for (sk) ); gcry_md_close (md); if( !rc ) { /* and write it */ PACKET pkt; init_packet(&pkt); pkt.pkttype = PKT_SIGNATURE; pkt.pkt.signature = sig; rc = build_packet (out, &pkt); if (!rc && is_status_enabled()) { print_status_sig_created ( sk, sig, status_letter); } free_packet (&pkt); if (rc) log_error ("build signature packet failed: %s\n", g10_errstr(rc) ); } if( rc ) return rc;; } return 0; } /**************** * Sign the files whose names are in FILENAME. * If DETACHED has the value true, * make a detached signature. If FILENAMES->d is NULL read from stdin * and ignore the detached mode. Sign the file with all secret keys * which can be taken from LOCUSR, if this is NULL, use the default one * If ENCRYPTFLAG is true, use REMUSER (or ask if it is NULL) to encrypt the * signed data for these users. * If OUTFILE is not NULL; this file is used for output and the function * does not ask for overwrite permission; output is then always * uncompressed, non-armored and in binary mode. */ int sign_file( strlist_t filenames, int detached, strlist_t locusr, int encryptflag, strlist_t remusr, const char *outfile ) { const char *fname; armor_filter_context_t *afx; compress_filter_context_t zfx; md_filter_context_t mfx; text_filter_context_t tfx; progress_filter_context_t *pfx; encrypt_filter_context_t efx; IOBUF inp = NULL, out = NULL; PACKET pkt; int rc = 0; PK_LIST pk_list = NULL; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; int multifile = 0; u32 duration=0; pfx = new_progress_context (); afx = new_armor_context (); memset( &zfx, 0, sizeof zfx); memset( &mfx, 0, sizeof mfx); memset( &efx, 0, sizeof efx); init_packet( &pkt ); if( filenames ) { fname = filenames->d; multifile = !!filenames->next; } else fname = NULL; if( fname && filenames->next && (!detached || encryptflag) ) log_bug("multiple files can only be detached signed"); if(encryptflag==2 && (rc=setup_symkey(&efx.symkey_s2k,&efx.symkey_dek))) goto leave; if(!opt.force_v3_sigs && !RFC1991) { if(opt.ask_sig_expire && !opt.batch) duration=ask_expire_interval(1,opt.def_sig_expire); else duration=parse_expire_string(opt.def_sig_expire); } if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) ) goto leave; if(PGP2 && !only_old_style(sk_list)) { log_info(_("you can only detach-sign with PGP 2.x style keys " "while in --pgp2 mode\n")); compliance_failure(); } if(encryptflag && (rc=build_pk_list( remusr, &pk_list, PUBKEY_USAGE_ENC ))) goto leave; /* prepare iobufs */ if( multifile ) /* have list of filenames */ inp = NULL; /* we do it later */ else { inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; errno = EPERM; } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); } if( outfile ) { if (is_secured_filename ( outfile )) { out = NULL; errno = EPERM; } else out = iobuf_create( outfile ); if( !out ) { rc = gpg_error_from_syserror (); log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) ); goto leave; } else if( opt.verbose ) log_info(_("writing to `%s'\n"), outfile ); } else if( (rc = open_outfile( fname, opt.armor? 1: detached? 2:0, &out ))) goto leave; /* prepare to calculate the MD over the input */ if( opt.textmode && !outfile && !multifile ) { memset( &tfx, 0, sizeof tfx); iobuf_push_filter( inp, text_filter, &tfx ); } if ( gcry_md_open (&mfx.md, 0, 0) ) BUG (); if (DBG_HASHING) gcry_md_debug (mfx.md, "sign"); /* If we're encrypting and signing, it is reasonable to pick the hash algorithm to use out of the recepient key prefs. This is best effort only, as in a DSA2 and smartcard world there are cases where we cannot please everyone with a single hash (DSA2 wants >160 and smartcards want =160). In the future this could be more complex with different hashes for each sk, but the current design requires a single hash for all SKs. */ if(pk_list) { if(opt.def_digest_algo) { if(!opt.expert && select_algo_from_prefs(pk_list,PREFTYPE_HASH, opt.def_digest_algo, NULL)!=opt.def_digest_algo) log_info(_("WARNING: forcing digest algorithm %s (%d)" " violates recipient preferences\n"), gcry_md_algo_name (opt.def_digest_algo), opt.def_digest_algo ); } else { int algo, smartcard=0; union pref_hint hint; hint.digest_length = 0; /* Of course, if the recipient asks for something unreasonable (like the wrong hash for a DSA key) then don't do it. Check all sk's - if any are DSA or live on a smartcard, then the hash has restrictions and we may not be able to give the recipient what they want. For DSA, pass a hint for the largest q we have. Note that this means that a q>160 key will override a q=160 key and force the use of truncation for the q=160 key. The alternative would be to ignore the recipient prefs completely and get a different hash for each DSA key in hash_for(). The override behavior here is more or less reasonable as it is under the control of the user which keys they sign with for a given message and the fact that the message with multiple signatures won't be usable on an implementation that doesn't understand DSA2 anyway. */ for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { if (sk_rover->sk->pubkey_algo == PUBKEY_ALGO_DSA) { int temp_hashlen = (gcry_mpi_get_nbits (sk_rover->sk->skey[1])+7)/8; /* Pick a hash that is large enough for our largest q */ if (hint.digest_length<temp_hashlen) hint.digest_length=temp_hashlen; } else if (sk_rover->sk->is_protected && sk_rover->sk->protect.s2k.mode == 1002) smartcard = 1; } /* Current smartcards only do 160-bit hashes. If we have to have a >160-bit hash, then we can't use the recipient prefs as we'd need both =160 and >160 at the same time and recipient prefs currently require a single hash for all signatures. All this may well have to change as the cards add algorithms. */ if (!smartcard || (smartcard && hint.digest_length==20)) if ( (algo= select_algo_from_prefs(pk_list,PREFTYPE_HASH,-1,&hint)) > 0) recipient_digest_algo=algo; } } for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { PKT_secret_key *sk = sk_rover->sk; gcry_md_enable (mfx.md, hash_for(sk)); } if( !multifile ) iobuf_push_filter( inp, md_filter, &mfx ); if( detached && !encryptflag && !RFC1991 ) afx->what = 2; if( opt.armor && !outfile ) push_armor_filter (afx, out); if( encryptflag ) { efx.pk_list = pk_list; /* fixme: set efx.cfx.datalen if known */ iobuf_push_filter( out, encrypt_filter, &efx ); } if( opt.compress_algo && !outfile && ( !detached || opt.compress_sigs) ) { int compr_algo=opt.compress_algo; /* If not forced by user */ if(compr_algo==-1) { /* If we're not encrypting, then select_algo_from_prefs will fail and we'll end up with the default. If we are encrypting, select_algo_from_prefs cannot fail since there is an assumed preference for uncompressed data. Still, if it did fail, we'll also end up with the default. */ if((compr_algo= select_algo_from_prefs(pk_list,PREFTYPE_ZIP,-1,NULL))==-1) compr_algo=default_compress_algo(); } else if(!opt.expert && pk_list && select_algo_from_prefs(pk_list,PREFTYPE_ZIP, compr_algo,NULL)!=compr_algo) log_info(_("WARNING: forcing compression algorithm %s (%d)" " violates recipient preferences\n"), compress_algo_to_string(compr_algo),compr_algo); /* algo 0 means no compression */ if( compr_algo ) push_compress_filter(out,&zfx,compr_algo); } /* Write the one-pass signature packets if needed */ if (!detached && !RFC1991) { rc = write_onepass_sig_packets (sk_list, out, opt.textmode && !outfile ? 0x01:0x00); if (rc) goto leave; } write_status_begin_signing (mfx.md); /* Setup the inner packet. */ if( detached ) { if( multifile ) { strlist_t sl; if( opt.verbose ) log_info(_("signing:") ); /* must walk reverse trough this list */ for( sl = strlist_last(filenames); sl; sl = strlist_prev( filenames, sl ) ) { inp = iobuf_open(sl->d); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; errno = EPERM; } if( !inp ) { rc = gpg_error_from_syserror (); log_error(_("can't open `%s': %s\n"), sl->d,strerror(errno)); goto leave; } handle_progress (pfx, inp, sl->d); if( opt.verbose ) fprintf(stderr, " `%s'", sl->d ); if(opt.textmode) { memset( &tfx, 0, sizeof tfx); iobuf_push_filter( inp, text_filter, &tfx ); } iobuf_push_filter( inp, md_filter, &mfx ); while( iobuf_get(inp) != -1 ) ; iobuf_close(inp); inp = NULL; } if( opt.verbose ) putc( '\n', stderr ); } else { /* read, so that the filter can calculate the digest */ while( iobuf_get(inp) != -1 ) ; } } else { rc = write_plaintext_packet (out, inp, fname, opt.textmode && !outfile ? 't':'b'); } /* catch errors from above */ if (rc) goto leave; /* write the signatures */ rc = write_signature_packets (sk_list, out, mfx.md, opt.textmode && !outfile? 0x01 : 0x00, 0, duration, detached ? 'D':'S'); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else { iobuf_close(out); if (encryptflag) write_status( STATUS_END_ENCRYPTION ); } iobuf_close(inp); gcry_md_close ( mfx.md ); release_sk_list( sk_list ); release_pk_list( pk_list ); recipient_digest_algo=0; release_progress_context (pfx); release_armor_context (afx); return rc; } /**************** * make a clear signature. note that opt.armor is not needed */ int clearsign_file( const char *fname, strlist_t locusr, const char *outfile ) { armor_filter_context_t *afx; progress_filter_context_t *pfx; gcry_md_hd_t textmd = NULL; IOBUF inp = NULL, out = NULL; PACKET pkt; int rc = 0; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; int old_style = RFC1991; int only_md5 = 0; u32 duration=0; pfx = new_progress_context (); afx = new_armor_context (); init_packet( &pkt ); if(!opt.force_v3_sigs && !RFC1991) { if(opt.ask_sig_expire && !opt.batch) duration=ask_expire_interval(1,opt.def_sig_expire); else duration=parse_expire_string(opt.def_sig_expire); } if( (rc=build_sk_list( locusr, &sk_list, 1, PUBKEY_USAGE_SIG )) ) goto leave; if( !old_style && !duration ) old_style = only_old_style( sk_list ); if(PGP2 && !only_old_style(sk_list)) { log_info(_("you can only clearsign with PGP 2.x style keys " "while in --pgp2 mode\n")); compliance_failure(); } /* prepare iobufs */ inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; errno = EPERM; } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); if( outfile ) { if (is_secured_filename (outfile) ) { outfile = NULL; errno = EPERM; } else out = iobuf_create( outfile ); if( !out ) { rc = gpg_error_from_syserror (); log_error(_("can't create `%s': %s\n"), outfile, strerror(errno) ); goto leave; } else if( opt.verbose ) log_info(_("writing to `%s'\n"), outfile ); } else if( (rc = open_outfile( fname, 1, &out )) ) goto leave; iobuf_writestr(out, "-----BEGIN PGP SIGNED MESSAGE-----" LF ); for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { PKT_secret_key *sk = sk_rover->sk; if( hash_for(sk) == DIGEST_ALGO_MD5 ) only_md5 = 1; else { only_md5 = 0; break; } } if( !(old_style && only_md5) ) { const char *s; int any = 0; byte hashs_seen[256]; memset( hashs_seen, 0, sizeof hashs_seen ); iobuf_writestr(out, "Hash: " ); for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { PKT_secret_key *sk = sk_rover->sk; int i = hash_for(sk); if( !hashs_seen[ i & 0xff ] ) { s = gcry_md_algo_name ( i ); if( s ) { hashs_seen[ i & 0xff ] = 1; if( any ) iobuf_put(out, ',' ); iobuf_writestr(out, s ); any = 1; } } } assert(any); iobuf_writestr(out, LF ); } if( opt.not_dash_escaped ) iobuf_writestr( out, "NotDashEscaped: You need GnuPG to verify this message" LF ); iobuf_writestr(out, LF ); if ( gcry_md_open (&textmd, 0, 0) ) BUG (); for( sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next ) { PKT_secret_key *sk = sk_rover->sk; gcry_md_enable (textmd, hash_for(sk)); } if ( DBG_HASHING ) gcry_md_debug ( textmd, "clearsign" ); copy_clearsig_text( out, inp, textmd, !opt.not_dash_escaped, opt.escape_from, (old_style && only_md5) ); /* fixme: check for read errors */ /* now write the armor */ afx->what = 2; push_armor_filter (afx, out); /* write the signatures */ rc=write_signature_packets (sk_list, out, textmd, 0x01, 0, duration, 'C'); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else iobuf_close(out); iobuf_close(inp); gcry_md_close ( textmd ); release_sk_list( sk_list ); release_progress_context (pfx); release_armor_context (afx); return rc; } /* * Sign and conventionally encrypt the given file. * FIXME: Far too much code is duplicated - revamp the whole file. */ int sign_symencrypt_file (const char *fname, strlist_t locusr) { armor_filter_context_t *afx; progress_filter_context_t *pfx; compress_filter_context_t zfx; md_filter_context_t mfx; text_filter_context_t tfx; cipher_filter_context_t cfx; IOBUF inp = NULL, out = NULL; PACKET pkt; STRING2KEY *s2k = NULL; int rc = 0; SK_LIST sk_list = NULL; SK_LIST sk_rover = NULL; int algo; u32 duration=0; int canceled; pfx = new_progress_context (); afx = new_armor_context (); memset( &zfx, 0, sizeof zfx); memset( &mfx, 0, sizeof mfx); memset( &tfx, 0, sizeof tfx); memset( &cfx, 0, sizeof cfx); init_packet( &pkt ); if(!opt.force_v3_sigs && !RFC1991) { if(opt.ask_sig_expire && !opt.batch) duration=ask_expire_interval(1,opt.def_sig_expire); else duration=parse_expire_string(opt.def_sig_expire); } rc = build_sk_list (locusr, &sk_list, 1, PUBKEY_USAGE_SIG); if (rc) goto leave; /* prepare iobufs */ inp = iobuf_open(fname); if (inp && is_secured_file (iobuf_get_fd (inp))) { iobuf_close (inp); inp = NULL; errno = EPERM; } if( !inp ) { rc = gpg_error_from_syserror (); log_error (_("can't open `%s': %s\n"), fname? fname: "[stdin]", strerror(errno) ); goto leave; } handle_progress (pfx, inp, fname); /* prepare key */ s2k = xmalloc_clear( sizeof *s2k ); s2k->mode = RFC1991? 0:opt.s2k_mode; s2k->hash_algo = S2K_DIGEST_ALGO; algo = default_cipher_algo(); if (!opt.quiet || !opt.batch) log_info (_("%s encryption will be used\n"), openpgp_cipher_algo_name (algo) ); cfx.dek = passphrase_to_dek( NULL, 0, algo, s2k, 2, NULL, &canceled); if (!cfx.dek || !cfx.dek->keylen) { rc = gpg_error (canceled?GPG_ERR_CANCELED:GPG_ERR_BAD_PASSPHRASE); log_error(_("error creating passphrase: %s\n"), gpg_strerror (rc) ); goto leave; } /* We have no way to tell if the recipient can handle messages with an MDC, so this defaults to no. Perhaps in a few years, this can be defaulted to yes. Note that like regular encrypting, --force-mdc overrides --disable-mdc. */ if(opt.force_mdc) cfx.dek->use_mdc=1; /* now create the outfile */ rc = open_outfile (fname, opt.armor? 1:0, &out); if (rc) goto leave; /* prepare to calculate the MD over the input */ if (opt.textmode) iobuf_push_filter (inp, text_filter, &tfx); if ( gcry_md_open (&mfx.md, 0, 0) ) BUG (); if ( DBG_HASHING ) gcry_md_debug (mfx.md, "symc-sign"); for (sk_rover = sk_list; sk_rover; sk_rover = sk_rover->next) { PKT_secret_key *sk = sk_rover->sk; gcry_md_enable (mfx.md, hash_for (sk)); } iobuf_push_filter (inp, md_filter, &mfx); /* Push armor output filter */ if (opt.armor) push_armor_filter (afx, out); /* Write the symmetric key packet */ /*(current filters: armor)*/ if (!RFC1991) { PKT_symkey_enc *enc = xmalloc_clear( sizeof *enc ); enc->version = 4; enc->cipher_algo = cfx.dek->algo; enc->s2k = *s2k; pkt.pkttype = PKT_SYMKEY_ENC; pkt.pkt.symkey_enc = enc; if( (rc = build_packet( out, &pkt )) ) log_error("build symkey packet failed: %s\n", g10_errstr(rc) ); xfree(enc); } /* Push the encryption filter */ iobuf_push_filter( out, cipher_filter, &cfx ); /* Push the compress filter */ if (default_compress_algo()) push_compress_filter(out,&zfx,default_compress_algo()); /* Write the one-pass signature packets */ /*(current filters: zip - encrypt - armor)*/ if (!RFC1991) { rc = write_onepass_sig_packets (sk_list, out, opt.textmode? 0x01:0x00); if (rc) goto leave; } write_status_begin_signing (mfx.md); /* Pipe data through all filters; i.e. write the signed stuff */ /*(current filters: zip - encrypt - armor)*/ rc = write_plaintext_packet (out, inp, fname, opt.textmode ? 't':'b'); if (rc) goto leave; /* Write the signatures */ /*(current filters: zip - encrypt - armor)*/ rc = write_signature_packets (sk_list, out, mfx.md, opt.textmode? 0x01 : 0x00, 0, duration, 'S'); if( rc ) goto leave; leave: if( rc ) iobuf_cancel(out); else { iobuf_close(out); write_status( STATUS_END_ENCRYPTION ); } iobuf_close(inp); release_sk_list( sk_list ); gcry_md_close( mfx.md ); xfree(cfx.dek); xfree(s2k); release_progress_context (pfx); release_armor_context (afx); return rc; } /**************** * Create a signature packet for the given public key certificate and * the user id and return it in ret_sig. User signature class SIGCLASS * user-id is not used (and may be NULL if sigclass is 0x20) If * DIGEST_ALGO is 0 the function selects an appropriate one. * SIGVERSION gives the minimal required signature packet version; * this is needed so that special properties like local sign are not * applied (actually: dropped) when a v3 key is used. TIMESTAMP is * the timestamp to use for the signature. 0 means "now" */ int make_keysig_packet( PKT_signature **ret_sig, PKT_public_key *pk, PKT_user_id *uid, PKT_public_key *subpk, PKT_secret_key *sk, int sigclass, int digest_algo, int sigversion, u32 timestamp, u32 duration, int (*mksubpkt)(PKT_signature *, void *), void *opaque ) { PKT_signature *sig; int rc=0; gcry_md_hd_t md; assert( (sigclass >= 0x10 && sigclass <= 0x13) || sigclass == 0x1F || sigclass == 0x20 || sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x30 || sigclass == 0x28 ); if (opt.force_v4_certs) sigversion = 4; if (sigversion < sk->version) sigversion = sk->version; /* If you are making a signature on a v4 key using your v3 key, it doesn't make sense to generate a v3 sig. After all, no v3-only PGP implementation could understand the v4 key in the first place. Note that this implies that a signature on an attribute uid is usually going to be v4 as well, since they are not generally found on v3 keys. */ if (sigversion < pk->version) sigversion = pk->version; if( !digest_algo ) { /* Basically, this means use SHA1 always unless it's a v3 RSA key making a v3 cert (use MD5), or the user specified something (use whatever they said), or it's DSA (use the best match). They still can't pick an inappropriate hash for DSA or the signature will fail. Note that this still allows the caller of make_keysig_packet to override the user setting if it must. */ if(opt.cert_digest_algo) digest_algo=opt.cert_digest_algo; else if(sk->pubkey_algo==PUBKEY_ALGO_RSA && pk->version<4 && sigversion<4) digest_algo = DIGEST_ALGO_MD5; else if(sk->pubkey_algo==PUBKEY_ALGO_DSA) digest_algo = match_dsa_hash (gcry_mpi_get_nbits (sk->skey[1])/8); else digest_algo = DIGEST_ALGO_SHA1; } if ( gcry_md_open (&md, digest_algo, 0 ) ) BUG (); /* Hash the public key certificate. */ hash_public_key( md, pk ); if( sigclass == 0x18 || sigclass == 0x19 || sigclass == 0x28 ) { /* hash the subkey binding/backsig/revocation */ hash_public_key( md, subpk ); } else if( sigclass != 0x1F && sigclass != 0x20 ) { /* hash the user id */ hash_uid (md, sigversion, uid); } /* and make the signature packet */ sig = xmalloc_clear( sizeof *sig ); sig->version = sigversion; sig->flags.exportable=1; sig->flags.revocable=1; keyid_from_sk( sk, sig->keyid ); sig->pubkey_algo = sk->pubkey_algo; sig->digest_algo = digest_algo; if(timestamp) sig->timestamp=timestamp; else sig->timestamp=make_timestamp(); if(duration) sig->expiredate=sig->timestamp+duration; sig->sig_class = sigclass; if( sig->version >= 4 ) { build_sig_subpkt_from_sig( sig ); mk_notation_policy_etc( sig, pk, sk ); } /* Crucial that the call to mksubpkt comes LAST before the calls to finalize the sig as that makes it possible for the mksubpkt function to get a reliable pointer to the subpacket area. */ if( sig->version >= 4 && mksubpkt ) rc = (*mksubpkt)( sig, opaque ); if( !rc ) { hash_sigversion_to_magic (md, sig); gcry_md_final (md); rc = complete_sig( sig, sk, md ); } gcry_md_close ( md ); if( rc ) free_seckey_enc( sig ); else *ret_sig = sig; return rc; } /**************** * Create a new signature packet based on an existing one. * Only user ID signatures are supported for now. * TODO: Merge this with make_keysig_packet. */ int update_keysig_packet( PKT_signature **ret_sig, PKT_signature *orig_sig, PKT_public_key *pk, PKT_user_id *uid, PKT_public_key *subpk, PKT_secret_key *sk, int (*mksubpkt)(PKT_signature *, void *), void *opaque ) { PKT_signature *sig; int rc = 0; int digest_algo; gcry_md_hd_t md; if ((!orig_sig || !pk || !sk) || (orig_sig->sig_class >= 0x10 && orig_sig->sig_class <= 0x13 && !uid) || (orig_sig->sig_class == 0x18 && !subpk)) return G10ERR_GENERAL; if ( opt.cert_digest_algo ) digest_algo = opt.cert_digest_algo; else digest_algo = orig_sig->digest_algo; if ( gcry_md_open (&md, digest_algo, 0 ) ) BUG (); /* Hash the public key certificate and the user id. */ hash_public_key( md, pk ); if( orig_sig->sig_class == 0x18 ) hash_public_key( md, subpk ); else hash_uid (md, orig_sig->version, uid); /* create a new signature packet */ sig = copy_signature (NULL, orig_sig); sig->digest_algo=digest_algo; /* We need to create a new timestamp so that new sig expiration calculations are done correctly... */ sig->timestamp=make_timestamp(); /* ... but we won't make a timestamp earlier than the existing one. */ while(sig->timestamp<=orig_sig->timestamp) { gnupg_sleep (1); sig->timestamp=make_timestamp(); } /* Note that already expired sigs will remain expired (with a duration of 1) since build-packet.c:build_sig_subpkt_from_sig detects this case. */ if( sig->version >= 4 ) { /* Put the updated timestamp into the sig. Note that this will automagically lower any sig expiration dates to correctly correspond to the differences in the timestamps (i.e. the duration will shrink). */ build_sig_subpkt_from_sig( sig ); if (mksubpkt) rc = (*mksubpkt)(sig, opaque); } if (!rc) { hash_sigversion_to_magic (md, sig); gcry_md_final (md); rc = complete_sig( sig, sk, md ); } gcry_md_close (md); if( rc ) free_seckey_enc (sig); else *ret_sig = sig; return rc; }
239029.c
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.40 * * This file is not intended to be easily readable and contains a number of * coding conventions designed to improve portability and efficiency. Do not make * changes to this file unless you know what you are doing--modify the SWIG * interface file instead. * ----------------------------------------------------------------------------- */ #define SWIGTCL /* ----------------------------------------------------------------------------- * This section contains generic SWIG labels for method/variable * declarations/attributes, and other compiler dependent labels. * ----------------------------------------------------------------------------- */ /* template workaround for compilers that cannot correctly implement the C++ standard */ #ifndef SWIGTEMPLATEDISAMBIGUATOR # if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560) # define SWIGTEMPLATEDISAMBIGUATOR template # elif defined(__HP_aCC) /* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */ /* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */ # define SWIGTEMPLATEDISAMBIGUATOR template # else # define SWIGTEMPLATEDISAMBIGUATOR # endif #endif /* inline attribute */ #ifndef SWIGINLINE # if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__)) # define SWIGINLINE inline # else # define SWIGINLINE # endif #endif /* attribute recognised by some compilers to avoid 'unused' warnings */ #ifndef SWIGUNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif # elif defined(__ICC) # define SWIGUNUSED __attribute__ ((__unused__)) # else # define SWIGUNUSED # endif #endif #ifndef SWIG_MSC_UNSUPPRESS_4505 # if defined(_MSC_VER) # pragma warning(disable : 4505) /* unreferenced local function has been removed */ # endif #endif #ifndef SWIGUNUSEDPARM # ifdef __cplusplus # define SWIGUNUSEDPARM(p) # else # define SWIGUNUSEDPARM(p) p SWIGUNUSED # endif #endif /* internal SWIG method */ #ifndef SWIGINTERN # define SWIGINTERN static SWIGUNUSED #endif /* internal inline SWIG method */ #ifndef SWIGINTERNINLINE # define SWIGINTERNINLINE SWIGINTERN SWIGINLINE #endif /* exporting methods */ #if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) # ifndef GCC_HASCLASSVISIBILITY # define GCC_HASCLASSVISIBILITY # endif #endif #ifndef SWIGEXPORT # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # if defined(STATIC_LINKED) # define SWIGEXPORT # else # define SWIGEXPORT __declspec(dllexport) # endif # else # if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY) # define SWIGEXPORT __attribute__ ((visibility("default"))) # else # define SWIGEXPORT # endif # endif #endif /* calling conventions for Windows */ #ifndef SWIGSTDCALL # if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) # define SWIGSTDCALL __stdcall # else # define SWIGSTDCALL # endif #endif /* Deal with Microsoft's attempt at deprecating C standard runtime functions */ #if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) # define _CRT_SECURE_NO_DEPRECATE #endif /* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */ #if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE) # define _SCL_SECURE_NO_DEPRECATE #endif #include <stdio.h> #include <tcl.h> #include <errno.h> #include <stdlib.h> #include <stdarg.h> #include <ctype.h> /* ----------------------------------------------------------------------------- * swigrun.swg * * This file contains generic C API SWIG runtime support for pointer * type checking. * ----------------------------------------------------------------------------- */ /* This should only be incremented when either the layout of swig_type_info changes, or for whatever reason, the runtime changes incompatibly */ #define SWIG_RUNTIME_VERSION "4" /* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */ #ifdef SWIG_TYPE_TABLE # define SWIG_QUOTE_STRING(x) #x # define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x) # define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE) #else # define SWIG_TYPE_TABLE_NAME #endif /* You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for creating a static or dynamic library from the SWIG runtime code. In 99.9% of the cases, SWIG just needs to declare them as 'static'. But only do this if strictly necessary, ie, if you have problems with your compiler or suchlike. */ #ifndef SWIGRUNTIME # define SWIGRUNTIME SWIGINTERN #endif #ifndef SWIGRUNTIMEINLINE # define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE #endif /* Generic buffer size */ #ifndef SWIG_BUFFER_SIZE # define SWIG_BUFFER_SIZE 1024 #endif /* Flags for pointer conversions */ #define SWIG_POINTER_DISOWN 0x1 #define SWIG_CAST_NEW_MEMORY 0x2 /* Flags for new pointer objects */ #define SWIG_POINTER_OWN 0x1 /* Flags/methods for returning states. The SWIG conversion methods, as ConvertPtr, return and integer that tells if the conversion was successful or not. And if not, an error code can be returned (see swigerrors.swg for the codes). Use the following macros/flags to set or process the returning states. In old versions of SWIG, code such as the following was usually written: if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) { // success code } else { //fail code } Now you can be more explicit: int res = SWIG_ConvertPtr(obj,vptr,ty.flags); if (SWIG_IsOK(res)) { // success code } else { // fail code } which is the same really, but now you can also do Type *ptr; int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags); if (SWIG_IsOK(res)) { // success code if (SWIG_IsNewObj(res) { ... delete *ptr; } else { ... } } else { // fail code } I.e., now SWIG_ConvertPtr can return new objects and you can identify the case and take care of the deallocation. Of course that also requires SWIG_ConvertPtr to return new result values, such as int SWIG_ConvertPtr(obj, ptr,...) { if (<obj is ok>) { if (<need new object>) { *ptr = <ptr to new allocated object>; return SWIG_NEWOBJ; } else { *ptr = <ptr to old object>; return SWIG_OLDOBJ; } } else { return SWIG_BADOBJ; } } Of course, returning the plain '0(success)/-1(fail)' still works, but you can be more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the SWIG errors code. Finally, if the SWIG_CASTRANK_MODE is enabled, the result code allows to return the 'cast rank', for example, if you have this int food(double) int fooi(int); and you call food(1) // cast rank '1' (1 -> 1.0) fooi(1) // cast rank '0' just use the SWIG_AddCast()/SWIG_CheckState() */ #define SWIG_OK (0) #define SWIG_ERROR (-1) #define SWIG_IsOK(r) (r >= 0) #define SWIG_ArgError(r) ((r != SWIG_ERROR) ? r : SWIG_TypeError) /* The CastRankLimit says how many bits are used for the cast rank */ #define SWIG_CASTRANKLIMIT (1 << 8) /* The NewMask denotes the object was created (using new/malloc) */ #define SWIG_NEWOBJMASK (SWIG_CASTRANKLIMIT << 1) /* The TmpMask is for in/out typemaps that use temporal objects */ #define SWIG_TMPOBJMASK (SWIG_NEWOBJMASK << 1) /* Simple returning values */ #define SWIG_BADOBJ (SWIG_ERROR) #define SWIG_OLDOBJ (SWIG_OK) #define SWIG_NEWOBJ (SWIG_OK | SWIG_NEWOBJMASK) #define SWIG_TMPOBJ (SWIG_OK | SWIG_TMPOBJMASK) /* Check, add and del mask methods */ #define SWIG_AddNewMask(r) (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r) #define SWIG_DelNewMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r) #define SWIG_IsNewObj(r) (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK)) #define SWIG_AddTmpMask(r) (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r) #define SWIG_DelTmpMask(r) (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r) #define SWIG_IsTmpObj(r) (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK)) /* Cast-Rank Mode */ #if defined(SWIG_CASTRANK_MODE) # ifndef SWIG_TypeRank # define SWIG_TypeRank unsigned long # endif # ifndef SWIG_MAXCASTRANK /* Default cast allowed */ # define SWIG_MAXCASTRANK (2) # endif # define SWIG_CASTRANKMASK ((SWIG_CASTRANKLIMIT) -1) # define SWIG_CastRank(r) (r & SWIG_CASTRANKMASK) SWIGINTERNINLINE int SWIG_AddCast(int r) { return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r; } SWIGINTERNINLINE int SWIG_CheckState(int r) { return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; } #else /* no cast-rank mode */ # define SWIG_AddCast # define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0) #endif #include <string.h> #ifdef __cplusplus extern "C" { #endif typedef void *(*swig_converter_func)(void *, int *); typedef struct swig_type_info *(*swig_dycast_func)(void **); /* Structure to store information on one type */ typedef struct swig_type_info { const char *name; /* mangled name of this type */ const char *str; /* human readable name of this type */ swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ struct swig_cast_info *cast; /* linked list of types that can cast into this type */ void *clientdata; /* language specific type data */ int owndata; /* flag if the structure owns the clientdata */ } swig_type_info; /* Structure to store a type and conversion function used for casting */ typedef struct swig_cast_info { swig_type_info *type; /* pointer to type that is equivalent to this type */ swig_converter_func converter; /* function to cast the void pointers */ struct swig_cast_info *next; /* pointer to next cast in linked list */ struct swig_cast_info *prev; /* pointer to the previous cast */ } swig_cast_info; /* Structure used to store module information * Each module generates one structure like this, and the runtime collects * all of these structures and stores them in a circularly linked list.*/ typedef struct swig_module_info { swig_type_info **types; /* Array of pointers to swig_type_info structures that are in this module */ size_t size; /* Number of types in this module */ struct swig_module_info *next; /* Pointer to next element in circularly linked list */ swig_type_info **type_initial; /* Array of initially generated type structures */ swig_cast_info **cast_initial; /* Array of initially generated casting structures */ void *clientdata; /* Language specific module data */ } swig_module_info; /* Compare two type names skipping the space characters, therefore "char*" == "char *" and "Class<int>" == "Class<int >", etc. Return 0 when the two name types are equivalent, as in strncmp, but skipping ' '. */ SWIGRUNTIME int SWIG_TypeNameComp(const char *f1, const char *l1, const char *f2, const char *l2) { for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) { while ((*f1 == ' ') && (f1 != l1)) ++f1; while ((*f2 == ' ') && (f2 != l2)) ++f2; if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1; } return (int)((l1 - f1) - (l2 - f2)); } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if not equal, 1 if equal */ SWIGRUNTIME int SWIG_TypeEquiv(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check type equivalence in a name list like <name1>|<name2>|... Return 0 if equal, -1 if nb < tb, 1 if nb > tb */ SWIGRUNTIME int SWIG_TypeCompare(const char *nb, const char *tb) { int equiv = 0; const char* te = tb + strlen(tb); const char* ne = nb; while (!equiv && *ne) { for (nb = ne; *ne; ++ne) { if (*ne == '|') break; } equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0; if (*ne) ++ne; } return equiv; } /* Check the typename */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheck(const char *c, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (strcmp(iter->type->name, c) == 0) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Identical to SWIG_TypeCheck, except strcmp is replaced with a pointer comparison */ SWIGRUNTIME swig_cast_info * SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *ty) { if (ty) { swig_cast_info *iter = ty->cast; while (iter) { if (iter->type == from) { if (iter == ty->cast) return iter; /* Move iter to the top of the linked list */ iter->prev->next = iter->next; if (iter->next) iter->next->prev = iter->prev; iter->next = ty->cast; iter->prev = 0; if (ty->cast) ty->cast->prev = iter; ty->cast = iter; return iter; } iter = iter->next; } } return 0; } /* Cast a pointer up an inheritance hierarchy */ SWIGRUNTIMEINLINE void * SWIG_TypeCast(swig_cast_info *ty, void *ptr, int *newmemory) { return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr, newmemory); } /* Dynamic pointer casting. Down an inheritance hierarchy */ SWIGRUNTIME swig_type_info * SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) { swig_type_info *lastty = ty; if (!ty || !ty->dcast) return ty; while (ty && (ty->dcast)) { ty = (*ty->dcast)(ptr); if (ty) lastty = ty; } return lastty; } /* Return the name associated with this type */ SWIGRUNTIMEINLINE const char * SWIG_TypeName(const swig_type_info *ty) { return ty->name; } /* Return the pretty name associated with this type, that is an unmangled type name in a form presentable to the user. */ SWIGRUNTIME const char * SWIG_TypePrettyName(const swig_type_info *type) { /* The "str" field contains the equivalent pretty names of the type, separated by vertical-bar characters. We choose to print the last name, as it is often (?) the most specific. */ if (!type) return NULL; if (type->str != NULL) { const char *last_name = type->str; const char *s; for (s = type->str; *s; s++) if (*s == '|') last_name = s+1; return last_name; } else return type->name; } /* Set the clientdata field for a type */ SWIGRUNTIME void SWIG_TypeClientData(swig_type_info *ti, void *clientdata) { swig_cast_info *cast = ti->cast; /* if (ti->clientdata == clientdata) return; */ ti->clientdata = clientdata; while (cast) { if (!cast->converter) { swig_type_info *tc = cast->type; if (!tc->clientdata) { SWIG_TypeClientData(tc, clientdata); } } cast = cast->next; } } SWIGRUNTIME void SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) { SWIG_TypeClientData(ti, clientdata); ti->owndata = 1; } /* Search for a swig_type_info structure only by mangled name Search is a O(log #types) We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_MangledTypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { swig_module_info *iter = start; do { if (iter->size) { register size_t l = 0; register size_t r = iter->size - 1; do { /* since l+r >= 0, we can (>> 1) instead (/ 2) */ register size_t i = (l + r) >> 1; const char *iname = iter->types[i]->name; if (iname) { register int compare = strcmp(name, iname); if (compare == 0) { return iter->types[i]; } else if (compare < 0) { if (i) { r = i - 1; } else { break; } } else if (compare > 0) { l = i + 1; } } else { break; /* should never happen */ } } while (l <= r); } iter = iter->next; } while (iter != end); return 0; } /* Search for a swig_type_info structure for either a mangled name or a human readable name. It first searches the mangled names of the types, which is a O(log #types) If a type is not found it then searches the human readable names, which is O(#types). We start searching at module start, and finish searching when start == end. Note: if start == end at the beginning of the function, we go all the way around the circular list. */ SWIGRUNTIME swig_type_info * SWIG_TypeQueryModule(swig_module_info *start, swig_module_info *end, const char *name) { /* STEP 1: Search the name field using binary search */ swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name); if (ret) { return ret; } else { /* STEP 2: If the type hasn't been found, do a complete search of the str field (the human readable name) */ swig_module_info *iter = start; do { register size_t i = 0; for (; i < iter->size; ++i) { if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name))) return iter->types[i]; } iter = iter->next; } while (iter != end); } /* neither found a match */ return 0; } /* Pack binary data into a string */ SWIGRUNTIME char * SWIG_PackData(char *c, void *ptr, size_t sz) { static const char hex[17] = "0123456789abcdef"; register const unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register unsigned char uu = *u; *(c++) = hex[(uu & 0xf0) >> 4]; *(c++) = hex[uu & 0xf]; } return c; } /* Unpack binary data from a string */ SWIGRUNTIME const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { register unsigned char *u = (unsigned char *) ptr; register const unsigned char *eu = u + sz; for (; u != eu; ++u) { register char d = *(c++); register unsigned char uu; if ((d >= '0') && (d <= '9')) uu = ((d - '0') << 4); else if ((d >= 'a') && (d <= 'f')) uu = ((d - ('a'-10)) << 4); else return (char *) 0; d = *(c++); if ((d >= '0') && (d <= '9')) uu |= (d - '0'); else if ((d >= 'a') && (d <= 'f')) uu |= (d - ('a'-10)); else return (char *) 0; *u = uu; } return c; } /* Pack 'void *' into a string buffer. */ SWIGRUNTIME char * SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) { char *r = buff; if ((2*sizeof(void *) + 2) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,&ptr,sizeof(void *)); if (strlen(name) + 1 > (bsz - (r - buff))) return 0; strcpy(r,name); return buff; } SWIGRUNTIME const char * SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { *ptr = (void *) 0; return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sizeof(void *)); } SWIGRUNTIME char * SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) { char *r = buff; size_t lname = (name ? strlen(name) : 0); if ((2*sz + 2 + lname) > bsz) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); if (lname) { strncpy(r,name,lname+1); } else { *r = 0; } return buff; } SWIGRUNTIME const char * SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) { if (*c != '_') { if (strcmp(c,"NULL") == 0) { memset(ptr,0,sz); return name; } else { return 0; } } return SWIG_UnpackData(++c,ptr,sz); } #ifdef __cplusplus } #endif /* Errors in SWIG */ #define SWIG_UnknownError -1 #define SWIG_IOError -2 #define SWIG_RuntimeError -3 #define SWIG_IndexError -4 #define SWIG_TypeError -5 #define SWIG_DivisionByZero -6 #define SWIG_OverflowError -7 #define SWIG_SyntaxError -8 #define SWIG_ValueError -9 #define SWIG_SystemError -10 #define SWIG_AttributeError -11 #define SWIG_MemoryError -12 #define SWIG_NullReferenceError -13 /* ----------------------------------------------------------------------------- * error manipulation * ----------------------------------------------------------------------------- */ SWIGINTERN const char* SWIG_Tcl_ErrorType(int code) { const char* type = 0; switch(code) { case SWIG_MemoryError: type = "MemoryError"; break; case SWIG_IOError: type = "IOError"; break; case SWIG_RuntimeError: type = "RuntimeError"; break; case SWIG_IndexError: type = "IndexError"; break; case SWIG_TypeError: type = "TypeError"; break; case SWIG_DivisionByZero: type = "ZeroDivisionError"; break; case SWIG_OverflowError: type = "OverflowError"; break; case SWIG_SyntaxError: type = "SyntaxError"; break; case SWIG_ValueError: type = "ValueError"; break; case SWIG_SystemError: type = "SystemError"; break; case SWIG_AttributeError: type = "AttributeError"; break; default: type = "RuntimeError"; } return type; } SWIGINTERN void SWIG_Tcl_SetErrorObj(Tcl_Interp *interp, const char *ctype, Tcl_Obj *obj) { Tcl_ResetResult(interp); Tcl_SetObjResult(interp, obj); Tcl_SetErrorCode(interp, "SWIG", ctype, NULL); } SWIGINTERN void SWIG_Tcl_SetErrorMsg(Tcl_Interp *interp, const char *ctype, const char *mesg) { Tcl_ResetResult(interp); Tcl_SetErrorCode(interp, "SWIG", ctype, NULL); Tcl_AppendResult(interp, ctype, " ", mesg, NULL); /* Tcl_AddErrorInfo(interp, ctype); Tcl_AddErrorInfo(interp, " "); Tcl_AddErrorInfo(interp, mesg); */ } SWIGINTERNINLINE void SWIG_Tcl_AddErrorMsg(Tcl_Interp *interp, const char* mesg) { Tcl_AddErrorInfo(interp, mesg); } /* ----------------------------------------------------------------------------- * SWIG API. Portion that goes into the runtime * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * Constant declarations * ----------------------------------------------------------------------------- */ /* Constant Types */ #define SWIG_TCL_POINTER 4 #define SWIG_TCL_BINARY 5 /* Constant information structure */ typedef struct swig_const_info { int type; char *name; long lvalue; double dvalue; void *pvalue; swig_type_info **ptype; } swig_const_info; typedef int (*swig_wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); typedef int (*swig_wrapper_func)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); typedef char *(*swig_variable_func)(ClientData, Tcl_Interp *, char *, char *, int); typedef void (*swig_delete_func)(ClientData); typedef struct swig_method { const char *name; swig_wrapper method; } swig_method; typedef struct swig_attribute { const char *name; swig_wrapper getmethod; swig_wrapper setmethod; } swig_attribute; typedef struct swig_class { const char *name; swig_type_info **type; swig_wrapper constructor; void (*destructor)(void *); swig_method *methods; swig_attribute *attributes; struct swig_class **bases; const char **base_names; swig_module_info *module; } swig_class; typedef struct swig_instance { Tcl_Obj *thisptr; void *thisvalue; swig_class *classptr; int destroy; Tcl_Command cmdtok; } swig_instance; /* Structure for command table */ typedef struct { const char *name; int (*wrapper)(ClientData, Tcl_Interp *, int, Tcl_Obj *CONST []); ClientData clientdata; } swig_command_info; /* Structure for variable linking table */ typedef struct { const char *name; void *addr; char * (*get)(ClientData, Tcl_Interp *, char *, char *, int); char * (*set)(ClientData, Tcl_Interp *, char *, char *, int); } swig_var_info; /* -----------------------------------------------------------------------------* * Install a constant object * -----------------------------------------------------------------------------*/ static Tcl_HashTable swigconstTable; static int swigconstTableinit = 0; SWIGINTERN void SWIG_Tcl_SetConstantObj(Tcl_Interp *interp, const char* name, Tcl_Obj *obj) { int newobj; Tcl_ObjSetVar2(interp,Tcl_NewStringObj(name,-1), NULL, obj, TCL_GLOBAL_ONLY); Tcl_SetHashValue(Tcl_CreateHashEntry(&swigconstTable, name, &newobj), (ClientData) obj); } SWIGINTERN Tcl_Obj * SWIG_Tcl_GetConstantObj(const char *key) { Tcl_HashEntry *entryPtr; if (!swigconstTableinit) return 0; entryPtr = Tcl_FindHashEntry(&swigconstTable, key); if (entryPtr) { return (Tcl_Obj *) Tcl_GetHashValue(entryPtr); } return 0; } #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * See the LICENSE file for information on copyright, usage and redistribution * of SWIG, and the README file for authors - http://www.swig.org/release.html. * * tclrun.swg * * This file contains the runtime support for Tcl modules and includes * code for managing global variables and pointer type checking. * ----------------------------------------------------------------------------- */ /* Common SWIG API */ /* for raw pointers */ #define SWIG_ConvertPtr(oc, ptr, ty, flags) SWIG_Tcl_ConvertPtr(interp, oc, ptr, ty, flags) #define SWIG_NewPointerObj(ptr, type, flags) SWIG_Tcl_NewPointerObj(ptr, type, flags) /* for raw packed data */ #define SWIG_ConvertPacked(obj, ptr, sz, ty) SWIG_Tcl_ConvertPacked(interp, obj, ptr, sz, ty) #define SWIG_NewPackedObj(ptr, sz, type) SWIG_Tcl_NewPackedObj(ptr, sz, type) /* for class or struct pointers */ #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_Tcl_ConvertPtr(interp, obj, pptr, type, flags) #define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_Tcl_NewInstanceObj(interp, thisvalue, type, flags) /* for C or C++ function pointers */ #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_Tcl_ConvertPtr(interp, obj, pptr, type, 0) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_Tcl_NewPointerObj(ptr, type, 0) /* for C++ member pointers, ie, member methods */ #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_Tcl_ConvertPacked(interp,obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_Tcl_NewPackedObj(ptr, sz, type) /* Runtime API */ #define SWIG_GetModule(clientdata) SWIG_Tcl_GetModule((Tcl_Interp *) (clientdata)) #define SWIG_SetModule(clientdata, pointer) SWIG_Tcl_SetModule((Tcl_Interp *) (clientdata), pointer) /* Error manipulation */ #define SWIG_ErrorType(code) SWIG_Tcl_ErrorType(code) #define SWIG_Error(code, msg) SWIG_Tcl_SetErrorMsg(interp, SWIG_Tcl_ErrorType(code), msg) #define SWIG_fail goto fail /* Tcl-specific SWIG API */ #define SWIG_Acquire(ptr) SWIG_Tcl_Acquire(ptr) #define SWIG_MethodCommand SWIG_Tcl_MethodCommand #define SWIG_Disown(ptr) SWIG_Tcl_Disown(ptr) #define SWIG_ConvertPtrFromString(c, ptr, ty, flags) SWIG_Tcl_ConvertPtrFromString(interp, c, ptr, ty, flags) #define SWIG_MakePtr(c, ptr, ty, flags) SWIG_Tcl_MakePtr(c, ptr, ty, flags) #define SWIG_PointerTypeFromString(c) SWIG_Tcl_PointerTypeFromString(c) #define SWIG_GetArgs SWIG_Tcl_GetArgs #define SWIG_GetConstantObj(key) SWIG_Tcl_GetConstantObj(key) #define SWIG_ObjectConstructor SWIG_Tcl_ObjectConstructor #define SWIG_Thisown(ptr) SWIG_Tcl_Thisown(ptr) #define SWIG_ObjectDelete SWIG_Tcl_ObjectDelete #define SWIG_TCL_DECL_ARGS_2(arg1, arg2) (Tcl_Interp *interp SWIGUNUSED, arg1, arg2) #define SWIG_TCL_CALL_ARGS_2(arg1, arg2) (interp, arg1, arg2) /* ----------------------------------------------------------------------------- * pointers/data manipulation * ----------------------------------------------------------------------------- */ /* For backward compatibility only */ #define SWIG_POINTER_EXCEPTION 0 #define SWIG_GetConstant SWIG_GetConstantObj #define SWIG_Tcl_GetConstant SWIG_Tcl_GetConstantObj #include "assert.h" #ifdef __cplusplus extern "C" { #if 0 } /* cc-mode */ #endif #endif /* Object support */ SWIGRUNTIME Tcl_HashTable* SWIG_Tcl_ObjectTable(void) { static Tcl_HashTable swigobjectTable; static int swigobjectTableinit = 0; if (!swigobjectTableinit) { Tcl_InitHashTable(&swigobjectTable, TCL_ONE_WORD_KEYS); swigobjectTableinit = 1; } return &swigobjectTable; } /* Acquire ownership of a pointer */ SWIGRUNTIME void SWIG_Tcl_Acquire(void *ptr) { int newobj; Tcl_CreateHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr, &newobj); } SWIGRUNTIME int SWIG_Tcl_Thisown(void *ptr) { if (Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr)) { return 1; } return 0; } /* Disown a pointer. Returns 1 if we owned it to begin with */ SWIGRUNTIME int SWIG_Tcl_Disown(void *ptr) { Tcl_HashEntry *entryPtr = Tcl_FindHashEntry(SWIG_Tcl_ObjectTable(), (char *) ptr); if (entryPtr) { Tcl_DeleteHashEntry(entryPtr); return 1; } return 0; } /* Convert a pointer value */ SWIGRUNTIME int SWIG_Tcl_ConvertPtrFromString(Tcl_Interp *interp, const char *c, void **ptr, swig_type_info *ty, int flags) { swig_cast_info *tc; /* Pointer values must start with leading underscore */ while (*c != '_') { *ptr = (void *) 0; if (strcmp(c,"NULL") == 0) return SWIG_OK; /* Empty string: not a pointer */ if (*c == 0) return SWIG_ERROR; /* Hmmm. It could be an object name. */ /* Check if this is a command at all. Prevents <c> cget -this */ /* from being called when c is not a command, firing the unknown proc */ if (Tcl_VarEval(interp,"info commands ", c, (char *) NULL) == TCL_OK) { Tcl_Obj *result = Tcl_GetObjResult(interp); if (*(Tcl_GetStringFromObj(result, NULL)) == 0) { /* It's not a command, so it can't be a pointer */ Tcl_ResetResult(interp); return SWIG_ERROR; } } else { /* This will only fail if the argument is multiple words. */ /* Multiple words are also not commands. */ Tcl_ResetResult(interp); return SWIG_ERROR; } /* Check if this is really a SWIG pointer */ if (Tcl_VarEval(interp,c," cget -this", (char *) NULL) != TCL_OK) { Tcl_ResetResult(interp); return SWIG_ERROR; } c = Tcl_GetStringFromObj(Tcl_GetObjResult(interp), NULL); } c++; c = SWIG_UnpackData(c,ptr,sizeof(void *)); if (ty) { tc = c ? SWIG_TypeCheck(c,ty) : 0; if (!tc) { return SWIG_ERROR; } if (flags & SWIG_POINTER_DISOWN) { SWIG_Disown((void *) *ptr); } { int newmemory = 0; *ptr = SWIG_TypeCast(tc,(void *) *ptr,&newmemory); assert(!newmemory); /* newmemory handling not yet implemented */ } } return SWIG_OK; } /* Convert a pointer value */ SWIGRUNTIMEINLINE int SWIG_Tcl_ConvertPtr(Tcl_Interp *interp, Tcl_Obj *oc, void **ptr, swig_type_info *ty, int flags) { return SWIG_Tcl_ConvertPtrFromString(interp, Tcl_GetStringFromObj(oc,NULL), ptr, ty, flags); } /* Convert a pointer value */ SWIGRUNTIME char * SWIG_Tcl_PointerTypeFromString(char *c) { char d; /* Pointer values must start with leading underscore. NULL has no type */ if (*c != '_') { return 0; } c++; /* Extract hex value from pointer */ while ((d = *c)) { if (!(((d >= '0') && (d <= '9')) || ((d >= 'a') && (d <= 'f')))) break; c++; } return c; } /* Convert a packed value value */ SWIGRUNTIME int SWIG_Tcl_ConvertPacked(Tcl_Interp *SWIGUNUSEDPARM(interp) , Tcl_Obj *obj, void *ptr, int sz, swig_type_info *ty) { swig_cast_info *tc; const char *c; if (!obj) goto type_error; c = Tcl_GetStringFromObj(obj,NULL); /* Pointer values must start with leading underscore */ if (*c != '_') goto type_error; c++; c = SWIG_UnpackData(c,ptr,sz); if (ty) { tc = SWIG_TypeCheck(c,ty); if (!tc) goto type_error; } return SWIG_OK; type_error: return SWIG_ERROR; } /* Take a pointer and convert it to a string */ SWIGRUNTIME void SWIG_Tcl_MakePtr(char *c, void *ptr, swig_type_info *ty, int flags) { if (ptr) { *(c++) = '_'; c = SWIG_PackData(c,&ptr,sizeof(void *)); strcpy(c,ty->name); } else { strcpy(c,(char *)"NULL"); } flags = 0; } /* Create a new pointer object */ SWIGRUNTIMEINLINE Tcl_Obj * SWIG_Tcl_NewPointerObj(void *ptr, swig_type_info *type, int flags) { Tcl_Obj *robj; char result[SWIG_BUFFER_SIZE]; SWIG_MakePtr(result,ptr,type,flags); robj = Tcl_NewStringObj(result,-1); return robj; } SWIGRUNTIME Tcl_Obj * SWIG_Tcl_NewPackedObj(void *ptr, int sz, swig_type_info *type) { char result[1024]; char *r = result; if ((2*sz + 1 + strlen(type->name)) > 1000) return 0; *(r++) = '_'; r = SWIG_PackData(r,ptr,sz); strcpy(r,type->name); return Tcl_NewStringObj(result,-1); } /* -----------------------------------------------------------------------------* * Get type list * -----------------------------------------------------------------------------*/ SWIGRUNTIME swig_module_info * SWIG_Tcl_GetModule(Tcl_Interp *interp) { const char *data; swig_module_info *ret = 0; /* first check if pointer already created */ data = Tcl_GetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, TCL_GLOBAL_ONLY); if (data) { SWIG_UnpackData(data, &ret, sizeof(swig_type_info **)); } return ret; } SWIGRUNTIME void SWIG_Tcl_SetModule(Tcl_Interp *interp, swig_module_info *module) { char buf[SWIG_BUFFER_SIZE]; char *data; /* create a new pointer */ data = SWIG_PackData(buf, &module, sizeof(swig_type_info **)); *data = 0; Tcl_SetVar(interp, (char *)"swig_runtime_data_type_pointer" SWIG_RUNTIME_VERSION SWIG_TYPE_TABLE_NAME, buf, 0); } /* -----------------------------------------------------------------------------* * Object auxiliars * -----------------------------------------------------------------------------*/ SWIGRUNTIME void SWIG_Tcl_ObjectDelete(ClientData clientData) { swig_instance *si = (swig_instance *) clientData; if ((si) && (si->destroy) && (SWIG_Disown(si->thisvalue))) { if (si->classptr->destructor) { (si->classptr->destructor)(si->thisvalue); } } Tcl_DecrRefCount(si->thisptr); free(si); } /* Function to invoke object methods given an instance */ SWIGRUNTIME int SWIG_Tcl_MethodCommand(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST _objv[]) { char *method, *attrname; swig_instance *inst = (swig_instance *) clientData; swig_method *meth; swig_attribute *attr; Tcl_Obj *oldarg; Tcl_Obj **objv; int rcode; swig_class *cls; swig_class *cls_stack[64]; int cls_stack_bi[64]; int cls_stack_top = 0; int numconf = 2; int bi; objv = (Tcl_Obj **) _objv; if (objc < 2) { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } method = Tcl_GetStringFromObj(objv[1],NULL); if (strcmp(method,"-acquire") == 0) { inst->destroy = 1; SWIG_Acquire(inst->thisvalue); return TCL_OK; } if (strcmp(method,"-disown") == 0) { if (inst->destroy) { SWIG_Disown(inst->thisvalue); } inst->destroy = 0; return TCL_OK; } if (strcmp(method,"-delete") == 0) { Tcl_DeleteCommandFromToken(interp,inst->cmdtok); return TCL_OK; } cls_stack[cls_stack_top] = inst->classptr; cls_stack_bi[cls_stack_top] = -1; cls = inst->classptr; while (1) { bi = cls_stack_bi[cls_stack_top]; cls = cls_stack[cls_stack_top]; if (bi != -1) { if (!cls->bases[bi] && cls->base_names[bi]) { /* lookup and cache the base class */ swig_type_info *info = SWIG_TypeQueryModule(cls->module, cls->module, cls->base_names[bi]); if (info) cls->bases[bi] = (swig_class *) info->clientdata; } cls = cls->bases[bi]; if (cls) { cls_stack_bi[cls_stack_top]++; cls_stack_top++; cls_stack[cls_stack_top] = cls; cls_stack_bi[cls_stack_top] = -1; continue; } } if (!cls) { cls_stack_top--; if (cls_stack_top < 0) break; else continue; } cls_stack_bi[cls_stack_top]++; meth = cls->methods; /* Check for methods */ while (meth && meth->name) { if (strcmp(meth->name,method) == 0) { oldarg = objv[1]; objv[1] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); rcode = (*meth->method)(clientData,interp,objc,objv); objv[1] = oldarg; Tcl_DecrRefCount(inst->thisptr); return rcode; } meth++; } /* Check class methods for a match */ if (strcmp(method,"cget") == 0) { if (objc < 3) { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } attrname = Tcl_GetStringFromObj(objv[2],NULL); attr = cls->attributes; while (attr && attr->name) { if ((strcmp(attr->name, attrname) == 0) && (attr->getmethod)) { oldarg = objv[1]; objv[1] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); rcode = (*attr->getmethod)(clientData,interp,2, objv); objv[1] = oldarg; Tcl_DecrRefCount(inst->thisptr); return rcode; } attr++; } if (strcmp(attrname, "-this") == 0) { Tcl_SetObjResult(interp, Tcl_DuplicateObj(inst->thisptr)); return TCL_OK; } if (strcmp(attrname, "-thisown") == 0) { if (SWIG_Thisown(inst->thisvalue)) { Tcl_SetResult(interp,(char*)"1",TCL_STATIC); } else { Tcl_SetResult(interp,(char*)"0",TCL_STATIC); } return TCL_OK; } } else if (strcmp(method, "configure") == 0) { int i; if (objc < 4) { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } i = 2; while (i < objc) { attrname = Tcl_GetStringFromObj(objv[i],NULL); attr = cls->attributes; while (attr && attr->name) { if ((strcmp(attr->name, attrname) == 0) && (attr->setmethod)) { oldarg = objv[i]; objv[i] = inst->thisptr; Tcl_IncrRefCount(inst->thisptr); rcode = (*attr->setmethod)(clientData,interp,3, &objv[i-1]); objv[i] = oldarg; Tcl_DecrRefCount(inst->thisptr); if (rcode != TCL_OK) return rcode; numconf += 2; } attr++; } i+=2; } } } if (strcmp(method,"configure") == 0) { if (numconf >= objc) { return TCL_OK; } else { Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC); return TCL_ERROR; } } if (strcmp(method,"cget") == 0) { Tcl_SetResult(interp,(char *) "Invalid attribute name.", TCL_STATIC); return TCL_ERROR; } Tcl_SetResult(interp, (char *) "Invalid method. Must be one of: configure cget -acquire -disown -delete", TCL_STATIC); cls = inst->classptr; bi = 0; while (cls) { meth = cls->methods; while (meth && meth->name) { char *cr = (char *) Tcl_GetStringResult(interp); size_t meth_len = strlen(meth->name); char* where = strchr(cr,':'); while(where) { where = strstr(where, meth->name); if(where) { if(where[-1] == ' ' && (where[meth_len] == ' ' || where[meth_len]==0)) { break; } else { where++; } } } if (!where) Tcl_AppendElement(interp, (char *) meth->name); meth++; } cls = inst->classptr->bases[bi++]; } return TCL_ERROR; } /* This function takes the current result and turns it into an object command */ SWIGRUNTIME Tcl_Obj * SWIG_Tcl_NewInstanceObj(Tcl_Interp *interp, void *thisvalue, swig_type_info *type, int flags) { Tcl_Obj *robj = SWIG_NewPointerObj(thisvalue, type,0); /* Check to see if this pointer belongs to a class or not */ if ((type->clientdata) && (interp)) { Tcl_CmdInfo ci; char *name; name = Tcl_GetStringFromObj(robj,NULL); if (!Tcl_GetCommandInfo(interp,name, &ci) || (flags)) { swig_instance *newinst = (swig_instance *) malloc(sizeof(swig_instance)); newinst->thisptr = Tcl_DuplicateObj(robj); Tcl_IncrRefCount(newinst->thisptr); newinst->thisvalue = thisvalue; newinst->classptr = (swig_class *) type->clientdata; newinst->destroy = flags; newinst->cmdtok = Tcl_CreateObjCommand(interp, Tcl_GetStringFromObj(robj,NULL), (swig_wrapper_func) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete); if (flags) { SWIG_Acquire(thisvalue); } } } return robj; } /* Function to create objects */ SWIGRUNTIME int SWIG_Tcl_ObjectConstructor(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { Tcl_Obj *newObj = 0; void *thisvalue = 0; swig_instance *newinst = 0; swig_class *classptr = (swig_class *) clientData; swig_wrapper cons = 0; char *name = 0; int firstarg = 0; int thisarg = 0; int destroy = 1; if (!classptr) { Tcl_SetResult(interp, (char *) "swig: internal runtime error. No class object defined.", TCL_STATIC); return TCL_ERROR; } cons = classptr->constructor; if (objc > 1) { char *s = Tcl_GetStringFromObj(objv[1],NULL); if (strcmp(s,"-this") == 0) { thisarg = 2; cons = 0; } else if (strcmp(s,"-args") == 0) { firstarg = 1; } else if (objc == 2) { firstarg = 1; name = s; } else if (objc >= 3) { char *s1; name = s; s1 = Tcl_GetStringFromObj(objv[2],NULL); if (strcmp(s1,"-this") == 0) { thisarg = 3; cons = 0; } else { firstarg = 1; } } } if (cons) { int result; result = (*cons)(0, interp, objc-firstarg, &objv[firstarg]); if (result != TCL_OK) { return result; } newObj = Tcl_DuplicateObj(Tcl_GetObjResult(interp)); if (!name) name = Tcl_GetStringFromObj(newObj,NULL); } else if (thisarg > 0) { if (thisarg < objc) { destroy = 0; newObj = Tcl_DuplicateObj(objv[thisarg]); if (!name) name = Tcl_GetStringFromObj(newObj,NULL); } else { Tcl_SetResult(interp, (char *) "wrong # args.", TCL_STATIC); return TCL_ERROR; } } else { Tcl_SetResult(interp, (char *) "No constructor available.", TCL_STATIC); return TCL_ERROR; } if (SWIG_Tcl_ConvertPtr(interp,newObj, (void **) &thisvalue, *(classptr->type), 0) != SWIG_OK) { Tcl_DecrRefCount(newObj); return TCL_ERROR; } newinst = (swig_instance *) malloc(sizeof(swig_instance)); newinst->thisptr = newObj; Tcl_IncrRefCount(newObj); newinst->thisvalue = thisvalue; newinst->classptr = classptr; newinst->destroy = destroy; if (destroy) { SWIG_Acquire(thisvalue); } newinst->cmdtok = Tcl_CreateObjCommand(interp,name, (swig_wrapper) SWIG_MethodCommand, (ClientData) newinst, (swig_delete_func) SWIG_ObjectDelete); return TCL_OK; } /* -----------------------------------------------------------------------------* * Get arguments * -----------------------------------------------------------------------------*/ SWIGRUNTIME int SWIG_Tcl_GetArgs(Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[], const char *fmt, ...) { int argno = 0, opt = 0; long tempi; double tempd; const char *c; va_list ap; void *vptr; Tcl_Obj *obj = 0; swig_type_info *ty; va_start(ap,fmt); for (c = fmt; (*c && (*c != ':') && (*c != ';')); c++,argno++) { if (*c == '|') { opt = 1; c++; } if (argno >= (objc-1)) { if (!opt) { Tcl_SetResult(interp, (char *) "Wrong number of arguments ", TCL_STATIC); goto argerror; } else { va_end(ap); return TCL_OK; } } vptr = va_arg(ap,void *); if (vptr) { if (isupper(*c)) { obj = SWIG_Tcl_GetConstantObj(Tcl_GetStringFromObj(objv[argno+1],0)); if (!obj) obj = objv[argno+1]; } else { obj = objv[argno+1]; } switch(*c) { case 'i': case 'I': case 'l': case 'L': case 'h': case 'H': case 'b': case 'B': if (Tcl_GetLongFromObj(interp,obj,&tempi) != TCL_OK) goto argerror; if ((*c == 'i') || (*c == 'I')) *((int *)vptr) = (int)tempi; else if ((*c == 'l') || (*c == 'L')) *((long *)vptr) = (long)tempi; else if ((*c == 'h') || (*c == 'H')) *((short*)vptr) = (short)tempi; else if ((*c == 'b') || (*c == 'B')) *((unsigned char *)vptr) = (unsigned char)tempi; break; case 'f': case 'F': case 'd': case 'D': if (Tcl_GetDoubleFromObj(interp,obj,&tempd) != TCL_OK) goto argerror; if ((*c == 'f') || (*c == 'F')) *((float *) vptr) = (float)tempd; else if ((*c == 'd') || (*c == 'D')) *((double*) vptr) = tempd; break; case 's': case 'S': if (*(c+1) == '#') { int *vlptr = (int *) va_arg(ap, void *); *((char **) vptr) = Tcl_GetStringFromObj(obj, vlptr); c++; } else { *((char **)vptr) = Tcl_GetStringFromObj(obj,NULL); } break; case 'c': case 'C': *((char *)vptr) = *(Tcl_GetStringFromObj(obj,NULL)); break; case 'p': case 'P': ty = (swig_type_info *) va_arg(ap, void *); if (SWIG_Tcl_ConvertPtr(interp, obj, (void **) vptr, ty, 0) != SWIG_OK) goto argerror; break; case 'o': case 'O': *((Tcl_Obj **)vptr) = objv[argno+1]; break; default: break; } } } if ((*c != ';') && ((objc-1) > argno)) { Tcl_SetResult(interp, (char *) "Wrong # args.", TCL_STATIC); goto argerror; } va_end(ap); return TCL_OK; argerror: { char temp[32]; sprintf(temp,"%d", argno+1); c = strchr(fmt,':'); if (!c) c = strchr(fmt,';'); if (!c) c = (char *)""; Tcl_AppendResult(interp,c," argument ", temp, NULL); va_end(ap); return TCL_ERROR; } } #ifdef __cplusplus #if 0 { /* cc-mode */ #endif } #endif #define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) #define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else /* -------- TYPES TABLE (BEGIN) -------- */ #define SWIGTYPE_p_char swig_types[0] #define SWIGTYPE_p_int swig_types[1] #define SWIGTYPE_p_macho swig_types[2] #define SWIGTYPE_p_macho_arch swig_types[3] #define SWIGTYPE_p_macho_handle swig_types[4] #define SWIGTYPE_p_macho_loadcmd swig_types[5] #define SWIGTYPE_p_p_macho swig_types[6] #define SWIGTYPE_p_unsigned_int swig_types[7] static swig_type_info *swig_types[9]; static swig_module_info swig_module = {swig_types, 8, 0, 0, 0, 0}; #define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name) #define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name) /* -------- TYPES TABLE (END) -------- */ #define SWIG_init Machista_Init #define SWIG_name "machista" #define SWIG_prefix "machista::" #define SWIG_namespace "machista" #define SWIG_version "1.0" #define SWIGVERSION 0x010340 #define SWIG_VERSION SWIGVERSION #define SWIG_as_voidptr(a) (void *)((const void *)(a)) #define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) #ifdef __cplusplus extern "C" { #endif #ifdef MAC_TCL #pragma export on #endif SWIGEXPORT int SWIG_init(Tcl_Interp *); #ifdef MAC_TCL #pragma export off #endif #ifdef __cplusplus } #endif /* Compatibility version for TCL stubs */ #ifndef SWIG_TCL_STUBS_VERSION #define SWIG_TCL_STUBS_VERSION "8.1" #endif #include "libmachista.h" #ifdef __MACH__ #include <mach-o/arch.h> #endif #include <inttypes.h> #include <stdint.h> #include <limits.h> #if !defined(SWIG_NO_LLONG_MAX) # if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__) # define LLONG_MAX __LONG_LONG_MAX__ # define LLONG_MIN (-LLONG_MAX - 1LL) # define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL) # endif #endif SWIGINTERNINLINE Tcl_Obj* SWIG_From_long (long value) { if (((long) INT_MIN <= value) && (value <= (long) INT_MAX)) { return Tcl_NewIntObj((int)(value)); } else { return Tcl_NewLongObj(value); } } SWIGINTERNINLINE Tcl_Obj * SWIG_From_int (int value) { return SWIG_From_long (value); } SWIGINTERNINLINE Tcl_Obj * SWIG_FromCharPtrAndSize(const char* carray, size_t size) { return (size < INT_MAX) ? Tcl_NewStringObj(carray, (int)(size)) : NULL; } SWIGINTERNINLINE Tcl_Obj * SWIG_FromCharPtr(const char *cptr) { return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0)); } #include <stdio.h> #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM) # ifndef snprintf # define snprintf _snprintf # endif #endif SWIGINTERNINLINE Tcl_Obj* SWIG_From_unsigned_SS_long (unsigned long value) { if (value < (unsigned long) LONG_MAX) { return SWIG_From_long ((long)(value)); } else { char temp[256]; sprintf(temp, "%lu", value); return Tcl_NewStringObj(temp,-1); } } SWIGINTERNINLINE Tcl_Obj * SWIG_From_unsigned_SS_int (unsigned int value) { return SWIG_From_unsigned_SS_long (value); } SWIGINTERN int SWIG_AsCharPtrAndSize(Tcl_Obj *obj, char** cptr, size_t* psize, int *alloc) { int len = 0; char *cstr = Tcl_GetStringFromObj(obj, &len); if (cstr) { if (cptr) *cptr = cstr; if (psize) *psize = len + 1; if (alloc) *alloc = SWIG_OLDOBJ; return SWIG_OK; } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_long SWIG_TCL_DECL_ARGS_2(Tcl_Obj *obj, long* val) { long v; if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) { if (val) *val = (long) v; return SWIG_OK; } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_int SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, int *val) { long v; int res = SWIG_AsVal_long SWIG_TCL_CALL_ARGS_2(obj, &v); if (SWIG_IsOK(res)) { if ((v < INT_MIN || v > INT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (int)(v); } } return res; } SWIGINTERN int SWIG_AsVal_unsigned_SS_long SWIG_TCL_DECL_ARGS_2(Tcl_Obj *obj, unsigned long *val) { long v; if (Tcl_GetLongFromObj(0,obj, &v) == TCL_OK) { if (v >= 0) { if (val) *val = (unsigned long) v; return SWIG_OK; } /* If v is negative, then this could be a negative number, or an unsigned value which doesn't fit in a signed long, so try to get it as a string so we can distinguish these cases. */ } { int len = 0; const char *nptr = Tcl_GetStringFromObj(obj, &len); if (nptr && len > 0) { char *endptr; unsigned long v; if (*nptr == '-') return SWIG_OverflowError; errno = 0; v = strtoul(nptr, &endptr,0); if (nptr[0] == '\0' || *endptr != '\0') return SWIG_TypeError; if (v == ULONG_MAX && errno == ERANGE) { errno = 0; return SWIG_OverflowError; } else { if (*endptr == '\0') { if (val) *val = v; return SWIG_OK; } } } } return SWIG_TypeError; } SWIGINTERN int SWIG_AsVal_unsigned_SS_int SWIG_TCL_DECL_ARGS_2(Tcl_Obj * obj, unsigned int *val) { unsigned long v; int res = SWIG_AsVal_unsigned_SS_long SWIG_TCL_CALL_ARGS_2(obj, &v); if (SWIG_IsOK(res)) { if ((v > UINT_MAX)) { return SWIG_OverflowError; } else { if (val) *val = (unsigned int)(v); } } return res; } #ifdef __cplusplus extern "C" { #endif static swig_method swig_macho_handle_methods[] = { {0,0} }; static swig_attribute swig_macho_handle_attributes[] = { {0,0,0} }; static swig_class *swig_macho_handle_bases[] = {0}; static const char * swig_macho_handle_base_names[] = {0}; static swig_class _wrap_class_macho_handle = { "macho_handle", &SWIGTYPE_p_macho_handle,0,0, swig_macho_handle_methods, swig_macho_handle_attributes, swig_macho_handle_bases,swig_macho_handle_base_names, &swig_module }; SWIGINTERN int _wrap_macho_loadcmd_mlt_install_name_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_loadcmd *arg1 = (struct macho_loadcmd *) 0 ; void *argp1 = 0 ; int res1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_loadcmd_mlt_install_name_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_loadcmd, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_loadcmd_mlt_install_name_get" "', argument " "1"" of type '" "struct macho_loadcmd *""'"); } arg1 = (struct macho_loadcmd *)(argp1); result = (char *) ((arg1)->mlt_install_name); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_loadcmd_mlt_type_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_loadcmd *arg1 = (struct macho_loadcmd *) 0 ; void *argp1 = 0 ; int res1 = 0 ; uint32_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_loadcmd_mlt_type_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_loadcmd, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_loadcmd_mlt_type_get" "', argument " "1"" of type '" "struct macho_loadcmd *""'"); } arg1 = (struct macho_loadcmd *)(argp1); result = (uint32_t) ((arg1)->mlt_type); Tcl_SetObjResult(interp,SWIG_From_unsigned_SS_int((unsigned int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_loadcmd_mlt_comp_version_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_loadcmd *arg1 = (struct macho_loadcmd *) 0 ; void *argp1 = 0 ; int res1 = 0 ; uint32_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_loadcmd_mlt_comp_version_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_loadcmd, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_loadcmd_mlt_comp_version_get" "', argument " "1"" of type '" "struct macho_loadcmd *""'"); } arg1 = (struct macho_loadcmd *)(argp1); result = (uint32_t) ((arg1)->mlt_comp_version); Tcl_SetObjResult(interp,SWIG_From_unsigned_SS_int((unsigned int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_loadcmd_mlt_version_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_loadcmd *arg1 = (struct macho_loadcmd *) 0 ; void *argp1 = 0 ; int res1 = 0 ; uint32_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_loadcmd_mlt_version_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_loadcmd, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_loadcmd_mlt_version_get" "', argument " "1"" of type '" "struct macho_loadcmd *""'"); } arg1 = (struct macho_loadcmd *)(argp1); result = (uint32_t) ((arg1)->mlt_version); Tcl_SetObjResult(interp,SWIG_From_unsigned_SS_int((unsigned int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_loadcmd_next_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_loadcmd *arg1 = (struct macho_loadcmd *) 0 ; void *argp1 = 0 ; int res1 = 0 ; struct macho_loadcmd *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_loadcmd_next_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_loadcmd, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_loadcmd_next_get" "', argument " "1"" of type '" "struct macho_loadcmd *""'"); } arg1 = (struct macho_loadcmd *)(argp1); result = (struct macho_loadcmd *) ((arg1)->next); Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_macho_loadcmd,0)); return TCL_OK; fail: return TCL_ERROR; } static swig_method swig_macho_loadcmd_methods[] = { {0,0} }; static swig_attribute swig_macho_loadcmd_attributes[] = { { "-mlt_install_name",_wrap_macho_loadcmd_mlt_install_name_get, 0 }, { "-mlt_type",_wrap_macho_loadcmd_mlt_type_get, 0 }, { "-mlt_comp_version",_wrap_macho_loadcmd_mlt_comp_version_get, 0 }, { "-mlt_version",_wrap_macho_loadcmd_mlt_version_get, 0 }, { "-next",_wrap_macho_loadcmd_next_get, 0 }, {0,0,0} }; static swig_class *swig_macho_loadcmd_bases[] = {0}; static const char * swig_macho_loadcmd_base_names[] = {0}; static swig_class _wrap_class_macho_loadcmd = { "macho_loadcmd", &SWIGTYPE_p_macho_loadcmd,0,0, swig_macho_loadcmd_methods, swig_macho_loadcmd_attributes, swig_macho_loadcmd_bases,swig_macho_loadcmd_base_names, &swig_module }; SWIGINTERN int _wrap_macho_arch_mat_install_name_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_install_name_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_install_name_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (char *) ((arg1)->mat_install_name); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_mat_rpath_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_rpath_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_rpath_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (char *) ((arg1)->mat_rpath); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_mat_arch_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; cpu_type_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_arch_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_arch_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (cpu_type_t) ((arg1)->mat_arch); Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_mat_comp_version_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; uint32_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_comp_version_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_comp_version_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (uint32_t) ((arg1)->mat_comp_version); Tcl_SetObjResult(interp,SWIG_From_unsigned_SS_int((unsigned int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_mat_version_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; uint32_t result; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_version_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_version_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (uint32_t) ((arg1)->mat_version); Tcl_SetObjResult(interp,SWIG_From_unsigned_SS_int((unsigned int)(result))); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_mat_loadcmds_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; struct macho_loadcmd *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_mat_loadcmds_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_mat_loadcmds_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (struct macho_loadcmd *) ((arg1)->mat_loadcmds); Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_macho_loadcmd,0)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_macho_arch_next_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_arch *arg1 = (struct macho_arch *) 0 ; void *argp1 = 0 ; int res1 = 0 ; struct macho_arch *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_arch_next_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_arch, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_arch_next_get" "', argument " "1"" of type '" "struct macho_arch *""'"); } arg1 = (struct macho_arch *)(argp1); result = (struct macho_arch *) ((arg1)->next); Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_macho_arch,0)); return TCL_OK; fail: return TCL_ERROR; } static swig_method swig_macho_arch_methods[] = { {0,0} }; static swig_attribute swig_macho_arch_attributes[] = { { "-mat_install_name",_wrap_macho_arch_mat_install_name_get, 0 }, { "-mat_rpath",_wrap_macho_arch_mat_rpath_get, 0 }, { "-mat_arch",_wrap_macho_arch_mat_arch_get, 0 }, { "-mat_comp_version",_wrap_macho_arch_mat_comp_version_get, 0 }, { "-mat_version",_wrap_macho_arch_mat_version_get, 0 }, { "-mat_loadcmds",_wrap_macho_arch_mat_loadcmds_get, 0 }, { "-next",_wrap_macho_arch_next_get, 0 }, {0,0,0} }; static swig_class *swig_macho_arch_bases[] = {0}; static const char * swig_macho_arch_base_names[] = {0}; static swig_class _wrap_class_macho_arch = { "macho_arch", &SWIGTYPE_p_macho_arch,0,0, swig_macho_arch_methods, swig_macho_arch_attributes, swig_macho_arch_bases,swig_macho_arch_base_names, &swig_module }; SWIGINTERN int _wrap_macho_mt_archs_get(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho *arg1 = (struct macho *) 0 ; void *argp1 = 0 ; int res1 = 0 ; struct macho_arch *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::macho_mt_archs_get self ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "macho_mt_archs_get" "', argument " "1"" of type '" "struct macho *""'"); } arg1 = (struct macho *)(argp1); result = (struct macho_arch *) ((arg1)->mt_archs); Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_macho_arch,0)); return TCL_OK; fail: return TCL_ERROR; } static swig_method swig_macho_methods[] = { {0,0} }; static swig_attribute swig_macho_attributes[] = { { "-mt_archs",_wrap_macho_mt_archs_get, 0 }, {0,0,0} }; static swig_class *swig_macho_bases[] = {0}; static const char * swig_macho_base_names[] = {0}; static swig_class _wrap_class_macho = { "macho", &SWIGTYPE_p_macho,0,0, swig_macho_methods, swig_macho_attributes, swig_macho_bases,swig_macho_base_names, &swig_module }; SWIGINTERN int _wrap_create_handle(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_handle *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,":machista::create_handle ") == TCL_ERROR) SWIG_fail; result = (struct macho_handle *)macho_create_handle(); Tcl_SetObjResult(interp, SWIG_NewInstanceObj( SWIG_as_voidptr(result), SWIGTYPE_p_macho_handle,0)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_destroy_handle(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_handle *arg1 = (struct macho_handle *) 0 ; void *argp1 = 0 ; int res1 = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::destroy_handle INPUT ",(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_handle, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "destroy_handle" "', argument " "1"" of type '" "struct macho_handle *""'"); } arg1 = (struct macho_handle *)(argp1); macho_destroy_handle(arg1); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_parse_file(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { struct macho_handle *arg1 = (struct macho_handle *) 0 ; char *arg2 = (char *) 0 ; struct macho **arg3 = (struct macho **) 0 ; void *argp1 = 0 ; int res1 = 0 ; int res2 ; char *buf2 = 0 ; int alloc2 = 0 ; struct macho *res3 ; int result; { arg3 = &res3; } if (SWIG_GetArgs(interp, objc, objv,"oo:machista::parse_file handle filename ",(void *)0,(void *)0) == TCL_ERROR) SWIG_fail; res1 = SWIG_ConvertPtr(objv[1], &argp1,SWIGTYPE_p_macho_handle, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "parse_file" "', argument " "1"" of type '" "struct macho_handle *""'"); } arg1 = (struct macho_handle *)(argp1); res2 = SWIG_AsCharPtrAndSize(objv[2], &buf2, NULL, &alloc2); if (!SWIG_IsOK(res2)) { SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "parse_file" "', argument " "2"" of type '" "char const *""'"); } arg2 = (char *)(buf2); result = (int)macho_parse_file(arg1,(char const *)arg2,(struct macho const **)arg3); Tcl_SetObjResult(interp,SWIG_From_int((int)(result))); { Tcl_ListObjAppendElement(interp, (Tcl_GetObjResult(interp)), SWIG_NewInstanceObj(SWIG_as_voidptr(*arg3), SWIGTYPE_p_macho, 0)); } if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return TCL_OK; fail: if (alloc2 == SWIG_NEWOBJ) free((char*)buf2); return TCL_ERROR; } SWIGINTERN int _wrap_strerror(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { int arg1 ; int val1 ; int ecode1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::strerror err ",(void *)0) == TCL_ERROR) SWIG_fail; ecode1 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[1], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "strerror" "', argument " "1"" of type '" "int""'"); } arg1 = (int)(val1); result = (char *)macho_strerror(arg1); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_get_arch_name(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { cpu_type_t arg1 ; int val1 ; int ecode1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::get_arch_name cpu_type_t ",(void *)0) == TCL_ERROR) SWIG_fail; ecode1 = SWIG_AsVal_int SWIG_TCL_CALL_ARGS_2(objv[1], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "get_arch_name" "', argument " "1"" of type '" "cpu_type_t""'"); } arg1 = (cpu_type_t)(val1); result = (char *)macho_get_arch_name(arg1); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); return TCL_OK; fail: return TCL_ERROR; } SWIGINTERN int _wrap_format_dylib_version(ClientData clientData SWIGUNUSED, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[]) { uint32_t arg1 ; unsigned int val1 ; int ecode1 = 0 ; char *result = 0 ; if (SWIG_GetArgs(interp, objc, objv,"o:machista::format_dylib_version uint32_t ",(void *)0) == TCL_ERROR) SWIG_fail; ecode1 = SWIG_AsVal_unsigned_SS_int SWIG_TCL_CALL_ARGS_2(objv[1], &val1); if (!SWIG_IsOK(ecode1)) { SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "format_dylib_version" "', argument " "1"" of type '" "uint32_t""'"); } arg1 = (uint32_t)(val1); result = (char *)macho_format_dylib_version(arg1); Tcl_SetObjResult(interp,SWIG_FromCharPtr((const char *)result)); { free(result); } return TCL_OK; fail: return TCL_ERROR; } static swig_command_info swig_commands[] = { { SWIG_prefix "macho_handle", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_macho_handle}, { SWIG_prefix "macho_loadcmd_mlt_install_name_get", (swig_wrapper_func) _wrap_macho_loadcmd_mlt_install_name_get, NULL}, { SWIG_prefix "macho_loadcmd_mlt_type_get", (swig_wrapper_func) _wrap_macho_loadcmd_mlt_type_get, NULL}, { SWIG_prefix "macho_loadcmd_mlt_comp_version_get", (swig_wrapper_func) _wrap_macho_loadcmd_mlt_comp_version_get, NULL}, { SWIG_prefix "macho_loadcmd_mlt_version_get", (swig_wrapper_func) _wrap_macho_loadcmd_mlt_version_get, NULL}, { SWIG_prefix "macho_loadcmd_next_get", (swig_wrapper_func) _wrap_macho_loadcmd_next_get, NULL}, { SWIG_prefix "macho_loadcmd", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_macho_loadcmd}, { SWIG_prefix "macho_arch_mat_install_name_get", (swig_wrapper_func) _wrap_macho_arch_mat_install_name_get, NULL}, { SWIG_prefix "macho_arch_mat_rpath_get", (swig_wrapper_func) _wrap_macho_arch_mat_rpath_get, NULL}, { SWIG_prefix "macho_arch_mat_arch_get", (swig_wrapper_func) _wrap_macho_arch_mat_arch_get, NULL}, { SWIG_prefix "macho_arch_mat_comp_version_get", (swig_wrapper_func) _wrap_macho_arch_mat_comp_version_get, NULL}, { SWIG_prefix "macho_arch_mat_version_get", (swig_wrapper_func) _wrap_macho_arch_mat_version_get, NULL}, { SWIG_prefix "macho_arch_mat_loadcmds_get", (swig_wrapper_func) _wrap_macho_arch_mat_loadcmds_get, NULL}, { SWIG_prefix "macho_arch_next_get", (swig_wrapper_func) _wrap_macho_arch_next_get, NULL}, { SWIG_prefix "macho_arch", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_macho_arch}, { SWIG_prefix "macho_mt_archs_get", (swig_wrapper_func) _wrap_macho_mt_archs_get, NULL}, { SWIG_prefix "macho", (swig_wrapper_func) SWIG_ObjectConstructor, (ClientData)&_wrap_class_macho}, { SWIG_prefix "create_handle", (swig_wrapper_func) _wrap_create_handle, NULL}, { SWIG_prefix "destroy_handle", (swig_wrapper_func) _wrap_destroy_handle, NULL}, { SWIG_prefix "parse_file", (swig_wrapper_func) _wrap_parse_file, NULL}, { SWIG_prefix "strerror", (swig_wrapper_func) _wrap_strerror, NULL}, { SWIG_prefix "get_arch_name", (swig_wrapper_func) _wrap_get_arch_name, NULL}, { SWIG_prefix "format_dylib_version", (swig_wrapper_func) _wrap_format_dylib_version, NULL}, {0, 0, 0} }; static swig_var_info swig_variables[] = { {0,0,0,0} }; static swig_const_info swig_constants[] = { {0,0,0,0,0,0} }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_int = {"_p_int", "int *|cpu_type_t *", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_macho = {"_p_macho", "struct macho *|macho *", 0, 0, (void*)&_wrap_class_macho, 0}; static swig_type_info _swigt__p_macho_arch = {"_p_macho_arch", "struct macho_arch *|macho_arch *", 0, 0, (void*)&_wrap_class_macho_arch, 0}; static swig_type_info _swigt__p_macho_handle = {"_p_macho_handle", "macho_handle *|struct macho_handle *", 0, 0, (void*)&_wrap_class_macho_handle, 0}; static swig_type_info _swigt__p_macho_loadcmd = {"_p_macho_loadcmd", "struct macho_loadcmd *|macho_loadcmd *", 0, 0, (void*)&_wrap_class_macho_loadcmd, 0}; static swig_type_info _swigt__p_p_macho = {"_p_p_macho", "struct macho **", 0, 0, (void*)0, 0}; static swig_type_info _swigt__p_unsigned_int = {"_p_unsigned_int", "uint32_t *|unsigned int *", 0, 0, (void*)0, 0}; static swig_type_info *swig_type_initial[] = { &_swigt__p_char, &_swigt__p_int, &_swigt__p_macho, &_swigt__p_macho_arch, &_swigt__p_macho_handle, &_swigt__p_macho_loadcmd, &_swigt__p_p_macho, &_swigt__p_unsigned_int, }; static swig_cast_info _swigc__p_char[] = { {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_macho[] = { {&_swigt__p_macho, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_macho_arch[] = { {&_swigt__p_macho_arch, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_macho_handle[] = { {&_swigt__p_macho_handle, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_macho_loadcmd[] = { {&_swigt__p_macho_loadcmd, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_p_macho[] = { {&_swigt__p_p_macho, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info _swigc__p_unsigned_int[] = { {&_swigt__p_unsigned_int, 0, 0, 0},{0, 0, 0, 0}}; static swig_cast_info *swig_cast_initial[] = { _swigc__p_char, _swigc__p_int, _swigc__p_macho, _swigc__p_macho_arch, _swigc__p_macho_handle, _swigc__p_macho_loadcmd, _swigc__p_p_macho, _swigc__p_unsigned_int, }; /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ #ifdef __cplusplus } #endif /* ----------------------------------------------------------------------------- * Type initialization: * This problem is tough by the requirement that no dynamic * memory is used. Also, since swig_type_info structures store pointers to * swig_cast_info structures and swig_cast_info structures store pointers back * to swig_type_info structures, we need some lookup code at initialization. * The idea is that swig generates all the structures that are needed. * The runtime then collects these partially filled structures. * The SWIG_InitializeModule function takes these initial arrays out of * swig_module, and does all the lookup, filling in the swig_module.types * array with the correct data and linking the correct swig_cast_info * structures together. * * The generated swig_type_info structures are assigned staticly to an initial * array. We just loop through that array, and handle each type individually. * First we lookup if this type has been already loaded, and if so, use the * loaded structure instead of the generated one. Then we have to fill in the * cast linked list. The cast data is initially stored in something like a * two-dimensional array. Each row corresponds to a type (there are the same * number of rows as there are in the swig_type_initial array). Each entry in * a column is one of the swig_cast_info structures for that type. * The cast_initial array is actually an array of arrays, because each row has * a variable number of columns. So to actually build the cast linked list, * we find the array of casts associated with the type, and loop through it * adding the casts to the list. The one last trick we need to do is making * sure the type pointer in the swig_cast_info struct is correct. * * First off, we lookup the cast->type name to see if it is already loaded. * There are three cases to handle: * 1) If the cast->type has already been loaded AND the type we are adding * casting info to has not been loaded (it is in this module), THEN we * replace the cast->type pointer with the type pointer that has already * been loaded. * 2) If BOTH types (the one we are adding casting info to, and the * cast->type) are loaded, THEN the cast info has already been loaded by * the previous module so we just ignore it. * 3) Finally, if cast->type has not already been loaded, then we add that * swig_cast_info to the linked list (because the cast->type) pointer will * be correct. * ----------------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" { #if 0 } /* c-mode */ #endif #endif #if 0 #define SWIGRUNTIME_DEBUG #endif SWIGRUNTIME void SWIG_InitializeModule(void *clientdata) { size_t i; swig_module_info *module_head, *iter; int found, init; /* check to see if the circular list has been setup, if not, set it up */ if (swig_module.next==0) { /* Initialize the swig_module */ swig_module.type_initial = swig_type_initial; swig_module.cast_initial = swig_cast_initial; swig_module.next = &swig_module; init = 1; } else { init = 0; } /* Try and load any already created modules */ module_head = SWIG_GetModule(clientdata); if (!module_head) { /* This is the first module loaded for this interpreter */ /* so set the swig module into the interpreter */ SWIG_SetModule(clientdata, &swig_module); module_head = &swig_module; } else { /* the interpreter has loaded a SWIG module, but has it loaded this one? */ found=0; iter=module_head; do { if (iter==&swig_module) { found=1; break; } iter=iter->next; } while (iter!= module_head); /* if the is found in the list, then all is done and we may leave */ if (found) return; /* otherwise we must add out module into the list */ swig_module.next = module_head->next; module_head->next = &swig_module; } /* When multiple interpeters are used, a module could have already been initialized in a different interpreter, but not yet have a pointer in this interpreter. In this case, we do not want to continue adding types... everything should be set up already */ if (init == 0) return; /* Now work on filling in swig_module.types */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: size %d\n", swig_module.size); #endif for (i = 0; i < swig_module.size; ++i) { swig_type_info *type = 0; swig_type_info *ret; swig_cast_info *cast; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); #endif /* if there is another module already loaded */ if (swig_module.next != &swig_module) { type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name); } if (type) { /* Overwrite clientdata field */ #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found type %s\n", type->name); #endif if (swig_module.type_initial[i]->clientdata) { type->clientdata = swig_module.type_initial[i]->clientdata; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name); #endif } } else { type = swig_module.type_initial[i]; } /* Insert casting types */ cast = swig_module.cast_initial[i]; while (cast->type) { /* Don't need to add information already in the list */ ret = 0; #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: look cast %s\n", cast->type->name); #endif if (swig_module.next != &swig_module) { ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name); #ifdef SWIGRUNTIME_DEBUG if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name); #endif } if (ret) { if (type == swig_module.type_initial[i]) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: skip old type %s\n", ret->name); #endif cast->type = ret; ret = 0; } else { /* Check for casting already in the list */ swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type); #ifdef SWIGRUNTIME_DEBUG if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name); #endif if (!ocast) ret = 0; } } if (!ret) { #ifdef SWIGRUNTIME_DEBUG printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name); #endif if (type->cast) { type->cast->prev = cast; cast->next = type->cast; } type->cast = cast; } cast++; } /* Set entry in modules->types array equal to the type */ swig_module.types[i] = type; } swig_module.types[i] = 0; #ifdef SWIGRUNTIME_DEBUG printf("**** SWIG_InitializeModule: Cast List ******\n"); for (i = 0; i < swig_module.size; ++i) { int j = 0; swig_cast_info *cast = swig_module.cast_initial[i]; printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name); while (cast->type) { printf("SWIG_InitializeModule: cast type %s\n", cast->type->name); cast++; ++j; } printf("---- Total casts: %d\n",j); } printf("**** SWIG_InitializeModule: Cast List ******\n"); #endif } /* This function will propagate the clientdata field of type to * any new swig_type_info structures that have been added into the list * of equivalent types. It is like calling * SWIG_TypeClientData(type, clientdata) a second time. */ SWIGRUNTIME void SWIG_PropagateClientData(void) { size_t i; swig_cast_info *equiv; static int init_run = 0; if (init_run) return; init_run = 1; for (i = 0; i < swig_module.size; i++) { if (swig_module.types[i]->clientdata) { equiv = swig_module.types[i]->cast; while (equiv) { if (!equiv->converter) { if (equiv->type && !equiv->type->clientdata) SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata); } equiv = equiv->next; } } } } #ifdef __cplusplus #if 0 { /* c-mode */ #endif } #endif #ifdef __cplusplus extern "C" { #endif /* ----------------------------------------------------------------------------- * constants/methods manipulation * ----------------------------------------------------------------------------- */ /* Install Constants */ SWIGINTERN void SWIG_Tcl_InstallConstants(Tcl_Interp *interp, swig_const_info constants[]) { int i; Tcl_Obj *obj; if (!swigconstTableinit) { Tcl_InitHashTable(&swigconstTable, TCL_STRING_KEYS); swigconstTableinit = 1; } for (i = 0; constants[i].type; i++) { switch(constants[i].type) { case SWIG_TCL_POINTER: obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0); break; case SWIG_TCL_BINARY: obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype)); break; default: obj = 0; break; } if (obj) { SWIG_Tcl_SetConstantObj(interp, constants[i].name, obj); } } } #ifdef __cplusplus } #endif /* -----------------------------------------------------------------------------* * Partial Init method * -----------------------------------------------------------------------------*/ SWIGEXPORT int SWIG_init(Tcl_Interp *interp) { int i; if (interp == 0) return TCL_ERROR; #ifdef USE_TCL_STUBS /* (char*) cast is required to avoid compiler warning/error for Tcl < 8.4. */ if (Tcl_InitStubs(interp, (char*)SWIG_TCL_STUBS_VERSION, 0) == NULL) { return TCL_ERROR; } #endif #ifdef USE_TK_STUBS /* (char*) cast is required to avoid compiler warning/error. */ if (Tk_InitStubs(interp, (char*)SWIG_TCL_STUBS_VERSION, 0) == NULL) { return TCL_ERROR; } #endif Tcl_PkgProvide(interp, (char*)SWIG_name, (char*)SWIG_version); #ifdef SWIG_namespace Tcl_Eval(interp, "namespace eval " SWIG_namespace " { }"); #endif SWIG_InitializeModule((void *) interp); SWIG_PropagateClientData(); for (i = 0; swig_commands[i].name; i++) { Tcl_CreateObjCommand(interp, (char *) swig_commands[i].name, (swig_wrapper_func) swig_commands[i].wrapper, swig_commands[i].clientdata, NULL); } for (i = 0; swig_variables[i].name; i++) { Tcl_SetVar(interp, (char *) swig_variables[i].name, (char *) "", TCL_GLOBAL_ONLY); Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_READS | TCL_GLOBAL_ONLY, (Tcl_VarTraceProc *) swig_variables[i].get, (ClientData) swig_variables[i].addr); Tcl_TraceVar(interp, (char *) swig_variables[i].name, TCL_TRACE_WRITES | TCL_GLOBAL_ONLY, (Tcl_VarTraceProc *) swig_variables[i].set, (ClientData) swig_variables[i].addr); } SWIG_Tcl_InstallConstants(interp, swig_constants); SWIG_Tcl_SetConstantObj(interp, "machista::SUCCESS", SWIG_From_int((int)((0x00)))); SWIG_Tcl_SetConstantObj(interp, "machista::EFILE", SWIG_From_int((int)((0x01)))); SWIG_Tcl_SetConstantObj(interp, "machista::EMMAP", SWIG_From_int((int)((0x02)))); SWIG_Tcl_SetConstantObj(interp, "machista::EMEM", SWIG_From_int((int)((0x04)))); SWIG_Tcl_SetConstantObj(interp, "machista::ERANGE", SWIG_From_int((int)((0x08)))); SWIG_Tcl_SetConstantObj(interp, "machista::EMAGIC", SWIG_From_int((int)((0x10)))); return TCL_OK; } SWIGEXPORT int Machista_SafeInit(Tcl_Interp *interp) { return SWIG_init(interp); }
536722.c
/* * Copyright (c) 2016-2017 Intel, Inc. All rights reserved. * Copyright (c) 2015-2017 Mellanox Technologies, Inc. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ * */ #include "test_fence.h" static void get_cb(pmix_status_t status, pmix_value_t *kv, void *cbdata) { get_cbdata *cb = (get_cbdata*)cbdata; if (PMIX_SUCCESS == status) { pmix_value_xfer(cb->kv, kv); } cb->in_progress = 0; cb->status = status; } static void add_noise(char *noise_param, char *my_nspace, pmix_rank_t my_rank) { bool participate = false; participant_t *p; parse_noise(noise_param, 1); if (NULL != noise_range) { PMIX_LIST_FOREACH(p, noise_range, participant_t) { if (0 == strncmp(my_nspace, p->proc.nspace, strlen(my_nspace)) && (my_rank == p->proc.rank || PMIX_RANK_WILDCARD == p->proc.rank)) { participate = true; break; } } if (participate) { sleep(2); TEST_VERBOSE(("I'm %s:%d sleeping\n", my_nspace, my_rank)); } PMIX_LIST_RELEASE(noise_range); noise_range = NULL; } } static void release_cb(pmix_status_t status, void *cbdata) { int *ptr = (int*)cbdata; *ptr = 0; } int test_fence(test_params params, char *my_nspace, pmix_rank_t my_rank) { int len; int rc; size_t i, npcs; fence_desc_t *desc; participant_t *p, *next; pmix_proc_t *pcs; bool participate; int fence_num = 0; char sval[50]; int put_ind; if (NULL != params.noise) { add_noise(params.noise, my_nspace, my_rank); } PMIX_CONSTRUCT(&test_fences, pmix_list_t); parse_fence(params.fences, 1); TEST_VERBOSE(("fences %s\n", params.fences)); /* cycle thru all the test fence descriptors to find * those that include my nspace/rank */ PMIX_LIST_FOREACH(desc, &test_fences, fence_desc_t) { char tmp[256] = {0}; len = sprintf(tmp, "fence %d: block = %d de = %d ", fence_num, desc->blocking, desc->data_exchange); participate = false; /* search the participants */ PMIX_LIST_FOREACH(p, desc->participants, participant_t) { if (0 == strncmp(my_nspace, p->proc.nspace, strlen(my_nspace)) && (my_rank == p->proc.rank || PMIX_RANK_WILDCARD == p->proc.rank)) { participate = true; } if (PMIX_RANK_WILDCARD == p->proc.rank) { len += sprintf(tmp+len, "all; "); } else { len += sprintf(tmp+len, "%d,", p->proc.rank); } } TEST_VERBOSE(("%s\n", tmp)); if (participate) { /*run fence test on this range */ /* first put value (my_ns, my_rank) with key based on fence_num to split results of different fences*/ put_ind = 0; (void)snprintf(sval, 50, "%d:%s:%d", fence_num, my_nspace, my_rank); PUT(string, sval, PMIX_GLOBAL, fence_num, put_ind++, params.use_same_keys); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } PUT(int, fence_num+my_rank, PMIX_GLOBAL, fence_num, put_ind++, params.use_same_keys); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } PUT(float, fence_num+1.1, PMIX_GLOBAL, fence_num, put_ind++, params.use_same_keys); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } PUT(uint32_t, fence_num+14, PMIX_GLOBAL, fence_num, put_ind++, params.use_same_keys); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } PUT(uint16_t, fence_num+15, PMIX_GLOBAL, fence_num, put_ind++, params.use_same_keys); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } /* Submit the data */ if (PMIX_SUCCESS != (rc = PMIx_Commit())) { TEST_ERROR(("%s:%d: PMIx_Commit failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); return rc; } /* setup the fence */ npcs = pmix_list_get_size(desc->participants); PMIX_PROC_CREATE(pcs, npcs); i = 0; PMIX_LIST_FOREACH(p, desc->participants, participant_t) { (void)strncpy(pcs[i].nspace, p->proc.nspace, PMIX_MAX_NSLEN); pcs[i].rank = p->proc.rank; i++; } /* perform fence */ FENCE(desc->blocking, desc->data_exchange, pcs, npcs); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Fence failed: %d", my_nspace, my_rank, rc)); PMIX_LIST_DESTRUCT(&test_fences); PMIX_PROC_FREE(pcs, npcs); return rc; } /* replace all items in the list with PMIX_RANK_WILDCARD rank by real ranks to get their data. */ pmix_proc_t *ranks; size_t nranks; PMIX_LIST_FOREACH_SAFE(p, next, desc->participants, participant_t) { if (PMIX_RANK_WILDCARD == p->proc.rank) { rc = get_all_ranks_from_namespace(params, p->proc.nspace, &ranks, &nranks); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: Can't parse --ns-dist value in order to get ranks for namespace %s", my_nspace, my_rank, p->proc.nspace)); PMIX_LIST_DESTRUCT(&test_fences); return PMIX_ERROR; } pmix_list_remove_item(desc->participants, (pmix_list_item_t*)p); for (i = 0; i < nranks; i++) { participant_t *prt; prt = PMIX_NEW(participant_t); strncpy(prt->proc.nspace, ranks[i].nspace, strlen(ranks[i].nspace)+1); prt->proc.rank = ranks[i].rank; pmix_list_append(desc->participants, &prt->super); } PMIX_PROC_FREE(ranks, nranks); } } /* get data from all participating in this fence clients */ PMIX_LIST_FOREACH(p, desc->participants, participant_t) { put_ind = 0; snprintf(sval, 50, "%d:%s:%d", fence_num, p->proc.nspace, p->proc.rank); GET(string, sval, p->proc.nspace, p->proc.rank, fence_num, put_ind++, params.use_same_keys, 1, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d) from %s:%d", my_nspace, my_rank, rc, p->proc.nspace, p->proc.rank)); PMIX_PROC_FREE(pcs, npcs); PMIX_LIST_DESTRUCT(&test_fences); return rc; } GET(int, (int)(fence_num+p->proc.rank), p->proc.nspace, p->proc.rank, fence_num, put_ind++, params.use_same_keys, 0, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d) from %s:%d", my_nspace, my_rank, rc, p->proc.nspace, p->proc.rank)); PMIX_PROC_FREE(pcs, npcs); PMIX_LIST_DESTRUCT(&test_fences); return rc; } GET(float, fence_num+1.1, p->proc.nspace, p->proc.rank, fence_num, put_ind++, params.use_same_keys, 1, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d) from %s:%d", my_nspace, my_rank, rc, p->proc.nspace, p->proc.rank)); PMIX_PROC_FREE(pcs, npcs); PMIX_LIST_DESTRUCT(&test_fences); return rc; } GET(uint32_t, (uint32_t)fence_num+14, p->proc.nspace, p->proc.rank, fence_num, put_ind++, params.use_same_keys, 0, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d) from %s:%d", my_nspace, my_rank, rc, p->proc.nspace, p->proc.rank)); PMIX_PROC_FREE(pcs, npcs); PMIX_LIST_DESTRUCT(&test_fences); return rc; } GET(uint16_t, fence_num+15, p->proc.nspace, p->proc.rank, fence_num, put_ind++, params.use_same_keys, 1, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d) from %s:%d", my_nspace, my_rank, rc, p->proc.nspace, p->proc.rank)); PMIX_PROC_FREE(pcs, npcs); PMIX_LIST_DESTRUCT(&test_fences); return rc; } } /* barrier across participating processes to prevent putting new values with the same key * before finishing data exchange with other processes. */ FENCE(1, 0, pcs, npcs); PMIX_PROC_FREE(pcs, npcs); } fence_num++; } PMIX_LIST_DESTRUCT(&test_fences); return PMIX_SUCCESS; } static int get_local_peers(char *my_nspace, int my_rank, pmix_rank_t **_peers, pmix_rank_t *count) { pmix_value_t *val; pmix_rank_t *peers = NULL; char *sptr, *token, *eptr, *str; pmix_rank_t npeers; int rc; pmix_proc_t proc; (void)strncpy(proc.nspace, my_nspace, PMIX_MAX_NSLEN); proc.rank = PMIX_RANK_WILDCARD; /* get number of neighbours on this node */ if (PMIX_SUCCESS != (rc = PMIx_Get(&proc, PMIX_LOCAL_SIZE, NULL, 0, &val))) { TEST_ERROR(("%s:%d: PMIx_Get local peer # failed: %d", my_nspace, my_rank, rc)); return rc; } if (NULL == val) { TEST_ERROR(("%s:%d: PMIx_Get local peer # returned NULL value", my_nspace, my_rank)); return PMIX_ERROR; } if (val->type != PMIX_UINT32 ) { TEST_ERROR(("%s:%d: local peer # attribute value type mismatch," " want %d get %d(%d)", my_nspace, my_rank, PMIX_UINT32, val->type)); return PMIX_ERROR; } npeers = val->data.uint32; peers = malloc(sizeof(pmix_rank_t) * npeers); /* get ranks of neighbours on this node */ if (PMIX_SUCCESS != (rc = PMIx_Get(&proc, PMIX_LOCAL_PEERS, NULL, 0, &val))) { TEST_ERROR(("%s:%d: PMIx_Get local peers failed: %d", my_nspace, my_rank, rc)); free(peers); return rc; } if (NULL == val) { TEST_ERROR(("%s:%d: PMIx_Get local peers returned NULL value", my_nspace, my_rank)); free(peers); return PMIX_ERROR; } if (val->type != PMIX_STRING ) { TEST_ERROR(("%s:%d: local peers attribute value type mismatch," " want %d get %d(%d)", my_nspace, my_rank, PMIX_UINT32, val->type)); free(peers); return PMIX_ERROR; } *count = 0; sptr = NULL; str = val->data.string; do{ if( *count > npeers ){ TEST_ERROR(("%s:%d: Bad peer ranks number: should be %d, actual %d (%s)", my_nspace, my_rank, npeers, *count, val->data.string)); free(peers); return PMIX_ERROR; } token = strtok_r(str, ",", &sptr); str = NULL; if( NULL != token ){ peers[(*count)++] = strtol(token,&eptr,10); if( *eptr != '\0' ){ TEST_ERROR(("%s:%d: Bad peer ranks string", my_nspace, my_rank)); free(peers); return PMIX_ERROR; } } } while( NULL != token ); if( *count != npeers ){ TEST_ERROR(("%s:%d: Bad peer ranks number: should be %d, actual %d (%s)", my_nspace, my_rank, npeers, *count, val->data.string)); free(peers); return PMIX_ERROR; } *_peers = peers; return PMIX_SUCCESS; } int test_job_fence(test_params params, char *my_nspace, pmix_rank_t my_rank) { int rc; int i, j; char sval[50]; pmix_rank_t *peers, npeers; pmix_value_t value; pmix_value_t *val = &value; pmix_proc_t proc; (void)strncpy(proc.nspace, my_nspace, PMIX_MAX_NSLEN); proc.rank = my_rank; for (i=0; i < 3; i++) { PUT(int, 12340 + i, PMIX_LOCAL, 100, i, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); return rc; } (void)snprintf(sval, 50, "%s:%d", my_nspace, my_rank); PUT(string, sval, PMIX_REMOTE, 101, i, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); return PMIX_ERROR; } PUT(float, (float)12.15 + i, PMIX_GLOBAL, 102, i, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Put failed: %d", my_nspace, my_rank, rc)); return PMIX_ERROR; } } /* Submit the data */ if (PMIX_SUCCESS != (rc = PMIx_Commit())) { TEST_ERROR(("%s:%d: PMIx_Commit failed: %d", my_nspace, my_rank, rc)); return PMIX_ERROR; } /* Perform a fence if was requested */ FENCE(!params.nonblocking, params.collect, NULL, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Fence failed: %d", my_nspace, my_rank, rc)); return rc; } if (PMIX_SUCCESS != (rc = get_local_peers(my_nspace, my_rank, &peers, &npeers))) { return PMIX_ERROR; } /* Check the predefined output */ for (i=0; i < (int)params.ns_size; i++) { for (j=0; j < 3; j++) { int local = 0; pmix_rank_t k; for(k=0; k<npeers; k++){ if( peers[k] == i+params.base_rank){ local = 1; } } if( local ){ GET(int, (12340+j), my_nspace, i+params.base_rank, 100, j, 0, 0, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed: %d", my_nspace, my_rank, rc)); return PMIX_ERROR; } snprintf(sval, 50, "%s:%d", my_nspace, i+params.base_rank); GET(string, sval, my_nspace, i+params.base_rank, 101, j, 0, 1, 1); if (PMIX_SUCCESS == rc && (i+params.base_rank) != my_rank ) { TEST_ERROR(("%s:%d: PMIx_Get of remote key on local proc", my_nspace, my_rank)); return PMIX_ERROR; } } else { GET(int, (12340+j), my_nspace, i+params.base_rank, 100, j, 0, 0, 1); if (PMIX_SUCCESS == rc && (i+params.base_rank) != my_rank) { TEST_ERROR(("%s:%d: PMIx_Get of local key on the remote proc", my_nspace, my_rank)); return PMIX_ERROR; } snprintf(sval, 50, "%s:%d", my_nspace, i+params.base_rank); GET(string, sval, my_nspace, i+params.base_rank, 101, j, 0, 1, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d)", my_nspace, my_rank, rc)); return PMIX_ERROR; } } GET(float, (float)12.15 + j, my_nspace, i+params.base_rank, 102, j, 0, 0, 0); if (PMIX_SUCCESS != rc) { TEST_ERROR(("%s:%d: PMIx_Get failed (%d)", my_nspace, my_rank, rc)); return PMIX_ERROR; } } /* ask for a non-existent key */ proc.rank = i+params.base_rank; if (PMIX_SUCCESS == (rc = PMIx_Get(&proc, "foobar", NULL, 0, &val))) { TEST_ERROR(("%s:%d: PMIx_Get returned success instead of failure", my_nspace, my_rank)); return PMIX_ERROR; } if (PMIX_ERR_NOT_FOUND != rc) { TEST_ERROR(("%s:%d [ERROR]: PMIx_Get returned %d instead of not_found", my_nspace, my_rank, rc)); } if (NULL != val) { TEST_ERROR(("%s:%d [ERROR]: PMIx_Get did not return NULL value", my_nspace, my_rank)); return PMIX_ERROR; } TEST_VERBOSE(("%s:%d: rank %d is OK", my_nspace, my_rank, i+params.base_rank)); } return PMIX_SUCCESS; }
41752.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; /* > \brief \b CUNM2L multiplies a general matrix by the unitary matrix from a QL factorization determined by cgeqlf (unblocked algorithm). */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download CUNM2L + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/cunm2l. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/cunm2l. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/cunm2l. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE CUNM2L( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, */ /* WORK, INFO ) */ /* CHARACTER SIDE, TRANS */ /* INTEGER INFO, K, LDA, LDC, M, N */ /* COMPLEX A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CUNM2L overwrites the general complex m-by-n matrix C with */ /* > */ /* > Q * C if SIDE = 'L' and TRANS = 'N', or */ /* > */ /* > Q**H* C if SIDE = 'L' and TRANS = 'C', or */ /* > */ /* > C * Q if SIDE = 'R' and TRANS = 'N', or */ /* > */ /* > C * Q**H if SIDE = 'R' and TRANS = 'C', */ /* > */ /* > where Q is a complex unitary matrix defined as the product of k */ /* > elementary reflectors */ /* > */ /* > Q = H(k) . . . H(2) H(1) */ /* > */ /* > as returned by CGEQLF. Q is of order m if SIDE = 'L' and of order n */ /* > if SIDE = 'R'. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] SIDE */ /* > \verbatim */ /* > SIDE is CHARACTER*1 */ /* > = 'L': apply Q or Q**H from the Left */ /* > = 'R': apply Q or Q**H from the Right */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS */ /* > \verbatim */ /* > TRANS is CHARACTER*1 */ /* > = 'N': apply Q (No transpose) */ /* > = 'C': apply Q**H (Conjugate transpose) */ /* > \endverbatim */ /* > */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the matrix C. M >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the matrix C. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] K */ /* > \verbatim */ /* > K is INTEGER */ /* > The number of elementary reflectors whose product defines */ /* > the matrix Q. */ /* > If SIDE = 'L', M >= K >= 0; */ /* > if SIDE = 'R', N >= K >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] A */ /* > \verbatim */ /* > A is COMPLEX array, dimension (LDA,K) */ /* > The i-th column must contain the vector which defines the */ /* > elementary reflector H(i), for i = 1,2,...,k, as returned by */ /* > CGEQLF in the last k columns of its array argument A. */ /* > A is modified by the routine but restored on exit. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. */ /* > If SIDE = 'L', LDA >= f2cmax(1,M); */ /* > if SIDE = 'R', LDA >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] TAU */ /* > \verbatim */ /* > TAU is COMPLEX array, dimension (K) */ /* > TAU(i) must contain the scalar factor of the elementary */ /* > reflector H(i), as returned by CGEQLF. */ /* > \endverbatim */ /* > */ /* > \param[in,out] C */ /* > \verbatim */ /* > C is COMPLEX array, dimension (LDC,N) */ /* > On entry, the m-by-n matrix C. */ /* > On exit, C is overwritten by Q*C or Q**H*C or C*Q**H or C*Q. */ /* > \endverbatim */ /* > */ /* > \param[in] LDC */ /* > \verbatim */ /* > LDC is INTEGER */ /* > The leading dimension of the array C. LDC >= f2cmax(1,M). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is COMPLEX array, dimension */ /* > (N) if SIDE = 'L', */ /* > (M) if SIDE = 'R' */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complexOTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int cunm2l_(char *side, char *trans, integer *m, integer *n, integer *k, complex *a, integer *lda, complex *tau, complex *c__, integer *ldc, complex *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2, i__3; complex q__1; /* Local variables */ logical left; complex taui; integer i__; extern /* Subroutine */ int clarf_(char *, integer *, integer *, complex * , integer *, complex *, complex *, integer *, complex *); extern logical lsame_(char *, char *); integer i1, i2, i3, mi, ni, nq; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); logical notran; complex aii; /* -- LAPACK computational routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1 * 1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "C")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if (*k < 0 || *k > nq) { *info = -5; } else if (*lda < f2cmax(1,nq)) { *info = -7; } else if (*ldc < f2cmax(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("CUNM2L", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*m == 0 || *n == 0 || *k == 0) { return 0; } if (left && notran || ! left && ! notran) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) or H(i)**H is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) or H(i)**H is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) or H(i)**H */ if (notran) { i__3 = i__; taui.r = tau[i__3].r, taui.i = tau[i__3].i; } else { r_cnjg(&q__1, &tau[i__]); taui.r = q__1.r, taui.i = q__1.i; } i__3 = nq - *k + i__ + i__ * a_dim1; aii.r = a[i__3].r, aii.i = a[i__3].i; i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = 1.f, a[i__3].i = 0.f; clarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &taui, &c__[ c_offset], ldc, &work[1]); i__3 = nq - *k + i__ + i__ * a_dim1; a[i__3].r = aii.r, a[i__3].i = aii.i; /* L10: */ } return 0; /* End of CUNM2L */ } /* cunm2l_ */
66014.c
/* * ***** BEGIN LICENSE BLOCK ***** Copyright (C) 2009-2019 Olof Hagsand Copyright (C) 2020-2021 Olof Hagsand and Rubicon Communications, LLC(Netgate) This file is part of CLIXON. 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. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 3 or later (the "GPL"), in which case the provisions of the GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of the GPL, and not to allow others to use your version of this file under the terms of Apache License version 2, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by the GPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the Apache License version 2 or the GPL. ***** END LICENSE BLOCK ***** */ #ifdef HAVE_CONFIG_H #include "clixon_config.h" /* generated by config & autoconf */ #endif #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <limits.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <assert.h> #include <syslog.h> #include <fcntl.h> /* cligen */ #include <cligen/cligen.h> /* clixon */ #include "clixon_err.h" #include "clixon_string.h" #include "clixon_queue.h" #include "clixon_hash.h" #include "clixon_handle.h" #include "clixon_log.h" #include "clixon_file.h" #include "clixon_yang.h" #include "clixon_xml.h" #include "clixon_xml_sort.h" #include "clixon_xml_bind.h" #include "clixon_options.h" #include "clixon_data.h" #include "clixon_xpath_ctx.h" #include "clixon_xpath.h" #include "clixon_json.h" #include "clixon_nacm.h" #include "clixon_path.h" #include "clixon_netconf_lib.h" #include "clixon_yang_module.h" #include "clixon_yang_parse_lib.h" #include "clixon_xml_map.h" #include "clixon_xml_io.h" #include "clixon_xml_nsctx.h" #include "clixon_datastore.h" #include "clixon_datastore_read.h" #define handle(xh) (assert(text_handle_check(xh)==0),(struct text_handle *)(xh)) /*! Ensure that xt only has a single sub-element and that is "config" * @retval -1 Top element not "config" or "config" element not unique or * other error, check specific clicon_errno, clicon_suberrno * @retval 0 There exists a single "config" sub-element */ static int singleconfigroot(cxobj *xt, cxobj **xp) { int retval = -1; cxobj *x = NULL; int i = 0; /* There should only be one element and called config */ x = NULL; while ((x = xml_child_each(xt, x, CX_ELMNT)) != NULL){ i++; if (strcmp(xml_name(x), DATASTORE_TOP_SYMBOL)){ clicon_err(OE_DB, ENOENT, "Wrong top-element %s expected %s", xml_name(x), DATASTORE_TOP_SYMBOL); goto done; } } if (i != 1){ clicon_err(OE_DB, ENOENT, "Top-element is not unique, expecting single config"); goto done; } x = NULL; while ((x = xml_child_each(xt, x, CX_ELMNT)) != NULL){ if (xml_rm(x) < 0) goto done; if (xml_free(xt) < 0) goto done; *xp = x; break; } retval = 0; done: return retval; } /*! Recurse up from x0 up to x0t then create objects from x1t down to new object x1 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 OK */ static int xml_copy_bottom_recurse(cxobj *x0t, cxobj *x0, cxobj *x1t, cxobj **x1pp) { int retval = -1; cxobj *x0p = NULL; cxobj *x1p = NULL; cxobj *x1 = NULL; cxobj *x1a = NULL; cxobj *x0a = NULL; cxobj *x0k; cxobj *x1k; yang_stmt *y = NULL; cvec *cvk = NULL; /* vector of index keys */ cg_var *cvi; char *keyname; if (x0 == x0t){ *x1pp = x1t; goto ok; } if ((x0p = xml_parent(x0)) == NULL){ clicon_err(OE_XML, EFAULT, "Reached top of tree"); goto done; } if (xml_copy_bottom_recurse(x0t, x0p, x1t, &x1p) < 0) goto done; y = xml_spec(x0); /* Look if it exists */ if (match_base_child(x1p, x0, y, &x1) < 0) goto done; if (x1 == NULL){ /* If not, create it and copy it one level only */ if ((x1 = xml_new(xml_name(x0), x1p, CX_ELMNT)) == NULL) goto done; if (xml_copy_one(x0, x1) < 0) goto done; /* Copy all attributes */ x0a = NULL; while ((x0a = xml_child_each(x0, x0a, -1)) != NULL) { /* Assume ordered, skip after attributes */ if (xml_type(x0a) != CX_ATTR) break; if ((x1a = xml_new(xml_name(x0a), x1, CX_ATTR)) == NULL) goto done; if (xml_copy_one(x0a, x1a) < 0) goto done; } /* Key nodes in lists are copied */ if (y && yang_keyword_get(y) == Y_LIST){ /* Loop over all key variables */ cvk = yang_cvec_get(y); /* Use Y_LIST cache, see ys_populate_list() */ cvi = NULL; /* Iterate over individual keys */ while ((cvi = cvec_each(cvk, cvi)) != NULL) { keyname = cv_string_get(cvi); if ((x0k = xml_find_type(x0, NULL, keyname, CX_ELMNT)) != NULL){ if ((x1k = xml_new(keyname, x1, CX_ELMNT)) == NULL) goto done; if (xml_copy(x0k, x1k) < 0) goto done; } } } } *x1pp = x1; ok: retval = 0; done: return retval; } /*! Copy an XML tree bottom-up * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 OK */ static int xml_copy_from_bottom(cxobj *x0t, cxobj *x0, cxobj *x1t) { int retval = -1; cxobj *x1p = NULL; cxobj *x0p = NULL; cxobj *x1 = NULL; yang_stmt *y = NULL; if (x0 == x0t) goto ok; x0p = xml_parent(x0); if (xml_copy_bottom_recurse(x0t, x0p, x1t, &x1p) < 0) goto done; if ((y = xml_spec(x0)) != NULL){ /* Look if it exists */ if (match_base_child(x1p, x0, y, &x1) < 0) goto done; } if (x1 == NULL){ /* If not, create it and copy complete tree */ if ((x1 = xml_new(xml_name(x0), x1p, CX_ELMNT)) == NULL) goto done; if (xml_copy(x0, x1) < 0) goto done; } ok: retval = 0; done: return retval; } /*! Read module-state in an XML tree * * @param[in] th Datastore text handle * @param[in] yspec Top-level yang spec * @param[in] xt XML tree * @param[out] msdiff Modules-state differences * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 OK * * The modstate difference contains: * - if there is a modstate * - the modstate identifier * - An entry for each modstate that differs marked with flag: ADD|DEL|CHANGE * * Algorithm: * Read mst (module-state-tree) from xml tree (if any) and compare it with * the system state mst. * This can happen: * 1) There is no modules-state info in the file * 2) There is module state info in the file * 3) For each module state m in the file: * 3a) There is no such module in the system -> add to list mark as DEL * 3b) File module-state matches system * 3c) File module-state does not match system -> add to list mark as CHANGE * 4) For each module state s in the system * 4a) If there is no such module in the file -> add to list mark as ADD */ static int text_read_modstate(clicon_handle h, yang_stmt *yspec, cxobj *xt, modstate_diff_t *msdiff) { int retval = -1; cxobj *xmodfile = NULL; /* modstate of system (loaded yang modules in runtime) */ cxobj *xmodsystem = NULL; /* modstate of file, eg startup */ cxobj *xf = NULL; /* xml modstate in file */ cxobj *xf2; /* copy */ cxobj *xs; /* xml modstate in system */ cxobj *xs2; /* copy */ char *name; /* module name */ char *frev; /* file revision */ char *srev; /* system revision */ /* Read module-state as computed at startup, see startup_module_state() */ xmodsystem = clicon_modst_cache_get(h, 1); if ((xmodfile = xml_find_type(xt, NULL, "modules-state", CX_ELMNT)) == NULL){ /* 1) There is no modules-state info in the file */ } else if (xmodsystem && msdiff){ msdiff->md_status = 1; /* There is module state in the file */ /* Create modstate tree for this file */ if (clixon_xml_parse_string("<modules-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-yang-library\"/>", YB_MODULE, yspec, &msdiff->md_diff, NULL) < 0) goto done; if (xml_rootchild(msdiff->md_diff, 0, &msdiff->md_diff) < 0) goto done; /* 3) For each module state m in the file */ xf = NULL; while ((xf = xml_child_each(xmodfile, xf, CX_ELMNT)) != NULL) { if (strcmp(xml_name(xf), "module-set-id") == 0){ if (xml_body(xf) && (msdiff->md_set_id = strdup(xml_body(xf))) == NULL){ clicon_err(OE_UNIX, errno, "strdup"); goto done; } continue; } if (strcmp(xml_name(xf), "module")) continue; /* ignore other tags, such as module-set-id */ if ((name = xml_find_body(xf, "name")) == NULL) continue; /* 3a) There is no such module in the system */ if ((xs = xpath_first(xmodsystem, NULL, "module[name=\"%s\"]", name)) == NULL){ if ((xf2 = xml_dup(xf)) == NULL) /* Make a copy of this modstate */ goto done; if (xml_addsub(msdiff->md_diff, xf2) < 0) /* Add it to modstatediff */ goto done; xml_flag_set(xf2, XML_FLAG_DEL); continue; } /* These two shouldnt happen since revision is key, just ignore */ if ((frev = xml_find_body(xf, "revision")) == NULL) continue; if ((srev = xml_find_body(xs, "revision")) == NULL) continue; if (strcmp(frev, srev) != 0){ /* 3c) File module-state does not match system */ if ((xf2 = xml_dup(xf)) == NULL) goto done; if (xml_addsub(msdiff->md_diff, xf2) < 0) goto done; xml_flag_set(xf2, XML_FLAG_CHANGE); } } /* 4) For each module state s in the system (xmodsystem) */ xs = NULL; while ((xs = xml_child_each(xmodsystem, xs, CX_ELMNT)) != NULL) { if (strcmp(xml_name(xs), "module")) continue; /* ignore other tags, such as module-set-id */ if ((name = xml_find_body(xs, "name")) == NULL) continue; /* 4a) If there is no such module in the file -> add to list mark as ADD */ if ((xf = xpath_first(xmodfile, NULL, "module[name=\"%s\"]", name)) == NULL){ if ((xs2 = xml_dup(xs)) == NULL) /* Make a copy of this modstate */ goto done; if (xml_addsub(msdiff->md_diff, xs2) < 0) /* Add it to modstatediff */ goto done; xml_flag_set(xs2, XML_FLAG_ADD); continue; } } } /* The module-state is removed from the input XML tree. This is done * in all cases, whether CLICON_XMLDB_MODSTATE is on or not. * Clixon systems with CLICON_XMLDB_MODSTATE disabled ignores it */ if (xmodfile){ if (xml_purge(xmodfile) < 0) goto done; } retval = 0; done: return retval; } /*! Check if nacm only contains default values, if so disable NACM * @param[in] xt Top-level XML * @param[in] yspec YANG spec * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 OK */ static int disable_nacm_on_empty(cxobj *xt, yang_stmt *yspec) { int retval = -1; yang_stmt *ymod; cxobj **vec = NULL; int len = 0; cxobj *xnacm = NULL; cxobj *x; cxobj *xb; if ((ymod = yang_find(yspec, Y_MODULE, "ietf-netconf-acm")) == NULL) goto ok; if ((xnacm = xpath_first(xt, NULL, "nacm")) == NULL) goto ok; /* Go through all children and check all are defaults, otherwise quit */ x = NULL; while ((x = xml_child_each(xnacm, x, CX_ELMNT)) != NULL) { if (!xml_flag(x, XML_FLAG_DEFAULT)) break; } if (x != NULL) goto ok; /* not empty, at least one non-default child of nacm */ if (clixon_xml_find_instance_id(xt, yspec, &vec, &len, "/nacm:nacm/nacm:enable-nacm") < 1) goto done; if (len){ if ((xb = xml_body_get(vec[0])) == NULL) goto done; if (xml_value_set(xb, "false") < 0) goto done; } if (vec) free(vec); ok: retval = 0; done: return retval; } /*! Common read function that reads an XML tree from file * @param[in] th Datastore text handle * @param[in] db Symbolic database name, eg "candidate", "running" * @param[in] yb How to bind yang to XML top-level when parsing * @param[in] yspec Top-level yang spec * @param[out] xp XML tree read from file * @param[out] de If set, return db-element status (eg empty flag) * @param[out] msdiff If set, return modules-state differences * @param[out] xerr XML error if retval is 0 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK * @note retval 0 is NYI because calling functions cannot handle it yet * XXX if this code pass tests this code can be rewritten, esp the modstate stuff */ int xmldb_readfile(clicon_handle h, const char *db, yang_bind yb, yang_stmt *yspec, cxobj **xp, db_elmnt *de, modstate_diff_t *msdiff0, cxobj **xerr) { int retval = -1; cxobj *x0 = NULL; char *dbfile = NULL; FILE *fp = NULL; char *format; int ret; modstate_diff_t *msdiff = NULL; cxobj *xmsd; /* XML module state diff */ yang_stmt *ymod; char *name; char *ns; /* namespace */ char *rev; /* revision */ int needclone; cxobj *xmodfile = NULL; cxobj *x; yang_stmt *yspec1 = NULL; if (yb != YB_MODULE && yb != YB_NONE){ clicon_err(OE_XML, EINVAL, "yb is %d but should be module or none", yb); goto done; } if (xmldb_db2file(h, db, &dbfile) < 0) goto done; if (dbfile==NULL){ clicon_err(OE_XML, 0, "dbfile NULL"); goto done; } if ((format = clicon_option_str(h, "CLICON_XMLDB_FORMAT")) == NULL){ clicon_err(OE_CFG, ENOENT, "No CLICON_XMLDB_FORMAT"); goto done; } /* Parse file into internal XML tree from different formats */ if ((fp = fopen(dbfile, "r")) == NULL) { clicon_err(OE_UNIX, errno, "open(%s)", dbfile); goto done; } /* Read whole datastore file on the form: * <config> * modstate* # this is analyzed, stripped and returned as msdiff in text_read_modstate * config* * </config> * ret == 0 should not happen with YB_NONE. Binding is done later */ if (strcmp(format, "json")==0){ if (clixon_json_parse_file(fp, YB_NONE, yspec, &x0, xerr) < 0) goto done; } else { if (clixon_xml_parse_file(fp, YB_NONE, yspec, &x0, xerr) < 0){ goto done; } } /* Always assert a top-level called "config". * To ensure that, deal with two cases: * 1. File is empty <top/> -> rename top-level to "config" */ if (xml_child_nr(x0) == 0){ if (xml_name_set(x0, DATASTORE_TOP_SYMBOL) < 0) goto done; } /* 2. File is not empty <top><config>...</config></top> -> replace root */ else{ /* There should only be one element and called config */ if (singleconfigroot(x0, &x0) < 0) goto done; } /* Purge all top-level body objects */ x = NULL; while ((x = xml_find_type(x0, NULL, "body", CX_BODY)) != NULL) xml_purge(x); xml_flag_set(x0, XML_FLAG_TOP); if (xml_child_nr(x0) == 0 && de) de->de_empty = 1; /* Check if we support modstate */ if (clicon_option_bool(h, "CLICON_XMLDB_MODSTATE")) if ((msdiff = modstate_diff_new()) == NULL) goto done; if ((x = xml_find_type(x0, NULL, "modules-state", CX_ELMNT)) != NULL) if ((xmodfile = xml_dup(x)) == NULL) goto done; /* Datastore files may contain module-state defining * which modules are used in the file. * Strip module-state, analyze it with CHANGE/ADD/RM and return msdiff */ if (text_read_modstate(h, yspec, x0, msdiff) < 0) goto done; if (yb == YB_MODULE){ if (msdiff){ /* Check if old/deleted yangs not present in the loaded/running yangspec. * If so, append them to the global yspec */ needclone = 0; xmsd = NULL; while ((xmsd = xml_child_each(msdiff->md_diff, xmsd, CX_ELMNT)) != NULL) { if (xml_flag(xmsd, XML_FLAG_CHANGE|XML_FLAG_DEL) == 0) continue; needclone++; /* Extract name, namespace, and revision */ if ((name = xml_find_body(xmsd, "name")) == NULL) continue; if ((ns = xml_find_body(xmsd, "namespace")) == NULL) continue; /* Extract revision */ if ((rev = xml_find_body(xmsd, "revision")) == NULL) continue; /* Add old/deleted yangs not present in the loaded/running yangspec. */ if ((ymod = yang_find_module_by_namespace_revision(yspec, ns, rev)) == NULL){ /* YANG Module not found, look for it and append if found */ if (yang_spec_parse_module(h, name, rev, yspec) < 0){ /* Special case: file-not-found errors */ if (clicon_suberrno == ENOENT){ cbuf *cberr = NULL; if ((cberr = cbuf_new()) == NULL){ clicon_err(OE_XML, errno, "cbuf_new"); goto done; } cprintf(cberr, "Internal error: %s", clicon_err_reason); clicon_err_reset(); if (netconf_operation_failed_xml(xerr, "application", cbuf_get(cberr))< 0) goto done; cbuf_free(cberr); goto fail; } goto done; } } } /* If we found an obsolete yang module, we need to make a clone yspec with the * exactly the yang modules found * Same ymodules are inserted into yspec1, ie pointers only */ if (needclone && xmodfile){ if ((yspec1 = yspec_new()) == NULL) goto done; xmsd = NULL; while ((xmsd = xml_child_each(xmodfile, xmsd, CX_ELMNT)) != NULL) { if (strcmp(xml_name(xmsd), "module")) continue; if ((ns = xml_find_body(xmsd, "namespace")) == NULL) continue; if ((rev = xml_find_body(xmsd, "revision")) == NULL) continue; if ((ymod = yang_find_module_by_namespace_revision(yspec, ns, rev)) == NULL) continue; // XXX error? if (yn_insert1(yspec1, ymod) < 0) goto done; } } } /* if msdiff */ /* xml looks like: <top><config><x>... actually YB_MODULE_NEXT */ if ((ret = xml_bind_yang(x0, YB_MODULE, yspec1?yspec1:yspec, xerr)) < 0) goto done; if (ret == 0) goto fail; if (xml_sort_recurse(x0) < 0) goto done; } if (xp){ *xp = x0; x0 = NULL; } if (msdiff0){ *msdiff0 = *msdiff; free(msdiff); /* Just body */ msdiff = NULL; } retval = 1; done: if (yspec1) ys_free1(yspec1, 1); if (xmodfile) xml_free(xmodfile); if (msdiff) modstate_diff_free(msdiff); if (fp) fclose(fp); if (dbfile) free(dbfile); if (x0) xml_free(x0); return retval; fail: retval = 0; goto done; } /*! Get content of database using xpath. return a set of matching sub-trees * The function returns a minimal tree that includes all sub-trees that match * xpath. * This is a clixon datastore plugin of the the xmldb api * @param[in] h Clicon handle * @param[in] db Name of database to search in (filename including dir path * @param[in] yb How to bind yang to XML top-level when parsing * @param[in] nsc External XML namespace context, or NULL * @param[in] xpath String with XPATH syntax. or NULL for all * @param[out] xret Single return XML tree. Free with xml_free() * @param[out] msdiff If set, return modules-state differences * @param[out] xerr XML error if retval is 0 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK * @see xmldb_get the generic API function */ static int xmldb_get_nocache(clicon_handle h, const char *db, yang_bind yb, cvec *nsc, const char *xpath, cxobj **xtop, modstate_diff_t *msdiff, cxobj **xerr) { int retval = -1; char *dbfile = NULL; yang_stmt *yspec; cxobj *xt = NULL; cxobj *x; int fd = -1; cxobj **xvec = NULL; size_t xlen; int i; int ret; db_elmnt de0 = {0,}; if ((yspec = clicon_dbspec_yang(h)) == NULL){ clicon_err(OE_YANG, ENOENT, "No yang spec"); goto done; } /* xml looks like: <top><config><x>... where "x" is a top-level symbol in a module */ if ((ret = xmldb_readfile(h, db, yb, yspec, &xt, &de0, msdiff, xerr)) < 0) goto done; if (ret == 0) goto fail; clicon_db_elmnt_set(h, db, &de0); /* Content is copied */ /* Here xt looks like: <config>...</config> */ /* Given the xpath, return a vector of matches in xvec */ if (xpath_vec(xt, nsc, "%s", &xvec, &xlen, xpath?xpath:"/") < 0) goto done; /* If vectors are specified then mark the nodes found with all ancestors * and filter out everything else, * otherwise return complete tree. */ if (xvec != NULL) for (i=0; i<xlen; i++){ x = xvec[i]; xml_flag_set(x, XML_FLAG_MARK); } /* Remove everything that is not marked */ if (!xml_flag(xt, XML_FLAG_MARK)) if (xml_tree_prune_flagged_sub(xt, XML_FLAG_MARK, 1, NULL) < 0) goto done; /* reset flag */ if (xml_apply(xt, CX_ELMNT, (xml_applyfn_t*)xml_flag_reset, (void*)XML_FLAG_MARK) < 0) goto done; if (yb != YB_NONE){ /* Add global defaults. */ if (xml_global_defaults(h, xt, nsc, xpath, yspec, 0) < 0) goto done; /* Add default values (if not set) */ if (xml_default_recurse(xt, 0) < 0) goto done; } /* If empty NACM config, then disable NACM if loaded */ if (clicon_option_bool(h, "CLICON_NACM_DISABLED_ON_EMPTY")){ if (disable_nacm_on_empty(xt, yspec) < 0) goto done; } #if 0 /* debug */ if (xml_apply0(xt, -1, xml_sort_verify, NULL) < 0) clicon_log(LOG_NOTICE, "%s: sort verify failed #2", __FUNCTION__); #endif if (clicon_debug_get()>1) clicon_xml2file(stderr, xt, 0, 1); *xtop = xt; xt = NULL; retval = 1; done: if (xt) xml_free(xt); if (dbfile) free(dbfile); if (xvec) free(xvec); if (fd != -1) close(fd); return retval; fail: retval = 0; goto done; } /*! Get content of database using xpath. return a set of matching sub-trees * The function returns a minimal tree that includes all sub-trees that match * xpath. * This is a clixon datastore plugin of the the xmldb api * @param[in] h Clicon handle * @param[in] db Name of database to search in (filename including dir path * @param[in] yb How to bind yang to XML top-level when parsing * @param[in] nsc External XML namespace context, or NULL * @param[in] xpath String with XPATH syntax. or NULL for all * @param[out] xret Single return XML tree. Free with xml_free() * @param[out] msdiff If set, return modules-state differences * @param[out] xerr XML error if retval is 0 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK * @see xmldb_get the generic API function */ static int xmldb_get_cache(clicon_handle h, const char *db, yang_bind yb, cvec *nsc, const char *xpath, cxobj **xtop, modstate_diff_t *msdiff, cxobj **xerr) { int retval = -1; yang_stmt *yspec; cxobj *x0t = NULL; /* (cached) top of tree */ cxobj *x0; cxobj **xvec = NULL; size_t xlen; int i; db_elmnt *de = NULL; cxobj *x1t = NULL; db_elmnt de0 = {0,}; int ret; if ((yspec = clicon_dbspec_yang(h)) == NULL){ clicon_err(OE_YANG, ENOENT, "No yang spec"); goto done; } de = clicon_db_elmnt_get(h, db); if (de == NULL || de->de_xml == NULL){ /* Cache miss, read XML from file */ /* If there is no xml x0 tree (in cache), then read it from file */ /* xml looks like: <top><config><x>... where "x" is a top-level symbol in a module */ if ((ret = xmldb_readfile(h, db, yb, yspec, &x0t, &de0, msdiff, xerr)) < 0) goto done; if (ret == 0) goto fail; /* Should we validate file if read from disk? * No, argument against: we may want to have a semantically wrong file and wish to edit? */ de0.de_xml = x0t; clicon_db_elmnt_set(h, db, &de0); /* Content is copied */ } /* x0t == NULL */ else x0t = de->de_xml; if (yb == YB_MODULE && !xml_spec(x0t)){ if ((ret = xml_bind_yang(x0t, YB_MODULE, yspec, xerr)) < 0) goto done; if (ret == 0) ; /* XXX */ else { /* Add default global values (to make xpath below include defaults) */ if (xml_global_defaults(h, x0t, nsc, xpath, yspec, 0) < 0) goto done; /* Add default recursive values */ if (xml_default_recurse(x0t, 0) < 0) goto done; } } /* Here x0t looks like: <config>...</config> */ /* Given the xpath, return a vector of matches in xvec * Can we do everything in one go? * 0) Make a new tree * 1) make the xpath check * 2) iterate thru matches (maybe this can be folded into the xpath_vec?) * a) for every node that is found, copy to new tree * b) if config dont dont state data */ if (xpath_vec(x0t, nsc, "%s", &xvec, &xlen, xpath?xpath:"/") < 0) goto done; /* Make new tree by copying top-of-tree from x0t to x1t */ if ((x1t = xml_new(xml_name(x0t), NULL, CX_ELMNT)) == NULL) goto done; xml_flag_set(x1t, XML_FLAG_TOP); xml_spec_set(x1t, xml_spec(x0t)); if (xlen < 1000){ /* This is optimized for the case when the tree is large and xlen is small * If the tree is large and xlen too, then the other is better. * This only works if yang bind */ for (i=0; i<xlen; i++){ x0 = xvec[i]; if (xml_copy_from_bottom(x0t, x0, x1t) < 0) /* config */ goto done; } } else { /* Iterate through the match vector * For every node found in x0, mark the tree up to t1 * XXX can we do this directly from xvec? */ for (i=0; i<xlen; i++){ x0 = xvec[i]; xml_flag_set(x0, XML_FLAG_MARK); xml_apply_ancestor(x0, (xml_applyfn_t*)xml_flag_set, (void*)XML_FLAG_CHANGE); } if (xml_copy_marked(x0t, x1t) < 0) /* config */ goto done; if (xml_apply(x0t, CX_ELMNT, (xml_applyfn_t*)xml_flag_reset, (void*)(XML_FLAG_MARK|XML_FLAG_CHANGE)) < 0) goto done; if (xml_apply(x1t, CX_ELMNT, (xml_applyfn_t*)xml_flag_reset, (void*)(XML_FLAG_MARK|XML_FLAG_CHANGE)) < 0) goto done; } /* Remove global defaults from cache * Mark non-presence containers */ if (xml_apply(x0t, CX_ELMNT, xml_nopresence_default_mark, (void*)XML_FLAG_TRANSIENT) < 0) goto done; /* clear XML tree of defaults */ if (xml_tree_prune_flagged(x0t, XML_FLAG_DEFAULT, 1) < 0) goto done; /* Clear XML tree of defaults */ if (xml_tree_prune_flagged(x0t, XML_FLAG_TRANSIENT, 1) < 0) goto done; if (yb != YB_NONE){ /* Add default global values */ if (xml_global_defaults(h, x1t, nsc, xpath, yspec, 0) < 0) goto done; /* Add default recursive values */ if (xml_default_recurse(x1t, 0) < 0) goto done; } /* If empty NACM config, then disable NACM if loaded */ if (clicon_option_bool(h, "CLICON_NACM_DISABLED_ON_EMPTY")){ if (disable_nacm_on_empty(x1t, yspec) < 0) goto done; } /* Copy the matching parts of the (relevant) XML tree. * If cache was empty, also update to datastore cache */ if (clicon_debug_get()>1) clicon_xml2file(stderr, x1t, 0, 1); *xtop = x1t; retval = 1; done: clicon_debug(2, "%s retval:%d", __FUNCTION__, retval); if (xvec) free(xvec); return retval; fail: retval = 0; goto done; } /*! Get the raw cache of whole tree * Useful for some higer level usecases for optimized access * This is a clixon datastore plugin of the the xmldb api * @param[in] h Clicon handle * @param[in] db Name of database to search in (filename including dir path * @param[in] yb How to bind yang to XML top-level when parsing * @param[in] nsc External XML namespace context, or NULL * @param[in] xpath String with XPATH syntax. or NULL for all * @param[in] config If set only configuration data, else also state * @param[out] xret Single return XML tree. Free with xml_free() * @param[out] msdiff If set, return modules-state differences * @param[out] xerr XML error if retval is 0 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK */ static int xmldb_get_zerocopy(clicon_handle h, const char *db, yang_bind yb, cvec *nsc, const char *xpath, cxobj **xtop, modstate_diff_t *msdiff, cxobj **xerr) { int retval = -1; yang_stmt *yspec; cxobj *x0t = NULL; /* (cached) top of tree */ cxobj **xvec = NULL; size_t xlen; int i; cxobj *x0; db_elmnt *de = NULL; db_elmnt de0 = {0,}; int ret; if ((yspec = clicon_dbspec_yang(h)) == NULL){ clicon_err(OE_YANG, ENOENT, "No yang spec"); goto done; } de = clicon_db_elmnt_get(h, db); if (de == NULL || de->de_xml == NULL){ /* Cache miss, read XML from file */ /* If there is no xml x0 tree (in cache), then read it from file */ /* xml looks like: <top><config><x>... where "x" is a top-level symbol in a module */ if ((ret = xmldb_readfile(h, db, yb, yspec, &x0t, &de0, msdiff, xerr)) < 0) goto done; if (ret == 0) goto fail; /* Should we validate file if read from disk? * No, argument against: we may want to have a semantically wrong file and wish to edit? */ de0.de_xml = x0t; clicon_db_elmnt_set(h, db, &de0); } /* x0t == NULL */ else x0t = de->de_xml; /* Here xt looks like: <config>...</config> */ if (xpath_vec(x0t, nsc, "%s", &xvec, &xlen, xpath?xpath:"/") < 0) goto done; /* Iterate through the match vector * For every node found in x0, mark the tree up to t1 */ for (i=0; i<xlen; i++){ x0 = xvec[i]; xml_flag_set(x0, XML_FLAG_MARK); xml_apply_ancestor(x0, (xml_applyfn_t*)xml_flag_set, (void*)XML_FLAG_CHANGE); } if (yb != YB_NONE){ /* Add global defaults. */ if (xml_global_defaults(h, x0t, nsc, xpath, yspec, 0) < 0) goto done; /* Apply default values (removed in clear function) */ if (xml_default_recurse(x0t, 0) < 0) goto done; } /* If empty NACM config, then disable NACM if loaded */ if (clicon_option_bool(h, "CLICON_NACM_DISABLED_ON_EMPTY")){ if (disable_nacm_on_empty(x0t, yspec) < 0) goto done; } if (clicon_debug_get()>1) clicon_xml2file(stderr, x0t, 0, 1); *xtop = x0t; retval = 1; done: clicon_debug(2, "%s retval:%d", __FUNCTION__, retval); if (xvec) free(xvec); return retval; fail: retval = 0; goto done; } /*! Get content of datastore and return a copy of the XML tree * @param[in] h Clicon handle * @param[in] db Name of database to search in, eg "running" * @param[in] nsc XML namespace context for XPATH * @param[in] xpath String with XPATH syntax. or NULL for all * @param[out] xret Single return XML tree. Free with xml_free() * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK * @code * if (xmldb_get(xh, "running", NULL, "/interfaces/interface[name="eth"]", &xt) < 0) * err; * xml_free(xt); * @endcode * @see xmldb_get0 Underlying more capable API for enabling zero-copy */ int xmldb_get(clicon_handle h, const char *db, cvec *nsc, char *xpath, cxobj **xret) { return xmldb_get0(h, db, YB_MODULE, nsc, xpath, 1, xret, NULL, NULL); } /*! Zero-copy variant of get content of database * * The function returns a minimal tree that includes all sub-trees that match * xpath. * It can be used for zero-copying if CLICON_DATASTORE_CACHE is set * appropriately. * The tree returned may be the actual cache, therefore calls for cleaning and * freeing tree must be made after use. * @param[in] h Clicon handle * @param[in] db Name of datastore, eg "running" * @param[in] yb How to bind yang to XML top-level when parsing (if YB_NONE, no defaults) * @param[in] nsc External XML namespace context, or NULL * @param[in] xpath String with XPATH syntax. or NULL for all * @param[in] copy Force copy. Overrides cache_zerocopy -> cache * @param[out] xret Single return XML tree. Free with xml_free() * @param[out] msdiff If set, return modules-state differences (upgrade code) * @param[out] xerr XML error if retval is 0 * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 Parse OK but yang assigment not made (or only partial) and xerr set * @retval 1 OK * @note Use of 1 for OK * @code * cxobj *xt; * cxobj *xerr = NULL; * if (xmldb_get0(h, "running", YB_MODULE, nsc, "/interface[name="eth"]", 0, &xt, NULL, &xerr) < 0) * err; * if (ret == 0){ # Not if YB_NONE * # Error handling * } * ... * xmldb_get0_clear(h, xt); # Clear tree from default values and flags * xmldb_get0_free(h, &xt); # Free tree * xml_free(xerr); * @endcode * @see xml_nsctx_node to get a XML namespace context from XML tree * @see xmldb_get for a copy version (old-style) * @note An annoying issue is one with default values and xpath miss: * Assume a yang spec: * module m { * container c { * leaf x { * default 0; * And a db content: * <c><x>1</x></c> * With the following call: * xmldb_get0(h, "running", NULL, NULL, "/c[x=0]", 1, &xt, NULL, NULL) * which result in a miss (there is no c with x=0), but when the returned xt is printed * (the existing tree is discarded), the default (empty) xml tree is: * <c><x>0</x></c> */ int xmldb_get0(clicon_handle h, const char *db, yang_bind yb, cvec *nsc, const char *xpath, int copy, cxobj **xret, modstate_diff_t *msdiff, cxobj **xerr) { int retval = -1; switch (clicon_datastore_cache(h)){ case DATASTORE_NOCACHE: /* Read from file into created/copy tree, prune non-matching xpath * Add default values in copy * Copy deleted by xmldb_free */ retval = xmldb_get_nocache(h, db, yb, nsc, xpath, xret, msdiff, xerr); break; case DATASTORE_CACHE_ZEROCOPY: /* Get cache (file if empty) mark xpath match in original tree * add default values in original tree and return that. * Default values and markings removed in xmldb_clear */ if (!copy){ retval = xmldb_get_zerocopy(h, db, yb, nsc, xpath, xret, msdiff, xerr); break; } /* fall through */ case DATASTORE_CACHE: /* Get cache (file if empty) mark xpath match and copy marked into copy * Add default values in copy, return copy * Copy deleted by xmldb_free */ retval = xmldb_get_cache(h, db, yb, nsc, xpath, xret, msdiff, xerr); break; } return retval; } /*! Clear cached xml tree obtained with xmldb_get0, if zerocopy * * @param[in] h Clicon handle * @param[in] db Name of datastore * @retval -1 General error, check specific clicon_errno, clicon_suberrno * @retval 0 OK * @note "Clear" an xml tree means removing default values and resetting all flags. * @see xmldb_get0 */ int xmldb_get0_clear(clicon_handle h, cxobj *x) { int retval = -1; if (x == NULL) goto ok; /* Mark non-presence containers */ if (xml_apply(x, CX_ELMNT, xml_nopresence_default_mark, (void*)XML_FLAG_TRANSIENT) < 0) goto done; /* Clear XML tree of defaults */ if (xml_tree_prune_flagged(x, XML_FLAG_TRANSIENT, 1) < 0) goto done; /* clear mark and change */ xml_apply0(x, CX_ELMNT, (xml_applyfn_t*)xml_flag_reset, (void*)(XML_FLAG_MARK|XML_FLAG_ADD|XML_FLAG_CHANGE)); ok: retval = 0; done: return retval; } /*! Free xml tree obtained with xmldb_get0 * @param[in] h Clixon handle * @param[in,out] xp Pointer to XML cache. * @retval 0 Always. * @see xmldb_get0 */ int xmldb_get0_free(clicon_handle h, cxobj **xp) { if (*xp == NULL) return 0; /* Note that if clicon_datastore_cache(h) fails (returns -1), the following * xml_free can fail (if **xp not obtained using xmldb_get0) */ if (clicon_datastore_cache(h) != DATASTORE_CACHE_ZEROCOPY) xml_free(*xp); *xp = NULL; return 0; }
511064.c
#include "msh.h" void replace_data(t_env *old, t_env *new) { if (new->def) old->def = new->def; free(new->key); free(new->def); } void add_data(t_env *new) { t_llst *node; node = llst_new(new); if (!node) msh_exit(1, "nomem"); llst_push(&g_msh_env, node); } void msh_env_set(t_env *entry) { t_env *old; if ((old = msh_env_get(entry->key))) replace_data(old, entry); else add_data(entry); }
171186.c
//sewer_room.c #include <std.h> inherit ROOM; void create(){ int i, j; string *names; object statue; ::create(); names = "d/dragon/sewer/statues_d"->query_statues(TO); j = sizeof(names); if(j){ for(i = 0;i<j;i++){ statue = new(OBJECT); statue->set_name(names[i]); statue->set_id(({"statue",names[i]})); statue->set_short("A stone statue of "+capitalize(names[i])); statue->set_weight(10000); statue->set_long(" This was once a famous warrior that journied the lands of Shadowgate. The accomplishments of this warrior vanished with this stone statue."); statue->move(TO); } } } void reset(){ return; }
419399.c
#line 2 "JsLexer.c" #line 4 "JsLexer.c" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ /* %not-for-header */ /* %if-c-only */ /* %if-not-reentrant */ /* %endif */ /* %endif */ /* %ok-for-header */ #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* %if-c++-only */ /* %endif */ /* %if-c-only */ /* %endif */ /* %if-c-only */ /* %endif */ /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ /* %if-c-only */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* %endif */ /* %if-tables-serialization */ /* %endif */ /* end standard C headers. */ /* %if-c-or-c++ */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ /* %endif */ /* %if-c++-only */ /* %endif */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* %not-for-header */ /* Returned upon end-of-file. */ #define YY_NULL 0 /* %ok-for-header */ /* %not-for-header */ /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* %ok-for-header */ /* %if-reentrant */ /* An opaque pointer. */ #ifndef YY_TYPEDEF_YY_SCANNER_T #define YY_TYPEDEF_YY_SCANNER_T typedef void* yyscan_t; #endif /* For convenience, these vars (plus the bison vars far below) are macros in the reentrant scanner. */ #define yyin yyg->yyin_r #define yyout yyg->yyout_r #define yyextra yyg->yyextra_r #define yyleng yyg->yyleng_r #define yytext yyg->yytext_r #define yylineno (YY_CURRENT_BUFFER_LVALUE->yy_bs_lineno) #define yycolumn (YY_CURRENT_BUFFER_LVALUE->yy_bs_column) #define yy_flex_debug yyg->yy_flex_debug_r /* %endif */ /* %if-not-reentrant */ /* %endif */ /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN yyg->yy_start = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START ((yyg->yy_start - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE yyrestart(yyin ,yyscanner ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif /* %if-not-reentrant */ /* %endif */ /* %if-c-only */ /* %if-not-reentrant */ /* %endif */ /* %endif */ #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. * One obvious solution it to make yy_act a global. I tried that, and saw * a 5% performance hit in a non-yylineno scanner, because yy_act is * normally declared as a register variable-- so it is not worth it. */ #define YY_LESS_LINENO(n) \ do { \ int yyl;\ for ( yyl = n; yyl < yyleng; ++yyl )\ if ( yytext[yyl] == '\n' )\ --yylineno;\ }while(0) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = yyg->yy_hold_char; \ YY_RESTORE_YY_MORE_OFFSET \ yyg->yy_c_buf_p = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up yytext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, yyg->yytext_ptr , yyscanner ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { /* %if-c-only */ FILE *yy_input_file; /* %endif */ /* %if-c++-only */ /* %endif */ char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via yyrestart()), so that the user can continue scanning by * just pointing yyin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* %if-c-only Standard (non-C++) definition */ /* %not-for-header */ /* %if-not-reentrant */ /* %endif */ /* %ok-for-header */ /* %endif */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( yyg->yy_buffer_stack \ ? yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE yyg->yy_buffer_stack[yyg->yy_buffer_stack_top] /* %if-c-only Standard (non-C++) definition */ /* %if-not-reentrant */ /* %not-for-header */ /* %ok-for-header */ /* %endif */ void yyrestart (FILE *input_file ,yyscan_t yyscanner ); void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); YY_BUFFER_STATE yy_create_buffer (FILE *file,int size ,yyscan_t yyscanner ); void yy_delete_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void yy_flush_buffer (YY_BUFFER_STATE b ,yyscan_t yyscanner ); void yypush_buffer_state (YY_BUFFER_STATE new_buffer ,yyscan_t yyscanner ); void yypop_buffer_state (yyscan_t yyscanner ); static void yyensure_buffer_stack (yyscan_t yyscanner ); static void yy_load_buffer_state (yyscan_t yyscanner ); static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file ,yyscan_t yyscanner ); #define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER ,yyscanner) YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size ,yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str ,yyscan_t yyscanner ); YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len ,yyscan_t yyscanner ); /* %endif */ void *yyalloc (yy_size_t ,yyscan_t yyscanner ); void *yyrealloc (void *,yy_size_t ,yyscan_t yyscanner ); void yyfree (void * ,yyscan_t yyscanner ); #define yy_new_buffer yy_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ yyensure_buffer_stack (yyscanner); \ YY_CURRENT_BUFFER_LVALUE = \ yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* %% [1.0] yytext/yyin/yyout/yy_state_type/yylineno etc. def's & init go here */ /* Begin user sect3 */ #define yywrap(n) 1 #define YY_SKIP_YYWRAP #define FLEX_DEBUG typedef unsigned char YY_CHAR; typedef int yy_state_type; #define yytext_ptr yytext_r /* %if-c-only Standard (non-C++) definition */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ,yyscan_t yyscanner); static int yy_get_next_buffer (yyscan_t yyscanner ); static void yy_fatal_error (yyconst char msg[] ,yyscan_t yyscanner ); /* %endif */ /* Done after the current pattern has been matched and before the * corresponding action - sets up yytext. */ #define YY_DO_BEFORE_ACTION \ yyg->yytext_ptr = yy_bp; \ /* %% [2.0] code to fiddle yytext and yyleng for yymore() goes here \ */\ yyleng = (size_t) (yy_cp - yy_bp); \ yyg->yy_hold_char = *yy_cp; \ *yy_cp = '\0'; \ /* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\ yyg->yy_c_buf_p = yy_cp; /* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */ #define YY_NUM_RULES 66 #define YY_END_OF_BUFFER 67 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[197] = { 0, 0, 0, 0, 0, 67, 61, 59, 60, 61, 61, 53, 61, 61, 61, 61, 61, 61, 61, 56, 61, 61, 61, 61, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 61, 63, 65, 64, 26, 0, 54, 0, 53, 25, 1, 2, 0, 55, 0, 37, 31, 30, 24, 23, 57, 0, 9, 0, 56, 56, 56, 21, 20, 12, 16, 33, 48, 53, 53, 53, 53, 10, 53, 53, 53, 53, 53, 17, 18, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 28, 29, 63, 62, 36, 54, 55, 0, 58, 56, 56, 56, 22, 35, 34, 43, 53, 53, 53, 53, 53, 53, 53, 53, 53, 14, 53, 53, 27, 53, 53, 53, 53, 53, 53, 53, 41, 53, 45, 53, 53, 44, 53, 4, 53, 53, 53, 53, 11, 53, 53, 53, 53, 51, 53, 53, 53, 39, 53, 49, 53, 46, 53, 3, 5, 53, 53, 53, 50, 53, 53, 53, 53, 53, 53, 40, 53, 47, 53, 53, 8, 53, 53, 53, 32, 38, 53, 42, 53, 7, 13, 53, 53, 53, 6, 15, 53, 53, 53, 53, 19, 53, 53, 52, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 1, 6, 7, 8, 9, 1, 1, 10, 11, 1, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 1, 1, 16, 17, 18, 1, 1, 6, 6, 6, 6, 19, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 1, 20, 1, 21, 6, 1, 22, 23, 24, 25, 26, 27, 6, 28, 29, 6, 30, 31, 6, 32, 33, 34, 6, 35, 36, 37, 38, 39, 40, 6, 41, 42, 1, 43, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[44] = { 0, 1, 2, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1, 1, 3, 1, 1, 1, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1 } ; static yyconst flex_int16_t yy_base[203] = { 0, 0, 0, 42, 43, 235, 236, 236, 236, 217, 41, 0, 216, 39, 39, 215, 38, 45, 50, 50, 34, 214, 53, 213, 194, 44, 42, 197, 50, 46, 48, 201, 40, 54, 63, 198, 41, 0, 236, 211, 207, 82, 236, 85, 0, 236, 236, 236, 83, 236, 84, 236, 236, 236, 236, 236, 236, 221, 236, 207, 93, 236, 86, 204, 236, 203, 236, 82, 236, 193, 73, 186, 80, 0, 181, 185, 183, 179, 181, 0, 176, 171, 179, 172, 179, 175, 85, 53, 172, 170, 175, 174, 236, 236, 0, 236, 236, 108, 106, 200, 236, 103, 186, 185, 236, 236, 236, 182, 176, 171, 172, 158, 172, 167, 166, 155, 168, 0, 165, 151, 0, 156, 148, 148, 160, 147, 149, 155, 0, 154, 0, 154, 147, 236, 147, 0, 148, 146, 136, 136, 0, 146, 140, 133, 147, 0, 133, 143, 138, 0, 125, 0, 131, 0, 137, 0, 0, 130, 130, 134, 0, 128, 129, 125, 124, 127, 119, 0, 126, 0, 114, 114, 0, 109, 116, 124, 0, 0, 114, 0, 120, 0, 0, 113, 114, 95, 0, 0, 92, 95, 96, 79, 0, 91, 91, 0, 236, 129, 132, 51, 135, 138, 141 } ; static yyconst flex_int16_t yy_def[203] = { 0, 196, 1, 197, 197, 196, 196, 196, 196, 196, 198, 199, 196, 196, 200, 196, 196, 196, 196, 196, 196, 196, 196, 196, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 196, 201, 196, 196, 196, 198, 196, 198, 199, 196, 196, 196, 200, 196, 200, 196, 196, 196, 196, 196, 196, 202, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 196, 196, 201, 196, 196, 198, 200, 202, 196, 196, 196, 196, 196, 196, 196, 196, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 196, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 199, 0, 196, 196, 196, 196, 196, 196 } ; static yyconst flex_int16_t yy_nxt[280] = { 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 6, 18, 19, 20, 21, 22, 11, 6, 23, 11, 24, 25, 26, 27, 28, 11, 29, 11, 11, 30, 11, 11, 31, 32, 33, 11, 34, 35, 11, 11, 36, 38, 38, 42, 46, 49, 52, 63, 64, 39, 39, 44, 53, 47, 54, 92, 50, 56, 43, 55, 59, 57, 60, 70, 58, 72, 61, 66, 67, 75, 79, 81, 73, 62, 71, 80, 76, 84, 85, 86, 77, 93, 89, 82, 42, 78, 87, 97, 127, 49, 98, 128, 88, 90, 102, 102, 106, 107, 103, 43, 50, 50, 43, 59, 112, 60, 109, 110, 113, 61, 42, 125, 49, 195, 194, 101, 62, 126, 193, 61, 192, 191, 190, 50, 189, 43, 62, 37, 37, 37, 41, 41, 41, 48, 48, 48, 94, 188, 94, 99, 99, 99, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, 175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, 159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 103, 103, 100, 132, 131, 130, 129, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 111, 108, 105, 104, 101, 100, 96, 95, 91, 83, 74, 69, 68, 65, 51, 45, 40, 196, 5, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196 } ; static yyconst flex_int16_t yy_chk[280] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 4, 10, 13, 14, 16, 20, 20, 3, 4, 199, 16, 13, 17, 36, 14, 18, 10, 17, 19, 18, 19, 25, 18, 26, 19, 22, 22, 28, 29, 30, 26, 19, 25, 29, 28, 32, 32, 33, 28, 36, 34, 30, 41, 28, 33, 43, 87, 48, 50, 87, 33, 34, 62, 62, 67, 67, 62, 41, 48, 50, 43, 60, 72, 60, 70, 70, 72, 60, 97, 86, 98, 194, 193, 101, 60, 86, 191, 101, 190, 189, 188, 98, 185, 97, 101, 197, 197, 197, 198, 198, 198, 200, 200, 200, 201, 184, 201, 202, 202, 202, 183, 180, 178, 175, 174, 173, 171, 170, 168, 166, 165, 164, 163, 162, 161, 159, 158, 157, 154, 152, 150, 148, 147, 146, 144, 143, 142, 141, 139, 138, 137, 136, 134, 132, 131, 129, 127, 126, 125, 124, 123, 122, 121, 119, 118, 116, 115, 114, 113, 112, 111, 110, 109, 108, 107, 103, 102, 99, 91, 90, 89, 88, 85, 84, 83, 82, 81, 80, 78, 77, 76, 75, 74, 71, 69, 65, 63, 59, 57, 40, 39, 35, 31, 27, 24, 23, 21, 15, 12, 9, 5, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196, 196 } ; /* Table of booleans, true if rule could match eol. */ static yyconst flex_int32_t yy_rule_can_match_eol[67] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, }; static yyconst flex_int16_t yy_rule_linenum[66] = { 0, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 80, 87, 94, 100, 101, 102, 103, 104, 114, 115, 116, 117 } ; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET #line 1 "JsLexer.l" #line 2 "JsLexer.l" #include "JsToken.h" /* Generated by bison. */ #include "JsSys.h" #include <stdlib.h> #include <string.h> #include <ctype.h> #define YY_NO_INPUT 1 #line 693 "JsLexer.c" #define INITIAL 0 #define IN_COMMENT 1 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ /* %if-c-only */ #include <unistd.h> /* %endif */ /* %if-c++-only */ /* %endif */ #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif /* %if-c-only Reentrant structure and macros (non-C++). */ /* %if-reentrant */ /* Holds the entire state of the reentrant scanner. */ struct yyguts_t { /* User-defined. Not touched by flex. */ YY_EXTRA_TYPE yyextra_r; /* The rest are the same as the globals declared in the non-reentrant scanner. */ FILE *yyin_r, *yyout_r; size_t yy_buffer_stack_top; /**< index of top of stack. */ size_t yy_buffer_stack_max; /**< capacity of stack. */ YY_BUFFER_STATE * yy_buffer_stack; /**< Stack as an array. */ char yy_hold_char; int yy_n_chars; int yyleng_r; char *yy_c_buf_p; int yy_init; int yy_start; int yy_did_buffer_switch_on_eof; int yy_start_stack_ptr; int yy_start_stack_depth; int *yy_start_stack; yy_state_type yy_last_accepting_state; char* yy_last_accepting_cpos; int yylineno_r; int yy_flex_debug_r; char *yytext_r; int yy_more_flag; int yy_more_len; YYSTYPE * yylval_r; }; /* end struct yyguts_t */ /* %if-c-only */ static int yy_init_globals (yyscan_t yyscanner ); /* %endif */ /* %if-reentrant */ /* This must go here because YYSTYPE and YYLTYPE are included * from bison output in section 1.*/ # define yylval yyg->yylval_r int yylex_init (yyscan_t* scanner); int yylex_init_extra (YY_EXTRA_TYPE user_defined,yyscan_t* scanner); /* %endif */ /* %endif End reentrant structures and macros. */ /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int yylex_destroy (yyscan_t yyscanner ); int yyget_debug (yyscan_t yyscanner ); void yyset_debug (int debug_flag ,yyscan_t yyscanner ); YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner ); void yyset_extra (YY_EXTRA_TYPE user_defined ,yyscan_t yyscanner ); FILE *yyget_in (yyscan_t yyscanner ); void yyset_in (FILE * in_str ,yyscan_t yyscanner ); FILE *yyget_out (yyscan_t yyscanner ); void yyset_out (FILE * out_str ,yyscan_t yyscanner ); int yyget_leng (yyscan_t yyscanner ); char *yyget_text (yyscan_t yyscanner ); int yyget_lineno (yyscan_t yyscanner ); void yyset_lineno (int line_number ,yyscan_t yyscanner ); /* %if-bison-bridge */ YYSTYPE * yyget_lval (yyscan_t yyscanner ); void yyset_lval (YYSTYPE * yylval_param ,yyscan_t yyscanner ); /* %endif */ /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int yywrap (yyscan_t yyscanner ); #else extern int yywrap (yyscan_t yyscanner ); #endif #endif /* %not-for-header */ /* %ok-for-header */ /* %endif */ #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ,yyscan_t yyscanner); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ,yyscan_t yyscanner); #endif #ifndef YY_NO_INPUT /* %if-c-only Standard (non-C++) definition */ /* %not-for-header */ #ifdef __cplusplus static int yyinput (yyscan_t yyscanner ); #else static int input (yyscan_t yyscanner ); #endif /* %ok-for-header */ /* %endif */ #endif /* %if-c-only */ /* %endif */ /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* %if-c-only Standard (non-C++) definition */ /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( yytext, yyleng, 1, yyout )) {} } while (0) /* %endif */ /* %if-c++-only C++ definition */ /* %endif */ #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ /* %% [5.0] fread()/read() definition of YY_INPUT goes here unless we're doing C++ \ */\ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( yyin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(yyin); \ } \ }\ \ /* %if-c++-only C++ definition \ */\ /* %endif */ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR /* %if-c-only */ #define YY_FATAL_ERROR(msg) yy_fatal_error( msg , yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ #endif /* %if-tables-serialization structures and prototypes */ /* %not-for-header */ /* %ok-for-header */ /* %not-for-header */ /* %tables-yydmap generated elements */ /* %endif */ /* end tables serialization structures and prototypes */ /* %ok-for-header */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 /* %if-c-only Standard (non-C++) definition */ extern int yylex \ (YYSTYPE * yylval_param ,yyscan_t yyscanner); #define YY_DECL int yylex \ (YYSTYPE * yylval_param , yyscan_t yyscanner) /* %endif */ /* %if-c++-only C++ definition */ /* %endif */ #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after yytext and yyleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif /* %% [6.0] YY_RULE_SETUP definition goes here */ #define YY_RULE_SETUP \ YY_USER_ACTION /* %not-for-header */ /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* %% [7.0] user's declarations go here */ #line 17 "JsLexer.l" #line 998 "JsLexer.c" yylval = yylval_param; if ( !yyg->yy_init ) { yyg->yy_init = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! yyg->yy_start ) yyg->yy_start = 1; /* first start state */ if ( ! yyin ) /* %if-c-only */ yyin = stdin; /* %endif */ /* %if-c++-only */ /* %endif */ if ( ! yyout ) /* %if-c-only */ yyout = stdout; /* %endif */ /* %if-c++-only */ /* %endif */ if ( ! YY_CURRENT_BUFFER ) { yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } yy_load_buffer_state(yyscanner ); } while ( 1 ) /* loops until end-of-file is reached */ { /* %% [8.0] yymore()-related code goes here */ yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; /* %% [9.0] code to set up and find next match goes here */ yy_current_state = yyg->yy_start; yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 197 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 236 ); yy_find_action: /* %% [10.0] code to find the action number goes here */ yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; /* %% [11.0] code for yylineno update goes here */ if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ /* %% [12.0] debug code goes here */ if ( yy_flex_debug ) { if ( yy_act == 0 ) fprintf( stderr, "--scanner backing up\n" ); else if ( yy_act < 66 ) fprintf( stderr, "--accepting rule at line %ld (\"%s\")\n", (long)yy_rule_linenum[yy_act], yytext ); else if ( yy_act == 66 ) fprintf( stderr, "--accepting default rule (\"%s\")\n", yytext ); else if ( yy_act == 67 ) fprintf( stderr, "--(end of buffer or a NUL)\n" ); else fprintf( stderr, "--EOF (start condition %d)\n", YY_START ); } switch ( yy_act ) { /* beginning of action switch */ /* %% [13.0] actions go here */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 21 "JsLexer.l" return tANDAND; YY_BREAK case 2: YY_RULE_SETUP #line 22 "JsLexer.l" return tANDEQ; YY_BREAK case 3: YY_RULE_SETUP #line 23 "JsLexer.l" return tBREAK; YY_BREAK case 4: YY_RULE_SETUP #line 24 "JsLexer.l" return tCASE; YY_BREAK case 5: YY_RULE_SETUP #line 25 "JsLexer.l" return tCATCH; YY_BREAK case 6: YY_RULE_SETUP #line 26 "JsLexer.l" return tCONTINUE; YY_BREAK case 7: YY_RULE_SETUP #line 27 "JsLexer.l" return tDEFAULT; YY_BREAK case 8: YY_RULE_SETUP #line 28 "JsLexer.l" return tDELETE; YY_BREAK case 9: YY_RULE_SETUP #line 29 "JsLexer.l" return tDIVEQ; YY_BREAK case 10: YY_RULE_SETUP #line 30 "JsLexer.l" return tDO; YY_BREAK case 11: YY_RULE_SETUP #line 31 "JsLexer.l" return tELSE; YY_BREAK case 12: YY_RULE_SETUP #line 32 "JsLexer.l" return tEQ; YY_BREAK case 13: YY_RULE_SETUP #line 33 "JsLexer.l" return tFINALLY; YY_BREAK case 14: YY_RULE_SETUP #line 34 "JsLexer.l" return tFOR; YY_BREAK case 15: YY_RULE_SETUP #line 35 "JsLexer.l" return tFUNCTION; YY_BREAK case 16: YY_RULE_SETUP #line 36 "JsLexer.l" return tGE; YY_BREAK case 17: YY_RULE_SETUP #line 37 "JsLexer.l" return tIF; YY_BREAK case 18: YY_RULE_SETUP #line 38 "JsLexer.l" return tIN; YY_BREAK case 19: YY_RULE_SETUP #line 39 "JsLexer.l" return tINSTANCEOF; YY_BREAK case 20: YY_RULE_SETUP #line 40 "JsLexer.l" return tLE; YY_BREAK case 21: YY_RULE_SETUP #line 41 "JsLexer.l" return tLSHIFT; YY_BREAK case 22: YY_RULE_SETUP #line 42 "JsLexer.l" return tLSHIFTEQ; YY_BREAK case 23: YY_RULE_SETUP #line 43 "JsLexer.l" return tMINUSEQ; YY_BREAK case 24: YY_RULE_SETUP #line 44 "JsLexer.l" return tMINUSMINUS; YY_BREAK case 25: YY_RULE_SETUP #line 45 "JsLexer.l" return tMODEQ; YY_BREAK case 26: YY_RULE_SETUP #line 46 "JsLexer.l" return tNE; YY_BREAK case 27: YY_RULE_SETUP #line 47 "JsLexer.l" return tNEW; YY_BREAK case 28: YY_RULE_SETUP #line 48 "JsLexer.l" return tOREQ; YY_BREAK case 29: YY_RULE_SETUP #line 49 "JsLexer.l" return tOROR; YY_BREAK case 30: YY_RULE_SETUP #line 50 "JsLexer.l" return tPLUSEQ; YY_BREAK case 31: YY_RULE_SETUP #line 51 "JsLexer.l" return tPLUSPLUS; YY_BREAK case 32: YY_RULE_SETUP #line 52 "JsLexer.l" return tRETURN; YY_BREAK case 33: YY_RULE_SETUP #line 53 "JsLexer.l" return tRSHIFT; YY_BREAK case 34: YY_RULE_SETUP #line 54 "JsLexer.l" return tRSHIFTEQ; YY_BREAK case 35: YY_RULE_SETUP #line 55 "JsLexer.l" return tSEQ; YY_BREAK case 36: YY_RULE_SETUP #line 56 "JsLexer.l" return tSNE; YY_BREAK case 37: YY_RULE_SETUP #line 57 "JsLexer.l" return tSTAREQ; YY_BREAK case 38: YY_RULE_SETUP #line 58 "JsLexer.l" return tSWITCH; YY_BREAK case 39: YY_RULE_SETUP #line 59 "JsLexer.l" return tTHIS; YY_BREAK case 40: YY_RULE_SETUP #line 60 "JsLexer.l" return tTHROW; YY_BREAK case 41: YY_RULE_SETUP #line 61 "JsLexer.l" return tTRY; YY_BREAK case 42: YY_RULE_SETUP #line 62 "JsLexer.l" return tTYPEOF; YY_BREAK case 43: YY_RULE_SETUP #line 63 "JsLexer.l" return tURSHIFT; YY_BREAK case 44: YY_RULE_SETUP #line 64 "JsLexer.l" return tURSHIFTEQ; YY_BREAK case 45: YY_RULE_SETUP #line 65 "JsLexer.l" return tVAR; YY_BREAK case 46: YY_RULE_SETUP #line 66 "JsLexer.l" return tVOID; YY_BREAK case 47: YY_RULE_SETUP #line 67 "JsLexer.l" return tWHILE; YY_BREAK case 48: YY_RULE_SETUP #line 68 "JsLexer.l" return tXOREQ; YY_BREAK case 49: YY_RULE_SETUP #line 69 "JsLexer.l" return tTRUE; YY_BREAK case 50: YY_RULE_SETUP #line 70 "JsLexer.l" return tFALSE; YY_BREAK case 51: YY_RULE_SETUP #line 71 "JsLexer.l" return tNULL; YY_BREAK case 52: YY_RULE_SETUP #line 72 "JsLexer.l" return tSYNCHRONIZED; YY_BREAK case 53: YY_RULE_SETUP #line 74 "JsLexer.l" { yylval->string = (char*)JsGcMalloc(yyleng+1,NULL,NULL); strcpy(yylval->string,yytext); return tIDENT; } YY_BREAK case 54: /* rule 54 can match eol */ YY_RULE_SETUP #line 80 "JsLexer.l" { yylval->string = (char*)JsGcMalloc(yyleng-1,NULL,NULL); memcpy(yylval->string,yytext+1,yyleng-2); yylval->string[yyleng-2] = '\0'; return tSTRING; } YY_BREAK case 55: /* rule 55 can match eol */ YY_RULE_SETUP #line 87 "JsLexer.l" { yylval->string = (char*)JsGcMalloc(yyleng-1,NULL,NULL); memcpy(yylval->string,yytext+1,yyleng-2); yylval->string[yyleng-2] = '\0'; return tSTRING; } YY_BREAK case 56: YY_RULE_SETUP #line 94 "JsLexer.l" { yylval->number = atof(yytext); return tNUMBER; } YY_BREAK case 57: YY_RULE_SETUP #line 100 "JsLexer.l" BEGIN(IN_COMMENT); YY_BREAK case 58: *yy_cp = yyg->yy_hold_char; /* undo effects of setting up yytext */ yyg->yy_c_buf_p = yy_cp -= 1; YY_DO_BEFORE_ACTION; /* set up yytext again */ YY_RULE_SETUP #line 101 "JsLexer.l" { } YY_BREAK case 59: /* rule 59 can match eol */ YY_RULE_SETUP #line 102 "JsLexer.l" { return tLINETERMINATOR;} YY_BREAK case 60: /* rule 60 can match eol */ YY_RULE_SETUP #line 103 "JsLexer.l" { return tLINETERMINATOR;} YY_BREAK case 61: YY_RULE_SETUP #line 104 "JsLexer.l" { if (!isspace(*yytext)) { return *yytext; } } YY_BREAK /* INITIAL */ case 62: YY_RULE_SETUP #line 114 "JsLexer.l" BEGIN(INITIAL); YY_BREAK case 63: YY_RULE_SETUP #line 115 "JsLexer.l" {} YY_BREAK case 64: YY_RULE_SETUP #line 116 "JsLexer.l" {} YY_BREAK case 65: /* rule 65 can match eol */ YY_RULE_SETUP #line 117 "JsLexer.l" {} YY_BREAK case 66: YY_RULE_SETUP #line 119 "JsLexer.l" YY_FATAL_ERROR( "flex scanner jammed" ); YY_BREAK #line 1489 "JsLexer.c" case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(IN_COMMENT): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { /* %% [14.0] code to do back-up for compressed tables and set up yy_cp goes here */ yy_cp = yyg->yy_c_buf_p; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of yylex */ /* %ok-for-header */ /* %if-c++-only */ /* %not-for-header */ /* %ok-for-header */ /* %endif */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ /* %if-c-only */ static int yy_get_next_buffer (yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = yyg->yytext_ptr; register int number_to_move, i; int ret_val; if ( yyg->yy_c_buf_p > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( yyg->yy_c_buf_p - yyg->yytext_ptr - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) (yyg->yy_c_buf_p - yyg->yytext_ptr) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) (yyg->yy_c_buf_p - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ,yyscanner ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); yyg->yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), yyg->yy_n_chars, (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } if ( yyg->yy_n_chars == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; yyrestart(yyin ,yyscanner); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) (yyg->yy_n_chars + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = yyg->yy_n_chars + number_to_move + (yyg->yy_n_chars >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) yyrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ,yyscanner ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } yyg->yy_n_chars += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; yyg->yytext_ptr = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ /* %if-c-only */ /* %not-for-header */ static yy_state_type yy_get_previous_state (yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { register yy_state_type yy_current_state; register char *yy_cp; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* %% [15.0] code to get the start state into yy_current_state goes here */ yy_current_state = yyg->yy_start; for ( yy_cp = yyg->yytext_ptr + YY_MORE_ADJ; yy_cp < yyg->yy_c_buf_p; ++yy_cp ) { /* %% [16.0] code to find the next state goes here */ register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 197 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ /* %if-c-only */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { register int yy_is_jam; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* This var may be unused depending upon options. */ /* %% [17.0] code to find the next state, and perhaps do backing up, goes here */ register char *yy_cp = yyg->yy_c_buf_p; register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 197 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 196); return yy_is_jam ? 0 : yy_current_state; } /* %if-c-only */ /* %endif */ /* %if-c-only */ #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (yyscan_t yyscanner) #else static int input (yyscan_t yyscanner) #endif /* %endif */ /* %if-c++-only */ /* %endif */ { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ int offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; /* %% [19.0] update BOL and yylineno */ if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; } /* %if-c-only */ #endif /* ifndef YY_NO_INPUT */ /* %endif */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * @param yyscanner The scanner object. * @note This function does not reset the start condition to @c INITIAL . */ /* %if-c-only */ void yyrestart (FILE * input_file , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (yyscanner); YY_CURRENT_BUFFER_LVALUE = yy_create_buffer(yyin,YY_BUF_SIZE ,yyscanner); } yy_init_buffer(YY_CURRENT_BUFFER,input_file ,yyscanner); yy_load_buffer_state(yyscanner ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * @param yyscanner The scanner object. */ /* %if-c-only */ void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); * yypush_buffer_state(new_buffer); */ yyensure_buffer_stack (yyscanner); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } YY_CURRENT_BUFFER_LVALUE = new_buffer; yy_load_buffer_state(yyscanner ); /* We don't actually know whether we did this switch during * EOF (yywrap()) processing, but the only time this flag * is looked at is after yywrap() is called, so it's safe * to go ahead and always set it. */ yyg->yy_did_buffer_switch_on_eof = 1; } /* %if-c-only */ static void yy_load_buffer_state (yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; yyg->yytext_ptr = yyg->yy_c_buf_p = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; yyg->yy_hold_char = *yyg->yy_c_buf_p; } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * @param yyscanner The scanner object. * @return the allocated buffer state. */ /* %if-c-only */ YY_BUFFER_STATE yy_create_buffer (FILE * file, int size , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2 ,yyscanner ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); b->yy_is_our_buffer = 1; yy_init_buffer(b,file ,yyscanner); return b; } /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() * @param yyscanner The scanner object. */ /* %if-c-only */ void yy_delete_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) yyfree((void *) b->yy_ch_buf ,yyscanner ); yyfree((void *) b ,yyscanner ); } /* %if-c-only */ #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* %endif */ /* %if-c++-only */ /* %endif */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a yyrestart() or at EOF. */ /* %if-c-only */ static void yy_init_buffer (YY_BUFFER_STATE b, FILE * file , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { int oerrno = errno; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flush_buffer(b ,yyscanner); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then yy_init_buffer was _probably_ * called from yyrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } /* %if-c-only */ b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; /* %endif */ /* %if-c++-only */ /* %endif */ errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * @param yyscanner The scanner object. */ /* %if-c-only */ void yy_flush_buffer (YY_BUFFER_STATE b , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) yy_load_buffer_state(yyscanner ); } /* %if-c-or-c++ */ /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * @param yyscanner The scanner object. */ /* %if-c-only */ void yypush_buffer_state (YY_BUFFER_STATE new_buffer , yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (new_buffer == NULL) return; yyensure_buffer_stack(yyscanner); /* This block is copied from yy_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *yyg->yy_c_buf_p = yyg->yy_hold_char; YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = yyg->yy_c_buf_p; YY_CURRENT_BUFFER_LVALUE->yy_n_chars = yyg->yy_n_chars; } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) yyg->yy_buffer_stack_top++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from yy_switch_to_buffer. */ yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } /* %endif */ /* %if-c-or-c++ */ /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * @param yyscanner The scanner object. */ /* %if-c-only */ void yypop_buffer_state (yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!YY_CURRENT_BUFFER) return; yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner); YY_CURRENT_BUFFER_LVALUE = NULL; if (yyg->yy_buffer_stack_top > 0) --yyg->yy_buffer_stack_top; if (YY_CURRENT_BUFFER) { yy_load_buffer_state(yyscanner ); yyg->yy_did_buffer_switch_on_eof = 1; } } /* %endif */ /* %if-c-or-c++ */ /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ /* %if-c-only */ static void yyensure_buffer_stack (yyscan_t yyscanner) /* %endif */ /* %if-c++-only */ /* %endif */ { int num_to_alloc; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (!yyg->yy_buffer_stack) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; yyg->yy_buffer_stack = (struct yy_buffer_state**)yyalloc (num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); memset(yyg->yy_buffer_stack, 0, num_to_alloc * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; yyg->yy_buffer_stack_top = 0; return; } if (yyg->yy_buffer_stack_top >= (yyg->yy_buffer_stack_max) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = yyg->yy_buffer_stack_max + grow_size; yyg->yy_buffer_stack = (struct yy_buffer_state**)yyrealloc (yyg->yy_buffer_stack, num_to_alloc * sizeof(struct yy_buffer_state*) , yyscanner); if ( ! yyg->yy_buffer_stack ) YY_FATAL_ERROR( "out of dynamic memory in yyensure_buffer_stack()" ); /* zero only the new slots.*/ memset(yyg->yy_buffer_stack + yyg->yy_buffer_stack_max, 0, grow_size * sizeof(struct yy_buffer_state*)); yyg->yy_buffer_stack_max = num_to_alloc; } } /* %endif */ /* %if-c-only */ /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_buffer (char * base, yy_size_t size , yyscan_t yyscanner) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state ) ,yyscanner ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; yy_switch_to_buffer(b ,yyscanner ); return b; } /* %endif */ /* %if-c-only */ /** Setup the input buffer state to scan a string. The next call to yylex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * @param yyscanner The scanner object. * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * yy_scan_bytes() instead. */ YY_BUFFER_STATE yy_scan_string (yyconst char * yystr , yyscan_t yyscanner) { return yy_scan_bytes(yystr,strlen(yystr) ,yyscanner); } /* %endif */ /* %if-c-only */ /** Setup the input buffer state to scan the given bytes. The next call to yylex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * @param yyscanner The scanner object. * @return the newly allocated buffer state object. */ YY_BUFFER_STATE yy_scan_bytes (yyconst char * yybytes, int _yybytes_len , yyscan_t yyscanner) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) yyalloc(n ,yyscanner ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = yy_scan_buffer(buf,n ,yyscanner); if ( ! b ) YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } /* %endif */ #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif /* %if-c-only */ static void yy_fatal_error (yyconst char* msg , yyscan_t yyscanner) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* %endif */ /* %if-c++-only */ /* %endif */ /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up yytext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ yytext[yyleng] = yyg->yy_hold_char; \ yyg->yy_c_buf_p = yytext + yyless_macro_arg; \ yyg->yy_hold_char = *yyg->yy_c_buf_p; \ *yyg->yy_c_buf_p = '\0'; \ yyleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /* %if-c-only */ /* %if-reentrant */ /** Get the user-defined data for this scanner. * @param yyscanner The scanner object. */ YY_EXTRA_TYPE yyget_extra (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyextra; } /* %endif */ /** Get the current line number. * @param yyscanner The scanner object. */ int yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; } /** Get the current column number. * @param yyscanner The scanner object. */ int yyget_column (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yycolumn; } /** Get the input stream. * @param yyscanner The scanner object. */ FILE *yyget_in (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyin; } /** Get the output stream. * @param yyscanner The scanner object. */ FILE *yyget_out (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyout; } /** Get the length of the current token. * @param yyscanner The scanner object. */ int yyget_leng (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yyleng; } /** Get the current token. * @param yyscanner The scanner object. */ char *yyget_text (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yytext; } /* %if-reentrant */ /** Set the user-defined data. This data is never touched by the scanner. * @param user_defined The data to be associated with this scanner. * @param yyscanner The scanner object. */ void yyset_extra (YY_EXTRA_TYPE user_defined , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyextra = user_defined ; } /* %endif */ /** Set the current line number. * @param line_number * @param yyscanner The scanner object. */ void yyset_lineno (int line_number , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* lineno is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "yyset_lineno called with no buffer" , yyscanner); yylineno = line_number; } /** Set the current column. * @param line_number * @param yyscanner The scanner object. */ void yyset_column (int column_no , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* column is only valid if an input buffer exists. */ if (! YY_CURRENT_BUFFER ) yy_fatal_error( "yyset_column called with no buffer" , yyscanner); yycolumn = column_no; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * @param yyscanner The scanner object. * @see yy_switch_to_buffer */ void yyset_in (FILE * in_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyin = in_str ; } void yyset_out (FILE * out_str , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yyout = out_str ; } int yyget_debug (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yy_flex_debug; } void yyset_debug (int bdebug , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yy_flex_debug = bdebug ; } /* %endif */ /* %if-reentrant */ /* Accessor methods for yylval and yylloc */ /* %if-bison-bridge */ YYSTYPE * yyget_lval (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; return yylval; } void yyset_lval (YYSTYPE * yylval_param , yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; yylval = yylval_param; } /* %endif */ /* User-visible API */ /* yylex_init is special because it creates the scanner itself, so it is * the ONLY reentrant function that doesn't take the scanner as the last argument. * That's why we explicitly handle the declaration, instead of using our macros. */ int yylex_init(yyscan_t* ptr_yy_globals) { if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), NULL ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); return yy_init_globals ( *ptr_yy_globals ); } /* yylex_init_extra has the same functionality as yylex_init, but follows the * convention of taking the scanner as the last argument. Note however, that * this is a *pointer* to a scanner, as it will be allocated by this call (and * is the reason, too, why this function also must handle its own declaration). * The user defined value in the first argument will be available to yyalloc in * the yyextra field. */ int yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); } /* %endif if-c-only */ /* %if-c-only */ static int yy_init_globals (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Initialization is the same as for the non-reentrant scanner. * This function is called from yylex_destroy(), so don't allocate here. */ yyg->yy_buffer_stack = 0; yyg->yy_buffer_stack_top = 0; yyg->yy_buffer_stack_max = 0; yyg->yy_c_buf_p = (char *) 0; yyg->yy_init = 0; yyg->yy_start = 0; yyg->yy_start_stack_ptr = 0; yyg->yy_start_stack_depth = 0; yyg->yy_start_stack = NULL; /* Defined in main.c */ #ifdef YY_STDINIT yyin = stdin; yyout = stdout; #else yyin = (FILE *) 0; yyout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * yylex_init() */ return 0; } /* %endif */ /* %if-c-only SNIP! this currently causes conflicts with the c++ scanner */ /* yylex_destroy is for both reentrant and non-reentrant scanners. */ int yylex_destroy (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ yy_delete_buffer(YY_CURRENT_BUFFER ,yyscanner ); YY_CURRENT_BUFFER_LVALUE = NULL; yypop_buffer_state(yyscanner); } /* Destroy the stack itself. */ yyfree(yyg->yy_buffer_stack ,yyscanner); yyg->yy_buffer_stack = NULL; /* Destroy the start condition stack. */ yyfree(yyg->yy_start_stack ,yyscanner ); yyg->yy_start_stack = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * yylex() is called, initialization will occur. */ yy_init_globals( yyscanner); /* %if-reentrant */ /* Destroy the main struct (reentrant only). */ yyfree ( yyscanner , yyscanner ); yyscanner = NULL; /* %endif */ return 0; } /* %endif */ /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n , yyscan_t yyscanner) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s , yyscan_t yyscanner) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *yyalloc (yy_size_t size , yyscan_t yyscanner) { return (void *) malloc( size ); } void *yyrealloc (void * ptr, yy_size_t size , yyscan_t yyscanner) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void yyfree (void * ptr , yyscan_t yyscanner) { free( (char *) ptr ); /* see yyrealloc() for (char *) cast */ } /* %if-tables-serialization definitions */ /* %define-yytables The name for this specific scanner's tables. */ #define YYTABLES_NAME "yytables" /* %endif */ /* %ok-for-header */ #line 119 "JsLexer.l"
316492.c
// SPDX-License-Identifier: GPL-2.0-or-later /* Mantis PCI bridge driver Copyright (C) Manu Abraham ([email protected]) */ #include <linux/kernel.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/interrupt.h> #include <asm/io.h> #include <media/dmxdev.h> #include <media/dvbdev.h> #include <media/dvb_demux.h> #include <media/dvb_frontend.h> #include <media/dvb_net.h> #include "mantis_common.h" #include "mantis_hif.h" #include "mantis_link.h" /* temporary due to physical layer stuff */ #include "mantis_reg.h" static int mantis_hif_sbuf_opdone_wait(struct mantis_ca *ca) { struct mantis_pci *mantis = ca->ca_priv; int rc = 0; if (wait_event_timeout(ca->hif_opdone_wq, ca->hif_event & MANTIS_SBUF_OPDONE, msecs_to_jiffies(500)) == -ERESTARTSYS) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): Smart buffer operation timeout !", mantis->num); rc = -EREMOTEIO; } dprintk(MANTIS_DEBUG, 1, "Smart Buffer Operation complete"); ca->hif_event &= ~MANTIS_SBUF_OPDONE; return rc; } static int mantis_hif_write_wait(struct mantis_ca *ca) { struct mantis_pci *mantis = ca->ca_priv; u32 opdone = 0, timeout = 0; int rc = 0; if (wait_event_timeout(ca->hif_write_wq, mantis->gpif_status & MANTIS_GPIF_WRACK, msecs_to_jiffies(500)) == -ERESTARTSYS) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): Write ACK timed out !", mantis->num); rc = -EREMOTEIO; } dprintk(MANTIS_DEBUG, 1, "Write Acknowledged"); mantis->gpif_status &= ~MANTIS_GPIF_WRACK; while (!opdone) { opdone = (mmread(MANTIS_GPIF_STATUS) & MANTIS_SBUF_OPDONE); udelay(500); timeout++; if (timeout > 100) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): Write operation timed out!", mantis->num); rc = -ETIMEDOUT; break; } } dprintk(MANTIS_DEBUG, 1, "HIF Write success"); return rc; } int mantis_hif_read_mem(struct mantis_ca *ca, u32 addr) { struct mantis_pci *mantis = ca->ca_priv; u32 hif_addr = 0, data, count = 4; dprintk(MANTIS_DEBUG, 1, "Adapter(%d) Slot(0): Request HIF Mem Read", mantis->num); mutex_lock(&ca->ca_lock); hif_addr &= ~MANTIS_GPIF_PCMCIAREG; hif_addr &= ~MANTIS_GPIF_PCMCIAIOM; hif_addr |= MANTIS_HIF_STATUS; hif_addr |= addr; mmwrite(hif_addr, MANTIS_GPIF_BRADDR); mmwrite(count, MANTIS_GPIF_BRBYTES); udelay(20); mmwrite(hif_addr | MANTIS_GPIF_HIFRDWRN, MANTIS_GPIF_ADDR); if (mantis_hif_sbuf_opdone_wait(ca) != 0) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): GPIF Smart Buffer operation failed", mantis->num); mutex_unlock(&ca->ca_lock); return -EREMOTEIO; } data = mmread(MANTIS_GPIF_DIN); mutex_unlock(&ca->ca_lock); dprintk(MANTIS_DEBUG, 1, "Mem Read: 0x%02x", data); return (data >> 24) & 0xff; } int mantis_hif_write_mem(struct mantis_ca *ca, u32 addr, u8 data) { struct mantis_slot *slot = ca->slot; struct mantis_pci *mantis = ca->ca_priv; u32 hif_addr = 0; dprintk(MANTIS_DEBUG, 1, "Adapter(%d) Slot(0): Request HIF Mem Write", mantis->num); mutex_lock(&ca->ca_lock); hif_addr &= ~MANTIS_GPIF_HIFRDWRN; hif_addr &= ~MANTIS_GPIF_PCMCIAREG; hif_addr &= ~MANTIS_GPIF_PCMCIAIOM; hif_addr |= MANTIS_HIF_STATUS; hif_addr |= addr; mmwrite(slot->slave_cfg, MANTIS_GPIF_CFGSLA); /* Slot0 alone for now */ mmwrite(hif_addr, MANTIS_GPIF_ADDR); mmwrite(data, MANTIS_GPIF_DOUT); if (mantis_hif_write_wait(ca) != 0) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): HIF Smart Buffer operation failed", mantis->num); mutex_unlock(&ca->ca_lock); return -EREMOTEIO; } dprintk(MANTIS_DEBUG, 1, "Mem Write: (0x%02x to 0x%02x)", data, addr); mutex_unlock(&ca->ca_lock); return 0; } int mantis_hif_read_iom(struct mantis_ca *ca, u32 addr) { struct mantis_pci *mantis = ca->ca_priv; u32 data, hif_addr = 0; dprintk(MANTIS_DEBUG, 1, "Adapter(%d) Slot(0): Request HIF I/O Read", mantis->num); mutex_lock(&ca->ca_lock); hif_addr &= ~MANTIS_GPIF_PCMCIAREG; hif_addr |= MANTIS_GPIF_PCMCIAIOM; hif_addr |= MANTIS_HIF_STATUS; hif_addr |= addr; mmwrite(hif_addr, MANTIS_GPIF_BRADDR); mmwrite(1, MANTIS_GPIF_BRBYTES); udelay(20); mmwrite(hif_addr | MANTIS_GPIF_HIFRDWRN, MANTIS_GPIF_ADDR); if (mantis_hif_sbuf_opdone_wait(ca) != 0) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): HIF Smart Buffer operation failed", mantis->num); mutex_unlock(&ca->ca_lock); return -EREMOTEIO; } data = mmread(MANTIS_GPIF_DIN); dprintk(MANTIS_DEBUG, 1, "I/O Read: 0x%02x", data); udelay(50); mutex_unlock(&ca->ca_lock); return (u8) data; } int mantis_hif_write_iom(struct mantis_ca *ca, u32 addr, u8 data) { struct mantis_pci *mantis = ca->ca_priv; u32 hif_addr = 0; dprintk(MANTIS_DEBUG, 1, "Adapter(%d) Slot(0): Request HIF I/O Write", mantis->num); mutex_lock(&ca->ca_lock); hif_addr &= ~MANTIS_GPIF_PCMCIAREG; hif_addr &= ~MANTIS_GPIF_HIFRDWRN; hif_addr |= MANTIS_GPIF_PCMCIAIOM; hif_addr |= MANTIS_HIF_STATUS; hif_addr |= addr; mmwrite(hif_addr, MANTIS_GPIF_ADDR); mmwrite(data, MANTIS_GPIF_DOUT); if (mantis_hif_write_wait(ca) != 0) { dprintk(MANTIS_ERROR, 1, "Adapter(%d) Slot(0): HIF Smart Buffer operation failed", mantis->num); mutex_unlock(&ca->ca_lock); return -EREMOTEIO; } dprintk(MANTIS_DEBUG, 1, "I/O Write: (0x%02x to 0x%02x)", data, addr); mutex_unlock(&ca->ca_lock); udelay(50); return 0; } int mantis_hif_init(struct mantis_ca *ca) { struct mantis_slot *slot = ca->slot; struct mantis_pci *mantis = ca->ca_priv; u32 irqcfg; slot[0].slave_cfg = 0x70773028; dprintk(MANTIS_ERROR, 1, "Adapter(%d) Initializing Mantis Host Interface", mantis->num); mutex_lock(&ca->ca_lock); irqcfg = mmread(MANTIS_GPIF_IRQCFG); irqcfg = MANTIS_MASK_BRRDY | MANTIS_MASK_WRACK | MANTIS_MASK_EXTIRQ | MANTIS_MASK_WSTO | MANTIS_MASK_OTHERR | MANTIS_MASK_OVFLW; mmwrite(irqcfg, MANTIS_GPIF_IRQCFG); mutex_unlock(&ca->ca_lock); return 0; } void mantis_hif_exit(struct mantis_ca *ca) { struct mantis_pci *mantis = ca->ca_priv; u32 irqcfg; dprintk(MANTIS_ERROR, 1, "Adapter(%d) Exiting Mantis Host Interface", mantis->num); mutex_lock(&ca->ca_lock); irqcfg = mmread(MANTIS_GPIF_IRQCFG); irqcfg &= ~MANTIS_MASK_BRRDY; mmwrite(irqcfg, MANTIS_GPIF_IRQCFG); mutex_unlock(&ca->ca_lock); }
630801.c
/* * Emma Mobile GPIO Support - GIO * * Copyright (C) 2012 Magnus Damm * * 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 * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/init.h> #include <linux/platform_device.h> #include <linux/spinlock.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/io.h> #include <linux/irq.h> #include <linux/irqdomain.h> #include <linux/bitops.h> #include <linux/err.h> #include <linux/gpio.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/pinctrl/consumer.h> #include <linux/platform_data/gpio-em.h> struct em_gio_priv { void __iomem *base0; void __iomem *base1; spinlock_t sense_lock; struct platform_device *pdev; struct gpio_chip gpio_chip; struct irq_chip irq_chip; struct irq_domain *irq_domain; }; #define GIO_E1 0x00 #define GIO_E0 0x04 #define GIO_EM 0x04 #define GIO_OL 0x08 #define GIO_OH 0x0c #define GIO_I 0x10 #define GIO_IIA 0x14 #define GIO_IEN 0x18 #define GIO_IDS 0x1c #define GIO_IIM 0x1c #define GIO_RAW 0x20 #define GIO_MST 0x24 #define GIO_IIR 0x28 #define GIO_IDT0 0x40 #define GIO_IDT1 0x44 #define GIO_IDT2 0x48 #define GIO_IDT3 0x4c #define GIO_RAWBL 0x50 #define GIO_RAWBH 0x54 #define GIO_IRBL 0x58 #define GIO_IRBH 0x5c #define GIO_IDT(n) (GIO_IDT0 + ((n) * 4)) static inline unsigned long em_gio_read(struct em_gio_priv *p, int offs) { if (offs < GIO_IDT0) return ioread32(p->base0 + offs); else return ioread32(p->base1 + (offs - GIO_IDT0)); } static inline void em_gio_write(struct em_gio_priv *p, int offs, unsigned long value) { if (offs < GIO_IDT0) iowrite32(value, p->base0 + offs); else iowrite32(value, p->base1 + (offs - GIO_IDT0)); } static void em_gio_irq_disable(struct irq_data *d) { struct em_gio_priv *p = irq_data_get_irq_chip_data(d); em_gio_write(p, GIO_IDS, BIT(irqd_to_hwirq(d))); } static void em_gio_irq_enable(struct irq_data *d) { struct em_gio_priv *p = irq_data_get_irq_chip_data(d); em_gio_write(p, GIO_IEN, BIT(irqd_to_hwirq(d))); } static unsigned int em_gio_irq_startup(struct irq_data *d) { struct em_gio_priv *p = irq_data_get_irq_chip_data(d); if (gpio_lock_as_irq(&p->gpio_chip, irqd_to_hwirq(d))) dev_err(p->gpio_chip.dev, "unable to lock HW IRQ %lu for IRQ\n", irqd_to_hwirq(d)); em_gio_irq_enable(d); return 0; } static void em_gio_irq_shutdown(struct irq_data *d) { struct em_gio_priv *p = irq_data_get_irq_chip_data(d); em_gio_irq_disable(d); gpio_unlock_as_irq(&p->gpio_chip, irqd_to_hwirq(d)); } #define GIO_ASYNC(x) (x + 8) static unsigned char em_gio_sense_table[IRQ_TYPE_SENSE_MASK + 1] = { [IRQ_TYPE_EDGE_RISING] = GIO_ASYNC(0x00), [IRQ_TYPE_EDGE_FALLING] = GIO_ASYNC(0x01), [IRQ_TYPE_LEVEL_HIGH] = GIO_ASYNC(0x02), [IRQ_TYPE_LEVEL_LOW] = GIO_ASYNC(0x03), [IRQ_TYPE_EDGE_BOTH] = GIO_ASYNC(0x04), }; static int em_gio_irq_set_type(struct irq_data *d, unsigned int type) { unsigned char value = em_gio_sense_table[type & IRQ_TYPE_SENSE_MASK]; struct em_gio_priv *p = irq_data_get_irq_chip_data(d); unsigned int reg, offset, shift; unsigned long flags; unsigned long tmp; if (!value) return -EINVAL; offset = irqd_to_hwirq(d); pr_debug("gio: sense irq = %d, mode = %d\n", offset, value); /* 8 x 4 bit fields in 4 IDT registers */ reg = GIO_IDT(offset >> 3); shift = (offset & 0x07) << 4; spin_lock_irqsave(&p->sense_lock, flags); /* disable the interrupt in IIA */ tmp = em_gio_read(p, GIO_IIA); tmp &= ~BIT(offset); em_gio_write(p, GIO_IIA, tmp); /* change the sense setting in IDT */ tmp = em_gio_read(p, reg); tmp &= ~(0xf << shift); tmp |= value << shift; em_gio_write(p, reg, tmp); /* clear pending interrupts */ em_gio_write(p, GIO_IIR, BIT(offset)); /* enable the interrupt in IIA */ tmp = em_gio_read(p, GIO_IIA); tmp |= BIT(offset); em_gio_write(p, GIO_IIA, tmp); spin_unlock_irqrestore(&p->sense_lock, flags); return 0; } static irqreturn_t em_gio_irq_handler(int irq, void *dev_id) { struct em_gio_priv *p = dev_id; unsigned long pending; unsigned int offset, irqs_handled = 0; while ((pending = em_gio_read(p, GIO_MST))) { offset = __ffs(pending); em_gio_write(p, GIO_IIR, BIT(offset)); generic_handle_irq(irq_find_mapping(p->irq_domain, offset)); irqs_handled++; } return irqs_handled ? IRQ_HANDLED : IRQ_NONE; } static inline struct em_gio_priv *gpio_to_priv(struct gpio_chip *chip) { return container_of(chip, struct em_gio_priv, gpio_chip); } static int em_gio_direction_input(struct gpio_chip *chip, unsigned offset) { em_gio_write(gpio_to_priv(chip), GIO_E0, BIT(offset)); return 0; } static int em_gio_get(struct gpio_chip *chip, unsigned offset) { return (int)(em_gio_read(gpio_to_priv(chip), GIO_I) & BIT(offset)); } static void __em_gio_set(struct gpio_chip *chip, unsigned int reg, unsigned shift, int value) { /* upper 16 bits contains mask and lower 16 actual value */ em_gio_write(gpio_to_priv(chip), reg, (1 << (shift + 16)) | (value << shift)); } static void em_gio_set(struct gpio_chip *chip, unsigned offset, int value) { /* output is split into two registers */ if (offset < 16) __em_gio_set(chip, GIO_OL, offset, value); else __em_gio_set(chip, GIO_OH, offset - 16, value); } static int em_gio_direction_output(struct gpio_chip *chip, unsigned offset, int value) { /* write GPIO value to output before selecting output mode of pin */ em_gio_set(chip, offset, value); em_gio_write(gpio_to_priv(chip), GIO_E1, BIT(offset)); return 0; } static int em_gio_to_irq(struct gpio_chip *chip, unsigned offset) { return irq_create_mapping(gpio_to_priv(chip)->irq_domain, offset); } static int em_gio_request(struct gpio_chip *chip, unsigned offset) { return pinctrl_request_gpio(chip->base + offset); } static void em_gio_free(struct gpio_chip *chip, unsigned offset) { pinctrl_free_gpio(chip->base + offset); /* Set the GPIO as an input to ensure that the next GPIO request won't * drive the GPIO pin as an output. */ em_gio_direction_input(chip, offset); } static int em_gio_irq_domain_map(struct irq_domain *h, unsigned int irq, irq_hw_number_t hwirq) { struct em_gio_priv *p = h->host_data; pr_debug("gio: map hw irq = %d, irq = %d\n", (int)hwirq, irq); irq_set_chip_data(irq, h->host_data); irq_set_chip_and_handler(irq, &p->irq_chip, handle_level_irq); set_irq_flags(irq, IRQF_VALID); /* kill me now */ return 0; } static struct irq_domain_ops em_gio_irq_domain_ops = { .map = em_gio_irq_domain_map, .xlate = irq_domain_xlate_twocell, }; static int em_gio_probe(struct platform_device *pdev) { struct gpio_em_config pdata_dt; struct gpio_em_config *pdata = dev_get_platdata(&pdev->dev); struct em_gio_priv *p; struct resource *io[2], *irq[2]; struct gpio_chip *gpio_chip; struct irq_chip *irq_chip; const char *name = dev_name(&pdev->dev); int ret; p = devm_kzalloc(&pdev->dev, sizeof(*p), GFP_KERNEL); if (!p) { dev_err(&pdev->dev, "failed to allocate driver data\n"); ret = -ENOMEM; goto err0; } p->pdev = pdev; platform_set_drvdata(pdev, p); spin_lock_init(&p->sense_lock); io[0] = platform_get_resource(pdev, IORESOURCE_MEM, 0); io[1] = platform_get_resource(pdev, IORESOURCE_MEM, 1); irq[0] = platform_get_resource(pdev, IORESOURCE_IRQ, 0); irq[1] = platform_get_resource(pdev, IORESOURCE_IRQ, 1); if (!io[0] || !io[1] || !irq[0] || !irq[1]) { dev_err(&pdev->dev, "missing IRQ or IOMEM\n"); ret = -EINVAL; goto err0; } p->base0 = devm_ioremap_nocache(&pdev->dev, io[0]->start, resource_size(io[0])); if (!p->base0) { dev_err(&pdev->dev, "failed to remap low I/O memory\n"); ret = -ENXIO; goto err0; } p->base1 = devm_ioremap_nocache(&pdev->dev, io[1]->start, resource_size(io[1])); if (!p->base1) { dev_err(&pdev->dev, "failed to remap high I/O memory\n"); ret = -ENXIO; goto err0; } if (!pdata) { memset(&pdata_dt, 0, sizeof(pdata_dt)); pdata = &pdata_dt; if (of_property_read_u32(pdev->dev.of_node, "ngpios", &pdata->number_of_pins)) { dev_err(&pdev->dev, "Missing ngpios OF property\n"); ret = -EINVAL; goto err0; } ret = of_alias_get_id(pdev->dev.of_node, "gpio"); if (ret < 0) { dev_err(&pdev->dev, "Couldn't get OF id\n"); goto err0; } pdata->gpio_base = ret * 32; /* 32 GPIOs per instance */ } gpio_chip = &p->gpio_chip; gpio_chip->of_node = pdev->dev.of_node; gpio_chip->direction_input = em_gio_direction_input; gpio_chip->get = em_gio_get; gpio_chip->direction_output = em_gio_direction_output; gpio_chip->set = em_gio_set; gpio_chip->to_irq = em_gio_to_irq; gpio_chip->request = em_gio_request; gpio_chip->free = em_gio_free; gpio_chip->label = name; gpio_chip->dev = &pdev->dev; gpio_chip->owner = THIS_MODULE; gpio_chip->base = pdata->gpio_base; gpio_chip->ngpio = pdata->number_of_pins; irq_chip = &p->irq_chip; irq_chip->name = name; irq_chip->irq_mask = em_gio_irq_disable; irq_chip->irq_unmask = em_gio_irq_enable; irq_chip->irq_set_type = em_gio_irq_set_type; irq_chip->irq_startup = em_gio_irq_startup; irq_chip->irq_shutdown = em_gio_irq_shutdown; irq_chip->flags = IRQCHIP_SKIP_SET_WAKE | IRQCHIP_MASK_ON_SUSPEND; p->irq_domain = irq_domain_add_simple(pdev->dev.of_node, pdata->number_of_pins, pdata->irq_base, &em_gio_irq_domain_ops, p); if (!p->irq_domain) { ret = -ENXIO; dev_err(&pdev->dev, "cannot initialize irq domain\n"); goto err0; } if (devm_request_irq(&pdev->dev, irq[0]->start, em_gio_irq_handler, 0, name, p)) { dev_err(&pdev->dev, "failed to request low IRQ\n"); ret = -ENOENT; goto err1; } if (devm_request_irq(&pdev->dev, irq[1]->start, em_gio_irq_handler, 0, name, p)) { dev_err(&pdev->dev, "failed to request high IRQ\n"); ret = -ENOENT; goto err1; } ret = gpiochip_add(gpio_chip); if (ret) { dev_err(&pdev->dev, "failed to add GPIO controller\n"); goto err1; } if (pdata->pctl_name) { ret = gpiochip_add_pin_range(gpio_chip, pdata->pctl_name, 0, gpio_chip->base, gpio_chip->ngpio); if (ret < 0) dev_warn(&pdev->dev, "failed to add pin range\n"); } return 0; err1: irq_domain_remove(p->irq_domain); err0: return ret; } static int em_gio_remove(struct platform_device *pdev) { struct em_gio_priv *p = platform_get_drvdata(pdev); int ret; ret = gpiochip_remove(&p->gpio_chip); if (ret) return ret; irq_domain_remove(p->irq_domain); return 0; } static const struct of_device_id em_gio_dt_ids[] = { { .compatible = "renesas,em-gio", }, {}, }; MODULE_DEVICE_TABLE(of, em_gio_dt_ids); static struct platform_driver em_gio_device_driver = { .probe = em_gio_probe, .remove = em_gio_remove, .driver = { .name = "em_gio", .of_match_table = em_gio_dt_ids, .owner = THIS_MODULE, } }; static int __init em_gio_init(void) { return platform_driver_register(&em_gio_device_driver); } postcore_initcall(em_gio_init); static void __exit em_gio_exit(void) { platform_driver_unregister(&em_gio_device_driver); } module_exit(em_gio_exit); MODULE_AUTHOR("Magnus Damm"); MODULE_DESCRIPTION("Renesas Emma Mobile GIO Driver"); MODULE_LICENSE("GPL v2");
190748.c
/* * Copyright (c) 1988,1990,1993,1994,2021 by Paul Vixie ("VIXIE") * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") * Copyright (c) 1997,2000 by Internet Software Consortium, Inc. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND VIXIE DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL VIXIE 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(LINT) static char rcsid[] = "$Id: entry.c,v 1.17 2004/01/23 18:56:42 vixie Exp $"; #endif /* vix 26jan87 [RCS'd; rest of log is in RCS file] * vix 01jan87 [added line-level error recovery] * vix 31dec86 [added /step to the from-to range, per bob@acornrc] * vix 30dec86 [written] */ #include "cron.h" typedef enum ecode { e_none, e_minute, e_hour, e_dom, e_month, e_dow, e_cmd, e_timespec, e_username, e_option, e_memory } ecode_e; static const char *ecodes[] = { "no error", "bad minute", "bad hour", "bad day-of-month", "bad month", "bad day-of-week", "bad command", "bad time specifier", "bad username", "bad option", "out of memory" }; static int get_list(bitstr_t *, int, int, const char *[], int, FILE *), get_range(bitstr_t *, int, int, const char *[], int, FILE *), get_number(int *, int, const char *[], int, FILE *, const char *), set_element(bitstr_t *, int, int, int); void free_entry(entry *e) { free(e->cmd); free(e->pwd); env_free(e->envp); free(e); } /* return NULL if eof or syntax error occurs; * otherwise return a pointer to a new entry. */ entry * load_entry(FILE *file, void (*error_func)(), struct passwd *pw, char **envp) { /* this function reads one crontab entry -- the next -- from a file. * it skips any leading blank lines, ignores comments, and returns * NULL if for any reason the entry can't be read and parsed. * * the entry is also parsed here. * * syntax: * user crontab: * minutes hours doms months dows cmd\n * system crontab (/etc/crontab): * minutes hours doms months dows USERNAME cmd\n */ ecode_e ecode = e_none; entry *e; int ch; char cmd[MAX_COMMAND]; char envstr[MAX_ENVSTR]; char **tenvp; Debug(DPARS, ("load_entry()...about to eat comments\n")) skip_comments(file); ch = get_char(file); if (ch == EOF) return (NULL); /* ch is now the first useful character of a useful line. * it may be an @special or it may be the first character * of a list of minutes. */ e = (entry *) calloc(sizeof(entry), sizeof(char)); if (ch == '@') { /* all of these should be flagged and load-limited; i.e., * instead of @hourly meaning "0 * * * *" it should mean * "close to the front of every hour but not 'til the * system load is low". Problems are: how do you know * what "low" means? (save me from /etc/cron.conf!) and: * how to guarantee low variance (how low is low?), which * means how to we run roughly every hour -- seems like * we need to keep a history or let the first hour set * the schedule, which means we aren't load-limited * anymore. too much for my overloaded brain. (vix, jan90) * HINT */ ch = get_string(cmd, MAX_COMMAND, file, " \t\n"); if (!strcmp("reboot", cmd)) { e->flags |= WHEN_REBOOT; } else if (!strcmp("yearly", cmd) || !strcmp("annually", cmd)){ bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); bit_set(e->month, 0); bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); e->flags |= DOW_STAR; } else if (!strcmp("monthly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_set(e->dom, 0); bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); e->flags |= DOW_STAR; } else if (!strcmp("weekly", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); bit_set(e->dow, 0); e->flags |= DOW_STAR; } else if (!strcmp("daily", cmd) || !strcmp("midnight", cmd)) { bit_set(e->minute, 0); bit_set(e->hour, 0); bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); } else if (!strcmp("hourly", cmd)) { bit_set(e->minute, 0); bit_nset(e->hour, 0, (LAST_HOUR-FIRST_HOUR+1)); bit_nset(e->dom, 0, (LAST_DOM-FIRST_DOM+1)); bit_nset(e->month, 0, (LAST_MONTH-FIRST_MONTH+1)); bit_nset(e->dow, 0, (LAST_DOW-FIRST_DOW+1)); e->flags |= HR_STAR; } else { ecode = e_timespec; goto eof; } /* Advance past whitespace between shortcut and * username/command. */ Skip_Blanks(ch, file); if (ch == EOF || ch == '\n') { ecode = e_cmd; goto eof; } } else { Debug(DPARS, ("load_entry()...about to parse numerics\n")) if (ch == '*') e->flags |= MIN_STAR; ch = get_list(e->minute, FIRST_MINUTE, LAST_MINUTE, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_minute; goto eof; } /* hours */ if (ch == '*') e->flags |= HR_STAR; ch = get_list(e->hour, FIRST_HOUR, LAST_HOUR, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_hour; goto eof; } /* DOM (days of month) */ if (ch == '*') e->flags |= DOM_STAR; ch = get_list(e->dom, FIRST_DOM, LAST_DOM, PPC_NULL, ch, file); if (ch == EOF) { ecode = e_dom; goto eof; } /* month */ ch = get_list(e->month, FIRST_MONTH, LAST_MONTH, MonthNames, ch, file); if (ch == EOF) { ecode = e_month; goto eof; } /* DOW (days of week) */ if (ch == '*') e->flags |= DOW_STAR; ch = get_list(e->dow, FIRST_DOW, LAST_DOW, DowNames, ch, file); if (ch == EOF) { ecode = e_dow; goto eof; } } /* make sundays equivalent */ if (bit_test(e->dow, 0) || bit_test(e->dow, 7)) { bit_set(e->dow, 0); bit_set(e->dow, 7); } /* check for permature EOL and catch a common typo */ if (ch == '\n' || ch == '*') { ecode = e_cmd; goto eof; } /* ch is the first character of a command, or a username */ unget_char(ch, file); if (!pw) { char *username = cmd; /* temp buffer */ Debug(DPARS, ("load_entry()...about to parse username\n")) ch = get_string(username, MAX_COMMAND, file, " \t\n"); Debug(DPARS, ("load_entry()...got %s\n",username)) if (ch == EOF || ch == '\n' || ch == '*') { ecode = e_cmd; goto eof; } pw = getpwnam(username); if (pw == NULL) { ecode = e_username; goto eof; } Debug(DPARS, ("load_entry()...uid %ld, gid %ld\n", (long)pw->pw_uid, (long)pw->pw_gid)) } if ((e->pwd = pw_dup(pw)) == NULL) { ecode = e_memory; goto eof; } bzero(e->pwd->pw_passwd, strlen(e->pwd->pw_passwd)); /* copy and fix up environment. some variables are just defaults and * others are overrides. */ if ((e->envp = env_copy(envp)) == NULL) { ecode = e_memory; goto eof; } if (!env_get("SHELL", e->envp)) { if (glue_strings(envstr, sizeof envstr, "SHELL", _PATH_BSHELL, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "error", "can't set SHELL"); } if (!env_get("HOME", e->envp)) { if (glue_strings(envstr, sizeof envstr, "HOME", pw->pw_dir, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "error", "can't set HOME"); } #ifndef LOGIN_CAP /* If login.conf is in used we will get the default PATH later. */ if (!env_get("PATH", e->envp)) { if (glue_strings(envstr, sizeof envstr, "PATH", _PATH_DEFPATH, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "error", "can't set PATH"); } #endif /* LOGIN_CAP */ if (glue_strings(envstr, sizeof envstr, "LOGNAME", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "error", "can't set LOGNAME"); #if defined(BSD) || defined(__linux) if (glue_strings(envstr, sizeof envstr, "USER", pw->pw_name, '=')) { if ((tenvp = env_set(e->envp, envstr)) == NULL) { ecode = e_memory; goto eof; } e->envp = tenvp; } else log_it("CRON", getpid(), "error", "can't set USER"); #endif Debug(DPARS, ("load_entry()...about to parse command\n")) /* If the first character of the command is '-' it is a cron option. */ while ((ch = get_char(file)) == '-') { switch (ch = get_char(file)) { case 'q': e->flags |= DONT_LOG; Skip_Nonblanks(ch, file) break; default: ecode = e_option; goto eof; } Skip_Blanks(ch, file) if (ch == EOF || ch == '\n') { ecode = e_cmd; goto eof; } } unget_char(ch, file); /* Everything up to the next \n or EOF is part of the command... * too bad we don't know in advance how long it will be, since we * need to malloc a string for it... so, we limit it to MAX_COMMAND. */ ch = get_string(cmd, MAX_COMMAND, file, "\n"); /* a file without a \n before the EOF is rude, so we'll complain... */ if (ch == EOF) { ecode = e_cmd; goto eof; } /* got the command in the 'cmd' string; save it in *e. */ if ((e->cmd = strdup(cmd)) == NULL) { ecode = e_memory; goto eof; } Debug(DPARS, ("load_entry()...returning successfully\n")) /* success, fini, return pointer to the entry we just created... */ return (e); eof: if (e->envp) env_free(e->envp); if (e->pwd) free(e->pwd); if (e->cmd) free(e->cmd); free(e); while (ch != '\n' && !feof(file)) ch = get_char(file); if (ecode != e_none && error_func) (*error_func)(ecodes[(int)ecode]); return (NULL); } static int get_list(bitstr_t *bits, int low, int high, const char *names[], int ch, FILE *file) { int done; /* we know that we point to a non-blank character here; * must do a Skip_Blanks before we exit, so that the * next call (or the code that picks up the cmd) can * assume the same thing. */ Debug(DPARS|DEXT, ("get_list()...entered\n")) /* list = range {"," range} */ /* clear the bit string, since the default is 'off'. */ bit_nclear(bits, 0, (high-low+1)); /* process all ranges */ done = FALSE; while (!done) { if (EOF == (ch = get_range(bits, low, high, names, ch, file))) return (EOF); if (ch == ',') ch = get_char(file); else done = TRUE; } /* exiting. skip to some blanks, then skip over the blanks. */ Skip_Nonblanks(ch, file) Skip_Blanks(ch, file) Debug(DPARS|DEXT, ("get_list()...exiting w/ %02x\n", ch)) return (ch); } static int get_range(bitstr_t *bits, int low, int high, const char *names[], int ch, FILE *file) { /* range = number | number "-" number [ "/" number ] */ int i, num1, num2, num3; Debug(DPARS|DEXT, ("get_range()...entering, exit won't show\n")) if (ch == '*') { /* '*' means "first-last" but can still be modified by /step */ num1 = low; num2 = high; ch = get_char(file); if (ch == EOF) return (EOF); } else { ch = get_number(&num1, low, names, ch, file, ",- \t\n"); if (ch == EOF) return (EOF); if (ch != '-') { /* not a range, it's a single number. */ if (EOF == set_element(bits, low, high, num1)) { unget_char(ch, file); return (EOF); } return (ch); } else { /* eat the dash */ ch = get_char(file); if (ch == EOF) return (EOF); /* get the number following the dash */ ch = get_number(&num2, low, names, ch, file, "/, \t\n"); if (ch == EOF || num1 > num2) return (EOF); } } /* check for step size */ if (ch == '/') { /* eat the slash */ ch = get_char(file); if (ch == EOF) return (EOF); /* get the step size -- note: we don't pass the * names here, because the number is not an * element id, it's a step size. 'low' is * sent as a 0 since there is no offset either. */ ch = get_number(&num3, 0, PPC_NULL, ch, file, ", \t\n"); if (ch == EOF || num3 == 0) return (EOF); } else { /* no step. default==1. */ num3 = 1; } /* range. set all elements from num1 to num2, stepping * by num3. (the step is a downward-compatible extension * proposed conceptually by bob@acornrc, syntactically * designed then implemented by paul vixie). */ for (i = num1; i <= num2; i += num3) if (EOF == set_element(bits, low, high, i)) { unget_char(ch, file); return (EOF); } return (ch); } static int get_number(int *numptr, int low, const char *names[], int ch, FILE *file, const char *terms) { char temp[MAX_TEMPSTR], *pc; int len, i; pc = temp; len = 0; /* first look for a number */ while (isdigit((unsigned char)ch)) { if (++len >= MAX_TEMPSTR) goto bad; *pc++ = ch; ch = get_char(file); } *pc = '\0'; if (len != 0) { /* got a number, check for valid terminator */ if (!strchr(terms, ch)) goto bad; *numptr = atoi(temp); return (ch); } /* no numbers, look for a string if we have any */ if (names) { while (isalpha((unsigned char)ch)) { if (++len >= MAX_TEMPSTR) goto bad; *pc++ = ch; ch = get_char(file); } *pc = '\0'; if (len != 0 && strchr(terms, ch)) { for (i = 0; names[i] != NULL; i++) { Debug(DPARS|DEXT, ("get_num, compare(%s,%s)\n", names[i], temp)) if (!strcasecmp(names[i], temp)) { *numptr = i+low; return (ch); } } } } bad: unget_char(ch, file); return (EOF); } static int set_element(bitstr_t *bits, int low, int high, int number) { Debug(DPARS|DEXT, ("set_element(?,%d,%d,%d)\n", low, high, number)) if (number < low || number > high) return (EOF); bit_set(bits, (number-low)); return (OK); }
885794.c
/* version 20080912 D. J. Bernstein Public domain. */ #define ROUNDS 20 #define CRYPTO_KEYBYTES 32 #define CRYPTO_NONCEBYTES 8 #define CRYPTO_OUTPUTBYTES 64 #define CRYPTO_INPUTBYTES 16 typedef unsigned int uint32; static const unsigned char sigma[16] = "expand 32-byte k"; static uint32 rotate(uint32 u,int c) { return (u << c) | (u >> (32 - c)); } static uint32 load_littleendian(const unsigned char *x) { return (uint32) (x[0]) \ | (((uint32) (x[1])) << 8) \ | (((uint32) (x[2])) << 16) \ | (((uint32) (x[3])) << 24) ; } static void store_littleendian(unsigned char *x,uint32 u) { x[0] = u; u >>= 8; x[1] = u; u >>= 8; x[2] = u; u >>= 8; x[3] = u; } int crypto_core( unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c ) { uint32 x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; uint32 j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15; int i; j0 = x0 = load_littleendian(c + 0); j1 = x1 = load_littleendian(k + 0); j2 = x2 = load_littleendian(k + 4); j3 = x3 = load_littleendian(k + 8); j4 = x4 = load_littleendian(k + 12); j5 = x5 = load_littleendian(c + 4); j6 = x6 = load_littleendian(in + 0); j7 = x7 = load_littleendian(in + 4); j8 = x8 = load_littleendian(in + 8); j9 = x9 = load_littleendian(in + 12); j10 = x10 = load_littleendian(c + 8); j11 = x11 = load_littleendian(k + 16); j12 = x12 = load_littleendian(k + 20); j13 = x13 = load_littleendian(k + 24); j14 = x14 = load_littleendian(k + 28); j15 = x15 = load_littleendian(c + 12); for (i = ROUNDS;i > 0;i -= 2) { x4 ^= rotate( x0+x12, 7); x8 ^= rotate( x4+ x0, 9); x12 ^= rotate( x8+ x4,13); x0 ^= rotate(x12+ x8,18); x9 ^= rotate( x5+ x1, 7); x13 ^= rotate( x9+ x5, 9); x1 ^= rotate(x13+ x9,13); x5 ^= rotate( x1+x13,18); x14 ^= rotate(x10+ x6, 7); x2 ^= rotate(x14+x10, 9); x6 ^= rotate( x2+x14,13); x10 ^= rotate( x6+ x2,18); x3 ^= rotate(x15+x11, 7); x7 ^= rotate( x3+x15, 9); x11 ^= rotate( x7+ x3,13); x15 ^= rotate(x11+ x7,18); x1 ^= rotate( x0+ x3, 7); x2 ^= rotate( x1+ x0, 9); x3 ^= rotate( x2+ x1,13); x0 ^= rotate( x3+ x2,18); x6 ^= rotate( x5+ x4, 7); x7 ^= rotate( x6+ x5, 9); x4 ^= rotate( x7+ x6,13); x5 ^= rotate( x4+ x7,18); x11 ^= rotate(x10+ x9, 7); x8 ^= rotate(x11+x10, 9); x9 ^= rotate( x8+x11,13); x10 ^= rotate( x9+ x8,18); x12 ^= rotate(x15+x14, 7); x13 ^= rotate(x12+x15, 9); x14 ^= rotate(x13+x12,13); x15 ^= rotate(x14+x13,18); } x0 += j0; x1 += j1; x2 += j2; x3 += j3; x4 += j4; x5 += j5; x6 += j6; x7 += j7; x8 += j8; x9 += j9; x10 += j10; x11 += j11; x12 += j12; x13 += j13; x14 += j14; x15 += j15; store_littleendian(out + 0,x0); store_littleendian(out + 4,x1); store_littleendian(out + 8,x2); store_littleendian(out + 12,x3); store_littleendian(out + 16,x4); store_littleendian(out + 20,x5); store_littleendian(out + 24,x6); store_littleendian(out + 28,x7); store_littleendian(out + 32,x8); store_littleendian(out + 36,x9); store_littleendian(out + 40,x10); store_littleendian(out + 44,x11); store_littleendian(out + 48,x12); store_littleendian(out + 52,x13); store_littleendian(out + 56,x14); store_littleendian(out + 60,x15); return 0; } int nfl_crypto_stream_salsa20( unsigned char *c,unsigned long long clen, const unsigned char *n, const unsigned char *k ) { unsigned char in[16]; unsigned char block[64]; unsigned char kcopy[32]; int i; unsigned int u; if (!clen) return 0; for (i = 0;i < 32;++i) kcopy[i] = k[i]; for (i = 0;i < 8;++i) in[i] = n[i]; for (i = 8;i < 16;++i) in[i] = 0; while (clen >= 64) { crypto_core_salsa20(c,in,kcopy,sigma); u = 1; for (i = 8;i < 16;++i) { u += (unsigned int) in[i]; in[i] = u; u >>= 8; } clen -= 64; c += 64; } if (clen) { crypto_core_salsa20(block,in,kcopy,sigma); for (i = 0;i < clen;++i) c[i] = block[i]; } return 0; }
739874.c
/*************************************************************************** * * rw/_heap.c * * $Id: //stdlib/dev/include/rw/_heap.c#2 $ * *************************************************************************** * * Copyright (c) 1994-2005 Quovadx, Inc., acting through its Rogue Wave * Software division. 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 <rw/_heap.cc>
796036.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. */ #include <stdio.h> #include <sys/types.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <stropts.h> #include <ctype.h> #include <errno.h> #include <stdlib.h> #include <door.h> #include <sys/mman.h> #include <libscf.h> #include <libscf_priv.h> #include <libdllink.h> #include <libdlbridge.h> #include <libdladm_impl.h> #include <stp_in.h> #include <net/bridge.h> #include <net/trill.h> #include <sys/socket.h> #include <sys/dld_ioc.h> /* * Bridge Administration Library. * * This library is used by administration tools such as dladm(1M) to configure * bridges, and by the bridge daemon to retrieve configuration information. */ #define BRIDGE_SVC_NAME "network/bridge" #define TRILL_SVC_NAME "network/routing/trill" #define DEFAULT_TIMEOUT 60000000 #define INIT_WAIT_USECS 50000 #define MAXPORTS 256 typedef struct scf_state { scf_handle_t *ss_handle; scf_instance_t *ss_inst; scf_service_t *ss_svc; scf_snapshot_t *ss_snap; scf_propertygroup_t *ss_pg; scf_property_t *ss_prop; } scf_state_t; static void shut_down_scf(scf_state_t *sstate) { scf_instance_destroy(sstate->ss_inst); (void) scf_handle_unbind(sstate->ss_handle); scf_handle_destroy(sstate->ss_handle); } static char * alloc_fmri(const char *service, const char *instance_name) { ssize_t max_fmri; char *fmri; /* If the limit is unknown, then use an arbitrary value */ if ((max_fmri = scf_limit(SCF_LIMIT_MAX_FMRI_LENGTH)) == -1) max_fmri = 1024; if ((fmri = malloc(max_fmri)) != NULL) { (void) snprintf(fmri, max_fmri, "svc:/%s:%s", service, instance_name); } return (fmri); } /* * Start up SCF and bind the requested instance alone. */ static int bind_instance(const char *service, const char *instance_name, scf_state_t *sstate) { char *fmri = NULL; (void) memset(sstate, 0, sizeof (*sstate)); if ((sstate->ss_handle = scf_handle_create(SCF_VERSION)) == NULL) return (-1); if (scf_handle_bind(sstate->ss_handle) != 0) goto failure; sstate->ss_inst = scf_instance_create(sstate->ss_handle); if (sstate->ss_inst == NULL) goto failure; fmri = alloc_fmri(service, instance_name); if (scf_handle_decode_fmri(sstate->ss_handle, fmri, NULL, NULL, sstate->ss_inst, NULL, NULL, SCF_DECODE_FMRI_REQUIRE_INSTANCE) != 0) goto failure; free(fmri); return (0); failure: free(fmri); shut_down_scf(sstate); return (-1); } /* * Start up SCF and an exact FMRI. This is used for creating new instances and * enable/disable actions. */ static dladm_status_t exact_instance(const char *fmri, scf_state_t *sstate) { dladm_status_t status; (void) memset(sstate, 0, sizeof (*sstate)); if ((sstate->ss_handle = scf_handle_create(SCF_VERSION)) == NULL) return (DLADM_STATUS_NOMEM); status = DLADM_STATUS_FAILED; if (scf_handle_bind(sstate->ss_handle) != 0) goto failure; sstate->ss_svc = scf_service_create(sstate->ss_handle); if (sstate->ss_svc == NULL) goto failure; if (scf_handle_decode_fmri(sstate->ss_handle, fmri, NULL, sstate->ss_svc, NULL, NULL, NULL, SCF_DECODE_FMRI_EXACT) != 0) { if (scf_error() == SCF_ERROR_NOT_FOUND) status = DLADM_STATUS_OPTMISSING; goto failure; } sstate->ss_inst = scf_instance_create(sstate->ss_handle); if (sstate->ss_inst == NULL) goto failure; return (DLADM_STATUS_OK); failure: shut_down_scf(sstate); return (status); } static void drop_composed(scf_state_t *sstate) { scf_property_destroy(sstate->ss_prop); scf_pg_destroy(sstate->ss_pg); scf_snapshot_destroy(sstate->ss_snap); } /* * This function sets up a composed view of the configuration information for * the specified instance. When this is done, the get_property() function * should be able to return individual parameters. */ static int get_composed_properties(const char *lpg, boolean_t snap, scf_state_t *sstate) { sstate->ss_snap = NULL; sstate->ss_pg = NULL; sstate->ss_prop = NULL; if (snap) { sstate->ss_snap = scf_snapshot_create(sstate->ss_handle); if (sstate->ss_snap == NULL) goto failure; if (scf_instance_get_snapshot(sstate->ss_inst, "running", sstate->ss_snap) != 0) goto failure; } if ((sstate->ss_pg = scf_pg_create(sstate->ss_handle)) == NULL) goto failure; if (scf_instance_get_pg_composed(sstate->ss_inst, sstate->ss_snap, lpg, sstate->ss_pg) != 0) goto failure; if ((sstate->ss_prop = scf_property_create(sstate->ss_handle)) == NULL) goto failure; return (0); failure: drop_composed(sstate); return (-1); } static int get_count(const char *lprop, scf_state_t *sstate, uint64_t *answer) { scf_value_t *val; int retv; if (scf_pg_get_property(sstate->ss_pg, lprop, sstate->ss_prop) != 0) return (-1); if ((val = scf_value_create(sstate->ss_handle)) == NULL) return (-1); if (scf_property_get_value(sstate->ss_prop, val) == 0 && scf_value_get_count(val, answer) == 0) retv = 0; else retv = -1; scf_value_destroy(val); return (retv); } static int get_boolean(const char *lprop, scf_state_t *sstate, boolean_t *answer) { scf_value_t *val; int retv; uint8_t bval; if (scf_pg_get_property(sstate->ss_pg, lprop, sstate->ss_prop) != 0) return (-1); if ((val = scf_value_create(sstate->ss_handle)) == NULL) return (-1); if (scf_property_get_value(sstate->ss_prop, val) == 0 && scf_value_get_boolean(val, &bval) == 0) { retv = 0; *answer = bval != 0; } else { retv = -1; } scf_value_destroy(val); return (retv); } static dladm_status_t bridge_door_call(const char *instname, bridge_door_type_t dtype, datalink_id_t linkid, void **bufp, size_t inlen, size_t *buflenp, boolean_t is_list) { char doorname[MAXPATHLEN]; int did, retv, etmp; bridge_door_cmd_t *bdc; door_arg_t arg; (void) snprintf(doorname, sizeof (doorname), "%s/%s", DOOR_DIRNAME, instname); /* Knock on the door */ did = open(doorname, O_RDONLY | O_NOFOLLOW | O_NONBLOCK); if (did == -1) return (dladm_errno2status(errno)); if ((bdc = malloc(sizeof (*bdc) + inlen)) == NULL) { (void) close(did); return (DLADM_STATUS_NOMEM); } bdc->bdc_type = dtype; bdc->bdc_linkid = linkid; if (inlen != 0) (void) memcpy(bdc + 1, *bufp, inlen); (void) memset(&arg, 0, sizeof (arg)); arg.data_ptr = (char *)bdc; arg.data_size = sizeof (*bdc) + inlen; arg.rbuf = *bufp; arg.rsize = *buflenp; /* The door_call function doesn't restart, so take care of that */ do { errno = 0; if ((retv = door_call(did, &arg)) == 0) break; } while (errno == EINTR); /* If we get an unexpected response, then return an error */ if (retv == 0) { /* The daemon returns a single int for errors */ /* LINTED: pointer alignment */ if (arg.data_size == sizeof (int) && *(int *)arg.rbuf != 0) { retv = -1; /* LINTED: pointer alignment */ errno = *(int *)arg.rbuf; } /* Terminated daemon returns with zero data */ if (arg.data_size == 0) { retv = -1; errno = EBADF; } } if (retv == 0) { if (arg.rbuf != *bufp) { if (is_list) { void *newp; newp = realloc(*bufp, arg.data_size); if (newp == NULL) { retv = -1; } else { *bufp = newp; (void) memcpy(*bufp, arg.rbuf, arg.data_size); } } (void) munmap(arg.rbuf, arg.rsize); } if (is_list) { *buflenp = arg.data_size; } else if (arg.data_size != *buflenp || arg.rbuf != *bufp) { errno = EINVAL; retv = -1; } } etmp = errno; (void) close(did); /* Revoked door is the same as no door at all */ if (etmp == EBADF) etmp = ENOENT; return (retv == 0 ? DLADM_STATUS_OK : dladm_errno2status(etmp)); } /* * Wrapper function for making per-port calls. */ static dladm_status_t port_door_call(dladm_handle_t handle, datalink_id_t linkid, bridge_door_type_t dtype, void *buf, size_t inlen, size_t buflen) { char bridge[MAXLINKNAMELEN]; dladm_status_t status; status = dladm_bridge_getlink(handle, linkid, bridge, sizeof (bridge)); if (status != DLADM_STATUS_OK) return (status); return (bridge_door_call(bridge, dtype, linkid, &buf, inlen, &buflen, B_FALSE)); } static dladm_status_t bridge_refresh(const char *bridge) { dladm_status_t status; int twoints[2]; void *bdptr; size_t buflen; char *fmri; int refresh_count; buflen = sizeof (twoints); bdptr = twoints; status = bridge_door_call(bridge, bdcBridgeGetRefreshCount, DATALINK_INVALID_LINKID, &bdptr, 0, &buflen, B_FALSE); if (status == DLADM_STATUS_NOTFOUND) return (DLADM_STATUS_OK); if (status != DLADM_STATUS_OK) return (status); refresh_count = twoints[0]; if ((fmri = alloc_fmri(BRIDGE_SVC_NAME, bridge)) == NULL) return (DLADM_STATUS_NOMEM); status = smf_refresh_instance(fmri) == 0 ? DLADM_STATUS_OK : DLADM_STATUS_FAILED; free(fmri); if (status == DLADM_STATUS_OK) { int i = 0; /* * SMF doesn't give any synchronous behavior or dependency * ordering for refresh operations, so we have to invent our * own mechanism here. Get the refresh counter from the * daemon, and wait for it to change. It's not pretty, but * it's sufficient. */ while (++i <= 10) { buflen = sizeof (twoints); bdptr = twoints; status = bridge_door_call(bridge, bdcBridgeGetRefreshCount, DATALINK_INVALID_LINKID, &bdptr, 0, &buflen, B_FALSE); if (status != DLADM_STATUS_OK) break; if (twoints[0] != refresh_count) break; (void) usleep(100000); } fmri = alloc_fmri(TRILL_SVC_NAME, bridge); if (fmri == NULL) return (DLADM_STATUS_NOMEM); status = smf_refresh_instance(fmri) == 0 || scf_error() == SCF_ERROR_NOT_FOUND ? DLADM_STATUS_OK : DLADM_STATUS_FAILED; free(fmri); } return (status); } /* * Look up bridge property values from SCF and return them. */ dladm_status_t dladm_bridge_get_properties(const char *instance_name, UID_STP_CFG_T *cfg, dladm_bridge_prot_t *brprotp) { scf_state_t sstate; uint64_t value; boolean_t trill_enabled; cfg->field_mask = 0; cfg->bridge_priority = DEF_BR_PRIO; cfg->max_age = DEF_BR_MAXAGE; cfg->hello_time = DEF_BR_HELLOT; cfg->forward_delay = DEF_BR_FWDELAY; cfg->force_version = DEF_FORCE_VERS; (void) strlcpy(cfg->vlan_name, instance_name, sizeof (cfg->vlan_name)); *brprotp = DLADM_BRIDGE_PROT_STP; /* It's ok for this to be missing; it's installed separately */ if (bind_instance(TRILL_SVC_NAME, instance_name, &sstate) == 0) { trill_enabled = B_FALSE; if (get_composed_properties(SCF_PG_GENERAL, B_FALSE, &sstate) == 0) { (void) get_boolean(SCF_PROPERTY_ENABLED, &sstate, &trill_enabled); if (trill_enabled) *brprotp = DLADM_BRIDGE_PROT_TRILL; drop_composed(&sstate); } if (get_composed_properties(SCF_PG_GENERAL_OVR, B_FALSE, &sstate) == 0) { (void) get_boolean(SCF_PROPERTY_ENABLED, &sstate, &trill_enabled); if (trill_enabled) *brprotp = DLADM_BRIDGE_PROT_TRILL; drop_composed(&sstate); } shut_down_scf(&sstate); } cfg->stp_enabled = (*brprotp == DLADM_BRIDGE_PROT_STP) ? STP_ENABLED : STP_DISABLED; cfg->field_mask |= BR_CFG_STATE; if (bind_instance(BRIDGE_SVC_NAME, instance_name, &sstate) != 0) return (DLADM_STATUS_REPOSITORYINVAL); if (get_composed_properties("config", B_TRUE, &sstate) != 0) { shut_down_scf(&sstate); return (DLADM_STATUS_REPOSITORYINVAL); } if (get_count("priority", &sstate, &value) == 0) { cfg->bridge_priority = value; cfg->field_mask |= BR_CFG_PRIO; } if (get_count("max-age", &sstate, &value) == 0) { cfg->max_age = value / IEEE_TIMER_SCALE; cfg->field_mask |= BR_CFG_AGE; } if (get_count("hello-time", &sstate, &value) == 0) { cfg->hello_time = value / IEEE_TIMER_SCALE; cfg->field_mask |= BR_CFG_HELLO; } if (get_count("forward-delay", &sstate, &value) == 0) { cfg->forward_delay = value / IEEE_TIMER_SCALE; cfg->field_mask |= BR_CFG_DELAY; } if (get_count("force-protocol", &sstate, &value) == 0) { cfg->force_version = value; cfg->field_mask |= BR_CFG_FORCE_VER; } drop_composed(&sstate); shut_down_scf(&sstate); return (DLADM_STATUS_OK); } /* * Retrieve special non-settable and undocumented parameters. */ dladm_status_t dladm_bridge_get_privprop(const char *instance_name, boolean_t *debugp, uint32_t *tablemaxp) { scf_state_t sstate; uint64_t value; *debugp = B_FALSE; *tablemaxp = 10000; if (bind_instance(BRIDGE_SVC_NAME, instance_name, &sstate) != 0) return (DLADM_STATUS_REPOSITORYINVAL); if (get_composed_properties("config", B_TRUE, &sstate) != 0) { shut_down_scf(&sstate); return (DLADM_STATUS_REPOSITORYINVAL); } (void) get_boolean("debug", &sstate, debugp); if (get_count("table-maximum", &sstate, &value) == 0) *tablemaxp = (uint32_t)value; drop_composed(&sstate); shut_down_scf(&sstate); return (DLADM_STATUS_OK); } static boolean_t set_count_property(scf_handle_t *handle, scf_transaction_t *tran, const char *propname, uint64_t propval) { scf_transaction_entry_t *entry; scf_value_t *value = NULL; if ((entry = scf_entry_create(handle)) == NULL) return (B_FALSE); if ((value = scf_value_create(handle)) == NULL) goto out; if (scf_transaction_property_new(tran, entry, propname, SCF_TYPE_COUNT) != 0 && scf_transaction_property_change(tran, entry, propname, SCF_TYPE_COUNT) != 0) goto out; scf_value_set_count(value, propval); if (scf_entry_add_value(entry, value) == 0) return (B_TRUE); out: if (value != NULL) scf_value_destroy(value); scf_entry_destroy_children(entry); scf_entry_destroy(entry); return (B_FALSE); } static boolean_t set_string_property(scf_handle_t *handle, scf_transaction_t *tran, const char *propname, const char *propval) { scf_transaction_entry_t *entry; scf_value_t *value = NULL; if ((entry = scf_entry_create(handle)) == NULL) return (B_FALSE); if ((value = scf_value_create(handle)) == NULL) goto out; if (scf_transaction_property_new(tran, entry, propname, SCF_TYPE_ASTRING) != 0 && scf_transaction_property_change(tran, entry, propname, SCF_TYPE_ASTRING) != 0) goto out; if (scf_value_set_astring(value, propval) != 0) goto out; if (scf_entry_add_value(entry, value) == 0) return (B_TRUE); out: if (value != NULL) scf_value_destroy(value); scf_entry_destroy_children(entry); scf_entry_destroy(entry); return (B_FALSE); } static boolean_t set_fmri_property(scf_handle_t *handle, scf_transaction_t *tran, const char *propname, const char *propval) { scf_transaction_entry_t *entry; scf_value_t *value = NULL; if ((entry = scf_entry_create(handle)) == NULL) return (B_FALSE); if ((value = scf_value_create(handle)) == NULL) goto out; if (scf_transaction_property_new(tran, entry, propname, SCF_TYPE_FMRI) != 0 && scf_transaction_property_change(tran, entry, propname, SCF_TYPE_FMRI) != 0) goto out; if (scf_value_set_from_string(value, SCF_TYPE_FMRI, propval) != 0) goto out; if (scf_entry_add_value(entry, value) == 0) return (B_TRUE); out: if (value != NULL) scf_value_destroy(value); scf_entry_destroy_children(entry); scf_entry_destroy(entry); return (B_FALSE); } static dladm_status_t dladm_bridge_persist_conf(dladm_handle_t handle, const char *link, datalink_id_t linkid) { dladm_conf_t conf; dladm_status_t status; status = dladm_create_conf(handle, link, linkid, DATALINK_CLASS_BRIDGE, DL_ETHER, &conf); if (status == DLADM_STATUS_OK) { /* * Create the datalink entry for the bridge. Note that all of * the real configuration information is in SMF. */ status = dladm_write_conf(handle, conf); dladm_destroy_conf(handle, conf); } return (status); } /* Convert bridge protection option string to dladm_bridge_prot_t */ dladm_status_t dladm_bridge_str2prot(const char *str, dladm_bridge_prot_t *brprotp) { if (strcmp(str, "stp") == 0) *brprotp = DLADM_BRIDGE_PROT_STP; else if (strcmp(str, "trill") == 0) *brprotp = DLADM_BRIDGE_PROT_TRILL; else return (DLADM_STATUS_BADARG); return (DLADM_STATUS_OK); } /* Convert bridge protection option from dladm_bridge_prot_t to string */ const char * dladm_bridge_prot2str(dladm_bridge_prot_t brprot) { switch (brprot) { case DLADM_BRIDGE_PROT_STP: return ("stp"); case DLADM_BRIDGE_PROT_TRILL: return ("trill"); default: return ("unknown"); } } static dladm_status_t enable_instance(const char *service_name, const char *instance) { dladm_status_t status; char *fmri = alloc_fmri(service_name, instance); if (fmri == NULL) return (DLADM_STATUS_NOMEM); status = smf_enable_instance(fmri, 0) == 0 ? DLADM_STATUS_OK : DLADM_STATUS_FAILED; free(fmri); return (status); } /* * Shut down a possibly-running service instance. If this is a permanent * change, then delete it from the system. */ static dladm_status_t shut_down_instance(const char *service_name, const char *instance, uint32_t flags) { dladm_status_t status; char *fmri = alloc_fmri(service_name, instance); char *state; scf_state_t sstate; if (fmri == NULL) return (DLADM_STATUS_NOMEM); if (smf_disable_instance(fmri, flags & DLADM_OPT_PERSIST ? 0 : SMF_TEMPORARY) == 0) { useconds_t usecs, umax; /* If we can disable, then wait for it to happen. */ umax = DEFAULT_TIMEOUT; for (usecs = INIT_WAIT_USECS; umax != 0; umax -= usecs) { state = smf_get_state(fmri); if (state != NULL && strcmp(state, SCF_STATE_STRING_DISABLED) == 0) break; free(state); usecs *= 2; if (usecs > umax) usecs = umax; (void) usleep(usecs); } if (umax == 0) { state = smf_get_state(fmri); if (state != NULL && strcmp(state, SCF_STATE_STRING_DISABLED) == 0) umax = 1; } free(state); status = umax != 0 ? DLADM_STATUS_OK : DLADM_STATUS_FAILED; } else if (scf_error() == SCF_ERROR_NOT_FOUND) { free(fmri); return (DLADM_STATUS_OK); } else { status = DLADM_STATUS_FAILED; } free(fmri); if (status == DLADM_STATUS_OK && (flags & DLADM_OPT_PERSIST) && bind_instance(service_name, instance, &sstate) == 0) { (void) scf_instance_delete(sstate.ss_inst); shut_down_scf(&sstate); } return (status); } static dladm_status_t disable_trill(const char *instance, uint32_t flags) { return (shut_down_instance(TRILL_SVC_NAME, instance, flags)); } /* * To enable TRILL, we must create a new instance of the TRILL service, then * add proper dependencies to it, and finally mark it as enabled. The * dependencies will keep it from going on-line until the bridge is running. */ static dladm_status_t enable_trill(const char *instance) { dladm_status_t status = DLADM_STATUS_FAILED; char *fmri = NULL; scf_state_t sstate; scf_transaction_t *tran = NULL; boolean_t new_instance = B_FALSE; boolean_t new_pg = B_FALSE; int rv; /* * This check is here in case the user has installed and then removed * the package. SMF should remove the manifest, but currently does * not. */ if (access("/usr/sbin/trilld", F_OK) != 0) return (DLADM_STATUS_OPTMISSING); if ((status = exact_instance(TRILL_SVC_NAME, &sstate)) != DLADM_STATUS_OK) goto out; status = DLADM_STATUS_FAILED; if (scf_service_get_instance(sstate.ss_svc, instance, sstate.ss_inst) != 0) { if (scf_service_add_instance(sstate.ss_svc, instance, sstate.ss_inst) != 0) goto out; new_instance = B_TRUE; } if ((tran = scf_transaction_create(sstate.ss_handle)) == NULL) goto out; if ((sstate.ss_pg = scf_pg_create(sstate.ss_handle)) == NULL) goto out; if (scf_instance_get_pg(sstate.ss_inst, "bridging", sstate.ss_pg) == 0) { status = DLADM_STATUS_OK; goto out; } if ((fmri = alloc_fmri(BRIDGE_SVC_NAME, instance)) == NULL) goto out; if (scf_instance_add_pg(sstate.ss_inst, "bridging", SCF_GROUP_DEPENDENCY, 0, sstate.ss_pg) != 0) goto out; new_pg = B_TRUE; do { if (scf_transaction_start(tran, sstate.ss_pg) != 0) goto out; if (!set_string_property(sstate.ss_handle, tran, SCF_PROPERTY_GROUPING, SCF_DEP_REQUIRE_ALL)) goto out; if (!set_string_property(sstate.ss_handle, tran, SCF_PROPERTY_RESTART_ON, SCF_DEP_RESET_ON_RESTART)) goto out; if (!set_string_property(sstate.ss_handle, tran, SCF_PROPERTY_TYPE, "service")) goto out; if (!set_fmri_property(sstate.ss_handle, tran, SCF_PROPERTY_ENTITIES, fmri)) goto out; rv = scf_transaction_commit(tran); scf_transaction_reset(tran); if (rv == 0 && scf_pg_update(sstate.ss_pg) == -1) goto out; } while (rv == 0); if (rv != 1) goto out; status = DLADM_STATUS_OK; out: free(fmri); if (tran != NULL) { scf_transaction_destroy_children(tran); scf_transaction_destroy(tran); } if (status != DLADM_STATUS_OK && new_pg) (void) scf_pg_delete(sstate.ss_pg); drop_composed(&sstate); /* * If we created an instance and then failed, then remove the instance * from the system. */ if (status != DLADM_STATUS_OK && new_instance) (void) scf_instance_delete(sstate.ss_inst); shut_down_scf(&sstate); if (status == DLADM_STATUS_OK) status = enable_instance(TRILL_SVC_NAME, instance); return (status); } /* * Create a new bridge or modify an existing one. Update the SMF configuration * and add links. * * Input timer values are in IEEE scaled (* 256) format. */ dladm_status_t dladm_bridge_configure(dladm_handle_t handle, const char *name, const UID_STP_CFG_T *cfg, dladm_bridge_prot_t brprot, uint32_t flags) { dladm_status_t status; scf_state_t sstate; scf_transaction_t *tran = NULL; boolean_t new_instance = B_FALSE; boolean_t new_pg = B_FALSE; datalink_id_t linkid = DATALINK_INVALID_LINKID; char linkname[MAXLINKNAMELEN]; int rv; if (!dladm_valid_bridgename(name)) return (DLADM_STATUS_FAILED); if (flags & DLADM_OPT_CREATE) { /* * This check is here in case the user has installed and then * removed the package. SMF should remove the manifest, but * currently does not. */ if (access("/usr/lib/bridged", F_OK) != 0) return (DLADM_STATUS_OPTMISSING); (void) snprintf(linkname, sizeof (linkname), "%s0", name); status = dladm_create_datalink_id(handle, linkname, DATALINK_CLASS_BRIDGE, DL_ETHER, flags & (DLADM_OPT_ACTIVE | DLADM_OPT_PERSIST), &linkid); if (status != DLADM_STATUS_OK) return (status); if ((flags & DLADM_OPT_PERSIST) && (status = dladm_bridge_persist_conf(handle, linkname, linkid) != DLADM_STATUS_OK)) goto dladm_fail; } if (brprot == DLADM_BRIDGE_PROT_TRILL) status = enable_trill(name); else status = disable_trill(name, flags); if (status != DLADM_STATUS_OK) goto dladm_fail; if ((status = exact_instance(BRIDGE_SVC_NAME, &sstate)) != DLADM_STATUS_OK) goto out; /* set up for a series of scf calls */ status = DLADM_STATUS_FAILED; if (scf_service_get_instance(sstate.ss_svc, name, sstate.ss_inst) == 0) { if (flags & DLADM_OPT_CREATE) { status = DLADM_STATUS_EXIST; goto out; } } else { if (!(flags & DLADM_OPT_CREATE)) { status = DLADM_STATUS_NOTFOUND; goto out; } if (scf_service_add_instance(sstate.ss_svc, name, sstate.ss_inst) != 0) goto out; new_instance = B_TRUE; } if ((tran = scf_transaction_create(sstate.ss_handle)) == NULL) goto out; if (cfg->field_mask & BR_CFG_ALL) { if ((sstate.ss_pg = scf_pg_create(sstate.ss_handle)) == NULL) goto out; if (scf_instance_add_pg(sstate.ss_inst, "config", SCF_GROUP_APPLICATION, 0, sstate.ss_pg) == 0) { new_pg = B_TRUE; } else if (scf_instance_get_pg(sstate.ss_inst, "config", sstate.ss_pg) != 0) { goto out; } do { if (scf_transaction_start(tran, sstate.ss_pg) != 0) goto out; if ((cfg->field_mask & BR_CFG_PRIO) && !set_count_property(sstate.ss_handle, tran, "priority", cfg->bridge_priority)) goto out; if ((cfg->field_mask & BR_CFG_AGE) && !set_count_property(sstate.ss_handle, tran, "max-age", cfg->max_age * IEEE_TIMER_SCALE)) goto out; if ((cfg->field_mask & BR_CFG_HELLO) && !set_count_property(sstate.ss_handle, tran, "hello-time", cfg->hello_time * IEEE_TIMER_SCALE)) goto out; if ((cfg->field_mask & BR_CFG_DELAY) && !set_count_property(sstate.ss_handle, tran, "forward-delay", cfg->forward_delay * IEEE_TIMER_SCALE)) goto out; if ((cfg->field_mask & BR_CFG_FORCE_VER) && !set_count_property(sstate.ss_handle, tran, "force-protocol", cfg->force_version)) goto out; rv = scf_transaction_commit(tran); scf_transaction_reset(tran); if (rv == 0 && scf_pg_update(sstate.ss_pg) == -1) goto out; } while (rv == 0); if (rv != 1) goto out; } /* * If we're modifying an existing and running bridge, then tell the * daemon to update the requested values. */ if ((flags & DLADM_OPT_ACTIVE) && !(flags & DLADM_OPT_CREATE)) status = bridge_refresh(name); else status = DLADM_STATUS_OK; out: if (tran != NULL) { scf_transaction_destroy_children(tran); scf_transaction_destroy(tran); } if (status != DLADM_STATUS_OK && new_pg) (void) scf_pg_delete(sstate.ss_pg); drop_composed(&sstate); /* * If we created an instance and then failed, then remove the instance * from the system. */ if (status != DLADM_STATUS_OK && new_instance) (void) scf_instance_delete(sstate.ss_inst); shut_down_scf(&sstate); /* * Remove the bridge linkid if we've allocated one in this function but * we've failed to set up the SMF properties. */ dladm_fail: if (status != DLADM_STATUS_OK && linkid != DATALINK_INVALID_LINKID) { (void) dladm_remove_conf(handle, linkid); (void) dladm_destroy_datalink_id(handle, linkid, flags); } return (status); } /* * Enable a newly-created bridge in SMF by creating "general/enabled" and * deleting any "general_ovr/enabled" (used for temporary services). */ dladm_status_t dladm_bridge_enable(const char *name) { return (enable_instance(BRIDGE_SVC_NAME, name)); } /* * Set a link as a member of a bridge, or remove bridge membership. If the * DLADM_OPT_CREATE flag is set, then we assume that the daemon isn't running. * In all other cases, we must tell the daemon to add or delete the link in * order to stay in sync. */ dladm_status_t dladm_bridge_setlink(dladm_handle_t handle, datalink_id_t linkid, const char *bridge) { dladm_status_t status; dladm_conf_t conf; char oldbridge[MAXLINKNAMELEN]; boolean_t has_oldbridge; boolean_t changed = B_FALSE; if (*bridge != '\0' && !dladm_valid_bridgename(bridge)) return (DLADM_STATUS_FAILED); status = dladm_open_conf(handle, linkid, &conf); if (status != DLADM_STATUS_OK) return (status); has_oldbridge = B_FALSE; status = dladm_get_conf_field(handle, conf, FBRIDGE, oldbridge, sizeof (oldbridge)); if (status == DLADM_STATUS_OK) { /* * Don't allow a link to be reassigned directly from one bridge * to another. It must be removed first. */ if (*oldbridge != '\0' && *bridge != '\0') { status = DLADM_STATUS_EXIST; goto out; } has_oldbridge = B_TRUE; } else if (status != DLADM_STATUS_NOTFOUND) { goto out; } if (*bridge != '\0') { status = dladm_set_conf_field(handle, conf, FBRIDGE, DLADM_TYPE_STR, bridge); changed = B_TRUE; } else if (has_oldbridge) { status = dladm_unset_conf_field(handle, conf, FBRIDGE); changed = B_TRUE; } else { status = DLADM_STATUS_OK; goto out; } if (status == DLADM_STATUS_OK) status = dladm_write_conf(handle, conf); out: dladm_destroy_conf(handle, conf); if (changed && status == DLADM_STATUS_OK) { if (bridge[0] == '\0') bridge = oldbridge; status = bridge_refresh(bridge); } return (status); } /* * Get the name of the bridge of which the given linkid is a member. */ dladm_status_t dladm_bridge_getlink(dladm_handle_t handle, datalink_id_t linkid, char *bridge, size_t bridgelen) { dladm_status_t status; dladm_conf_t conf; if ((status = dladm_getsnap_conf(handle, linkid, &conf)) != DLADM_STATUS_OK) return (status); *bridge = '\0'; status = dladm_get_conf_field(handle, conf, FBRIDGE, bridge, bridgelen); if (status == DLADM_STATUS_OK && *bridge == '\0') status = DLADM_STATUS_NOTFOUND; dladm_destroy_conf(handle, conf); return (status); } dladm_status_t dladm_bridge_refresh(dladm_handle_t handle, datalink_id_t linkid) { char bridge[MAXLINKNAMELEN]; dladm_status_t status; status = dladm_bridge_getlink(handle, linkid, bridge, sizeof (bridge)); if (status == DLADM_STATUS_NOTFOUND) return (DLADM_STATUS_OK); if (status == DLADM_STATUS_OK) status = bridge_refresh(bridge); return (status); } typedef struct bridge_held_arg_s { const char *bha_bridge; boolean_t bha_isheld; } bridge_held_arg_t; static int i_dladm_bridge_is_held(dladm_handle_t handle, datalink_id_t linkid, void *arg) { dladm_status_t status = DLADM_STATUS_FAILED; dladm_conf_t conf; char bridge[MAXLINKNAMELEN]; bridge_held_arg_t *bha = arg; if ((status = dladm_getsnap_conf(handle, linkid, &conf)) != DLADM_STATUS_OK) return (DLADM_WALK_CONTINUE); status = dladm_get_conf_field(handle, conf, FBRIDGE, bridge, sizeof (bridge)); if (status == DLADM_STATUS_OK && strcmp(bha->bha_bridge, bridge) == 0) { bha->bha_isheld = B_TRUE; dladm_destroy_conf(handle, conf); return (DLADM_WALK_TERMINATE); } else { dladm_destroy_conf(handle, conf); return (DLADM_WALK_CONTINUE); } } /* * Delete a previously created bridge. */ dladm_status_t dladm_bridge_delete(dladm_handle_t handle, const char *bridge, uint32_t flags) { datalink_id_t linkid; datalink_class_t class; dladm_status_t status; char linkname[MAXLINKNAMELEN]; if (!dladm_valid_bridgename(bridge)) return (DLADM_STATUS_LINKINVAL); /* Get the datalink ID for this bridge */ (void) snprintf(linkname, sizeof (linkname), "%s0", bridge); if (dladm_name2info(handle, linkname, &linkid, NULL, NULL, NULL) != DLADM_STATUS_OK) linkid = DATALINK_INVALID_LINKID; else if (dladm_datalink_id2info(handle, linkid, NULL, &class, NULL, NULL, 0) != DLADM_STATUS_OK) linkid = DATALINK_INVALID_LINKID; else if (class != DATALINK_CLASS_BRIDGE) return (DLADM_STATUS_BADARG); if ((flags & DLADM_OPT_ACTIVE) && linkid == DATALINK_INVALID_LINKID) return (DLADM_STATUS_BADARG); if (flags & DLADM_OPT_PERSIST) { bridge_held_arg_t arg; arg.bha_bridge = bridge; arg.bha_isheld = B_FALSE; /* * See whether there are any persistent links using this * bridge. If so, we fail the operation. */ (void) dladm_walk_datalink_id(i_dladm_bridge_is_held, handle, &arg, DATALINK_CLASS_PHYS | DATALINK_CLASS_AGGR | DATALINK_CLASS_ETHERSTUB | DATALINK_CLASS_SIMNET, DATALINK_ANY_MEDIATYPE, DLADM_OPT_PERSIST); if (arg.bha_isheld) return (DLADM_STATUS_LINKBUSY); } if ((status = disable_trill(bridge, flags)) != DLADM_STATUS_OK) goto out; /* Disable or remove the SMF instance */ status = shut_down_instance(BRIDGE_SVC_NAME, bridge, flags); if (status != DLADM_STATUS_OK) goto out; if (flags & DLADM_OPT_ACTIVE) { /* * Delete ACTIVE linkprop now that daemon is gone. */ (void) dladm_set_linkprop(handle, linkid, NULL, NULL, 0, DLADM_OPT_ACTIVE); (void) dladm_destroy_datalink_id(handle, linkid, DLADM_OPT_ACTIVE); } if (flags & DLADM_OPT_PERSIST) { (void) dladm_remove_conf(handle, linkid); (void) dladm_destroy_datalink_id(handle, linkid, DLADM_OPT_PERSIST); } out: return (status); } /* Check if given name is valid for bridges */ boolean_t dladm_valid_bridgename(const char *bridge) { size_t len = strnlen(bridge, MAXLINKNAMELEN); const char *cp; if (len == MAXLINKNAMELEN) return (B_FALSE); /* * The bridge name cannot start or end with a digit. */ if (isdigit(bridge[0]) || isdigit(bridge[len - 1])) return (B_FALSE); /* * The legal characters within a bridge name are: * alphanumeric (a-z, A-Z, 0-9), and the underscore ('_'). */ for (cp = bridge; *cp != '\0'; cp++) { if (!isalnum(*cp) && *cp != '_') return (B_FALSE); } return (B_TRUE); } /* * Convert a bridge-related observability node name back into the name of the * bridge. Returns B_FALSE without making changes if the input name is not in * a legal format. */ boolean_t dladm_observe_to_bridge(char *link) { int llen; llen = strnlen(link, MAXLINKNAMELEN); if (llen < 2 || link[llen - 1] != '0' || isdigit(link[llen - 2])) return (B_FALSE); link[llen - 1] = '\0'; return (B_TRUE); } /* * Get bridge property values from the running daemon and return them in a * common structure. */ dladm_status_t dladm_bridge_run_properties(const char *instname, UID_STP_CFG_T *smcfg, dladm_bridge_prot_t *brprotp) { dladm_status_t status; bridge_door_cfg_t bdcf; bridge_door_cfg_t *bdcfp = &bdcf; size_t buflen = sizeof (bdcf); status = bridge_door_call(instname, bdcBridgeGetConfig, DATALINK_INVALID_LINKID, (void **)&bdcfp, 0, &buflen, B_FALSE); if (status == DLADM_STATUS_OK) { *smcfg = bdcfp->bdcf_cfg; *brprotp = bdcfp->bdcf_prot; } else { smcfg->field_mask = 0; *brprotp = DLADM_BRIDGE_PROT_STP; } return (status); } /* * Get bridge state from the running daemon and return in structure borrowed * from librstp. */ dladm_status_t dladm_bridge_state(const char *instname, UID_STP_STATE_T *statep) { size_t buflen = sizeof (*statep); return (bridge_door_call(instname, bdcBridgeGetState, DATALINK_INVALID_LINKID, (void **)&statep, 0, &buflen, B_FALSE)); } /* Returns list of ports (datalink_id_t values) assigned to a bridge instance */ datalink_id_t * dladm_bridge_get_portlist(const char *instname, uint_t *nports) { size_t buflen = sizeof (int) + MAXPORTS * sizeof (datalink_id_t); int *rbuf; if ((rbuf = malloc(buflen)) == NULL) return (NULL); if (bridge_door_call(instname, bdcBridgeGetPorts, DATALINK_INVALID_LINKID, (void **)&rbuf, 0, &buflen, B_TRUE) != DLADM_STATUS_OK) { free(rbuf); return (NULL); } else { /* * Returns an array of datalink_id_t values for all the ports * part of the bridge instance. First entry in the array is the * number of ports. */ *nports = *rbuf; return ((datalink_id_t *)(rbuf + 1)); } } void dladm_bridge_free_portlist(datalink_id_t *dlp) { free((int *)dlp - 1); } /* Retrieve Bridge port configuration values */ dladm_status_t dladm_bridge_get_port_cfg(dladm_handle_t handle, datalink_id_t linkid, int field, int *valuep) { UID_STP_PORT_CFG_T portcfg; dladm_status_t status; status = port_door_call(handle, linkid, bdcPortGetConfig, &portcfg, 0, sizeof (portcfg)); if (status != DLADM_STATUS_OK) return (status); switch (field) { case PT_CFG_COST: *valuep = portcfg.admin_port_path_cost; break; case PT_CFG_PRIO: *valuep = portcfg.port_priority; break; case PT_CFG_P2P: *valuep = portcfg.admin_point2point; break; case PT_CFG_EDGE: *valuep = portcfg.admin_edge; break; case PT_CFG_NON_STP: *valuep = !portcfg.admin_non_stp; break; case PT_CFG_MCHECK: *valuep = (portcfg.field_mask & PT_CFG_MCHECK) ? 1 : 0; break; } return (status); } /* Retreive Bridge port status (disabled, bad SDU etc.) */ dladm_status_t dladm_bridge_link_state(dladm_handle_t handle, datalink_id_t linkid, UID_STP_PORT_STATE_T *spsp) { return (port_door_call(handle, linkid, bdcPortGetState, spsp, 0, sizeof (*spsp))); } /* Retrieve Bridge forwarding status of the given link */ dladm_status_t dladm_bridge_get_forwarding(dladm_handle_t handle, datalink_id_t linkid, uint_t *valuep) { int twoints[2]; dladm_status_t status; status = port_door_call(handle, linkid, bdcPortGetForwarding, twoints, 0, sizeof (twoints)); if (status == DLADM_STATUS_OK) *valuep = twoints[0]; return (status); } /* Retrieve Bridge forwarding table entries */ bridge_listfwd_t * dladm_bridge_get_fwdtable(dladm_handle_t handle, const char *bridge, uint_t *nfwd) { bridge_listfwd_t *blf = NULL, *newblf, blfread; uint_t nblf = 0, maxblf = 0; static uint8_t zero_addr[ETHERADDRL]; int rc; (void) memset(&blfread, 0, sizeof (blfread)); (void) snprintf(blfread.blf_name, sizeof (blfread.blf_name), "%s0", bridge); for (;;) { if (nblf >= maxblf) { maxblf = maxblf == 0 ? 64 : (maxblf << 1); newblf = realloc(blf, maxblf * sizeof (*blf)); if (newblf == NULL) { free(blf); blf = NULL; break; } blf = newblf; } rc = ioctl(dladm_dld_fd(handle), BRIDGE_IOC_LISTFWD, &blfread); if (rc != 0) { free(blf); blf = NULL; break; } if (memcmp(blfread.blf_dest, zero_addr, ETHERADDRL) == 0) break; blf[nblf++] = blfread; } if (blf != NULL) *nfwd = nblf; return (blf); } void dladm_bridge_free_fwdtable(bridge_listfwd_t *blf) { free(blf); } /* Retrieve list of TRILL nicknames from the TRILL module */ trill_listnick_t * dladm_bridge_get_trillnick(const char *bridge, uint_t *nnick) { int fd; char brcopy[MAXLINKNAMELEN]; trill_listnick_t *tln = NULL, *newtln, tlnread; uint_t ntln = 0, maxtln = 0; if ((fd = socket(PF_TRILL, SOCK_DGRAM, 0)) == -1) return (NULL); (void) strlcpy(brcopy, bridge, sizeof (brcopy)); if (ioctl(fd, TRILL_GETBRIDGE, &brcopy) < 0) { (void) close(fd); return (NULL); } (void) memset(&tlnread, 0, sizeof (tlnread)); for (;;) { if (ntln >= maxtln) { maxtln = maxtln == 0 ? 64 : (maxtln << 1); newtln = realloc(tln, maxtln * sizeof (*tln)); if (newtln == NULL) { free(tln); tln = NULL; break; } tln = newtln; } if (ioctl(fd, TRILL_LISTNICK, &tlnread) == -1) { free(tln); tln = NULL; break; } if (tlnread.tln_nick == 0) break; tln[ntln++] = tlnread; } (void) close(fd); if (tln != NULL) *nnick = ntln; return (tln); } void dladm_bridge_free_trillnick(trill_listnick_t *tln) { free(tln); } /* Retrieve any stored TRILL nickname from TRILL SMF service */ uint16_t dladm_bridge_get_nick(const char *bridge) { scf_state_t sstate; uint64_t value; uint16_t nickname = RBRIDGE_NICKNAME_NONE; if (bind_instance(TRILL_SVC_NAME, bridge, &sstate) != 0) return (nickname); if (get_composed_properties("config", B_TRUE, &sstate) == 0 && get_count("nickname", &sstate, &value) == 0) nickname = value; shut_down_scf(&sstate); return (nickname); } /* Stores TRILL nickname in SMF configuraiton for the TRILL service */ void dladm_bridge_set_nick(const char *bridge, uint16_t nick) { scf_state_t sstate; scf_transaction_t *tran = NULL; boolean_t new_pg = B_FALSE; int rv = 0; char *fmri; if (exact_instance(TRILL_SVC_NAME, &sstate) != DLADM_STATUS_OK) return; if (scf_service_get_instance(sstate.ss_svc, bridge, sstate.ss_inst) != 0) goto out; if ((tran = scf_transaction_create(sstate.ss_handle)) == NULL) goto out; if ((sstate.ss_pg = scf_pg_create(sstate.ss_handle)) == NULL) goto out; if (scf_instance_add_pg(sstate.ss_inst, "config", SCF_GROUP_APPLICATION, 0, sstate.ss_pg) == 0) { new_pg = B_TRUE; } else if (scf_instance_get_pg(sstate.ss_inst, "config", sstate.ss_pg) != 0) { goto out; } do { if (scf_transaction_start(tran, sstate.ss_pg) != 0) goto out; if (!set_count_property(sstate.ss_handle, tran, "nickname", nick)) goto out; rv = scf_transaction_commit(tran); scf_transaction_reset(tran); if (rv == 0 && scf_pg_update(sstate.ss_pg) == -1) goto out; } while (rv == 0); out: if (tran != NULL) { scf_transaction_destroy_children(tran); scf_transaction_destroy(tran); } if (rv != 1 && new_pg) (void) scf_pg_delete(sstate.ss_pg); drop_composed(&sstate); shut_down_scf(&sstate); if (rv == 1 && (fmri = alloc_fmri(TRILL_SVC_NAME, bridge)) != NULL) { (void) smf_refresh_instance(fmri); free(fmri); } }
86552.c
#include "utils.h" #include "printf.h" #include "timer.h" #include "entry.h" #include "peripherals/irq.h" #include "peripherals/timer.h" const char *entry_error_messages[] = { "SYNC_INVALID_EL1t", "IRQ_INVALID_EL1t", "FIQ_INVALID_EL1t", "ERROR_INVALID_EL1T", "SYNC_INVALID_EL1h", "IRQ_INVALID_EL1h", "FIQ_INVALID_EL1h", "ERROR_INVALID_EL1h", "SYNC_INVALID_EL0_64", "IRQ_INVALID_EL0_64", "FIQ_INVALID_EL0_64", "ERROR_INVALID_EL0_64", "SYNC_INVALID_EL0_32", "IRQ_INVALID_EL0_32", "FIQ_INVALID_EL0_32", "ERROR_INVALID_EL0_32" }; void enable_interrupt_controller() { // it isn't the interrupt controller, but enable local timer interrupt unsigned int local_timer_ctrl = get32(TIMER_CTRL); put32(TIMER_CTRL, (local_timer_ctrl | (1 << 29))); } void show_invalid_entry_message(int type, unsigned long esr, unsigned long address) { printf("%s, ESR: %x, address: %x\r\n", entry_error_messages[type], esr, address); } void handle_irq(void) { unsigned int irq = get32(CORE0_INT_SOURCE); switch (irq) { case (LOCAL_TIMER_INT): handle_timer_irq(); break; default: printf("Unknown pending irq: %x\r\n", irq); } }
294538.c
/** @file Copyright (c) 2008 - 2021, Intel Corporation. All rights reserved.<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <PiPei.h> #include <Library/BaseLib.h> #include <Library/PcdLib.h> #include <Library/IoLib.h> #include <Library/PciLib.h> #include <Library/BaseMemoryLib.h> #include <Library/MemoryAllocationLib.h> #include <Library/GpioLib.h> #include <Library/BoardInitLib.h> #include <Library/SerialPortLib.h> #include <Library/PlatformHookLib.h> #include <Library/ConfigDataLib.h> #include <Library/SpiFlashLib.h> #include <Library/PchInfoLib.h> #include <FspmUpd.h> #include <Library/DebugLib.h> #include <IndustryStandard/Pci30.h> #include <Library/BootloaderCoreLib.h> #include <Library/BoardSupportLib.h> #include <PchAccess.h> #include <CpuRegsAccess.h> #include <CpuRegs.h> #include <Library/CryptoLib.h> #include <ConfigDataDefs.h> #include <Library/TpmLib.h> #include <Library/BootGuardLib.h> #include <PlatformData.h> #include "GpioTableTglHPreMem.h" #include "GpioTableTglUPreMem.h" #include <Library/TimerLib.h> #include "BoardSaConfigPreMem.h" #include <PlatformBoardId.h> #include <TccConfigSubRegions.h> #include <Library/ResetSystemLib.h> #include <Library/WatchDogTimerLib.h> #include <Library/SocInitLib.h> CONST PLT_DEVICE mPlatformDevices[]= { {{0x00001700}, OsBootDeviceSata , 0 }, {{0x00001F05}, OsBootDeviceSpi , 0 }, {{0x00001400}, OsBootDeviceUsb , 0 }, {{0x01000000}, OsBootDeviceMemory, 0 }, {{0x00010000}, OsBootDeviceNvme , 0 }, {{0x00020000}, OsBootDeviceNvme , 1 }, {{0x00050000}, OsBootDeviceNvme , 2 }, {{0x00000200}, PlatformDeviceGraphics, 0}, }; VOID GetBoardId ( OUT UINT8 *BoardId ); /** Update FSP-M UPD config data for TCC mode and tuning @param FspmUpd The pointer to the FSP-M UPD to be updated. @retval EFI_NOT_FOUND TCC Features Data not found or disabled. @retval EFI_LOAD_ERROR Tcc Buffer sub-region not found @retval EFI_SUCCESS Successfully loaded buffer sub-region **/ EFI_STATUS TccModePreMemConfig ( FSPM_UPD *FspmUpd ) { UINT32 *TccCacheBase; UINT32 TccCacheSize; UINT32 *TccStreamBase; UINT32 TccStreamSize; EFI_STATUS Status; TCC_CFG_DATA *TccCfgData; BIOS_SETTINGS *PolicyConfig; TCC_STREAM_CONFIGURATION *StreamConfig; TccCfgData = (TCC_CFG_DATA *) FindConfigDataByTag(CDATA_TCC_TAG); if ((TccCfgData == NULL) || ((TccCfgData->TccEnable == 0) && (TccCfgData->TccTuning == 0))) { return EFI_NOT_FOUND; } // TCC related memory settings DEBUG ((DEBUG_INFO, "Tcc is enabled, Setting memory config.\n")); FspmUpd->FspmConfig.SaGv = 0; // System Agent Geyserville - SAGV dynamically adjusts the system agent // voltage and clock frequencies depending on power and performance requirements FspmUpd->FspmConfig.DisPgCloseIdleTimeout = 1; // controls Page Close Idle Timeout FspmUpd->FspmConfig.PowerDownMode = 0; // controls command bus tristating during idle periods FspmUpd->FspmConfig.WrcFeatureEnable = 1; FspmUpd->FspmConfig.HyperThreading = 0; FspmUpd->FspmConfig.GtClosEnable = 1; FspmUpd->FspmConfig.BiosGuard = 0x0; FspmUpd->FspmConfig.VmxEnable = 1; // RTCM need enable VMX FspmUpd->FspmConfig.SoftwareSramEnPreMem = TccCfgData->TccSoftSram; FspmUpd->FspmConfig.DsoTuningEnPreMem = TccCfgData->TccTuning; FspmUpd->FspmConfig.TccErrorLogEnPreMem = TccCfgData->TccErrorLog; // S0ix is disabled if TCC is enabled. if (PLAT_FEAT.S0ixEnable == 1) { PLAT_FEAT.S0ixEnable = 0; DEBUG ((DEBUG_INFO, "S0ix is turned off when TCC is enabled\n")); } if (IsWdtFlagsSet(WDT_FLAG_TCC_DSO) && IsWdtTimeout()) { DEBUG ((DEBUG_INFO, "Incorrect TCC tuning parameters. Platform rebooted with default values.\n")); WdtClearFlags (WDT_FLAG_TCC_DSO); FspmUpd->FspmConfig.TccStreamCfgStatusPreMem = 1; } else if (TccCfgData->TccTuning != 0) { // Setup Watch dog timer WdtReloadAndStart (WDT_TIMEOUT_TCC_DSO, WDT_FLAG_TCC_DSO); // Load TCC stream config from container TccStreamBase = NULL; TccStreamSize = 0; Status = LoadComponent (SIGNATURE_32 ('I', 'P', 'F', 'W'), SIGNATURE_32 ('T', 'C', 'C', 'T'), (VOID **)&TccStreamBase, &TccStreamSize); if (EFI_ERROR (Status) || (TccStreamSize < sizeof(TCC_STREAM_CONFIGURATION))) { DEBUG ((DEBUG_INFO, "Load TCC Stream %r, size = 0x%x\n", Status, TccStreamSize)); } else { FspmUpd->FspmConfig.TccStreamCfgBasePreMem = (UINT32)(UINTN)TccStreamBase; FspmUpd->FspmConfig.TccStreamCfgSizePreMem = TccStreamSize; DEBUG ((DEBUG_INFO, "Load TCC stream @0x%p, size = 0x%x\n", TccStreamBase, TccStreamSize)); StreamConfig = (TCC_STREAM_CONFIGURATION *) TccStreamBase; PolicyConfig = (BIOS_SETTINGS *) &StreamConfig->BiosSettings; FspmUpd->FspmConfig.SaGv = PolicyConfig->SaGv; FspmUpd->FspmConfig.HyperThreading = PolicyConfig->HyperThreading; FspmUpd->FspmConfig.PowerDownMode = PolicyConfig->MemPowerDown; FspmUpd->FspmConfig.DisPgCloseIdleTimeout = PolicyConfig->DisPgCloseIdle; PLAT_FEAT.S0ixEnable = PolicyConfig->Sstates; if (PLAT_FEAT.S0ixEnable == 1) { DEBUG ((DEBUG_INFO, "S0ix is forced turning on by TCC DSO\n")); } DEBUG ((DEBUG_INFO, "Dump TCC DSO BIOS settings:\n")); DumpHex (2, 0, sizeof(BIOS_SETTINGS), PolicyConfig); } } // Load Tcc Cache config from container TccCacheBase = NULL; TccCacheSize = 0; Status = LoadComponent (SIGNATURE_32 ('I', 'P', 'F', 'W'), SIGNATURE_32 ('T', 'C', 'C', 'C'), (VOID **)&TccCacheBase, &TccCacheSize); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_INFO, "TCC Cache config not found! %r\n", Status)); } else { FspmUpd->FspmConfig.TccCacheCfgBasePreMem = (UINT32)(UINTN)TccCacheBase; FspmUpd->FspmConfig.TccCacheCfgSizePreMem = TccCacheSize; DEBUG ((DEBUG_INFO, "Load TCC cache @0x%p, size = 0x%x\n", TccCacheBase, TccCacheSize)); } return Status; } /** Update FSP-M UPD config data @param FspmUpdPtr The pointer to the FSP-M UPD to be updated. @retval None **/ VOID EFIAPI UpdateFspConfig ( VOID *FspmUpdPtr ) { FSPM_UPD *FspmUpd; FSPM_ARCH_UPD *FspmArchUpd; FSP_M_CONFIG *Fspmcfg; MEMORY_CFG_DATA *MemCfgData; GRAPHICS_CFG_DATA *GfxCfgData; UINT8 Index; UINT32 SpdData[3]; UINT16 BoardId; UINT8 SaDisplayConfigTable[16] = { 0 }; TCC_CFG_DATA *TccCfgData; FEATURES_CFG_DATA *FeaturesCfgData; SILICON_CFG_DATA *SiCfgData; PLATFORM_DATA *PlatformData; UINT8 DebugPort; FspmUpd = (FSPM_UPD *)FspmUpdPtr; FspmArchUpd = &FspmUpd->FspmArchUpd; Fspmcfg = &FspmUpd->FspmConfig; BoardId = GetPlatformId(); // SGX is not supported on this platform Fspmcfg->EnableSgx = 0; switch (GetPlatformId ()) { case BoardIdTglHDdr4SODimm: case 0xF: Fspmcfg->PrmrrSize = 0x100000; Fspmcfg->MmioSizeAdjustment = 0x308; break; default: break; } DebugPort = GetDebugPort (); if (DebugPort < PCH_MAX_SERIALIO_UART_CONTROLLERS) { Fspmcfg->PcdDebugInterfaceFlags = BIT4; Fspmcfg->SerialIoUartDebugControllerNumber = DebugPort; Fspmcfg->SerialIoUartDebugMode = 4; } else { Fspmcfg->PcdDebugInterfaceFlags = BIT1; if (DebugPort == 0xFF) { Fspmcfg->PcdIsaSerialUartBase = 0; } else { Fspmcfg->PcdIsaSerialUartBase = 1; } } //FSPM has a default value initially, during boot time, Slimboot can modify //it using data from CfgData blob. //then call FSPMemoryInit() who consumes all the overridden values. DEBUG ((DEBUG_INFO, "FSPM CfgData assignment\n")); MemCfgData = (MEMORY_CFG_DATA *)FindConfigDataByTag (CDATA_MEMORY_TAG); if (MemCfgData == NULL) { CpuHalt ("Failed to find memory CFGDATA!"); return; } DEBUG ((DEBUG_INFO, "Load Memory Cfg Data\n")); CopyMem (&Fspmcfg->SpdAddressTable, MemCfgData->SpdAddressTable, sizeof(MemCfgData->SpdAddressTable)); PlatformData = (PLATFORM_DATA *)GetPlatformDataPtr (); if (PlatformData == NULL) { return; } PlatformData->PlatformFeatures.VtdEnable = (!MemCfgData->VtdDisable) & FeaturePcdGet (PcdVtdEnabled); // Need enable VTD if TCC is enalbed. if (FeaturePcdGet (PcdTccEnabled)) { TccCfgData = (TCC_CFG_DATA *)FindConfigDataByTag (CDATA_TCC_TAG); if ((TccCfgData != NULL) && (TccCfgData->TccEnable == 1)) { DEBUG ((DEBUG_INFO, "Enable VTd since TCC is enabled\n")); PlatformData->PlatformFeatures.VtdEnable = 1; } } // Need enable VTd if TSN is enabled SiCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if (SiCfgData != NULL) { if (SiCfgData->PchTsnEnable == 1) { DEBUG ((DEBUG_INFO, "TSN is enabled\n")); PlatformData->PlatformFeatures.VtdEnable = 1; } } // Memory SPD Data SpdData[0] = 0; SpdData[1] = (UINT32)(UINTN) (((MEM_SPD0_CFG_DATA *)FindConfigDataByTag (CDATA_MEM_SPD0_TAG))->MemorySpdPtr0); SpdData[2] = (UINT32)(UINTN) (((MEM_SPD1_CFG_DATA *)FindConfigDataByTag (CDATA_MEM_SPD1_TAG))->MemorySpdPtr1); Fspmcfg->MemorySpdPtr000 = SpdData[MemCfgData->SpdDataSel000]; Fspmcfg->MemorySpdPtr001 = SpdData[MemCfgData->SpdDataSel001]; Fspmcfg->MemorySpdPtr010 = SpdData[MemCfgData->SpdDataSel010]; Fspmcfg->MemorySpdPtr011 = SpdData[MemCfgData->SpdDataSel011]; Fspmcfg->MemorySpdPtr020 = SpdData[MemCfgData->SpdDataSel020]; Fspmcfg->MemorySpdPtr021 = SpdData[MemCfgData->SpdDataSel021]; Fspmcfg->MemorySpdPtr030 = SpdData[MemCfgData->SpdDataSel030]; Fspmcfg->MemorySpdPtr031 = SpdData[MemCfgData->SpdDataSel031]; Fspmcfg->MemorySpdPtr100 = SpdData[MemCfgData->SpdDataSel100]; Fspmcfg->MemorySpdPtr101 = SpdData[MemCfgData->SpdDataSel101]; Fspmcfg->MemorySpdPtr110 = SpdData[MemCfgData->SpdDataSel110]; Fspmcfg->MemorySpdPtr111 = SpdData[MemCfgData->SpdDataSel111]; Fspmcfg->MemorySpdPtr120 = SpdData[MemCfgData->SpdDataSel120]; Fspmcfg->MemorySpdPtr121 = SpdData[MemCfgData->SpdDataSel121]; Fspmcfg->MemorySpdPtr130 = SpdData[MemCfgData->SpdDataSel130]; Fspmcfg->MemorySpdPtr131 = SpdData[MemCfgData->SpdDataSel131]; //Dq/Dqs Mapping arrays CopyMem (&Fspmcfg->DqsMapCpu2DramMc0Ch0, MemCfgData->DqsMapCpu2DramMc0Ch0, sizeof(MemCfgData->DqsMapCpu2DramMc0Ch0)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc0Ch1, MemCfgData->DqsMapCpu2DramMc0Ch1, sizeof(MemCfgData->DqsMapCpu2DramMc0Ch1)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc0Ch2, MemCfgData->DqsMapCpu2DramMc0Ch2, sizeof(MemCfgData->DqsMapCpu2DramMc0Ch2)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc0Ch3, MemCfgData->DqsMapCpu2DramMc0Ch3, sizeof(MemCfgData->DqsMapCpu2DramMc0Ch3)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc1Ch0, MemCfgData->DqsMapCpu2DramMc1Ch0, sizeof(MemCfgData->DqsMapCpu2DramMc1Ch0)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc1Ch1, MemCfgData->DqsMapCpu2DramMc1Ch1, sizeof(MemCfgData->DqsMapCpu2DramMc1Ch1)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc1Ch2, MemCfgData->DqsMapCpu2DramMc1Ch2, sizeof(MemCfgData->DqsMapCpu2DramMc1Ch2)); CopyMem (&Fspmcfg->DqsMapCpu2DramMc1Ch3, MemCfgData->DqsMapCpu2DramMc1Ch3, sizeof(MemCfgData->DqsMapCpu2DramMc1Ch3)); CopyMem (&Fspmcfg->DqMapCpu2DramMc0Ch0, MemCfgData->DqMapCpu2DramMc0Ch0, sizeof(MemCfgData->DqMapCpu2DramMc0Ch0)); CopyMem (&Fspmcfg->DqMapCpu2DramMc0Ch1, MemCfgData->DqMapCpu2DramMc0Ch1, sizeof(MemCfgData->DqMapCpu2DramMc0Ch1)); CopyMem (&Fspmcfg->DqMapCpu2DramMc0Ch2, MemCfgData->DqMapCpu2DramMc0Ch2, sizeof(MemCfgData->DqMapCpu2DramMc0Ch2)); CopyMem (&Fspmcfg->DqMapCpu2DramMc0Ch3, MemCfgData->DqMapCpu2DramMc0Ch3, sizeof(MemCfgData->DqMapCpu2DramMc0Ch3)); CopyMem (&Fspmcfg->DqMapCpu2DramMc1Ch0, MemCfgData->DqMapCpu2DramMc1Ch0, sizeof(MemCfgData->DqMapCpu2DramMc1Ch0)); CopyMem (&Fspmcfg->DqMapCpu2DramMc1Ch1, MemCfgData->DqMapCpu2DramMc1Ch1, sizeof(MemCfgData->DqMapCpu2DramMc1Ch1)); CopyMem (&Fspmcfg->DqMapCpu2DramMc1Ch2, MemCfgData->DqMapCpu2DramMc1Ch2, sizeof(MemCfgData->DqMapCpu2DramMc1Ch2)); CopyMem (&Fspmcfg->DqMapCpu2DramMc1Ch3, MemCfgData->DqMapCpu2DramMc1Ch3, sizeof(MemCfgData->DqMapCpu2DramMc1Ch3)); Fspmcfg->DqPinsInterleaved = MemCfgData->DqPinsInterleaved; //RComp Fspmcfg->RcompResistor = MemCfgData->RcompResistor; CopyMem (&Fspmcfg->RcompTarget, MemCfgData->RcompTarget, sizeof(MemCfgData->RcompTarget)); Fspmcfg->MrcFastBoot = MemCfgData->MrcFastBoot; Fspmcfg->RmtPerTask = MemCfgData->RmtPerTask; Fspmcfg->IedSize = MemCfgData->IedSize; Fspmcfg->TsegSize = MemCfgData->TsegSize; Fspmcfg->MmioSize = MemCfgData->MmioSize; Fspmcfg->SmbusEnable = MemCfgData->SmbusEnable; Fspmcfg->PlatformMemorySize = MemCfgData->PlatformMemorySize; Fspmcfg->X2ApicOptOut = MemCfgData->X2ApicOptOut; Fspmcfg->DmaControlGuarantee = MemCfgData->DmaControlGuarantee; Fspmcfg->TxtDprMemorySize = MemCfgData->TxtDprMemorySize; Fspmcfg->BiosAcmBase = MemCfgData->BiosAcmBase; Fspmcfg->UserBd = MemCfgData->UserBd; Fspmcfg->RealtimeMemoryTiming = MemCfgData->RealtimeMemoryTiming; Fspmcfg->EnableC6Dram = MemCfgData->EnableC6Dram; Fspmcfg->CpuRatio = MemCfgData->CpuRatio; Fspmcfg->BootFrequency = MemCfgData->BootFrequency; Fspmcfg->ActiveCoreCount = MemCfgData->ActiveCoreCount; Fspmcfg->FClkFrequency = MemCfgData->FClkFrequency; Fspmcfg->MrcSafeConfig = MemCfgData->MrcSafeConfig; Fspmcfg->EnhancedInterleave = MemCfgData->EnhancedInterleave; Fspmcfg->RankInterleave = MemCfgData->RankInterleave; Fspmcfg->RhPrevention = MemCfgData->RhPrevention; // Skip CPU replacement check for embedded design to always enable fast boot Fspmcfg->SkipCpuReplacementCheck = 1; if(MemCfgData->RhPrevention == 1) { Fspmcfg->RhSolution = MemCfgData->RhSolution; } if((MemCfgData->RhPrevention == 1) || (MemCfgData->RhSolution == 0)) { Fspmcfg->RhActProbability = MemCfgData->RhActProbability; } Fspmcfg->ExitOnFailure = MemCfgData->ExitOnFailure; Fspmcfg->ChHashEnable = MemCfgData->ChHashEnable; Fspmcfg->ChHashInterleaveBit = MemCfgData->ChHashInterleaveBit; Fspmcfg->ChHashMask = MemCfgData->ChHashMask; Fspmcfg->RemapEnable = MemCfgData->RemapEnable; Fspmcfg->ScramblerSupport = MemCfgData->ScramblerSupport; //MRC Training algorithms Fspmcfg->RMT = MemCfgData->RMT; Fspmcfg->BdatEnable = MemCfgData->BdatEnable; Fspmcfg->BdatTestType = MemCfgData->BdatTestType; Fspmcfg->RMC = MemCfgData->RMC; Fspmcfg->MEMTST = MemCfgData->MEMTST; Fspmcfg->ECT = MemCfgData->ECT; CopyMem (Fspmcfg->DmiGen3RootPortPreset, MemCfgData->DmiGen3RootPortPreset, sizeof(MemCfgData->DmiGen3RootPortPreset)); CopyMem (Fspmcfg->DmiGen3EndPointPreset, MemCfgData->DmiGen3EndPointPreset, sizeof(MemCfgData->DmiGen3EndPointPreset)); CopyMem (Fspmcfg->DmiGen3EndPointHint, MemCfgData->DmiGen3EndPointHint, sizeof(MemCfgData->DmiGen3EndPointHint)); CopyMem (Fspmcfg->PcieClkSrcUsage, MemCfgData->PcieClkSrcUsage, sizeof(MemCfgData->PcieClkSrcUsage)); CopyMem (Fspmcfg->PcieClkSrcClkReq, MemCfgData->PcieClkSrcClkReq, sizeof(MemCfgData->PcieClkSrcClkReq)); Fspmcfg->PchNumRsvdSmbusAddresses = sizeof (MemCfgData->SmbusAddressTable) / sizeof (MemCfgData->SmbusAddressTable[0]); Fspmcfg->RsvdSmbusAddressTablePtr = (UINT32) (UINTN)MemCfgData->SmbusAddressTable; Fspmcfg->UsbTcPortEnPreMem = MemCfgData->UsbTcPortEnPreMem; Fspmcfg->TmeEnable = MemCfgData->TmeEnable; // Disable TME, if // 1. If this is a FuSa Enabled SKU // 2. In-Band ECC is enabled if (Fspmcfg->TmeEnable != 0) { if ((AsmReadMsr64(MSR_CORE_CAPABILITIES) & B_MSR_CORE_CAPABILITIES_FUSA_SUPPORTED) != 0 || MemCfgData->Ibecc != 0) { DEBUG ((DEBUG_INFO, "FuSa-Supported SKU Detected or Ibecc enabled. Disabling TME.\n")); Fspmcfg->TmeEnable = 0; } } DEBUG ((DEBUG_INFO, "SkipMbpHob = 0x%x\n", Fspmcfg->SkipMbpHob)); Fspmcfg->SkipMbpHob = 0; GfxCfgData = (GRAPHICS_CFG_DATA *)FindConfigDataByTag (CDATA_GRAPHICS_TAG); if (GfxCfgData != NULL) { DEBUG ((DEBUG_INFO, "Load Graphics Cfg Data\n")); Fspmcfg->IgdDvmt50PreAlloc = GfxCfgData->IgdDvmt50PreAlloc; Fspmcfg->ApertureSize = GfxCfgData->ApertureSize; Fspmcfg->GttSize = GfxCfgData->GttSize; Fspmcfg->InternalGfx = GfxCfgData->InternalGfx; Fspmcfg->PrimaryDisplay = GfxCfgData->PrimaryDisplay; } else { DEBUG ((DEBUG_INFO, "Failed to find GFX CFG!\n")); } // Value from EDKII bios, refine these settings later. FspmArchUpd->StackBase = 0xFEF4FF00; FspmArchUpd->StackSize = 0x50000; Fspmcfg->TcssXdciEn = 0x1; // Following UPDs are related to TCC . But all of these are also generic features that can be changed regardless of TCC feature. Fspmcfg->SaGv = MemCfgData->SaGv; // System Agent Geyserville - SAGV dynamically adjusts the system agent // voltage and clock frequencies depending on power and performance requirements Fspmcfg->DisPgCloseIdleTimeout = MemCfgData->DisPgCloseIdleTimeout; // controls Page Close Idle Timeout Fspmcfg->PowerDownMode = MemCfgData->PowerDownMode; // controls command bus tristating during idle periods Fspmcfg->VtdDisable = (UINT8)(!PlatformData->PlatformFeatures.VtdEnable); Fspmcfg->WrcFeatureEnable = MemCfgData->WrcFeatureEnable; Fspmcfg->HyperThreading = MemCfgData->HyperThreading; Fspmcfg->GtClosEnable = MemCfgData->GtClosEnable; Fspmcfg->VmxEnable = MemCfgData->VmxEnable; Fspmcfg->BiosGuard = 0x0; // Need disable, else it will failed in fSPS Fspmcfg->SafeMode = 0x1; // Need enable, else failed in MRC // IBECC configuration Fspmcfg->Ibecc = MemCfgData->Ibecc; Fspmcfg->IbeccParity = MemCfgData->IbeccParity; Fspmcfg->IbeccOperationMode = MemCfgData->IbeccOperationMode; Fspmcfg->IbeccErrorInj = MemCfgData->IbeccErrorInj; for (Index = 0; Index < 8; Index++) { Fspmcfg->IbeccProtectedRegionEnable[Index] = MemCfgData->IbeccProtectedRegionEnable[Index]; Fspmcfg->IbeccProtectedRegionBase[Index] = MemCfgData->IbeccProtectedRegionBase[Index]; if (MemCfgData->IbeccProtectedRegionMask[Index] > 0x3FFF) { MemCfgData->IbeccProtectedRegionMask[Index] = 0x3FFF; } Fspmcfg->IbeccProtectedRegionMask[Index] = MemCfgData->IbeccProtectedRegionMask[Index]; } DEBUG((DEBUG_INFO, "board Id = %x .....\n", BoardId)); // // Display DDI Initialization ( default Native GPIO as per board during AUTO case) // switch (BoardId) { case BoardIdTglHDdr4SODimm: case 0xF: CopyMem(SaDisplayConfigTable, (VOID *)(UINTN)mTglHDdr4RowDisplayDdiConfig, sizeof(mTglHDdr4RowDisplayDdiConfig)); break; case BoardIdTglUDdr4: case BoardIdTglUpxi11: CopyMem(SaDisplayConfigTable, (VOID *)(UINTN)mTglUDdr4RowDisplayDdiConfig, sizeof(mTglUDdr4RowDisplayDdiConfig)); break; case BoardIdTglULp4Type4: CopyMem(SaDisplayConfigTable, (VOID *)(UINTN)mTglULpDdr4RowDisplayDdiConfig, sizeof(mTglULpDdr4RowDisplayDdiConfig)); break; default: DEBUG((DEBUG_INFO, "Unsupported board Id %x .....\n", BoardId)); break; } Fspmcfg->DdiPortAConfig = SaDisplayConfigTable[0]; Fspmcfg->DdiPortBConfig = SaDisplayConfigTable[1]; Fspmcfg->DdiPortAHpd = SaDisplayConfigTable[2]; Fspmcfg->DdiPortBHpd = SaDisplayConfigTable[3]; Fspmcfg->DdiPortCHpd = SaDisplayConfigTable[4]; Fspmcfg->DdiPort1Hpd = SaDisplayConfigTable[5]; Fspmcfg->DdiPort2Hpd = SaDisplayConfigTable[6]; Fspmcfg->DdiPort3Hpd = SaDisplayConfigTable[7]; Fspmcfg->DdiPort4Hpd = SaDisplayConfigTable[8]; Fspmcfg->DdiPortADdc = SaDisplayConfigTable[9]; Fspmcfg->DdiPortBDdc = SaDisplayConfigTable[10]; Fspmcfg->DdiPortCDdc = SaDisplayConfigTable[11]; Fspmcfg->DdiPort1Ddc = SaDisplayConfigTable[12]; Fspmcfg->DdiPort2Ddc = SaDisplayConfigTable[13]; Fspmcfg->DdiPort3Ddc = SaDisplayConfigTable[14]; Fspmcfg->DdiPort4Ddc = SaDisplayConfigTable[15]; if (PlatformData->PlatformFeatures.VtdEnable == 1) { Fspmcfg->VtdIgdEnable = 1; Fspmcfg->VtdIpuEnable = 1; Fspmcfg->VtdIopEnable = 1; Fspmcfg->VtdItbtEnable = 1; Fspmcfg->VtdBaseAddress[0] = 0xfed90000; Fspmcfg->VtdBaseAddress[1] = 0xfed92000; Fspmcfg->VtdBaseAddress[2] = 0xfed91000; Fspmcfg->VtdBaseAddress[3] = 0xfed84000; Fspmcfg->VtdBaseAddress[4] = 0xfed85000; Fspmcfg->VtdBaseAddress[5] = 0xfed86000; Fspmcfg->VtdBaseAddress[6] = 0xfed87000; } Fspmcfg->BootFrequency = 0x2; // will hang using default upds if (SiCfgData != NULL) { Fspmcfg->PchHdaEnable = SiCfgData->PchHdaEnable; Fspmcfg->PchHdaDspEnable = SiCfgData->PchHdaDspEnable; Fspmcfg->PchHdaAudioLinkDmicEnable[0] = SiCfgData->PchHdaAudioLinkDmicEnable[0]; Fspmcfg->PchHdaAudioLinkDmicEnable[1] = SiCfgData->PchHdaAudioLinkDmicEnable[1]; } Fspmcfg->PchHdaAudioLinkDmicClkAPinMux[0] = 0x29460c06; Fspmcfg->PchHdaAudioLinkDmicClkAPinMux[1] = 0x29460e04; Fspmcfg->PchHdaAudioLinkDmicClkBPinMux[0] = 0x29461402; Fspmcfg->PchHdaAudioLinkDmicClkBPinMux[1] = 0x29461603; Fspmcfg->PchHdaAudioLinkDmicDataPinMux[0] = 0x29460407; Fspmcfg->PchHdaAudioLinkDmicDataPinMux[1] = 0x29460605; Fspmcfg->PchHdaAudioLinkSndwEnable[1] = 0x1; Fspmcfg->PchTraceHubMode = MemCfgData->PchTraceHubMode; Fspmcfg->PlatformDebugConsent = MemCfgData->PlatformDebugConsent; Fspmcfg->DciEn = MemCfgData->DciEn; Fspmcfg->ConfigTdpLevel = MemCfgData->ConfigTdpLevel; // ES2 A1 silicon need set this to 1 Fspmcfg->McParity = MemCfgData->McParity; if (GetBootMode() == BOOT_ON_FLASH_UPDATE) { Fspmcfg->SiSkipOverrideBootModeWhenFwUpdate = TRUE; } Fspmcfg->DebugInterfaceLockEnable = TRUE; if (PcdGetBool(PcdFastBootEnabled)) { Fspmcfg->CpuPcieRpEnableMask = 0; } // s0ix update FeaturesCfgData = (FEATURES_CFG_DATA *) FindConfigDataByTag (CDATA_FEATURES_TAG); if (FeaturesCfgData != NULL) { PLAT_FEAT.S0ixEnable = FeaturesCfgData->Features.S0ix; // S0ix is disabled if TSN is enabled. if ((PLAT_FEAT.S0ixEnable == 1) && (SiCfgData != NULL) && (SiCfgData->PchTsnEnable == 1)) { PLAT_FEAT.S0ixEnable = 0; DEBUG ((DEBUG_INFO, "S0ix is turned off when TSN is enabled\n")); } } // Update TCC related UPDs if TCC is enabled if (FeaturePcdGet (PcdTccEnabled)) { TccModePreMemConfig (FspmUpd); } if (S0IX_STATUS() == 1) { // configure s0ix related FSP-M UPDs Fspmcfg->TcssXdciEn = 0; Fspmcfg->TcssXhciEn = 0; Fspmcfg->TcssDma0En = 0; Fspmcfg->TcssDma1En = 0; Fspmcfg->TcssItbtPcie0En = 0; Fspmcfg->TcssItbtPcie1En = 0; Fspmcfg->TcssItbtPcie2En = 0; Fspmcfg->TcssItbtPcie3En = 0; Fspmcfg->DmiAspmCtrl = 2;// ASPM configuration on the CPU side of the DMI/OPI Link } } /** Determine if this is firmware update mode. This function will determine if we have to put system in firmware update mode. @retval EFI_SUCCESS The operation completed successfully. @retval others There is error happening. **/ BOOLEAN IsFirmwareUpdate () { // // Check if state machine is set to capsule processing mode. // if (CheckStateMachine (NULL) == EFI_SUCCESS) { return TRUE; } // // Check if platform firmware update trigger is set. // if (IoRead32 (ACPI_BASE_ADDRESS + R_ACPI_IO_OC_WDT_CTL) & BIT16) { return TRUE; } return FALSE; } /** Initialize the SPI controller. @retval None **/ VOID SpiControllerInitialize ( VOID ) { UINT32 SpiAddress; UINT32 SpiBar; SpiAddress = GetDeviceAddr (OsBootDeviceSpi, 0); SpiAddress = TO_PCI_LIB_ADDRESS (SpiAddress); // Enable PCI config space for SPI device SpiBar = PciRead32(SpiAddress + PCI_BASE_ADDRESSREG_OFFSET) & 0xFFFFF000; if (SpiBar == 0) { PciWrite32(SpiAddress + R_SPI_CFG_BAR0, SPI_TEMP_MEM_BASE_ADDRESS); PciWrite8(SpiAddress + 4, 6); } SpiConstructor (); } /** Read the Platform Features from the config data **/ VOID PlatformFeaturesInit ( VOID ) { FEATURES_CFG_DATA *FeaturesCfgData; PLATFORM_DATA *PlatformData; UINTN HeciBaseAddress; UINT32 LdrFeatures; // Set common features LdrFeatures = GetFeatureCfg (); LdrFeatures |= FeaturePcdGet (PcdAcpiEnabled)?FEATURE_ACPI:0; LdrFeatures |= FeaturePcdGet (PcdVerifiedBootEnabled)?FEATURE_VERIFIED_BOOT:0; LdrFeatures |= FeaturePcdGet (PcdMeasuredBootEnabled)?FEATURE_MEASURED_BOOT:0; // Disable feature by configuration data. FeaturesCfgData = (FEATURES_CFG_DATA *) FindConfigDataByTag(CDATA_FEATURES_TAG); if (FeaturesCfgData != NULL) { if (FeaturesCfgData->Features.Acpi == 0) { LdrFeatures &= ~FEATURE_ACPI; } if (FeaturesCfgData->Features.MeasuredBoot == 0) { LdrFeatures &= ~FEATURE_MEASURED_BOOT; } } else { DEBUG ((DEBUG_INFO, "FEATURES CFG DATA NOT FOUND!\n")); } // Disable features by boot guard profile PlatformData = (PLATFORM_DATA *)GetPlatformDataPtr (); if (PlatformData != NULL) { HeciBaseAddress = MM_PCI_ADDRESS ( 0x0, 22, 0x0, 0x0 ); GetBootGuardInfo (HeciBaseAddress, &PlatformData->BtGuardInfo); DEBUG ((DEBUG_INFO, "GetPlatformDataPtr is copied 0x%08X \n", PlatformData)); if (!PlatformData->BtGuardInfo.MeasuredBoot) { LdrFeatures &= ~FEATURE_MEASURED_BOOT; } if (!PlatformData->BtGuardInfo.VerifiedBoot) { LdrFeatures &= ~FEATURE_VERIFIED_BOOT; } } SetFeatureCfg (LdrFeatures); } /** Initialize TPM. **/ VOID TpmInitialize ( VOID ) { EFI_STATUS Status; UINT8 BootMode; PLATFORM_DATA *PlatformData; UINT32 Features; BootMode = GetBootMode(); PlatformData = (PLATFORM_DATA *)GetPlatformDataPtr (); if((PlatformData != NULL) && PlatformData->BtGuardInfo.MeasuredBoot && (!PlatformData->BtGuardInfo.DisconnectAllTpms) && ((PlatformData->BtGuardInfo.TpmType == dTpm20) || (PlatformData->BtGuardInfo.TpmType == Ptt))){ // As per PC Client spec, SRTM should perform a host platform reset if (PlatformData->BtGuardInfo.TpmStartupFailureOnS3) { ResetSystem(EfiResetCold); CpuDeadLoop (); } // Initialize TPM if it has not already been initialized by BootGuard component (i.e. ACM) Status = TpmInit(PlatformData->BtGuardInfo.BypassTpmInit, BootMode); if (EFI_ERROR (Status)) { CpuHalt ("Tpm Initialization failed !!\n"); } else { if (BootMode != BOOT_ON_S3_RESUME) { // Create and add BootGuard Event logs in TCG Event log CreateTpmEventLog (PlatformData->BtGuardInfo.TpmType); } } } else { DisableTpm(); Features = GetFeatureCfg (); Features &= (UINT32)(~FEATURE_MEASURED_BOOT); SetFeatureCfg (Features); } } /** Read the current platform state from PM status reg. @retval Bootmode current power state. **/ UINT8 GetPlatformPowerState ( VOID ) { UINT8 BootMode; UINT32 PmconA; PmconA = MmioRead32 (PCH_PWRM_BASE_ADDRESS + R_PMC_PWRM_GEN_PMCON_A); // // Clear PWRBTNOR_STS // if (IoRead16 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS) & B_ACPI_IO_PM1_STS_PRBTNOR) { IoWrite16 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS, B_ACPI_IO_PM1_STS_PRBTNOR); } // // If Global Reset Status, Power Failure. Host Reset Status bits are set, return S5 State // if ((PmconA & (B_PMC_PWRM_GEN_PMCON_A_GBL_RST_STS | B_PMC_PWRM_GEN_PMCON_A_PWR_FLR | B_PMC_PWRM_GEN_PMCON_A_HOST_RST_STS)) != 0) { return BOOT_WITH_FULL_CONFIGURATION; } BootMode = BOOT_WITH_FULL_CONFIGURATION; if (IoRead16 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS) & B_ACPI_IO_PM1_STS_WAK) { switch (IoRead16 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_CNT) & B_ACPI_IO_PM1_CNT_SLP_TYP) { case V_ACPI_IO_PM1_CNT_S3: BootMode = BOOT_ON_S3_RESUME; break; case V_ACPI_IO_PM1_CNT_S4: BootMode = BOOT_ON_S4_RESUME; break; case V_ACPI_IO_PM1_CNT_S5: BootMode = BOOT_ON_S5_RESUME; break; default: BootMode = BOOT_WITH_FULL_CONFIGURATION; break; } } /// /// Clear Wake Status /// Also clear the PWRBTN_EN, it causes SMI# otherwise (SCI_EN is 0) /// IoAndThenOr32 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_STS, (UINT32)~B_ACPI_IO_PM1_EN_PWRBTN_EN, B_ACPI_IO_PM1_STS_WAK); if ((MmioRead8 (PCH_PWRM_BASE_ADDRESS + R_PMC_PWRM_GEN_PMCON_B) & B_PMC_PWRM_GEN_PMCON_B_RTC_PWR_STS) != 0) { BootMode = BOOT_WITH_FULL_CONFIGURATION; /// /// Clear Sleep Type /// IoAndThenOr16 (ACPI_BASE_ADDRESS + R_ACPI_IO_PM1_CNT, (UINT16) ~B_ACPI_IO_PM1_CNT_SLP_TYP, V_ACPI_IO_PM1_CNT_S0); } /// /// Disable Power Management Event EN /// IoAnd32 (ACPI_BASE_ADDRESS + R_ACPI_IO_GPE0_EN_127_96, (UINT32)~B_ACPI_IO_GPE0_EN_127_96_PME_B0); return BootMode; } /** Initialize Board specific things in Stage1 Phase @param[in] InitPhase Indicates a board init phase to be initialized @retval None **/ VOID EFIAPI BoardInit ( IN BOARD_INIT_PHASE InitPhase ) { UINTN PmcMmioBase; PLT_DEVICE_TABLE *PltDeviceTable; UINT8 BoardId; SILICON_CFG_DATA *SiCfgData; PmcMmioBase = PCH_PWRM_BASE_ADDRESS; switch (InitPhase) { case PreConfigInit: DEBUG_CODE_BEGIN(); UINT32 Data; Data = *(UINT32 *) (UINTN) (0xFED30328); DEBUG ((DEBUG_ERROR, "[Boot Guard] AcmStatus : 0x%08X\n", Data)); Data = *(UINT32 *) (UINTN) (0xFED300A4); DEBUG ((DEBUG_ERROR, "[Boot Guard] BootStatus: 0x%08X\n", Data)); if ((Data & (BIT31 | BIT30)) != BIT31) { DEBUG ((DEBUG_ERROR, "[Boot Guard] Boot Guard Failed or is Disabled!\n", Data)); } else { DEBUG ((DEBUG_INFO, "[Boot Guard] Boot Guard is Enabled Successfully.\n", Data)); } DEBUG_CODE_END(); SetSocSku (PchSeries ()); PltDeviceTable = (PLT_DEVICE_TABLE *)AllocatePool (sizeof (PLT_DEVICE_TABLE) + sizeof (mPlatformDevices)); if (PltDeviceTable != NULL) { PltDeviceTable->DeviceNumber = sizeof (mPlatformDevices) /sizeof (PLT_DEVICE); CopyMem (PltDeviceTable->Device, mPlatformDevices, sizeof (mPlatformDevices)); SetDeviceTable (PltDeviceTable); } else { DEBUG ((DEBUG_ERROR, "Out of resource for PltDeviceTable\n")); } SpiControllerInitialize (); break; case PostConfigInit: if (GetPlatformId() == 0) { // If PlatformId is not initialized yet, set the PlatformId based on detected BoardId. // If EC is disabled, set to DDR4 board and skip board detection. SiCfgData = (SILICON_CFG_DATA *)FindConfigDataByTag (CDATA_SILICON_TAG); if ((SiCfgData == NULL) || (SiCfgData->EcEnable == 0)){ BoardId = BoardIdTglUDdr4; } else { GetBoardId (&BoardId); if (BoardId == BoardIdTglHDdr4SODimm) { // TGL-H DDR4 board is 0x21, map to PlatformId 0xF since PlatformId is limited to max of 0x1F BoardId = 0xF; } } SetPlatformId (BoardId); } PlatformNameInit (); SetBootMode (IsFirmwareUpdate() ? BOOT_ON_FLASH_UPDATE : GetPlatformPowerState()); PlatformFeaturesInit (); break; case PreMemoryInit: // // Set the DISB bit in PCH (DRAM Initialization Scratchpad Bit) // prior to starting DRAM Initialization Sequence. // MmioOr32 (PmcMmioBase + R_PMC_PWRM_GEN_PMCON_A, B_PCH_PMC_GEN_PMCON_A_DISB); switch (GetPlatformId ()) { case BoardIdTglHDdr4SODimm: case 0xF: ConfigureGpio (CDATA_NO_TAG, sizeof (mGpioTablePreMemTglHDdr4) / sizeof (mGpioTablePreMemTglHDdr4[0]), (UINT8*)mGpioTablePreMemTglHDdr4); break; case BoardIdTglUDdr4: case BoardIdTglULp4Type4: default: ConfigureGpio (CDATA_NO_TAG, sizeof (mGpioTablePreMemTglUDdr4) / sizeof (mGpioTablePreMemTglUDdr4[0]), (UINT8*)mGpioTablePreMemTglUDdr4); break; } break; case PostMemoryInit: // // Clear the DISB bit after completing DRAM Initialization Sequence // MmioAnd32 (PmcMmioBase + R_PMC_PWRM_GEN_PMCON_A, (UINT32)~B_PCH_PMC_GEN_PMCON_A_DISB); UpdateMemoryInfo (); break; case PreTempRamExit: break; case PostTempRamExit: if (MEASURED_BOOT_ENABLED()) { TpmInitialize(); } break; default: break; } } /** Search for the saved MrcParam to initialize Memory for fastboot @retval Found MrcParam or NULL **/ VOID * EFIAPI FindNvsData ( VOID ) { UINT32 MrcData; DYNAMIC_CFG_DATA *DynCfgData; EFI_STATUS Status; DynCfgData = (DYNAMIC_CFG_DATA *)FindConfigDataByTag (CDATA_DYNAMIC_TAG); if (DynCfgData != NULL) { // // When enabled, memory training is enforced even if consistent memory parameters are available // if (DynCfgData->MrcTrainingEnforcement) { DEBUG ((DEBUG_INFO, "Training Enforcement enabled, hence providing NULL pointer for NVS Data!\n")); return NULL; } } else { DEBUG ((DEBUG_INFO, "Failed to find dynamic CFG!\n")); } Status = GetComponentInfo (FLASH_MAP_SIG_MRCDATA, &MrcData, NULL); if (EFI_ERROR(Status)) { return NULL; } if (*(UINT32 *)(UINTN)MrcData == 0xFFFFFFFF) { return NULL; } else { return (VOID *)(UINTN)MrcData; } } /** Load the configuration data blob from media into destination buffer. Currently for ICL, we support the sources: PDR, BIOS for external Cfgdata. @param[in] Dst Destination address to load configuration data blob. @param[in] Src Source address to load configuration data blob. @param[in] Len The destination address buffer size. @retval EFI_SUCCESS Configuration data blob was loaded successfully. @retval EFI_NOT_FOUND Configuration data blob cannot be found. @retval EFI_OUT_OF_RESOURCES Destination buffer is too small to hold the configuration data blob. @retval Others Failed to load configuration data blob. **/ EFI_STATUS EFIAPI LoadExternalConfigData ( IN UINT32 Dst, IN UINT32 Src, IN UINT32 Len ) { return SpiLoadExternalConfigData (Dst, Src, Len); }
1000704.c
/* FreeRDP: A Remote Desktop Protocol client. RemoteFX Codec Library - NEON Optimizations Copyright 2011 Martin Fleisz <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if defined(__ARM_NEON__) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arm_neon.h> #include "rfx_types.h" #include "rfx_neon.h" #if defined(ANDROID) #include <cpu-features.h> #endif void rfx_decode_YCbCr_to_RGB_NEON(sint16 * y_r_buffer, sint16 * cb_g_buffer, sint16 * cr_b_buffer) { int16x8_t zero = vdupq_n_s16(0); int16x8_t max = vdupq_n_s16(255); int16x8_t y_add = vdupq_n_s16(128); int16x8_t* y_r_buf = (int16x8_t*)y_r_buffer; int16x8_t* cb_g_buf = (int16x8_t*)cb_g_buffer; int16x8_t* cr_b_buf = (int16x8_t*)cr_b_buffer; int i; for (i = 0; i < 4096 / 8; i++) { int16x8_t y = vld1q_s16((sint16*)&y_r_buf[i]); y = vaddq_s16(y, y_add); int16x8_t cr = vld1q_s16((sint16*)&cr_b_buf[i]); // r = between((y + cr + (cr >> 2) + (cr >> 3) + (cr >> 5)), 0, 255); int16x8_t r = vaddq_s16(y, cr); r = vaddq_s16(r, vshrq_n_s16(cr, 2)); r = vaddq_s16(r, vshrq_n_s16(cr, 3)); r = vaddq_s16(r, vshrq_n_s16(cr, 5)); r = vminq_s16(vmaxq_s16(r, zero), max); vst1q_s16((sint16*)&y_r_buf[i], r); // cb = cb_g_buf[i]; int16x8_t cb = vld1q_s16((sint16*)&cb_g_buf[i]); // g = between(y - (cb >> 2) - (cb >> 4) - (cb >> 5) - (cr >> 1) - (cr >> 3) - (cr >> 4) - (cr >> 5), 0, 255); int16x8_t g = vsubq_s16(y, vshrq_n_s16(cb, 2)); g = vsubq_s16(g, vshrq_n_s16(cb, 4)); g = vsubq_s16(g, vshrq_n_s16(cb, 5)); g = vsubq_s16(g, vshrq_n_s16(cr, 1)); g = vsubq_s16(g, vshrq_n_s16(cr, 3)); g = vsubq_s16(g, vshrq_n_s16(cr, 4)); g = vsubq_s16(g, vshrq_n_s16(cr, 5)); g = vminq_s16(vmaxq_s16(g, zero), max); vst1q_s16((sint16*)&cb_g_buf[i], g); // b = between((y + cb + (cb >> 1) + (cb >> 2) + (cb >> 6)), 0, 255); int16x8_t b = vaddq_s16(y, cb); b = vaddq_s16(b, vshrq_n_s16(cb, 1)); b = vaddq_s16(b, vshrq_n_s16(cb, 2)); b = vaddq_s16(b, vshrq_n_s16(cb, 6)); b = vminq_s16(vmaxq_s16(b, zero), max); vst1q_s16((sint16*)&cr_b_buf[i], b); } } static __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) rfx_quantization_decode_block_NEON(sint16 * buffer, const int buffer_size, const uint32 factor) { if (factor <= 6) return; int16x8_t quantFactors = vdupq_n_s16(factor - 6); int16x8_t* buf = (int16x8_t*)buffer; int16x8_t* buf_end = (int16x8_t*)(buffer + buffer_size); do { int16x8_t val = vld1q_s16((sint16*)buf); val = vshlq_s16(val, quantFactors); vst1q_s16((sint16*)buf, val); buf++; } while(buf < buf_end); } void rfx_quantization_decode_NEON(sint16 * buffer, const uint32 * quantization_values) { rfx_quantization_decode_block_NEON(buffer, 1024, quantization_values[8]); /* HL1 */ rfx_quantization_decode_block_NEON(buffer + 1024, 1024, quantization_values[7]); /* LH1 */ rfx_quantization_decode_block_NEON(buffer + 2048, 1024, quantization_values[9]); /* HH1 */ rfx_quantization_decode_block_NEON(buffer + 3072, 256, quantization_values[5]); /* HL2 */ rfx_quantization_decode_block_NEON(buffer + 3328, 256, quantization_values[4]); /* LH2 */ rfx_quantization_decode_block_NEON(buffer + 3584, 256, quantization_values[6]); /* HH2 */ rfx_quantization_decode_block_NEON(buffer + 3840, 64, quantization_values[2]); /* HL3 */ rfx_quantization_decode_block_NEON(buffer + 3904, 64, quantization_values[1]); /* LH3 */ rfx_quantization_decode_block_NEON(buffer + 3968, 64, quantization_values[3]); /* HH3 */ rfx_quantization_decode_block_NEON(buffer + 4032, 64, quantization_values[0]); /* LL3 */ } static __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) rfx_dwt_2d_decode_block_horiz_NEON(sint16 * l, sint16 * h, sint16 * dst, int subband_width) { int y, n; sint16 * l_ptr = l; sint16 * h_ptr = h; sint16 * dst_ptr = dst; for (y = 0; y < subband_width; y++) { /* Even coefficients */ for (n = 0; n < subband_width; n+=8) { // dst[2n] = l[n] - ((h[n-1] + h[n] + 1) >> 1); int16x8_t l_n = vld1q_s16(l_ptr); int16x8_t h_n = vld1q_s16(h_ptr); int16x8_t h_n_m = vld1q_s16(h_ptr - 1); if (n == 0) { int16_t first = vgetq_lane_s16(h_n_m, 1); h_n_m = vsetq_lane_s16(first, h_n_m, 0); } int16x8_t tmp_n = vaddq_s16(h_n, h_n_m); tmp_n = vaddq_s16(tmp_n, vdupq_n_s16(1)); tmp_n = vshrq_n_s16(tmp_n, 1); int16x8_t dst_n = vsubq_s16(l_n, tmp_n); vst1q_s16(l_ptr, dst_n); l_ptr+=8; h_ptr+=8; } l_ptr -= subband_width; h_ptr -= subband_width; /* Odd coefficients */ for (n = 0; n < subband_width; n+=8) { // dst[2n + 1] = (h[n] << 1) + ((dst[2n] + dst[2n + 2]) >> 1); int16x8_t h_n = vld1q_s16(h_ptr); h_n = vshlq_n_s16(h_n, 1); int16x8x2_t dst_n; dst_n.val[0] = vld1q_s16(l_ptr); int16x8_t dst_n_p = vld1q_s16(l_ptr + 1); if (n == subband_width - 8) { int16_t last = vgetq_lane_s16(dst_n_p, 6); dst_n_p = vsetq_lane_s16(last, dst_n_p, 7); } dst_n.val[1] = vaddq_s16(dst_n_p, dst_n.val[0]); dst_n.val[1] = vshrq_n_s16(dst_n.val[1], 1); dst_n.val[1] = vaddq_s16(dst_n.val[1], h_n); vst2q_s16(dst_ptr, dst_n); l_ptr+=8; h_ptr+=8; dst_ptr+=16; } } } static __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) rfx_dwt_2d_decode_block_vert_NEON(sint16 * l, sint16 * h, sint16 * dst, int subband_width) { int x, n; sint16 * l_ptr = l; sint16 * h_ptr = h; sint16 * dst_ptr = dst; int total_width = subband_width + subband_width; /* Even coefficients */ for (n = 0; n < subband_width; n++) { for (x = 0; x < total_width; x+=8) { // dst[2n] = l[n] - ((h[n-1] + h[n] + 1) >> 1); int16x8_t l_n = vld1q_s16(l_ptr); int16x8_t h_n = vld1q_s16(h_ptr); int16x8_t tmp_n = vaddq_s16(h_n, vdupq_n_s16(1));; if (n == 0) tmp_n = vaddq_s16(tmp_n, h_n); else { int16x8_t h_n_m = vld1q_s16((h_ptr - total_width)); tmp_n = vaddq_s16(tmp_n, h_n_m); } tmp_n = vshrq_n_s16(tmp_n, 1); int16x8_t dst_n = vsubq_s16(l_n, tmp_n); vst1q_s16(dst_ptr, dst_n); l_ptr+=8; h_ptr+=8; dst_ptr+=8; } dst_ptr+=total_width; } h_ptr = h; dst_ptr = dst + total_width; /* Odd coefficients */ for (n = 0; n < subband_width; n++) { for (x = 0; x < total_width; x+=8) { // dst[2n + 1] = (h[n] << 1) + ((dst[2n] + dst[2n + 2]) >> 1); int16x8_t h_n = vld1q_s16(h_ptr); int16x8_t dst_n_m = vld1q_s16(dst_ptr - total_width); h_n = vshlq_n_s16(h_n, 1); int16x8_t tmp_n = dst_n_m; if (n == subband_width - 1) tmp_n = vaddq_s16(tmp_n, dst_n_m); else { int16x8_t dst_n_p = vld1q_s16((dst_ptr + total_width)); tmp_n = vaddq_s16(tmp_n, dst_n_p); } tmp_n = vshrq_n_s16(tmp_n, 1); int16x8_t dst_n = vaddq_s16(tmp_n, h_n); vst1q_s16(dst_ptr, dst_n); h_ptr+=8; dst_ptr+=8; } dst_ptr+=total_width; } } static __inline void __attribute__((__gnu_inline__, __always_inline__, __artificial__)) rfx_dwt_2d_decode_block_NEON(sint16 * buffer, sint16 * idwt, int subband_width) { sint16 * hl, * lh, * hh, * ll; sint16 * l_dst, * h_dst; /* Inverse DWT in horizontal direction, results in 2 sub-bands in L, H order in tmp buffer idwt. */ /* The 4 sub-bands are stored in HL(0), LH(1), HH(2), LL(3) order. */ /* The lower part L uses LL(3) and HL(0). */ /* The higher part H uses LH(1) and HH(2). */ ll = buffer + subband_width * subband_width * 3; hl = buffer; l_dst = idwt; rfx_dwt_2d_decode_block_horiz_NEON(ll, hl, l_dst, subband_width); lh = buffer + subband_width * subband_width; hh = buffer + subband_width * subband_width * 2; h_dst = idwt + subband_width * subband_width * 2; rfx_dwt_2d_decode_block_horiz_NEON(lh, hh, h_dst, subband_width); /* Inverse DWT in vertical direction, results are stored in original buffer. */ rfx_dwt_2d_decode_block_vert_NEON(l_dst, h_dst, buffer, subband_width); } void rfx_dwt_2d_decode_NEON(sint16 * buffer, sint16 * dwt_buffer) { rfx_dwt_2d_decode_block_NEON(buffer + 3840, dwt_buffer, 8); rfx_dwt_2d_decode_block_NEON(buffer + 3072, dwt_buffer, 16); rfx_dwt_2d_decode_block_NEON(buffer, dwt_buffer, 32); } int isNeonSupported() { #if defined(ANDROID) if (android_getCpuFamily() != ANDROID_CPU_FAMILY_ARM) { DEBUG_RFX("NEON optimization disabled - No ARM CPU found"); return 0; } uint64_t features = android_getCpuFeatures(); if ((features & ANDROID_CPU_ARM_FEATURE_ARMv7)) { if (features & ANDROID_CPU_ARM_FEATURE_NEON) { DEBUG_RFX("NEON optimization enabled!"); return 1; } DEBUG_RFX("NEON optimization disabled - CPU not NEON capable"); } else DEBUG_RFX("NEON optimization disabled - No ARMv7 CPU found"); return 0; #else return 1; #endif } void rfx_init_decoder_neon(RFX_CONTEXT * context) { RFX_CONTEXT_DEFAULT_PRIV* priv = (RFX_CONTEXT_DEFAULT_PRIV*)context->priv; if(isNeonSupported()) { DEBUG_RFX("Using NEON optimizations"); IF_PROFILER(priv->prof_rfx_decode_ycbcr_to_rgb->name = "rfx_decode_YCbCr_to_RGB_NEON"); IF_PROFILER(priv->prof_rfx_quantization_decode->name = "rfx_quantization_decode_NEON"); IF_PROFILER(priv->prof_rfx_dwt_2d_decode->name = "rfx_dwt_2d_decode_NEON"); priv->decode_ycbcr_to_rgb = rfx_decode_YCbCr_to_RGB_NEON; priv->quantization_decode = rfx_quantization_decode_NEON; priv->dwt_2d_decode = rfx_dwt_2d_decode_NEON; } } void rfx_init_encoder_neon(RFX_COMPOSE_CONTEXT * context) { } #endif // __ARM_NEON__
774823.c
/* Copyright (c) 2016, Alexander Entinger / LXRobotics * 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 motor-controller-highpower-motorshield 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 <avr/interrupt.h> #include <avr/wdt.h> #include <stdint.h> #include "project.h" #include "gpio.h" #include "analog.h" #include "servo.h" #include "uart.h" #include "parser.h" // Prototype section void initApplication(); int main() { initApplication(); for(;;) { wdt_reset(); while(uartDataAvailable()) { uint8_t data; readByte(&data); parse(data); } } return 0; } /** * @brief initialises the application */ void initApplication() { wdt_enable(WDTO_500MS); // enable watchdog, set to 0.5 second initGpio(); initAnalog(); initServo(); initUart(); sei(); // enable globally interrupts }
473488.c
/* * Interplay C93 video decoder * Copyright (c) 2007 Anssi Hannula <[email protected]> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avcodec.h" #include "bytestream.h" #include "internal.h" typedef struct C93DecoderContext { AVFrame *pictures[2]; int currentpic; } C93DecoderContext; typedef enum { C93_8X8_FROM_PREV = 0x02, C93_4X4_FROM_PREV = 0x06, C93_4X4_FROM_CURR = 0x07, C93_8X8_2COLOR = 0x08, C93_4X4_2COLOR = 0x0A, C93_4X4_4COLOR_GRP = 0x0B, C93_4X4_4COLOR = 0x0D, C93_NOOP = 0x0E, C93_8X8_INTRA = 0x0F, } C93BlockType; #define WIDTH 320 #define HEIGHT 192 #define C93_HAS_PALETTE 0x01 #define C93_FIRST_FRAME 0x02 static av_cold int decode_end(AVCodecContext *avctx) { C93DecoderContext * const c93 = avctx->priv_data; av_frame_free(&c93->pictures[0]); av_frame_free(&c93->pictures[1]); return 0; } static av_cold int decode_init(AVCodecContext *avctx) { C93DecoderContext *s = avctx->priv_data; avctx->pix_fmt = AV_PIX_FMT_PAL8; s->pictures[0] = av_frame_alloc(); s->pictures[1] = av_frame_alloc(); if (!s->pictures[0] || !s->pictures[1]) { decode_end(avctx); return AVERROR(ENOMEM); } return 0; } static inline int copy_block(AVCodecContext *avctx, uint8_t *to, uint8_t *from, int offset, int height, int stride) { int i; int width = height; int from_x = offset % WIDTH; int from_y = offset / WIDTH; int overflow = from_x + width - WIDTH; if (!from) { /* silently ignoring predictive blocks in first frame */ return 0; } if (from_y + height > HEIGHT) { av_log(avctx, AV_LOG_ERROR, "invalid offset %d during C93 decoding\n", offset); return AVERROR_INVALIDDATA; } if (overflow > 0) { width -= overflow; for (i = 0; i < height; i++) { memcpy(&to[i*stride+width], &from[(from_y+i)*stride], overflow); } } for (i = 0; i < height; i++) { memcpy(&to[i*stride], &from[(from_y+i)*stride+from_x], width); } return 0; } static inline void draw_n_color(uint8_t *out, int stride, int width, int height, int bpp, uint8_t cols[4], uint8_t grps[4], uint32_t col) { int x, y; for (y = 0; y < height; y++) { if (grps) cols[0] = grps[3 * (y >> 1)]; for (x = 0; x < width; x++) { if (grps) cols[1]= grps[(x >> 1) + 1]; out[x + y*stride] = cols[col & ((1 << bpp) - 1)]; col >>= bpp; } } } static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame, AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; C93DecoderContext * const c93 = avctx->priv_data; AVFrame * const newpic = c93->pictures[c93->currentpic]; AVFrame * const oldpic = c93->pictures[c93->currentpic^1]; GetByteContext gb; uint8_t *out; int stride, ret, i, x, y, b, bt = 0; if ((ret = ff_set_dimensions(avctx, WIDTH, HEIGHT)) < 0) return ret; c93->currentpic ^= 1; if ((ret = ff_reget_buffer(avctx, newpic, 0)) < 0) return ret; stride = newpic->linesize[0]; bytestream2_init(&gb, buf, buf_size); b = bytestream2_get_byte(&gb); if (b & C93_FIRST_FRAME) { newpic->pict_type = AV_PICTURE_TYPE_I; newpic->key_frame = 1; } else { newpic->pict_type = AV_PICTURE_TYPE_P; newpic->key_frame = 0; } for (y = 0; y < HEIGHT; y += 8) { out = newpic->data[0] + y * stride; for (x = 0; x < WIDTH; x += 8) { uint8_t *copy_from = oldpic->data[0]; unsigned int offset, j; uint8_t cols[4], grps[4]; C93BlockType block_type; if (!bt) bt = bytestream2_get_byte(&gb); block_type= bt & 0x0F; switch (block_type) { case C93_8X8_FROM_PREV: offset = bytestream2_get_le16(&gb); if ((ret = copy_block(avctx, out, copy_from, offset, 8, stride)) < 0) return ret; break; case C93_4X4_FROM_CURR: copy_from = newpic->data[0]; case C93_4X4_FROM_PREV: for (j = 0; j < 8; j += 4) { for (i = 0; i < 8; i += 4) { int offset = bytestream2_get_le16(&gb); int from_x = offset % WIDTH; int from_y = offset / WIDTH; if (block_type == C93_4X4_FROM_CURR && from_y == y+j && (FFABS(from_x - x-i) < 4 || FFABS(from_x - x-i) > WIDTH-4)) { avpriv_request_sample(avctx, "block overlap %d %d %d %d", from_x, x+i, from_y, y+j); return AVERROR_INVALIDDATA; } if ((ret = copy_block(avctx, &out[j*stride+i], copy_from, offset, 4, stride)) < 0) return ret; } } break; case C93_8X8_2COLOR: bytestream2_get_buffer(&gb, cols, 2); for (i = 0; i < 8; i++) { draw_n_color(out + i*stride, stride, 8, 1, 1, cols, NULL, bytestream2_get_byte(&gb)); } break; case C93_4X4_2COLOR: case C93_4X4_4COLOR: case C93_4X4_4COLOR_GRP: for (j = 0; j < 8; j += 4) { for (i = 0; i < 8; i += 4) { if (block_type == C93_4X4_2COLOR) { bytestream2_get_buffer(&gb, cols, 2); draw_n_color(out + i + j*stride, stride, 4, 4, 1, cols, NULL, bytestream2_get_le16(&gb)); } else if (block_type == C93_4X4_4COLOR) { bytestream2_get_buffer(&gb, cols, 4); draw_n_color(out + i + j*stride, stride, 4, 4, 2, cols, NULL, bytestream2_get_le32(&gb)); } else { bytestream2_get_buffer(&gb, grps, 4); draw_n_color(out + i + j*stride, stride, 4, 4, 1, cols, grps, bytestream2_get_le16(&gb)); } } } break; case C93_NOOP: break; case C93_8X8_INTRA: for (j = 0; j < 8; j++) bytestream2_get_buffer(&gb, out + j*stride, 8); break; default: av_log(avctx, AV_LOG_ERROR, "unexpected type %x at %dx%d\n", block_type, x, y); return AVERROR_INVALIDDATA; } bt >>= 4; out += 8; } } if (b & C93_HAS_PALETTE) { uint32_t *palette = (uint32_t *) newpic->data[1]; for (i = 0; i < 256; i++) { palette[i] = 0xFFU << 24 | bytestream2_get_be24(&gb); } newpic->palette_has_changed = 1; } else { if (oldpic->data[1]) memcpy(newpic->data[1], oldpic->data[1], 256 * 4); } if ((ret = av_frame_ref(data, newpic)) < 0) return ret; *got_frame = 1; return buf_size; } AVCodec ff_c93_decoder = { .name = "c93", .long_name = NULL_IF_CONFIG_SMALL("Interplay C93"), .type = AVMEDIA_TYPE_VIDEO, .id = AV_CODEC_ID_C93, .priv_data_size = sizeof(C93DecoderContext), .init = decode_init, .close = decode_end, .decode = decode_frame, .capabilities = AV_CODEC_CAP_DR1, .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE, };
193993.c
#include <stdio.h> void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } void shellSort(int A[], int n) { for (int gap = n/2; gap != 0; gap /= 2) { int i, temp = gap; for (i = 0; temp < n; ++i, ++temp) { if (A[i] > A[temp]) { swap(&A[i], &A[temp]); } } for (--i, --temp; i >= 0; --i, --temp) { if (A[i] > A[temp]) { swap(&A[i], &A[temp]); } } } } int main() { int n; printf("Enter how many numbers: "); scanf("%d", &n); int Arr[n]; printf("Enter %d numbers\n", n); for (int i = 0; i < n; ++i) { scanf("%d", &Arr[i]); } shellSort(Arr, n); printf("After Sort\n"); for (int i = 0; i < n; ++i) { printf("%d\t", Arr[i]); } printf("\n"); return 0; } /* Output: Enter how many numbers: 5 Enter 5 numbers 76 2 56 24 42 After Sort 2 24 42 56 76 */
492246.c
/* OpenGL loader generated by glad 0.1.35 on Thu Jan 20 11:57:47 2022. Language/Generator: C/C++ Specification: gl APIs: gl=3.3 Profile: core Extensions: Loader: True Local files: False Omit khrplatform: False Reproducible: False Commandline: --profile="core" --api="gl=3.3" --generator="c" --spec="gl" --extensions="" Online: https://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D3.3 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glad/glad.h> static void* get_proc(const char *namez); #if defined(_WIN32) || defined(__CYGWIN__) #ifndef _WINDOWS_ #undef APIENTRY #endif #include <windows.h> static HMODULE libGL; typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #ifdef _MSC_VER #ifdef __has_include #if __has_include(<winapifamily.h>) #define HAVE_WINAPIFAMILY 1 #endif #elif _MSC_VER >= 1700 && !_USING_V110_SDK71_ #define HAVE_WINAPIFAMILY 1 #endif #endif #ifdef HAVE_WINAPIFAMILY #include <winapifamily.h> #if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) #define IS_UWP 1 #endif #endif static int open_gl(void) { #ifndef IS_UWP libGL = LoadLibraryW(L"opengl32.dll"); if(libGL != NULL) { void (* tmp)(void); tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress"); gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp; return gladGetProcAddressPtr != NULL; } #endif return 0; } static void close_gl(void) { if(libGL != NULL) { FreeLibrary((HMODULE) libGL); libGL = NULL; } } #else #include <dlfcn.h> static void* libGL; #if !defined(__APPLE__) && !defined(__HAIKU__) typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #endif static int open_gl(void) { #ifdef __APPLE__ static const char *NAMES[] = { "../Frameworks/OpenGL.framework/OpenGL", "/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" }; #else static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; #endif unsigned int index = 0; for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); if(libGL != NULL) { #if defined(__APPLE__) || defined(__HAIKU__) return 1; #else gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, "glXGetProcAddressARB"); return gladGetProcAddressPtr != NULL; #endif } } return 0; } static void close_gl(void) { if(libGL != NULL) { dlclose(libGL); libGL = NULL; } } #endif static void* get_proc(const char *namez) { void* result = NULL; if(libGL == NULL) return NULL; #if !defined(__APPLE__) && !defined(__HAIKU__) if(gladGetProcAddressPtr != NULL) { result = gladGetProcAddressPtr(namez); } #endif if(result == NULL) { #if defined(_WIN32) || defined(__CYGWIN__) result = (void*)GetProcAddress((HMODULE) libGL, namez); #else result = dlsym(libGL, namez); #endif } return result; } int gladLoadGL(void) { int status = 0; if(open_gl()) { status = gladLoadGLLoader(&get_proc); close_gl(); } return status; } struct gladGLversionStruct GLVersion = { 0, 0 }; #if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) #define _GLAD_IS_SOME_NEW_VERSION 1 #endif static int max_loaded_major; static int max_loaded_minor; static const char *exts = NULL; static int num_exts_i = 0; static char **exts_i = NULL; static int get_exts(void) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif exts = (const char *)glGetString(GL_EXTENSIONS); #ifdef _GLAD_IS_SOME_NEW_VERSION } else { unsigned int index; num_exts_i = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); if (num_exts_i > 0) { exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i)); } if (exts_i == NULL) { return 0; } for(index = 0; index < (unsigned)num_exts_i; index++) { const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index); size_t len = strlen(gl_str_tmp); char *local_str = (char*)malloc((len+1) * sizeof(char)); if(local_str != NULL) { memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char)); } exts_i[index] = local_str; } } #endif return 1; } static void free_exts(void) { if (exts_i != NULL) { int index; for(index = 0; index < num_exts_i; index++) { free((char *)exts_i[index]); } free((void *)exts_i); exts_i = NULL; } } static int has_ext(const char *ext) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif const char *extensions; const char *loc; const char *terminator; extensions = exts; if(extensions == NULL || ext == NULL) { return 0; } while(1) { loc = strstr(extensions, ext); if(loc == NULL) { return 0; } terminator = loc + strlen(ext); if((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return 1; } extensions = terminator; } #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; if(exts_i == NULL) return 0; for(index = 0; index < num_exts_i; index++) { const char *e = exts_i[index]; if(exts_i[index] != NULL && strcmp(e, ext) == 0) { return 1; } } } #endif return 0; } int GLAD_GL_VERSION_1_0 = 0; int GLAD_GL_VERSION_1_1 = 0; int GLAD_GL_VERSION_1_2 = 0; int GLAD_GL_VERSION_1_3 = 0; int GLAD_GL_VERSION_1_4 = 0; int GLAD_GL_VERSION_1_5 = 0; int GLAD_GL_VERSION_2_0 = 0; int GLAD_GL_VERSION_2_1 = 0; int GLAD_GL_VERSION_3_0 = 0; int GLAD_GL_VERSION_3_1 = 0; int GLAD_GL_VERSION_3_2 = 0; int GLAD_GL_VERSION_3_3 = 0; PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL; PFNGLATTACHSHADERPROC glad_glAttachShader = NULL; PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL; PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL; PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL; PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL; PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL; PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL; PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL; PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL; PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL; PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL; PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL; PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL; PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL; PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL; PFNGLBLENDCOLORPROC glad_glBlendColor = NULL; PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL; PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL; PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL; PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL; PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL; PFNGLBUFFERDATAPROC glad_glBufferData = NULL; PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL; PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL; PFNGLCLAMPCOLORPROC glad_glClampColor = NULL; PFNGLCLEARPROC glad_glClear = NULL; PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL; PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL; PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL; PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL; PFNGLCLEARCOLORPROC glad_glClearColor = NULL; PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL; PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL; PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL; PFNGLCOLORMASKPROC glad_glColorMask = NULL; PFNGLCOLORMASKIPROC glad_glColorMaski = NULL; PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL; PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL; PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL; PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL; PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL; PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL; PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL; PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL; PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL; PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL; PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL; PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL; PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL; PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL; PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL; PFNGLCREATESHADERPROC glad_glCreateShader = NULL; PFNGLCULLFACEPROC glad_glCullFace = NULL; PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL; PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL; PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL; PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL; PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL; PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL; PFNGLDELETESHADERPROC glad_glDeleteShader = NULL; PFNGLDELETESYNCPROC glad_glDeleteSync = NULL; PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL; PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL; PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL; PFNGLDEPTHMASKPROC glad_glDepthMask = NULL; PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL; PFNGLDETACHSHADERPROC glad_glDetachShader = NULL; PFNGLDISABLEPROC glad_glDisable = NULL; PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL; PFNGLDISABLEIPROC glad_glDisablei = NULL; PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL; PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL; PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL; PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL; PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL; PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL; PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL; PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL; PFNGLENABLEPROC glad_glEnable = NULL; PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL; PFNGLENABLEIPROC glad_glEnablei = NULL; PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL; PFNGLENDQUERYPROC glad_glEndQuery = NULL; PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL; PFNGLFENCESYNCPROC glad_glFenceSync = NULL; PFNGLFINISHPROC glad_glFinish = NULL; PFNGLFLUSHPROC glad_glFlush = NULL; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL; PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL; PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL; PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL; PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL; PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL; PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL; PFNGLFRONTFACEPROC glad_glFrontFace = NULL; PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL; PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL; PFNGLGENQUERIESPROC glad_glGenQueries = NULL; PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL; PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL; PFNGLGENTEXTURESPROC glad_glGenTextures = NULL; PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL; PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL; PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL; PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL; PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL; PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL; PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL; PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL; PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL; PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL; PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL; PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL; PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL; PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL; PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL; PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL; PFNGLGETERRORPROC glad_glGetError = NULL; PFNGLGETFLOATVPROC glad_glGetFloatv = NULL; PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL; PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL; PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL; PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL; PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL; PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL; PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL; PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL; PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL; PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL; PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL; PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL; PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL; PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL; PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL; PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL; PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL; PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL; PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL; PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL; PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL; PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL; PFNGLGETSTRINGPROC glad_glGetString = NULL; PFNGLGETSTRINGIPROC glad_glGetStringi = NULL; PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL; PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL; PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL; PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL; PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL; PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL; PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL; PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL; PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL; PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL; PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL; PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL; PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL; PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL; PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL; PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL; PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL; PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL; PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL; PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL; PFNGLHINTPROC glad_glHint = NULL; PFNGLISBUFFERPROC glad_glIsBuffer = NULL; PFNGLISENABLEDPROC glad_glIsEnabled = NULL; PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL; PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL; PFNGLISPROGRAMPROC glad_glIsProgram = NULL; PFNGLISQUERYPROC glad_glIsQuery = NULL; PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL; PFNGLISSAMPLERPROC glad_glIsSampler = NULL; PFNGLISSHADERPROC glad_glIsShader = NULL; PFNGLISSYNCPROC glad_glIsSync = NULL; PFNGLISTEXTUREPROC glad_glIsTexture = NULL; PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL; PFNGLLINEWIDTHPROC glad_glLineWidth = NULL; PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL; PFNGLLOGICOPPROC glad_glLogicOp = NULL; PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL; PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL; PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL; PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL; PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL; PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL; PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL; PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL; PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL; PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL; PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL; PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL; PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL; PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL; PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL; PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL; PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL; PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL; PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL; PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL; PFNGLPOINTSIZEPROC glad_glPointSize = NULL; PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL; PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL; PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL; PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL; PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL; PFNGLREADBUFFERPROC glad_glReadBuffer = NULL; PFNGLREADPIXELSPROC glad_glReadPixels = NULL; PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL; PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL; PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL; PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL; PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL; PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL; PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL; PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL; PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL; PFNGLSCISSORPROC glad_glScissor = NULL; PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL; PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL; PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL; PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL; PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL; PFNGLSTENCILMASKPROC glad_glStencilMask = NULL; PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL; PFNGLSTENCILOPPROC glad_glStencilOp = NULL; PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL; PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL; PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL; PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL; PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL; PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL; PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL; PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL; PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL; PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL; PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL; PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL; PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL; PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL; PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL; PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL; PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL; PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL; PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL; PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL; PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL; PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL; PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL; PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL; PFNGLUNIFORM1FPROC glad_glUniform1f = NULL; PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL; PFNGLUNIFORM1IPROC glad_glUniform1i = NULL; PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL; PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL; PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL; PFNGLUNIFORM2FPROC glad_glUniform2f = NULL; PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL; PFNGLUNIFORM2IPROC glad_glUniform2i = NULL; PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL; PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL; PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL; PFNGLUNIFORM3FPROC glad_glUniform3f = NULL; PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL; PFNGLUNIFORM3IPROC glad_glUniform3i = NULL; PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL; PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL; PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL; PFNGLUNIFORM4FPROC glad_glUniform4f = NULL; PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL; PFNGLUNIFORM4IPROC glad_glUniform4i = NULL; PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL; PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL; PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL; PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL; PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL; PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL; PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL; PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL; PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL; PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL; PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL; PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL; PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL; PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL; PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL; PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL; PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL; PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL; PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL; PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL; PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL; PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL; PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL; PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL; PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL; PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL; PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL; PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL; PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL; PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL; PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL; PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL; PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL; PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL; PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL; PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL; PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL; PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL; PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL; PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL; PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL; PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL; PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL; PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL; PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL; PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL; PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL; PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL; PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL; PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL; PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL; PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL; PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL; PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL; PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL; PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL; PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL; PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL; PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL; PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL; PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL; PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL; PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL; PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL; PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL; PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL; PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL; PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL; PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL; PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL; PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL; PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL; PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL; PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL; PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL; PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL; PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL; PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL; PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL; PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL; PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL; PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL; PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL; PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL; PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL; PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL; PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL; PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL; PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL; PFNGLVIEWPORTPROC glad_glViewport = NULL; PFNGLWAITSYNCPROC glad_glWaitSync = NULL; static void load_GL_VERSION_1_0(GLADloadproc load) { if(!GLAD_GL_VERSION_1_0) return; glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); glad_glHint = (PFNGLHINTPROC)load("glHint"); glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); glad_glClear = (PFNGLCLEARPROC)load("glClear"); glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); } static void load_GL_VERSION_1_1(GLADloadproc load) { if(!GLAD_GL_VERSION_1_1) return; glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); } static void load_GL_VERSION_1_2(GLADloadproc load) { if(!GLAD_GL_VERSION_1_2) return; glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); } static void load_GL_VERSION_1_3(GLADloadproc load) { if(!GLAD_GL_VERSION_1_3) return; glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); } static void load_GL_VERSION_1_4(GLADloadproc load) { if(!GLAD_GL_VERSION_1_4) return; glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); } static void load_GL_VERSION_1_5(GLADloadproc load) { if(!GLAD_GL_VERSION_1_5) return; glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); } static void load_GL_VERSION_2_0(GLADloadproc load) { if(!GLAD_GL_VERSION_2_0) return; glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); } static void load_GL_VERSION_2_1(GLADloadproc load) { if(!GLAD_GL_VERSION_2_1) return; glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); } static void load_GL_VERSION_3_0(GLADloadproc load) { if(!GLAD_GL_VERSION_3_0) return; glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); } static void load_GL_VERSION_3_1(GLADloadproc load) { if(!GLAD_GL_VERSION_3_1) return; glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); } static void load_GL_VERSION_3_2(GLADloadproc load) { if(!GLAD_GL_VERSION_3_2) return; glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); } static void load_GL_VERSION_3_3(GLADloadproc load) { if(!GLAD_GL_VERSION_3_3) return; glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); } static int find_extensionsGL(void) { if (!get_exts()) return 0; (void)&has_ext; free_exts(); return 1; } static void find_coreGL(void) { /* Thank you @elmindreda * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 * https://github.com/glfw/glfw/blob/master/src/context.c#L36 */ int i, major, minor; const char* version; const char* prefixes[] = { "OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL }; version = (const char*) glGetString(GL_VERSION); if (!version) return; for (i = 0; prefixes[i]; i++) { const size_t length = strlen(prefixes[i]); if (strncmp(version, prefixes[i], length) == 0) { version += length; break; } } /* PR #18 */ #ifdef _MSC_VER sscanf_s(version, "%d.%d", &major, &minor); #else sscanf(version, "%d.%d", &major, &minor); #endif GLVersion.major = major; GLVersion.minor = minor; max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; if (GLVersion.major > 3 || (GLVersion.major >= 3 && GLVersion.minor >= 3)) { max_loaded_major = 3; max_loaded_minor = 3; } } int gladLoadGLLoader(GLADloadproc load) { GLVersion.major = 0; GLVersion.minor = 0; glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); if(glGetString == NULL) return 0; if(glGetString(GL_VERSION) == NULL) return 0; find_coreGL(); load_GL_VERSION_1_0(load); load_GL_VERSION_1_1(load); load_GL_VERSION_1_2(load); load_GL_VERSION_1_3(load); load_GL_VERSION_1_4(load); load_GL_VERSION_1_5(load); load_GL_VERSION_2_0(load); load_GL_VERSION_2_1(load); load_GL_VERSION_3_0(load); load_GL_VERSION_3_1(load); load_GL_VERSION_3_2(load); load_GL_VERSION_3_3(load); if (!find_extensionsGL()) return 0; return GLVersion.major != 0 || GLVersion.minor != 0; }
920178.c
#include "pscmn.h" #include "imgdef.h" void psicmn ( int *hv, int *iret ) /************************************************************************ * psicmn * * * * This subroutine sets some information in the image common header. * * * * psicmn ( hv, iret ) * * * * Input parameters: * * *hv int Pointer to first header variable* * * * Output parameters: * * *iret int Return code * * 0 = normal return * ** * * Log: * * S. Jacobs/NCEP 1/97 Copied from PSICMN * * S. Jacobs/NCEP 2/97 Changed variable names * * D.W.Plummer/NCEP 3/03 Changes for expanded common block * * T. Piper/SAIC 09/07 Replaced strncpy with cst_ncpy. * ***********************************************************************/ { int ier; char *cptr; /*---------------------------------------------------------------------*/ *iret = G_NORMAL; /* * Set variables - order is important here. * Follow the order in the imgdef.h file. */ imftyp = *hv++ ; imbank = *hv++ ; imdoff = *hv++ ; imldat = *hv++ ; imnpix = *hv++ ; imnlin = *hv++ ; imdpth = *hv++ ; rmxres = *(float *) hv++ ; rmyres = *(float *) hv++ ; imleft = *hv++ ; imbot = *hv++ ; imrght = *hv++ ; imtop = *hv++ ; rmxysc = *(float *) hv++ ; imbswp = *hv++ ; imnchl = *hv++ ; imprsz = *hv++ ; imdcsz = *hv++ ; imclsz = *hv++ ; imlvsz = *hv++ ; imvald = *hv++ ; imrdfl = *hv++ ; immnpx = *hv++ ; immxpx = *hv++ ; imsorc = *hv++ ; imtype = *hv++ ; imradf = *hv++ ; rmbelv = *(float *) hv++ ; immode = *hv++ ; imdate = *hv++ ; imtime = *hv++ ; cptr = (char *)hv; cst_ncpy ( cmsorc, cptr, 20, &ier ); cptr += 20; cst_ncpy ( cmtype, cptr, 8, &ier ); cptr += 8; cst_ncpy ( cmstyp, cptr, 4, &ier ); cptr += 4; cst_ncpy ( cmcalb, cptr, 4, &ier ); cptr += 4; }
253738.c
/****************************************************************************** * @file read_data_polling.c * @author Sensors Software Solution Team * @brief This file show the simplest way to get data from sensor. * ****************************************************************************** * @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 * ****************************************************************************** */ /* * This example was developed using the following STMicroelectronics * evaluation boards: * * - STEVAL_MKI109V3 + STEVAL-MKI173V1 * - NUCLEO_F411RE + STEVAL-MKI173V1 * - DISCOVERY_SPC584B + STEVAL-MKI173V1 * * Used interfaces: * * STEVAL_MKI109V3 - Host side: USB (Virtual COM) * - Sensor side: SPI(Default) / I2C(supported) * * NUCLEO_STM32F411RE - Host side: UART(COM) to USB bridge * - Sensor side: I2C(Default) / SPI(supported) * * DISCOVERY_SPC584B - Host side: UART(COM) to USB bridge * - Sensor side: I2C(Default) / SPI(supported) * * If you need to run this example on a different hardware platform a * modification of the functions: `platform_write`, `platform_read`, * `tx_com` and 'platform_init' is required. * */ /* STMicroelectronics evaluation boards definition * * Please uncomment ONLY the evaluation boards in use. * If a different hardware is used please comment all * following target board and redefine yours. */ //#define STEVAL_MKI109V3 /* little endian */ //#define NUCLEO_F411RE /* little endian */ //#define SPC584B_DIS /* big endian */ /* ATTENTION: By default the driver is little endian. If you need switch * to big endian please see "Endianness definitions" in the * header file of the driver (_reg.h). */ #if defined(STEVAL_MKI109V3) /* MKI109V3: Define communication interface */ #define SENSOR_BUS hspi2 /* MKI109V3: Vdd and Vddio power supply values */ #define PWM_3V3 915 #elif defined(NUCLEO_F411RE) /* NUCLEO_F411RE: Define communication interface */ #define SENSOR_BUS hi2c1 #elif defined(SPC584B_DIS) /* DISCOVERY_SPC584B: Define communication interface */ #define SENSOR_BUS I2CD1 #endif /* Includes ------------------------------------------------------------------*/ #include "lsm303ah_reg.h" #include <string.h> #include <stdio.h> #if defined(NUCLEO_F411RE) #include "stm32f4xx_hal.h" #include "usart.h" #include "gpio.h" #include "i2c.h" #elif defined(STEVAL_MKI109V3) #include "stm32f4xx_hal.h" #include "usbd_cdc_if.h" #include "gpio.h" #include "spi.h" #include "tim.h" #elif defined(SPC584B_DIS) #include "components.h" #endif typedef struct { void *hbus; uint8_t i2c_address; GPIO_TypeDef *cs_port; uint16_t cs_pin; } sensbus_t; /* Private macro -------------------------------------------------------------*/ #define BOOT_TIME 20 //ms #define TX_BUF_DIM 1000 /* Private variables ---------------------------------------------------------*/ #if defined(STEVAL_MKI109V3) static sensbus_t xl_bus = {&SENSOR_BUS, 0, CS_up_GPIO_Port, CS_up_Pin }; static sensbus_t mag_bus = {&SENSOR_BUS, 0, CS_A_up_GPIO_Port, CS_A_up_Pin }; #elif defined(NUCLEO_F411RE) || defined(SPC584B_DIS) static sensbus_t xl_bus = {&SENSOR_BUS, LSM303AH_I2C_ADD_XL, 0, 0 }; static sensbus_t mag_bus = {&SENSOR_BUS, LSM303AH_I2C_ADD_MG, 0, 0 }; #endif static int16_t data_raw_acceleration[3]; static int16_t data_raw_magnetic[3]; static uint8_t tx_buffer[TX_BUF_DIM]; static float acceleration_mg[3]; static float magnetic_mG[3]; static uint8_t whoamI, rst; /* Extern variables ----------------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* * WARNING: * Functions declare in this section are defined at the end of this file * and are strictly related to the hardware platform used. * */ static int32_t platform_write(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len); static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len); static void tx_com(uint8_t *tx_buffer, uint16_t len); static void platform_delay(uint32_t ms); static void platform_init(void); /* Main Example --------------------------------------------------------------*/ void lsm303ah_read_data_polling(void) { stmdev_ctx_t dev_ctx_xl; stmdev_ctx_t dev_ctx_mg; /* Initialize mems driver interface */ dev_ctx_xl.write_reg = platform_write; dev_ctx_xl.read_reg = platform_read; dev_ctx_xl.handle = (void *)&xl_bus; dev_ctx_mg.write_reg = platform_write; dev_ctx_mg.read_reg = platform_read; dev_ctx_mg.handle = (void *)&mag_bus; /* Wait boot time and initialize platform specific hardware */ platform_init(); /* Wait sensor boot time */ platform_delay(BOOT_TIME); /* Check device ID */ whoamI = 0; lsm303ah_xl_device_id_get(&dev_ctx_xl, &whoamI); if ( whoamI != LSM303AH_ID_XL ) while (1); /*manage here device not found */ whoamI = 0; lsm303ah_mg_device_id_get(&dev_ctx_mg, &whoamI); if ( whoamI != LSM303AH_ID_MG ) while (1); /*manage here device not found */ /* Restore default configuration */ lsm303ah_xl_reset_set(&dev_ctx_xl, PROPERTY_ENABLE); do { lsm303ah_xl_reset_get(&dev_ctx_xl, &rst); } while (rst); lsm303ah_mg_reset_set(&dev_ctx_mg, PROPERTY_ENABLE); do { lsm303ah_mg_reset_get(&dev_ctx_mg, &rst); } while (rst); /* Enable Block Data Update */ lsm303ah_xl_block_data_update_set(&dev_ctx_xl, PROPERTY_ENABLE); lsm303ah_mg_block_data_update_set(&dev_ctx_mg, PROPERTY_ENABLE); /* Set full scale */ lsm303ah_xl_full_scale_set(&dev_ctx_xl, LSM303AH_XL_2g); /* Configure filtering chain */ /* Accelerometer - High Pass / Slope path */ //lsm303ah_xl_hp_path_set(&dev_ctx_xl, LSM303AH_HP_ON_OUTPUTS); /* Set / Reset magnetic sensor mode */ lsm303ah_mg_set_rst_mode_set(&dev_ctx_mg, LSM303AH_MG_SENS_OFF_CANC_EVERY_ODR); /* Enable temperature compensation on mag sensor */ lsm303ah_mg_offset_temp_comp_set(&dev_ctx_mg, PROPERTY_ENABLE); /* Set Output Data Rate */ lsm303ah_xl_data_rate_set(&dev_ctx_xl, LSM303AH_XL_ODR_100Hz_LP); lsm303ah_mg_data_rate_set(&dev_ctx_mg, LSM303AH_MG_ODR_10Hz); /* Set magnetometer in continuous mode */ lsm303ah_mg_operating_mode_set(&dev_ctx_mg, LSM303AH_MG_CONTINUOUS_MODE); /* Read samples in polling mode (no int) */ while (1) { /* Read output only if new value is available */ lsm303ah_reg_t reg; lsm303ah_xl_status_reg_get(&dev_ctx_xl, &reg.status_a); if (reg.status_a.drdy) { /* Read acceleration data */ memset(data_raw_acceleration, 0x00, 3 * sizeof(int16_t)); lsm303ah_acceleration_raw_get(&dev_ctx_xl, data_raw_acceleration); acceleration_mg[0] = lsm303ah_from_fs2g_to_mg( data_raw_acceleration[0]); acceleration_mg[1] = lsm303ah_from_fs2g_to_mg( data_raw_acceleration[1]); acceleration_mg[2] = lsm303ah_from_fs2g_to_mg( data_raw_acceleration[2]); sprintf((char *)tx_buffer, "Acceleration [mg]:%4.2f\t%4.2f\t%4.2f\r\n", acceleration_mg[0], acceleration_mg[1], acceleration_mg[2]); tx_com( tx_buffer, strlen( (char const *)tx_buffer ) ); } lsm303ah_mg_status_get(&dev_ctx_mg, &reg.status_reg_m); if (reg.status_reg_m.zyxda) { /* Read magnetic field data */ memset(data_raw_magnetic, 0x00, 3 * sizeof(int16_t)); lsm303ah_magnetic_raw_get(&dev_ctx_mg, data_raw_magnetic); magnetic_mG[0] = lsm303ah_from_lsb_to_mgauss( data_raw_magnetic[0]); magnetic_mG[1] = lsm303ah_from_lsb_to_mgauss( data_raw_magnetic[1]); magnetic_mG[2] = lsm303ah_from_lsb_to_mgauss( data_raw_magnetic[2]); sprintf((char *)tx_buffer, "Magnetic field [mG]:%4.2f\t%4.2f\t%4.2f\r\n", magnetic_mG[0], magnetic_mG[1], magnetic_mG[2]); tx_com( tx_buffer, strlen( (char const *)tx_buffer ) ); } } } /* * @brief Write generic device register (platform dependent) * * @param handle customizable argument. In this examples is used in * order to select the correct sensor bus handler. * @param reg register to write * @param bufp pointer to data to write in register reg * @param len number of consecutive register to write * */ static int32_t platform_write(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len) { sensbus_t *sensbus = (sensbus_t *)handle; #if defined(NUCLEO_F411RE) /* Write multiple command */ reg |= 0x80; HAL_I2C_Mem_Write(sensbus->hbus, sensbus->i2c_address, reg, I2C_MEMADD_SIZE_8BIT, bufp, len, 1000); #elif defined(STEVAL_MKI109V3) /* Write multiple command */ reg |= 0x40; HAL_GPIO_WritePin(sensbus->cs_port, sensbus->cs_pin, GPIO_PIN_RESET); HAL_SPI_Transmit(sensbus->hbus, &reg, 1, 1000); HAL_SPI_Transmit(sensbus->hbus, bufp, len, 1000); HAL_GPIO_WritePin(sensbus->cs_port, sensbus->cs_pin, GPIO_PIN_SET); #elif defined(SPC584B_DIS) reg |= 0x80; i2c_lld_write(sensbus->hbus, sensbus->i2c_address & 0xFE, reg, bufp, len); #endif return 0; } /* * @brief Read generic device register (platform dependent) * * @param handle customizable argument. In this examples is used in * order to select the correct sensor bus handler. * @param reg register to read * @param bufp pointer to buffer that store the data read * @param len number of consecutive register to read * */ static int32_t platform_read(void *handle, uint8_t reg, uint8_t *bufp, uint16_t len) { sensbus_t *sensbus = (sensbus_t *)handle; #if defined(NUCLEO_F411RE) /* Read multiple command */ reg |= 0x80; HAL_I2C_Mem_Read(sensbus->hbus, sensbus->i2c_address, reg, I2C_MEMADD_SIZE_8BIT, bufp, len, 1000); #elif defined(STEVAL_MKI109V3) /* Read multiple command */ reg |= 0xC0; HAL_GPIO_WritePin(sensbus->cs_port, sensbus->cs_pin, GPIO_PIN_RESET); HAL_SPI_Transmit(sensbus->hbus, &reg, 1, 1000); HAL_SPI_Receive(sensbus->hbus, bufp, len, 1000); HAL_GPIO_WritePin(sensbus->cs_port, sensbus->cs_pin, GPIO_PIN_SET); #elif defined(SPC584B_DIS) /* Read multiple command */ reg |= 0x80; i2c_lld_read(sensbus->hbus, sensbus->i2c_address & 0xFE, reg, bufp, len); #endif return 0; } /* * @brief Write generic device register (platform dependent) * * @param tx_buffer buffer to transmit * @param len number of byte to send * */ static void tx_com(uint8_t *tx_buffer, uint16_t len) { #if defined(NUCLEO_F411RE) HAL_UART_Transmit(&huart2, tx_buffer, len, 1000); #elif defined(STEVAL_MKI109V3) CDC_Transmit_FS(tx_buffer, len); #elif defined(SPC584B_DIS) sd_lld_write(&SD2, tx_buffer, len); #endif } /* * @brief platform specific delay (platform dependent) * * @param ms delay in ms * */ static void platform_delay(uint32_t ms) { #if defined(NUCLEO_F411RE) | defined(STEVAL_MKI109V3) HAL_Delay(ms); #elif defined(SPC584B_DIS) osalThreadDelayMilliseconds(ms); #endif } /* * @brief platform specific initialization (platform dependent) */ static void platform_init(void) { #if defined(STEVAL_MKI109V3) TIM3->CCR1 = PWM_3V3; TIM3->CCR2 = PWM_3V3; HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1); HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_2); HAL_Delay(1000); #endif }
84801.c
/* picoJava specific support for 32-bit ELF Copyright (C) 1999-2018 Free Software Foundation, Inc. Contributed by Steve Chamberlan of Transmeta ([email protected]). This file is part of BFD, the Binary File Descriptor library. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ #include "sysdep.h" #include "bfd.h" #include "bfdlink.h" #include "libbfd.h" #include "elf-bfd.h" #include "elf/pj.h" /* This function is used for normal relocs. This is like the COFF function, and is almost certainly incorrect for other ELF targets. */ static bfd_reloc_status_type pj_elf_reloc (bfd *abfd, arelent *reloc_entry, asymbol *symbol_in, void * data, asection *input_section, bfd *output_bfd, char **error_message ATTRIBUTE_UNUSED) { unsigned long insn; bfd_vma sym_value; enum elf_pj_reloc_type r_type; bfd_vma addr = reloc_entry->address; bfd_byte *hit_data = addr + (bfd_byte *) data; r_type = (enum elf_pj_reloc_type) reloc_entry->howto->type; if (output_bfd != NULL) { /* Partial linking--do nothing. */ reloc_entry->address += input_section->output_offset; return bfd_reloc_ok; } if (symbol_in != NULL && bfd_is_und_section (symbol_in->section)) return bfd_reloc_undefined; if (bfd_is_com_section (symbol_in->section)) sym_value = 0; else sym_value = (symbol_in->value + symbol_in->section->output_section->vma + symbol_in->section->output_offset); switch (r_type) { case R_PJ_DATA_DIR32: insn = bfd_get_32 (abfd, hit_data); insn += sym_value + reloc_entry->addend; bfd_put_32 (abfd, (bfd_vma) insn, hit_data); break; /* Relocations in code are always bigendian, no matter what the data endianness is. */ case R_PJ_CODE_DIR32: insn = bfd_getb32 (hit_data); insn += sym_value + reloc_entry->addend; bfd_putb32 ((bfd_vma) insn, hit_data); break; case R_PJ_CODE_REL16: insn = bfd_getb16 (hit_data); insn += sym_value + reloc_entry->addend - (input_section->output_section->vma + input_section->output_offset); bfd_putb16 ((bfd_vma) insn, hit_data); break; case R_PJ_CODE_LO16: insn = bfd_getb16 (hit_data); insn += sym_value + reloc_entry->addend; bfd_putb16 ((bfd_vma) insn, hit_data); break; case R_PJ_CODE_HI16: insn = bfd_getb16 (hit_data); insn += (sym_value + reloc_entry->addend) >> 16; bfd_putb16 ((bfd_vma) insn, hit_data); break; default: abort (); break; } return bfd_reloc_ok; } static reloc_howto_type pj_elf_howto_table[] = { /* No relocation. */ HOWTO (R_PJ_NONE, /* type */ 0, /* rightshift */ 3, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_NONE", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* 32 bit absolute relocation. Setting partial_inplace to TRUE and src_mask to a non-zero value is similar to the COFF toolchain. */ HOWTO (R_PJ_DATA_DIR32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_DIR32", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ /* 32 bit PC relative relocation. */ HOWTO (R_PJ_CODE_REL32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_REL32", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0xffffffff, /* dst_mask */ TRUE), /* pcrel_offset */ /* 16 bit PC relative relocation. */ HOWTO (R_PJ_CODE_REL16, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ TRUE, /* pc_relative */ 0, /* bitpos */ complain_overflow_signed, /* complain_on_overf6w */ pj_elf_reloc, /* special_function */ "R_PJ_REL16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ TRUE), /* pcrel_offset */ EMPTY_HOWTO (4), EMPTY_HOWTO (5), HOWTO (R_PJ_CODE_DIR32, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 32, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_bitfield, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_CODE_DIR32", /* name */ TRUE, /* partial_inplace */ 0xffffffff, /* src_mask */ 0xffffffff, /* dst_mask */ FALSE), /* pcrel_offset */ EMPTY_HOWTO (7), EMPTY_HOWTO (8), EMPTY_HOWTO (9), EMPTY_HOWTO (10), EMPTY_HOWTO (11), EMPTY_HOWTO (12), HOWTO (R_PJ_CODE_LO16, /* type */ 0, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_unsigned, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_LO16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ TRUE), /* pcrel_offset */ HOWTO (R_PJ_CODE_HI16, /* type */ 16, /* rightshift */ 1, /* size (0 = byte, 1 = short, 2 = long) */ 16, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_unsigned, /* complain_on_overflow */ pj_elf_reloc, /* special_function */ "R_PJ_HI16", /* name */ FALSE, /* partial_inplace */ 0xffff, /* src_mask */ 0xffff, /* dst_mask */ TRUE), /* pcrel_offset */ /* GNU extension to record C++ vtable hierarchy. */ HOWTO (R_PJ_GNU_VTINHERIT, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ NULL, /* special_function */ "R_PJ_GNU_VTINHERIT", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ /* GNU extension to record C++ vtable member usage. */ HOWTO (R_PJ_GNU_VTENTRY, /* type */ 0, /* rightshift */ 2, /* size (0 = byte, 1 = short, 2 = long) */ 0, /* bitsize */ FALSE, /* pc_relative */ 0, /* bitpos */ complain_overflow_dont, /* complain_on_overflow */ _bfd_elf_rel_vtable_reloc_fn, /* special_function */ "R_PJ_GNU_VTENTRY", /* name */ FALSE, /* partial_inplace */ 0, /* src_mask */ 0, /* dst_mask */ FALSE), /* pcrel_offset */ }; /* This structure is used to map BFD reloc codes to PJ ELF relocs. */ struct elf_reloc_map { bfd_reloc_code_real_type bfd_reloc_val; unsigned char elf_reloc_val; }; /* An array mapping BFD reloc codes to PJ ELF relocs. */ static const struct elf_reloc_map pj_reloc_map[] = { { BFD_RELOC_NONE, R_PJ_NONE }, { BFD_RELOC_32, R_PJ_DATA_DIR32 }, { BFD_RELOC_PJ_CODE_DIR16, R_PJ_CODE_DIR16 }, { BFD_RELOC_PJ_CODE_DIR32, R_PJ_CODE_DIR32 }, { BFD_RELOC_PJ_CODE_LO16, R_PJ_CODE_LO16 }, { BFD_RELOC_PJ_CODE_HI16, R_PJ_CODE_HI16 }, { BFD_RELOC_PJ_CODE_REL32, R_PJ_CODE_REL32 }, { BFD_RELOC_PJ_CODE_REL16, R_PJ_CODE_REL16 }, { BFD_RELOC_VTABLE_INHERIT, R_PJ_GNU_VTINHERIT }, { BFD_RELOC_VTABLE_ENTRY, R_PJ_GNU_VTENTRY }, }; /* Given a BFD reloc code, return the howto structure for the corresponding PJ ELf reloc. */ static reloc_howto_type * pj_elf_reloc_type_lookup (bfd *abfd ATTRIBUTE_UNUSED, bfd_reloc_code_real_type code) { unsigned int i; for (i = 0; i < sizeof (pj_reloc_map) / sizeof (struct elf_reloc_map); i++) if (pj_reloc_map[i].bfd_reloc_val == code) return & pj_elf_howto_table[(int) pj_reloc_map[i].elf_reloc_val]; return NULL; } static reloc_howto_type * pj_elf_reloc_name_lookup (bfd *abfd ATTRIBUTE_UNUSED, const char *r_name) { unsigned int i; for (i = 0; i < sizeof (pj_elf_howto_table) / sizeof (pj_elf_howto_table[0]); i++) if (pj_elf_howto_table[i].name != NULL && strcasecmp (pj_elf_howto_table[i].name, r_name) == 0) return &pj_elf_howto_table[i]; return NULL; } /* Given an ELF reloc, fill in the howto field of a relent. */ static void pj_elf_info_to_howto (bfd *abfd ATTRIBUTE_UNUSED, arelent *cache_ptr, Elf_Internal_Rela *dst) { unsigned int r; r = ELF32_R_TYPE (dst->r_info); if (r >= R_PJ_max) { /* xgettext:c-format */ _bfd_error_handler (_("%B: unrecognised PicoJava reloc number: %d"), abfd, r); bfd_set_error (bfd_error_bad_value); r = R_PJ_NONE; } cache_ptr->howto = &pj_elf_howto_table[r]; } /* Take this moment to fill in the special picoJava bits in the e_flags field. */ static void pj_elf_final_write_processing (bfd *abfd, bfd_boolean linker ATTRIBUTE_UNUSED) { elf_elfheader (abfd)->e_flags |= EF_PICOJAVA_ARCH; elf_elfheader (abfd)->e_flags |= EF_PICOJAVA_GNUCALLS; } #define TARGET_BIG_SYM pj_elf32_vec #define TARGET_BIG_NAME "elf32-pj" #define TARGET_LITTLE_SYM pj_elf32_le_vec #define TARGET_LITTLE_NAME "elf32-pjl" #define ELF_ARCH bfd_arch_pj #define ELF_MACHINE_CODE EM_PJ #define ELF_MACHINE_ALT1 EM_PJ_OLD #define ELF_MAXPAGESIZE 0x1000 #define bfd_elf32_bfd_get_relocated_section_contents \ bfd_generic_get_relocated_section_contents #define bfd_elf32_bfd_reloc_type_lookup pj_elf_reloc_type_lookup #define bfd_elf32_bfd_reloc_name_lookup pj_elf_reloc_name_lookup #define elf_backend_final_write_processing pj_elf_final_write_processing #define elf_info_to_howto pj_elf_info_to_howto #include "elf32-target.h"
828285.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: Zeev Suraski <[email protected]> | | Jouni Ahto <[email protected]> | | Yasuo Ohgaki <[email protected]> | | Youichi Iwakiri <[email protected]> (pg_copy_*) | | Chris Kings-Lynne <[email protected]> (v3 protocol) | +----------------------------------------------------------------------+ */ /* $Id$ */ #include <stdlib.h> #define PHP_PGSQL_PRIVATE 1 #ifdef HAVE_CONFIG_H #include "config.h" #endif #define SMART_STR_PREALLOC 512 #include "php.h" #include "php_ini.h" #include "ext/standard/php_standard.h" #include "zend_smart_str.h" #include "ext/pcre/php_pcre.h" #ifdef PHP_WIN32 # include "win32/time.h" #endif #undef PACKAGE_BUGREPORT #undef PACKAGE_NAME #undef PACKAGE_STRING #undef PACKAGE_TARNAME #undef PACKAGE_VERSION #include "php_pgsql.h" #include "php_globals.h" #include "zend_exceptions.h" #if HAVE_PGSQL #ifndef InvalidOid #define InvalidOid ((Oid) 0) #endif #define PGSQL_ASSOC 1<<0 #define PGSQL_NUM 1<<1 #define PGSQL_BOTH (PGSQL_ASSOC|PGSQL_NUM) #define PGSQL_NOTICE_LAST 1 /* Get the last notice */ #define PGSQL_NOTICE_ALL 2 /* Get all notices */ #define PGSQL_NOTICE_CLEAR 3 /* Remove notices */ #define PGSQL_STATUS_LONG 1 #define PGSQL_STATUS_STRING 2 #define PGSQL_MAX_LENGTH_OF_LONG 30 #define PGSQL_MAX_LENGTH_OF_DOUBLE 60 #if ZEND_LONG_MAX < UINT_MAX #define PGSQL_RETURN_OID(oid) do { \ if (oid > ZEND_LONG_MAX) { \ smart_str s = {0}; \ smart_str_append_unsigned(&s, oid); \ smart_str_0(&s); \ RETURN_NEW_STR(s.s); \ } \ RETURN_LONG((zend_long)oid); \ } while(0) #else #define PGSQL_RETURN_OID(oid) RETURN_LONG((zend_long)oid) #endif #if HAVE_PQSETNONBLOCKING #define PQ_SETNONBLOCKING(pg_link, flag) PQsetnonblocking(pg_link, flag) #else #define PQ_SETNONBLOCKING(pg_link, flag) 0 #endif #define CHECK_DEFAULT_LINK(x) if ((x) == NULL) { php_error_docref(NULL, E_WARNING, "No PostgreSQL link opened yet"); } #define FETCH_DEFAULT_LINK() PGG(default_link) #ifndef HAVE_PQFREEMEM #define PQfreemem free #endif ZEND_DECLARE_MODULE_GLOBALS(pgsql) static PHP_GINIT_FUNCTION(pgsql); /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connect, 0, 0, 1) ZEND_ARG_INFO(0, connection_string) ZEND_ARG_INFO(0, connect_type) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, tty) ZEND_ARG_INFO(0, database) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_pconnect, 0, 0, 1) ZEND_ARG_INFO(0, connection_string) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, tty) ZEND_ARG_INFO(0, database) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connect_poll, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() #if HAVE_PQPARAMETERSTATUS ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_parameter_status, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, param_name) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_close, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_dbname, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_error, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_options, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_port, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_tty, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_host, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_version, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_ping, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_query, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, query) ZEND_END_ARG_INFO() #if HAVE_PQEXECPARAMS ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_query_params, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, query) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() #endif #if HAVE_PQPREPARE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_prepare, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, stmtname) ZEND_ARG_INFO(0, query) ZEND_END_ARG_INFO() #endif #if HAVE_PQEXECPREPARED ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_execute, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, stmtname) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_num_rows, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_num_fields, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() #if HAVE_PQCMDTUPLES ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_affected_rows, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_notice, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, option) ZEND_END_ARG_INFO() #ifdef HAVE_PQFTABLE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_table, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_number) ZEND_ARG_INFO(0, oid_only) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_name, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_size, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_type, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_type_oid, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_num, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, field_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_result, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row_number) ZEND_ARG_INFO(0, field_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_row, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_ARG_INFO(0, result_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_assoc, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_array, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_ARG_INFO(0, result_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_object, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_ARG_INFO(0, class_name) ZEND_ARG_INFO(0, l) ZEND_ARG_INFO(0, ctor_params) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_all, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, result_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_fetch_all_columns, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, column_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_seek, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, offset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_prtlen, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_ARG_INFO(0, field_name_or_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_field_is_null, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, row) ZEND_ARG_INFO(0, field_name_or_number) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_free_result, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_last_oid, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_trace, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_untrace, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_create, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, large_object_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_unlink, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, large_object_oid) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_open, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, large_object_oid) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_close, 0, 0, 1) ZEND_ARG_INFO(0, large_object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_read, 0, 0, 1) ZEND_ARG_INFO(0, large_object) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_write, 0, 0, 2) ZEND_ARG_INFO(0, large_object) ZEND_ARG_INFO(0, buf) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_read_all, 0, 0, 1) ZEND_ARG_INFO(0, large_object) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_import, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, large_object_oid) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_export, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, objoid) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_seek, 0, 0, 2) ZEND_ARG_INFO(0, large_object) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_tell, 0, 0, 1) ZEND_ARG_INFO(0, large_object) ZEND_END_ARG_INFO() #if HAVE_PG_LO_TRUNCATE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_lo_truncate, 0, 0, 1) ZEND_ARG_INFO(0, large_object) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() #endif #if HAVE_PQSETERRORVERBOSITY ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_set_error_verbosity, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, verbosity) ZEND_END_ARG_INFO() #endif #if HAVE_PQCLIENTENCODING ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_set_client_encoding, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, encoding) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_client_encoding, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_end_copy, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_put_line, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, query) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_copy_to, 0, 0, 2) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, table_name) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, null_as) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_copy_from, 0, 0, 3) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, table_name) ZEND_ARG_INFO(0, rows) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, null_as) ZEND_END_ARG_INFO() #if HAVE_PQESCAPE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_string, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_bytea, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_unescape_bytea, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() #endif #if HAVE_PQESCAPE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_literal, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_escape_identifier, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_error, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_END_ARG_INFO() #if HAVE_PQRESULTERRORFIELD ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_error_field, 0, 0, 2) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, fieldcode) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_status, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() #if HAVE_PGTRANSACTIONSTATUS ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_transaction_status, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_reset, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_cancel_query, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_connection_busy, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_query, 0, 0, 2) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, query) ZEND_END_ARG_INFO() #if HAVE_PQSENDQUERYPARAMS ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_query_params, 0, 0, 3) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, query) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() #endif #if HAVE_PQSENDPREPARE ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_prepare, 0, 0, 3) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, stmtname) ZEND_ARG_INFO(0, query) ZEND_END_ARG_INFO() #endif #if HAVE_PQSENDQUERYPREPARED ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_send_execute, 0, 0, 3) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, stmtname) ZEND_ARG_INFO(0, params) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_result, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_result_status, 0, 0, 1) ZEND_ARG_INFO(0, result) ZEND_ARG_INFO(0, result_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_notify, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_ARG_INFO(0, e) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_get_pid, 0, 0, 0) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_socket, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_consume_input, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_flush, 0, 0, 1) ZEND_ARG_INFO(0, connection) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_meta_data, 0, 0, 2) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_convert, 0, 0, 3) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, values) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_insert, 0, 0, 3) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, values) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_update, 0, 0, 4) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, ids) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_delete, 0, 0, 3) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, ids) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_pg_select, 0, 0, 3) ZEND_ARG_INFO(0, db) ZEND_ARG_INFO(0, table) ZEND_ARG_INFO(0, ids) ZEND_ARG_INFO(0, options) ZEND_ARG_INFO(0, result_type) ZEND_END_ARG_INFO() /* }}} */ /* {{{ pgsql_functions[] */ static const zend_function_entry pgsql_functions[] = { /* connection functions */ PHP_FE(pg_connect, arginfo_pg_connect) PHP_FE(pg_pconnect, arginfo_pg_pconnect) PHP_FE(pg_connect_poll, arginfo_pg_connect_poll) PHP_FE(pg_close, arginfo_pg_close) PHP_FE(pg_connection_status, arginfo_pg_connection_status) PHP_FE(pg_connection_busy, arginfo_pg_connection_busy) PHP_FE(pg_connection_reset, arginfo_pg_connection_reset) PHP_FE(pg_host, arginfo_pg_host) PHP_FE(pg_dbname, arginfo_pg_dbname) PHP_FE(pg_port, arginfo_pg_port) PHP_FE(pg_tty, arginfo_pg_tty) PHP_FE(pg_options, arginfo_pg_options) PHP_FE(pg_version, arginfo_pg_version) PHP_FE(pg_ping, arginfo_pg_ping) #if HAVE_PQPARAMETERSTATUS PHP_FE(pg_parameter_status, arginfo_pg_parameter_status) #endif #if HAVE_PGTRANSACTIONSTATUS PHP_FE(pg_transaction_status, arginfo_pg_transaction_status) #endif /* query functions */ PHP_FE(pg_query, arginfo_pg_query) #if HAVE_PQEXECPARAMS PHP_FE(pg_query_params, arginfo_pg_query_params) #endif #if HAVE_PQPREPARE PHP_FE(pg_prepare, arginfo_pg_prepare) #endif #if HAVE_PQEXECPREPARED PHP_FE(pg_execute, arginfo_pg_execute) #endif PHP_FE(pg_send_query, arginfo_pg_send_query) #if HAVE_PQSENDQUERYPARAMS PHP_FE(pg_send_query_params, arginfo_pg_send_query_params) #endif #if HAVE_PQSENDPREPARE PHP_FE(pg_send_prepare, arginfo_pg_send_prepare) #endif #if HAVE_PQSENDQUERYPREPARED PHP_FE(pg_send_execute, arginfo_pg_send_execute) #endif PHP_FE(pg_cancel_query, arginfo_pg_cancel_query) /* result functions */ PHP_FE(pg_fetch_result, arginfo_pg_fetch_result) PHP_FE(pg_fetch_row, arginfo_pg_fetch_row) PHP_FE(pg_fetch_assoc, arginfo_pg_fetch_assoc) PHP_FE(pg_fetch_array, arginfo_pg_fetch_array) PHP_FE(pg_fetch_object, arginfo_pg_fetch_object) PHP_FE(pg_fetch_all, arginfo_pg_fetch_all) PHP_FE(pg_fetch_all_columns, arginfo_pg_fetch_all_columns) #if HAVE_PQCMDTUPLES PHP_FE(pg_affected_rows,arginfo_pg_affected_rows) #endif PHP_FE(pg_get_result, arginfo_pg_get_result) PHP_FE(pg_result_seek, arginfo_pg_result_seek) PHP_FE(pg_result_status,arginfo_pg_result_status) PHP_FE(pg_free_result, arginfo_pg_free_result) PHP_FE(pg_last_oid, arginfo_pg_last_oid) PHP_FE(pg_num_rows, arginfo_pg_num_rows) PHP_FE(pg_num_fields, arginfo_pg_num_fields) PHP_FE(pg_field_name, arginfo_pg_field_name) PHP_FE(pg_field_num, arginfo_pg_field_num) PHP_FE(pg_field_size, arginfo_pg_field_size) PHP_FE(pg_field_type, arginfo_pg_field_type) PHP_FE(pg_field_type_oid, arginfo_pg_field_type_oid) PHP_FE(pg_field_prtlen, arginfo_pg_field_prtlen) PHP_FE(pg_field_is_null,arginfo_pg_field_is_null) #ifdef HAVE_PQFTABLE PHP_FE(pg_field_table, arginfo_pg_field_table) #endif /* async message function */ PHP_FE(pg_get_notify, arginfo_pg_get_notify) PHP_FE(pg_socket, arginfo_pg_socket) PHP_FE(pg_consume_input,arginfo_pg_consume_input) PHP_FE(pg_flush, arginfo_pg_flush) PHP_FE(pg_get_pid, arginfo_pg_get_pid) /* error message functions */ PHP_FE(pg_result_error, arginfo_pg_result_error) #if HAVE_PQRESULTERRORFIELD PHP_FE(pg_result_error_field, arginfo_pg_result_error_field) #endif PHP_FE(pg_last_error, arginfo_pg_last_error) PHP_FE(pg_last_notice, arginfo_pg_last_notice) /* copy functions */ PHP_FE(pg_put_line, arginfo_pg_put_line) PHP_FE(pg_end_copy, arginfo_pg_end_copy) PHP_FE(pg_copy_to, arginfo_pg_copy_to) PHP_FE(pg_copy_from, arginfo_pg_copy_from) /* debug functions */ PHP_FE(pg_trace, arginfo_pg_trace) PHP_FE(pg_untrace, arginfo_pg_untrace) /* large object functions */ PHP_FE(pg_lo_create, arginfo_pg_lo_create) PHP_FE(pg_lo_unlink, arginfo_pg_lo_unlink) PHP_FE(pg_lo_open, arginfo_pg_lo_open) PHP_FE(pg_lo_close, arginfo_pg_lo_close) PHP_FE(pg_lo_read, arginfo_pg_lo_read) PHP_FE(pg_lo_write, arginfo_pg_lo_write) PHP_FE(pg_lo_read_all, arginfo_pg_lo_read_all) PHP_FE(pg_lo_import, arginfo_pg_lo_import) PHP_FE(pg_lo_export, arginfo_pg_lo_export) PHP_FE(pg_lo_seek, arginfo_pg_lo_seek) PHP_FE(pg_lo_tell, arginfo_pg_lo_tell) #if HAVE_PG_LO_TRUNCATE PHP_FE(pg_lo_truncate, arginfo_pg_lo_truncate) #endif /* utility functions */ #if HAVE_PQESCAPE PHP_FE(pg_escape_string, arginfo_pg_escape_string) PHP_FE(pg_escape_bytea, arginfo_pg_escape_bytea) PHP_FE(pg_unescape_bytea, arginfo_pg_unescape_bytea) PHP_FE(pg_escape_literal, arginfo_pg_escape_literal) PHP_FE(pg_escape_identifier, arginfo_pg_escape_identifier) #endif #if HAVE_PQSETERRORVERBOSITY PHP_FE(pg_set_error_verbosity, arginfo_pg_set_error_verbosity) #endif #if HAVE_PQCLIENTENCODING PHP_FE(pg_client_encoding, arginfo_pg_client_encoding) PHP_FE(pg_set_client_encoding, arginfo_pg_set_client_encoding) #endif /* misc function */ PHP_FE(pg_meta_data, arginfo_pg_meta_data) PHP_FE(pg_convert, arginfo_pg_convert) PHP_FE(pg_insert, arginfo_pg_insert) PHP_FE(pg_update, arginfo_pg_update) PHP_FE(pg_delete, arginfo_pg_delete) PHP_FE(pg_select, arginfo_pg_select) /* aliases for downwards compatibility */ PHP_FALIAS(pg_exec, pg_query, arginfo_pg_query) PHP_FALIAS(pg_getlastoid, pg_last_oid, arginfo_pg_last_oid) #if HAVE_PQCMDTUPLES PHP_FALIAS(pg_cmdtuples, pg_affected_rows, arginfo_pg_affected_rows) #endif PHP_FALIAS(pg_errormessage, pg_last_error, arginfo_pg_last_error) PHP_FALIAS(pg_numrows, pg_num_rows, arginfo_pg_num_rows) PHP_FALIAS(pg_numfields, pg_num_fields, arginfo_pg_num_fields) PHP_FALIAS(pg_fieldname, pg_field_name, arginfo_pg_field_name) PHP_FALIAS(pg_fieldsize, pg_field_size, arginfo_pg_field_size) PHP_FALIAS(pg_fieldtype, pg_field_type, arginfo_pg_field_type) PHP_FALIAS(pg_fieldnum, pg_field_num, arginfo_pg_field_num) PHP_FALIAS(pg_fieldprtlen, pg_field_prtlen, arginfo_pg_field_prtlen) PHP_FALIAS(pg_fieldisnull, pg_field_is_null, arginfo_pg_field_is_null) PHP_FALIAS(pg_freeresult, pg_free_result, arginfo_pg_free_result) PHP_FALIAS(pg_result, pg_fetch_result, arginfo_pg_get_result) PHP_FALIAS(pg_loreadall, pg_lo_read_all, arginfo_pg_lo_read_all) PHP_FALIAS(pg_locreate, pg_lo_create, arginfo_pg_lo_create) PHP_FALIAS(pg_lounlink, pg_lo_unlink, arginfo_pg_lo_unlink) PHP_FALIAS(pg_loopen, pg_lo_open, arginfo_pg_lo_open) PHP_FALIAS(pg_loclose, pg_lo_close, arginfo_pg_lo_close) PHP_FALIAS(pg_loread, pg_lo_read, arginfo_pg_lo_read) PHP_FALIAS(pg_lowrite, pg_lo_write, arginfo_pg_lo_write) PHP_FALIAS(pg_loimport, pg_lo_import, arginfo_pg_lo_import) PHP_FALIAS(pg_loexport, pg_lo_export, arginfo_pg_lo_export) #if HAVE_PQCLIENTENCODING PHP_FALIAS(pg_clientencoding, pg_client_encoding, arginfo_pg_client_encoding) PHP_FALIAS(pg_setclientencoding, pg_set_client_encoding, arginfo_pg_set_client_encoding) #endif PHP_FE_END }; /* }}} */ /* {{{ pgsql_module_entry */ zend_module_entry pgsql_module_entry = { STANDARD_MODULE_HEADER, "pgsql", pgsql_functions, PHP_MINIT(pgsql), PHP_MSHUTDOWN(pgsql), PHP_RINIT(pgsql), PHP_RSHUTDOWN(pgsql), PHP_MINFO(pgsql), PHP_PGSQL_VERSION, PHP_MODULE_GLOBALS(pgsql), PHP_GINIT(pgsql), NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; /* }}} */ #ifdef COMPILE_DL_PGSQL #ifdef ZTS ZEND_TSRMLS_CACHE_DEFINE() #endif ZEND_GET_MODULE(pgsql) #endif static int le_link, le_plink, le_result, le_lofp, le_string; /* Compatibility definitions */ #ifndef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT #define pg_encoding_to_char(x) "SQL_ASCII" #endif #if !HAVE_PQESCAPE_CONN #define PQescapeStringConn(conn, to, from, len, error) PQescapeString(to, from, len) #endif #if HAVE_PQESCAPELITERAL #define PGSQLescapeLiteral(conn, str, len) PQescapeLiteral(conn, str, len) #define PGSQLescapeIdentifier(conn, str, len) PQescapeIdentifier(conn, str, len) #define PGSQLfree(a) PQfreemem(a) #else #define PGSQLescapeLiteral(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 1, 0) #define PGSQLescapeLiteral2(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 1, 1) #define PGSQLescapeIdentifier(conn, str, len) php_pgsql_PQescapeInternal(conn, str, len, 0, 0) #define PGSQLfree(a) efree(a) /* emulate libpq's PQescapeInternal() 9.0 or later */ static char *php_pgsql_PQescapeInternal(PGconn *conn, const char *str, size_t len, int escape_literal, int safe) /* {{{ */ { char *result, *rp, *s; if (!conn) { return NULL; } /* allocate enough memory */ rp = result = (char *)safe_emalloc(len, 2, 5); /* leading " E" needs extra 2 bytes + quote_chars on both end for 2 bytes + NULL */ if (escape_literal) { if (safe) { size_t new_len; char *tmp = (char *)safe_emalloc(len, 2, 1); *rp++ = '\''; /* PQescapeString does not escape \, but it handles multibyte chars safely. This escape is incompatible with PQescapeLiteral. */ new_len = PQescapeStringConn(conn, tmp, str, len, NULL); strncpy(rp, tmp, new_len); efree(tmp); rp += new_len; } else { char *encoding; size_t tmp_len; /* This is compatible with PQescapeLiteral, but it cannot handle multbyte chars such as SJIS, BIG5. Raise warning and return NULL by checking client_encoding. */ encoding = (char *) pg_encoding_to_char(PQclientEncoding(conn)); if (!strncmp(encoding, "SJIS", sizeof("SJIS")-1) || !strncmp(encoding, "SHIFT_JIS_2004", sizeof("SHIFT_JIS_2004")-1) || !strncmp(encoding, "BIG5", sizeof("BIG5")-1) || !strncmp(encoding, "GB18030", sizeof("GB18030")-1) || !strncmp(encoding, "GBK", sizeof("GBK")-1) || !strncmp(encoding, "JOHAB", sizeof("JOHAB")-1) || !strncmp(encoding, "UHC", sizeof("UHC")-1) ) { php_error_docref(NULL, E_WARNING, "Unsafe encoding is used. Do not use '%s' encoding or use PostgreSQL 9.0 or later libpq.", encoding); } /* check backslashes */ tmp_len = strspn(str, "\\"); if (tmp_len != len) { /* add " E" for escaping slashes */ *rp++ = ' '; *rp++ = 'E'; } *rp++ = '\''; for (s = (char *)str; s - str < len; ++s) { if (*s == '\'' || *s == '\\') { *rp++ = *s; *rp++ = *s; } else { *rp++ = *s; } } } *rp++ = '\''; } else { /* Identifier escape. */ *rp++ = '"'; for (s = (char *)str; s - str < len; ++s) { if (*s == '"') { *rp++ = '"'; *rp++ = '"'; } else { *rp++ = *s; } } *rp++ = '"'; } *rp = '\0'; return result; } /* }}} */ #endif /* {{{ _php_pgsql_trim_message */ static char * _php_pgsql_trim_message(const char *message, size_t *len) { register size_t i = strlen(message); if (i>2 && (message[i-2] == '\r' || message[i-2] == '\n') && message[i-1] == '.') { --i; } while (i>1 && (message[i-1] == '\r' || message[i-1] == '\n')) { --i; } if (len) { *len = i; } return estrndup(message, i); } /* }}} */ /* {{{ _php_pgsql_trim_result */ static inline char * _php_pgsql_trim_result(PGconn * pgsql, char **buf) { return *buf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL); } /* }}} */ #define PQErrorMessageTrim(pgsql, buf) _php_pgsql_trim_result(pgsql, buf) #define PHP_PQ_ERROR(text, pgsql) { \ char *msgbuf = _php_pgsql_trim_message(PQerrorMessage(pgsql), NULL); \ php_error_docref(NULL, E_WARNING, text, msgbuf); \ efree(msgbuf); \ } \ /* {{{ php_pgsql_set_default_link */ static void php_pgsql_set_default_link(zend_resource *res) { GC_ADDREF(res); if (PGG(default_link) != NULL) { zend_list_delete(PGG(default_link)); } PGG(default_link) = res; } /* }}} */ /* {{{ _close_pgsql_link */ static void _close_pgsql_link(zend_resource *rsrc) { PGconn *link = (PGconn *)rsrc->ptr; PGresult *res; while ((res = PQgetResult(link))) { PQclear(res); } PQfinish(link); PGG(num_links)--; } /* }}} */ /* {{{ _close_pgsql_plink */ static void _close_pgsql_plink(zend_resource *rsrc) { PGconn *link = (PGconn *)rsrc->ptr; PGresult *res; while ((res = PQgetResult(link))) { PQclear(res); } PQfinish(link); PGG(num_persistent)--; PGG(num_links)--; } /* }}} */ /* {{{ _php_pgsql_notice_handler */ static void _php_pgsql_notice_handler(void *resource_id, const char *message) { zval *notices; zval tmp; char *trimed_message; size_t trimed_message_len; if (! PGG(ignore_notices)) { notices = zend_hash_index_find(&PGG(notices), (zend_ulong)resource_id); if (!notices) { array_init(&tmp); notices = &tmp; zend_hash_index_update(&PGG(notices), (zend_ulong)resource_id, notices); } trimed_message = _php_pgsql_trim_message(message, &trimed_message_len); if (PGG(log_notices)) { php_error_docref(NULL, E_NOTICE, "%s", trimed_message); } add_next_index_stringl(notices, trimed_message, trimed_message_len); efree(trimed_message); } } /* }}} */ /* {{{ _rollback_transactions */ static int _rollback_transactions(zval *el) { PGconn *link; PGresult *res; zend_resource *rsrc = Z_RES_P(el); if (rsrc->type != le_plink) return 0; link = (PGconn *) rsrc->ptr; if (PQ_SETNONBLOCKING(link, 0)) { php_error_docref("ref.pgsql", E_NOTICE, "Cannot set connection to blocking mode"); return -1; } while ((res = PQgetResult(link))) { PQclear(res); } #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION if ((PQprotocolVersion(link) >= 3 && PQtransactionStatus(link) != PQTRANS_IDLE) || PQprotocolVersion(link) < 3) #endif { int orig = PGG(ignore_notices); PGG(ignore_notices) = 1; #if HAVE_PGTRANSACTIONSTATUS && HAVE_PQPROTOCOLVERSION res = PQexec(link,"ROLLBACK;"); #else res = PQexec(link,"BEGIN;"); PQclear(res); res = PQexec(link,"ROLLBACK;"); #endif PQclear(res); PGG(ignore_notices) = orig; } return 0; } /* }}} */ /* {{{ _free_ptr */ static void _free_ptr(zend_resource *rsrc) { pgLofp *lofp = (pgLofp *)rsrc->ptr; efree(lofp); } /* }}} */ /* {{{ _free_result */ static void _free_result(zend_resource *rsrc) { pgsql_result_handle *pg_result = (pgsql_result_handle *)rsrc->ptr; PQclear(pg_result->result); efree(pg_result); } /* }}} */ static int _php_pgsql_detect_identifier_escape(const char *identifier, size_t len) /* {{{ */ { /* Handle edge case. Cannot be a escaped string */ if (len <= 2) { return FAILURE; } /* Detect double qoutes */ if (identifier[0] == '"' && identifier[len-1] == '"') { size_t i; /* Detect wrong format of " inside of escaped string */ for (i = 1; i < len-1; i++) { if (identifier[i] == '"' && (identifier[++i] != '"' || i == len-1)) { return FAILURE; } } } else { return FAILURE; } /* Escaped properly */ return SUCCESS; } /* }}} */ /* {{{ PHP_INI */ PHP_INI_BEGIN() STD_PHP_INI_BOOLEAN( "pgsql.allow_persistent", "1", PHP_INI_SYSTEM, OnUpdateBool, allow_persistent, zend_pgsql_globals, pgsql_globals) STD_PHP_INI_ENTRY_EX("pgsql.max_persistent", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_persistent, zend_pgsql_globals, pgsql_globals, display_link_numbers) STD_PHP_INI_ENTRY_EX("pgsql.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_pgsql_globals, pgsql_globals, display_link_numbers) STD_PHP_INI_BOOLEAN( "pgsql.auto_reset_persistent", "0", PHP_INI_SYSTEM, OnUpdateBool, auto_reset_persistent, zend_pgsql_globals, pgsql_globals) STD_PHP_INI_BOOLEAN( "pgsql.ignore_notice", "0", PHP_INI_ALL, OnUpdateBool, ignore_notices, zend_pgsql_globals, pgsql_globals) STD_PHP_INI_BOOLEAN( "pgsql.log_notice", "0", PHP_INI_ALL, OnUpdateBool, log_notices, zend_pgsql_globals, pgsql_globals) PHP_INI_END() /* }}} */ /* {{{ PHP_GINIT_FUNCTION */ static PHP_GINIT_FUNCTION(pgsql) { #if defined(COMPILE_DL_PGSQL) && defined(ZTS) ZEND_TSRMLS_CACHE_UPDATE(); #endif memset(pgsql_globals, 0, sizeof(zend_pgsql_globals)); /* Initilize notice message hash at MINIT only */ zend_hash_init_ex(&pgsql_globals->notices, 0, NULL, ZVAL_PTR_DTOR, 1, 0); } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ PHP_MINIT_FUNCTION(pgsql) { REGISTER_INI_ENTRIES(); le_link = zend_register_list_destructors_ex(_close_pgsql_link, NULL, "pgsql link", module_number); le_plink = zend_register_list_destructors_ex(NULL, _close_pgsql_plink, "pgsql link persistent", module_number); le_result = zend_register_list_destructors_ex(_free_result, NULL, "pgsql result", module_number); le_lofp = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql large object", module_number); le_string = zend_register_list_destructors_ex(_free_ptr, NULL, "pgsql string", module_number); #if HAVE_PG_CONFIG_H /* PG_VERSION - libpq version */ REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION", PG_VERSION, CONST_CS | CONST_PERSISTENT); REGISTER_STRING_CONSTANT("PGSQL_LIBPQ_VERSION_STR", PG_VERSION_STR, CONST_CS | CONST_PERSISTENT); #endif /* For connection option */ REGISTER_LONG_CONSTANT("PGSQL_CONNECT_FORCE_NEW", PGSQL_CONNECT_FORCE_NEW, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECT_ASYNC", PGSQL_CONNECT_ASYNC, CONST_CS | CONST_PERSISTENT); /* For pg_fetch_array() */ REGISTER_LONG_CONSTANT("PGSQL_ASSOC", PGSQL_ASSOC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NUM", PGSQL_NUM, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_BOTH", PGSQL_BOTH, CONST_CS | CONST_PERSISTENT); /* For pg_last_notice() */ REGISTER_LONG_CONSTANT("PGSQL_NOTICE_LAST", PGSQL_NOTICE_LAST, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NOTICE_ALL", PGSQL_NOTICE_ALL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NOTICE_CLEAR", PGSQL_NOTICE_CLEAR, CONST_CS | CONST_PERSISTENT); /* For pg_connection_status() */ REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_BAD", CONNECTION_BAD, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_OK", CONNECTION_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_STARTED", CONNECTION_STARTED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_MADE", CONNECTION_MADE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AWAITING_RESPONSE", CONNECTION_AWAITING_RESPONSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_AUTH_OK", CONNECTION_AUTH_OK, CONST_CS | CONST_PERSISTENT); #ifdef CONNECTION_SSL_STARTUP REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SSL_STARTUP", CONNECTION_SSL_STARTUP, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("PGSQL_CONNECTION_SETENV", CONNECTION_SETENV, CONST_CS | CONST_PERSISTENT); /* For pg_connect_poll() */ REGISTER_LONG_CONSTANT("PGSQL_POLLING_FAILED", PGRES_POLLING_FAILED, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_READING", PGRES_POLLING_READING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_WRITING", PGRES_POLLING_WRITING, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_OK", PGRES_POLLING_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_POLLING_ACTIVE", PGRES_POLLING_ACTIVE, CONST_CS | CONST_PERSISTENT); #if HAVE_PGTRANSACTIONSTATUS /* For pg_transaction_status() */ REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_IDLE", PQTRANS_IDLE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_ACTIVE", PQTRANS_ACTIVE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INTRANS", PQTRANS_INTRANS, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_INERROR", PQTRANS_INERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TRANSACTION_UNKNOWN", PQTRANS_UNKNOWN, CONST_CS | CONST_PERSISTENT); #endif #if HAVE_PQSETERRORVERBOSITY /* For pg_set_error_verbosity() */ REGISTER_LONG_CONSTANT("PGSQL_ERRORS_TERSE", PQERRORS_TERSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_ERRORS_DEFAULT", PQERRORS_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_ERRORS_VERBOSE", PQERRORS_VERBOSE, CONST_CS | CONST_PERSISTENT); #endif /* For lo_seek() */ REGISTER_LONG_CONSTANT("PGSQL_SEEK_SET", SEEK_SET, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_SEEK_CUR", SEEK_CUR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_SEEK_END", SEEK_END, CONST_CS | CONST_PERSISTENT); /* For pg_result_status() return value type */ REGISTER_LONG_CONSTANT("PGSQL_STATUS_LONG", PGSQL_STATUS_LONG, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_STATUS_STRING", PGSQL_STATUS_STRING, CONST_CS | CONST_PERSISTENT); /* For pg_result_status() return value */ REGISTER_LONG_CONSTANT("PGSQL_EMPTY_QUERY", PGRES_EMPTY_QUERY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COMMAND_OK", PGRES_COMMAND_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_TUPLES_OK", PGRES_TUPLES_OK, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COPY_OUT", PGRES_COPY_OUT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_COPY_IN", PGRES_COPY_IN, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_BAD_RESPONSE", PGRES_BAD_RESPONSE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_NONFATAL_ERROR", PGRES_NONFATAL_ERROR, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_FATAL_ERROR", PGRES_FATAL_ERROR, CONST_CS | CONST_PERSISTENT); #if HAVE_PQRESULTERRORFIELD /* For pg_result_error_field() field codes */ REGISTER_LONG_CONSTANT("PGSQL_DIAG_SEVERITY", PG_DIAG_SEVERITY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SQLSTATE", PG_DIAG_SQLSTATE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_PRIMARY", PG_DIAG_MESSAGE_PRIMARY, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_DETAIL", PG_DIAG_MESSAGE_DETAIL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_MESSAGE_HINT", PG_DIAG_MESSAGE_HINT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_STATEMENT_POSITION", PG_DIAG_STATEMENT_POSITION, CONST_CS | CONST_PERSISTENT); #ifdef PG_DIAG_INTERNAL_POSITION REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_POSITION", PG_DIAG_INTERNAL_POSITION, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_INTERNAL_QUERY REGISTER_LONG_CONSTANT("PGSQL_DIAG_INTERNAL_QUERY", PG_DIAG_INTERNAL_QUERY, CONST_CS | CONST_PERSISTENT); #endif REGISTER_LONG_CONSTANT("PGSQL_DIAG_CONTEXT", PG_DIAG_CONTEXT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FILE", PG_DIAG_SOURCE_FILE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_LINE", PG_DIAG_SOURCE_LINE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DIAG_SOURCE_FUNCTION", PG_DIAG_SOURCE_FUNCTION, CONST_CS | CONST_PERSISTENT); #ifdef PG_DIAG_SCHEMA_NAME REGISTER_LONG_CONSTANT("PGSQL_DIAG_SCHEMA_NAME", PG_DIAG_SCHEMA_NAME, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_TABLE_NAME REGISTER_LONG_CONSTANT("PGSQL_DIAG_TABLE_NAME", PG_DIAG_TABLE_NAME, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_COLUMN_NAME REGISTER_LONG_CONSTANT("PGSQL_DIAG_COLUMN_NAME", PG_DIAG_COLUMN_NAME, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_DATATYPE_NAME REGISTER_LONG_CONSTANT("PGSQL_DIAG_DATATYPE_NAME", PG_DIAG_DATATYPE_NAME, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_CONSTRAINT_NAME REGISTER_LONG_CONSTANT("PGSQL_DIAG_CONSTRAINT_NAME", PG_DIAG_CONSTRAINT_NAME, CONST_CS | CONST_PERSISTENT); #endif #ifdef PG_DIAG_SEVERITY_NONLOCALIZED REGISTER_LONG_CONSTANT("PGSQL_DIAG_SEVERITY_NONLOCALIZED", PG_DIAG_SEVERITY_NONLOCALIZED, CONST_CS | CONST_PERSISTENT); #endif #endif /* pg_convert options */ REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_DEFAULT", PGSQL_CONV_IGNORE_DEFAULT, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONV_FORCE_NULL", PGSQL_CONV_FORCE_NULL, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_CONV_IGNORE_NOT_NULL", PGSQL_CONV_IGNORE_NOT_NULL, CONST_CS | CONST_PERSISTENT); /* pg_insert/update/delete/select options */ REGISTER_LONG_CONSTANT("PGSQL_DML_ESCAPE", PGSQL_DML_ESCAPE, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_NO_CONV", PGSQL_DML_NO_CONV, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_EXEC", PGSQL_DML_EXEC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_ASYNC", PGSQL_DML_ASYNC, CONST_CS | CONST_PERSISTENT); REGISTER_LONG_CONSTANT("PGSQL_DML_STRING", PGSQL_DML_STRING, CONST_CS | CONST_PERSISTENT); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ PHP_MSHUTDOWN_FUNCTION(pgsql) { UNREGISTER_INI_ENTRIES(); zend_hash_destroy(&PGG(notices)); return SUCCESS; } /* }}} */ /* {{{ PHP_RINIT_FUNCTION */ PHP_RINIT_FUNCTION(pgsql) { PGG(default_link) = NULL; PGG(num_links) = PGG(num_persistent); return SUCCESS; } /* }}} */ /* {{{ PHP_RSHUTDOWN_FUNCTION */ PHP_RSHUTDOWN_FUNCTION(pgsql) { /* clean up notice messages */ zend_hash_clean(&PGG(notices)); /* clean up persistent connection */ zend_hash_apply(&EG(persistent_list), (apply_func_t) _rollback_transactions); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ PHP_MINFO_FUNCTION(pgsql) { char buf[256]; php_info_print_table_start(); php_info_print_table_header(2, "PostgreSQL Support", "enabled"); #if HAVE_PG_CONFIG_H php_info_print_table_row(2, "PostgreSQL(libpq) Version", PG_VERSION); php_info_print_table_row(2, "PostgreSQL(libpq) ", PG_VERSION_STR); #ifdef HAVE_PGSQL_WITH_MULTIBYTE_SUPPORT php_info_print_table_row(2, "Multibyte character support", "enabled"); #else php_info_print_table_row(2, "Multibyte character support", "disabled"); #endif #if defined(USE_SSL) || defined(USE_OPENSSL) php_info_print_table_row(2, "SSL support", "enabled"); #else php_info_print_table_row(2, "SSL support", "disabled"); #endif #endif /* HAVE_PG_CONFIG_H */ snprintf(buf, sizeof(buf), ZEND_LONG_FMT, PGG(num_persistent)); php_info_print_table_row(2, "Active Persistent Links", buf); snprintf(buf, sizeof(buf), ZEND_LONG_FMT, PGG(num_links)); php_info_print_table_row(2, "Active Links", buf); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ php_pgsql_do_connect */ static void php_pgsql_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent) { char *host=NULL,*port=NULL,*options=NULL,*tty=NULL,*dbname=NULL,*connstring=NULL; PGconn *pgsql; smart_str str = {0}; zval *args; uint32_t i; int connect_type = 0; PGresult *pg_result; args = (zval *)safe_emalloc(ZEND_NUM_ARGS(), sizeof(zval), 0); if (ZEND_NUM_ARGS() < 1 || ZEND_NUM_ARGS() > 5 || zend_get_parameters_array_ex(ZEND_NUM_ARGS(), args) == FAILURE) { efree(args); WRONG_PARAM_COUNT; } smart_str_appends(&str, "pgsql"); for (i = 0; i < ZEND_NUM_ARGS(); i++) { /* make sure that the PGSQL_CONNECT_FORCE_NEW bit is not part of the hash so that subsequent connections * can re-use this connection. Bug #39979 */ if (i == 1 && ZEND_NUM_ARGS() == 2 && Z_TYPE(args[i]) == IS_LONG) { if (Z_LVAL(args[1]) == PGSQL_CONNECT_FORCE_NEW) { continue; } else if (Z_LVAL(args[1]) & PGSQL_CONNECT_FORCE_NEW) { smart_str_append_long(&str, Z_LVAL(args[1]) ^ PGSQL_CONNECT_FORCE_NEW); } } ZVAL_STR(&args[i], zval_get_string(&args[i])); smart_str_appendc(&str, '_'); smart_str_appendl(&str, Z_STRVAL(args[i]), Z_STRLEN(args[i])); } smart_str_0(&str); if (ZEND_NUM_ARGS() == 1) { /* new style, using connection string */ connstring = Z_STRVAL(args[0]); } else if (ZEND_NUM_ARGS() == 2 ) { /* Safe to add conntype_option, since 2 args was illegal */ connstring = Z_STRVAL(args[0]); connect_type = (int)zval_get_long(&args[1]); } else { host = Z_STRVAL(args[0]); port = Z_STRVAL(args[1]); dbname = Z_STRVAL(args[ZEND_NUM_ARGS()-1]); switch (ZEND_NUM_ARGS()) { case 5: tty = Z_STRVAL(args[3]); /* fall through */ case 4: options = Z_STRVAL(args[2]); break; } } if (persistent && PGG(allow_persistent)) { zend_resource *le; /* try to find if we already have this link in our persistent list */ if ((le = zend_hash_find_ptr(&EG(persistent_list), str.s)) == NULL) { /* we don't */ if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) { php_error_docref(NULL, E_WARNING, "Cannot create new link. Too many open links (" ZEND_LONG_FMT ")", PGG(num_links)); goto err; } if (PGG(max_persistent) != -1 && PGG(num_persistent) >= PGG(max_persistent)) { php_error_docref(NULL, E_WARNING, "Cannot create new link. Too many open persistent links (" ZEND_LONG_FMT ")", PGG(num_persistent)); goto err; } /* create the link */ if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host, port, options, tty, dbname); } if (pgsql == NULL || PQstatus(pgsql) == CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql) if (pgsql) { PQfinish(pgsql); } goto err; } /* hash it up */ if (zend_register_persistent_resource(ZSTR_VAL(str.s), ZSTR_LEN(str.s), pgsql, le_plink) == NULL) { goto err; } PGG(num_links)++; PGG(num_persistent)++; } else { /* we do */ if (le->type != le_plink) { goto err; } /* ensure that the link did not die */ if (PGG(auto_reset_persistent) & 1) { /* need to send & get something from backend to make sure we catch CONNECTION_BAD every time */ PGresult *pg_result; pg_result = PQexec(le->ptr, "select 1"); PQclear(pg_result); } if (PQstatus(le->ptr) == CONNECTION_BAD) { /* the link died */ if (le->ptr == NULL) { if (connstring) { le->ptr = PQconnectdb(connstring); } else { le->ptr = PQsetdb(host,port,options,tty,dbname); } } else { PQreset(le->ptr); } if (le->ptr == NULL || PQstatus(le->ptr) == CONNECTION_BAD) { php_error_docref(NULL, E_WARNING,"PostgreSQL link lost, unable to reconnect"); zend_hash_del(&EG(persistent_list), str.s); goto err; } } pgsql = (PGconn *) le->ptr; #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 7.2) { #else if (atof(PG_VERSION) >= 7.2) { #endif pg_result = PQexec(pgsql, "RESET ALL;"); PQclear(pg_result); } } RETVAL_RES(zend_register_resource(pgsql, le_plink)); } else { /* Non persistent connection */ zend_resource *index_ptr, new_index_ptr; /* first we check the hash for the hashed_details key. if it exists, * it should point us to the right offset where the actual pgsql link sits. * if it doesn't, open a new pgsql link, add it to the resource list, * and add a pointer to it with hashed_details as the key. */ if (!(connect_type & PGSQL_CONNECT_FORCE_NEW) && (index_ptr = zend_hash_find_ptr(&EG(regular_list), str.s)) != NULL) { zend_resource *link; if (index_ptr->type != le_index_ptr) { goto err; } link = (zend_resource *)index_ptr->ptr; if (link->ptr && (link->type == le_link || link->type == le_plink)) { php_pgsql_set_default_link(link); GC_ADDREF(link); RETVAL_RES(link); goto cleanup; } else { zend_hash_del(&EG(regular_list), str.s); } } if (PGG(max_links) != -1 && PGG(num_links) >= PGG(max_links)) { php_error_docref(NULL, E_WARNING, "Cannot create new link. Too many open links (" ZEND_LONG_FMT ")", PGG(num_links)); goto err; } /* Non-blocking connect */ if (connect_type & PGSQL_CONNECT_ASYNC) { if (connstring) { pgsql = PQconnectStart(connstring); if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } } else { php_error_docref(NULL, E_WARNING, "Connection string required for async connections"); goto err; } } else { if (connstring) { pgsql = PQconnectdb(connstring); } else { pgsql = PQsetdb(host,port,options,tty,dbname); } if (pgsql==NULL || PQstatus(pgsql)==CONNECTION_BAD) { PHP_PQ_ERROR("Unable to connect to PostgreSQL server: %s", pgsql); if (pgsql) { PQfinish(pgsql); } goto err; } } /* add it to the list */ RETVAL_RES(zend_register_resource(pgsql, le_link)); /* add it to the hash */ new_index_ptr.ptr = (void *) Z_RES_P(return_value); new_index_ptr.type = le_index_ptr; zend_hash_update_mem(&EG(regular_list), str.s, (void *) &new_index_ptr, sizeof(zend_resource)); PGG(num_links)++; } /* set notice processor */ if (! PGG(ignore_notices) && Z_TYPE_P(return_value) == IS_RESOURCE) { PQsetNoticeProcessor(pgsql, _php_pgsql_notice_handler, (void*)(zend_uintptr_t)Z_RES_HANDLE_P(return_value)); } php_pgsql_set_default_link(Z_RES_P(return_value)); cleanup: for (i = 0; i < ZEND_NUM_ARGS(); i++) { zval_dtor(&args[i]); } efree(args); smart_str_free(&str); return; err: for (i = 0; i < ZEND_NUM_ARGS(); i++) { zval_dtor(&args[i]); } efree(args); smart_str_free(&str); RETURN_FALSE; } /* }}} */ /* {{{ proto resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database) Open a PostgreSQL connection */ PHP_FUNCTION(pg_connect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,0); } /* }}} */ /* {{{ proto resource pg_connect_poll(resource connection) Poll the status of an in-progress async PostgreSQL connection attempt*/ PHP_FUNCTION(pg_connect_poll) { zval *pgsql_link; PGconn *pgsql; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } ret = PQconnectPoll(pgsql); RETURN_LONG(ret); } /* }}} */ /* {{{ proto resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database) Open a persistent PostgreSQL connection */ PHP_FUNCTION(pg_pconnect) { php_pgsql_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU,1); } /* }}} */ /* {{{ proto bool pg_close([resource connection]) Close a PostgreSQL connection */ PHP_FUNCTION(pg_close) { zval *pgsql_link = NULL; zend_resource *link; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|r", &pgsql_link) == FAILURE) { return; } if (pgsql_link) { link = Z_RES_P(pgsql_link); } else { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } if (zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink) == NULL) { RETURN_FALSE; } if (link == PGG(default_link)) { zend_list_delete(link); PGG(default_link) = NULL; } zend_list_close(link); RETURN_TRUE; } /* }}} */ #define PHP_PG_DBNAME 1 #define PHP_PG_ERROR_MESSAGE 2 #define PHP_PG_OPTIONS 3 #define PHP_PG_PORT 4 #define PHP_PG_TTY 5 #define PHP_PG_HOST 6 #define PHP_PG_VERSION 7 /* {{{ php_pgsql_get_link_info */ static void php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zend_resource *link; zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; char *msgbuf; char *result; if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } switch(entry_type) { case PHP_PG_DBNAME: result = PQdb(pgsql); break; case PHP_PG_ERROR_MESSAGE: result = PQErrorMessageTrim(pgsql, &msgbuf); RETVAL_STRING(result); efree(result); return; case PHP_PG_OPTIONS: result = PQoptions(pgsql); break; case PHP_PG_PORT: result = PQport(pgsql); break; case PHP_PG_TTY: result = PQtty(pgsql); break; case PHP_PG_HOST: result = PQhost(pgsql); break; case PHP_PG_VERSION: array_init(return_value); add_assoc_string(return_value, "client", PG_VERSION); #if HAVE_PQPROTOCOLVERSION add_assoc_long(return_value, "protocol", PQprotocolVersion(pgsql)); #if HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3) { /* 8.0 or grater supports protorol version 3 */ char *tmp; add_assoc_string(return_value, "server", (char*)PQparameterStatus(pgsql, "server_version")); #define PHP_PQ_COPY_PARAM(_x) tmp = (char*)PQparameterStatus(pgsql, _x); \ if(tmp) add_assoc_string(return_value, _x, tmp); \ else add_assoc_null(return_value, _x); PHP_PQ_COPY_PARAM("server_encoding"); PHP_PQ_COPY_PARAM("client_encoding"); PHP_PQ_COPY_PARAM("is_superuser"); PHP_PQ_COPY_PARAM("session_authorization"); PHP_PQ_COPY_PARAM("DateStyle"); PHP_PQ_COPY_PARAM("IntervalStyle"); PHP_PQ_COPY_PARAM("TimeZone"); PHP_PQ_COPY_PARAM("integer_datetimes"); PHP_PQ_COPY_PARAM("standard_conforming_strings"); PHP_PQ_COPY_PARAM("application_name"); } #endif #endif return; default: RETURN_FALSE; } if (result) { RETURN_STRING(result); } else { RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string pg_dbname([resource connection]) Get the database name */ PHP_FUNCTION(pg_dbname) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_DBNAME); } /* }}} */ /* {{{ proto string pg_last_error([resource connection]) Get the error message string */ PHP_FUNCTION(pg_last_error) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_ERROR_MESSAGE); } /* }}} */ /* {{{ proto string pg_options([resource connection]) Get the options associated with the connection */ PHP_FUNCTION(pg_options) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_OPTIONS); } /* }}} */ /* {{{ proto int pg_port([resource connection]) Return the port number associated with the connection */ PHP_FUNCTION(pg_port) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_PORT); } /* }}} */ /* {{{ proto string pg_tty([resource connection]) Return the tty name associated with the connection */ PHP_FUNCTION(pg_tty) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_TTY); } /* }}} */ /* {{{ proto string pg_host([resource connection]) Returns the host name associated with the connection */ PHP_FUNCTION(pg_host) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_HOST); } /* }}} */ /* {{{ proto array pg_version([resource connection]) Returns an array with client, protocol and server version (when available) */ PHP_FUNCTION(pg_version) { php_pgsql_get_link_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_VERSION); } /* }}} */ #if HAVE_PQPARAMETERSTATUS /* {{{ proto string|false pg_parameter_status([resource connection,] string param_name) Returns the value of a server parameter */ PHP_FUNCTION(pg_parameter_status) { zval *pgsql_link = NULL; zend_resource *link; PGconn *pgsql; char *param; size_t len; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "rs", &pgsql_link, &param, &len) == FAILURE) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &param, &len) == SUCCESS) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { RETURN_FALSE; } } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } param = (char*)PQparameterStatus(pgsql, param); if (param) { RETURN_STRING(param); } else { RETURN_FALSE; } } /* }}} */ #endif /* {{{ proto bool pg_ping([resource connection]) Ping database. If connection is bad, try to reconnect. */ PHP_FUNCTION(pg_ping) { zval *pgsql_link; PGconn *pgsql; PGresult *res; zend_resource *link; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == SUCCESS) { link = Z_RES_P(pgsql_link); } else { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } /* ping connection */ res = PQexec(pgsql, "SELECT 1;"); PQclear(res); /* check status. */ if (PQstatus(pgsql) == CONNECTION_OK) RETURN_TRUE; /* reset connection if it's broken */ PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_OK) { RETURN_TRUE; } RETURN_FALSE; } /* }}} */ /* {{{ proto resource pg_query([resource connection,] string query) Execute a query */ PHP_FUNCTION(pg_query) { zval *pgsql_link = NULL; char *query; int argc = ZEND_NUM_ARGS(); size_t query_len; int leftover = 0; zend_resource *link; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; if (argc == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &query, &query_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQexec(pgsql, query); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexec(pgsql, query); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pgsql_result_handle *pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; RETURN_RES(zend_register_resource(pg_result, le_result)); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #if HAVE_PQEXECPARAMS || HAVE_PQEXECPREPARED || HAVE_PQSENDQUERYPARAMS || HAVE_PQSENDQUERYPREPARED /* {{{ _php_pgsql_free_params */ static void _php_pgsql_free_params(char **params, int num_params) { if (num_params > 0) { int i; for (i = 0; i < num_params; i++) { if (params[i]) { efree(params[i]); } } efree(params); } } /* }}} */ #endif #if HAVE_PQEXECPARAMS /* {{{ proto resource pg_query_params([resource connection,] string query, array params) Execute a query */ PHP_FUNCTION(pg_query_params) { zval *pgsql_link = NULL; zval *pv_param_arr, *tmp; char *query; size_t query_len; int argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; zend_resource *link; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, "sa", &query, &query_len, &pv_param_arr) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { ZVAL_DEREF(tmp); if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_cstring(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,"Error converting parameter"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; RETURN_RES(zend_register_resource(pg_result, le_result)); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQPREPARE /* {{{ proto resource pg_prepare([resource connection,] string stmtname, string query) Prepare a query for future execution */ PHP_FUNCTION(pg_prepare) { zval *pgsql_link = NULL; char *query, *stmtname; size_t query_len, stmtname_len; int argc = ZEND_NUM_ARGS(); int leftover = 0; PGconn *pgsql; zend_resource *link; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, "ss", &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQprepare(pgsql, stmtname, query, 0, NULL); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; RETURN_RES(zend_register_resource(pg_result, le_result)); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #if HAVE_PQEXECPREPARED /* {{{ proto resource pg_execute([resource connection,] string stmtname, array params) Execute a prepared query */ PHP_FUNCTION(pg_execute) { zval *pgsql_link = NULL; zval *pv_param_arr, *tmp; char *stmtname; size_t stmtname_len; int argc = ZEND_NUM_ARGS(); int leftover = 0; int num_params = 0; char **params = NULL; PGconn *pgsql; zend_resource *link; PGresult *pgsql_result; ExecStatusType status; pgsql_result_handle *pg_result; if (argc == 2) { if (zend_parse_parameters(argc, "sa", &stmtname, &stmtname_len, &pv_param_arr)==FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rsa", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE,"Cannot set connection to blocking mode"); RETURN_FALSE; } while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); leftover = 1; } if (leftover) { php_error_docref(NULL, E_NOTICE, "Found results on this connection. Use pg_get_result() to get these results first"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zend_string *tmp_str; zend_string *str = zval_get_tmp_string(tmp, &tmp_str); params[i] = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_tmp_string_release(tmp_str); } i++; } ZEND_HASH_FOREACH_END(); } pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQclear(pgsql_result); PQreset(pgsql); pgsql_result = PQexecPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0); } if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } _php_pgsql_free_params(params, num_params); switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pgsql); PQclear(pgsql_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pgsql_result) { pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; RETURN_RES(zend_register_resource(pg_result, le_result)); } else { PQclear(pgsql_result); RETURN_FALSE; } break; } } /* }}} */ #endif #define PHP_PG_NUM_ROWS 1 #define PHP_PG_NUM_FIELDS 2 #define PHP_PG_CMD_TUPLES 3 /* {{{ php_pgsql_get_result_info */ static void php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; switch (entry_type) { case PHP_PG_NUM_ROWS: RETVAL_LONG(PQntuples(pgsql_result)); break; case PHP_PG_NUM_FIELDS: RETVAL_LONG(PQnfields(pgsql_result)); break; case PHP_PG_CMD_TUPLES: #if HAVE_PQCMDTUPLES RETVAL_LONG(atoi(PQcmdTuples(pgsql_result))); #else php_error_docref(NULL, E_WARNING, "Not supported under this build"); RETVAL_LONG(0); #endif break; default: RETURN_FALSE; } } /* }}} */ /* {{{ proto int pg_num_rows(resource result) Return the number of rows in the result */ PHP_FUNCTION(pg_num_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_ROWS); } /* }}} */ /* {{{ proto int pg_num_fields(resource result) Return the number of fields in the result */ PHP_FUNCTION(pg_num_fields) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_NUM_FIELDS); } /* }}} */ #if HAVE_PQCMDTUPLES /* {{{ proto int pg_affected_rows(resource result) Returns the number of affected tuples */ PHP_FUNCTION(pg_affected_rows) { php_pgsql_get_result_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_CMD_TUPLES); } /* }}} */ #endif /* {{{ proto mixed pg_last_notice(resource connection [, int option]) Returns the last notice set by the backend */ PHP_FUNCTION(pg_last_notice) { zval *pgsql_link = NULL; zval *notice, *notices; PGconn *pg_link; zend_long option = PGSQL_NOTICE_LAST; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pgsql_link, &option) == FAILURE) { return; } /* Just to check if user passed valid resoruce */ if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } notices = zend_hash_index_find(&PGG(notices), (zend_ulong)Z_RES_HANDLE_P(pgsql_link)); switch (option) { case PGSQL_NOTICE_LAST: if (notices) { zend_hash_internal_pointer_end(Z_ARRVAL_P(notices)); if ((notice = zend_hash_get_current_data(Z_ARRVAL_P(notices))) == NULL) { RETURN_EMPTY_STRING(); } RETURN_ZVAL(notice, 1, 0); } else { RETURN_EMPTY_STRING(); } break; case PGSQL_NOTICE_ALL: if (notices) { RETURN_ZVAL(notices, 1, 0); } else { array_init(return_value); return; } break; case PGSQL_NOTICE_CLEAR: if (notices) { zend_hash_clean(&PGG(notices)); } RETURN_TRUE; break; default: php_error_docref(NULL, E_WARNING, "Invalid option specified (" ZEND_LONG_FMT ")", option); } RETURN_FALSE; } /* }}} */ /* {{{ get_field_name */ static char *get_field_name(PGconn *pgsql, Oid oid, HashTable *list) { smart_str str = {0}; zend_resource *field_type; char *ret=NULL; /* try to lookup the type in the resource list */ smart_str_appends(&str, "pgsql_oid_"); smart_str_append_unsigned(&str, oid); smart_str_0(&str); if ((field_type = zend_hash_find_ptr(list, str.s)) != NULL) { ret = estrdup((char *)field_type->ptr); } else { /* hash all oid's */ int i, num_rows; int oid_offset,name_offset; char *tmp_oid, *end_ptr, *tmp_name; zend_resource new_oid_entry; PGresult *result; if ((result = PQexec(pgsql, "select oid,typname from pg_type")) == NULL || PQresultStatus(result) != PGRES_TUPLES_OK) { if (result) { PQclear(result); } smart_str_free(&str); return estrndup("", sizeof("") - 1); } num_rows = PQntuples(result); oid_offset = PQfnumber(result,"oid"); name_offset = PQfnumber(result,"typname"); for (i=0; i<num_rows; i++) { if ((tmp_oid = PQgetvalue(result,i,oid_offset))==NULL) { continue; } smart_str_free(&str); smart_str_appends(&str, "pgsql_oid_"); smart_str_appends(&str, tmp_oid); smart_str_0(&str); if ((tmp_name = PQgetvalue(result,i,name_offset))==NULL) { continue; } new_oid_entry.type = le_string; new_oid_entry.ptr = estrdup(tmp_name); zend_hash_update_mem(list, str.s, (void *) &new_oid_entry, sizeof(zend_resource)); if (!ret && strtoul(tmp_oid, &end_ptr, 10)==oid) { ret = estrdup(tmp_name); } } PQclear(result); } smart_str_free(&str); return ret; } /* }}} */ #ifdef HAVE_PQFTABLE /* {{{ proto mixed pg_field_table(resource result, int field_number[, bool oid_only]) Returns the name of the table field belongs to, or table's oid if oid_only is true */ PHP_FUNCTION(pg_field_table) { zval *result; pgsql_result_handle *pg_result; zend_long fnum = -1; zend_bool return_oid = 0; Oid oid; smart_str hash_key = {0}; char *table_name; zend_resource *field_table; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|b", &result, &fnum, &return_oid) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } if (fnum < 0 || fnum >= PQnfields(pg_result->result)) { php_error_docref(NULL, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } oid = PQftable(pg_result->result, (int)fnum); if (InvalidOid == oid) { RETURN_FALSE; } if (return_oid) { #if UINT_MAX > ZEND_LONG_MAX /* Oid is unsigned int, we don't need this code, where LONG is wider */ if (oid > ZEND_LONG_MAX) { smart_str oidstr = {0}; smart_str_append_unsigned(&oidstr, oid); smart_str_0(&oidstr); RETURN_NEW_STR(oidstr.s); } else #endif RETURN_LONG((zend_long)oid); } /* try to lookup the table name in the resource list */ smart_str_appends(&hash_key, "pgsql_table_oid_"); smart_str_append_unsigned(&hash_key, oid); smart_str_0(&hash_key); if ((field_table = zend_hash_find_ptr(&EG(regular_list), hash_key.s)) != NULL) { smart_str_free(&hash_key); RETURN_STRING((char *)field_table->ptr); } else { /* Not found, lookup by querying PostgreSQL system tables */ PGresult *tmp_res; smart_str querystr = {0}; zend_resource new_field_table; smart_str_appends(&querystr, "select relname from pg_class where oid="); smart_str_append_unsigned(&querystr, oid); smart_str_0(&querystr); if ((tmp_res = PQexec(pg_result->conn, ZSTR_VAL(querystr.s))) == NULL || PQresultStatus(tmp_res) != PGRES_TUPLES_OK) { if (tmp_res) { PQclear(tmp_res); } smart_str_free(&querystr); smart_str_free(&hash_key); RETURN_FALSE; } smart_str_free(&querystr); if ((table_name = PQgetvalue(tmp_res, 0, 0)) == NULL) { PQclear(tmp_res); smart_str_free(&hash_key); RETURN_FALSE; } new_field_table.type = le_string; new_field_table.ptr = estrdup(table_name); zend_hash_update_mem(&EG(regular_list), hash_key.s, (void *)&new_field_table, sizeof(zend_resource)); smart_str_free(&hash_key); PQclear(tmp_res); RETURN_STRING(table_name); } } /* }}} */ #endif #define PHP_PG_FIELD_NAME 1 #define PHP_PG_FIELD_SIZE 2 #define PHP_PG_FIELD_TYPE 3 #define PHP_PG_FIELD_TYPE_OID 4 /* {{{ php_pgsql_get_field_info */ static void php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result; zend_long field; PGresult *pgsql_result; pgsql_result_handle *pg_result; Oid oid; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &result, &field) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (field < 0 || field >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Bad field offset specified"); RETURN_FALSE; } switch (entry_type) { case PHP_PG_FIELD_NAME: RETURN_STRING(PQfname(pgsql_result, (int)field)); break; case PHP_PG_FIELD_SIZE: RETURN_LONG(PQfsize(pgsql_result, (int)field)); break; case PHP_PG_FIELD_TYPE: { char *name = get_field_name(pg_result->conn, PQftype(pgsql_result, (int)field), &EG(regular_list)); RETVAL_STRING(name); efree(name); } break; case PHP_PG_FIELD_TYPE_OID: oid = PQftype(pgsql_result, (int)field); #if UINT_MAX > ZEND_LONG_MAX if (oid > ZEND_LONG_MAX) { smart_str s = {0}; smart_str_append_unsigned(&s, oid); smart_str_0(&s); RETURN_NEW_STR(s.s); } else #endif { RETURN_LONG((zend_long)oid); } break; default: RETURN_FALSE; } } /* }}} */ /* {{{ proto string pg_field_name(resource result, int field_number) Returns the name of the field */ PHP_FUNCTION(pg_field_name) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_NAME); } /* }}} */ /* {{{ proto int pg_field_size(resource result, int field_number) Returns the internal size of the field */ PHP_FUNCTION(pg_field_size) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_SIZE); } /* }}} */ /* {{{ proto string pg_field_type(resource result, int field_number) Returns the type name for the given field */ PHP_FUNCTION(pg_field_type) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE); } /* }}} */ /* {{{ proto string pg_field_type_oid(resource result, int field_number) Returns the type oid for the given field */ PHP_FUNCTION(pg_field_type_oid) { php_pgsql_get_field_info(INTERNAL_FUNCTION_PARAM_PASSTHRU,PHP_PG_FIELD_TYPE_OID); } /* }}} */ /* {{{ proto int pg_field_num(resource result, string field_name) Returns the field number of the named field */ PHP_FUNCTION(pg_field_num) { zval *result; char *field; size_t field_len; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &result, &field, &field_len) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; RETURN_LONG(PQfnumber(pgsql_result, field)); } /* }}} */ /* {{{ proto mixed pg_fetch_result(resource result, [int row_number,] mixed field_name) Returns values from a result identifier */ PHP_FUNCTION(pg_fetch_result) { zval *result, *field=NULL; zend_long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc, "rz", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc, "rlz", &result, &row, &field) == FAILURE) { return; } } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Unable to jump to row " ZEND_LONG_FMT " on PostgreSQL result index " ZEND_LONG_FMT, row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; } switch (Z_TYPE_P(field)) { case IS_STRING: field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field)); if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } break; default: convert_to_long_ex(field); if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } field_offset = (int)Z_LVAL_P(field); break; } if (PQgetisnull(pgsql_result, pgsql_row, field_offset)) { RETVAL_NULL(); } else { RETVAL_STRINGL(PQgetvalue(pgsql_result, pgsql_row, field_offset), PQgetlength(pgsql_result, pgsql_row, field_offset)); } } /* }}} */ /* {{{ void php_pgsql_fetch_hash */ static void php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, zend_long result_type, int into_object) { zval *result, *zrow = NULL; PGresult *pgsql_result; pgsql_result_handle *pg_result; int i, num_fields, pgsql_row, use_row; zend_long row = -1; char *field_name; zval *ctor_params = NULL; zend_class_entry *ce = NULL; if (into_object) { zend_string *class_name = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|z!Sz", &result, &zrow, &class_name, &ctor_params) == FAILURE) { return; } if (!class_name) { ce = zend_standard_class_def; } else { ce = zend_fetch_class(class_name, ZEND_FETCH_CLASS_AUTO); } if (!ce) { php_error_docref(NULL, E_WARNING, "Could not find class '%s'", ZSTR_VAL(class_name)); return; } result_type = PGSQL_ASSOC; } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|z!l", &result, &zrow, &result_type) == FAILURE) { return; } } if (zrow == NULL) { row = -1; } else { convert_to_long(zrow); row = Z_LVAL_P(zrow); if (row < 0) { php_error_docref(NULL, E_WARNING, "The row parameter must be greater or equal to zero"); RETURN_FALSE; } } use_row = ZEND_NUM_ARGS() > 1 && row != -1; if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, "Invalid result type"); RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (use_row) { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Unable to jump to row " ZEND_LONG_FMT " on PostgreSQL result index " ZEND_LONG_FMT, row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; pg_result->row = pgsql_row; } else { /* If 2nd param is NULL, use internal row counter to access next row */ pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } pg_result->row++; } array_init(return_value); for (i = 0, num_fields = PQnfields(pgsql_result); i < num_fields; i++) { if (PQgetisnull(pgsql_result, pgsql_row, i)) { if (result_type & PGSQL_NUM) { add_index_null(return_value, i); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_null(return_value, field_name); } } else { char *element = PQgetvalue(pgsql_result, pgsql_row, i); if (element) { const size_t element_len = strlen(element); if (result_type & PGSQL_NUM) { add_index_stringl(return_value, i, element, element_len); } if (result_type & PGSQL_ASSOC) { field_name = PQfname(pgsql_result, i); add_assoc_stringl(return_value, field_name, element, element_len); } } } } if (into_object) { zval dataset; zend_fcall_info fci; zend_fcall_info_cache fcc; zval retval; ZVAL_COPY_VALUE(&dataset, return_value); object_and_properties_init(return_value, ce, NULL); if (!ce->default_properties_count && !ce->__set) { Z_OBJ_P(return_value)->properties = Z_ARR(dataset); } else { zend_merge_properties(return_value, Z_ARRVAL(dataset)); zval_ptr_dtor(&dataset); } if (ce->constructor) { fci.size = sizeof(fci); ZVAL_UNDEF(&fci.function_name); fci.object = Z_OBJ_P(return_value); fci.retval = &retval; fci.params = NULL; fci.param_count = 0; fci.no_separation = 1; if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) { if (zend_fcall_info_args(&fci, ctor_params) == FAILURE) { /* Two problems why we throw exceptions here: PHP is typeless * and hence passing one argument that's not an array could be * by mistake and the other way round is possible, too. The * single value is an array. Also we'd have to make that one * argument passed by reference. */ zend_throw_exception(zend_ce_exception, "Parameter ctor_params must be an array", 0); return; } } fcc.function_handler = ce->constructor; fcc.called_scope = Z_OBJCE_P(return_value); fcc.object = Z_OBJ_P(return_value); if (zend_call_function(&fci, &fcc) == FAILURE) { zend_throw_exception_ex(zend_ce_exception, 0, "Could not execute %s::%s()", ZSTR_VAL(ce->name), ZSTR_VAL(ce->constructor->common.function_name)); } else { zval_ptr_dtor(&retval); } if (fci.params) { efree(fci.params); } } else if (ctor_params) { zend_throw_exception_ex(zend_ce_exception, 0, "Class %s does not have a constructor hence you cannot use ctor_params", ZSTR_VAL(ce->name)); } } } /* }}} */ /* {{{ proto array pg_fetch_row(resource result [, int row [, int result_type]]) Get a row as an enumerated array */ PHP_FUNCTION(pg_fetch_row) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_NUM, 0); } /* }}} */ /* {{{ proto array pg_fetch_assoc(resource result [, int row]) Fetch a row as an assoc array */ PHP_FUNCTION(pg_fetch_assoc) { /* pg_fetch_assoc() is added from PHP 4.3.0. It should raise error, when there is 3rd parameter */ if (ZEND_NUM_ARGS() > 2) WRONG_PARAM_COUNT; php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 0); } /* }}} */ /* {{{ proto array pg_fetch_array(resource result [, int row [, int result_type]]) Fetch a row as an array */ PHP_FUNCTION(pg_fetch_array) { php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_BOTH, 0); } /* }}} */ /* {{{ proto object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]]) Fetch a row as an object */ PHP_FUNCTION(pg_fetch_object) { /* pg_fetch_object() allowed result_type used to be. 3rd parameter must be allowed for compatibility */ php_pgsql_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, PGSQL_ASSOC, 1); } /* }}} */ /* {{{ proto array pg_fetch_all(resource result [, int result_type]) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all) { zval *result; long result_type = PGSQL_ASSOC; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &result, &result_type) == FAILURE) { return; } if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, "Invalid result type"); RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; array_init(return_value); if (php_pgsql_result2array(pgsql_result, return_value, result_type) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ /* {{{ proto array pg_fetch_all_columns(resource result [, int column_number]) Fetch all rows into array */ PHP_FUNCTION(pg_fetch_all_columns) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; zend_long colno=0; int pg_numrows, pg_row; size_t num_fields; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &result, &colno) == FAILURE) { RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; num_fields = PQnfields(pgsql_result); if (colno >= (zend_long)num_fields || colno < 0) { php_error_docref(NULL, E_WARNING, "Invalid column number '" ZEND_LONG_FMT "'", colno); RETURN_FALSE; } array_init(return_value); if ((pg_numrows = PQntuples(pgsql_result)) <= 0) { return; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { if (PQgetisnull(pgsql_result, pg_row, (int)colno)) { add_next_index_null(return_value); } else { add_next_index_string(return_value, PQgetvalue(pgsql_result, pg_row, (int)colno)); } } } /* }}} */ /* {{{ proto bool pg_result_seek(resource result, int offset) Set internal row offset */ PHP_FUNCTION(pg_result_seek) { zval *result; zend_long row; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &result, &row) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } if (row < 0 || row >= PQntuples(pg_result->result)) { RETURN_FALSE; } /* seek to offset */ pg_result->row = (int)row; RETURN_TRUE; } /* }}} */ #define PHP_PG_DATA_LENGTH 1 #define PHP_PG_DATA_ISNULL 2 /* {{{ php_pgsql_data_info */ static void php_pgsql_data_info(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *result, *field; zend_long row; PGresult *pgsql_result; pgsql_result_handle *pg_result; int field_offset, pgsql_row, argc = ZEND_NUM_ARGS(); if (argc == 2) { if (zend_parse_parameters(argc, "rz", &result, &field) == FAILURE) { return; } } else { if (zend_parse_parameters(argc, "rlz", &result, &row, &field) == FAILURE) { return; } } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (argc == 2) { if (pg_result->row < 0) { pg_result->row = 0; } pgsql_row = pg_result->row; if (pgsql_row < 0 || pgsql_row >= PQntuples(pgsql_result)) { RETURN_FALSE; } } else { if (row < 0 || row >= PQntuples(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Unable to jump to row " ZEND_LONG_FMT " on PostgreSQL result index " ZEND_LONG_FMT, row, Z_LVAL_P(result)); RETURN_FALSE; } pgsql_row = (int)row; } switch (Z_TYPE_P(field)) { case IS_STRING: convert_to_string_ex(field); field_offset = PQfnumber(pgsql_result, Z_STRVAL_P(field)); if (field_offset < 0 || field_offset >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } break; default: convert_to_long_ex(field); if (Z_LVAL_P(field) < 0 || Z_LVAL_P(field) >= PQnfields(pgsql_result)) { php_error_docref(NULL, E_WARNING, "Bad column offset specified"); RETURN_FALSE; } field_offset = (int)Z_LVAL_P(field); break; } switch (entry_type) { case PHP_PG_DATA_LENGTH: RETVAL_LONG(PQgetlength(pgsql_result, pgsql_row, field_offset)); break; case PHP_PG_DATA_ISNULL: RETVAL_LONG(PQgetisnull(pgsql_result, pgsql_row, field_offset)); break; } } /* }}} */ /* {{{ proto int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number) Returns the printed length */ PHP_FUNCTION(pg_field_prtlen) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_LENGTH); } /* }}} */ /* {{{ proto int pg_field_is_null(resource result, [int row,] mixed field_name_or_number) Test if a field is NULL */ PHP_FUNCTION(pg_field_is_null) { php_pgsql_data_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_DATA_ISNULL); } /* }}} */ /* {{{ proto bool pg_free_result(resource result) Free result memory */ PHP_FUNCTION(pg_free_result) { zval *result; pgsql_result_handle *pg_result; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } zend_list_close(Z_RES_P(result)); RETURN_TRUE; } /* }}} */ /* {{{ proto string pg_last_oid(resource result) Returns the last object identifier */ PHP_FUNCTION(pg_last_oid) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; #ifdef HAVE_PQOIDVALUE Oid oid; #endif if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) == FAILURE) { return; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; #ifdef HAVE_PQOIDVALUE oid = PQoidValue(pgsql_result); if (oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(oid); #else Z_STRVAL_P(return_value) = (char *) PQoidStatus(pgsql_result); if (Z_STRVAL_P(return_value)) { RETURN_STRING(Z_STRVAL_P(return_value)); } RETURN_EMPTY_STRING(); #endif } /* }}} */ /* {{{ proto bool pg_trace(string filename [, string mode [, resource connection]]) Enable tracing a PostgreSQL connection */ PHP_FUNCTION(pg_trace) { char *z_filename, *mode = "w"; size_t z_filename_len, mode_len; zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; FILE *fp = NULL; php_stream *stream; zend_resource *link; if (zend_parse_parameters(argc, "p|sr", &z_filename, &z_filename_len, &mode, &mode_len, &pgsql_link) == FAILURE) { return; } if (argc < 3) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } stream = php_stream_open_wrapper(z_filename, mode, REPORT_ERRORS, NULL); if (!stream) { RETURN_FALSE; } if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_STDIO, (void**)&fp, REPORT_ERRORS)) { php_stream_close(stream); RETURN_FALSE; } php_stream_auto_cleanup(stream); PQtrace(pgsql, fp); RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_untrace([resource connection]) Disable tracing of a PostgreSQL connection */ PHP_FUNCTION(pg_untrace) { zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; zend_resource *link; if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } PQuntrace(pgsql); RETURN_TRUE; } /* }}} */ /* {{{ proto mixed pg_lo_create([resource connection],[mixed large_object_oid]) Create a large object */ PHP_FUNCTION(pg_lo_create) { zval *pgsql_link = NULL, *oid = NULL; PGconn *pgsql; Oid pgsql_oid, wanted_oid = InvalidOid; int argc = ZEND_NUM_ARGS(); zend_resource *link; if (zend_parse_parameters(argc, "|zz", &pgsql_link, &oid) == FAILURE) { return; } if ((argc == 1) && (Z_TYPE_P(pgsql_link) != IS_RESOURCE)) { oid = pgsql_link; pgsql_link = NULL; } if (pgsql_link == NULL) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else if ((Z_TYPE_P(pgsql_link) == IS_RESOURCE)) { link = Z_RES_P(pgsql_link); } else { link = NULL; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (oid) { #ifndef HAVE_PG_LO_CREATE php_error_docref(NULL, E_NOTICE, "Passing OID value is not supported. Upgrade your PostgreSQL"); #else switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } if ((pgsql_oid = lo_create(pgsql, wanted_oid)) == InvalidOid) { php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); #endif } if ((pgsql_oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == InvalidOid) { php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } PGSQL_RETURN_OID(pgsql_oid); } /* }}} */ /* {{{ proto bool pg_lo_unlink([resource connection,] string large_object_oid) Delete a large object */ PHP_FUNCTION(pg_lo_unlink) { zval *pgsql_link = NULL; zend_long oid_long; char *oid_string, *end_ptr; size_t oid_strlen; PGconn *pgsql; Oid oid; zend_resource *link; int argc = ZEND_NUM_ARGS(); /* accept string type since Oid type is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rs", &pgsql_link, &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rl", &pgsql_link, &oid_long) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "s", &oid_string, &oid_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "l", &oid_long) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID is specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { php_error_docref(NULL, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (lo_unlink(pgsql, oid) == -1) { php_error_docref(NULL, E_WARNING, "Unable to delete PostgreSQL large object %u", oid); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto resource pg_lo_open([resource connection,] int large_object_oid, string mode) Open a large object and return fd */ PHP_FUNCTION(pg_lo_open) { zval *pgsql_link = NULL; zend_long oid_long; char *oid_string, *end_ptr, *mode_string; size_t oid_strlen, mode_strlen; PGconn *pgsql; Oid oid; int pgsql_mode=0, pgsql_lofd; int create = 0; pgLofp *pgsql_lofp; int argc = ZEND_NUM_ARGS(); zend_resource *link; /* accept string type since Oid is unsigned int */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rss", &pgsql_link, &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rls", &pgsql_link, &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "ss", &oid_string, &oid_strlen, &mode_string, &mode_strlen) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "ls", &oid_long, &mode_string, &mode_strlen) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { php_error_docref(NULL, E_WARNING, "Requires 1 or 2 arguments"); RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } /* r/w/+ is little bit more PHP-like than INV_READ/INV_WRITE and a lot of faster to type. Unfortunately, doesn't behave the same way as fopen()... (Jouni) */ if (strchr(mode_string, 'r') == mode_string) { pgsql_mode |= INV_READ; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_WRITE; } } if (strchr(mode_string, 'w') == mode_string) { pgsql_mode |= INV_WRITE; create = 1; if (strchr(mode_string, '+') == mode_string+1) { pgsql_mode |= INV_READ; } } pgsql_lofp = (pgLofp *) emalloc(sizeof(pgLofp)); if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (create) { if ((oid = lo_creat(pgsql, INV_READ|INV_WRITE)) == 0) { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, "Unable to create PostgreSQL large object"); RETURN_FALSE; } else { if ((pgsql_lofd = lo_open(pgsql, oid, pgsql_mode)) == -1) { if (lo_unlink(pgsql, oid) == -1) { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, "Something is really messed up! Your database is badly corrupted in a way NOT related to PHP"); RETURN_FALSE; } efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; RETURN_RES(zend_register_resource(pgsql_lofp, le_lofp)); } } } else { efree(pgsql_lofp); php_error_docref(NULL, E_WARNING, "Unable to open PostgreSQL large object"); RETURN_FALSE; } } else { pgsql_lofp->conn = pgsql; pgsql_lofp->lofd = pgsql_lofd; RETURN_RES(zend_register_resource(pgsql_lofp, le_lofp)); } } /* }}} */ /* {{{ proto bool pg_lo_close(resource large_object) Close a large object */ PHP_FUNCTION(pg_lo_close) { zval *pgsql_lofp; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_lofp) == FAILURE) { return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_lofp), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } if (lo_close((PGconn *)pgsql->conn, pgsql->lofd) < 0) { php_error_docref(NULL, E_WARNING, "Unable to close PostgreSQL large object descriptor %d", pgsql->lofd); RETVAL_FALSE; } else { RETVAL_TRUE; } zend_list_close(Z_RES_P(pgsql_lofp)); return; } /* }}} */ #define PGSQL_LO_READ_BUF_SIZE 8192 /* {{{ proto string pg_lo_read(resource large_object [, int len]) Read a large object */ PHP_FUNCTION(pg_lo_read) { zval *pgsql_id; zend_long len; size_t buf_len = PGSQL_LO_READ_BUF_SIZE; int nbytes, argc = ZEND_NUM_ARGS(); zend_string *buf; pgLofp *pgsql; if (zend_parse_parameters(argc, "r|l", &pgsql_id, &len) == FAILURE) { return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } if (argc > 1) { buf_len = len < 0 ? 0 : len; } buf = zend_string_alloc(buf_len, 0); if ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, ZSTR_VAL(buf), ZSTR_LEN(buf)))<0) { zend_string_efree(buf); RETURN_FALSE; } ZSTR_LEN(buf) = nbytes; ZSTR_VAL(buf)[ZSTR_LEN(buf)] = '\0'; RETURN_NEW_STR(buf); } /* }}} */ /* {{{ proto int pg_lo_write(resource large_object, string buf [, int len]) Write a large object */ PHP_FUNCTION(pg_lo_write) { zval *pgsql_id; char *str; zend_long z_len; size_t str_len, nbytes; size_t len; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rs|l", &pgsql_id, &str, &str_len, &z_len) == FAILURE) { return; } if (argc > 2) { if (z_len > (zend_long)str_len) { php_error_docref(NULL, E_WARNING, "Cannot write more than buffer size %zu. Tried to write " ZEND_LONG_FMT, str_len, z_len); RETURN_FALSE; } if (z_len < 0) { php_error_docref(NULL, E_WARNING, "Buffer size must be larger than 0, but " ZEND_LONG_FMT " was specified", z_len); RETURN_FALSE; } len = z_len; } else { len = str_len; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } if ((nbytes = lo_write((PGconn *)pgsql->conn, pgsql->lofd, str, len)) == (size_t)-1) { RETURN_FALSE; } RETURN_LONG(nbytes); } /* }}} */ /* {{{ proto int pg_lo_read_all(resource large_object) Read a large object and send straight to browser */ PHP_FUNCTION(pg_lo_read_all) { zval *pgsql_id; int tbytes; volatile int nbytes; char buf[PGSQL_LO_READ_BUF_SIZE]; pgLofp *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_id) == FAILURE) { return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } tbytes = 0; while ((nbytes = lo_read((PGconn *)pgsql->conn, pgsql->lofd, buf, PGSQL_LO_READ_BUF_SIZE))>0) { PHPWRITE(buf, nbytes); tbytes += nbytes; } RETURN_LONG(tbytes); } /* }}} */ /* {{{ proto int pg_lo_import([resource connection, ] string filename [, mixed oid]) Import large object direct from filesystem */ PHP_FUNCTION(pg_lo_import) { zval *pgsql_link = NULL, *oid = NULL; char *file_in; size_t name_len; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; Oid returned_oid; zend_resource *link; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rp|z", &pgsql_link, &file_in, &name_len, &oid) == SUCCESS) { link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "p|z", &file_in, &name_len, &oid) == SUCCESS) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } /* old calling convention, deprecated since PHP 4.2 */ else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "pr", &file_in, &name_len, &pgsql_link ) == SUCCESS) { php_error_docref(NULL, E_NOTICE, "Old API is used"); link = Z_RES_P(pgsql_link); } else { WRONG_PARAM_COUNT; } if (php_check_open_basedir(file_in)) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (oid) { #ifndef HAVE_PG_LO_IMPORT_WITH_OID php_error_docref(NULL, E_NOTICE, "OID value passing not supported"); #else Oid wanted_oid; switch (Z_TYPE_P(oid)) { case IS_STRING: { char *end_ptr; wanted_oid = (Oid)strtoul(Z_STRVAL_P(oid), &end_ptr, 10); if ((Z_STRVAL_P(oid)+Z_STRLEN_P(oid)) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } } break; case IS_LONG: if (Z_LVAL_P(oid) < (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } wanted_oid = (Oid)Z_LVAL_P(oid); break; default: php_error_docref(NULL, E_NOTICE, "invalid OID value passed"); RETURN_FALSE; } returned_oid = lo_import_with_oid(pgsql, file_in, wanted_oid); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); #endif } returned_oid = lo_import(pgsql, file_in); if (returned_oid == InvalidOid) { RETURN_FALSE; } PGSQL_RETURN_OID(returned_oid); } /* }}} */ /* {{{ proto bool pg_lo_export([resource connection, ] int objoid, string filename) Export large object direct to filesystem */ PHP_FUNCTION(pg_lo_export) { zval *pgsql_link = NULL; char *file_out, *oid_string, *end_ptr; size_t oid_strlen; size_t name_len; zend_long oid_long; Oid oid; PGconn *pgsql; int argc = ZEND_NUM_ARGS(); zend_resource *link; /* allow string to handle large OID value correctly */ if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rlp", &pgsql_link, &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "rss", &pgsql_link, &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "lp", &oid_long, &file_out, &name_len) == SUCCESS) { if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "sp", &oid_string, &oid_strlen, &file_out, &name_len) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "spr", &oid_string, &oid_strlen, &file_out, &name_len, &pgsql_link) == SUCCESS) { oid = (Oid)strtoul(oid_string, &end_ptr, 10); if ((oid_string+oid_strlen) != end_ptr) { /* wrong integer format */ php_error_docref(NULL, E_NOTICE, "Wrong OID value passed"); RETURN_FALSE; } link = Z_RES_P(pgsql_link); } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, argc, "lpr", &oid_long, &file_out, &name_len, &pgsql_link) == SUCCESS) { php_error_docref(NULL, E_NOTICE, "Old API is used"); if (oid_long <= (zend_long)InvalidOid) { php_error_docref(NULL, E_NOTICE, "Invalid OID specified"); RETURN_FALSE; } oid = (Oid)oid_long; link = Z_RES_P(pgsql_link); } else { php_error_docref(NULL, E_WARNING, "Requires 2 or 3 arguments"); RETURN_FALSE; } if (php_check_open_basedir(file_out)) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (lo_export(pgsql, oid, file_out) == -1) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_lo_seek(resource large_object, int offset [, int whence]) Seeks position of large object */ PHP_FUNCTION(pg_lo_seek) { zval *pgsql_id = NULL; zend_long result, offset = 0, whence = SEEK_CUR; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rl|l", &pgsql_id, &offset, &whence) == FAILURE) { return; } if (whence != SEEK_SET && whence != SEEK_CUR && whence != SEEK_END) { php_error_docref(NULL, E_WARNING, "Invalid whence parameter"); return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { result = lo_lseek64((PGconn *)pgsql->conn, pgsql->lofd, offset, (int)whence); } else { result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, (int)offset, (int)whence); } #else result = lo_lseek((PGconn *)pgsql->conn, pgsql->lofd, offset, whence); #endif if (result > -1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto int pg_lo_tell(resource large_object) Returns current position of large object */ PHP_FUNCTION(pg_lo_tell) { zval *pgsql_id = NULL; zend_long offset = 0; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "r", &pgsql_id) == FAILURE) { return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { offset = lo_tell64((PGconn *)pgsql->conn, pgsql->lofd); } else { offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); } #else offset = lo_tell((PGconn *)pgsql->conn, pgsql->lofd); #endif RETURN_LONG(offset); } /* }}} */ #if HAVE_PG_LO_TRUNCATE /* {{{ proto bool pg_lo_truncate(resource large_object, int size) Truncate large object to size */ PHP_FUNCTION(pg_lo_truncate) { zval *pgsql_id = NULL; size_t size; pgLofp *pgsql; int argc = ZEND_NUM_ARGS(); int result; if (zend_parse_parameters(argc, "rl", &pgsql_id, &size) == FAILURE) { return; } if ((pgsql = (pgLofp *)zend_fetch_resource(Z_RES_P(pgsql_id), "PostgreSQL large object", le_lofp)) == NULL) { RETURN_FALSE; } #if HAVE_PG_LO64 if (PQserverVersion((PGconn *)pgsql->conn) >= 90300) { result = lo_truncate64((PGconn *)pgsql->conn, pgsql->lofd, size); } else { result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size); } #else result = lo_truncate((PGconn *)pgsql->conn, pgsql->lofd, size); #endif if (!result) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ #endif #if HAVE_PQSETERRORVERBOSITY /* {{{ proto int pg_set_error_verbosity([resource connection,] int verbosity) Set error verbosity */ PHP_FUNCTION(pg_set_error_verbosity) { zval *pgsql_link = NULL; zend_long verbosity; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; zend_resource *link; if (argc == 1) { if (zend_parse_parameters(argc, "l", &verbosity) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rl", &pgsql_link, &verbosity) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (verbosity & (PQERRORS_TERSE|PQERRORS_DEFAULT|PQERRORS_VERBOSE)) { RETURN_LONG(PQsetErrorVerbosity(pgsql, verbosity)); } else { RETURN_FALSE; } } /* }}} */ #endif #ifdef HAVE_PQCLIENTENCODING /* {{{ proto int pg_set_client_encoding([resource connection,] string encoding) Set client encoding */ PHP_FUNCTION(pg_set_client_encoding) { char *encoding; size_t encoding_len; zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; zend_resource *link; if (argc == 1) { if (zend_parse_parameters(argc, "s", &encoding, &encoding_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rs", &pgsql_link, &encoding, &encoding_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } RETURN_LONG(PQsetClientEncoding(pgsql, encoding)); } /* }}} */ /* {{{ proto string pg_client_encoding([resource connection]) Get the current client encoding */ PHP_FUNCTION(pg_client_encoding) { zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; zend_resource *link; if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } /* Just do the same as found in PostgreSQL sources... */ RETURN_STRING((char *) pg_encoding_to_char(PQclientEncoding(pgsql))); } /* }}} */ #endif #if !HAVE_PQGETCOPYDATA #define COPYBUFSIZ 8192 #endif /* {{{ proto bool pg_end_copy([resource connection]) Sync with backend. Completes the Copy command */ PHP_FUNCTION(pg_end_copy) { zval *pgsql_link = NULL; int argc = ZEND_NUM_ARGS(); PGconn *pgsql; int result = 0; zend_resource *link; if (zend_parse_parameters(argc, "|r", &pgsql_link) == FAILURE) { return; } if (argc == 0) { link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } result = PQendcopy(pgsql); if (result!=0) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool pg_put_line([resource connection,] string query) Send null-terminated string to backend server*/ PHP_FUNCTION(pg_put_line) { char *query; zval *pgsql_link = NULL; size_t query_len; PGconn *pgsql; zend_resource *link; int result = 0, argc = ZEND_NUM_ARGS(); if (argc == 1) { if (zend_parse_parameters(argc, "s", &query, &query_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); } else { if (zend_parse_parameters(argc, "rs", &pgsql_link, &query, &query_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } result = PQputline(pgsql, query); if (result==EOF) { PHP_PQ_ERROR("Query failed: %s", pgsql); RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]]) Copy table to array */ PHP_FUNCTION(pg_copy_to) { zval *pgsql_link; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; size_t table_name_len, pg_delim_len, pg_null_as_len, free_pg_null = 0; char *query; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; char *csv = (char *)NULL; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rs|ss", &pgsql_link, &table_name, &table_name_len, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (!pg_delim) { pg_delim = "\t"; } if (!pg_null_as) { pg_null_as = estrdup("\\\\N"); free_pg_null = 1; } spprintf(&query, 0, "COPY %s TO STDOUT DELIMITER E'%c' NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (free_pg_null) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_OUT: if (pgsql_result) { int copydone = 0; #if !HAVE_PQGETCOPYDATA char copybuf[COPYBUFSIZ]; #endif PQclear(pgsql_result); array_init(return_value); #if HAVE_PQGETCOPYDATA while (!copydone) { int ret = PQgetCopyData(pgsql, &csv, 0); switch (ret) { case -1: copydone = 1; break; case 0: case -2: PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; break; default: add_next_index_string(return_value, csv); PQfreemem(csv); break; } } #else while (!copydone) { if ((ret = PQgetline(pgsql, copybuf, COPYBUFSIZ))) { PHP_PQ_ERROR("getline failed: %s", pgsql); RETURN_FALSE; } if (copybuf[0] == '\\' && copybuf[1] == '.' && copybuf[2] == '\0') { copydone = 1; } else { if (csv == (char *)NULL) { csv = estrdup(copybuf); } else { csv = (char *)erealloc(csv, strlen(csv) + sizeof(char)*(COPYBUFSIZ+1)); strcat(csv, copybuf); } switch (ret) { case EOF: copydone = 1; case 0: add_next_index_string(return_value, csv); efree(csv); csv = (char *)NULL; break; case 1: break; } } } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } } else { PQclear(pgsql_result); RETURN_FALSE; } break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ /* {{{ proto bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]]) Copy table from array */ PHP_FUNCTION(pg_copy_from) { zval *pgsql_link = NULL, *pg_rows; zval *value; char *table_name, *pg_delim = NULL, *pg_null_as = NULL; size_t table_name_len, pg_delim_len, pg_null_as_len; int pg_null_as_free = 0; char *query; PGconn *pgsql; PGresult *pgsql_result; ExecStatusType status; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsa|ss", &pgsql_link, &table_name, &table_name_len, &pg_rows, &pg_delim, &pg_delim_len, &pg_null_as, &pg_null_as_len) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (!pg_delim) { pg_delim = "\t"; } if (!pg_null_as) { pg_null_as = estrdup("\\\\N"); pg_null_as_free = 1; } spprintf(&query, 0, "COPY %s FROM STDIN DELIMITER E'%c' NULL AS E'%s'", table_name, *pg_delim, pg_null_as); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } pgsql_result = PQexec(pgsql, query); if (pg_null_as_free) { efree(pg_null_as); } efree(query); if (pgsql_result) { status = PQresultStatus(pgsql_result); } else { status = (ExecStatusType) PQstatus(pgsql); } switch (status) { case PGRES_COPY_IN: if (pgsql_result) { int command_failed = 0; PQclear(pgsql_result); #if HAVE_PQPUTCOPYDATA ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), value) { zval tmp; ZVAL_COPY(&tmp, value); convert_to_string_ex(&tmp); query = (char *)emalloc(Z_STRLEN(tmp) + 2); strlcpy(query, Z_STRVAL(tmp), Z_STRLEN(tmp) + 2); if(Z_STRLEN(tmp) > 0 && *(query + Z_STRLEN(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN(tmp) + 2); } if (PQputCopyData(pgsql, query, (int)strlen(query)) != 1) { efree(query); zval_dtor(&tmp); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zval_dtor(&tmp); } ZEND_HASH_FOREACH_END(); if (PQputCopyEnd(pgsql, NULL) != 1) { PHP_PQ_ERROR("putcopyend failed: %s", pgsql); RETURN_FALSE; } #else ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pg_rows), value) { zval tmp; ZVAL_COPY(&tmp, value); convert_to_string_ex(&tmp); query = (char *)emalloc(Z_STRLEN(tmp) + 2); strlcpy(query, Z_STRVAL(tmp), Z_STRLEN(tmp) + 2); if(Z_STRLEN(tmp) > 0 && *(query + Z_STRLEN(tmp) - 1) != '\n') { strlcat(query, "\n", Z_STRLEN(tmp) + 2); } if (PQputline(pgsql, query)==EOF) { efree(query); zval_dtor(&tmp); PHP_PQ_ERROR("copy failed: %s", pgsql); RETURN_FALSE; } efree(query); zval_dtor(&tmp); } ZEND_HASH_FOREACH_END(); if (PQputline(pgsql, "\\.\n") == EOF) { PHP_PQ_ERROR("putline failed: %s", pgsql); RETURN_FALSE; } if (PQendcopy(pgsql)) { PHP_PQ_ERROR("endcopy failed: %s", pgsql); RETURN_FALSE; } #endif while ((pgsql_result = PQgetResult(pgsql))) { if (PGRES_COMMAND_OK != PQresultStatus(pgsql_result)) { PHP_PQ_ERROR("Copy command failed: %s", pgsql); command_failed = 1; } PQclear(pgsql_result); } if (command_failed) { RETURN_FALSE; } } else { PQclear(pgsql_result); RETURN_FALSE; } RETURN_TRUE; break; default: PQclear(pgsql_result); PHP_PQ_ERROR("Copy command failed: %s", pgsql); RETURN_FALSE; break; } } /* }}} */ #ifdef HAVE_PQESCAPE /* {{{ proto string pg_escape_string([resource connection,] string data) Escape string for text/char type */ PHP_FUNCTION(pg_escape_string) { zend_string *from = NULL, *to = NULL; zval *pgsql_link; zend_resource *link; #ifdef HAVE_PQESCAPE_CONN PGconn *pgsql; #endif switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), "S", &from) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), "rS", &pgsql_link, &from) == FAILURE) { return; } link = Z_RES_P(pgsql_link); break; } to = zend_string_safe_alloc(ZSTR_LEN(from), 2, 0, 0); #ifdef HAVE_PQESCAPE_CONN if (link) { if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } ZSTR_LEN(to) = PQescapeStringConn(pgsql, ZSTR_VAL(to), ZSTR_VAL(from), ZSTR_LEN(from), NULL); } else #endif { ZSTR_LEN(to) = PQescapeString(ZSTR_VAL(to), ZSTR_VAL(from), ZSTR_LEN(from)); } to = zend_string_truncate(to, ZSTR_LEN(to), 0); RETURN_NEW_STR(to); } /* }}} */ /* {{{ proto string pg_escape_bytea([resource connection,] string data) Escape binary for bytea type */ PHP_FUNCTION(pg_escape_bytea) { char *from = NULL, *to = NULL; size_t to_len; size_t from_len; #ifdef HAVE_PQESCAPE_BYTEA_CONN PGconn *pgsql; #endif zval *pgsql_link; zend_resource *link; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &from, &from_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); break; } #ifdef HAVE_PQESCAPE_BYTEA_CONN if (link) { if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } to = (char *)PQescapeByteaConn(pgsql, (unsigned char *)from, (size_t)from_len, &to_len); } else #endif to = (char *)PQescapeBytea((unsigned char*)from, from_len, &to_len); RETVAL_STRINGL(to, to_len-1); /* to_len includes additional '\0' */ PQfreemem(to); } /* }}} */ #if !HAVE_PQUNESCAPEBYTEA /* PQunescapeBytea() from PostgreSQL 7.3 to provide bytea unescape feature to 7.2 users. Renamed to php_pgsql_unescape_bytea() */ /* * PQunescapeBytea - converts the null terminated string representation * of a bytea, strtext, into binary, filling a buffer. It returns a * pointer to the buffer which is NULL on error, and the size of the * buffer in retbuflen. The pointer may subsequently be used as an * argument to the function free(3). It is the reverse of PQescapeBytea. * * The following transformations are reversed: * '\0' == ASCII 0 == \000 * '\'' == ASCII 39 == \' * '\\' == ASCII 92 == \\ * * States: * 0 normal 0->1->2->3->4 * 1 \ 1->5 * 2 \0 1->6 * 3 \00 * 4 \000 * 5 \' * 6 \\ */ static unsigned char * php_pgsql_unescape_bytea(unsigned char *strtext, size_t *retbuflen) /* {{{ */ { size_t buflen; unsigned char *buffer, *sp, *bp; unsigned int state = 0; if (strtext == NULL) return NULL; buflen = strlen(strtext); /* will shrink, also we discover if * strtext */ buffer = (unsigned char *) emalloc(buflen); /* isn't NULL terminated */ for (bp = buffer, sp = strtext; *sp != '\0'; bp++, sp++) { switch (state) { case 0: if (*sp == '\\') state = 1; *bp = *sp; break; case 1: if (*sp == '\'') /* state=5 */ { /* replace \' with 39 */ bp--; *bp = '\''; buflen--; state = 0; } else if (*sp == '\\') /* state=6 */ { /* replace \\ with 92 */ bp--; *bp = '\\'; buflen--; state = 0; } else { if (isdigit(*sp)) state = 2; else state = 0; *bp = *sp; } break; case 2: if (isdigit(*sp)) state = 3; else state = 0; *bp = *sp; break; case 3: if (isdigit(*sp)) /* state=4 */ { unsigned char *start, *end, buf[4]; /* 000 + '\0' */ bp -= 3; memcpy(buf, sp-2, 3); buf[3] = '\0'; start = buf; *bp = (unsigned char)strtoul(start, (char **)&end, 8); buflen -= 3; state = 0; } else { *bp = *sp; state = 0; } break; } } buffer = erealloc(buffer, buflen+1); buffer[buflen] = '\0'; *retbuflen = buflen; return buffer; } /* }}} */ #endif /* {{{ proto string pg_unescape_bytea(string data) Unescape binary for bytea type */ PHP_FUNCTION(pg_unescape_bytea) { char *from = NULL, *to = NULL, *tmp = NULL; size_t to_len; size_t from_len; if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &from, &from_len) == FAILURE) { return; } #if HAVE_PQUNESCAPEBYTEA tmp = (char *)PQunescapeBytea((unsigned char*)from, &to_len); to = estrndup(tmp, to_len); PQfreemem(tmp); #else to = (char *)php_pgsql_unescape_bytea((unsigned char*)from, &to_len); #endif if (!to) { php_error_docref(NULL, E_WARNING,"Invalid parameter"); RETURN_FALSE; } RETVAL_STRINGL(to, to_len); efree(to); } /* }}} */ #endif #ifdef HAVE_PQESCAPE static void php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAMETERS, int escape_literal) /* {{{ */ { char *from = NULL; zval *pgsql_link = NULL; PGconn *pgsql; size_t from_len; char *tmp; zend_resource *link; switch (ZEND_NUM_ARGS()) { case 1: if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &from, &from_len) == FAILURE) { return; } link = FETCH_DEFAULT_LINK(); CHECK_DEFAULT_LINK(link); break; default: if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &from, &from_len) == FAILURE) { return; } link = Z_RES_P(pgsql_link); break; } if ((pgsql = (PGconn *)zend_fetch_resource2(link, "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (pgsql == NULL) { php_error_docref(NULL, E_WARNING,"Cannot get pgsql link"); RETURN_FALSE; } if (escape_literal) { tmp = PGSQLescapeLiteral(pgsql, from, (size_t)from_len); } else { tmp = PGSQLescapeIdentifier(pgsql, from, (size_t)from_len); } if (!tmp) { php_error_docref(NULL, E_WARNING,"Failed to escape"); RETURN_FALSE; } RETVAL_STRING(tmp); PGSQLfree(tmp); } /* }}} */ /* {{{ proto string pg_escape_literal([resource connection,] string data) Escape parameter as string literal (i.e. parameter) */ PHP_FUNCTION(pg_escape_literal) { php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string pg_escape_identifier([resource connection,] string data) Escape identifier (i.e. table name, field name) */ PHP_FUNCTION(pg_escape_identifier) { php_pgsql_escape_internal(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ #endif /* {{{ proto string pg_result_error(resource result) Get error message associated with result */ PHP_FUNCTION(pg_result_error) { zval *result; PGresult *pgsql_result; pgsql_result_handle *pg_result; char *err = NULL; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &result) == FAILURE) { RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (!pgsql_result) { RETURN_FALSE; } err = (char *)PQresultErrorMessage(pgsql_result); RETURN_STRING(err); } /* }}} */ #if HAVE_PQRESULTERRORFIELD /* {{{ proto string pg_result_error_field(resource result, int fieldcode) Get error message field associated with result */ PHP_FUNCTION(pg_result_error_field) { zval *result; zend_long fieldcode; PGresult *pgsql_result; pgsql_result_handle *pg_result; char *field = NULL; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "rl", &result, &fieldcode) == FAILURE) { RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (!pgsql_result) { RETURN_FALSE; } if (fieldcode & (PG_DIAG_SEVERITY|PG_DIAG_SQLSTATE|PG_DIAG_MESSAGE_PRIMARY|PG_DIAG_MESSAGE_DETAIL |PG_DIAG_MESSAGE_HINT|PG_DIAG_STATEMENT_POSITION #if PG_DIAG_INTERNAL_POSITION |PG_DIAG_INTERNAL_POSITION #endif #if PG_DIAG_INTERNAL_QUERY |PG_DIAG_INTERNAL_QUERY #endif |PG_DIAG_CONTEXT|PG_DIAG_SOURCE_FILE|PG_DIAG_SOURCE_LINE |PG_DIAG_SOURCE_FUNCTION)) { field = (char *)PQresultErrorField(pgsql_result, (int)fieldcode); if (field == NULL) { RETURN_NULL(); } else { RETURN_STRING(field); } } else { RETURN_FALSE; } } /* }}} */ #endif /* {{{ proto int pg_connection_status(resource connection) Get connection status */ PHP_FUNCTION(pg_connection_status) { zval *pgsql_link = NULL; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } RETURN_LONG(PQstatus(pgsql)); } /* }}} */ #if HAVE_PGTRANSACTIONSTATUS /* {{{ proto int pg_transaction_status(resource connection) Get transaction status */ PHP_FUNCTION(pg_transaction_status) { zval *pgsql_link = NULL; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } RETURN_LONG(PQtransactionStatus(pgsql)); } #endif /* }}} */ /* {{{ proto bool pg_connection_reset(resource connection) Reset connection (reconnect) */ PHP_FUNCTION(pg_connection_reset) { zval *pgsql_link; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } PQreset(pgsql); if (PQstatus(pgsql) == CONNECTION_BAD) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ #define PHP_PG_ASYNC_IS_BUSY 1 #define PHP_PG_ASYNC_REQUEST_CANCEL 2 /* {{{ php_pgsql_flush_query */ static int php_pgsql_flush_query(PGconn *pgsql) { PGresult *res; int leftover = 0; if (PQ_SETNONBLOCKING(pgsql, 1)) { php_error_docref(NULL, E_NOTICE,"Cannot set connection to nonblocking mode"); return -1; } while ((res = PQgetResult(pgsql))) { PQclear(res); leftover++; } PQ_SETNONBLOCKING(pgsql, 0); return leftover; } /* }}} */ /* {{{ php_pgsql_do_async */ static void php_pgsql_do_async(INTERNAL_FUNCTION_PARAMETERS, int entry_type) { zval *pgsql_link; PGconn *pgsql; PGresult *pgsql_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (PQ_SETNONBLOCKING(pgsql, 1)) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } switch(entry_type) { case PHP_PG_ASYNC_IS_BUSY: PQconsumeInput(pgsql); RETVAL_LONG(PQisBusy(pgsql)); break; case PHP_PG_ASYNC_REQUEST_CANCEL: RETVAL_LONG(PQrequestCancel(pgsql)); while ((pgsql_result = PQgetResult(pgsql))) { PQclear(pgsql_result); } break; default: php_error_docref(NULL, E_ERROR, "PostgreSQL module error, please report this error"); break; } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode"); } convert_to_boolean_ex(return_value); } /* }}} */ /* {{{ proto bool pg_cancel_query(resource connection) Cancel request */ PHP_FUNCTION(pg_cancel_query) { php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_REQUEST_CANCEL); } /* }}} */ /* {{{ proto bool pg_connection_busy(resource connection) Get connection is busy or not */ PHP_FUNCTION(pg_connection_busy) { php_pgsql_do_async(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_PG_ASYNC_IS_BUSY); } /* }}} */ static int _php_pgsql_link_has_results(PGconn *pgsql) /* {{{ */ { PGresult *result; while ((result = PQgetResult(pgsql))) { PQclear(result); return 1; } return 0; } /* }}} */ /* {{{ proto bool pg_send_query(resource connection, string query) Send asynchronous query */ PHP_FUNCTION(pg_send_query) { zval *pgsql_link; char *query; size_t len; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pgsql_link, &query, &len) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE"); } if (is_non_blocking) { if (!PQsendQuery(pgsql, query)) { RETURN_FALSE; } ret = PQflush(pgsql); } else { if (!PQsendQuery(pgsql, query)) { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQuery(pgsql, query)) { RETURN_FALSE; } } /* Wait to finish sending buffer */ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0)) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } /* }}} */ #if HAVE_PQSENDQUERYPARAMS /* {{{ proto bool pg_send_query_params(resource connection, string query, array params) Send asynchronous parameterized query */ PHP_FUNCTION(pg_send_query_params) { zval *pgsql_link, *pv_param_arr, *tmp; int num_params = 0; char **params = NULL; char *query; size_t query_len; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa", &pgsql_link, &query, &query_len, &pv_param_arr) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zend_string *tmp_str; zend_string *str = zval_get_tmp_string(tmp, &tmp_str); params[i] = estrndup(ZSTR_VAL(str), ZSTR_LEN(str)); zend_tmp_string_release(tmp_str); } i++; } ZEND_HASH_FOREACH_END(); } if (PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); } else if (is_non_blocking) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQueryParams(pgsql, query, num_params, NULL, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } } if (is_non_blocking) { ret = PQflush(pgsql); } else { /* Wait to finish sending buffer */ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } /* }}} */ #endif #if HAVE_PQSENDPREPARE /* {{{ proto bool pg_send_prepare(resource connection, string stmtname, string query) Asynchronously prepare a query for future execution */ PHP_FUNCTION(pg_send_prepare) { zval *pgsql_link; char *query, *stmtname; size_t stmtname_len, query_len; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rss", &pgsql_link, &stmtname, &stmtname_len, &query, &query_len) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE"); } if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) { if (is_non_blocking) { RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendPrepare(pgsql, stmtname, query, 0, NULL)) { RETURN_FALSE; } } } if (is_non_blocking) { ret = PQflush(pgsql); } else { /* Wait to finish sending buffer */ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } /* }}} */ #endif #if HAVE_PQSENDQUERYPREPARED /* {{{ proto bool pg_send_execute(resource connection, string stmtname, array params) Executes prevriously prepared stmtname asynchronously */ PHP_FUNCTION(pg_send_execute) { zval *pgsql_link; zval *pv_param_arr, *tmp; int num_params = 0; char **params = NULL; char *stmtname; size_t stmtname_len; PGconn *pgsql; int is_non_blocking; int ret; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa", &pgsql_link, &stmtname, &stmtname_len, &pv_param_arr) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } if (_php_pgsql_link_has_results(pgsql)) { php_error_docref(NULL, E_NOTICE, "There are results on this connection. Call pg_get_result() until it returns FALSE"); } num_params = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr)); if (num_params > 0) { int i = 0; params = (char **)safe_emalloc(sizeof(char *), num_params, 0); ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(pv_param_arr), tmp) { if (Z_TYPE_P(tmp) == IS_NULL) { params[i] = NULL; } else { zval tmp_val; ZVAL_COPY(&tmp_val, tmp); convert_to_string(&tmp_val); if (Z_TYPE(tmp_val) != IS_STRING) { php_error_docref(NULL, E_WARNING,"Error converting parameter"); zval_ptr_dtor(&tmp_val); _php_pgsql_free_params(params, num_params); RETURN_FALSE; } params[i] = estrndup(Z_STRVAL(tmp_val), Z_STRLEN(tmp_val)); zval_ptr_dtor(&tmp_val); } i++; } ZEND_HASH_FOREACH_END(); } if (PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); } else if (is_non_blocking) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } else { if ((PGG(auto_reset_persistent) & 2) && PQstatus(pgsql) != CONNECTION_OK) { PQreset(pgsql); } if (!PQsendQueryPrepared(pgsql, stmtname, num_params, (const char * const *)params, NULL, NULL, 0)) { _php_pgsql_free_params(params, num_params); RETURN_FALSE; } } if (is_non_blocking) { ret = PQflush(pgsql); } else { /* Wait to finish sending buffer */ while ((ret = PQflush(pgsql))) { if (ret == -1) { php_error_docref(NULL, E_NOTICE, "Could not empty PostgreSQL send buffer"); break; } usleep(10000); } if (PQ_SETNONBLOCKING(pgsql, 0) != 0) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to blocking mode"); } } if (ret == 0) { RETURN_TRUE; } else if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(0); } } /* }}} */ #endif /* {{{ proto resource pg_get_result(resource connection) Get asynchronous query result */ PHP_FUNCTION(pg_get_result) { zval *pgsql_link; PGconn *pgsql; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } pgsql_result = PQgetResult(pgsql); if (!pgsql_result) { /* no result */ RETURN_FALSE; } pg_result = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pg_result->conn = pgsql; pg_result->result = pgsql_result; pg_result->row = 0; RETURN_RES(zend_register_resource(pg_result, le_result)); } /* }}} */ /* {{{ proto mixed pg_result_status(resource result[, int result_type]) Get status of query result */ PHP_FUNCTION(pg_result_status) { zval *result; zend_long result_type = PGSQL_STATUS_LONG; ExecStatusType status; PGresult *pgsql_result; pgsql_result_handle *pg_result; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l", &result, &result_type) == FAILURE) { RETURN_FALSE; } if ((pg_result = (pgsql_result_handle *)zend_fetch_resource(Z_RES_P(result), "PostgreSQL result", le_result)) == NULL) { RETURN_FALSE; } pgsql_result = pg_result->result; if (result_type == PGSQL_STATUS_LONG) { status = PQresultStatus(pgsql_result); RETURN_LONG((int)status); } else if (result_type == PGSQL_STATUS_STRING) { RETURN_STRING(PQcmdStatus(pgsql_result)); } else { php_error_docref(NULL, E_WARNING, "Optional 2nd parameter should be PGSQL_STATUS_LONG or PGSQL_STATUS_STRING"); RETURN_FALSE; } } /* }}} */ /* {{{ proto mixed pg_get_notify([resource connection[, int result_type]]) Get asynchronous notification */ PHP_FUNCTION(pg_get_notify) { zval *pgsql_link; zend_long result_type = PGSQL_ASSOC; PGconn *pgsql; PGnotify *pgsql_notify; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r|l", &pgsql_link, &result_type) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, "Invalid result type"); RETURN_FALSE; } PQconsumeInput(pgsql); pgsql_notify = PQnotifies(pgsql); if (!pgsql_notify) { /* no notify message */ RETURN_FALSE; } array_init(return_value); if (result_type & PGSQL_NUM) { add_index_string(return_value, 0, pgsql_notify->relname); add_index_long(return_value, 1, pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_index_string(return_value, 2, pgsql_notify->extra); #endif } } if (result_type & PGSQL_ASSOC) { add_assoc_string(return_value, "message", pgsql_notify->relname); add_assoc_long(return_value, "pid", pgsql_notify->be_pid); #if HAVE_PQPROTOCOLVERSION && HAVE_PQPARAMETERSTATUS if (PQprotocolVersion(pgsql) >= 3 && atof(PQparameterStatus(pgsql, "server_version")) >= 9.0) { #else if (atof(PG_VERSION) >= 9.0) { #endif #if HAVE_PQPARAMETERSTATUS add_assoc_string(return_value, "payload", pgsql_notify->extra); #endif } } PQfreemem(pgsql_notify); } /* }}} */ /* {{{ proto int pg_get_pid([resource connection) Get backend(server) pid */ PHP_FUNCTION(pg_get_pid) { zval *pgsql_link; PGconn *pgsql; if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { RETURN_FALSE; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } RETURN_LONG(PQbackendPID(pgsql)); } /* }}} */ static size_t php_pgsql_fd_write(php_stream *stream, const char *buf, size_t count) /* {{{ */ { return 0; } /* }}} */ static size_t php_pgsql_fd_read(php_stream *stream, char *buf, size_t count) /* {{{ */ { return 0; } /* }}} */ static int php_pgsql_fd_close(php_stream *stream, int close_handle) /* {{{ */ { return EOF; } /* }}} */ static int php_pgsql_fd_flush(php_stream *stream) /* {{{ */ { return FAILURE; } /* }}} */ static int php_pgsql_fd_set_option(php_stream *stream, int option, int value, void *ptrparam) /* {{{ */ { PGconn *pgsql = (PGconn *) stream->abstract; switch (option) { case PHP_STREAM_OPTION_BLOCKING: return PQ_SETNONBLOCKING(pgsql, value); default: return FAILURE; } } /* }}} */ static int php_pgsql_fd_cast(php_stream *stream, int cast_as, void **ret) /* {{{ */ { PGconn *pgsql = (PGconn *) stream->abstract; switch (cast_as) { case PHP_STREAM_AS_FD_FOR_SELECT: case PHP_STREAM_AS_FD: case PHP_STREAM_AS_SOCKETD: if (ret) { int fd_number = PQsocket(pgsql); if (fd_number == -1) { return FAILURE; } *(php_socket_t *)ret = fd_number; return SUCCESS; } default: return FAILURE; } } /* }}} */ /* {{{ proto resource pg_socket(resource connection) Get a read-only handle to the socket underlying the pgsql connection */ PHP_FUNCTION(pg_socket) { zval *pgsql_link; php_stream *stream; PGconn *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } stream = php_stream_alloc(&php_stream_pgsql_fd_ops, pgsql, NULL, "r"); if (stream) { php_stream_to_zval(stream, return_value); return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool pg_consume_input(resource connection) Reads input on the connection */ PHP_FUNCTION(pg_consume_input) { zval *pgsql_link; PGconn *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } RETURN_BOOL(PQconsumeInput(pgsql)); } /* }}} */ /* {{{ proto mixed pg_flush(resource connection) Flush outbound query data on the connection */ PHP_FUNCTION(pg_flush) { zval *pgsql_link; PGconn *pgsql; int ret; int is_non_blocking; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pgsql_link) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } is_non_blocking = PQisnonblocking(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 1) == -1) { php_error_docref(NULL, E_NOTICE, "Cannot set connection to nonblocking mode"); RETURN_FALSE; } ret = PQflush(pgsql); if (is_non_blocking == 0 && PQ_SETNONBLOCKING(pgsql, 0) == -1) { php_error_docref(NULL, E_NOTICE, "Failed resetting connection to blocking mode"); } switch (ret) { case 0: RETURN_TRUE; break; case 1: RETURN_LONG(0); break; default: RETURN_FALSE; } } /* }}} */ /* {{{ php_pgsql_meta_data * TODO: Add meta_data cache for better performance */ PHP_PGSQL_API int php_pgsql_meta_data(PGconn *pg_link, const char *table_name, zval *meta, zend_bool extended) { PGresult *pg_result; char *src, *tmp_name, *tmp_name2 = NULL; char *escaped; smart_str querystr = {0}; size_t new_len; int i, num_rows; zval elem; if (!*table_name) { php_error_docref(NULL, E_WARNING, "The table name must be specified"); return FAILURE; } src = estrdup(table_name); tmp_name = php_strtok_r(src, ".", &tmp_name2); if (!tmp_name) { efree(src); php_error_docref(NULL, E_WARNING, "The table name must be specified"); return FAILURE; } if (!tmp_name2 || !*tmp_name2) { /* Default schema */ tmp_name2 = tmp_name; tmp_name = "public"; } if (extended) { smart_str_appends(&querystr, "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotNULL, a.atthasdef, a.attndims, t.typtype, " "d.description " "FROM pg_class as c " " JOIN pg_attribute a ON (a.attrelid = c.oid) " " JOIN pg_type t ON (a.atttypid = t.oid) " " JOIN pg_namespace n ON (c.relnamespace = n.oid) " " LEFT JOIN pg_description d ON (d.objoid=a.attrelid AND d.objsubid=a.attnum AND c.oid=d.objoid) " "WHERE a.attnum > 0 AND c.relname = '"); } else { smart_str_appends(&querystr, "SELECT a.attname, a.attnum, t.typname, a.attlen, a.attnotnull, a.atthasdef, a.attndims, t.typtype " "FROM pg_class as c " " JOIN pg_attribute a ON (a.attrelid = c.oid) " " JOIN pg_type t ON (a.atttypid = t.oid) " " JOIN pg_namespace n ON (c.relnamespace = n.oid) " "WHERE a.attnum > 0 AND c.relname = '"); } escaped = (char *)safe_emalloc(strlen(tmp_name2), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name2, strlen(tmp_name2), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' AND n.nspname = '"); escaped = (char *)safe_emalloc(strlen(tmp_name), 2, 1); new_len = PQescapeStringConn(pg_link, escaped, tmp_name, strlen(tmp_name), NULL); if (new_len) { smart_str_appendl(&querystr, escaped, new_len); } efree(escaped); smart_str_appends(&querystr, "' ORDER BY a.attnum;"); smart_str_0(&querystr); efree(src); pg_result = PQexec(pg_link, ZSTR_VAL(querystr.s)); if (PQresultStatus(pg_result) != PGRES_TUPLES_OK || (num_rows = PQntuples(pg_result)) == 0) { php_error_docref(NULL, E_WARNING, "Table '%s' doesn't exists", table_name); smart_str_free(&querystr); PQclear(pg_result); return FAILURE; } smart_str_free(&querystr); for (i = 0; i < num_rows; i++) { char *name; array_init(&elem); /* pg_attribute.attnum */ add_assoc_long_ex(&elem, "num", sizeof("num") - 1, atoi(PQgetvalue(pg_result, i, 1))); /* pg_type.typname */ add_assoc_string_ex(&elem, "type", sizeof("type") - 1, PQgetvalue(pg_result, i, 2)); /* pg_attribute.attlen */ add_assoc_long_ex(&elem, "len", sizeof("len") - 1, atoi(PQgetvalue(pg_result,i,3))); /* pg_attribute.attnonull */ add_assoc_bool_ex(&elem, "not null", sizeof("not null") - 1, !strcmp(PQgetvalue(pg_result, i, 4), "t")); /* pg_attribute.atthasdef */ add_assoc_bool_ex(&elem, "has default", sizeof("has default") - 1, !strcmp(PQgetvalue(pg_result,i,5), "t")); /* pg_attribute.attndims */ add_assoc_long_ex(&elem, "array dims", sizeof("array dims") - 1, atoi(PQgetvalue(pg_result, i, 6))); /* pg_type.typtype */ add_assoc_bool_ex(&elem, "is enum", sizeof("is enum") - 1, !strcmp(PQgetvalue(pg_result, i, 7), "e")); if (extended) { /* pg_type.typtype */ add_assoc_bool_ex(&elem, "is base", sizeof("is base") - 1, !strcmp(PQgetvalue(pg_result, i, 7), "b")); add_assoc_bool_ex(&elem, "is composite", sizeof("is composite") - 1, !strcmp(PQgetvalue(pg_result, i, 7), "c")); add_assoc_bool_ex(&elem, "is pesudo", sizeof("is pesudo") - 1, !strcmp(PQgetvalue(pg_result, i, 7), "p")); /* pg_description.description */ add_assoc_string_ex(&elem, "description", sizeof("description") - 1, PQgetvalue(pg_result, i, 8)); } /* pg_attribute.attname */ name = PQgetvalue(pg_result,i,0); add_assoc_zval(meta, name, &elem); } PQclear(pg_result); return SUCCESS; } /* }}} */ /* {{{ proto array pg_meta_data(resource db, string table [, bool extended]) Get meta_data */ PHP_FUNCTION(pg_meta_data) { zval *pgsql_link; char *table_name; size_t table_name_len; zend_bool extended=0; PGconn *pgsql; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|b", &pgsql_link, &table_name, &table_name_len, &extended) == FAILURE) { return; } if ((pgsql = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } array_init(return_value); if (php_pgsql_meta_data(pgsql, table_name, return_value, extended) == FAILURE) { zval_dtor(return_value); /* destroy array */ RETURN_FALSE; } } /* }}} */ /* {{{ php_pgsql_get_data_type */ static php_pgsql_data_type php_pgsql_get_data_type(const char *type_name, size_t len) { /* This is stupid way to do. I'll fix it when I decied how to support user defined types. (Yasuo) */ /* boolean */ if (!strcmp(type_name, "bool")|| !strcmp(type_name, "boolean")) return PG_BOOL; /* object id */ if (!strcmp(type_name, "oid")) return PG_OID; /* integer */ if (!strcmp(type_name, "int2") || !strcmp(type_name, "smallint")) return PG_INT2; if (!strcmp(type_name, "int4") || !strcmp(type_name, "integer")) return PG_INT4; if (!strcmp(type_name, "int8") || !strcmp(type_name, "bigint")) return PG_INT8; /* real and other */ if (!strcmp(type_name, "float4") || !strcmp(type_name, "real")) return PG_FLOAT4; if (!strcmp(type_name, "float8") || !strcmp(type_name, "double precision")) return PG_FLOAT8; if (!strcmp(type_name, "numeric")) return PG_NUMERIC; if (!strcmp(type_name, "money")) return PG_MONEY; /* character */ if (!strcmp(type_name, "text")) return PG_TEXT; if (!strcmp(type_name, "bpchar") || !strcmp(type_name, "character")) return PG_CHAR; if (!strcmp(type_name, "varchar") || !strcmp(type_name, "character varying")) return PG_VARCHAR; /* time and interval */ if (!strcmp(type_name, "abstime")) return PG_UNIX_TIME; if (!strcmp(type_name, "reltime")) return PG_UNIX_TIME_INTERVAL; if (!strcmp(type_name, "tinterval")) return PG_UNIX_TIME_INTERVAL; if (!strcmp(type_name, "date")) return PG_DATE; if (!strcmp(type_name, "time")) return PG_TIME; if (!strcmp(type_name, "time with time zone") || !strcmp(type_name, "timetz")) return PG_TIME_WITH_TIMEZONE; if (!strcmp(type_name, "timestamp without time zone") || !strcmp(type_name, "timestamp")) return PG_TIMESTAMP; if (!strcmp(type_name, "timestamp with time zone") || !strcmp(type_name, "timestamptz")) return PG_TIMESTAMP_WITH_TIMEZONE; if (!strcmp(type_name, "interval")) return PG_INTERVAL; /* binary */ if (!strcmp(type_name, "bytea")) return PG_BYTEA; /* network */ if (!strcmp(type_name, "cidr")) return PG_CIDR; if (!strcmp(type_name, "inet")) return PG_INET; if (!strcmp(type_name, "macaddr")) return PG_MACADDR; /* bit */ if (!strcmp(type_name, "bit")) return PG_BIT; if (!strcmp(type_name, "bit varying")) return PG_VARBIT; /* geometric */ if (!strcmp(type_name, "line")) return PG_LINE; if (!strcmp(type_name, "lseg")) return PG_LSEG; if (!strcmp(type_name, "box")) return PG_BOX; if (!strcmp(type_name, "path")) return PG_PATH; if (!strcmp(type_name, "point")) return PG_POINT; if (!strcmp(type_name, "polygon")) return PG_POLYGON; if (!strcmp(type_name, "circle")) return PG_CIRCLE; return PG_UNKNOWN; } /* }}} */ /* {{{ php_pgsql_convert_match * test field value with regular expression specified. */ static int php_pgsql_convert_match(const char *str, size_t str_len, const char *regex , size_t regex_len, int icase) { pcre2_code *re; PCRE2_SIZE err_offset; int res, errnumber; uint32_t options = PCRE2_NO_AUTO_CAPTURE; size_t i; pcre2_match_data *match_data; /* Check invalid chars for POSIX regex */ for (i = 0; i < str_len; i++) { if (str[i] == '\n' || str[i] == '\r' || str[i] == '\0' ) { return FAILURE; } } if (icase) { options |= PCRE2_CASELESS; } re = pcre2_compile((PCRE2_SPTR)regex, regex_len, options, &errnumber, &err_offset, php_pcre_cctx()); if (NULL == re) { PCRE2_UCHAR err_msg[256]; pcre2_get_error_message(errnumber, err_msg, sizeof(err_msg)); php_error_docref(NULL, E_WARNING, "Cannot compile regex: '%s'", err_msg); return FAILURE; } match_data = php_pcre_create_match_data(0, re); if (NULL == match_data) { pcre2_code_free(re); php_error_docref(NULL, E_WARNING, "Cannot allocate match data"); return FAILURE; } res = pcre2_match(re, (PCRE2_SPTR)str, str_len, 0, 0, match_data, php_pcre_mctx()); php_pcre_free_match_data(match_data); pcre2_code_free(re); if (res == PCRE2_ERROR_NOMATCH) { return FAILURE; } else if (res < 0) { php_error_docref(NULL, E_WARNING, "Cannot exec regex"); return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ php_pgsql_add_quote * add quotes around string. */ static int php_pgsql_add_quotes(zval *src, zend_bool should_free) { smart_str str = {0}; assert(Z_TYPE_P(src) == IS_STRING); assert(should_free == 1 || should_free == 0); smart_str_appendc(&str, 'E'); smart_str_appendc(&str, '\''); smart_str_appendl(&str, Z_STRVAL_P(src), Z_STRLEN_P(src)); smart_str_appendc(&str, '\''); smart_str_0(&str); if (should_free) { zval_ptr_dtor(src); } ZVAL_NEW_STR(src, str.s); return SUCCESS; } /* }}} */ #define PGSQL_CONV_CHECK_IGNORE() \ if (!err && Z_TYPE(new_val) == IS_STRING && !strcmp(Z_STRVAL(new_val), "NULL")) { \ /* if new_value is string "NULL" and field has default value, remove element to use default value */ \ if (!(opt & PGSQL_CONV_IGNORE_DEFAULT) && Z_TYPE_P(has_default) == IS_TRUE) { \ zval_ptr_dtor(&new_val); \ skip_field = 1; \ } \ /* raise error if it's not null and cannot be ignored */ \ else if (!(opt & PGSQL_CONV_IGNORE_NOT_NULL) && Z_TYPE_P(not_null) == IS_TRUE) { \ php_error_docref(NULL, E_NOTICE, "Detected NULL for 'NOT NULL' field '%s'", ZSTR_VAL(field)); \ err = 1; \ } \ } /* {{{ php_pgsql_convert * check and convert array values (fieldname=>value pair) for sql */ PHP_PGSQL_API int php_pgsql_convert(PGconn *pg_link, const char *table_name, const zval *values, zval *result, zend_ulong opt) { zend_string *field = NULL; zval meta, *def, *type, *not_null, *has_default, *is_enum, *val, new_val; int err = 0, skip_field; php_pgsql_data_type data_type; assert(pg_link != NULL); assert(Z_TYPE_P(values) == IS_ARRAY); assert(Z_TYPE_P(result) == IS_ARRAY); assert(!(opt & ~PGSQL_CONV_OPTS)); if (!table_name) { return FAILURE; } array_init(&meta); /* table_name is escaped by php_pgsql_meta_data */ if (php_pgsql_meta_data(pg_link, table_name, &meta, 0) == FAILURE) { zval_ptr_dtor(&meta); return FAILURE; } ZEND_HASH_FOREACH_STR_KEY_VAL(Z_ARRVAL_P(values), field, val) { skip_field = 0; ZVAL_NULL(&new_val); if (!err && field == NULL) { php_error_docref(NULL, E_WARNING, "Accepts only string key for values"); err = 1; } if (!err && (def = zend_hash_find(Z_ARRVAL(meta), field)) == NULL) { php_error_docref(NULL, E_NOTICE, "Invalid field name (%s) in values", ZSTR_VAL(field)); err = 1; } if (!err && (type = zend_hash_str_find(Z_ARRVAL_P(def), "type", sizeof("type") - 1)) == NULL) { php_error_docref(NULL, E_NOTICE, "Detected broken meta data. Missing 'type'"); err = 1; } if (!err && (not_null = zend_hash_str_find(Z_ARRVAL_P(def), "not null", sizeof("not null") - 1)) == NULL) { php_error_docref(NULL, E_NOTICE, "Detected broken meta data. Missing 'not null'"); err = 1; } if (!err && (has_default = zend_hash_str_find(Z_ARRVAL_P(def), "has default", sizeof("has default") - 1)) == NULL) { php_error_docref(NULL, E_NOTICE, "Detected broken meta data. Missing 'has default'"); err = 1; } if (!err && (is_enum = zend_hash_str_find(Z_ARRVAL_P(def), "is enum", sizeof("is enum") - 1)) == NULL) { php_error_docref(NULL, E_NOTICE, "Detected broken meta data. Missing 'is enum'"); err = 1; } if (!err && (Z_TYPE_P(val) == IS_ARRAY || Z_TYPE_P(val) == IS_OBJECT)) { php_error_docref(NULL, E_NOTICE, "Expects scalar values as field values"); err = 1; } if (err) { break; /* break out for() */ } convert_to_boolean(is_enum); if (Z_TYPE_P(is_enum) == IS_TRUE) { /* enums need to be treated like strings */ data_type = PG_TEXT; } else { data_type = php_pgsql_get_data_type(Z_STRVAL_P(type), Z_STRLEN_P(type)); } switch(data_type) { case PG_BOOL: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRING(&new_val, "NULL"); } else { if (!strcmp(Z_STRVAL_P(val), "t") || !strcmp(Z_STRVAL_P(val), "T") || !strcmp(Z_STRVAL_P(val), "y") || !strcmp(Z_STRVAL_P(val), "Y") || !strcmp(Z_STRVAL_P(val), "true") || !strcmp(Z_STRVAL_P(val), "True") || !strcmp(Z_STRVAL_P(val), "yes") || !strcmp(Z_STRVAL_P(val), "Yes") || !strcmp(Z_STRVAL_P(val), "1")) { ZVAL_STRINGL(&new_val, "'t'", sizeof("'t'")-1); } else if (!strcmp(Z_STRVAL_P(val), "f") || !strcmp(Z_STRVAL_P(val), "F") || !strcmp(Z_STRVAL_P(val), "n") || !strcmp(Z_STRVAL_P(val), "N") || !strcmp(Z_STRVAL_P(val), "false") || !strcmp(Z_STRVAL_P(val), "False") || !strcmp(Z_STRVAL_P(val), "no") || !strcmp(Z_STRVAL_P(val), "No") || !strcmp(Z_STRVAL_P(val), "0")) { ZVAL_STRINGL(&new_val, "'f'", sizeof("'f'")-1); } else { php_error_docref(NULL, E_NOTICE, "Detected invalid value (%s) for PostgreSQL %s field (%s)", Z_STRVAL_P(val), Z_STRVAL_P(type), ZSTR_VAL(field)); err = 1; } } break; case IS_LONG: if (Z_LVAL_P(val)) { ZVAL_STRINGL(&new_val, "'t'", sizeof("'t'")-1); } else { ZVAL_STRINGL(&new_val, "'f'", sizeof("'f'")-1); } break; case IS_TRUE: ZVAL_STRINGL(&new_val, "'t'", sizeof("'t'")-1); break; case IS_FALSE: ZVAL_STRINGL(&new_val, "'f'", sizeof("'f'")-1); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects string, null, long or boolelan value for PostgreSQL '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_OID: case PG_INT2: case PG_INT4: case PG_INT8: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { /* FIXME: better regex must be used */ #define REGEX0 "^([+-]{0,1}[0-9]+)$" if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 0) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); } #undef REGEX0 } break; case IS_DOUBLE: ZVAL_DOUBLE(&new_val, Z_DVAL_P(val)); convert_to_long_ex(&new_val); break; case IS_LONG: ZVAL_LONG(&new_val, Z_LVAL_P(val)); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for pgsql '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_NUMERIC: case PG_MONEY: case PG_FLOAT4: case PG_FLOAT8: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { #define REGEX0 "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$" #define REGEX1 "^[+-]{0,1}(inf)(inity){0,1}$" /* better regex? */ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 0) == FAILURE) { if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX1, sizeof(REGEX1)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRING(&new_val, Z_STRVAL_P(val)); php_pgsql_add_quotes(&new_val, 1); } } else { ZVAL_STRING(&new_val, Z_STRVAL_P(val)); } #undef REGEX0 #undef REGEX1 } break; case IS_LONG: ZVAL_LONG(&new_val, Z_LVAL_P(val)); break; case IS_DOUBLE: ZVAL_DOUBLE(&new_val, Z_DVAL_P(val)); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; /* Exotic types are handled as string also. Please feel free to add more valitions. Invalid query fails at execution anyway. */ case PG_TEXT: case PG_CHAR: case PG_VARCHAR: /* bit */ case PG_BIT: case PG_VARBIT: /* geometric */ case PG_LINE: case PG_LSEG: case PG_POINT: case PG_BOX: case PG_PATH: case PG_POLYGON: case PG_CIRCLE: /* unknown. JSON, Array etc */ case PG_UNKNOWN: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { if (opt & PGSQL_CONV_FORCE_NULL) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { ZVAL_STRINGL(&new_val, "''", sizeof("''")-1); } } else { zend_string *str; /* PostgreSQL ignores \0 */ str = zend_string_alloc(Z_STRLEN_P(val) * 2, 0); /* better to use PGSQLescapeLiteral since PGescapeStringConn does not handle special \ */ ZSTR_LEN(str) = PQescapeStringConn(pg_link, ZSTR_VAL(str), Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); str = zend_string_truncate(str, ZSTR_LEN(str), 0); ZVAL_NEW_STR(&new_val, str); php_pgsql_add_quotes(&new_val, 1); } break; case IS_LONG: ZVAL_LONG(&new_val, Z_LVAL_P(val)); convert_to_string_ex(&new_val); break; case IS_DOUBLE: ZVAL_DOUBLE(&new_val, Z_DVAL_P(val)); convert_to_string_ex(&new_val); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_UNIX_TIME: case PG_UNIX_TIME_INTERVAL: /* these are the actallay a integer */ switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { /* better regex? */ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), "^[0-9]+$", sizeof("^[0-9]+$")-1, 0) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); convert_to_long_ex(&new_val); } } break; case IS_DOUBLE: ZVAL_DOUBLE(&new_val, Z_DVAL_P(val)); convert_to_long_ex(&new_val); break; case IS_LONG: ZVAL_LONG(&new_val, Z_LVAL_P(val)); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_CIDR: case PG_INET: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { #define REGEX0 "^((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])(\\/[0-9]{1,3})?$" #define REGEX1 "^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(\\/[0-9]{1,3})?$" /* The inet type holds an IPv4 or IPv6 host address, and optionally its subnet, all in one field. See more in the doc. The regex might still be not perfect, but catches the most of IP variants. We might decide to remove the regex at all though and let the server side to handle it.*/ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 0) == FAILURE && php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX1, sizeof(REGEX1)-1, 0) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 #undef REGEX1 } break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or IPv4 or IPv6 address string for '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_TIME_WITH_TIMEZONE: case PG_TIMESTAMP: case PG_TIMESTAMP_WITH_TIMEZONE: switch(Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else if (!strcasecmp(Z_STRVAL_P(val), "now()")) { ZVAL_STRINGL(&new_val, "NOW()", sizeof("NOW()")-1); } else { #define REGEX0 "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})(([ \\t]+|T)(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1}(\\.[0-9]+){0,1}([ \\t]*([+-][0-9]{1,4}(:[0-9]{1,2}){0,1}|[-a-zA-Z_/+]{1,50})){0,1})){0,1}$" /* better regex? */ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRING(&new_val, Z_STRVAL_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 } break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_DATE: switch(Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { #define REGEX0 "^([0-9]{4}[/-][0-9]{1,2}[/-][0-9]{1,2})$" /* FIXME: better regex must be used */ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 } break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_TIME: switch(Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { #define REGEX0 "^(([0-9]{1,2}:[0-9]{1,2}){1}(:[0-9]{1,2}){0,1})){0,1}$" /* FIXME: better regex must be used */ if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 } break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; case PG_INTERVAL: switch(Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRING(&new_val, "NULL"); } else { /* From the Postgres docs: interval values can be written with the following syntax: [@] quantity unit [quantity unit...] [direction] Where: quantity is a number (possibly signed); unit is second, minute, hour, day, week, month, year, decade, century, millennium, or abbreviations or plurals of these units [note not *all* abbreviations] ; direction can be ago or empty. The at sign (@) is optional noise. ... Quantities of days, hours, minutes, and seconds can be specified without explicit unit markings. For example, '1 12:59:10' is read the same as '1 day 12 hours 59 min 10 sec'. */ #define REGEX0 \ "^(@?[ \\t]+)?(" \ /* Textual time units and their abbreviations: */ \ "(([-+]?[ \\t]+)?" \ "[0-9]+(\\.[0-9]*)?[ \\t]*" \ "(millenniums|millennia|millennium|mil|mils|" \ "centuries|century|cent|c|" \ "decades|decade|dec|decs|" \ "years|year|y|" \ "months|month|mon|" \ "weeks|week|w|" \ "days|day|d|" \ "hours|hour|hr|hrs|h|" \ "minutes|minute|mins|min|m|" \ "seconds|second|secs|sec|s))+|" \ /* Textual time units plus (dd)* hh[:mm[:ss]] */ \ "((([-+]?[ \\t]+)?" \ "[0-9]+(\\.[0-9]*)?[ \\t]*" \ "(millenniums|millennia|millennium|mil|mils|" \ "centuries|century|cent|c|" \ "decades|decade|dec|decs|" \ "years|year|y|" \ "months|month|mon|" \ "weeks|week|w|" \ "days|day|d))+" \ "([-+]?[ \\t]+" \ "([0-9]+[ \\t]+)+" /* dd */ \ "(([0-9]{1,2}:){0,2}[0-9]{0,2})" /* hh:[mm:[ss]] */ \ ")?))" \ "([ \\t]+ago)?$" if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRING(&new_val, Z_STRVAL_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 } break; case IS_NULL: ZVAL_STRING(&new_val, "NULL"); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; #ifdef HAVE_PQESCAPE case PG_BYTEA: switch (Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRING(&new_val, "NULL"); } else { unsigned char *tmp; size_t to_len; smart_str s = {0}; #ifdef HAVE_PQESCAPE_BYTEA_CONN tmp = PQescapeByteaConn(pg_link, (unsigned char *)Z_STRVAL_P(val), Z_STRLEN_P(val), &to_len); #else tmp = PQescapeBytea(Z_STRVAL_P(val), (unsigned char *)Z_STRLEN_P(val), &to_len); #endif ZVAL_STRINGL(&new_val, (char *)tmp, to_len - 1); /* PQescapeBytea's to_len includes additional '\0' */ PQfreemem(tmp); php_pgsql_add_quotes(&new_val, 1); smart_str_appendl(&s, Z_STRVAL(new_val), Z_STRLEN(new_val)); smart_str_0(&s); zval_ptr_dtor(&new_val); ZVAL_NEW_STR(&new_val, s.s); } break; case IS_LONG: ZVAL_LONG(&new_val, Z_LVAL_P(val)); convert_to_string_ex(&new_val); break; case IS_DOUBLE: ZVAL_DOUBLE(&new_val, Z_DVAL_P(val)); convert_to_string_ex(&new_val); break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL, string, long or double value for PostgreSQL '%s' (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; #endif case PG_MACADDR: switch(Z_TYPE_P(val)) { case IS_STRING: if (Z_STRLEN_P(val) == 0) { ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); } else { #define REGEX0 "^([0-9a-f]{2,2}:){5,5}[0-9a-f]{2,2}$" if (php_pgsql_convert_match(Z_STRVAL_P(val), Z_STRLEN_P(val), REGEX0, sizeof(REGEX0)-1, 1) == FAILURE) { err = 1; } else { ZVAL_STRINGL(&new_val, Z_STRVAL_P(val), Z_STRLEN_P(val)); php_pgsql_add_quotes(&new_val, 1); } #undef REGEX0 } break; case IS_NULL: ZVAL_STRINGL(&new_val, "NULL", sizeof("NULL")-1); break; default: err = 1; } PGSQL_CONV_CHECK_IGNORE(); if (err) { php_error_docref(NULL, E_NOTICE, "Expects NULL or string for PostgreSQL %s field (%s)", Z_STRVAL_P(type), ZSTR_VAL(field)); } break; default: /* should not happen */ php_error_docref(NULL, E_NOTICE, "Unknown or system data type '%s' for '%s'. Report error", Z_STRVAL_P(type), ZSTR_VAL(field)); err = 1; break; } /* switch */ if (err) { zval_ptr_dtor(&new_val); break; /* break out for() */ } /* If field is NULL and HAS DEFAULT, should be skipped */ if (!skip_field) { if (_php_pgsql_detect_identifier_escape(ZSTR_VAL(field), ZSTR_LEN(field)) == SUCCESS) { zend_hash_update(Z_ARRVAL_P(result), field, &new_val); } else { char *escaped = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(field), ZSTR_LEN(field)); add_assoc_zval(result, escaped, &new_val); PGSQLfree(escaped); } } } ZEND_HASH_FOREACH_END(); /* for */ zval_ptr_dtor(&meta); if (err) { /* shouldn't destroy & free zval here */ return FAILURE; } return SUCCESS; } /* }}} */ /* {{{ proto array pg_convert(resource db, string table, array values[, int options]) Check and convert values for PostgreSQL SQL statement */ PHP_FUNCTION(pg_convert) { zval *pgsql_link, *values; char *table_name; size_t table_name_len; zend_ulong option = 0; PGconn *pg_link; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa|l", &pgsql_link, &table_name, &table_name_len, &values, &option) == FAILURE) { return; } if (option & ~PGSQL_CONV_OPTS) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } if (!table_name_len) { php_error_docref(NULL, E_NOTICE, "Table name is invalid"); RETURN_FALSE; } if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } array_init(return_value); if (php_pgsql_convert(pg_link, table_name, values, return_value, option) == FAILURE) { zval_dtor(return_value); RETURN_FALSE; } } /* }}} */ static int do_exec(smart_str *querystr, ExecStatusType expect, PGconn *pg_link, zend_ulong opt) /* {{{ */ { if (opt & PGSQL_DML_ASYNC) { if (PQsendQuery(pg_link, ZSTR_VAL(querystr->s))) { return 0; } } else { PGresult *pg_result; pg_result = PQexec(pg_link, ZSTR_VAL(querystr->s)); if (PQresultStatus(pg_result) == expect) { PQclear(pg_result); return 0; } else { php_error_docref(NULL, E_WARNING, "%s", PQresultErrorMessage(pg_result)); PQclear(pg_result); } } return -1; } /* }}} */ static inline void build_tablename(smart_str *querystr, PGconn *pg_link, const char *table) /* {{{ */ { char *table_copy, *escaped, *tmp; const char *token; size_t len; /* schame.table should be "schame"."table" */ table_copy = estrdup(table); token = php_strtok_r(table_copy, ".", &tmp); if (token == NULL) { token = table; } len = strlen(token); if (_php_pgsql_detect_identifier_escape(token, len) == SUCCESS) { smart_str_appendl(querystr, token, len); } else { escaped = PGSQLescapeIdentifier(pg_link, token, len); smart_str_appends(querystr, escaped); PGSQLfree(escaped); } if (tmp && *tmp) { len = strlen(tmp); /* "schema"."table" format */ if (_php_pgsql_detect_identifier_escape(tmp, len) == SUCCESS) { smart_str_appendc(querystr, '.'); smart_str_appendl(querystr, tmp, len); } else { escaped = PGSQLescapeIdentifier(pg_link, tmp, len); smart_str_appendc(querystr, '.'); smart_str_appends(querystr, escaped); PGSQLfree(escaped); } } efree(table_copy); } /* }}} */ /* {{{ php_pgsql_insert */ PHP_PGSQL_API int php_pgsql_insert(PGconn *pg_link, const char *table, zval *var_array, zend_ulong opt, zend_string **sql) { zval *val, converted; char buf[256]; char *tmp; smart_str querystr = {0}; int ret = FAILURE; zend_string *fld; assert(pg_link != NULL); assert(table != NULL); assert(Z_TYPE_P(var_array) == IS_ARRAY); ZVAL_UNDEF(&converted); if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0) { smart_str_appends(&querystr, "INSERT INTO "); build_tablename(&querystr, pg_link, table); smart_str_appends(&querystr, " DEFAULT VALUES"); goto no_values; } /* convert input array if needed */ if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) { array_init(&converted); if (php_pgsql_convert(pg_link, table, var_array, &converted, (opt & PGSQL_CONV_OPTS)) == FAILURE) { goto cleanup; } var_array = &converted; } smart_str_appends(&querystr, "INSERT INTO "); build_tablename(&querystr, pg_link, table); smart_str_appends(&querystr, " ("); ZEND_HASH_FOREACH_STR_KEY(Z_ARRVAL_P(var_array), fld) { if (fld == NULL) { php_error_docref(NULL, E_NOTICE, "Expects associative array for values to be inserted"); goto cleanup; } if (opt & PGSQL_DML_ESCAPE) { tmp = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(fld), ZSTR_LEN(fld) + 1); smart_str_appends(&querystr, tmp); PGSQLfree(tmp); } else { smart_str_appendl(&querystr, ZSTR_VAL(fld), ZSTR_LEN(fld)); } smart_str_appendc(&querystr, ','); } ZEND_HASH_FOREACH_END(); ZSTR_LEN(querystr.s)--; smart_str_appends(&querystr, ") VALUES ("); /* make values string */ ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(var_array), val) { /* we can avoid the key_type check here, because we tested it in the other loop */ switch (Z_TYPE_P(val)) { case IS_STRING: if (opt & PGSQL_DML_ESCAPE) { size_t new_len; char *tmp; tmp = (char *)safe_emalloc(Z_STRLEN_P(val), 2, 1); new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); smart_str_appendc(&querystr, '\''); smart_str_appendl(&querystr, tmp, new_len); smart_str_appendc(&querystr, '\''); efree(tmp); } else { smart_str_appendl(&querystr, Z_STRVAL_P(val), Z_STRLEN_P(val)); } break; case IS_LONG: smart_str_append_long(&querystr, Z_LVAL_P(val)); break; case IS_DOUBLE: smart_str_appendl(&querystr, buf, snprintf(buf, sizeof(buf), "%F", Z_DVAL_P(val))); break; case IS_NULL: smart_str_appendl(&querystr, "NULL", sizeof("NULL")-1); break; default: php_error_docref(NULL, E_WARNING, "Expects scaler values. type = %d", Z_TYPE_P(val)); goto cleanup; break; } smart_str_appendc(&querystr, ','); } ZEND_HASH_FOREACH_END(); /* Remove the trailing "," */ ZSTR_LEN(querystr.s)--; smart_str_appends(&querystr, ");"); no_values: smart_str_0(&querystr); if ((opt & (PGSQL_DML_EXEC|PGSQL_DML_ASYNC)) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, (opt & PGSQL_CONV_OPTS)) == 0) { ret = SUCCESS; } else if (opt & PGSQL_DML_STRING) { ret = SUCCESS; } cleanup: zval_ptr_dtor(&converted); if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) { *sql = querystr.s; } else { smart_str_free(&querystr); } return ret; } /* }}} */ /* {{{ proto mixed pg_insert(resource db, string table, array values[, int options]) Insert values (filed=>value) to table */ PHP_FUNCTION(pg_insert) { zval *pgsql_link, *values; char *table; size_t table_len; zend_ulong option = PGSQL_DML_EXEC, return_sql; PGconn *pg_link; PGresult *pg_result; ExecStatusType status; zend_string *sql = NULL; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsa|l", &pgsql_link, &table, &table_len, &values, &option) == FAILURE) { return; } if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } return_sql = option & PGSQL_DML_STRING; if (option & PGSQL_DML_EXEC) { /* return resource when executed */ option = option & ~PGSQL_DML_EXEC; if (php_pgsql_insert(pg_link, table, values, option|PGSQL_DML_STRING, &sql) == FAILURE) { RETURN_FALSE; } pg_result = PQexec(pg_link, ZSTR_VAL(sql)); if ((PGG(auto_reset_persistent) & 2) && PQstatus(pg_link) != CONNECTION_OK) { PQclear(pg_result); PQreset(pg_link); pg_result = PQexec(pg_link, ZSTR_VAL(sql)); } efree(sql); if (pg_result) { status = PQresultStatus(pg_result); } else { status = (ExecStatusType) PQstatus(pg_link); } switch (status) { case PGRES_EMPTY_QUERY: case PGRES_BAD_RESPONSE: case PGRES_NONFATAL_ERROR: case PGRES_FATAL_ERROR: PHP_PQ_ERROR("Query failed: %s", pg_link); PQclear(pg_result); RETURN_FALSE; break; case PGRES_COMMAND_OK: /* successful command that did not return rows */ default: if (pg_result) { pgsql_result_handle *pgsql_handle = (pgsql_result_handle *) emalloc(sizeof(pgsql_result_handle)); pgsql_handle->conn = pg_link; pgsql_handle->result = pg_result; pgsql_handle->row = 0; RETURN_RES(zend_register_resource(pgsql_handle, le_result)); } else { PQclear(pg_result); RETURN_FALSE; } break; } } else if (php_pgsql_insert(pg_link, table, values, option, &sql) == FAILURE) { RETURN_FALSE; } if (return_sql) { RETURN_STR(sql); return; } RETURN_TRUE; } /* }}} */ static inline int build_assignment_string(PGconn *pg_link, smart_str *querystr, HashTable *ht, int where_cond, const char *pad, int pad_len, zend_ulong opt) /* {{{ */ { zend_string *fld; zval *val; ZEND_HASH_FOREACH_STR_KEY_VAL(ht, fld, val) { if (fld == NULL) { php_error_docref(NULL, E_NOTICE, "Expects associative array for values to be inserted"); return -1; } if (opt & PGSQL_DML_ESCAPE) { char *tmp = PGSQLescapeIdentifier(pg_link, ZSTR_VAL(fld), ZSTR_LEN(fld) + 1); smart_str_appends(querystr, tmp); PGSQLfree(tmp); } else { smart_str_appendl(querystr, ZSTR_VAL(fld), ZSTR_LEN(fld)); } if (where_cond && (Z_TYPE_P(val) == IS_TRUE || Z_TYPE_P(val) == IS_FALSE || (Z_TYPE_P(val) == IS_STRING && !strcmp(Z_STRVAL_P(val), "NULL")))) { smart_str_appends(querystr, " IS "); } else { smart_str_appendc(querystr, '='); } switch (Z_TYPE_P(val)) { case IS_STRING: if (opt & PGSQL_DML_ESCAPE) { char *tmp = (char *)safe_emalloc(Z_STRLEN_P(val), 2, 1); size_t new_len = PQescapeStringConn(pg_link, tmp, Z_STRVAL_P(val), Z_STRLEN_P(val), NULL); smart_str_appendc(querystr, '\''); smart_str_appendl(querystr, tmp, new_len); smart_str_appendc(querystr, '\''); efree(tmp); } else { smart_str_appendl(querystr, Z_STRVAL_P(val), Z_STRLEN_P(val)); } break; case IS_LONG: smart_str_append_long(querystr, Z_LVAL_P(val)); break; case IS_DOUBLE: { char buf[256]; smart_str_appendl(querystr, buf, MIN(snprintf(buf, sizeof(buf), "%F", Z_DVAL_P(val)), sizeof(buf) - 1)); } break; case IS_NULL: smart_str_appendl(querystr, "NULL", sizeof("NULL")-1); break; default: php_error_docref(NULL, E_WARNING, "Expects scaler values. type=%d", Z_TYPE_P(val)); return -1; } smart_str_appendl(querystr, pad, pad_len); } ZEND_HASH_FOREACH_END(); if (querystr->s) { ZSTR_LEN(querystr->s) -= pad_len; } return 0; } /* }}} */ /* {{{ php_pgsql_update */ PHP_PGSQL_API int php_pgsql_update(PGconn *pg_link, const char *table, zval *var_array, zval *ids_array, zend_ulong opt, zend_string **sql) { zval var_converted, ids_converted; smart_str querystr = {0}; int ret = FAILURE; assert(pg_link != NULL); assert(table != NULL); assert(Z_TYPE_P(var_array) == IS_ARRAY); assert(Z_TYPE_P(ids_array) == IS_ARRAY); assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE))); if (zend_hash_num_elements(Z_ARRVAL_P(var_array)) == 0 || zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) { return FAILURE; } ZVAL_UNDEF(&var_converted); ZVAL_UNDEF(&ids_converted); if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) { array_init(&var_converted); if (php_pgsql_convert(pg_link, table, var_array, &var_converted, (opt & PGSQL_CONV_OPTS)) == FAILURE) { goto cleanup; } var_array = &var_converted; array_init(&ids_converted); if (php_pgsql_convert(pg_link, table, ids_array, &ids_converted, (opt & PGSQL_CONV_OPTS)) == FAILURE) { goto cleanup; } ids_array = &ids_converted; } smart_str_appends(&querystr, "UPDATE "); build_tablename(&querystr, pg_link, table); smart_str_appends(&querystr, " SET "); if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(var_array), 0, ",", 1, opt)) goto cleanup; smart_str_appends(&querystr, " WHERE "); if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt)) goto cleanup; smart_str_appendc(&querystr, ';'); smart_str_0(&querystr); if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt) == 0) { ret = SUCCESS; } else if (opt & PGSQL_DML_STRING) { ret = SUCCESS; } cleanup: zval_ptr_dtor(&var_converted); zval_ptr_dtor(&ids_converted); if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) { *sql = querystr.s; } else { smart_str_free(&querystr); } return ret; } /* }}} */ /* {{{ proto mixed pg_update(resource db, string table, array fields, array ids[, int options]) Update table using values (field=>value) and ids (id=>value) */ PHP_FUNCTION(pg_update) { zval *pgsql_link, *values, *ids; char *table; size_t table_len; zend_ulong option = PGSQL_DML_EXEC; PGconn *pg_link; zend_string *sql = NULL; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsaa|l", &pgsql_link, &table, &table_len, &values, &ids, &option) == FAILURE) { return; } if (option & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } if (php_pgsql_update(pg_link, table, values, ids, option, &sql) == FAILURE) { RETURN_FALSE; } if (option & PGSQL_DML_STRING) { RETURN_STR(sql); } RETURN_TRUE; } /* }}} */ /* {{{ php_pgsql_delete */ PHP_PGSQL_API int php_pgsql_delete(PGconn *pg_link, const char *table, zval *ids_array, zend_ulong opt, zend_string **sql) { zval ids_converted; smart_str querystr = {0}; int ret = FAILURE; assert(pg_link != NULL); assert(table != NULL); assert(Z_TYPE_P(ids_array) == IS_ARRAY); assert(!(opt & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE))); if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) { return FAILURE; } ZVAL_UNDEF(&ids_converted); if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) { array_init(&ids_converted); if (php_pgsql_convert(pg_link, table, ids_array, &ids_converted, (opt & PGSQL_CONV_OPTS)) == FAILURE) { goto cleanup; } ids_array = &ids_converted; } smart_str_appends(&querystr, "DELETE FROM "); build_tablename(&querystr, pg_link, table); smart_str_appends(&querystr, " WHERE "); if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt)) goto cleanup; smart_str_appendc(&querystr, ';'); smart_str_0(&querystr); if ((opt & PGSQL_DML_EXEC) && do_exec(&querystr, PGRES_COMMAND_OK, pg_link, opt) == 0) { ret = SUCCESS; } else if (opt & PGSQL_DML_STRING) { ret = SUCCESS; } cleanup: zval_ptr_dtor(&ids_converted); if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) { *sql = querystr.s; } else { smart_str_free(&querystr); } return ret; } /* }}} */ /* {{{ proto mixed pg_delete(resource db, string table, array ids[, int options]) Delete records has ids (id=>value) */ PHP_FUNCTION(pg_delete) { zval *pgsql_link, *ids; char *table; size_t table_len; zend_ulong option = PGSQL_DML_EXEC; PGconn *pg_link; zend_string *sql; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsa|l", &pgsql_link, &table, &table_len, &ids, &option) == FAILURE) { return; } if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } if (php_pgsql_delete(pg_link, table, ids, option, &sql) == FAILURE) { RETURN_FALSE; } if (option & PGSQL_DML_STRING) { RETURN_STR(sql); } RETURN_TRUE; } /* }}} */ /* {{{ php_pgsql_result2array */ PHP_PGSQL_API int php_pgsql_result2array(PGresult *pg_result, zval *ret_array, long result_type) { zval row; char *field_name; size_t num_fields; int pg_numrows, pg_row; uint32_t i; assert(Z_TYPE_P(ret_array) == IS_ARRAY); if ((pg_numrows = PQntuples(pg_result)) <= 0) { return FAILURE; } for (pg_row = 0; pg_row < pg_numrows; pg_row++) { array_init(&row); for (i = 0, num_fields = PQnfields(pg_result); i < num_fields; i++) { field_name = PQfname(pg_result, i); if (PQgetisnull(pg_result, pg_row, i)) { if (result_type & PGSQL_ASSOC) { add_assoc_null(&row, field_name); } if (result_type & PGSQL_NUM) { add_next_index_null(&row); } } else { char *element = PQgetvalue(pg_result, pg_row, i); if (element) { const size_t element_len = strlen(element); if (result_type & PGSQL_ASSOC) { add_assoc_stringl(&row, field_name, element, element_len); } if (result_type & PGSQL_NUM) { add_next_index_stringl(&row, element, element_len); } } } } add_index_zval(ret_array, pg_row, &row); } return SUCCESS; } /* }}} */ /* {{{ php_pgsql_select */ PHP_PGSQL_API int php_pgsql_select(PGconn *pg_link, const char *table, zval *ids_array, zval *ret_array, zend_ulong opt, long result_type, zend_string **sql) { zval ids_converted; smart_str querystr = {0}; int ret = FAILURE; PGresult *pg_result; assert(pg_link != NULL); assert(table != NULL); assert(Z_TYPE_P(ids_array) == IS_ARRAY); assert(Z_TYPE_P(ret_array) == IS_ARRAY); assert(!(opt & ~(PGSQL_CONV_OPTS|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE))); if (zend_hash_num_elements(Z_ARRVAL_P(ids_array)) == 0) { return FAILURE; } ZVAL_UNDEF(&ids_converted); if (!(opt & (PGSQL_DML_NO_CONV|PGSQL_DML_ESCAPE))) { array_init(&ids_converted); if (php_pgsql_convert(pg_link, table, ids_array, &ids_converted, (opt & PGSQL_CONV_OPTS)) == FAILURE) { goto cleanup; } ids_array = &ids_converted; } smart_str_appends(&querystr, "SELECT * FROM "); build_tablename(&querystr, pg_link, table); smart_str_appends(&querystr, " WHERE "); if (build_assignment_string(pg_link, &querystr, Z_ARRVAL_P(ids_array), 1, " AND ", sizeof(" AND ")-1, opt)) goto cleanup; smart_str_appendc(&querystr, ';'); smart_str_0(&querystr); pg_result = PQexec(pg_link, ZSTR_VAL(querystr.s)); if (PQresultStatus(pg_result) == PGRES_TUPLES_OK) { ret = php_pgsql_result2array(pg_result, ret_array, result_type); } else { php_error_docref(NULL, E_NOTICE, "Failed to execute '%s'", ZSTR_VAL(querystr.s)); } PQclear(pg_result); cleanup: zval_ptr_dtor(&ids_converted); if (ret == SUCCESS && (opt & PGSQL_DML_STRING)) { *sql = querystr.s; } else { smart_str_free(&querystr); } return ret; } /* }}} */ /* {{{ proto mixed pg_select(resource db, string table, array ids[, int options [, int result_type]) Select records that has ids (id=>value) */ PHP_FUNCTION(pg_select) { zval *pgsql_link, *ids; char *table; size_t table_len; zend_ulong option = PGSQL_DML_EXEC; long result_type = PGSQL_ASSOC; PGconn *pg_link; zend_string *sql = NULL; int argc = ZEND_NUM_ARGS(); if (zend_parse_parameters(argc, "rsa|l", &pgsql_link, &table, &table_len, &ids, &option, &result_type) == FAILURE) { return; } if (option & ~(PGSQL_CONV_FORCE_NULL|PGSQL_DML_NO_CONV|PGSQL_DML_EXEC|PGSQL_DML_ASYNC|PGSQL_DML_STRING|PGSQL_DML_ESCAPE)) { php_error_docref(NULL, E_WARNING, "Invalid option is specified"); RETURN_FALSE; } if (!(result_type & PGSQL_BOTH)) { php_error_docref(NULL, E_WARNING, "Invalid result type"); RETURN_FALSE; } if ((pg_link = (PGconn *)zend_fetch_resource2(Z_RES_P(pgsql_link), "PostgreSQL link", le_link, le_plink)) == NULL) { RETURN_FALSE; } if (php_pgsql_flush_query(pg_link)) { php_error_docref(NULL, E_NOTICE, "Detected unhandled result(s) in connection"); } array_init(return_value); if (php_pgsql_select(pg_link, table, ids, return_value, option, result_type, &sql) == FAILURE) { zval_ptr_dtor(return_value); RETURN_FALSE; } if (option & PGSQL_DML_STRING) { zval_ptr_dtor(return_value); RETURN_STR(sql); } return; } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
42989.c
/* * Common driver-related functions * Copyright (c) 2003-2011, Jouni Malinen <[email protected]> * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include "utils/common.h" #include "driver.h" void wpa_scan_results_free(struct wpa_scan_results *res) { size_t i; if (res == NULL) return; for (i = 0; i < res->num; i++) os_free(res->res[i]); os_free(res->res); os_free(res); } const char * event_to_string(enum wpa_event_type event) { #define E2S(n) case EVENT_ ## n: return #n switch (event) { E2S(ASSOC); E2S(DISASSOC); E2S(MICHAEL_MIC_FAILURE); E2S(SCAN_RESULTS); E2S(ASSOCINFO); E2S(INTERFACE_STATUS); E2S(PMKID_CANDIDATE); E2S(STKSTART); E2S(TDLS); E2S(FT_RESPONSE); E2S(IBSS_RSN_START); E2S(AUTH); E2S(DEAUTH); E2S(ASSOC_REJECT); E2S(AUTH_TIMED_OUT); E2S(ASSOC_TIMED_OUT); E2S(FT_RRB_RX); E2S(WPS_BUTTON_PUSHED); E2S(TX_STATUS); E2S(RX_FROM_UNKNOWN); E2S(RX_MGMT); E2S(RX_ACTION); E2S(REMAIN_ON_CHANNEL); E2S(CANCEL_REMAIN_ON_CHANNEL); E2S(MLME_RX); E2S(RX_PROBE_REQ); E2S(NEW_STA); E2S(EAPOL_RX); E2S(SIGNAL_CHANGE); E2S(INTERFACE_ENABLED); E2S(INTERFACE_DISABLED); E2S(CHANNEL_LIST_CHANGED); E2S(INTERFACE_UNAVAILABLE); E2S(BEST_CHANNEL); E2S(UNPROT_DEAUTH); E2S(UNPROT_DISASSOC); E2S(STATION_LOW_ACK); E2S(P2P_DEV_FOUND); E2S(P2P_GO_NEG_REQ_RX); E2S(P2P_GO_NEG_COMPLETED); E2S(P2P_PROV_DISC_REQUEST); E2S(P2P_PROV_DISC_RESPONSE); E2S(P2P_SD_REQUEST); E2S(P2P_SD_RESPONSE); E2S(IBSS_PEER_LOST); E2S(DRIVER_GTK_REKEY); E2S(SCHED_SCAN_STOPPED); E2S(DRIVER_CLIENT_POLL_OK); E2S(EAPOL_TX_STATUS); E2S(CH_SWITCH); E2S(ROAMING_ENABLED); E2S(ROAMING_DISABLED); E2S(START_ROAMING); E2S(REQ_CH_SW); } return "UNKNOWN"; #undef E2S }
615214.c
/* * Sun RPC is a product of Sun Microsystems, Inc. and is provided for * unrestricted use provided that this legend is included on all tape * media and as a part of the software program in whole or part. Users * may copy or modify Sun RPC without charge, but are not authorized * to license or distribute it to anyone else except as part of a product or * program developed by the user. * * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun RPC is provided with no support and without any obligation on the * part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ /* * xdr_rec.c, Implements TCP/IP based XDR streams with a "record marking" * layer above tcp (for rpc's use). * * Copyright (C) 1984, Sun Microsystems, Inc. * * These routines interface XDRSTREAMS to a tcp/ip connection. * There is a record marking layer between the xdr stream * and the tcp transport level. A record is composed on one or more * record fragments. A record fragment is a thirty-two bit header followed * by n bytes of data, where n is contained in the header. The header * is represented as a htonl(u_long). The high order bit encodes * whether or not the fragment is the last fragment of the record * (1 => fragment is last, 0 => more fragments to follow. * The other 31 bits encode the byte length of the fragment. */ #define __FORCE_GLIBC #include <features.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <rpc/rpc.h> #ifdef USE_IN_LIBIO # include <wchar.h> # include <libio/iolibio.h> # define fputs(s, f) _IO_fputs (s, f) #endif static bool_t xdrrec_getbytes (XDR *, caddr_t, u_int); static bool_t xdrrec_putbytes (XDR *, const char *, u_int); static bool_t xdrrec_getint32 (XDR *, int32_t *); static bool_t xdrrec_putint32 (XDR *, const int32_t *); #if ULONG_MAX != 0xffffffff static bool_t xdrrec_getlong (XDR *, long *); static bool_t xdrrec_putlong (XDR *, const long *); #endif static u_int xdrrec_getpos (const XDR *); static bool_t xdrrec_setpos (XDR *, u_int); static int32_t *xdrrec_inline (XDR *, u_int); static void xdrrec_destroy (XDR *); static const struct xdr_ops xdrrec_ops = { #if ULONG_MAX == 0xffffffff (bool_t (*)(XDR *, long *)) xdrrec_getint32, (bool_t (*)(XDR *, const long *)) xdrrec_putint32, #else xdrrec_getlong, xdrrec_putlong, #endif xdrrec_getbytes, xdrrec_putbytes, xdrrec_getpos, xdrrec_setpos, xdrrec_inline, xdrrec_destroy, xdrrec_getint32, xdrrec_putint32 }; /* * A record is composed of one or more record fragments. * A record fragment is a two-byte header followed by zero to * 2**32-1 bytes. The header is treated as a long unsigned and is * encode/decoded to the network via htonl/ntohl. The low order 31 bits * are a byte count of the fragment. The highest order bit is a boolean: * 1 => this fragment is the last fragment of the record, * 0 => this fragment is followed by more fragment(s). * * The fragment/record machinery is not general; it is constructed to * meet the needs of xdr and rpc based on tcp. */ #define LAST_FRAG (1UL << 31) typedef struct rec_strm { caddr_t tcp_handle; caddr_t the_buffer; /* * out-going bits */ int (*writeit) (char *, char *, int); caddr_t out_base; /* output buffer (points to frag header) */ caddr_t out_finger; /* next output position */ caddr_t out_boundry; /* data cannot up to this address */ u_int32_t *frag_header; /* beginning of curren fragment */ bool_t frag_sent; /* true if buffer sent in middle of record */ /* * in-coming bits */ int (*readit) (char *, char *, int); u_long in_size; /* fixed size of the input buffer */ caddr_t in_base; caddr_t in_finger; /* location of next byte to be had */ caddr_t in_boundry; /* can read up to this location */ long fbtbc; /* fragment bytes to be consumed */ bool_t last_frag; u_int sendsize; u_int recvsize; } RECSTREAM; static u_int fix_buf_size (u_int) internal_function; static bool_t skip_input_bytes (RECSTREAM *, long) internal_function; static bool_t flush_out (RECSTREAM *, bool_t) internal_function; static bool_t set_input_fragment (RECSTREAM *) internal_function; static bool_t get_input_bytes (RECSTREAM *, caddr_t, int) internal_function; /* * Create an xdr handle for xdrrec * xdrrec_create fills in xdrs. Sendsize and recvsize are * send and recv buffer sizes (0 => use default). * tcp_handle is an opaque handle that is passed as the first parameter to * the procedures readit and writeit. Readit and writeit are read and * write respectively. They are like the system * calls expect that they take an opaque handle rather than an fd. */ void xdrrec_create (XDR *xdrs, u_int sendsize, u_int recvsize, caddr_t tcp_handle, int (*readit) (char *, char *, int), int (*writeit) (char *, char *, int)) { RECSTREAM *rstrm = (RECSTREAM *) mem_alloc (sizeof (RECSTREAM)); caddr_t tmp; char *buf; sendsize = fix_buf_size (sendsize); recvsize = fix_buf_size (recvsize); buf = mem_alloc (sendsize + recvsize + BYTES_PER_XDR_UNIT); if (rstrm == NULL || buf == NULL) { #ifdef USE_IN_LIBIO if (_IO_fwide (stderr, 0) > 0) (void) fwprintf (stderr, L"%s", _("xdrrec_create: out of memory\n")); else #endif (void) fputs (_("xdrrec_create: out of memory\n"), stderr); mem_free (rstrm, sizeof (RECSTREAM)); mem_free (buf, sendsize + recvsize + BYTES_PER_XDR_UNIT); /* * This is bad. Should rework xdrrec_create to * return a handle, and in this case return NULL */ return; } /* * adjust sizes and allocate buffer quad byte aligned */ rstrm->sendsize = sendsize; rstrm->recvsize = recvsize; rstrm->the_buffer = buf; tmp = rstrm->the_buffer; if ((size_t)tmp % BYTES_PER_XDR_UNIT) tmp += BYTES_PER_XDR_UNIT - (size_t)tmp % BYTES_PER_XDR_UNIT; rstrm->out_base = tmp; rstrm->in_base = tmp + sendsize; /* * now the rest ... */ /* We have to add the const since the `struct xdr_ops' in `struct XDR' is not `const'. */ xdrs->x_ops = (struct xdr_ops *) &xdrrec_ops; xdrs->x_private = (caddr_t) rstrm; rstrm->tcp_handle = tcp_handle; rstrm->readit = readit; rstrm->writeit = writeit; rstrm->out_finger = rstrm->out_boundry = rstrm->out_base; rstrm->frag_header = (u_int32_t *) rstrm->out_base; rstrm->out_finger += 4; rstrm->out_boundry += sendsize; rstrm->frag_sent = FALSE; rstrm->in_size = recvsize; rstrm->in_boundry = rstrm->in_base; rstrm->in_finger = (rstrm->in_boundry += recvsize); rstrm->fbtbc = 0; rstrm->last_frag = TRUE; } libc_hidden_def(xdrrec_create) /* * The routines defined below are the xdr ops which will go into the * xdr handle filled in by xdrrec_create. */ static bool_t xdrrec_getint32 (XDR *xdrs, int32_t *ip) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; int32_t *bufip = (int32_t *) rstrm->in_finger; int32_t mylong; /* first try the inline, fast case */ if (rstrm->fbtbc >= BYTES_PER_XDR_UNIT && rstrm->in_boundry - (char *) bufip >= BYTES_PER_XDR_UNIT) { *ip = ntohl (*bufip); rstrm->fbtbc -= BYTES_PER_XDR_UNIT; rstrm->in_finger += BYTES_PER_XDR_UNIT; } else { if (!xdrrec_getbytes (xdrs, (caddr_t) &mylong, BYTES_PER_XDR_UNIT)) return FALSE; *ip = ntohl (mylong); } return TRUE; } #if ULONG_MAX != 0xffffffff static bool_t xdrrec_getlong (XDR *xdrs, long *lp) { int32_t v; bool_t r = xdrrec_getint32 (xdrs, &v); *lp = v; return r; } #endif static bool_t xdrrec_putint32 (XDR *xdrs, const int32_t *ip) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; int32_t *dest_ip = (int32_t *) rstrm->out_finger; if ((rstrm->out_finger += BYTES_PER_XDR_UNIT) > rstrm->out_boundry) { /* * this case should almost never happen so the code is * inefficient */ rstrm->out_finger -= BYTES_PER_XDR_UNIT; rstrm->frag_sent = TRUE; if (!flush_out (rstrm, FALSE)) return FALSE; dest_ip = (int32_t *) rstrm->out_finger; rstrm->out_finger += BYTES_PER_XDR_UNIT; } *dest_ip = htonl (*ip); return TRUE; } #if ULONG_MAX != 0xffffffff static bool_t xdrrec_putlong (XDR *xdrs, const long *lp) { int32_t v = *lp; return xdrrec_putint32 (xdrs, &v); } #endif static bool_t /* must manage buffers, fragments, and records */ xdrrec_getbytes (XDR *xdrs, caddr_t addr, u_int len) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; u_int current; while (len > 0) { current = rstrm->fbtbc; if (current == 0) { if (rstrm->last_frag) return FALSE; if (!set_input_fragment (rstrm)) return FALSE; continue; } current = (len < current) ? len : current; if (!get_input_bytes (rstrm, addr, current)) return FALSE; addr += current; rstrm->fbtbc -= current; len -= current; } return TRUE; } static bool_t xdrrec_putbytes (XDR *xdrs, const char *addr, u_int len) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; u_int current; while (len > 0) { current = rstrm->out_boundry - rstrm->out_finger; current = (len < current) ? len : current; memcpy (rstrm->out_finger, addr, current); rstrm->out_finger += current; addr += current; len -= current; if (rstrm->out_finger == rstrm->out_boundry && len > 0) { rstrm->frag_sent = TRUE; if (!flush_out (rstrm, FALSE)) return FALSE; } } return TRUE; } static u_int xdrrec_getpos (const XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; long pos; pos = lseek ((int) (long) rstrm->tcp_handle, (long) 0, 1); if (pos != -1) switch (xdrs->x_op) { case XDR_ENCODE: pos += rstrm->out_finger - rstrm->out_base; break; case XDR_DECODE: pos -= rstrm->in_boundry - rstrm->in_finger; break; default: pos = (u_int) - 1; break; } return (u_int) pos; } static bool_t xdrrec_setpos (XDR *xdrs, u_int pos) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; u_int currpos = xdrrec_getpos (xdrs); int delta = currpos - pos; caddr_t newpos; if ((int) currpos != -1) switch (xdrs->x_op) { case XDR_ENCODE: newpos = rstrm->out_finger - delta; if (newpos > (caddr_t) rstrm->frag_header && newpos < rstrm->out_boundry) { rstrm->out_finger = newpos; return TRUE; } break; case XDR_DECODE: newpos = rstrm->in_finger - delta; if ((delta < (int) (rstrm->fbtbc)) && (newpos <= rstrm->in_boundry) && (newpos >= rstrm->in_base)) { rstrm->in_finger = newpos; rstrm->fbtbc -= delta; return TRUE; } break; default: break; } return FALSE; } static int32_t * xdrrec_inline (XDR *xdrs, u_int len) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; int32_t *buf = NULL; switch (xdrs->x_op) { case XDR_ENCODE: if ((rstrm->out_finger + len) <= rstrm->out_boundry) { buf = (int32_t *) rstrm->out_finger; rstrm->out_finger += len; } break; case XDR_DECODE: if ((len <= rstrm->fbtbc) && ((rstrm->in_finger + len) <= rstrm->in_boundry)) { buf = (int32_t *) rstrm->in_finger; rstrm->fbtbc -= len; rstrm->in_finger += len; } break; default: break; } return buf; } static void xdrrec_destroy (XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; mem_free (rstrm->the_buffer, rstrm->sendsize + rstrm->recvsize + BYTES_PER_XDR_UNIT); mem_free ((caddr_t) rstrm, sizeof (RECSTREAM)); } /* * Exported routines to manage xdr records */ /* * Before reading (deserializing from the stream, one should always call * this procedure to guarantee proper record alignment. */ bool_t xdrrec_skiprecord (XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; while (rstrm->fbtbc > 0 || (!rstrm->last_frag)) { if (!skip_input_bytes (rstrm, rstrm->fbtbc)) return FALSE; rstrm->fbtbc = 0; if ((!rstrm->last_frag) && (!set_input_fragment (rstrm))) return FALSE; } rstrm->last_frag = FALSE; return TRUE; } libc_hidden_def(xdrrec_skiprecord) /* * Lookahead function. * Returns TRUE iff there is no more input in the buffer * after consuming the rest of the current record. */ bool_t xdrrec_eof (XDR *xdrs) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; while (rstrm->fbtbc > 0 || (!rstrm->last_frag)) { if (!skip_input_bytes (rstrm, rstrm->fbtbc)) return TRUE; rstrm->fbtbc = 0; if ((!rstrm->last_frag) && (!set_input_fragment (rstrm))) return TRUE; } if (rstrm->in_finger == rstrm->in_boundry) return TRUE; return FALSE; } libc_hidden_def(xdrrec_eof) /* * The client must tell the package when an end-of-record has occurred. * The second parameter tells whether the record should be flushed to the * (output) tcp stream. (This lets the package support batched or * pipelined procedure calls.) TRUE => immediate flush to tcp connection. */ bool_t xdrrec_endofrecord (XDR *xdrs, bool_t sendnow) { RECSTREAM *rstrm = (RECSTREAM *) xdrs->x_private; u_long len; /* fragment length */ if (sendnow || rstrm->frag_sent || rstrm->out_finger + BYTES_PER_XDR_UNIT >= rstrm->out_boundry) { rstrm->frag_sent = FALSE; return flush_out (rstrm, TRUE); } len = (rstrm->out_finger - (char *) rstrm->frag_header - BYTES_PER_XDR_UNIT); *rstrm->frag_header = htonl ((u_long) len | LAST_FRAG); rstrm->frag_header = (u_int32_t *) rstrm->out_finger; rstrm->out_finger += BYTES_PER_XDR_UNIT; return TRUE; } libc_hidden_def(xdrrec_endofrecord) /* * Internal useful routines */ static bool_t internal_function flush_out (RECSTREAM *rstrm, bool_t eor) { u_long eormask = (eor == TRUE) ? LAST_FRAG : 0; u_long len = (rstrm->out_finger - (char *) rstrm->frag_header - BYTES_PER_XDR_UNIT); *rstrm->frag_header = htonl (len | eormask); len = rstrm->out_finger - rstrm->out_base; if ((*(rstrm->writeit)) (rstrm->tcp_handle, rstrm->out_base, (int) len) != (int) len) return FALSE; rstrm->frag_header = (u_int32_t *) rstrm->out_base; rstrm->out_finger = (caddr_t) rstrm->out_base + BYTES_PER_XDR_UNIT; return TRUE; } static bool_t /* knows nothing about records! Only about input buffers */ fill_input_buf (RECSTREAM *rstrm) { caddr_t where; size_t i; int len; where = rstrm->in_base; i = (size_t) rstrm->in_boundry % BYTES_PER_XDR_UNIT; where += i; len = rstrm->in_size - i; if ((len = (*(rstrm->readit)) (rstrm->tcp_handle, where, len)) == -1) return FALSE; rstrm->in_finger = where; where += len; rstrm->in_boundry = where; return TRUE; } static bool_t /* knows nothing about records! Only about input buffers */ internal_function get_input_bytes (RECSTREAM *rstrm, caddr_t addr, int len) { int current; while (len > 0) { current = rstrm->in_boundry - rstrm->in_finger; if (current == 0) { if (!fill_input_buf (rstrm)) return FALSE; continue; } current = (len < current) ? len : current; memcpy (addr, rstrm->in_finger, current); rstrm->in_finger += current; addr += current; len -= current; } return TRUE; } static bool_t /* next two bytes of the input stream are treated as a header */ internal_function set_input_fragment (RECSTREAM *rstrm) { uint32_t header; if (! get_input_bytes (rstrm, (caddr_t)&header, BYTES_PER_XDR_UNIT)) return FALSE; header = ntohl (header); rstrm->last_frag = ((header & LAST_FRAG) == 0) ? FALSE : TRUE; /* * Sanity check. Try not to accept wildly incorrect fragment * sizes. Unfortunately, only a size of zero can be identified as * 'wildely incorrect', and this only, if it is not the last * fragment of a message. Ridiculously large fragment sizes may look * wrong, but we don't have any way to be certain that they aren't * what the client actually intended to send us. Many existing RPC * implementations may sent a fragment of size zero as the last * fragment of a message. */ if (header == 0) return FALSE; rstrm->fbtbc = header & ~LAST_FRAG; return TRUE; } static bool_t /* consumes input bytes; knows nothing about records! */ internal_function skip_input_bytes (RECSTREAM *rstrm, long cnt) { int current; while (cnt > 0) { current = rstrm->in_boundry - rstrm->in_finger; if (current == 0) { if (!fill_input_buf (rstrm)) return FALSE; continue; } current = (cnt < current) ? cnt : current; rstrm->in_finger += current; cnt -= current; } return TRUE; } static u_int internal_function fix_buf_size (u_int s) { if (s < 100) s = 4000; return RNDUP (s); }
632552.c
#include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> int partition(int a[], int beg, int end) { int left, right, temp, loc, flag; loc = left = beg; right = end; flag = 0; while(flag != 1) { while((a[loc] <= a[right]) && (loc!=right)) right--; if(loc==right) flag =1; else if(a[loc]>a[right]) { temp = a[loc]; a[loc] = a[right]; a[right] = temp; loc = right; } if(flag!=1) { while((a[loc] >= a[left]) && (loc!=left)) left++; if(loc==left) flag =1; else if(a[loc] <a[left]) { temp = a[loc]; a[loc] = a[left]; a[left] = temp; loc = left; } } } return loc; } void quickSort(int a[], int beg, int end) { int loc; if(beg<end) { loc = partition(a, beg, end); quickSort(a, beg, loc-1); quickSort(a, loc+1, end); } } int main() { int n,t; printf("Enter No of testcases : "); scanf("%d", &t); while(t--){ clock_t start, end; double cpu_time_used; start = clock(); printf("n = "); scanf("%d", &n); int i,arr[n]; for(i=0;i<n;i++) arr[i] = rand()%100; quickSort(arr,0,n-1); end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; printf("time = %.5f \n", cpu_time_used); } return 0; }
472700.c
/* test/test-vcf-api.c -- VCF test harness. Copyright (C) 2013, 2014, 2017-2021 Genome Research Ltd. Author: Petr Danecek <[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 <config.h> #include <errno.h> #include <stdio.h> #include <string.h> #include "htslib/hts.h" #include "htslib/vcf.h" #include "htslib/kstring.h" #include "htslib/kseq.h" void error(const char *format, ...) { va_list ap; va_start(ap, format); vfprintf(stderr, format, ap); va_end(ap); if (strrchr(format, '\n') == NULL) fputc('\n', stderr); exit(-1); } #define STRINGIFY(x) #x #define check0(x) ((x) == 0 ? (void) 0 : error("Failed: %s", STRINGIFY(x))) static int check_alleles(bcf1_t *rec, const char **alleles, int num) { int i; if (rec->n_allele != num) { fprintf(stderr, "Wrong number of alleles - expected %d, got %d\n", num, rec->n_allele); return -1; } if (bcf_unpack(rec, BCF_UN_STR) != 0) return -1; for (i = 0; i < num; i++) { if (0 != strcmp(alleles[i], rec->d.allele[i])) { fprintf(stderr, "Mismatch for allele %d : expected '%s' got '%s'\n", i, alleles[i], rec->d.allele[i]); return -1; } } return 0; } static void test_update_alleles(bcf_hdr_t *hdr, bcf1_t *rec) { // Exercise bcf_update_alleles() a bit const char *alleles1[2] = { "G", "A" }; const char *alleles2[3] = { "C", "TGCA", "CATG" }; #define rep10(x) x x x x x x x x x x const char *alleles3[3] = { rep10("ATTCTAGATC"), "TGCA", rep10("CTATTATCTCTAATGACATG") }; #undef rep10 const char *alleles4[3] = { alleles3[2], NULL, alleles3[0] }; // Add some alleles check0(bcf_update_alleles(hdr, rec, alleles1, 2)); check0(check_alleles(rec, alleles1, 2)); // Erase them check0(bcf_update_alleles(hdr, rec, NULL, 0)); check0(check_alleles(rec, NULL, 0)); // Expand to three check0(bcf_update_alleles(hdr, rec, alleles2, 3)); check0(check_alleles(rec, alleles2, 3)); // Now try some bigger ones (should force a realloc) check0(bcf_update_alleles(hdr, rec, alleles3, 3)); check0(check_alleles(rec, alleles3, 3)); // Ensure it works even if one of the alleles points into the // existing structure alleles4[1] = rec->d.allele[1]; check0(bcf_update_alleles(hdr, rec, alleles4, 3)); alleles4[1] = alleles3[1]; // Will have been clobbered by the update check0(check_alleles(rec, alleles4, 3)); // Ensure it works when the alleles point into the existing data, // rec->d.allele is used to define the input array and the // order of the entries is changed. The result of this should // be the same as alleles2. char *tmp = rec->d.allele[0] + strlen(rec->d.allele[0]) - 4; rec->d.allele[0] = rec->d.allele[2] + strlen(rec->d.allele[2]) - 1; rec->d.allele[2] = tmp; check0(bcf_update_alleles(hdr, rec, (const char **) rec->d.allele, 3)); check0(check_alleles(rec, alleles2, 3)); } void write_bcf(char *fname) { // Init htsFile *fp = hts_open(fname,"wb"); if (!fp) error("Failed to open \"%s\" : %s", fname, strerror(errno)); bcf_hdr_t *hdr = bcf_hdr_init("w"); if (!hdr) error("bcf_hdr_init : %s", strerror(errno)); bcf1_t *rec = bcf_init1(); if (!rec) error("bcf_init1 : %s", strerror(errno)); // Check no-op on fresh bcf1_t check0(bcf_update_alleles(hdr, rec, NULL, 0)); // Create VCF header kstring_t str = {0,0,0}; check0(bcf_hdr_append(hdr, "##fileDate=20090805")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=UF,Number=1,Type=Integer,Description=\"Unused FORMAT\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=UI,Number=1,Type=Integer,Description=\"Unused INFO\">")); check0(bcf_hdr_append(hdr, "##FILTER=<ID=Flt,Description=\"Unused FILTER\">")); check0(bcf_hdr_append(hdr, "##unused=<XX=AA,Description=\"Unused generic\">")); check0(bcf_hdr_append(hdr, "##unused=unformatted text 1")); check0(bcf_hdr_append(hdr, "##unused=unformatted text 2")); check0(bcf_hdr_append(hdr, "##contig=<ID=Unused,length=1>")); check0(bcf_hdr_append(hdr, "##source=myImputationProgramV3.1")); check0(bcf_hdr_append(hdr, "##reference=file:///seq/references/1000GenomesPilot-NCBI36.fasta")); check0(bcf_hdr_append(hdr, "##contig=<ID=20,length=62435964,assembly=B36,md5=f126cdf8a6e0c7f379d618ff66beb2da,species=\"Homo sapiens\",taxonomy=x>")); check0(bcf_hdr_append(hdr, "##phasing=partial")); check0(bcf_hdr_append(hdr, "##INFO=<ID=NS,Number=1,Type=Integer,Description=\"Number of Samples With Data\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total Depth\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=NEG,Number=.,Type=Integer,Description=\"Test -ve Numbers\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=AF,Number=A,Type=Float,Description=\"Allele Frequency\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=AA,Number=1,Type=String,Description=\"Ancestral Allele\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=DB,Number=0,Type=Flag,Description=\"dbSNP membership, build 129\">")); check0(bcf_hdr_append(hdr, "##INFO=<ID=H2,Number=0,Type=Flag,Description=\"HapMap2 membership\">")); check0(bcf_hdr_append(hdr, "##FILTER=<ID=q10,Description=\"Quality below 10\">")); check0(bcf_hdr_append(hdr, "##FILTER=<ID=s50,Description=\"Less than half of samples have data\">")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=GQ,Number=1,Type=Integer,Description=\"Genotype Quality\">")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=HQ,Number=2,Type=Integer,Description=\"Haplotype Quality\">")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=TS,Number=1,Type=String,Description=\"Test String 1\">")); // Try a few header modifications bcf_hdr_remove(hdr, BCF_HL_CTG, "Unused"); check0(bcf_hdr_append(hdr, "##contig=<ID=Unused,length=62435964>")); bcf_hdr_remove(hdr, BCF_HL_FMT, "TS"); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=TS,Number=1,Type=String,Description=\"Test String\">")); bcf_hdr_remove(hdr, BCF_HL_INFO, "NEG"); check0(bcf_hdr_append(hdr, "##INFO=<ID=NEG,Number=.,Type=Integer,Description=\"Test Negative Numbers\">")); bcf_hdr_remove(hdr, BCF_HL_FLT, "s50"); check0(bcf_hdr_append(hdr, "##FILTER=<ID=s50,Description=\"Less than 50% of samples have data\">")); check0(bcf_hdr_add_sample(hdr, "NA00001")); check0(bcf_hdr_add_sample(hdr, "NA00002")); check0(bcf_hdr_add_sample(hdr, "NA00003")); check0(bcf_hdr_add_sample(hdr, NULL)); // to update internal structures if ( bcf_hdr_write(fp, hdr)!=0 ) error("Failed to write to %s\n", fname); // Add a record // 20 14370 rs6054257 G A 29 PASS NS=3;DP=14;NEG=-127;AF=0.5;DB;H2 GT:GQ:DP:HQ 0|0:48:1:51,51 1|0:48:8:51,51 1/1:43:5:.,. // .. CHROM rec->rid = bcf_hdr_name2id(hdr, "20"); // .. POS rec->pos = 14369; // .. ID check0(bcf_update_id(hdr, rec, "rs6054257")); // .. REF and ALT test_update_alleles(hdr, rec); const char *alleles[2] = { "G", "A" }; check0(bcf_update_alleles_str(hdr, rec, "G,A")); check0(check_alleles(rec, alleles, 2)); // .. QUAL rec->qual = 29; // .. FILTER int32_t tmpi = bcf_hdr_id2int(hdr, BCF_DT_ID, "PASS"); check0(bcf_update_filter(hdr, rec, &tmpi, 1)); // .. INFO tmpi = 3; check0(bcf_update_info_int32(hdr, rec, "NS", &tmpi, 1)); tmpi = 500; check0(bcf_update_info_int32(hdr, rec, "DP", &tmpi, 1)); tmpi = 100000; check0(bcf_update_info_int32(hdr, rec, "DP", &tmpi, 1)); tmpi = 14; check0(bcf_update_info_int32(hdr, rec, "DP", &tmpi, 1)); tmpi = -127; check0(bcf_update_info_int32(hdr, rec, "NEG", &tmpi, 1)); float tmpf = 0.5; check0(bcf_update_info_float(hdr, rec, "AF", &tmpf, 1)); check0(bcf_update_info_flag(hdr, rec, "DB", NULL, 1)); check0(bcf_update_info_flag(hdr, rec, "H2", NULL, 1)); // .. FORMAT int32_t *tmpia = (int*)malloc(bcf_hdr_nsamples(hdr)*2*sizeof(int)); tmpia[0] = bcf_gt_phased(0); tmpia[1] = bcf_gt_phased(0); tmpia[2] = bcf_gt_phased(1); tmpia[3] = bcf_gt_phased(0); tmpia[4] = bcf_gt_unphased(1); tmpia[5] = bcf_gt_unphased(1); check0(bcf_update_genotypes(hdr, rec, tmpia, bcf_hdr_nsamples(hdr)*2)); tmpia[0] = 48; tmpia[1] = 48; tmpia[2] = 43; check0(bcf_update_format_int32(hdr, rec, "GQ", tmpia, bcf_hdr_nsamples(hdr))); tmpia[0] = 0; tmpia[1] = 0; tmpia[2] = 1; check0(bcf_update_format_int32(hdr, rec, "DP", tmpia, bcf_hdr_nsamples(hdr))); tmpia[0] = 1; tmpia[1] = 100000; tmpia[2] = 1; check0(bcf_update_format_int32(hdr, rec, "DP", tmpia, bcf_hdr_nsamples(hdr))); tmpia[0] = 1; tmpia[1] = 8; tmpia[2] = 5; check0(bcf_update_format_int32(hdr, rec, "DP", tmpia, bcf_hdr_nsamples(hdr))); tmpia[0] = 51; tmpia[1] = 51; tmpia[2] = 51; tmpia[3] = 51; tmpia[4] = bcf_int32_missing; tmpia[5] = bcf_int32_missing; check0(bcf_update_format_int32(hdr, rec, "HQ", tmpia, bcf_hdr_nsamples(hdr)*2)); char *tmp_str[] = {"String1","SomeOtherString2","YetAnotherString3"}; check0(bcf_update_format_string(hdr, rec, "TS", (const char**)tmp_str, 3)); tmp_str[0] = "LongerStringRequiringBufferReallocation"; check0(bcf_update_format_string(hdr, rec, "TS", (const char**)tmp_str, 3)); tmp_str[0] = "String1"; check0(bcf_update_format_string(hdr, rec, "TS", (const char**)tmp_str, 3)); if ( bcf_write1(fp, hdr, rec)!=0 ) error("Failed to write to %s\n", fname); // 20 1110696 . A G,T 67 . NS=2;DP=10;NEG=-128;AF=0.333,.;AA=T;DB GT 2 1 ./. bcf_clear1(rec); rec->rid = bcf_hdr_name2id(hdr, "20"); rec->pos = 1110695; check0(bcf_update_alleles_str(hdr, rec, "A,G,T")); rec->qual = 67; tmpi = 2; check0(bcf_update_info_int32(hdr, rec, "NS", &tmpi, 1)); tmpi = 10; check0(bcf_update_info_int32(hdr, rec, "DP", &tmpi, 1)); tmpi = -128; check0(bcf_update_info_int32(hdr, rec, "NEG", &tmpi, 1)); float *tmpfa = (float*)malloc(2*sizeof(float)); tmpfa[0] = 0.333; bcf_float_set_missing(tmpfa[1]); check0(bcf_update_info_float(hdr, rec, "AF", tmpfa, 2)); check0(bcf_update_info_string(hdr, rec, "AA", "SHORT")); check0(bcf_update_info_string(hdr, rec, "AA", "LONGSTRING")); check0(bcf_update_info_string(hdr, rec, "AA", "T")); check0(bcf_update_info_flag(hdr, rec, "DB", NULL, 1)); tmpia[0] = bcf_gt_phased(2); tmpia[1] = bcf_int32_vector_end; tmpia[2] = bcf_gt_phased(1); tmpia[3] = bcf_int32_vector_end; tmpia[4] = bcf_gt_missing; tmpia[5] = bcf_gt_missing; check0(bcf_update_genotypes(hdr, rec, tmpia, bcf_hdr_nsamples(hdr)*2)); if ( bcf_write1(fp, hdr, rec)!=0 ) error("Failed to write to %s\n", fname); free(tmpia); free(tmpfa); // Clean free(str.s); bcf_destroy1(rec); bcf_hdr_destroy(hdr); int ret; if ( (ret=hts_close(fp)) ) { fprintf(stderr,"hts_close(%s): non-zero status %d\n",fname,ret); exit(ret); } } void bcf_to_vcf(char *fname) { htsFile *fp = hts_open(fname,"rb"); if (!fp) error("Failed to open \"%s\" : %s", fname, strerror(errno)); bcf_hdr_t *hdr = bcf_hdr_read(fp); if (!hdr) error("bcf_hdr_read : %s", strerror(errno)); bcf1_t *rec = bcf_init1(); if (!rec) error("bcf_init1 : %s", strerror(errno)); char *gz_fname = (char*) malloc(strlen(fname)+4); if (!gz_fname) error("malloc : %s", strerror(errno)); snprintf(gz_fname,strlen(fname)+4,"%s.gz",fname); htsFile *out = hts_open(gz_fname,"wg"); if (!out) error("Couldn't open \"%s\" : %s\n", gz_fname, strerror(errno)); bcf_hdr_t *hdr_out = bcf_hdr_dup(hdr); bcf_hdr_remove(hdr_out,BCF_HL_STR,"unused"); bcf_hdr_remove(hdr_out,BCF_HL_GEN,"unused"); bcf_hdr_remove(hdr_out,BCF_HL_FLT,"Flt"); bcf_hdr_remove(hdr_out,BCF_HL_INFO,"UI"); bcf_hdr_remove(hdr_out,BCF_HL_FMT,"UF"); bcf_hdr_remove(hdr_out,BCF_HL_CTG,"Unused"); if ( bcf_hdr_write(out, hdr_out)!=0 ) error("Failed to write to %s\n", fname); int r; while ((r = bcf_read1(fp, hdr, rec)) >= 0) { if ( bcf_write1(out, hdr_out, rec)!=0 ) error("Failed to write to %s\n", fname); // Test problems caused by bcf1_sync: the data block // may be realloced, also the unpacked structures must // get updated. check0(bcf_unpack(rec, BCF_UN_STR)); check0(bcf_update_id(hdr, rec, 0)); check0(bcf_update_format_int32(hdr, rec, "GQ", NULL, 0)); bcf1_t *dup = bcf_dup(rec); // force bcf1_sync call if ( bcf_write1(out, hdr_out, dup)!=0 ) error("Failed to write to %s\n", fname); bcf_destroy1(dup); check0(bcf_update_alleles_str(hdr_out, rec, "G,A")); int32_t tmpi = 99; check0(bcf_update_info_int32(hdr_out, rec, "DP", &tmpi, 1)); int32_t tmpia[] = {9,9,9}; check0(bcf_update_format_int32(hdr_out, rec, "DP", tmpia, 3)); if ( bcf_write1(out, hdr_out, rec)!=0 ) error("Failed to write to %s\n", fname); } if (r < -1) error("bcf_read1"); bcf_destroy1(rec); bcf_hdr_destroy(hdr); bcf_hdr_destroy(hdr_out); int ret; if ( (ret=hts_close(fp)) ) { fprintf(stderr,"hts_close(%s): non-zero status %d\n",fname,ret); exit(ret); } if ( (ret=hts_close(out)) ) { fprintf(stderr,"hts_close(%s): non-zero status %d\n",gz_fname,ret); exit(ret); } // read gzip, write stdout htsFile *gz_in = hts_open(gz_fname, "r"); if ( !gz_in ) { fprintf(stderr,"Could not read: %s\n", gz_fname); exit(1); } kstring_t line = {0,0,0}; while ( hts_getline(gz_in, KS_SEP_LINE, &line)>0 ) { kputc('\n',&line); fwrite(line.s,1,line.l,stdout); } if ( (ret=hts_close(gz_in)) ) { fprintf(stderr,"hts_close(%s): non-zero status %d\n",gz_fname,ret); exit(ret); } free(line.s); free(gz_fname); } void iterator(const char *fname) { htsFile *fp = hts_open(fname, "r"); if (!fp) error("Failed to open \"%s\" : %s", fname, strerror(errno)); bcf_hdr_t *hdr = bcf_hdr_read(fp); if (!hdr) error("bcf_hdr_read : %s", strerror(errno)); hts_idx_t *idx; hts_itr_t *iter; bcf_index_build(fname, 0); idx = bcf_index_load(fname); iter = bcf_itr_queryi(idx, bcf_hdr_name2id(hdr, "20"), 1110600, 1110800); bcf_itr_destroy(iter); iter = bcf_itr_querys(idx, hdr, "20:1110600-1110800"); bcf_itr_destroy(iter); hts_idx_destroy(idx); bcf_hdr_destroy(hdr); int ret; if ( (ret=hts_close(fp)) ) { fprintf(stderr,"hts_close(%s): non-zero status %d\n",fname,ret); exit(ret); } } void test_get_info_values(const char *fname) { htsFile *fp = hts_open(fname, "r"); if (!fp) error("Failed to open \"%s\" : %s", fname, strerror(errno)); bcf_hdr_t *hdr = bcf_hdr_read(fp); if (!hdr) error("bcf_hdr_read : %s", strerror(errno)); bcf1_t *line = bcf_init(); if (!line) error("bcf_init : %s", strerror(errno)); int r; while ((r = bcf_read(fp, hdr, line)) == 0) { float *afs = 0; int32_t *negs = NULL; int count = 0; int ret = bcf_get_info_float(hdr, line, "AF", &afs, &count); if (line->pos == 14369) { if (ret != 1 || afs[0] != 0.5f) { fprintf(stderr, "AF on position 14370 should be 0.5\n"); exit(-1); } } else { if (ret != 2 || afs[0] != 0.333f || !bcf_float_is_missing(afs[1])) { fprintf(stderr, "AF on position 1110696 should be 0.333, missing\n"); exit(-1); } } free(afs); int32_t expected = (line->pos == 14369)? -127 : -128; count = 0; ret = bcf_get_info_int32(hdr, line, "NEG", &negs, &count); if (ret != 1 || negs[0] != expected) { if (ret < 0) fprintf(stderr, "NEG should be %d, got error ret=%d\n", expected, ret); else if (ret == 0) fprintf(stderr, "NEG should be %d, got no entries\n", expected); else fprintf(stderr, "NEG should be %d, got %d entries (first is %d)\n", expected, ret, negs[0]); exit(1); } free(negs); } if (r < -1) error("bcf_read"); bcf_destroy(line); bcf_hdr_destroy(hdr); hts_close(fp); } void write_format_values(const char *fname) { // Init htsFile *fp = hts_open(fname, "wb"); if (!fp) error("Failed to open \"%s\" : %s", fname, strerror(errno)); bcf_hdr_t *hdr = bcf_hdr_init("w"); if (!hdr) error("bcf_hdr_init : %s", strerror(errno)); bcf1_t *rec = bcf_init1(); if (!rec) error("bcf_init1 : %s", strerror(errno)); // Create VCF header check0(bcf_hdr_append(hdr, "##contig=<ID=1>")); check0(bcf_hdr_append(hdr, "##FORMAT=<ID=TF,Number=1,Type=Float,Description=\"Test Float\">")); check0(bcf_hdr_add_sample(hdr, "S")); check0(bcf_hdr_add_sample(hdr, NULL)); // to update internal structures if ( bcf_hdr_write(fp, hdr)!=0 ) error("Failed to write to %s\n", fname); // Add a record // .. FORMAT float test[4]; bcf_float_set_missing(test[0]); test[1] = 47.11f; bcf_float_set_vector_end(test[2]); test[3] = -1.2e-13; check0(bcf_update_format_float(hdr, rec, "TF", test, 4)); if ( bcf_write1(fp, hdr, rec)!=0 ) error("Failed to write to %s\n", fname); bcf_destroy1(rec); bcf_hdr_destroy(hdr); int ret; if ((ret = hts_close(fp))) { fprintf(stderr, "hts_close(%s): non-zero status %d\n", fname, ret); exit(ret); } } void check_format_values(const char *fname) { htsFile *fp = hts_open(fname, "r"); bcf_hdr_t *hdr = bcf_hdr_read(fp); bcf1_t *line = bcf_init(); while (bcf_read(fp, hdr, line) == 0) { float *values = 0; int count = 0; int ret = bcf_get_format_float(hdr, line, "TF", &values, &count); // NOTE the return value from bcf_get_format_float is different from // bcf_get_info_float in the sense that vector-end markers also count. if (ret != 4 || count < ret || !bcf_float_is_missing(values[0]) || values[1] != 47.11f || !bcf_float_is_vector_end(values[2]) || !bcf_float_is_vector_end(values[3])) { fprintf(stderr, "bcf_get_format_float didn't produce the expected output.\n"); exit(-1); } free(values); } bcf_destroy(line); bcf_hdr_destroy(hdr); hts_close(fp); } void test_get_format_values(const char *fname) { write_format_values(fname); check_format_values(fname); } void test_invalid_end_tag(void) { static const char vcf_data[] = "data:," "##fileformat=VCFv4.1\n" "##contig=<ID=X,length=155270560>\n" "##INFO=<ID=END,Number=1,Type=Integer,Description=\"End coordinate of this variant\">\n" "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n" "X\t86470037\trs59780433a\tTTTCA\tTGGTT,T\t.\t.\tEND=85725113\n" "X\t86470038\trs59780433b\tT\tTGGTT,T\t.\t.\tEND=86470047\n"; htsFile *fp; bcf_hdr_t *hdr; bcf1_t *rec; int ret; int32_t tmpi; enum htsLogLevel logging = hts_get_log_level(); // Silence warning messages hts_set_log_level(HTS_LOG_ERROR); fp = hts_open(vcf_data, "r"); if (!fp) error("Failed to open vcf data : %s", strerror(errno)); rec = bcf_init1(); if (!rec) error("Failed to allocate BCF record : %s", strerror(errno)); hdr = bcf_hdr_read(fp); if (!hdr) error("Failed to read BCF header : %s", strerror(errno)); check0(bcf_read(fp, hdr, rec)); // rec->rlen should ignore the bogus END tag value on the first read if (rec->rlen != 5) { error("Incorrect rlen - expected 5 got %"PRIhts_pos"\n", rec->rlen); } check0(bcf_read(fp, hdr, rec)); // While on the second it should use it if (rec->rlen != 10) { error("Incorrect rlen - expected 10 got %"PRIhts_pos"\n", rec->rlen); } // Try to break it - will change rlen tmpi = 85725113; check0(bcf_update_info_int32(hdr, rec, "END", &tmpi, 1)); if (rec->rlen != 1) { error("Incorrect rlen - expected 1 got %"PRIhts_pos"\n", rec->rlen); } ret = bcf_read(fp, hdr, rec); if (ret != -1) { error("Unexpected return code %d from bcf_read at EOF", ret); } bcf_destroy1(rec); bcf_hdr_destroy(hdr); ret = hts_close(fp); if (ret != 0) { error("Unexpected return code %d from hts_close", ret); } hts_set_log_level(logging); } void test_open_format() { char mode[5]; int ret; strcpy(mode, "r"); ret = vcf_open_mode(mode+1, "mode1.bcf", NULL); if (strncmp(mode, "rb", 2) || ret) error("Mode '%s' does not match the expected value '%s'", mode, "rb"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.vcf", NULL); if (strncmp(mode, "r", 1) || ret) error("Mode '%s' does not match the expected value '%s'", mode, "r"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.vcf.gz", NULL); if (strncmp(mode, "rz", 2) || ret) error("Mode '%s' does not match the expected value '%s'", mode, "rz"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.vcf.bgz", NULL); if (strncmp(mode, "rz", 2) || ret) error("Mode '%s' does not match the expected value '%s'", mode, "rz"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.xcf", NULL); if (!ret) error("Expected failure for wrong extension 'xcf'"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.vcf.gbz", NULL); if (!ret) error("Expected failure for wrong extension 'vcf.gbz'"); mode[1] = 0; ret = vcf_open_mode(mode+1, "mode1.bvcf.bgz", NULL); if (!ret) error("Expected failure for wrong extension 'vcf.bvcf.bgz'"); } int main(int argc, char **argv) { char *fname = argc>1 ? argv[1] : "rmme.bcf"; // format test. quiet unless there's a failure test_get_format_values(fname); // main test. writes to stdout write_bcf(fname); bcf_to_vcf(fname); iterator(fname); // // additional tests. quiet unless there's a failure. test_get_info_values(fname); test_invalid_end_tag(); test_open_format(); return 0; } // gcc VCFTest.c -g -o vcf-api-test -I ./htslib/ libhts.so.3
455046.c
/* Copyright (C) 1997-2015 Sam Lantinga <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely. */ /* Game controller mapping generator */ /* Gabriel Jacobo <[email protected]> */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" #ifndef SDL_JOYSTICK_DISABLED #ifdef __IPHONEOS__ #define SCREEN_WIDTH 320 #define SCREEN_HEIGHT 480 #else #define SCREEN_WIDTH 512 #define SCREEN_HEIGHT 317 #endif #define MAP_WIDTH 512 #define MAP_HEIGHT 317 #define MARKER_BUTTON 1 #define MARKER_AXIS 2 typedef struct MappingStep { int x, y; double angle; int marker; char *field; int axis, button, hat, hat_value; char mapping[4096]; }MappingStep; SDL_Texture * LoadTexture(SDL_Renderer *renderer, char *file, SDL_bool transparent) { SDL_Surface *temp; SDL_Texture *texture; /* Load the sprite image */ temp = SDL_LoadBMP(file); if (temp == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s", file, SDL_GetError()); return NULL; } /* Set transparent pixel as the pixel at (0,0) */ if (transparent) { if (temp->format->palette) { SDL_SetColorKey(temp, SDL_TRUE, *(Uint8 *) temp->pixels); } else { switch (temp->format->BitsPerPixel) { case 15: SDL_SetColorKey(temp, SDL_TRUE, (*(Uint16 *) temp->pixels) & 0x00007FFF); break; case 16: SDL_SetColorKey(temp, SDL_TRUE, *(Uint16 *) temp->pixels); break; case 24: SDL_SetColorKey(temp, SDL_TRUE, (*(Uint32 *) temp->pixels) & 0x00FFFFFF); break; case 32: SDL_SetColorKey(temp, SDL_TRUE, *(Uint32 *) temp->pixels); break; } } } /* Create textures from the image */ texture = SDL_CreateTextureFromSurface(renderer, temp); if (!texture) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture: %s\n", SDL_GetError()); SDL_FreeSurface(temp); return NULL; } SDL_FreeSurface(temp); /* We're ready to roll. :) */ return texture; } static SDL_bool WatchJoystick(SDL_Joystick * joystick) { SDL_Window *window = NULL; SDL_Renderer *screen = NULL; SDL_Texture *background, *button, *axis, *marker; const char *name = NULL; SDL_bool retval = SDL_FALSE; SDL_bool done = SDL_FALSE, next=SDL_FALSE; SDL_Event event; SDL_Rect dst; int s, _s; Uint8 alpha=200, alpha_step = -1; Uint32 alpha_ticks = 0; char mapping[4096], temp[4096]; MappingStep *step, *prev_step; MappingStep steps[] = { {342, 132, 0.0, MARKER_BUTTON, "x", -1, -1, -1, -1, ""}, {387, 167, 0.0, MARKER_BUTTON, "a", -1, -1, -1, -1, ""}, {431, 132, 0.0, MARKER_BUTTON, "b", -1, -1, -1, -1, ""}, {389, 101, 0.0, MARKER_BUTTON, "y", -1, -1, -1, -1, ""}, {174, 132, 0.0, MARKER_BUTTON, "back", -1, -1, -1, -1, ""}, {233, 132, 0.0, MARKER_BUTTON, "guide", -1, -1, -1, -1, ""}, {289, 132, 0.0, MARKER_BUTTON, "start", -1, -1, -1, -1, ""}, {116, 217, 0.0, MARKER_BUTTON, "dpleft", -1, -1, -1, -1, ""}, {154, 249, 0.0, MARKER_BUTTON, "dpdown", -1, -1, -1, -1, ""}, {186, 217, 0.0, MARKER_BUTTON, "dpright", -1, -1, -1, -1, ""}, {154, 188, 0.0, MARKER_BUTTON, "dpup", -1, -1, -1, -1, ""}, {77, 40, 0.0, MARKER_BUTTON, "leftshoulder", -1, -1, -1, -1, ""}, {91, 0, 0.0, MARKER_BUTTON, "lefttrigger", -1, -1, -1, -1, ""}, {396, 36, 0.0, MARKER_BUTTON, "rightshoulder", -1, -1, -1, -1, ""}, {375, 0, 0.0, MARKER_BUTTON, "righttrigger", -1, -1, -1, -1, ""}, {75, 154, 0.0, MARKER_BUTTON, "leftstick", -1, -1, -1, -1, ""}, {305, 230, 0.0, MARKER_BUTTON, "rightstick", -1, -1, -1, -1, ""}, {75, 154, 0.0, MARKER_AXIS, "leftx", -1, -1, -1, -1, ""}, {75, 154, 90.0, MARKER_AXIS, "lefty", -1, -1, -1, -1, ""}, {305, 230, 0.0, MARKER_AXIS, "rightx", -1, -1, -1, -1, ""}, {305, 230, 90.0, MARKER_AXIS, "righty", -1, -1, -1, -1, ""}, }; /* Create a window to display joystick axis position */ window = SDL_CreateWindow("Game Controller Map", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, 0); if (window == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window: %s\n", SDL_GetError()); return SDL_FALSE; } screen = SDL_CreateRenderer(window, -1, 0); if (screen == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create renderer: %s\n", SDL_GetError()); SDL_DestroyWindow(window); return SDL_FALSE; } background = LoadTexture(screen, "controllermap.bmp", SDL_FALSE); button = LoadTexture(screen, "button.bmp", SDL_TRUE); axis = LoadTexture(screen, "axis.bmp", SDL_TRUE); SDL_RaiseWindow(window); /* scale for platforms that don't give you the window size you asked for. */ SDL_RenderSetLogicalSize(screen, SCREEN_WIDTH, SCREEN_HEIGHT); /* Print info about the joystick we are watching */ name = SDL_JoystickName(joystick); SDL_Log("Watching joystick %d: (%s)\n", SDL_JoystickInstanceID(joystick), name ? name : "Unknown Joystick"); SDL_Log("Joystick has %d axes, %d hats, %d balls, and %d buttons\n", SDL_JoystickNumAxes(joystick), SDL_JoystickNumHats(joystick), SDL_JoystickNumBalls(joystick), SDL_JoystickNumButtons(joystick)); SDL_Log("\n\n\ ====================================================================================\n\ Press the buttons on your controller when indicated\n\ (Your controller may look different than the picture)\n\ If you want to correct a mistake, press backspace or the back button on your device\n\ To skip a button, press SPACE or click/touch the screen\n\ To exit, press ESC\n\ ====================================================================================\n"); /* Initialize mapping with GUID and name */ SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), temp, SDL_arraysize(temp)); SDL_snprintf(mapping, SDL_arraysize(mapping), "%s,%s,platform:%s,", temp, name ? name : "Unknown Joystick", SDL_GetPlatform()); /* Loop, getting joystick events! */ for(s=0; s<SDL_arraysize(steps) && !done;) { /* blank screen, set up for drawing this frame. */ step = &steps[s]; SDL_strlcpy(step->mapping, mapping, SDL_arraysize(step->mapping)); step->axis = -1; step->button = -1; step->hat = -1; step->hat_value = -1; switch(step->marker) { case MARKER_AXIS: marker = axis; break; case MARKER_BUTTON: marker = button; break; default: break; } dst.x = step->x; dst.y = step->y; SDL_QueryTexture(marker, NULL, NULL, &dst.w, &dst.h); next=SDL_FALSE; SDL_SetRenderDrawColor(screen, 0xFF, 0xFF, 0xFF, SDL_ALPHA_OPAQUE); while (!done && !next) { if (SDL_GetTicks() - alpha_ticks > 5) { alpha_ticks = SDL_GetTicks(); alpha += alpha_step; if (alpha == 255) { alpha_step = -1; } if (alpha < 128) { alpha_step = 1; } } SDL_RenderClear(screen); SDL_RenderCopy(screen, background, NULL, NULL); SDL_SetTextureAlphaMod(marker, alpha); SDL_SetTextureColorMod(marker, 10, 255, 21); SDL_RenderCopyEx(screen, marker, NULL, &dst, step->angle, NULL, 0); SDL_RenderPresent(screen); if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_JOYAXISMOTION: if (event.jaxis.value > 20000 || event.jaxis.value < -20000) { for (_s = 0; _s < s; _s++) { if (steps[_s].axis == event.jaxis.axis) { break; } } if (_s == s) { step->axis = event.jaxis.axis; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":a%u,", event.jaxis.axis); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } } break; case SDL_JOYHATMOTION: if (event.jhat.value == SDL_HAT_CENTERED) { break; /* ignore centering, we're probably just coming back to the center from the previous item we set. */ } for (_s = 0; _s < s; _s++) { if (steps[_s].hat == event.jhat.hat && steps[_s].hat_value == event.jhat.value) { break; } } if (_s == s) { step->hat = event.jhat.hat; step->hat_value = event.jhat.value; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":h%u.%u,", event.jhat.hat, event.jhat.value ); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } break; case SDL_JOYBALLMOTION: break; case SDL_JOYBUTTONUP: for (_s = 0; _s < s; _s++) { if (steps[_s].button == event.jbutton.button) { break; } } if (_s == s) { step->button = event.jbutton.button; SDL_strlcat(mapping, step->field, SDL_arraysize(mapping)); SDL_snprintf(temp, SDL_arraysize(temp), ":b%u,", event.jbutton.button); SDL_strlcat(mapping, temp, SDL_arraysize(mapping)); s++; next=SDL_TRUE; } break; case SDL_FINGERDOWN: case SDL_MOUSEBUTTONDOWN: /* Skip this step */ s++; next=SDL_TRUE; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_BACKSPACE || event.key.keysym.sym == SDLK_AC_BACK) { /* Undo! */ if (s > 0) { prev_step = &steps[--s]; SDL_strlcpy(mapping, prev_step->mapping, SDL_arraysize(prev_step->mapping)); next = SDL_TRUE; } break; } if (event.key.keysym.sym == SDLK_SPACE) { /* Skip this step */ s++; next=SDL_TRUE; break; } if ((event.key.keysym.sym != SDLK_ESCAPE)) { break; } /* Fall through to signal quit */ case SDL_QUIT: done = SDL_TRUE; break; default: break; } } } } if (s == SDL_arraysize(steps) ) { SDL_Log("Mapping:\n\n%s\n\n", mapping); /* Print to stdout as well so the user can cat the output somewhere */ printf("%s\n", mapping); } while(SDL_PollEvent(&event)) {}; SDL_DestroyRenderer(screen); SDL_DestroyWindow(window); return retval; } int main(int argc, char *argv[]) { const char *name; int i; SDL_Joystick *joystick; /* Enable standard application logging */ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); /* Initialize SDL (Note: video is required to start event loop) */ if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(1); } /* Print information about the joysticks */ SDL_Log("There are %d joysticks attached\n", SDL_NumJoysticks()); for (i = 0; i < SDL_NumJoysticks(); ++i) { name = SDL_JoystickNameForIndex(i); SDL_Log("Joystick %d: %s\n", i, name ? name : "Unknown Joystick"); joystick = SDL_JoystickOpen(i); if (joystick == NULL) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_JoystickOpen(%d) failed: %s\n", i, SDL_GetError()); } else { char guid[64]; SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joystick), guid, sizeof (guid)); SDL_Log(" axes: %d\n", SDL_JoystickNumAxes(joystick)); SDL_Log(" balls: %d\n", SDL_JoystickNumBalls(joystick)); SDL_Log(" hats: %d\n", SDL_JoystickNumHats(joystick)); SDL_Log(" buttons: %d\n", SDL_JoystickNumButtons(joystick)); SDL_Log("instance id: %d\n", SDL_JoystickInstanceID(joystick)); SDL_Log(" guid: %s\n", guid); SDL_JoystickClose(joystick); } } #ifdef __ANDROID__ if (SDL_NumJoysticks() > 0) { #else if (argv[1]) { #endif SDL_bool reportederror = SDL_FALSE; SDL_bool keepGoing = SDL_TRUE; SDL_Event event; int device; #ifdef __ANDROID__ device = 0; #else device = atoi(argv[1]); #endif joystick = SDL_JoystickOpen(device); while ( keepGoing ) { if (joystick == NULL) { if ( !reportederror ) { SDL_Log("Couldn't open joystick %d: %s\n", device, SDL_GetError()); keepGoing = SDL_FALSE; reportederror = SDL_TRUE; } } else { reportederror = SDL_FALSE; keepGoing = WatchJoystick(joystick); SDL_JoystickClose(joystick); } joystick = NULL; if (keepGoing) { SDL_Log("Waiting for attach\n"); } while (keepGoing) { SDL_WaitEvent(&event); if ((event.type == SDL_QUIT) || (event.type == SDL_FINGERDOWN) || (event.type == SDL_MOUSEBUTTONDOWN)) { keepGoing = SDL_FALSE; } else if (event.type == SDL_JOYDEVICEADDED) { joystick = SDL_JoystickOpen(device); break; } } } } else { SDL_Log("\n\nUsage: ./controllermap number\nFor example: ./controllermap 0\nOr: ./controllermap 0 >> gamecontrollerdb.txt"); } SDL_QuitSubSystem(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK); return 0; } #else int main(int argc, char *argv[]) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL compiled without Joystick support.\n"); exit(1); } #endif
811707.c
/* Copyright 2020 bbrfkr * * 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, see <http://www.gnu.org/licenses/>. */ #include "atom.h"
899803.c
/******************************************************************************* * Ledger Nano S - Secure firmware * (c) 2021 Ledger * * 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 "exceptions.h" #include "lcx_rng.h" #include "os_helpers.h" #include "os_io.h" #include "os_utils.h" #include <string.h> // apdu buffer must hold a complete apdu to avoid troubles unsigned char G_io_apdu_buffer[IO_APDU_BUFFER_SIZE]; #ifndef BOLOS_OS_UPGRADER_APP void os_boot(void) { // // TODO patch entry point when romming (f) // // set the default try context to nothing #ifndef HAVE_BOLOS try_context_set(NULL); #endif // HAVE_BOLOS // Relocation // Assumes sections are in the following order: // - .text // - .got (_sgot.._egot) // - .got.plt // - .data.rel.ro (_srelro.._erelro) // - .install_params #ifndef ROPI_MODE extern uint32_t * _erelro; extern uint32_t * _sgot; uint32_t * entry = pic(&_sgot); uint32_t * end = pic(&_erelro); while (entry <= end) { uint32_t val = pic(*entry); nvm_write(entry, &val, 4); entry++; } #endif } #endif // BOLOS_OS_UPGRADER_APP void os_memset4(void* dst, unsigned int initval, unsigned int nbintval) { while(nbintval--) { ((unsigned int*) dst)[nbintval] = initval; } } void os_xor(void * dst, void * src1, void * src2, unsigned int length) { #define SRC1 ((unsigned char const *)src1) #define SRC2 ((unsigned char const *)src2) #define DST ((unsigned char *)dst) unsigned int l = length; // don't || to ensure all condition are evaluated while(!(!length && !l)) { length--; DST[length] = SRC1[length] ^ SRC2[length]; l--; } // WHAT ??? glitch detected ? if (*((volatile unsigned int*)&l)!= *((volatile unsigned int*)&length)) { THROW(EXCEPTION); } } char os_secure_memcmp(void * src1, void * src2, unsigned int length) { #define SRC1 ((unsigned char const *)src1) #define SRC2 ((unsigned char const *)src2) unsigned int l = length; unsigned char xoracc=0; // don't || to ensure all condition are evaluated while(!(!length && !l)) { length--; xoracc |= SRC1[length] ^ SRC2[length]; l--; } // WHAT ??? glitch detected ? if (*(volatile unsigned int*)&l!=*(volatile unsigned int*)&length) { THROW(EXCEPTION); } return xoracc; } #ifndef HAVE_BOLOS void os_longjmp(unsigned int exception) { #ifdef HAVE_PRINTF unsigned int lr_val; __asm volatile("mov %0, lr" :"=r"(lr_val)); PRINTF("exception[%d]: LR=0x%08X\n", exception, lr_val); #endif // HAVE_PRINTF longjmp(try_context_get()->jmp_buf, exception); } #endif // HAVE_BOLOS // BER encoded // <tag> <length> <value> // tag: 1 byte only // length: 1 byte if little than 0x80, else 1 byte of length encoding (0x8Y, with Y the number of following bytes the length is encoded on) and then Y bytes of BE encoded total length // value: no encoding, raw data unsigned int os_parse_bertlv(unsigned char* mem, unsigned int mem_len, unsigned int * tlvoffset, unsigned int tag, unsigned int offset, void** buffer, unsigned int maxlength) { unsigned int ret, tlvoffset_in; unsigned int check_equals_buffer = offset & OS_PARSE_BERTLV_OFFSET_COMPARE_WITH_BUFFER; unsigned int get_address = offset & OS_PARSE_BERTLV_OFFSET_GET_LENGTH; offset &= ~(OS_PARSE_BERTLV_OFFSET_COMPARE_WITH_BUFFER|OS_PARSE_BERTLV_OFFSET_GET_LENGTH); // nothing to be read if (mem_len == 0 || buffer == NULL || (!get_address && *buffer == NULL)) { return 0; } // the tlv start address unsigned char* tlv = (unsigned char*) mem; unsigned int remlen = mem_len; ret = 0; // account for a shift in the tlv list before parsing tlvoffset_in = 0; if (tlvoffset) { tlvoffset_in = *tlvoffset; } // parse tlv until some tag to parse while(remlen>=2) { // tag matches unsigned int tlvtag = *tlv++; remlen--; unsigned int tlvlen = *tlv++; remlen--; if (remlen == 0) { goto retret; } if (tlvlen >= 0x80) { // invalid encoding if (tlvlen == 0x80) { goto retret; } unsigned int tlvlenlen_ = tlvlen & 0x7F; tlvlen = 0; while(tlvlenlen_--) { // BE encoded tlvlen = (tlvlen << 8) | ((*tlv++)&0xFF); remlen--; if (remlen == 0) { goto retret; } } } // check if tag matches if (tlvtag == (tag&0xFF)) { if (tlvoffset) { unsigned int o = (unsigned int) tlv - (unsigned int)mem; // compute the current position in the tlv bytes *tlvoffset = o; // skip the tag if the requested tlvoffset has not been matched yet. if (tlvoffset_in>o) { goto next_tlv; } } // avoid OOB if (offset > tlvlen || offset > remlen) { goto retret; } // check maxlength is respected for equality if (check_equals_buffer && (tlvlen-offset) != maxlength) { // buffer to check the complete given length goto retret; } maxlength = MIN(maxlength, MIN(tlvlen-offset, remlen)); // robustness check to avoid memory dumping, only allowing data space dumps if ( offset > mem_len || maxlength > mem_len || offset+maxlength > mem_len // don't rely only on provided app bounds to avoid address forgery || (unsigned int)tlv < (unsigned int)mem || (unsigned int)tlv+offset < (unsigned int)mem || (unsigned int)tlv+offset+maxlength < (unsigned int)mem || (unsigned int)tlv > (unsigned int)mem+mem_len || (unsigned int)tlv+offset > (unsigned int)mem+mem_len || (unsigned int)tlv+offset+maxlength > (unsigned int)mem+mem_len) { goto retret; } // retrieve the tlv's data content at the requested offset, and return the total data length if (get_address) { *buffer = tlv+offset; // return the tlv's total length from requested offset ret = MIN(tlvlen-offset, remlen); goto retret; } if (!check_equals_buffer) { memmove(*buffer, tlv+offset, maxlength); } else { ret = os_secure_memcmp(*buffer, tlv+offset, maxlength) == 0; goto retret; } ret = maxlength; goto retret; } next_tlv: // skip to next tlv tlv += tlvlen; remlen-=MIN(remlen, tlvlen); } retret: return ret; } #ifndef BOLOS_OS_UPGRADER_APP void safe_desynch() { volatile int a, b; unsigned int i; i = ((cx_rng_u32()&0xFF) + 1u); a = b = 1; while(i--) { a = 1 + (b << (a / 2)); b = cx_rng_u32(); } } #endif // BOLOS_OS_UPGRADER_APP void u4be_encode(unsigned char* buffer, unsigned int offset, unsigned int value) { U4BE_ENCODE(buffer, offset, value); } void u4le_encode(unsigned char* buffer, unsigned int offset, unsigned int value) { U4LE_ENCODE(buffer, offset, value); } void *os_memmove(void *dest, const void *src, size_t n) { return memmove(dest, src, n); } void *os_memcpy(void *dest, const void *src, size_t n) { return memmove(dest, src, n); } int os_memcmp(const void *s1, const void *s2, size_t n) { return memcmp(s1, s2, n); } void *os_memset(void *s, int c, size_t n) { return memset(s, c, n); }
836041.c
/* * Copyright (C)2005-2016 Haxe Foundation * * 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 <hl.h> #include <stdarg.h> static bool is_space_char( uchar c ) { return c > 8 && c < 14; } #ifdef HL_NATIVE_UCHAR_FUN HL_PRIM double utod( const uchar *str, uchar **end ) { while( is_space_char(*str) ) str++; return _utod(str,end); } HL_PRIM int utoi( const uchar *str, uchar **end ) { while( is_space_char(*str) ) str++; return _utoi(str,end); } #else #ifdef HL_ANDROID # include <android/log.h> # ifndef HL_ANDROID_LOG_TAG # define HL_ANDROID_LOG_TAG "hl" # endif # ifndef HL_ANDROID_LOG_LEVEL # define HL_ANDROID_LOG_LEVEL ANDROID_LOG_DEBUG # endif # define LOG_ANDROID(cfmt,cstr) __android_log_print(HL_ANDROID_LOG_LEVEL, HL_ANDROID_LOG_TAG, cfmt, cstr); #endif int ustrlen( const uchar *str ) { const uchar *p = str; while( *p ) p++; return (int)(p - str); } int ustrlen_utf8( const uchar *str ) { int size = 0; while(1) { uchar c = *str++; if( c == 0 ) break; if( c < 0x80 ) size++; else if( c < 0x800 ) size += 2; else if( c >= 0xD800 && c <= 0xDFFF ) { str++; size += 4; } else size += 3; } return size; } uchar *ustrdup( const uchar *str ) { int len = ustrlen(str); int size = (len + 1) << 1; uchar *d = (uchar*)malloc(size); memcpy(d,str,size); return d; } double utod( const uchar *str, uchar **end ) { char buf[31]; char *bend; int i = 0; double v; while( is_space_char(*str) ) str++; while( i < 30 ) { int c = *str++; if( (c < '0' || c > '9') && c != '.' && c != 'e' && c != 'E' && c != '-' && c != '+' ) break; buf[i++] = (char)c; } buf[i] = 0; v = strtod(buf,&bend); *end = (uchar*)(str - 1) + (bend - buf); return v; } int utoi( const uchar *str, uchar **end ) { char buf[17]; char *bend; int i = 0; int v; while( is_space_char(*str) ) str++; while( i < 16 ) { int c = *str++; if( (c < '0' || c > '9') && c != '-' ) break; buf[i++] = (char)c; } buf[i] = 0; v = strtol(buf,&bend,10); *end = (uchar*)(str - 1) + (bend - buf); return v; } int ucmp( const uchar *a, const uchar *b ) { while(true) { int d = (unsigned)*a - (unsigned)*b; if( d ) return d; if( !*a ) return 0; a++; b++; } } int usprintf( uchar *out, int out_size, const uchar *fmt, ... ) { va_list args; int ret; va_start(args, fmt); ret = uvszprintf(out, out_size, fmt, args); va_end(args); return ret; } // USE UTF-8 encoding int utostr( char *out, int out_size, const uchar *str ) { char *start = out; char *end = out + out_size - 1; // final 0 if( out_size <= 0 ) return 0; while( out < end ) { unsigned int c = *str++; if( c == 0 ) break; if( c < 0x80 ) *out++ = (char)c; else if( c < 0x800 ) { if( out + 2 > end ) break; *out++ = (char)(0xC0|(c>>6)); *out++ = 0x80|(c&63); } else if( c >= 0xD800 && c <= 0xDFFF ) { // surrogate pair if( out + 4 > end ) break; unsigned int full = (((c - 0xD800) << 10) | ((*str++) - 0xDC00)) + 0x10000; *out++ = (char)(0xF0|(full>>18)); *out++ = 0x80|((full>>12)&63); *out++ = 0x80|((full>>6)&63); *out++ = 0x80|(full&63); } else { if( out + 3 > end ) break; *out++ = (char)(0xE0|(c>>12)); *out++ = 0x80|((c>>6)&63); *out++ = 0x80|(c&63); } } *out = 0; return (int)(out - start); } static char *utos( const uchar *s ) { int len = ustrlen_utf8(s); char *out = (char*)malloc(len + 1); if( utostr(out,len+1,s) < 0 ) *out = 0; return out; } void uprintf( const uchar *fmt, const uchar *str ) { char *cfmt = utos(fmt); char *cstr = utos(str); #ifdef HL_ANDROID LOG_ANDROID(cfmt,cstr); #else printf(cfmt,cstr); #endif free(cfmt); free(cstr); } #endif #if !defined(HL_NATIVE_UCHAR_FUN) || defined(HL_WIN) HL_PRIM int uvszprintf( uchar *out, int out_size, const uchar *fmt, va_list arglist ) { uchar *start = out; uchar *end = out + out_size - 1; char cfmt[20]; char tmp[32]; uchar c; while(true) { sprintf_loop: c = *fmt++; if( out == end ) c = 0; switch( c ) { case 0: *out = 0; return (int)(out - start); case '%': { int i = 0, size = 0; cfmt[i++] = '%'; while( true ) { c = *fmt++; cfmt[i++] = (char)c; switch( c ) { case 'd': cfmt[i++] = 0; size = sprintf(tmp,cfmt,va_arg(arglist,int)); goto sprintf_add; case 'f': cfmt[i++] = 0; size = sprintf(tmp,cfmt,va_arg(arglist,double)); // according to GCC warning, float is promoted to double in var_args goto sprintf_add; case 'g': cfmt[i++] = 0; size = sprintf(tmp,cfmt,va_arg(arglist,double)); goto sprintf_add; case 'x': case 'X': cfmt[i++] = 0; if( cfmt[i-3] == 'l' ) size = sprintf(tmp,cfmt,va_arg(arglist,void*)); else size = sprintf(tmp,cfmt,va_arg(arglist,int)); goto sprintf_add; case 's': if( i != 2 ) hl_fatal("Unsupported printf format"); // no support for precision qualifier { uchar *s = va_arg(arglist,uchar *); while( *s && out < end ) *out++ = *s++; goto sprintf_loop; } case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'l': break; default: hl_fatal("Unsupported printf format"); break; } } sprintf_add: // copy from c string to u string i = 0; while( i < size && out < end ) *out++ = tmp[i++]; } break; default: *out++ = c; break; } } return 0; } #endif
35287.c
/* * Copyright (c) 2014-2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ns_types.h" #include "ns_list.h" #include "ns_timer.h" #include "ns_timer_stub.h" #include "eventOS_callback_timer.h" #include "platform/arm_hal_interrupt.h" #include "platform/arm_hal_timer.h" #include "nsdynmemLIB.h" ns_timer_stub_def ns_timer_stub; int8_t ns_timer_init(void) { return ns_timer_stub.int8_value; } int8_t eventOS_callback_timer_register(void (*timer_interrupt_handler)(int8_t, uint16_t)) { ns_timer_stub.cb = timer_interrupt_handler; return ns_timer_stub.int8_value; } int8_t eventOS_callback_timer_unregister(int8_t ns_timer_id) { return ns_timer_stub.int8_value; } int8_t ns_timer_sleep(void) { return ns_timer_stub.int8_value; } int8_t eventOS_callback_timer_start(int8_t ns_timer_id, uint16_t slots) { return ns_timer_stub.int8_value; } int8_t eventOS_callback_timer_stop(int8_t ns_timer_id) { return ns_timer_stub.int8_value; }
344589.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "calc.h" #include "trig.h" int main(void) { int i, n = 2; float a[] = {5, 2}; float *c = calloc(n, sizeof(float)); sine(a, c, n); for (i = 0; i < n; i++) printf("%f ", *(c+i)); free(c); return 0; }
918772.c
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID 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. * */ /* * broker.c - */ #ident "$Id$" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <errno.h> #include <fcntl.h> #include <assert.h> #if !defined(WINDOWS) #include <pthread.h> #include <unistd.h> #include <sys/file.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netinet/tcp.h> #include <sys/time.h> #include <sys/un.h> #else #include <io.h> #endif #ifdef BROKER_DEBUG #include <sys/time.h> #endif #include "connection_defs.h" #include "connection_cl.h" #include "system_parameter.h" #include "databases_file.h" #include "util_func.h" #include "cas_error.h" #include "cas_common.h" #include "broker_error.h" #include "broker_env_def.h" #include "broker_shm.h" #include "broker_msg.h" #include "broker_process_size.h" #include "broker_util.h" #include "broker_access_list.h" #include "broker_filename.h" #include "broker_er_html.h" #include "broker_send_fd.h" #include "error_manager.h" #include "shard_shm.h" #include "shard_metadata.h" #include "broker_proxy_conn.h" #include "dbtype_def.h" #if defined(WINDOWS) #include "broker_wsa_init.h" #endif #if defined(CAS_FOR_ORACLE) || defined(CAS_FOR_MYSQL) #define DB_EMPTY_SESSION (0) #endif /* CAS_FOR_ORACLE || CAS_FOR_MYSQL */ #ifdef WIN_FW #if !defined(WINDOWS) #error DEFINE ERROR #endif #endif #ifdef BROKER_RESTART_DEBUG #define PS_CHK_PERIOD 30 #else #define PS_CHK_PERIOD 600 #endif #ifdef ASYNC_MODE #ifdef HPUX10_2 #define SELECT_MASK int #else #define SELECT_MASK fd_set #endif #endif #define IP_ADDR_STR_LEN 20 #define BUFFER_SIZE ONE_K #define ENV_BUF_INIT_SIZE 512 #define ALIGN_ENV_BUF_SIZE(X) \ ((((X) + ENV_BUF_INIT_SIZE) / ENV_BUF_INIT_SIZE) * ENV_BUF_INIT_SIZE) #define MONITOR_SERVER_INTERVAL 5 #ifdef BROKER_DEBUG #define BROKER_LOG(X) \ do { \ FILE *fp; \ fp = fopen("broker.log", "a"); \ if (fp) { \ struct timeval tv; \ gettimeofday(&tv, NULL); \ fprintf(fp, "%d %d.%06d %s\n", __LINE__, (int)tv.tv_sec, (int)tv.tv_usec, X); \ fclose(fp); \ } \ } while (0) #define BROKER_LOG_INT(X) \ do { \ FILE *fp; \ struct timeval tv; \ gettimeofday(&tv, NULL); \ fp = fopen("broker.log", "a"); \ if (fp) { \ fprintf(fp, "%d %d.%06d %s=%d\n", __LINE__, (int)tv.tv_sec, (int)tv.tv_usec, #X, X); \ fclose(fp); \ } \ } while (0) #endif #ifdef SESSION_LOG #define SESSION_LOG_WRITE(IP, SID, APPL, INDEX) \ do { \ FILE *fp; \ struct timeval tv; \ char ip_str[64]; \ gettimeofday(&tv, NULL); \ ip2str(IP, ip_str); \ fp = fopen("session.log", "a"); \ if (fp) { \ fprintf(fp, "%d %-15s %d %d.%06d %s %d \n", br_index, ip_str, (int) SID, tv.tv_sec, tv.tv_usec, APPL, INDEX); \ fclose(fp); \ } \ } while (0) #endif #ifdef _EDU_ #define EDU_KEY "86999522480552846466422480899195252860256028745" #endif #define V3_WRITE_HEADER_OK_FILE_SOCK(sock_fd) \ do { \ char buf[V3_RESPONSE_HEADER_SIZE]; \ memset(buf, '\0', sizeof(buf)); \ sprintf(buf, V3_HEADER_OK); \ write_to_client(sock_fd, buf, sizeof(buf)); \ } while(0); #define V3_WRITE_HEADER_ERR_SOCK(sockfd) \ do { \ char buf[V3_RESPONSE_HEADER_SIZE]; \ memset(buf, '\0', sizeof(buf)); \ sprintf(buf, V3_HEADER_ERR); \ write_to_client(sockfd, buf, sizeof(buf)); \ } while(0); #define SET_BROKER_ERR_CODE() \ do { \ if (shm_br && br_index >= 0) { \ shm_br->br_info[br_index].err_code = uw_get_error_code(); \ shm_br->br_info[br_index].os_err_code = uw_get_os_error_code(); \ } \ } while (0) #define SET_BROKER_OK_CODE() \ do { \ if (shm_br && br_index >= 0) { \ shm_br->br_info[br_index].err_code = 0; \ } \ } while (0) #define CAS_SEND_ERROR_CODE(FD, VAL) \ do { \ int write_val; \ write_val = htonl(VAL); \ write_to_client(FD, (char*) &write_val, 4); \ } while (0) #define JOB_COUNT_MAX 1000000 /* num of collecting counts per monitoring interval */ #define NUM_COLLECT_COUNT_PER_INTVL 4 #define HANG_COUNT_THRESHOLD_RATIO 0.5 #if defined(WINDOWS) #define F_OK 0 #else #define SOCKET_TIMEOUT_SEC 2 #endif /* server state */ enum SERVER_STATE { SERVER_STATE_UNKNOWN = 0, SERVER_STATE_DEAD = 1, SERVER_STATE_DEREGISTERED = 2, SERVER_STATE_STARTED = 3, SERVER_STATE_NOT_REGISTERED = 4, SERVER_STATE_REGISTERED = 5, SERVER_STATE_REGISTERED_AND_TO_BE_STANDBY = 6, SERVER_STATE_REGISTERED_AND_ACTIVE = 7, SERVER_STATE_REGISTERED_AND_TO_BE_ACTIVE = 8 }; typedef struct t_clt_table T_CLT_TABLE; struct t_clt_table { SOCKET clt_sock_fd; char ip_addr[IP_ADDR_STR_LEN]; }; static void shard_broker_process (void); static void cleanup (int signo); static int init_env (void); #if !defined(WINDOWS) static int init_proxy_env (void); #endif /* !WINDOWS */ static int broker_init_shm (void); static void cas_monitor_worker (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index, int *busy_uts); static void psize_check_worker (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index); static void proxy_check_worker (int br_index, T_PROXY_INFO * proxy_info_p); static void proxy_monitor_worker (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index); static THREAD_FUNC receiver_thr_f (void *arg); static THREAD_FUNC dispatch_thr_f (void *arg); static THREAD_FUNC shard_dispatch_thr_f (void *arg); static THREAD_FUNC psize_check_thr_f (void *arg); static THREAD_FUNC cas_monitor_thr_f (void *arg); static THREAD_FUNC hang_check_thr_f (void *arg); static THREAD_FUNC proxy_monitor_thr_f (void *arg); #if !defined(WINDOWS) static THREAD_FUNC proxy_listener_thr_f (void *arg); #endif /* !WINDOWS */ static THREAD_FUNC server_monitor_thr_f (void *arg); static int read_nbytes_from_client (SOCKET sock_fd, char *buf, int size); #if defined(WIN_FW) static THREAD_FUNC service_thr_f (void *arg); static int process_cas_request (int cas_pid, int as_index, SOCKET clt_sock_fd, SOCKET srv_sock_fd); static int read_from_cas_client (SOCKET sock_fd, char *buf, int size, int as_index, int cas_pid); #endif static int write_to_client (SOCKET sock_fd, char *buf, int size); static int write_to_client_with_timeout (SOCKET sock_fd, char *buf, int size, int timeout_sec); static int read_from_client (SOCKET sock_fd, char *buf, int size); static int read_from_client_with_timeout (SOCKET sock_fd, char *buf, int size, int timeout_sec); static int run_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index); static int stop_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index); static void restart_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index); static int run_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index); static int stop_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index); static void restart_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index); static SOCKET connect_srv (char *br_name, int as_index); static int find_idle_cas (void); static int find_drop_as_index (void); static int find_add_as_index (void); static bool broker_add_new_cas (void); static void check_cas_log (char *br_name, T_APPL_SERVER_INFO * as_info_p, int as_index); static void check_proxy_log (char *br_name, T_PROXY_INFO * proxy_info_p); static void check_proxy_access_log (T_PROXY_INFO * proxy_info_p); static void get_as_sql_log_filename (char *log_filename, int len, char *broker_name, T_APPL_SERVER_INFO * as_info_p, int as_index); static void get_as_slow_log_filename (char *log_filename, int len, char *broker_name, T_APPL_SERVER_INFO * as_info_p, int as_index); static CSS_CONN_ENTRY *connect_to_master_for_server_monitor (const char *db_name, const char *db_host); static int get_server_state_from_master (CSS_CONN_ENTRY * conn, const char *db_name); static int insert_db_server_check_list (T_DB_SERVER * list_p, int check_list_cnt, const char *db_name, const char *db_host); #if defined(WINDOWS) static int get_cputime_sec (int pid); #endif static SOCKET sock_fd; static struct sockaddr_in sock_addr; static int sock_addr_len; #if defined(WINDOWS) static struct sockaddr_in shard_sock_addr; #else /* WINDOWS */ static SOCKET proxy_sock_fd; static struct sockaddr_un shard_sock_addr; #endif /* !WINDOWS */ static T_SHM_BROKER *shm_br = NULL; static T_SHM_APPL_SERVER *shm_appl; static T_BROKER_INFO *br_info_p = NULL; static T_SHM_PROXY *shm_proxy_p = NULL; static int br_index = -1; static int br_shard_flag = OFF; #if defined(WIN_FW) static int num_thr; #endif static pthread_cond_t clt_table_cond; static pthread_mutex_t clt_table_mutex; static pthread_mutex_t run_appl_mutex; static pthread_mutex_t broker_shm_mutex; static pthread_mutex_t run_proxy_mutex; static char run_proxy_flag = 0; static char run_appl_server_flag = 0; static int current_dropping_as_index = -1; static int process_flag = 1; static int num_busy_uts = 0; static int max_open_fd = 128; #if defined(WIN_FW) static int last_job_fetch_time; static time_t last_session_id = 0; static T_MAX_HEAP_NODE *session_request_q; #endif static int hold_job = 0; static bool broker_add_new_cas (void) { int cur_appl_server_num; int add_as_index; int pid; cur_appl_server_num = shm_br->br_info[br_index].appl_server_num; /* ADD UTS */ if (cur_appl_server_num >= shm_br->br_info[br_index].appl_server_max_num) { return false; } add_as_index = find_add_as_index (); if (add_as_index < 0) { return false; } pid = run_appl_server (&(shm_appl->as_info[add_as_index]), br_index, add_as_index); if (pid <= 0) { return false; } pthread_mutex_lock (&broker_shm_mutex); shm_appl->as_info[add_as_index].pid = pid; shm_appl->as_info[add_as_index].psize = getsize (pid); shm_appl->as_info[add_as_index].psize_time = time (NULL); shm_appl->as_info[add_as_index].uts_status = UTS_STATUS_IDLE; shm_appl->as_info[add_as_index].service_flag = SERVICE_ON; shm_appl->as_info[add_as_index].reset_flag = FALSE; memset (&shm_appl->as_info[add_as_index].cas_clt_ip[0], 0x0, sizeof (shm_appl->as_info[add_as_index].cas_clt_ip)); shm_appl->as_info[add_as_index].cas_clt_port = 0; shm_appl->as_info[add_as_index].driver_version[0] = '\0'; (shm_br->br_info[br_index].appl_server_num)++; (shm_appl->num_appl_server)++; pthread_mutex_unlock (&broker_shm_mutex); return true; } static bool broker_drop_one_cas_by_time_to_kill (void) { int cur_appl_server_num, wait_job_cnt; int drop_as_index; T_APPL_SERVER_INFO *drop_as_info; /* DROP UTS */ cur_appl_server_num = shm_br->br_info[br_index].appl_server_num; wait_job_cnt = shm_appl->job_queue[0].id + hold_job; wait_job_cnt -= (cur_appl_server_num - num_busy_uts); if (cur_appl_server_num <= shm_br->br_info[br_index].appl_server_min_num || wait_job_cnt > 0) { return false; } drop_as_index = find_drop_as_index (); if (drop_as_index < 0) { return false; } pthread_mutex_lock (&broker_shm_mutex); current_dropping_as_index = drop_as_index; drop_as_info = &shm_appl->as_info[drop_as_index]; drop_as_info->service_flag = SERVICE_OFF_ACK; pthread_mutex_unlock (&broker_shm_mutex); CON_STATUS_LOCK (drop_as_info, CON_STATUS_LOCK_BROKER); if (drop_as_info->uts_status == UTS_STATUS_IDLE) { /* do nothing */ } else if (drop_as_info->cur_keep_con == KEEP_CON_AUTO && drop_as_info->uts_status == UTS_STATUS_BUSY && drop_as_info->con_status == CON_STATUS_OUT_TRAN && time (NULL) - drop_as_info->last_access_time > shm_br->br_info[br_index].time_to_kill) { drop_as_info->con_status = CON_STATUS_CLOSE; } else { drop_as_info->service_flag = SERVICE_ON; drop_as_index = -1; } CON_STATUS_UNLOCK (drop_as_info, CON_STATUS_LOCK_BROKER); if (drop_as_index >= 0) { pthread_mutex_lock (&broker_shm_mutex); (shm_br->br_info[br_index].appl_server_num)--; (shm_appl->num_appl_server)--; pthread_mutex_unlock (&broker_shm_mutex); stop_appl_server (drop_as_info, br_index, drop_as_index); } current_dropping_as_index = -1; return true; } #if defined(WINDOWS) int WINAPI WinMain (HINSTANCE hInstance, // handle to current instance HINSTANCE hPrevInstance, // handle to previous instance LPSTR lpCmdLine, // pointer to command line int nShowCmd // show state of window ) #else int main (int argc, char *argv[]) #endif { pthread_t receiver_thread; pthread_t dispatch_thread; pthread_t cas_monitor_thread; pthread_t psize_check_thread; pthread_t hang_check_thread; pthread_t server_monitor_thread; pthread_t proxy_monitor_thread; #if !defined(WINDOWS) pthread_t proxy_listener_thread; #endif /* !WINDOWS */ #if defined(WIN_FW) pthread_t service_thread; int *thr_index; int i; #endif int error; error = broker_init_shm (); if (error) { goto error1; } br_shard_flag = br_info_p->shard_flag; signal (SIGTERM, cleanup); signal (SIGINT, cleanup); #if !defined(WINDOWS) signal (SIGCHLD, SIG_IGN); signal (SIGPIPE, SIG_IGN); #endif pthread_cond_init (&clt_table_cond, NULL); pthread_mutex_init (&clt_table_mutex, NULL); pthread_mutex_init (&run_appl_mutex, NULL); pthread_mutex_init (&broker_shm_mutex, NULL); if (br_shard_flag == ON) { pthread_mutex_init (&run_proxy_mutex, NULL); } #if defined(WINDOWS) if (wsa_initialize () < 0) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, 0); goto error1; } #endif /* WINDOWS */ if (br_shard_flag == OFF && uw_acl_make (shm_br->br_info[br_index].acl_file) < 0) { goto error1; } if (init_env () == -1) { goto error1; } if (br_shard_flag == ON) { #if !defined(WINDOWS) if (init_proxy_env () == -1) { goto error1; } if (broker_init_proxy_conn (br_info_p->num_proxy) < 0) { goto error1; } #endif /* !WINDOWS */ } else { #if defined(WIN_FW) num_thr = shm_br->br_info[br_index].appl_server_max_num; thr_index = (int *) malloc (sizeof (int) * num_thr); if (thr_index == NULL) { UW_SET_ERROR_CODE (UW_ER_NO_MORE_MEMORY, 0); goto error1; } /* initialize session request queue. queue size is 1 */ session_request_q = (T_MAX_HEAP_NODE *) malloc (sizeof (T_MAX_HEAP_NODE) * num_thr); if (session_request_q == NULL) { UW_SET_ERROR_CODE (UW_ER_NO_MORE_MEMORY, 0); goto error1; } for (i = 0; i < num_thr; i++) { session_request_q[i].clt_sock_fd = INVALID_SOCKET; } #endif } set_cubrid_file (FID_SQL_LOG_DIR, shm_appl->log_dir); set_cubrid_file (FID_SLOW_LOG_DIR, shm_appl->slow_log_dir); while (shm_br->br_info[br_index].ready_to_service != true) { SLEEP_MILISEC (0, 200); } THREAD_BEGIN (receiver_thread, receiver_thr_f, NULL); if (br_shard_flag == ON) { THREAD_BEGIN (dispatch_thread, shard_dispatch_thr_f, NULL); } else { THREAD_BEGIN (dispatch_thread, dispatch_thr_f, NULL); } THREAD_BEGIN (psize_check_thread, psize_check_thr_f, NULL); THREAD_BEGIN (cas_monitor_thread, cas_monitor_thr_f, NULL); THREAD_BEGIN (server_monitor_thread, server_monitor_thr_f, NULL); if (br_shard_flag == ON) { THREAD_BEGIN (proxy_monitor_thread, proxy_monitor_thr_f, NULL); #if !defined(WINDOWS) THREAD_BEGIN (proxy_listener_thread, proxy_listener_thr_f, NULL); #endif /* !WINDOWS */ } if (shm_br->br_info[br_index].monitor_hang_flag) { THREAD_BEGIN (hang_check_thread, hang_check_thr_f, NULL); } if (br_shard_flag == ON) { br_info_p->err_code = 0; /* DO NOT DELETE!!! : reset error code */ shard_broker_process (); } else { #if defined(WIN_FW) for (i = 0; i < num_thr; i++) { thr_index[i] = i; THREAD_BEGIN (service_thread, service_thr_f, thr_index + i); shm_appl->as_info[i].last_access_time = time (NULL); shm_appl->as_info[i].transaction_start_time = (time_t) 0; if (i < shm_br->br_info[br_index].appl_server_min_num) { shm_appl->as_info[i].service_flag = SERVICE_ON; } else { shm_appl->as_info[i].service_flag = SERVICE_OFF_ACK; } } #endif SET_BROKER_OK_CODE (); while (process_flag) { SLEEP_MILISEC (0, 100); if (shm_br->br_info[br_index].auto_add_appl_server == OFF) { continue; } broker_drop_one_cas_by_time_to_kill (); } /* end of while (process_flag) */ } /* end of if (SHARD == OFF) */ error1: if (br_shard_flag == ON) { #if !defined(WINDOWS) broker_destroy_proxy_conn (); #endif /* !WINDOWS */ } SET_BROKER_ERR_CODE (); return -1; } static void shard_broker_process (void) { int proxy_index, shard_index, i; T_PROXY_INFO *proxy_info_p; T_SHARD_INFO *shard_info_p; T_APPL_SERVER_INFO *as_info_p; while (process_flag) { SLEEP_MILISEC (0, 100); if (shm_br->br_info[br_index].auto_add_appl_server == OFF) { continue; } /* ADD UTS */ for (proxy_index = 0; proxy_index < shm_proxy_p->num_proxy; proxy_index++) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, proxy_index); for (shard_index = 0; shard_index < proxy_info_p->num_shard_conn; shard_index++) { shard_info_p = shard_shm_find_shard_info (proxy_info_p, shard_index); if ((shard_info_p->waiter_count > 0) && (shard_info_p->num_appl_server < shard_info_p->max_appl_server)) { for (i = shard_info_p->min_appl_server; i < shard_info_p->max_appl_server; i++) { as_info_p = &(shm_appl->as_info[i + shard_info_p->as_info_index_base]); if (as_info_p->service_flag == SERVICE_OFF) { int pid; as_info_p->uts_status = UTS_STATUS_START; as_info_p->cur_sql_log_mode = shm_appl->sql_log_mode; as_info_p->cur_slow_log_mode = shm_appl->slow_log_mode; pid = run_appl_server (as_info_p, br_index, i + shard_info_p->as_info_index_base); if (pid > 0) { as_info_p->pid = pid; as_info_p->psize = getsize (pid); as_info_p->psize_time = time (NULL); as_info_p->service_flag = SERVICE_ON; as_info_p->reset_flag = FALSE; (shm_br->br_info[br_index].appl_server_num)++; (shard_info_p->num_appl_server)++; (shm_appl->num_appl_server)++; } break; } } } } } } return; } static void cleanup (int signo) { signal (signo, SIG_IGN); process_flag = 0; #ifdef SOLARIS SLEEP_MILISEC (1, 0); #endif CLOSE_SOCKET (sock_fd); if (br_shard_flag == ON) { #if !defined(WINDOWS) CLOSE_SOCKET (proxy_sock_fd); #endif /* !WINDOWS */ } exit (0); } static void send_error_to_driver (int sock, int error, char *driver_info) { int write_val; int driver_version; driver_version = CAS_MAKE_PROTO_VER (driver_info); if (error == NO_ERROR) { write_val = 0; } else { if (driver_version == CAS_PROTO_MAKE_VER (PROTOCOL_V2) || cas_di_understand_renewed_error_code (driver_info)) { write_val = htonl (error); } else { write_val = htonl (CAS_CONV_ERROR_TO_OLD (error)); } } write_to_client (sock, (char *) &write_val, sizeof (int)); } static const char *cas_client_type_str[] = { "UNKNOWN", /* CAS_CLIENT_NONE */ "CCI", /* CAS_CLIENT_CCI */ "ODBC", /* CAS_CLIENT_ODBC */ "JDBC", /* CAS_CLIENT_JDBC */ "PHP", /* CAS_CLIENT_PHP */ "OLEDB", /* CAS_CLIENT_OLEDB */ "INTERNAL_JDBC", /* CAS_CLIENT_SERVER_SIDE_JDBC */ "GATEWAY_CCI" /* CAS_CLIENT_GATEWAY */ }; static THREAD_FUNC receiver_thr_f (void *arg) { T_SOCKLEN clt_sock_addr_len; struct sockaddr_in clt_sock_addr; SOCKET clt_sock_fd; int job_queue_size; T_MAX_HEAP_NODE *job_queue; T_MAX_HEAP_NODE new_job; int job_count; int read_len; int one = 1; char cas_req_header[SRV_CON_CLIENT_INFO_SIZE]; char cas_client_type; char driver_version; T_BROKER_VERSION client_version; #if defined(LINUX) int timeout; #endif /* LINUX */ job_queue_size = shm_appl->job_queue_size; job_queue = shm_appl->job_queue; job_count = 1; #if !defined(WINDOWS) signal (SIGPIPE, SIG_IGN); #endif #if defined(LINUX) timeout = 5; setsockopt (sock_fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, (char *) &timeout, sizeof (timeout)); #endif /* LINUX */ while (process_flag) { clt_sock_addr_len = sizeof (clt_sock_addr); clt_sock_fd = accept (sock_fd, (struct sockaddr *) &clt_sock_addr, &clt_sock_addr_len); if (IS_INVALID_SOCKET (clt_sock_fd)) { continue; } if (shm_br->br_info[br_index].monitor_hang_flag && shm_br->br_info[br_index].reject_client_flag) { shm_br->br_info[br_index].reject_client_count++; CLOSE_SOCKET (clt_sock_fd); continue; } #if !defined(WINDOWS) && defined(ASYNC_MODE) if (fcntl (clt_sock_fd, F_SETFL, FNDELAY) < 0) { CLOSE_SOCKET (clt_sock_fd); continue; } #endif setsockopt (clt_sock_fd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof (one)); ut_set_keepalive (clt_sock_fd); cas_client_type = CAS_CLIENT_NONE; /* read header */ read_len = read_nbytes_from_client (clt_sock_fd, cas_req_header, SRV_CON_CLIENT_INFO_SIZE); if (read_len < 0) { CLOSE_SOCKET (clt_sock_fd); continue; } if (strncmp (cas_req_header, "PING", 4) == 0) { int ret_code = 0; CAS_SEND_ERROR_CODE (clt_sock_fd, ret_code); CLOSE_SOCKET (clt_sock_fd); continue; } if (strncmp (cas_req_header, "ST", 2) == 0) { int status = FN_STATUS_NONE; int pid, i; unsigned int session_id; memcpy ((char *) &pid, cas_req_header + 2, 4); pid = ntohl (pid); memcpy ((char *) &session_id, cas_req_header + 6, 4); session_id = ntohl (session_id); if (shm_br->br_info[br_index].shard_flag == OFF) { for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { if (shm_appl->as_info[i].service_flag == SERVICE_ON && shm_appl->as_info[i].pid == pid) { if (session_id == shm_appl->as_info[i].session_id) { status = shm_appl->as_info[i].fn_status; } break; } } } CAS_SEND_ERROR_CODE (clt_sock_fd, status); CLOSE_SOCKET (clt_sock_fd); continue; } /* * Query cancel message (size in bytes) * * - For client version 8.4.0 patch 1 or below: * |COMMAND("CANCEL",6)|PID(4)| * * - For CAS protocol version 1 or above: * |COMMAND("QC",2)|PID(4)|CLIENT_PORT(2)|RESERVED(2)| * * CLIENT_PORT can be 0 if the client failed to get its local port. */ else if (strncmp (cas_req_header, "QC", 2) == 0 || strncmp (cas_req_header, "CANCEL", 6) == 0 || strncmp (cas_req_header, "X1", 2) == 0) { int ret_code = 0; #if !defined(WINDOWS) int pid, i; unsigned short client_port = 0; #endif #if !defined(WINDOWS) if (cas_req_header[0] == 'Q') { memcpy ((char *) &pid, cas_req_header + 2, 4); memcpy ((char *) &client_port, cas_req_header + 6, 2); pid = ntohl (pid); client_port = ntohs (client_port); } else { memcpy ((char *) &pid, cas_req_header + 6, 4); pid = ntohl (pid); } ret_code = CAS_ER_QUERY_CANCEL; if (shm_br->br_info[br_index].shard_flag == OFF) { for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { if (shm_appl->as_info[i].service_flag == SERVICE_ON && shm_appl->as_info[i].pid == pid && shm_appl->as_info[i].uts_status == UTS_STATUS_BUSY) { if (cas_req_header[0] == 'Q' && client_port > 0 && shm_appl->as_info[i].cas_clt_port != client_port && memcmp (&shm_appl->as_info[i].cas_clt_ip, &clt_sock_addr.sin_addr, 4) != 0) { continue; } ret_code = 0; kill (pid, SIGUSR1); break; } } } else { /* SHARD TODO : not implemented yet */ } #endif if (cas_req_header[0] == 'X') { char driver_info[SRV_CON_CLIENT_INFO_SIZE]; driver_info[SRV_CON_MSG_IDX_PROTO_VERSION] = cas_req_header[2]; driver_info[SRV_CON_MSG_IDX_FUNCTION_FLAG] = cas_req_header[3]; send_error_to_driver (clt_sock_fd, ret_code, driver_info); } else { ret_code = CAS_CONV_ERROR_TO_OLD (ret_code); CAS_SEND_ERROR_CODE (clt_sock_fd, ret_code); } CLOSE_SOCKET (clt_sock_fd); continue; } cas_client_type = cas_req_header[SRV_CON_MSG_IDX_CLIENT_TYPE]; if (!(strncmp (cas_req_header, SRV_CON_CLIENT_MAGIC_STR, SRV_CON_CLIENT_MAGIC_LEN) == 0 || strncmp (cas_req_header, SRV_CON_CLIENT_MAGIC_STR_SSL, SRV_CON_CLIENT_MAGIC_LEN) == 0) || cas_client_type < CAS_CLIENT_TYPE_MIN || cas_client_type > CAS_CLIENT_TYPE_MAX) { send_error_to_driver (clt_sock_fd, CAS_ER_NOT_AUTHORIZED_CLIENT, cas_req_header); CLOSE_SOCKET (clt_sock_fd); continue; } if ((IS_SSL_CLIENT (cas_req_header) && shm_br->br_info[br_index].use_SSL == OFF) || (!IS_SSL_CLIENT (cas_req_header) && shm_br->br_info[br_index].use_SSL == ON)) { send_error_to_driver (clt_sock_fd, CAS_ER_SSL_TYPE_NOT_ALLOWED, cas_req_header); CLOSE_SOCKET (clt_sock_fd); continue; } driver_version = cas_req_header[SRV_CON_MSG_IDX_PROTO_VERSION]; if (driver_version & CAS_PROTO_INDICATOR) { /* Protocol version */ client_version = CAS_PROTO_UNPACK_NET_VER (driver_version); } else { /* Build version; major, minor, and patch */ client_version = CAS_MAKE_VER (cas_req_header[SRV_CON_MSG_IDX_MAJOR_VER], cas_req_header[SRV_CON_MSG_IDX_MINOR_VER], cas_req_header[SRV_CON_MSG_IDX_PATCH_VER]); } if (br_shard_flag == ON) { /* SHARD ONLY SUPPORT client_version.8.2.0 ~ */ if (client_version < CAS_MAKE_VER (8, 2, 0)) { CAS_SEND_ERROR_CODE (clt_sock_fd, CAS_ER_COMMUNICATION); CLOSE_SOCKET (clt_sock_fd); continue; } } if (v3_acl != NULL) { unsigned char ip_addr[4]; memcpy (ip_addr, &(clt_sock_addr.sin_addr), 4); if (uw_acl_check (ip_addr) < 0) { send_error_to_driver (clt_sock_fd, CAS_ER_NOT_AUTHORIZED_CLIENT, cas_req_header); CLOSE_SOCKET (clt_sock_fd); continue; } } if (job_queue[0].id == job_queue_size) { send_error_to_driver (clt_sock_fd, CAS_ER_FREE_SERVER, cas_req_header); CLOSE_SOCKET (clt_sock_fd); continue; } if (max_open_fd < clt_sock_fd) { max_open_fd = clt_sock_fd; } job_count = (job_count >= JOB_COUNT_MAX) ? 1 : job_count + 1; new_job.id = job_count; new_job.clt_sock_fd = clt_sock_fd; new_job.recv_time = time (NULL); new_job.priority = 0; new_job.script[0] = '\0'; new_job.cas_client_type = cas_client_type; new_job.port = ntohs (clt_sock_addr.sin_port); memcpy (new_job.ip_addr, &(clt_sock_addr.sin_addr), 4); strcpy (new_job.prg_name, cas_client_type_str[(int) cas_client_type]); new_job.clt_version = client_version; memcpy (new_job.driver_info, cas_req_header, SRV_CON_CLIENT_INFO_SIZE); while (1) { pthread_mutex_lock (&clt_table_mutex); if (max_heap_insert (job_queue, job_queue_size, &new_job) < 0) { pthread_mutex_unlock (&clt_table_mutex); SLEEP_MILISEC (0, 100); } else { pthread_cond_signal (&clt_table_cond); pthread_mutex_unlock (&clt_table_mutex); break; } } } #if defined(WINDOWS) return; #else return NULL; #endif } static THREAD_FUNC shard_dispatch_thr_f (void *arg) { T_MAX_HEAP_NODE *job_queue; T_MAX_HEAP_NODE cur_job; int ip_addr; #if defined(WINDOWS) int proxy_port; #else SOCKET proxy_fd; int proxy_status; int ret_val; #endif job_queue = shm_appl->job_queue; while (process_flag) { pthread_mutex_lock (&clt_table_mutex); if (max_heap_delete (job_queue, &cur_job) < 0) { pthread_mutex_unlock (&clt_table_mutex); SLEEP_MILISEC (0, 30); continue; } pthread_mutex_unlock (&clt_table_mutex); max_heap_incr_priority (job_queue); #if defined(WINDOWS) memcpy (&ip_addr, cur_job.ip_addr, 4); proxy_port = broker_find_available_proxy (shm_proxy_p, ip_addr, cur_job.clt_version); CAS_SEND_ERROR_CODE (cur_job.clt_sock_fd, proxy_port); CLOSE_SOCKET (cur_job.clt_sock_fd); #else /* WINDOWS */ proxy_fd = broker_find_available_proxy (shm_proxy_p); if (proxy_fd != INVALID_SOCKET) { memcpy (&ip_addr, cur_job.ip_addr, 4); ret_val = send_fd (proxy_fd, cur_job.clt_sock_fd, ip_addr, cur_job.driver_info); if (ret_val > 0) { ret_val = read_from_client_with_timeout (proxy_fd, (char *) &proxy_status, sizeof (int), SOCKET_TIMEOUT_SEC); if (ret_val < 0) { broker_delete_proxy_conn_by_fd (proxy_fd); CLOSE_SOCKET (proxy_fd); send_error_to_driver (cur_job.clt_sock_fd, CAS_ER_FREE_SERVER, cur_job.driver_info); } } else { broker_delete_proxy_conn_by_fd (proxy_fd); CLOSE_SOCKET (proxy_fd); send_error_to_driver (cur_job.clt_sock_fd, CAS_ER_FREE_SERVER, cur_job.driver_info); } } else { send_error_to_driver (cur_job.clt_sock_fd, CAS_ER_FREE_SERVER, cur_job.driver_info); } CLOSE_SOCKET (cur_job.clt_sock_fd); #endif /* !WINDOWS */ } #if defined(WINDOWS) return; #else return NULL; #endif } static THREAD_FUNC dispatch_thr_f (void *arg) { T_MAX_HEAP_NODE *job_queue; T_MAX_HEAP_NODE cur_job; #if !defined(WINDOWS) SOCKET srv_sock_fd; #endif /* !WINDOWS */ int as_index, i; job_queue = shm_appl->job_queue; while (process_flag) { for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { if (shm_appl->as_info[i].service_flag == SERVICE_OFF) { if (shm_appl->as_info[i].uts_status == UTS_STATUS_IDLE) shm_appl->as_info[i].service_flag = SERVICE_OFF_ACK; } } pthread_mutex_lock (&clt_table_mutex); if (max_heap_delete (job_queue, &cur_job) < 0) { struct timespec ts; struct timeval tv; int r; gettimeofday (&tv, NULL); ts.tv_sec = tv.tv_sec; ts.tv_nsec = (tv.tv_usec + 30000) * 1000; if (ts.tv_nsec > 1000000000) { ts.tv_sec += 1; ts.tv_nsec -= 1000000000; } r = pthread_cond_timedwait (&clt_table_cond, &clt_table_mutex, &ts); if (r != 0) { pthread_mutex_unlock (&clt_table_mutex); continue; } r = max_heap_delete (job_queue, &cur_job); assert (r == 0); } hold_job = 1; max_heap_incr_priority (job_queue); pthread_mutex_unlock (&clt_table_mutex); #if !defined (WINDOWS) retry: #endif while (1) { as_index = find_idle_cas (); if (as_index < 0) { if (broker_add_new_cas ()) { continue; } else { SLEEP_MILISEC (0, 30); } } else { break; } } hold_job = 0; shm_appl->as_info[as_index].num_connect_requests++; #if !defined(WIN_FW) shm_appl->as_info[as_index].clt_version = cur_job.clt_version; memcpy (shm_appl->as_info[as_index].driver_info, cur_job.driver_info, SRV_CON_CLIENT_INFO_SIZE); shm_appl->as_info[as_index].cas_client_type = cur_job.cas_client_type; memcpy (shm_appl->as_info[as_index].cas_clt_ip, cur_job.ip_addr, 4); shm_appl->as_info[as_index].cas_clt_port = cur_job.port; #if defined(WINDOWS) shm_appl->as_info[as_index].uts_status = UTS_STATUS_BUSY_WAIT; CAS_SEND_ERROR_CODE (cur_job.clt_sock_fd, shm_appl->as_info[as_index].as_port); CLOSE_SOCKET (cur_job.clt_sock_fd); shm_appl->as_info[as_index].num_request++; shm_appl->as_info[as_index].last_access_time = time (NULL); shm_appl->as_info[as_index].transaction_start_time = (time_t) 0; #else /* WINDOWS */ srv_sock_fd = connect_srv (shm_br->br_info[br_index].name, as_index); if (!IS_INVALID_SOCKET (srv_sock_fd)) { int ip_addr; int ret_val; int con_status, uts_status; con_status = htonl (shm_appl->as_info[as_index].con_status); ret_val = write_to_client_with_timeout (srv_sock_fd, (char *) &con_status, sizeof (int), SOCKET_TIMEOUT_SEC); if (ret_val != sizeof (int)) { CLOSE_SOCKET (srv_sock_fd); goto retry; } ret_val = read_from_client_with_timeout (srv_sock_fd, (char *) &con_status, sizeof (int), SOCKET_TIMEOUT_SEC); if (ret_val != sizeof (int) || ntohl (con_status) != CON_STATUS_IN_TRAN) { CLOSE_SOCKET (srv_sock_fd); goto retry; } memcpy (&ip_addr, cur_job.ip_addr, 4); ret_val = send_fd (srv_sock_fd, cur_job.clt_sock_fd, ip_addr, cur_job.driver_info); if (ret_val > 0) { ret_val = read_from_client_with_timeout (srv_sock_fd, (char *) &uts_status, sizeof (int), SOCKET_TIMEOUT_SEC); } CLOSE_SOCKET (srv_sock_fd); if (ret_val < 0) { send_error_to_driver (cur_job.clt_sock_fd, CAS_ER_FREE_SERVER, cur_job.driver_info); } else { shm_appl->as_info[as_index].num_request++; } } else { goto retry; } CLOSE_SOCKET (cur_job.clt_sock_fd); #endif /* ifdef !WINDOWS */ #else /* !WIN_FW */ session_request_q[as_index] = cur_job; #endif /* WIN_FW */ } #if defined(WINDOWS) return; #else return NULL; #endif } #if defined(WIN_FW) static THREAD_FUNC service_thr_f (void *arg) { int self_index = *((int *) arg); SOCKET clt_sock_fd, srv_sock_fd; int ip_addr; int cas_pid; T_MAX_HEAP_NODE cur_job; while (process_flag) { if (!IS_INVALID_SOCKET (session_request_q[self_index].clt_sock_fd)) { cur_job = session_request_q[self_index]; session_request_q[self_index].clt_sock_fd = INVALID_SOCKET; } else { SLEEP_MILISEC (0, 10); continue; } clt_sock_fd = cur_job.clt_sock_fd; memcpy (&ip_addr, cur_job.ip_addr, 4); shm_appl->as_info[self_index].clt_major_version = cur_job.clt_major_version; shm_appl->as_info[self_index].clt_minor_version = cur_job.clt_minor_version; shm_appl->as_info[self_index].clt_patch_version = cur_job.clt_patch_version; shm_appl->as_info[self_index].cas_client_type = cur_job.cas_client_type; shm_appl->as_info[self_index].close_flag = 0; cas_pid = shm_appl->as_info[self_index].pid; srv_sock_fd = connect_srv (shm_br->br_info[br_index].name, self_index); if (IS_INVALID_SOCKET (srv_sock_fd)) { send_error_to_driver (clt_sock_fd, CAS_ER_FREE_SERVER, cur_job.driver_info); shm_appl->as_info[self_index].uts_status = UTS_STATUS_IDLE; CLOSE_SOCKET (cur_job.clt_sock_fd); continue; } else { CAS_SEND_ERROR_CODE (clt_sock_fd, 0); shm_appl->as_info[self_index].num_request++; shm_appl->as_info[self_index].last_access_time = time (NULL); shm_appl->as_info[self_index].transaction_start_time = (time_t) 0; } process_cas_request (cas_pid, self_index, clt_sock_fd, srv_sock_fd, cur_job.clt_major_version); CLOSE_SOCKET (clt_sock_fd); CLOSE_SOCKET (srv_sock_fd); } return; } #endif static int init_env (void) { char *port; int n; int one = 1; /* get a Unix stream socket */ sock_fd = socket (AF_INET, SOCK_STREAM, 0); if (IS_INVALID_SOCKET (sock_fd)) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, errno); return (-1); } if ((setsockopt (sock_fd, SOL_SOCKET, SO_REUSEADDR, (char *) &one, sizeof (one))) < 0) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, errno); return (-1); } if ((port = getenv (PORT_NUMBER_ENV_STR)) == NULL) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, 0); return (-1); } memset (&sock_addr, 0, sizeof (struct sockaddr_in)); sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons ((unsigned short) (atoi (port))); sock_addr_len = sizeof (struct sockaddr_in); n = INADDR_ANY; memcpy (&sock_addr.sin_addr, &n, sizeof (int)); if (bind (sock_fd, (struct sockaddr *) &sock_addr, sock_addr_len) < 0) { UW_SET_ERROR_CODE (UW_ER_CANT_BIND, errno); return (-1); } if (listen (sock_fd, shm_appl->job_queue_size) < 0) { UW_SET_ERROR_CODE (UW_ER_CANT_BIND, 0); return (-1); } return (0); } static int read_from_client (SOCKET sock_fd, char *buf, int size) { return read_from_client_with_timeout (sock_fd, buf, size, 60); } static int read_from_client_with_timeout (SOCKET sock_fd, char *buf, int size, int timeout_sec) { int read_len; #ifdef ASYNC_MODE SELECT_MASK read_mask; int nfound; int maxfd; struct timeval timeout_val, *timeout_ptr; if (timeout_sec < 0) { timeout_ptr = NULL; } else { timeout_val.tv_sec = timeout_sec; timeout_val.tv_usec = 0; timeout_ptr = &timeout_val; } #endif #ifdef ASYNC_MODE FD_ZERO (&read_mask); FD_SET (sock_fd, (fd_set *) (&read_mask)); maxfd = (int) sock_fd + 1; nfound = select (maxfd, &read_mask, (SELECT_MASK *) 0, (SELECT_MASK *) 0, timeout_ptr); if (nfound < 0) { return -1; } #endif #ifdef ASYNC_MODE if (FD_ISSET (sock_fd, (fd_set *) (&read_mask))) { #endif read_len = READ_FROM_SOCKET (sock_fd, buf, size); #ifdef ASYNC_MODE } else { return -1; } #endif return read_len; } static int write_to_client (SOCKET sock_fd, char *buf, int size) { return write_to_client_with_timeout (sock_fd, buf, size, 60); } static int write_to_client_with_timeout (SOCKET sock_fd, char *buf, int size, int timeout_sec) { int write_len; #ifdef ASYNC_MODE SELECT_MASK write_mask; int nfound; int maxfd; struct timeval timeout_val, *timeout_ptr; if (timeout_sec < 0) { timeout_ptr = NULL; } else { timeout_val.tv_sec = timeout_sec; timeout_val.tv_usec = 0; timeout_ptr = &timeout_val; } #endif if (IS_INVALID_SOCKET (sock_fd)) return -1; #ifdef ASYNC_MODE FD_ZERO (&write_mask); FD_SET (sock_fd, (fd_set *) (&write_mask)); maxfd = (int) sock_fd + 1; nfound = select (maxfd, (SELECT_MASK *) 0, &write_mask, (SELECT_MASK *) 0, timeout_ptr); if (nfound < 0) { return -1; } #endif #ifdef ASYNC_MODE if (FD_ISSET (sock_fd, (fd_set *) (&write_mask))) { #endif write_len = WRITE_TO_SOCKET (sock_fd, buf, size); #ifdef ASYNC_MODE } else { return -1; } #endif return write_len; } /* * run_appl_server () - * return: pid * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * proxy_index(in): it's only valid in SHARD! proxy index * shard_index(in): it's only valid in SHARD! shard index * as_index(in): cas index * * Note: activate CAS */ static int run_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index) { char appl_name[APPL_SERVER_NAME_MAX_SIZE]; int pid; char argv0[128]; #if !defined(WINDOWS) int i; #endif char as_id_env_str[32]; char appl_server_shm_key_env_str[32]; while (1) { pthread_mutex_lock (&run_appl_mutex); if (run_appl_server_flag) { pthread_mutex_unlock (&run_appl_mutex); SLEEP_MILISEC (0, 100); continue; } else { run_appl_server_flag = 1; pthread_mutex_unlock (&run_appl_mutex); break; } } as_info_p->service_ready_flag = FALSE; #if !defined(WINDOWS) signal (SIGCHLD, SIG_IGN); /* shard_cas does not have unix-domain socket */ if (br_shard_flag == OFF) { char path[BROKER_PATH_MAX]; ut_get_as_port_name (path, shm_br->br_info[br_index].name, as_index, BROKER_PATH_MAX); unlink (path); } pid = fork (); if (pid == 0) { signal (SIGCHLD, SIG_DFL); for (i = 3; i <= max_open_fd; i++) { close (i); } #endif strcpy (appl_name, shm_appl->appl_server_name); sprintf (appl_server_shm_key_env_str, "%s=%d", APPL_SERVER_SHM_KEY_STR, shm_br->br_info[br_index].appl_server_shm_id); putenv (appl_server_shm_key_env_str); snprintf (as_id_env_str, sizeof (as_id_env_str), "%s=%d", AS_ID_ENV_STR, as_index); putenv (as_id_env_str); if (shm_br->br_info[br_index].appl_server == APPL_SERVER_CAS_ORACLE) { snprintf (argv0, sizeof (argv0) - 1, "%s", appl_name); } else { if (br_shard_flag == ON) { snprintf (argv0, sizeof (argv0) - 1, "%s_%s_%d_%d_%d", shm_br->br_info[br_index].name, appl_name, as_info_p->proxy_id + 1, as_info_p->shard_id, as_info_p->shard_cas_id + 1); } else { snprintf (argv0, sizeof (argv0) - 1, "%s_%s_%d", shm_br->br_info[br_index].name, appl_name, as_index + 1); } } #if defined(WINDOWS) pid = run_child (appl_name); #else execle (appl_name, argv0, NULL, environ); #endif #if !defined(WINDOWS) exit (0); } #endif if (br_shard_flag == ON) { as_info_p->uts_status = UTS_STATUS_CON_WAIT; } CON_STATUS_LOCK_DESTROY (as_info_p); CON_STATUS_LOCK_INIT (as_info_p); if (ut_is_appl_server_ready (pid, &as_info_p->service_ready_flag)) { as_info_p->transaction_start_time = (time_t) 0; as_info_p->num_restarts++; } else { pid = -1; } run_appl_server_flag = 0; return pid; } /* * stop_appl_server () - * return: NO_ERROR * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * as_index(in): cas index * * Note: inactivate CAS */ static int stop_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index) { ut_kill_as_process (as_info_p->pid, shm_br->br_info[br_index].name, as_index, br_shard_flag); #if defined(WINDOWS) /* [CUBRIDSUS-2068] make the broker sleep for 0.1 sec when stopping the cas in order to prevent communication error * occurred on windows. */ SLEEP_MILISEC (0, 100); #endif as_info_p->pid = 0; as_info_p->last_access_time = time (NULL); as_info_p->transaction_start_time = (time_t) 0; return 0; } /* * restart_appl_server () - * return: void * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * as_index(in): cas index * * Note: inactivate and activate CAS */ static void restart_appl_server (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index) { int new_pid; #if defined(WINDOWS) ut_kill_as_process (as_info_p->pid, shm_br->br_info[br_index].name, as_info_p->as_id, br_shard_flag); /* [CUBRIDSUS-2068] make the broker sleep for 0.1 sec when stopping the cas in order to prevent communication error * occurred on windows. */ SLEEP_MILISEC (0, 100); new_pid = run_appl_server (as_info_p, br_index, as_index); as_info_p->pid = new_pid; #else as_info_p->psize = getsize (as_info_p->pid); if (as_info_p->psize > 1) { as_info_p->psize_time = time (NULL); } else { char pid_file_name[BROKER_PATH_MAX]; FILE *fp; int old_pid; ut_get_as_pid_name (pid_file_name, shm_br->br_info[br_index].name, as_index, BROKER_PATH_MAX); fp = fopen (pid_file_name, "r"); if (fp) { fscanf (fp, "%d", &old_pid); fclose (fp); as_info_p->psize = getsize (old_pid); if (as_info_p->psize > 1) { as_info_p->pid = old_pid; as_info_p->psize_time = time (NULL); } else { unlink (pid_file_name); } } } if (as_info_p->psize <= 0) { if (as_info_p->pid > 0) { ut_kill_as_process (as_info_p->pid, shm_br->br_info[br_index].name, as_index, br_shard_flag); } new_pid = run_appl_server (as_info_p, br_index, as_index); as_info_p->pid = new_pid; } #endif } static int read_nbytes_from_client (SOCKET sock_fd, char *buf, int size) { int total_read_size = 0, read_len; while (total_read_size < size) { read_len = read_from_client (sock_fd, buf + total_read_size, size - total_read_size); if (read_len <= 0) { total_read_size = -1; break; } total_read_size += read_len; } return total_read_size; } static SOCKET connect_srv (char *br_name, int as_index) { int sock_addr_len; #if defined(WINDOWS) struct sockaddr_in sock_addr; #else struct sockaddr_un sock_addr; #endif SOCKET srv_sock_fd; int one = 1; char retry_count = 0; retry: #if defined(WINDOWS) srv_sock_fd = socket (AF_INET, SOCK_STREAM, 0); if (IS_INVALID_SOCKET (srv_sock_fd)) return INVALID_SOCKET; memset (&sock_addr, 0, sizeof (struct sockaddr_in)); sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons ((unsigned short) shm_appl->as_info[as_index].as_port); memcpy (&sock_addr.sin_addr, shm_br->my_ip_addr, 4); sock_addr_len = sizeof (struct sockaddr_in); #else srv_sock_fd = socket (AF_UNIX, SOCK_STREAM, 0); if (IS_INVALID_SOCKET (srv_sock_fd)) return INVALID_SOCKET; memset (&sock_addr, 0, sizeof (struct sockaddr_un)); sock_addr.sun_family = AF_UNIX; ut_get_as_port_name (sock_addr.sun_path, br_name, as_index, sizeof (sock_addr.sun_path)); sock_addr_len = strlen (sock_addr.sun_path) + sizeof (sock_addr.sun_family) + 1; #endif if (connect (srv_sock_fd, (struct sockaddr *) &sock_addr, sock_addr_len) < 0) { if (retry_count < 1) { int new_pid; ut_kill_as_process (shm_appl->as_info[as_index].pid, shm_br->br_info[br_index].name, as_index, br_shard_flag); new_pid = run_appl_server (&(shm_appl->as_info[as_index]), br_index, as_index); shm_appl->as_info[as_index].pid = new_pid; retry_count++; CLOSE_SOCKET (srv_sock_fd); goto retry; } CLOSE_SOCKET (srv_sock_fd); return INVALID_SOCKET; } setsockopt (srv_sock_fd, IPPROTO_TCP, TCP_NODELAY, (char *) &one, sizeof (one)); return srv_sock_fd; } /* * cas_monitor_worker () - * return: void * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * as_index(in): cas index * busy_uts(out): counting UTS_STATUS_BUSY status cas * * Note: monitoring CAS */ static void cas_monitor_worker (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index, int *busy_uts) { int new_pid; int restart_flag = OFF; T_PROXY_INFO *proxy_info_p = NULL; T_SHARD_INFO *shard_info_p = NULL; if (as_info_p->service_flag != SERVICE_ON) { return; } if (as_info_p->uts_status == UTS_STATUS_BUSY) { (*busy_uts)++; } #if defined(WINDOWS) else if (as_info_p->uts_status == UTS_STATUS_BUSY_WAIT) { if (time (NULL) - as_info_p->last_access_time > 10) { as_info_p->uts_status = UTS_STATUS_IDLE; } else { (*busy_uts)++; } } #endif #if defined(WINDOWS) if (shm_appl->use_pdh_flag == TRUE) { if ((as_info_p->pid == as_info_p->pdh_pid) && (as_info_p->pdh_workset > shm_br->br_info[br_index].appl_server_hard_limit)) { as_info_p->uts_status = UTS_STATUS_RESTART; } } #else if (as_info_p->psize > shm_appl->appl_server_hard_limit) { as_info_p->uts_status = UTS_STATUS_RESTART; } #endif /* if (as_info_p->service_flag != SERVICE_ON) continue; */ /* check cas process status and restart it */ if (br_shard_flag == ON && (as_info_p->uts_status == UTS_STATUS_BUSY || as_info_p->uts_status == UTS_STATUS_IDLE || as_info_p->uts_status == UTS_STATUS_START)) { restart_flag = ON; } else if (br_shard_flag == OFF && as_info_p->uts_status == UTS_STATUS_BUSY) { restart_flag = ON; } if (restart_flag) { #if defined(WINDOWS) HANDLE phandle; phandle = OpenProcess (SYNCHRONIZE, FALSE, as_info_p->pid); if (phandle == NULL) { restart_appl_server (as_info_p, br_index, as_index); as_info_p->uts_status = UTS_STATUS_IDLE; } else { CloseHandle (phandle); } #else if (kill (as_info_p->pid, 0) < 0) { restart_appl_server (as_info_p, br_index, as_index); as_info_p->uts_status = UTS_STATUS_IDLE; } #endif } if (as_info_p->uts_status == UTS_STATUS_RESTART) { stop_appl_server (as_info_p, br_index, as_index); new_pid = run_appl_server (as_info_p, br_index, as_index); as_info_p->pid = new_pid; as_info_p->uts_status = UTS_STATUS_IDLE; } else if (br_shard_flag == ON && as_info_p->uts_status == UTS_STATUS_STOP) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, as_info_p->proxy_id); shard_info_p = shard_shm_find_shard_info (proxy_info_p, as_info_p->shard_id); assert (shard_info_p != NULL); (shm_br->br_info[br_index].appl_server_num)--; (shard_info_p->num_appl_server)--; (shm_appl->num_appl_server)--; as_info_p->service_flag = SERVICE_OFF; as_info_p->reset_flag = FALSE; stop_appl_server (as_info_p, br_index, as_index); as_info_p->uts_status = UTS_STATUS_IDLE; as_info_p->con_status = CON_STATUS_CLOSE; as_info_p->num_request = 0; CON_STATUS_LOCK_DESTROY (as_info_p); } } static THREAD_FUNC cas_monitor_thr_f (void *ar) { int i, tmp_num_busy_uts; while (process_flag) { tmp_num_busy_uts = 0; for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { cas_monitor_worker (&(shm_appl->as_info[i]), br_index, i, &tmp_num_busy_uts); } num_busy_uts = tmp_num_busy_uts; shm_br->br_info[br_index].num_busy_count = num_busy_uts; SLEEP_MILISEC (0, 100); } #if !defined(WINDOWS) return NULL; #endif } static CSS_CONN_ENTRY * connect_to_master_for_server_monitor (const char *db_name, const char *db_host) { int port_id; unsigned short rid; if (sysprm_load_and_init (db_name, NULL, SYSPRM_IGNORE_INTL_PARAMS) != NO_ERROR) { return NULL; } port_id = prm_get_master_port_id (); if (port_id <= 0) { return NULL; } /* timeout : 5000 milliseconds */ return (css_connect_to_master_timeout (db_host, port_id, 5000, &rid)); } static int get_server_state_from_master (CSS_CONN_ENTRY * conn, const char *db_name) { unsigned short request_id; int error = NO_ERROR; int server_state; int buffer_size; int *buffer = NULL; if (conn == NULL) { return SERVER_STATE_DEAD; } error = css_send_request (conn, GET_SERVER_STATE, &request_id, db_name, (int) strlen (db_name) + 1); if (error != NO_ERRORS) { return SERVER_STATE_DEAD; } /* timeout : 5000 milliseconds */ error = css_receive_data (conn, request_id, (char **) &buffer, &buffer_size, 5000); if (error == NO_ERRORS) { if (buffer_size == sizeof (int)) { server_state = ntohl (*buffer); free_and_init (buffer); return server_state; } } if (buffer != NULL) { free_and_init (buffer); } return SERVER_STATE_UNKNOWN; } static int insert_db_server_check_list (T_DB_SERVER * list_p, int check_list_cnt, const char *db_name, const char *db_host) { int i; for (i = 0; i < check_list_cnt && i < UNUSABLE_DATABASE_MAX; i++) { if (strcmp (db_name, list_p[i].database_name) == 0 && strcmp (db_host, list_p[i].database_host) == 0) { return check_list_cnt; } } if (i == UNUSABLE_DATABASE_MAX) { return UNUSABLE_DATABASE_MAX; } strncpy_bufsize (list_p[i].database_name, db_name); strncpy_bufsize (list_p[i].database_host, db_host); list_p[i].state = -1; return i + 1; } static THREAD_FUNC server_monitor_thr_f (void *arg) { int i, j, cnt; int u_index; int check_list_cnt = 0; T_APPL_SERVER_INFO *as_info_p; T_DB_SERVER *check_list; CSS_CONN_ENTRY *conn = NULL; DB_INFO *db_info_p = NULL; char **preferred_hosts; char *unusable_db_name; char *unusable_db_host; char busy_cas_db_name[SRV_CON_DBNAME_SIZE]; er_init (NULL, ER_NEVER_EXIT); check_list = (T_DB_SERVER *) malloc (sizeof (T_DB_SERVER) * UNUSABLE_DATABASE_MAX); while (process_flag) { if (!shm_appl->monitor_server_flag || br_shard_flag == ON || shm_br->br_info[br_index].appl_server != APPL_SERVER_CAS || check_list == NULL) { shm_appl->unusable_databases_seq = 0; memset (shm_appl->unusable_databases_cnt, 0, sizeof (shm_appl->unusable_databases_cnt)); SLEEP_MILISEC (MONITOR_SERVER_INTERVAL, 0); continue; } /* 1. collect server check list */ check_list_cnt = 0; u_index = shm_appl->unusable_databases_seq % 2; for (i = 0; i < shm_appl->unusable_databases_cnt[u_index]; i++) { unusable_db_name = shm_appl->unusable_databases[u_index][i].database_name; unusable_db_host = shm_appl->unusable_databases[u_index][i].database_host; check_list_cnt = insert_db_server_check_list (check_list, check_list_cnt, unusable_db_name, unusable_db_host); } for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { as_info_p = &(shm_appl->as_info[i]); if (as_info_p->uts_status == UTS_STATUS_BUSY) { strncpy (busy_cas_db_name, as_info_p->database_name, SRV_CON_DBNAME_SIZE - 1); if (busy_cas_db_name[0] != '\0') { preferred_hosts = util_split_string (shm_appl->preferred_hosts, ":"); if (preferred_hosts != NULL) { for (j = 0; preferred_hosts[j] != NULL; j++) { check_list_cnt = insert_db_server_check_list (check_list, check_list_cnt, busy_cas_db_name, preferred_hosts[j]); } util_free_string_array (preferred_hosts); } db_info_p = cfg_find_db (busy_cas_db_name); if (db_info_p == NULL || db_info_p->hosts == NULL) { if (db_info_p) { cfg_free_directory (db_info_p); } continue; } for (j = 0; j < db_info_p->num_hosts; j++) { check_list_cnt = insert_db_server_check_list (check_list, check_list_cnt, busy_cas_db_name, db_info_p->hosts[j]); } cfg_free_directory (db_info_p); } } } /* 2. check server state */ for (i = 0; i < check_list_cnt; i++) { conn = connect_to_master_for_server_monitor (check_list[i].database_name, check_list[i].database_host); check_list[i].state = get_server_state_from_master (conn, check_list[i].database_name); if (conn != NULL) { css_free_conn (conn); conn = NULL; } } /* 3. record server state to the shared memory */ cnt = 0; u_index = (shm_appl->unusable_databases_seq + 1) % 2; for (i = 0; i < check_list_cnt; i++) { if (check_list[i].state < SERVER_STATE_REGISTERED && check_list[i].state != SERVER_STATE_UNKNOWN) { strncpy (shm_appl->unusable_databases[u_index][cnt].database_name, check_list[i].database_name, SRV_CON_DBNAME_SIZE - 1); strncpy (shm_appl->unusable_databases[u_index][cnt].database_host, check_list[i].database_host, CUB_MAXHOSTNAMELEN - 1); cnt++; } } shm_appl->unusable_databases_cnt[u_index] = cnt; shm_appl->unusable_databases_seq++; SLEEP_MILISEC (MONITOR_SERVER_INTERVAL, 0); } free_and_init (check_list); er_final (ER_ALL_FINAL); #if !defined(WINDOWS) return NULL; #endif } static THREAD_FUNC hang_check_thr_f (void *ar) { unsigned int cur_index; int cur_hang_count; T_BROKER_INFO *br_info_p; time_t cur_time; int collect_count_interval; int hang_count[NUM_COLLECT_COUNT_PER_INTVL] = { 0, 0, 0, 0 }; float avg_hang_count; int proxy_index, i; T_PROXY_INFO *proxy_info_p = NULL; T_APPL_SERVER_INFO *as_info_p; SLEEP_MILISEC (shm_br->br_info[br_index].monitor_hang_interval, 0); br_info_p = &(shm_br->br_info[br_index]); cur_hang_count = 0; cur_index = 0; avg_hang_count = 0.0; collect_count_interval = br_info_p->monitor_hang_interval / NUM_COLLECT_COUNT_PER_INTVL; while (process_flag) { cur_time = time (NULL); if (br_shard_flag == OFF) { for (i = 0; i < br_info_p->appl_server_max_num; i++) { as_info_p = &(shm_appl->as_info[i]); if ((as_info_p->service_flag != SERVICE_ON) || as_info_p->claimed_alive_time == 0) { continue; } if ((br_info_p->hang_timeout < cur_time - as_info_p->claimed_alive_time)) { cur_hang_count++; } } } else { for (proxy_index = 0; proxy_index < shm_proxy_p->num_proxy; proxy_index++) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, proxy_index); if ((proxy_info_p->service_flag != SERVICE_ON) || (proxy_info_p->claimed_alive_time == 0)) { continue; } if ((br_info_p->hang_timeout < cur_time - proxy_info_p->claimed_alive_time)) { cur_hang_count++; } } } hang_count[cur_index] = cur_hang_count; avg_hang_count = ut_get_avg_from_array (hang_count, NUM_COLLECT_COUNT_PER_INTVL); if (br_shard_flag == OFF) { br_info_p->reject_client_flag = (avg_hang_count >= (float) br_info_p->appl_server_num * HANG_COUNT_THRESHOLD_RATIO); } else { /* * reject_client_flag for shard broker * does not depend on the current number of proxies. * If one proxy hangs for the last 1 min, then * it will disable shard_broker no matter how many proxies * there are. */ br_info_p->reject_client_flag = (avg_hang_count >= 1); } cur_index = (cur_index + 1) % NUM_COLLECT_COUNT_PER_INTVL; cur_hang_count = 0; SLEEP_MILISEC (collect_count_interval, 0); } #if !defined(WINDOWS) return NULL; #endif } /* * psize_check_worker () - * return: void * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * proxy_index(in): it's only valid in SHARD! proxy index * shard_index(in): it's only valid in SHARD! shard index * as_index(in): cas index * * Note: check cas psize and cas log */ static void psize_check_worker (T_APPL_SERVER_INFO * as_info_p, int br_index, int as_index) { #if defined(WINDOWS) int pid; int cpu_time; int workset_size; float pct_cpu; #endif if (as_info_p->service_flag != SERVICE_ON) { return; } #if defined(WINDOWS) pid = as_info_p->pid; cpu_time = get_cputime_sec (pid); if (cpu_time < 0) { as_info_p->cpu_time = 0; #if 0 HANDLE hProcess; hProcess = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProcess == NULL) { pid = 0; as_info_p->pid = 0; as_info_p->cpu_time = 0; } #endif } else { as_info_p->cpu_time = cpu_time; } if (pdh_get_value (pid, &workset_size, &pct_cpu, NULL) >= 0) { as_info_p->pdh_pid = pid; as_info_p->pdh_workset = workset_size; as_info_p->pdh_pct_cpu = pct_cpu; } #else as_info_p->psize = getsize (as_info_p->pid); #if 0 if (as_info_p->psize < 0 && as_info_p->pid > 0) { if (kill (as_info_p->pid, 0) < 0 && errno == ESRCH) { as_info_p->pid = 0; } } #endif #endif /* WINDOWS */ check_cas_log (shm_br->br_info[br_index].name, as_info_p, as_index); } static void check_proxy_log (char *br_name, T_PROXY_INFO * proxy_info_p) { char log_filepath[BROKER_PATH_MAX]; if (proxy_info_p->cur_proxy_log_mode != PROXY_LOG_MODE_NONE) { snprintf (log_filepath, sizeof (log_filepath), "%s/%s_%d.log", shm_appl->proxy_log_dir, br_name, proxy_info_p->proxy_id + 1); if (access (log_filepath, F_OK) < 0) { FILE *fp; fp = fopen (log_filepath, "a"); if (fp != NULL) { fclose (fp); } proxy_info_p->proxy_log_reset = PROXY_LOG_RESET_REOPEN; } } return; } static void check_proxy_access_log (T_PROXY_INFO * proxy_info_p) { char *access_log_file; FILE *fp; access_log_file = proxy_info_p->access_log_file; if (access (access_log_file, F_OK) < 0) { fp = fopen (access_log_file, "a"); if (fp != NULL) { fclose (fp); } proxy_info_p->proxy_access_log_reset = PROXY_LOG_RESET_REOPEN; } return; } static void proxy_check_worker (int br_index, T_PROXY_INFO * proxy_info_p) { check_proxy_log (shm_br->br_info[br_index].name, proxy_info_p); check_proxy_access_log (proxy_info_p); return; } #if defined(WINDOWS) static int get_cputime_sec (int pid) { ULARGE_INTEGER ul; HANDLE hProcess; FILETIME ctime, etime, systime, usertime; int cputime = 0; if (pid <= 0) return 0; hProcess = OpenProcess (PROCESS_QUERY_INFORMATION, FALSE, pid); if (hProcess == NULL) { return -1; } if (GetProcessTimes (hProcess, &ctime, &etime, &systime, &usertime) != 0) { ul.HighPart = systime.dwHighDateTime + usertime.dwHighDateTime; ul.LowPart = systime.dwLowDateTime + usertime.dwLowDateTime; cputime = ((int) (ul.QuadPart / 10000000)); } CloseHandle (hProcess); return cputime; } static THREAD_FUNC psize_check_thr_f (void *ar) { int workset_size; float pct_cpu; int cpu_time; int br_num_thr; int i; int proxy_index; T_PROXY_INFO *proxy_info_p = NULL; T_SHARD_INFO *shard_info_p = NULL; if (pdh_init () < 0) { shm_appl->use_pdh_flag = FALSE; return; } else { shm_appl->use_pdh_flag = TRUE; } while (process_flag) { pdh_collect (); if (pdh_get_value (shm_br->br_info[br_index].pid, &workset_size, &pct_cpu, &br_num_thr) < 0) { shm_br->br_info[br_index].pdh_pct_cpu = 0; } else { cpu_time = get_cputime_sec (shm_br->br_info[br_index].pid); if (cpu_time >= 0) { shm_br->br_info[br_index].cpu_time = cpu_time; } shm_br->br_info[br_index].pdh_workset = workset_size; shm_br->br_info[br_index].pdh_pct_cpu = pct_cpu; shm_br->br_info[br_index].pdh_num_thr = br_num_thr; } if (br_shard_flag == ON) { for (proxy_index = 0; proxy_index < shm_proxy_p->num_proxy; proxy_index++) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, proxy_index); proxy_check_worker (br_index, proxy_info_p); } } for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { psize_check_worker (&(shm_appl->as_info[i]), br_index, i); } SLEEP_MILISEC (1, 0); } } #else /* WINDOWS */ static THREAD_FUNC psize_check_thr_f (void *ar) { int i; int proxy_index; T_PROXY_INFO *proxy_info_p = NULL; while (process_flag) { if (br_shard_flag == ON) { for (proxy_index = 0; proxy_index < shm_proxy_p->num_proxy; proxy_index++) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, proxy_index); proxy_check_worker (br_index, proxy_info_p); } } for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { psize_check_worker (&(shm_appl->as_info[i]), br_index, i); } SLEEP_MILISEC (1, 0); } return NULL; } #endif /* !WINDOWS */ /* * check_cas_log () - * return: void * br_name(in): broker name * as_info_p(in): T_APPL_SERVER_INFO * as_index(in): cas index * Note: check cas log and recreate */ static void check_cas_log (char *br_name, T_APPL_SERVER_INFO * as_info_p, int as_index) { char log_filename[BROKER_PATH_MAX]; if (IS_NOT_APPL_SERVER_TYPE_CAS (shm_br->br_info[br_index].appl_server)) { return; } if (as_info_p->cur_sql_log_mode != SQL_LOG_MODE_NONE) { get_as_sql_log_filename (log_filename, BROKER_PATH_MAX, br_name, as_info_p, as_index); if (access (log_filename, F_OK) < 0) { FILE *fp; fp = fopen (log_filename, "a"); if (fp != NULL) { fclose (fp); } as_info_p->cas_log_reset = CAS_LOG_RESET_REOPEN; } } if (as_info_p->cur_slow_log_mode != SLOW_LOG_MODE_OFF) { get_as_slow_log_filename (log_filename, BROKER_PATH_MAX, br_name, as_info_p, as_index); if (access (log_filename, F_OK) < 0) { FILE *fp; fp = fopen (log_filename, "a"); if (fp != NULL) { fclose (fp); } as_info_p->cas_slow_log_reset = CAS_LOG_RESET_REOPEN; } } } #ifdef WIN_FW static int process_cas_request (int cas_pid, int as_index, SOCKET clt_sock_fd, SOCKET srv_sock_fd) { char read_buf[1024]; int msg_size; int read_len; int tmp_int; char *tmp_p; msg_size = SRV_CON_DB_INFO_SIZE; while (msg_size > 0) { read_len = read_from_cas_client (clt_sock_fd, read_buf, msg_size, as_index, cas_pid); if (read_len <= 0) { return -1; } if (send (srv_sock_fd, read_buf, read_len, 0) < read_len) return -1; msg_size -= read_len; } if (recv (srv_sock_fd, (char *) &msg_size, 4, 0) < 4) return -1; if (write_to_client (clt_sock_fd, (char *) &msg_size, 4) < 0) return -1; msg_size = ntohl (msg_size); while (msg_size > 0) { read_len = recv (srv_sock_fd, read_buf, (msg_size > sizeof (read_buf) ? sizeof (read_buf) : msg_size), 0); if (read_len <= 0) { return -1; } if (write_to_client (clt_sock_fd, read_buf, read_len) < 0) { return -1; } msg_size -= read_len; } while (1) { tmp_int = 4; tmp_p = (char *) &msg_size; while (tmp_int > 0) { read_len = read_from_cas_client (clt_sock_fd, tmp_p, tmp_int, as_index, cas_pid); if (read_len <= 0) { return -1; } tmp_int -= read_len; tmp_p += read_len; } if (send (srv_sock_fd, (char *) &msg_size, 4, 0) < 0) { return -1; } msg_size = ntohl (msg_size); while (msg_size > 0) { read_len = read_from_cas_client (clt_sock_fd, read_buf, (msg_size > sizeof (read_buf) ? sizeof (read_buf) : msg_size), as_index, cas_pid); if (read_len <= 0) { return -1; } if (send (srv_sock_fd, read_buf, read_len, 0) < read_len) { return -1; } msg_size -= read_len; } if (recv (srv_sock_fd, (char *) &msg_size, 4, 0) < 4) { return -1; } if (write_to_client (clt_sock_fd, (char *) &msg_size, 4) < 0) { return -1; } msg_size = ntohl (msg_size); while (msg_size > 0) { read_len = recv (srv_sock_fd, read_buf, (msg_size > sizeof (read_buf) ? sizeof (read_buf) : msg_size), 0); if (read_len <= 0) { return -1; } if (write_to_client (clt_sock_fd, read_buf, read_len) < 0) { return -1; } msg_size -= read_len; } if (shm_appl->as_info[as_index].close_flag || shm_appl->as_info[as_index].pid != cas_pid) { break; } } return 0; } static int read_from_cas_client (SOCKET sock_fd, char *buf, int size, int as_index, int cas_pid) { int read_len; #ifdef ASYNC_MODE SELECT_MASK read_mask; int nfound; int maxfd; struct timeval timeout = { 1, 0 }; #endif retry: #ifdef ASYNC_MODE FD_ZERO (&read_mask); FD_SET (sock_fd, (fd_set *) (&read_mask)); maxfd = sock_fd + 1; nfound = select (maxfd, &read_mask, (SELECT_MASK *) 0, (SELECT_MASK *) 0, &timeout); if (nfound < 1) { if (shm_appl->as_info[as_index].close_flag || shm_appl->as_info[as_index].pid != cas_pid) { return -1; } goto retry; } #endif #ifdef ASYNC_MODE if (FD_ISSET (sock_fd, (fd_set *) (&read_mask))) { #endif read_len = READ_FROM_SOCKET (sock_fd, buf, size); #ifdef ASYNC_MODE } else { return -1; } #endif return read_len; } #endif static int find_idle_cas (void) { int i; int idle_cas_id = -1; time_t max_wait_time; int wait_cas_id; time_t cur_time = time (NULL); pthread_mutex_lock (&broker_shm_mutex); wait_cas_id = -1; max_wait_time = 0; for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { if (shm_appl->as_info[i].service_flag != SERVICE_ON) { continue; } if (shm_appl->as_info[i].uts_status == UTS_STATUS_IDLE #if !defined (WINDOWS) && kill (shm_appl->as_info[i].pid, 0) == 0 #endif ) { idle_cas_id = i; wait_cas_id = -1; break; } if (shm_br->br_info[br_index].appl_server_num == shm_br->br_info[br_index].appl_server_max_num && shm_appl->as_info[i].uts_status == UTS_STATUS_BUSY && shm_appl->as_info[i].cur_keep_con == KEEP_CON_AUTO && shm_appl->as_info[i].con_status == CON_STATUS_OUT_TRAN && shm_appl->as_info[i].num_holdable_results < 1 && shm_appl->as_info[i].cas_change_mode == CAS_CHANGE_MODE_AUTO) { time_t wait_time = cur_time - shm_appl->as_info[i].last_access_time; if (wait_time > max_wait_time || wait_cas_id == -1) { max_wait_time = wait_time; wait_cas_id = i; } } } if (wait_cas_id >= 0) { CON_STATUS_LOCK (&(shm_appl->as_info[wait_cas_id]), CON_STATUS_LOCK_BROKER); if (shm_appl->as_info[wait_cas_id].con_status == CON_STATUS_OUT_TRAN && shm_appl->as_info[wait_cas_id].num_holdable_results < 1 && shm_appl->as_info[wait_cas_id].cas_change_mode == CAS_CHANGE_MODE_AUTO) { idle_cas_id = wait_cas_id; shm_appl->as_info[wait_cas_id].con_status = CON_STATUS_CLOSE_AND_CONNECT; } CON_STATUS_UNLOCK (&(shm_appl->as_info[wait_cas_id]), CON_STATUS_LOCK_BROKER); } #if defined(WINDOWS) if (idle_cas_id >= 0) { HANDLE h_proc; h_proc = OpenProcess (SYNCHRONIZE, FALSE, shm_appl->as_info[idle_cas_id].pid); if (h_proc == NULL) { shm_appl->as_info[i].uts_status = UTS_STATUS_RESTART; idle_cas_id = -1; } else { CloseHandle (h_proc); } } #endif if (idle_cas_id < 0) { pthread_mutex_unlock (&broker_shm_mutex); return -1; } shm_appl->as_info[idle_cas_id].uts_status = UTS_STATUS_BUSY; pthread_mutex_unlock (&broker_shm_mutex); return idle_cas_id; } static int find_drop_as_index (void) { int i, drop_as_index, exist_idle_cas; time_t max_wait_time, wait_time; pthread_mutex_lock (&broker_shm_mutex); if (IS_NOT_APPL_SERVER_TYPE_CAS (shm_br->br_info[br_index].appl_server)) { drop_as_index = shm_br->br_info[br_index].appl_server_num - 1; wait_time = time (NULL) - shm_appl->as_info[drop_as_index].last_access_time; if (shm_appl->as_info[drop_as_index].uts_status == UTS_STATUS_IDLE && wait_time > shm_br->br_info[br_index].time_to_kill) { pthread_mutex_unlock (&broker_shm_mutex); return drop_as_index; } pthread_mutex_unlock (&broker_shm_mutex); return -1; } drop_as_index = -1; max_wait_time = -1; exist_idle_cas = 0; for (i = shm_br->br_info[br_index].appl_server_max_num - 1; i >= 0; i--) { if (shm_appl->as_info[i].service_flag != SERVICE_ON) continue; wait_time = time (NULL) - shm_appl->as_info[i].last_access_time; if (shm_appl->as_info[i].uts_status == UTS_STATUS_IDLE) { if (wait_time > shm_br->br_info[br_index].time_to_kill) { drop_as_index = i; break; } else { exist_idle_cas = 1; drop_as_index = -1; } } if (shm_appl->as_info[i].uts_status == UTS_STATUS_BUSY && shm_appl->as_info[i].con_status == CON_STATUS_OUT_TRAN && shm_appl->as_info[i].num_holdable_results < 1 && shm_appl->as_info[i].cas_change_mode == CAS_CHANGE_MODE_AUTO && wait_time > max_wait_time && wait_time > shm_br->br_info[br_index].time_to_kill && exist_idle_cas == 0) { max_wait_time = wait_time; drop_as_index = i; } } pthread_mutex_unlock (&broker_shm_mutex); return drop_as_index; } static int find_add_as_index () { int i; pthread_mutex_lock (&broker_shm_mutex); for (i = 0; i < shm_br->br_info[br_index].appl_server_max_num; i++) { if (shm_appl->as_info[i].service_flag == SERVICE_OFF_ACK && current_dropping_as_index != i) { pthread_mutex_unlock (&broker_shm_mutex); return i; } } pthread_mutex_unlock (&broker_shm_mutex); return -1; } #if !defined(WINDOWS) static int init_proxy_env () { int len; if ((proxy_sock_fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) { return (-1); } /* FOR DEBUG */ SHARD_ERR ("<BROKER> listen to unixdoamin:[%s].\n", shm_appl->port_name); memset (&shard_sock_addr, 0, sizeof (shard_sock_addr)); shard_sock_addr.sun_family = AF_UNIX; strncpy_bufsize (shard_sock_addr.sun_path, shm_appl->port_name); #ifdef _SOCKADDR_LEN /* 4.3BSD Reno and later */ len = sizeof (shard_sock_addr.sun_len) + sizeof (shard_sock_addr.sun_family) + strlen (shard_sock_addr.sun_path) + 1; shard_sock_addr.sun_len = len; #else /* vanilla 4.3BSD */ len = strlen (shard_sock_addr.sun_path) + sizeof (shard_sock_addr.sun_family) + 1; #endif /* bind the name to the descriptor */ if (bind (proxy_sock_fd, (struct sockaddr *) &shard_sock_addr, len) < 0) { CLOSE_SOCKET (proxy_sock_fd); return (-2); } if (listen (proxy_sock_fd, 127) < 0) { /* tell kernel we're a server */ CLOSE_SOCKET (proxy_sock_fd); return (-3); } return (proxy_sock_fd); } #endif /* !WINDOWS */ static int broker_init_shm (void) { char *p; int i; int master_shm_key, as_shm_key, port_no, proxy_shm_id; p = getenv (MASTER_SHM_KEY_ENV_STR); if (p == NULL) { UW_SET_ERROR_CODE (UW_ER_SHM_OPEN, 0); goto return_error; } parse_int (&master_shm_key, p, 10); SHARD_ERR ("<BROKER> MASTER_SHM_KEY_ENV_STR:[%d:%x]\n", master_shm_key, master_shm_key); shm_br = (T_SHM_BROKER *) uw_shm_open (master_shm_key, SHM_BROKER, SHM_MODE_ADMIN); if (shm_br == NULL) { UW_SET_ERROR_CODE (UW_ER_SHM_OPEN, 0); goto return_error; } if ((p = getenv (PORT_NUMBER_ENV_STR)) == NULL) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, 0); goto return_error; } parse_int (&port_no, p, 10); for (i = 0, br_index = -1; i < shm_br->num_broker; i++) { if (shm_br->br_info[i].port == port_no) { br_index = i; break; } } if (br_index == -1) { UW_SET_ERROR_CODE (UW_ER_CANT_CREATE_SOCKET, 0); goto return_error; } br_info_p = &shm_br->br_info[i]; as_shm_key = br_info_p->appl_server_shm_id; SHARD_ERR ("<BROKER> APPL_SERVER_SHM_KEY_STR:[%d:%x]\n", as_shm_key, as_shm_key); shm_appl = (T_SHM_APPL_SERVER *) uw_shm_open (as_shm_key, SHM_APPL_SERVER, SHM_MODE_ADMIN); if (shm_appl == NULL) { UW_SET_ERROR_CODE (UW_ER_SHM_OPEN, 0); goto return_error; } if (shm_appl->shard_flag == ON) { proxy_shm_id = br_info_p->proxy_shm_id; shm_proxy_p = (T_SHM_PROXY *) uw_shm_open (proxy_shm_id, SHM_PROXY, SHM_MODE_ADMIN); if (shm_proxy_p == NULL) { UW_SET_ERROR_CODE (UW_ER_SHM_OPEN, 0); goto return_error; } } return 0; return_error: /* SHARD TODO : NOT IMPLEMENTED YET */ #if 0 SET_BROKER_ERR_CODE (); #endif /* SHARD TODO : DETACH SHARED MEMORY */ return -1; } static void proxy_monitor_worker (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index) { int new_pid; #if defined(WINDOWS) HANDLE phandle; #endif /* WINDOWS */ if (proxy_info_p->service_flag != SERVICE_ON || proxy_info_p->pid < 0) { return; } #if defined(WINDOWS) phandle = OpenProcess (SYNCHRONIZE, FALSE, proxy_info_p->pid); if (phandle == NULL) { restart_proxy_server (proxy_info_p, br_index, proxy_index); goto shm_init; } else { CloseHandle (phandle); } #else /* WINDOWS */ if (kill (proxy_info_p->pid, 0) < 0) { SLEEP_MILISEC (1, 0); if (kill (proxy_info_p->pid, 0) < 0) { restart_proxy_server (proxy_info_p, br_index, proxy_index); goto shm_init; } } #endif /* !WINDOWS */ if (proxy_info_p->status == PROXY_STATUS_RESTART) { stop_proxy_server (proxy_info_p, br_index, proxy_index); new_pid = run_proxy_server (proxy_info_p, br_index, proxy_index); proxy_info_p->pid = new_pid; goto shm_init; } return; shm_init: proxy_info_p->status = PROXY_STATUS_START; proxy_info_p->cur_client = 0; proxy_info_p->stmt_waiter_count = 0; } static THREAD_FUNC proxy_monitor_thr_f (void *arg) { int tmp_num_busy_uts; int proxy_index; T_PROXY_INFO *proxy_info_p = NULL; while (process_flag) { tmp_num_busy_uts = 0; for (proxy_index = 0; proxy_index < shm_proxy_p->num_proxy; proxy_index++) { proxy_info_p = shard_shm_find_proxy_info (shm_proxy_p, proxy_index); proxy_monitor_worker (proxy_info_p, br_index, proxy_index); } SLEEP_MILISEC (0, 100); } #if !defined(WINDOWS) return NULL; #endif } #if !defined(WINDOWS) static THREAD_FUNC proxy_listener_thr_f (void *arg) { SELECT_MASK allset, rset; struct timeval tv; struct sockaddr_in proxy_sock_addr; T_SOCKLEN proxy_sock_addr_len; SOCKET max_fd, client_fd; int proxy_id; int ret, select_ret; while (process_flag) { FD_ZERO (&allset); FD_SET (proxy_sock_fd, &allset); broker_set_proxy_fds (&allset); rset = allset; max_fd = broker_get_proxy_conn_maxfd (proxy_sock_fd); tv.tv_sec = 1; tv.tv_usec = 0; select_ret = select (max_fd, &rset, NULL, NULL, &tv); if (select_ret == 0) { continue; } else if (select_ret < 0) { if (errno == EINTR) { continue; } continue; } if (FD_ISSET (proxy_sock_fd, &rset)) { proxy_sock_addr_len = sizeof (proxy_sock_addr); client_fd = accept (proxy_sock_fd, (struct sockaddr *) &proxy_sock_addr, &proxy_sock_addr_len); ret = broker_add_proxy_conn (client_fd); if (ret < 0) { CLOSE_SOCKET (client_fd); client_fd = INVALID_SOCKET; } } while ((client_fd = broker_get_readable_proxy_conn (&rset)) != INVALID_SOCKET) { ret = read_from_client (client_fd, ((char *) &proxy_id), sizeof (proxy_id)); if (ret < 0) { broker_delete_proxy_conn_by_fd (client_fd); CLOSE_SOCKET (client_fd); client_fd = INVALID_SOCKET; } proxy_id = htonl (proxy_id); ret = broker_register_proxy_conn (client_fd, proxy_id); if (ret < 0) { broker_delete_proxy_conn_by_fd (client_fd); CLOSE_SOCKET (client_fd); client_fd = INVALID_SOCKET; } } } return NULL; } #endif /* !WINDOWS */ /* * run_proxy_server () - * return: pid * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * proxy_index(in): it's only valid in SHARD! proxy index * * Note: activate PROXY * it's only use in SHARD. */ static int run_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index) { const char *proxy_exe_name = NAME_PROXY; char proxy_shm_id_env_str[32], proxy_id_env_str[32]; int pid; #if !defined(WINDOWS) char process_name[APPL_SERVER_NAME_MAX_SIZE]; int i; #endif while (1) { pthread_mutex_lock (&run_proxy_mutex); if (run_proxy_flag) { pthread_mutex_unlock (&run_proxy_mutex); SLEEP_MILISEC (0, 100); continue; } else { run_proxy_flag = 1; pthread_mutex_unlock (&run_proxy_mutex); break; } } #if !defined(WINDOWS) signal (SIGCHLD, SIG_IGN); #endif proxy_info_p->cur_client = 0; #if !defined(WINDOWS) unlink (proxy_info_p->port_name); pid = fork (); if (pid == 0) { signal (SIGCHLD, SIG_DFL); for (i = 3; i <= max_open_fd; i++) { close (i); } #endif snprintf (proxy_shm_id_env_str, sizeof (proxy_shm_id_env_str), "%s=%d", PROXY_SHM_KEY_STR, shm_br->br_info[br_index].proxy_shm_id); putenv (proxy_shm_id_env_str); snprintf (proxy_id_env_str, sizeof (proxy_id_env_str), "%s=%d", PROXY_ID_ENV_STR, proxy_index); putenv (proxy_id_env_str); #if !defined(WINDOWS) if (snprintf (process_name, sizeof (process_name) - 1, "%s_%s_%d", shm_appl->broker_name, proxy_exe_name, proxy_index + 1) < 0) { assert (false); exit (0); } #endif /* !WINDOWS */ #if defined(WINDOWS) pid = run_child (proxy_exe_name); #else execle (proxy_exe_name, process_name, NULL, environ); #endif #if !defined(WINDOWS) exit (0); } #endif run_proxy_flag = 0; return pid; } /* * stop_proxy_server () - * return: NO_ERROR * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * proxy_index(in): it's only valid in SHARD! proxy index * * Note: inactivate Proxy * it's only use in SHARD. */ static int stop_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index) { ut_kill_proxy_process (proxy_info_p->pid, shm_br->br_info[br_index].name, proxy_index); #if defined(WINDOWS) /* [CUBRIDSUS-2068] make the broker sleep for 0.1 sec when stopping the cas in order to prevent communication error * occurred on windows. */ SLEEP_MILISEC (0, 100); #else /* WINDOWS */ broker_delete_proxy_conn_by_proxy_id (proxy_info_p->proxy_id); #endif /* !WINDOWS */ proxy_info_p->pid = 0; proxy_info_p->cur_client = 0; return 0; } /* * restart_proxy_server () - * return: void * as_info_p(in): T_APPL_SERVER_INFO * br_index(in): broker index * proxy_index(in): it's only valid in SHARD! proxy index * * Note: inactivate and activate Proxy * it's only use in SHARD. */ static void restart_proxy_server (T_PROXY_INFO * proxy_info_p, int br_index, int proxy_index) { int new_pid; stop_proxy_server (proxy_info_p, br_index, proxy_index); new_pid = run_proxy_server (proxy_info_p, br_index, proxy_index); proxy_info_p->pid = new_pid; proxy_info_p->num_restarts++; } static void get_as_sql_log_filename (char *log_filename, int len, char *broker_name, T_APPL_SERVER_INFO * as_info_p, int as_index) { int ret; char dirname[BROKER_PATH_MAX]; get_cubrid_file (FID_SQL_LOG_DIR, dirname, BROKER_PATH_MAX); if (br_shard_flag == ON) { ret = snprintf (log_filename, BROKER_PATH_MAX - 1, "%s%s_%d_%d_%d.sql.log", dirname, broker_name, as_info_p->proxy_id + 1, as_info_p->shard_id, as_info_p->shard_cas_id + 1); } else { ret = snprintf (log_filename, BROKER_PATH_MAX - 1, "%s%s_%d.sql.log", dirname, broker_name, as_index + 1); } if (ret < 0) { // bad name log_filename[0] = '\0'; } } static void get_as_slow_log_filename (char *log_filename, int len, char *broker_name, T_APPL_SERVER_INFO * as_info_p, int as_index) { int ret; char dirname[BROKER_PATH_MAX]; get_cubrid_file (FID_SLOW_LOG_DIR, dirname, BROKER_PATH_MAX); if (br_shard_flag == ON) { ret = snprintf (log_filename, BROKER_PATH_MAX - 1, "%s%s_%d_%d_%d.slow.log", dirname, broker_name, as_info_p->proxy_id + 1, as_info_p->shard_id, as_info_p->shard_cas_id + 1); } else { ret = snprintf (log_filename, BROKER_PATH_MAX - 1, "%s%s_%d.slow.log", dirname, broker_name, as_index + 1); } if (ret < 0) { // bad name log_filename[0] = '\0'; } }
382401.c
//===-- stubs.c -----------------------------------------------------------===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define _XOPEN_SOURCE 700 #include <errno.h> #include <limits.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <utime.h> #include <utmp.h> #include <sys/mman.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/times.h> #include <sys/types.h> #include <sys/wait.h> #include "klee/Config/config.h" void klee_warning(const char*); void klee_warning_once(const char*); /* Silent ignore */ int __syscall_rt_sigaction(int signum, const struct sigaction *act, struct sigaction *oldact, size_t _something) __attribute__((weak)); int __syscall_rt_sigaction(int signum, const struct sigaction *act, struct sigaction *oldact, size_t _something) { klee_warning_once("silently ignoring"); return 0; } int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) __attribute__((weak)); int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) { klee_warning_once("silently ignoring"); return 0; } int sigprocmask(int how, const sigset_t *set, sigset_t *oldset) __attribute__((weak)); int sigprocmask(int how, const sigset_t *set, sigset_t *oldset) { klee_warning_once("silently ignoring"); return 0; } /* Not even worth warning about these */ int fdatasync(int fd) __attribute__((weak)); int fdatasync(int fd) { return 0; } /* Not even worth warning about this */ void sync(void) __attribute__((weak)); void sync(void) { } /* Error ignore */ extern int __fgetc_unlocked(FILE *f); extern int __fputc_unlocked(int c, FILE *f); int __socketcall(int type, int *args) __attribute__((weak)); int __socketcall(int type, int *args) { klee_warning("ignoring (EAFNOSUPPORT)"); errno = EAFNOSUPPORT; return -1; } int _IO_getc(FILE *f) __attribute__((weak)); int _IO_getc(FILE *f) { return __fgetc_unlocked(f); } int _IO_putc(int c, FILE *f) __attribute__((weak)); int _IO_putc(int c, FILE *f) { return __fputc_unlocked(c, f); } int mkdir(const char *pathname, mode_t mode) __attribute__((weak)); int mkdir(const char *pathname, mode_t mode) { klee_warning("ignoring (EIO)"); errno = EIO; return -1; } int mkfifo(const char *pathname, mode_t mode) __attribute__((weak)); int mkfifo(const char *pathname, mode_t mode) { klee_warning("ignoring (EIO)"); errno = EIO; return -1; } int mknod(const char *pathname, mode_t mode, dev_t dev) __attribute__((weak)); int mknod(const char *pathname, mode_t mode, dev_t dev) { klee_warning("ignoring (EIO)"); errno = EIO; return -1; } int pipe(int filedes[2]) __attribute__((weak)); int pipe(int filedes[2]) { klee_warning("ignoring (ENFILE)"); errno = ENFILE; return -1; } int link(const char *oldpath, const char *newpath) __attribute__((weak)); int link(const char *oldpath, const char *newpath) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int symlink(const char *oldpath, const char *newpath) __attribute__((weak)); int symlink(const char *oldpath, const char *newpath) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int rename(const char *oldpath, const char *newpath) __attribute__((weak)); int rename(const char *oldpath, const char *newpath) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int nanosleep(const struct timespec *req, struct timespec *rem) __attribute__((weak)); int nanosleep(const struct timespec *req, struct timespec *rem) { return 0; } /* XXX why can't I call this internally? */ int clock_gettime(clockid_t clk_id, struct timespec *res) __attribute__((weak)); int clock_gettime(clockid_t clk_id, struct timespec *res) { /* Fake */ struct timeval tv; gettimeofday(&tv, NULL); res->tv_sec = tv.tv_sec; res->tv_nsec = tv.tv_usec * 1000; return 0; } int clock_settime(clockid_t clk_id, const struct timespec *res) __attribute__((weak)); int clock_settime(clockid_t clk_id, const struct timespec *res) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } time_t time(time_t *t) { struct timeval tv; gettimeofday(&tv, NULL); if (t) *t = tv.tv_sec; return tv.tv_sec; } clock_t times(struct tms *buf) { /* Fake */ if (!buf) klee_warning("returning 0\n"); else { klee_warning("setting all times to 0 and returning 0\n"); buf->tms_utime = 0; buf->tms_stime = 0; buf->tms_cutime = 0; buf->tms_cstime = 0; } return 0; } struct utmpx *getutxent(void) __attribute__((weak)); struct utmpx *getutxent(void) { return (struct utmpx*) getutent(); } void setutxent(void) __attribute__((weak)); void setutxent(void) { setutent(); } void endutxent(void) __attribute__((weak)); void endutxent(void) { endutent(); } int utmpxname(const char *file) __attribute__((weak)); int utmpxname(const char *file) { utmpname(file); return 0; } int euidaccess(const char *pathname, int mode) __attribute__((weak)); int euidaccess(const char *pathname, int mode) { return access(pathname, mode); } int eaccess(const char *pathname, int mode) __attribute__((weak)); int eaccess(const char *pathname, int mode) { return euidaccess(pathname, mode); } int group_member (gid_t __gid) __attribute__((weak)); int group_member (gid_t __gid) { return ((__gid == getgid ()) || (__gid == getegid ())); } int utime(const char *filename, const struct utimbuf *buf) __attribute__((weak)); int utime(const char *filename, const struct utimbuf *buf) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int futimes(int fd, const struct timeval times[2]) __attribute__((weak)); int futimes(int fd, const struct timeval times[2]) { klee_warning("ignoring (EBADF)"); errno = EBADF; return -1; } int strverscmp (__const char *__s1, __const char *__s2) { return strcmp(__s1, __s2); /* XXX no doubt this is bad */ } #if __GLIBC_PREREQ(2, 25) #define gnu_dev_type dev_t #else #define gnu_dev_type unsigned long long int #endif unsigned int gnu_dev_major(gnu_dev_type __dev) __attribute__((weak)); unsigned int gnu_dev_major(gnu_dev_type __dev) { return ((__dev >> 8) & 0xfff) | ((unsigned int) (__dev >> 32) & ~0xfff); } unsigned int gnu_dev_minor(gnu_dev_type __dev) __attribute__((weak)); unsigned int gnu_dev_minor(gnu_dev_type __dev) { return (__dev & 0xff) | ((unsigned int) (__dev >> 12) & ~0xff); } gnu_dev_type gnu_dev_makedev(unsigned int __major, unsigned int __minor) __attribute__((weak)); gnu_dev_type gnu_dev_makedev(unsigned int __major, unsigned int __minor) { return ((__minor & 0xff) | ((__major & 0xfff) << 8) | (((gnu_dev_type) (__minor & ~0xff)) << 12) | (((gnu_dev_type) (__major & ~0xfff)) << 32)); } char *canonicalize_file_name (const char *name) __attribute__((weak)); char *canonicalize_file_name (const char *name) { return realpath(name, NULL); } int getloadavg(double loadavg[], int nelem) __attribute__((weak)); int getloadavg(double loadavg[], int nelem) { klee_warning("ignoring (-1 result)"); return -1; } pid_t wait(int *status) __attribute__((weak)); pid_t wait(int *status) { klee_warning("ignoring (ECHILD)"); errno = ECHILD; return -1; } pid_t wait3(int *status, int options, struct rusage *rusage) __attribute__((weak)); pid_t wait3(int *status, int options, struct rusage *rusage) { klee_warning("ignoring (ECHILD)"); errno = ECHILD; return -1; } pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage) __attribute__((weak)); pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage) { klee_warning("ignoring (ECHILD)"); errno = ECHILD; return -1; } pid_t waitpid(pid_t pid, int *status, int options) __attribute__((weak)); pid_t waitpid(pid_t pid, int *status, int options) { klee_warning("ignoring (ECHILD)"); errno = ECHILD; return -1; } pid_t waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options) __attribute__((weak)); pid_t waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options) { klee_warning("ignoring (ECHILD)"); errno = ECHILD; return -1; } /* ACL */ /* FIXME: We need autoconf magic for this. */ #ifdef HAVE_SYS_ACL_H #include <sys/acl.h> int acl_delete_def_file(const char *path_p) __attribute__((weak)); int acl_delete_def_file(const char *path_p) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int acl_extended_file(const char path_p) __attribute__((weak)); int acl_extended_file(const char path_p) { klee_warning("ignoring (ENOENT)"); errno = ENOENT; return -1; } int acl_entries(acl_t acl) __attribute__((weak)); int acl_entries(acl_t acl) { klee_warning("ignoring (EINVAL)"); errno = EINVAL; return -1; } acl_t acl_from_mode(mode_t mode) __attribute__((weak)); acl_t acl_from_mode(mode_t mode) { klee_warning("ignoring (ENOMEM)"); errno = ENOMEM; return NULL; } acl_t acl_get_fd(int fd) __attribute__((weak)); acl_t acl_get_fd(int fd) { klee_warning("ignoring (ENOMEM)"); errno = ENOMEM; return NULL; } acl_t acl_get_file(const char *pathname, acl_type_t type) __attribute__((weak)); acl_t acl_get_file(const char *pathname, acl_type_t type) { klee_warning("ignoring (ENONMEM)"); errno = ENOMEM; return NULL; } int acl_set_fd(int fd, acl_t acl) __attribute__((weak)); int acl_set_fd(int fd, acl_t acl) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int acl_set_file(const char *path_p, acl_type_t type, acl_t acl) __attribute__((weak)); int acl_set_file(const char *path_p, acl_type_t type, acl_t acl) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int acl_free(void *obj_p) __attribute__((weak)); int acl_free(void *obj_p) { klee_warning("ignoring (EINVAL)"); errno = EINVAL; return -1; } #endif int mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data) __attribute__((weak)); int mount(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int umount(const char *target) __attribute__((weak)); int umount(const char *target) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int umount2(const char *target, int flags) __attribute__((weak)); int umount2(const char *target, int flags) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int swapon(const char *path, int swapflags) __attribute__((weak)); int swapon(const char *path, int swapflags) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int swapoff(const char *path) __attribute__((weak)); int swapoff(const char *path) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setgid(gid_t gid) __attribute__((weak)); int setgid(gid_t gid) { klee_warning("silently ignoring (returning 0)"); return 0; } int setgroups(size_t size, const gid_t *list) __attribute__((weak)); int setgroups(size_t size, const gid_t *list) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int sethostname(const char *name, size_t len) __attribute__((weak)); int sethostname(const char *name, size_t len) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setpgid(pid_t pid, pid_t pgid) __attribute__((weak)); int setpgid(pid_t pid, pid_t pgid) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setpgrp(void) __attribute__((weak)); int setpgrp(void) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setpriority(__priority_which_t which, id_t who, int prio) __attribute__((weak)); int setpriority(__priority_which_t which, id_t who, int prio) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setresgid(gid_t rgid, gid_t egid, gid_t sgid) __attribute__((weak)); int setresgid(gid_t rgid, gid_t egid, gid_t sgid) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setresuid(uid_t ruid, uid_t euid, uid_t suid) __attribute__((weak)); int setresuid(uid_t ruid, uid_t euid, uid_t suid) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) __attribute__((weak)); int setrlimit(__rlimit_resource_t resource, const struct rlimit *rlim) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setrlimit64(__rlimit_resource_t resource, const struct rlimit64 *rlim) __attribute__((weak)); int setrlimit64(__rlimit_resource_t resource, const struct rlimit64 *rlim) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } pid_t setsid(void) __attribute__((weak)); pid_t setsid(void) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int settimeofday(const struct timeval *tv, const struct timezone *tz) __attribute__((weak)); int settimeofday(const struct timeval *tv, const struct timezone *tz) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int setuid(uid_t uid) __attribute__((weak)); int setuid(uid_t uid) { klee_warning("silently ignoring (returning 0)"); return 0; } int reboot(int flag) __attribute__((weak)); int reboot(int flag) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int mlock(const void *addr, size_t len) __attribute__((weak)); int mlock(const void *addr, size_t len) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int munlock(const void *addr, size_t len) __attribute__((weak)); int munlock(const void *addr, size_t len) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } int pause(void) __attribute__((weak)); int pause(void) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } ssize_t readahead(int fd, off64_t *offset, size_t count) __attribute__((weak)); ssize_t readahead(int fd, off64_t *offset, size_t count) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; } void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) __attribute__((weak)); void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset) { klee_warning("ignoring (EPERM)"); errno = EPERM; return (void*) -1; } void *mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset) __attribute__((weak)); void *mmap64(void *start, size_t length, int prot, int flags, int fd, off64_t offset) { klee_warning("ignoring (EPERM)"); errno = EPERM; return (void*) -1; } int munmap(void*start, size_t length) __attribute__((weak)); int munmap(void*start, size_t length) { klee_warning("ignoring (EPERM)"); errno = EPERM; return -1; }